text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
/** * @module * Beetle module. */ declare module beetle { /** Promise abstraction. We can change Ajax Provider result via this type. */ type AjaxCall<T> = PromiseLike<T>; /** Beetle interfaces. Some polyfill, other duck typing signatures. */ namespace interfaces { /** Key-value pair collection. */ interface Dictionary<T> { [key: string]: T; } /** GroupBy produces this after key selection and pass to value selection. */ interface Grouping<T, TKey> extends Array<T> { Key: TKey; } /** GroupBy without value selection produces this interface as result. */ interface Grouped<T, TKey> { Key: TKey; /** Grouped items. */ Items: Array<T>; } /** When a trackable array change, event args has this properties. */ interface ArrayChangeEventArgs { added: Array<any>; removed: Array<any>; } /** When a validation state change, event args has this properties. */ interface ValidationErrorsChangedEventArgs { /** Current errors. */ errors: ValidationError[]; /** Newly added validation errors. */ added: ValidationError[]; /** Newly fixed validation errors. */ removed: ValidationError[]; } /** When state change for an entity, event args has this properties. */ interface EntityStateChangedEventArgs { entity: IEntity; oldState: enums.entityStates; newState: enums.entityStates; /** Indicates if entity was in Unchanged state before. */ newChanged: boolean; } /** When a property value change for an entity, event args has this properties. */ interface PropertyChangedEventArgs { entity: IEntity; property: Property; oldValue: any; newValue: any; } /** When an array member of an entity is changed, event args has this properties (for internal use only). */ interface ArrayChangedEventArgs { entity: IEntity; property: Property; items: Array<IEntity>; removedItems: Array<IEntity>; addedItems: Array<IEntity>; } /** When an entity state is changed or there is no more changed entity, an event is fired with this properties. */ interface HasChangesChangedEventArgs { /** Indicates if entity manager has any changes. */ hasChanges: boolean; } /** Before a query is executed, an event is fired with this properties. */ interface QueryExecutingEventArgs { manager: core.EntityManager; /** Query can be changed by setting this value. */ query: querying.EntityQuery<any>; /** Query options can be changed by setting this value. */ options: ManagerQueryOptions; } /** After a query executed, an event is fired with this properties. */ interface QueryExecutedEventArgs extends QueryExecutingEventArgs { result: any; } /** Before and after manager saves changes, an event is fired with this properties. */ interface SaveEventArgs { manager: core.EntityManager; changes: IEntity[]; options: ManagerSaveOptions; } /** This properties are used for global messages (i.e. warnings, infos). */ interface MessageEventArgs { message: string; query: Query<any>; options: ManagerQueryOptions; } /** Beetle converts plural navigation properties to TrackableArrays to track changes on collections. */ interface TrackableArray<T> extends Array<T> { object: any; property: string; /** Called after a change made on the array. */ after: (o: any, s: string, a: TrackableArray<T>, removed: T[], added: T[]) => void; changing: Event<ArrayChangeEventArgs>; changed: Event<ArrayChangeEventArgs>; /** Adding remove capability to array. */ remove(...T): T[]; load(expands: string[], resourceName: string, options: ManagerQueryOptions, successCallback?: (items: T[]) => void, errorCallback?: (e: AjaxError) => void): AjaxCall<QueryResultArray<T>>; } /** All validator objects have these properties. */ interface Validator { /** Validator name. */ name: string; /** Validation error message. Arguments might be used when formatting the message. */ message: string; /** Validation arguments. */ args?: any; toString(): string; } /** Validates the value of the property. */ interface PropertyValidator extends Validator { validate(value: any, entity: IEntity): string; } /** Validates all values of the entity. */ interface EntityValidator extends Validator { validate(entity: IEntity): string; } /** Property validators produces error messages compatible with this interface. */ interface ValidationError { message: string; entity: IEntity; /** If validation error is created for a property, this will be available. */ property?: string; /** If validation error is created for a property, this will be available. */ value?: any; } /** Entity validators produces error messages compatible with this interface. */ interface EntityValidationError { entity: IEntity; validationErrors: ValidationError[]; } /** Manager keeps tracks of all error messages using this interface. */ interface ManagerValidationError extends Error { entities: IEntity[]; entitiesInError: EntityValidationError[]; manager: core.EntityManager; } /** All data types share this common structure. */ interface DataTypeBase { name: string; /** Complex Type are based on Entity Framework's. */ isComplex: boolean; toString(): string; /** Returns network transferable value for the data type. */ getRawValue(value: any): string; /** Checks if given value is valid for this type. */ isValid(value: any): boolean; /** Converts given value to OData format. */ toODataValue(value: any): string; /** Converts given value to Beetle format. */ toBeetleValue(value: any): string; /** Gets default value for type. */ defaultValue(): any; /** Generates a new unique value for this type. Used for auto-incremented values. */ autoValue(): any; /** Tries to convert given value to this type. */ handle(value: any): any; } /** Base type for all metadata types. */ interface MetadataPart { name: string; displayName?: string; toString(): string; validate(entity: IEntity): ValidationError[]; } /** Shared interface for DataProperty and NavigationProperty. */ interface Property extends MetadataPart { owner: EntityType; /** Complex Type are based on Entity Framework's. */ isComplex: boolean; validators: PropertyValidator[]; /** Adds validation for the property dynamically. */ addValidation(name: string, func: (value: any, entity: IEntity) => string, message: string, args?: any); } /** Primitive member metadata. */ interface DataProperty extends Property { dataType: DataTypeBase; isNullable: boolean; /** Indicates if this property is one of the primary keys. */ isKeyPart: boolean; /** Auto generation strategy for the property (Identity, Computed, None). */ generationPattern?: enums.generationPattern; defaultValue: any; /** When true, this property will be used together with keys for updates. */ useForConcurrency: boolean; /** Navigation properties based on this property. */ relatedNavigationProperties: NavigationProperty[]; isEnum: boolean; isValid(value: any): boolean; handle(value: any): any; getDefaultValue(): any; } /** Relational member metadata. */ interface NavigationProperty extends Property { entityTypeName: string; entityType: EntityType; isScalar: boolean; /** To be able to match two way relations. Same relations have same association name for both side. */ associationName: string; /** Indicates if deleting this related entity causes cascade deletion. */ cascadeDelete: boolean; foreignKeyNames: string[]; foreignKeys: DataProperty[]; /** After this property changed, owner will also be marked as modified. */ triggerOwnerModify: boolean; /** Other side of the navigation. */ inverse?: NavigationProperty; /** Checks if given value can be assigned to this property. If not throws an error. */ checkAssign(entity: IEntity); } /** Entity type metadata. */ interface EntityType extends MetadataPart { /** Entity type's short name (i.e. 'Customer'). */ shortName: string; keyNames: string[]; baseTypeName: string; /** Entity set name. If this Entity is derived from another, set name is the root entity's name. */ setName: string; /** Entity set type name. If this Entity is derived from another, set type is the root entity's type. */ setTypeName: string; metadataManager: metadata.MetadataManager; /** Automatically filled EntityType will be used for unknown entities. */ hasMetadata: boolean; /** Properties that are not in metadata but available on the entity. */ properties: string[]; /** Complex Type are based on Entity Framework's. */ isComplexType: boolean; dataProperties: DataProperty[]; navigationProperties: NavigationProperty[]; keys: DataProperty[]; /** Lowest entity type in the inheritance hierarchy. */ floorType: EntityType; baseType: EntityType; validators: EntityValidator[]; /** Constructor function. Called right after the entity object is generated. */ constructor: (entity: RawEntity) => void; /** Initializer function. Called after entity started to being tracked (properties converted to observable). */ initializer: (entity: IEntity) => void; /** Parses given string and finds property, looks recursively to navigation properties when needed. */ getProperty(propertyPath: string): Property; /** * Register constructor and initializer (optional) for the type. * @param constructor Constructor function. Called right after the entity object is generated. * @param initializer Initializer function. Called after entity started to being tracked (properties converted to observable). */ registerCtor(ctor?: (entity: RawEntity) => void, initializer?: (entity: IEntity) => void); /** * Creates an entity for this type. * @param initialValues Entity initial values. * @returns Entity with observable properties. */ createEntity(initialValues: Object): IEntity; createRawEntity(initialValues: Object): RawEntity; /** Checks if this type can be set with given type. */ isAssignableWith(otherType: EntityType): boolean; /** Checks if this type can be set to given type. */ isAssignableTo(otherType: EntityType): boolean; /** Add new validation method to entity type. */ addValidation(name: string, func: (entity: IEntity) => string, message: string, args?: any); } /** Beetle uses this interface internally. */ interface InternalSet<T extends IEntity> { toString(): string; getEntity(key: string): T; getEntities(): T[]; } /** Server and array query shared interface */ interface Query<T> { /** * Indicates wheter or not include total count in result. * @param isEnabled When true, total count will be included in result. Default value: true. */ inlineCount(isEnabled?: boolean): Query<T>; /** * If model has inheritance, when querying base type we can tell which derived type we want to load. * @param type Derived type name. */ ofType<TResult extends T>(type: string | (new (...args: any[]) => TResult)): Query<TResult>; /** * Filter query based on given expression. * @param predicate A function to test each element for a condition (can be string expression). * @param varContext Variable context for the expression. */ where(predicate: string | ((entity: T) => boolean), varContext?: any): Query<T>; /** * Sorts results based on given properties. * @param keySelector The properties to sort by. */ orderBy(keySelector?: string | ((entity: T) => any)): Query<T>; /** * Sorts results based on given properties descendingly. * @param keySelector The properties to sort by. */ orderByDesc(keySelector?: string | ((entity: T) => any)): Query<T>; /** Selects only given properties using projection. */ select<TResult>(selector: string | string[] | ((entity: T) => TResult)): Query<TResult>; select<TResult>(...selectors: string[]): Query<TResult>; select(selector: string | string[] | ((entity: T) => any)): Query<any>; select(...selectors: string[]): Query<any>; /** * Skips given count records and start reading. * @param count The number of items to skip. */ skip(count: number): Query<T>; /** * Takes only given count records. * @param count The number of items to take. */ take(count: number): Query<T>; /** * Takes only given count records . * @param count The number of items to take. */ top(count: number): Query<T>; /** * Groups query by given keys (projects them into a new type) and returns values (projecting into new type). * @param keySelector A projection to extract the key for each element. * @param valueSelector A projection to create a result value from each group. */ groupBy<TKey, TResult>(keySelector: (entity: T) => TKey, valueSelector: (group: Grouping<T, TKey>) => TResult): Query<TResult>; groupBy<TKey>(keySelector: (entity: T) => TKey): Query<Grouped<T, TKey>>; groupBy<TResult>(keySelector: string | ((entity: T) => any), valueSelector: string | ((group: Grouping<T, any>) => TResult)): Query<TResult>; groupBy(keySelector: string | ((entity: T) => any)): Query<Grouped<T, any>>; groupBy(keySelector: string | ((entity: T) => any), valueSelector: string | ((group: Grouping<T, any>) => any)): Query<any>; /** * Gets only distinct items, when selector is given it will be used as comparer (project and compares projected objects). * @param selector A projection to extract the key for each element. */ distinct(): Query<T>; distinct<TResult>(selector: string | ((entity: T) => TResult)): Query<TResult>; distinct(selector: string | ((entity: T) => any)): Query<any>; /** Reverse the collection. */ reverse(): Query<T>; /** * Selects given collection property for each element and returns all in a new array. * @param properties Properties or PropertyPaths to select (project). */ selectMany<TResult>(selector: string | ((entity: T) => Array<TResult>)): Query<TResult>; selectMany(selector: string | ((entity: T) => any)): Query<any>; /** * Gets all the items after first succesful predicate. * @param predicate A function to test each element for a condition (can be string expression). * @param varContext Variable context for the expression. */ skipWhile(predicate: string | ((entity: T) => boolean), varContext?: any): Query<T>; /** * Gets all the items before first succesful predicate. * @param predicate A function to test each element for a condition (can be string expression). * @param varContext Variable context for the expression. */ takeWhile(predicate: string | ((entity: T) => boolean), varContext?: any): Query<T>; /** Executes this query. */ then(successCallback: (result: beetle.interfaces.QueryResultArray<T>) => void, errorCallback?: (e: AjaxError) => void, options?: any): AjaxCall<beetle.interfaces.QueryResultArray<T>>; /** Sets options to be used at execution. */ withOptions(options: any): Query<T>; } /** After an executer function called on a server query, this interface is returned. */ interface ClosedQueryable<T, TOptions> { /** Executes this query using related entity manager. */ execute(options?: TOptions, successCallback?: (result: T) => void, errorCallback?: (e: AjaxError) => void): AjaxCall<T>; /** Executes this query using related entity manager. */ execute<TResult>(options?: TOptions, successCallback?: (result: TResult) => void, errorCallback?: (e: AjaxError) => void): AjaxCall<TResult>; /** Executes this query using related entity manager. Shortcut for 'execute'. */ x(options?: TOptions, successCallback?: (result: T) => void, errorCallback?: (e: AjaxError) => void): AjaxCall<T>; /** Executes this query using related entity manager. Shortcut for 'execute'. */ x<TResult>(options?: TOptions, successCallback?: (result: TResult) => void, errorCallback?: (e: AjaxError) => void): AjaxCall<TResult>; /** Executes this query using related entity manager. Shortcut for 'execute(...).then'. */ then(successCallback: (result: T) => void, errorCallback?: (e: AjaxError) => void, options?: TOptions): AjaxCall<T>; } /** Server query parameters are kept with this structure. */ interface EntityQueryParameter { name: string; value: any; } /** When enabled these extra information will be attached to server results. */ interface QueryResultExtra { /** Server can send custom data using this property (carried using a http header). */ userData?: string; /** Http header getter function. */ headerGetter: (name: string) => string; /** When ajax provider exposes xhr, this property will be available. */ xhr?: any; } /** Server array results have these extra properties (when enabled). */ interface QueryResultArray<T> extends Array<T> { /** Extra information about query (when enabled). */ $extra?: QueryResultExtra; /** Inline count (calculated excluding skip-take from query). */ $inlineCount?: number; } /** Beetle uses some minified objects to reduce package size. */ interface PropertyValue { /** Property name. */ p: string; /** Property value. */ v: any; } /** This interface is used to track complex types' owners. */ interface OwnerValue { owner: IEntity; property: Property; } /** Entity tracker interface. Change tracking is made using this structure. */ interface Tracker { entity: IEntity; entityType: EntityType; entityState: enums.entityStates; /** When true, entity will be updated -even there is no modified property. */ forceUpdate: boolean; /** Initial values of changed properties. */ originalValues: PropertyValue[]; /** Previously accepted values of changed properties. */ changedValues: PropertyValue[]; manager: core.EntityManager; owners: OwnerValue[]; /** Validation errors for the entity. */ validationErrors: ValidationError[]; /** Notify when a valid state changed for the entity. */ validationErrorsChanged: core.Event<ValidationErrorsChangedEventArgs>; /** Notify when a state changed for the entity. */ entityStateChanged: core.Event<EntityStateChangedEventArgs>; /** Notify when a property changed for the entity. */ propertyChanged: core.Event<PropertyChangedEventArgs>; /** Notify when an array property changed for the entity. */ arrayChanged: core.Event<ArrayChangedEventArgs>; /** Entity's primary key value (multiple keys will be joined with '-'). */ key: string; toString(): string; isChanged(): boolean; /** Clears all navigations and marks entity as Deleted. */ delete(); /** Clears all navigations and detached entity from its manager. */ detach(); /** Marks entity as Added. */ toAdded(); /** Marks entity as Modified. */ toModified(); /** Marks entity as Deleted. */ toDeleted(); /** Marks entity as Unchanged. */ toUnchanged(); /** Marks entity as Detached. */ toDetached(); /** Resets all changes to initial values. */ rejectChanges(); /** Resets all changes to last accepted values. */ undoChanges(); /** Accept all changes. */ acceptChanges(); /** Gets internal value of the property from observable entity. */ getValue(property: string); /** Sets internal value of the property of observable entity. */ setValue(property: string, value: any); /** Gets original value for property. */ getOriginalValue(property: string): any; /** * Get foreign key value for this navigation property. * @returns Comma separated foreign keys. */ foreignKey(navProperty: NavigationProperty): string; /** Creates a query that can load this navigation property. */ createLoadQuery<T extends IEntity>(navPropName: string, resourceName: string): querying.EntityQuery<T>; /** Loads the navigation property using EntityManager. */ loadNavigationProperty(navPropName: string, expands: string[], resourceName: string, options?: ManagerQueryOptions, successCallback?: (result: any) => void, errorCallback?: (e: AjaxError) => void): AjaxCall<any>; /** Validates entity against metadata data annotation validations. */ validate(): ValidationError[]; /** * Creates a raw javascript object representing this entity. * @param includeNavigations When true, all navigation values will be included (recursively, so be careful it can cause stack overflow). */ toRaw(includeNavigations?: boolean): any; } /** Beetle uses some minified objects to reduce package size. */ interface TrackInfo { /** Type name. */ t: string; /** Entity state name. */ s: string; /** Save index in the save array. */ i: number; /** When true, entity will be updated -even there is no modified property. */ f?: boolean; /** Original values object. */ o?: any; } /** Exported entity tracking information are kept with this structure. It's like basic version of EntityTracker. */ interface ExportEntity { /** Entity tracking information. */ $t: TrackInfo; } /** Changes are merged in a package to use in server request. */ interface SavePackage { /** These entities will be sent to server for persistence. */ entities: ExportEntity[]; /** when true, each entity will be updated -even there is no modified property. */ forceUpdate?: boolean; /** We can send custom data to server using this property (carried using a http header). */ userData?: string; } /** * Server side generated value is carried back to client in this structure. * Index is the entity's index in the save package. */ interface GeneratedValue { /** Entity's save index in the save array. */ Index: number; /** Server side changed property name. */ Property: string; /** Server side assigned value. */ Value: any; } /** Server sends back this structure after a succesful save. */ interface SaveResult { /** Affected record count after the save. */ AffectedCount: number; /** Server side generated changes on existing entities. */ GeneratedValues: GeneratedValue[]; /** Server side generated entities, will be merged to local cache. */ GeneratedEntities: IEntity[]; /** Server can send custom data using this property (carried using a http header). */ UserData: string; } /** Entities read from Beetle server has these properties (before converting to observables). */ interface RawEntity { /** Entity type's full name (i.e. 'Package.Model.Customer'). */ $type: string; /** Extra information about query (when enabled). */ $extra?: QueryResultExtra; } /** Internationalization members. */ interface I18N { argCountMismatch: string; arrayEmpty: string; arrayNotSingle: string; arrayNotSingleOrEmpty: string; assignError: string; assignErrorNotEntity: string; autoGeneratedCannotBeModified: string; beetleQueryChosenMultiTyped: string; beetleQueryChosenPost: string; beetleQueryNotSupported: string; cannotBeEmptyString: string; cannotCheckInstanceOnNull: string; cannotDetachComplexTypeWithOwners: string; compareError: string; complexCannotBeNull: string; couldNotLoadMetadata: string; couldNotLocateNavFixer: string; couldNotLocatePromiseProvider: string; couldNotParseToken: string; countDiffCantBeCalculatedForGrouped: string; dataPropertyAlreadyExists: string; entityAlreadyBeingTracked: string; entityNotBeingTracked: string; executionBothNotAllowedForNoTracking: string; expressionCouldNotBeFound: string; functionNeedsAlias: string; functionNotSupportedForOData: string; instanceError: string; invalidArguments: string; invalidDefaultValue: string; invalidEnumValue: string; invalidExpression: string; invalidPropertyAlias: string; invalidStatement: string; invalidValue: string; managerInvalidArgs: string; maxLenError: string; maxPrecisionError: string; mergeStateError: string; minLenError: string; noMetadataEntityQuery: string; noMetadataRegisterCtor: string; noOpenGroup: string; notFoundInMetadata: string; notImplemented: string; notNullable: string; oDataNotSupportMultiTyped: string; onlyManagerCreatedCanBeExecuted: string; onlyManagerCreatedCanAcceptEntityShortName: string; pendingChanges: string; pluralNeedsInverse: string; projectionsMustHaveAlias: string; propertyNotFound: string; queryClosed: string; rangeError: string; requiredError: string; sameKeyExists: string; sameKeyOnDifferentTypesError: string; settingArrayNotAllowed: string; stringLengthError: string; syncNotSupported: string; twoEndCascadeDeleteNotAllowed: string; typeError: string; typeMismatch: string; typeRequiredForLocalQueries: string; unclosedQuote: string; unclosedToken: string; unexpectedProperty: string; unexpectedToken: string; unknownDataType: string; unknownExpression: string; unknownFunction: string; unknownParameter: string; unknownValidator: string; unsoppertedState: string; validationErrors: string; validationFailed: string; valueCannotBeNull: string; operatorNotSupportedForOData: string; } } /** Beetle entities have these properties (after converting to observables). */ interface IEntity { $tracker: interfaces.Tracker; /** Extra information about query (when enabled). */ $extra?: interfaces.QueryResultExtra; } /** Entity related options. */ interface EntityOptions { merge?: enums.mergeStrategy; state?: enums.entityStates; /** Automatically fix scalar navigations using foreign keys (fast). */ autoFixScalar?: boolean; /** Automatically fix plural navigations looking for foreign references (slow). */ autoFixPlural?: boolean; } /** Data service query options. */ interface ServiceQueryOptions { /** When true, all values will be handled by their value (i.e. some type changes, string->Date). */ handleUnmappedProperties?: boolean; /** Use request body for beetle parameters when making request. Useful for large queries (some web servers can't process very large query strings). */ useBody?: boolean; /** Web method to use (i.e. PUT, POST, GET etc..). */ method?: string; /** The type of data that you're expecting back from the server. */ dataType?: string; /** Type of data you're sending. */ contentType?: string; /** Use async for ajax operation. Default is true. Be careful, some AjaxProviders does not support sync. */ async?: boolean; /** Ajax request timeout. */ timeout?: number; /** AjaxProvider extra settings. These will be mixed to ajax options. */ extra?: any; /** Server uri to join with base address. To override existing resource address. */ uri?: string; /** Request headers. */ headers?: any; /** When enabled, if AjaxProvider exposes xhr, this will be attached to the results (via $extra). */ includeXhr?: boolean; /** When enabled, response header getter function will be attached to the results (via $extra). */ includeHeaderGetter?: boolean; } /** Entity manager query options. */ interface ManagerQueryOptions extends ServiceQueryOptions { /** Merge strategy to use when attaching an entity to local cache. */ merge?: enums.mergeStrategy; /** Executing strategy for the query. */ execution?: enums.executionStrategy; /** Automatically fix scalar navigations using foreign keys (fast). */ autoFixScalar?: boolean; /** Automatically fix plural navigations looking for foreign references (slow). */ autoFixPlural?: boolean; /** Variable context for the query. */ varContext?: any; /** Even service supports another query format (like OData), use Beetle format instead for this query. */ useBeetleQueryStrings?: boolean; } /** Data service constructor options. */ interface ServiceOptions { /** Ajax request timeout. */ ajaxTimeout?: number; /** The type of data that you're expecting back from the server. */ dataType?: string; /** Type of data you're sending. */ contentType?: string; /** Creates properties for entity sets on the manager. */ registerMetadataTypes?: boolean; /** Ajax provider instance. */ ajaxProvider?: baseTypes.AjaxProviderBase; /** Serializer service instance. */ serializationService?: baseTypes.SerializationServiceBase; } /** Entity manager constructor options. */ interface ManagerOptions extends ServiceOptions { /** Automatically fix scalar navigations using foreign keys (fast). */ autoFixScalar?: boolean; /** Automatically fix plural navigations looking for foreign references (slow). */ autoFixPlural?: boolean; /** Every merged entity will be validated. */ validateOnMerge?: boolean; /** Validates entities before save. */ validateOnSave?: boolean; /** Every change triggers a re-validation. Effects can be seen on EntityManager's validationErrors property. */ liveValidate?: boolean; /** When true, all values will be handled by their value (i.e. some type changes, string->Date). */ handleUnmappedProperties?: boolean; /** When true, entity will be updated -even there is no modified property. */ forceUpdate?: boolean; /** Use async for ajax operation. Default is true. Be careful, some AjaxProviders does not support sync. */ workAsync?: boolean; /** When true, while creating save package; for modified only changed and key properties, for deleted only key properties will be used. */ minimizePackage?: boolean; /** Promise provider instance. */ promiseProvider?: baseTypes.PromiseProviderBase; } /** * Entity exporting options. * Beetle can exclude unchanged properties for modified entities to reduce package size (server side needs to support this). */ interface ExportOptions { /** When true, while creating save package, for modified only changed and key properties, for deleted only key properties will be used. */ minimizePackage?: boolean; } /** Options used when creating a save package. */ interface PackageOptions extends ExportOptions { /** Validates entities before save. */ validateOnSave?: boolean; /** We can send custom data to server using this property (carried using a http header). */ userData?: string; /** when true, each entity will be updated -even there is no modified property. */ forceUpdate?: boolean; } /** Data service options for save operation. */ interface ServiceSaveOptions { /** Web method to use (i.e. PUT, POST, GET etc..). */ method?: string; /** The type of data that you're expecting back from the server. */ dataType?: string; /** Type of data you're sending. */ contentType?: string; /** Use async for ajax operation. Default is true. Be careful, some AjaxProviders does not support sync. */ async?: boolean; /** Ajax request timeout. */ timeout?: number; /** AjaxProvider extra settings. These will be mixed to ajax options. */ extra?: any; /** Server uri to join with base address. To override existing resource address. */ uri?: string; /** To override existing save address (default is 'SaveChanges'). */ saveAction?: string; /** Request headers. */ headers?: any; /** When enabled, if AjaxProvider exposes xhr, this will be attached to the results (via $extra). */ includeXhr?: boolean; /** When enabled, response header getter function will be attached to the results (via $extra). */ includeHeaderGetter?: boolean; } /** * General save options. * When extra entities are returned from save operation (via GeneratedEntities property), this options are used for merging with local cache. */ interface PackageSaveOptions extends PackageOptions, ServiceSaveOptions { /** Automatically fix scalar navigations using foreign keys (fast). */ autoFixScalar?: boolean; /** Automatically fix plural navigations looking for foreign references (slow). */ autoFixPlural?: boolean; } /** Entity manager save options, all save options are together. */ interface ManagerSaveOptions extends PackageSaveOptions { entities?: IEntity[]; } /** Beetle passes this interface to ObservableProviders for them to make entity observable. For advanced use only. */ interface ObservableProviderCallbackOptions { propertyChange: (entity: any, property: string, accessor: (v?: any) => any, newValue: any) => void; arrayChange: (entity: any, property: string, items: Array<any>, removed: Array<any>, added: Array<any>) => void; dataPropertyChange: (entity: any, property: interfaces.DataProperty, accessor: (v?: any) => any, newValue) => void; scalarNavigationPropertyChange: (entity: any, property: interfaces.NavigationProperty, accessor: (v?: any) => any, newValue: any) => void; pluralNavigationPropertyChange: (entity: any, property: interfaces.NavigationProperty, items: Array<any>, removed: Array<any>, added: Array<any>) => void; arraySet: (entity: any, property: string, oldArray: Array<any>, newArray: Array<any>) => void; } /** * Ajax operation error structure. * Some properties are not available for some libraries (like angular). * Error callback objects might contain library dependent members. */ interface AjaxError extends Error { /** Error status code (i.e. 400, 500). */ status: number; /** Ajax provider specific extra information about error. */ detail: any; /** Entity manager the query originated. */ manager: core.EntityManager; /** The query that caused the error. */ query: querying.EntityQuery<any>; /** Ajax provider's error object (when available). */ error?: any; /** Xhr object used in the request (available only if AjaxProvider exposes xhr). */ xhr?: XMLHttpRequest; } /** Helper functions. We are trying not to use ECMA 5, so we polyfill some methods. */ namespace helper { /** * Creates an assert instance to work with, a shortcut. * @example * helper.assertPrm(prm, 'prm').isArray().check() * @param value The value of parameter. * @param name The name of the parameter. */ function assertPrm(obj1: any, name: string): Assert; /** * Combines first object's properties with second object's properties on a new object. * @param obj1 The first object. * @param obj2 The second object. * @returns New object containing all properties from both objects. */ function combine(obj1: Object, obj2: Object): any; /** * Extends obj1 with obj2's properties. * @param obj1 The main object. * @param obj2 Object to extend with. * @returns obj1 is returned. */ function extend(obj1: Object, obj2: Object): any; /** * Checks if the given two are equal. if parameters are both objects, recursively controls their properties too. * @param obj1 The first object. * @param obj2 The second object. * @returns True when two objects are equal, otherwise false. */ function objEquals(obj1: Object, obj2: Object): boolean; /** * Format string using given arguments. %1 and {1} format can be used for placeholders. * @param string String to format. * @param params Values to replace. */ function formatString(str: string, ...params: string[]): string; /** * Finds the index of the given item in the array. * @param array Array to search. * @param item Item to find. * @param index Start index. * @returns Found index. If the item could not be found returns '-1'. */ function indexOf(array: any[], item, start?: number): number; /** * Calls given callback with item and current index parameters for each item in the array. * @param array Array to iterate. * @param callback Method to call for each item. */ function forEach(array: any[], callback: (item, idx) => void); /** * Iterate objects properties and skips ones starting with '$'. * @param object Object to iterate. * @param callback Method to call for each property. */ function forEachProperty(object: any, callback: (propName: string, value: any) => void); /** * Finds given item in the array. * When property is given, looks item's property value, otherwise compares item's itself. * @param array Array to search. * @param value Value to find. * @param property Property to look for the value. * @returns When value is found; if property is provided, the array item containing the given value, otherwise value itself. When not found, null. */ function findInArray(array: any[], value, property?: string); /** * Copies array items that match the given conditions to another array and returns the new array. * @param array The array to filter. * @param predicate A function to test each element for a condition (can be string expression). * @returns New array with filtered items. */ function filterArray<T>(array: T[], predicate: (item: T) => boolean): T[]; /** * Removes the item from given array. * @param array The array to remove item from. * @param item Item to remove. * @param property Property to look for the value. * @returns Removed item indexes. */ function removeFromArray(array: any[], item, property?: string): number; /** * Creates a new array with the results of calling the provided function on every element in the given array. * @param array The array to map. * @param callback Function that produces new element. * @returns New array with mapped values. */ function mapArray<T>(array: any[], callback: (item, index) => T): T[]; /** * Creates a GUID string with "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" format. * @returns Newly generated GUID. */ function createGuid(): string; /** * Creates string representation of given function with arrow syntax. * @param func The function. * @returns Arrow style code for given function. */ function funcToLambda(func: Function): string; /** * Finds and returns function name. Works for ES6 classes too. * @param func The function (or class). * @returns Name of the given function. */ function getFuncName(func: Function): string; /** * Reads property of value, used when we are not sure if property is observable. * @param object Deriving type. * @param property Property path. Can be a chain like "address.city.name". * @returns Value of property (undefined when a property cannot be found). */ function getValue(object, propertyPath: string); /** * Gets localized value for given name using "settings.localizeFunc" function. * @param resourceName Resource name. * @param altValue Alternative value to use when resource cannot be found. * @returns Value for the given resource name. */ function getResourceValue(resourceName: string, altValue?: string): string; /** * Creates validation error object using given parameters. * @param entity Entity containing invalid value. * @param value Invalid value itself. * @param property Property containing invalid value. * @param message Validation message. * @param validator Validator instance. * @returns Validation error object. */ function createValidationError(entity, value, property: string, message: string, validator: interfaces.Validator); /** * Creates error object by formatting provided message and populates with given object's values. * @param message Error message. * @param arg1 Message format arguments. * @param arg2 Extra informations, properties will be attached to error object. * @returns Error object. */ function createError(message: string, args?: Array<any>, props?: interfaces.Dictionary<any>): Error; /** * Updates foreign keys of given navigation property with new values. * @param entity The entity. * @param navProperty The navigation property. * @param newValue Value of the navigation property. */ function setForeignKeys(entity: IEntity, navProperty: interfaces.NavigationProperty, newValue); /** * Creates an array and overrides methods to provide callbacks on array changes. * @param initial Initial values for the array. * @param object Owner object of the array. * @param property Navigation property metadata. * @param after Array change callback. * @returns Trackable array, an array with change events. */ function createTrackableArray<T>(initial: Array<T>, object: Object, property: interfaces.NavigationProperty, after: (entity: any, property: string, instance: interfaces.TrackableArray<T>, removed: Array<T>, added: Array<T>) => void): interfaces.TrackableArray<T>; } /** * Assertion methods. Two different usage possible, static methods and instance methods. * Static methods returns true or false. Instance methods can be chained and they collect errors in an array. * Check method throws error if there are any. */ class Assert { constructor(value: any, name: string); errors: string[]; /** Checks if value is not null or undefined. */ hasValue(): Assert; /** Checks if value is object. */ isObject(): Assert; /** Checks if value is function. */ isFunction(): Assert; /** Checks if value is a non-empty string. */ isNotEmptyString(): Assert; /** * Checks if value is an object of given type. * @param typeName Name of the javascript type. */ isTypeOf(typeName: string): Assert; /** Checks if value is array. */ isArray(): Assert; /** * Checks if value is an symbol of given enum. * @param enumType Type of the enum. */ isEnum(enumType: string): Assert; /** * Checks if value is an instance of given type. * @param type Javascript function or class to check. */ isInstanceOf(type: any): Assert; /** If previous checks created any error, joins them with a new line and throws an Error. */ check(); /** Checks if value is not null or undefined. */ static hasValue(value: any): boolean; /** Checks if value is object. */ static isObject(value: any): boolean; /** Checks if value is function. */ static isFunction(value: any): boolean; /** Checks if value is a non-empty string. */ static isNotEmptyString(value: any): boolean; /** * Checks if value is an object of given type. * @param value The value to check. * @param typeName Name of the javascript type. */ static isTypeOf(value: any, typeName: string): boolean; /** Checks if value is array. */ static isArray(value: any): boolean; /** * Checks if value is an symbol of given enum. * @param value The value to check. * @param enumType Type of the enum. */ static isEnum(value: any, enumType: string): boolean; /** * Checks if value is an instance of given type. * @param value The value to check. * @param type Javascript function or class to check. */ static isInstanceOf(value: any, type: any): boolean; } /** * Base types, can be considered as abstract classes. * This classes can be overwritten outside of the project, and later can be injected through constructors to change behaviours of core classes. */ namespace baseTypes { /** Data conversion base type (interface). With this we can abstract date conversion and users can choose (or write) their implementation. */ abstract class DateConverterBase { protected constructor(name: string); name: string; toString(): string; /** Converts given value to date. */ parse(value: string): Date; /** Converts given date to ISO string. */ toISOString(value: Date): string; } /** Observable provider base class. Makes given object's properties observable. */ abstract class ObservableProviderBase { protected constructor(name: string); name: string; toString(): string; /** When given property for given object is observable returns true, otherwise false. */ isObservable(object: Object, property: string): boolean; /** Makes given object observable. */ toObservable(object: string, type: interfaces.EntityType, callbacks: ObservableProviderCallbackOptions); /** Reads an observable property value from object. */ getValue(object: Object, property: string): any; /** Sets the value of observable property of given object. */ setValue(object: Object, property: string, value: any); } /** Ajax provider base class. Operates ajax operations. */ abstract class AjaxProviderBase { protected constructor(name: string); name: string; toString(): string; /** * Ajax operation function. * @param uri Uri to make request. * @param type Request type (POST, GET..) * @param dataType Request data type (xml, json..) * @param contentType Request content type (application/x-www-form-urlencoded; charset=UTF-8, application/json..) * @param data Request data. * @param async If set to false, request will be made synchronously. * @param timeout AJAX call timeout value. if call won't be completed after given time, exception will be thrown. * @param extra Implementor specific arguments. * @param headers Custom HTTP headers. * @param successCallback Function to call after operation succeeded. * @param errorCallback Function to call when operation fails. */ doAjax(uri: string, method: string, dataType: string, contentType: string, data: any, async: boolean, timeout: number, extra: interfaces.Dictionary<any>, headers: interfaces.Dictionary<string>, successCallback: (data: any, headerGetter: (name: string) => string, xhr?: XMLHttpRequest) => void, errorCallback: (e: AjaxError) => void); } /** Serialization service base class. Deserializes incoming data and serializes outgoing data. */ abstract class SerializationServiceBase { protected constructor(name: string); name: string; toString(): string; /** Serializes given data to string. */ serialize(data: any): string; /** Deserializes given string to object. */ deserialize(string: string): any; } /** Promise provider base class. Creates deferred promises for async operations. */ abstract class PromiseProviderBase { protected constructor(name: string); name: string; toString(): string; /** * Creates deferred object. * @returns Deferred object which can be resolved or rejected. */ deferred(): any; /** * Gets promise for deferred object. * @param deferred Deferred object which can be resolved or rejected. * @returns Returns a promise. */ getPromise(deferred: any): AjaxCall<any>; /** * Resolves given promise for succesful operation. * @param deferred Deferred object. * @param data Operation result. */ resolve(deferred: any, data: any); /** * Rejects given promise for failed operation. * @param deferred Deferred object. * @param error Error to pass to failed callback. */ reject(deferred: any, error: AjaxError); } /** Data service base class. */ abstract class DataServiceBase { protected constructor(url: string, loadMetadata?: boolean, options?: ServiceOptions); protected constructor(url: string, metadataManager: metadata.MetadataManager, options?: ServiceOptions); protected constructor(url: string, metadata: Object, options?: ServiceOptions); protected constructor(url: string, metadata: string, options?: ServiceOptions); uri: string; /** Default ajax timeout. */ ajaxTimeout: number; /** Default data type for http requests. */ dataType: string; /** Default content type for http requests. */ contentType: string; /** Metadata container. */ metadataManager: metadata.MetadataManager; toString(): string; /** Checks if service is ready. */ isReady(): boolean; /** Subscribe the ready callback. */ ready(callback: () => void); /** Gets entity type from metadata by its short name. */ getEntityType(shortName: string): interfaces.EntityType; /** Gets entity type from metadata by its short name. */ getEntityType<T extends IEntity>(constructor: string | (new (...args: any[]) => T)): interfaces.EntityType; /** Creates a query for a resource. Every data service can have their own query types. */ createQuery<T extends IEntity>(resourceName: string, type?: string | (new (...args: any[]) => T), manager?: core.EntityManager): querying.EntityQuery<T>; /** Creates a query for a resource. Every data service can have their own query types. */ createQuery(resourceName: string, shortName?: string, manager?: core.EntityManager): querying.EntityQuery<any>; /** Creates a query for a resource. Every data service can have their own query types. */ createEntityQuery<T extends IEntity>(type: string | (new (...args: any[]) => T), resourceName?: string, manager?: core.EntityManager): querying.EntityQuery<T>; /** * Register constructor and initializer (optional) for given type. * @param shortName Short name of the type. * @param constructor Constructor function. Called right after the entity object is generated. * @param initializer Initializer function. Called after entity started to being tracked (properties converted to observable). */ registerCtor<T extends IEntity>(type: string | (new (...args: any[]) => T), ctor?: (rawEntity: interfaces.RawEntity) => void, initializer?: (entity: T) => void); /** * Fetch metadata from server. * @param options Fetch metadata options (async: boolean). * @param successCallback Function to call after operation succeeded. * @param errorCallback Function to call when operation fails. */ fetchMetadata(options?: ServiceQueryOptions, successCallback?: (data: any) => void, errorCallback?: (e: AjaxError) => void); /** * When there is no metadata available services may be able to create entities asynchronously (server side must be able to support this). * @param typeName Type name to create. * @param initialValues Entity initial values. * @param options Options (makeObservable: boolean, async: boolean). * @param successCallback Function to call after operation succeeded. * @param errorCallback Function to call when operation fails. */ createEntityAsync<T extends IEntity>(type: string | (new (...args: any[]) => T), initialValues: Object, options: ServiceQueryOptions, successCallback: (entity: T) => void, errorCallback: (e: AjaxError) => void); /** * When there is no metadata available services may be able to create entities asynchronously (server side must be able to support this). * @param typeName Type name to create. * @param initialValues Entity initial values. * @param options Options (makeObservable: boolean, async: boolean). * @param successCallback Function to call after operation succeeded. * @param errorCallback Function to call when operation fails. */ createEntityAsync(shortName: string, initialValues: Object, options: ServiceQueryOptions, successCallback: (entity: IEntity) => void, errorCallback: (e: AjaxError) => void); /** * Executes given query. * @param query Query to execute. * @param options Query options. * @param successCallback Function to call after operation succeeded. * @param errorCallback Function to call when operation fails. */ executeQuery<T>(query: querying.EntityQuery<T>, options: ServiceQueryOptions, successCallback: (result: interfaces.QueryResultArray<T>) => void, errorCallback: (e: AjaxError) => void); executeQuery<T>(query: interfaces.ClosedQueryable<T, ServiceQueryOptions>, options: ServiceQueryOptions, successCallback: (result: T) => void, errorCallback: (e: AjaxError) => void); executeQuery(query: querying.EntityQuery<any>, options: ServiceQueryOptions, successCallback: (result: any) => void, errorCallback: (e: AjaxError) => void); executeQuery(query: interfaces.ClosedQueryable<any, ServiceQueryOptions>, options: ServiceQueryOptions, successCallback: (result: any) => void, errorCallback: (e: AjaxError) => void); /** * Send changes to server. * @param savePackage An object containing entities to send to server for persistence. * @param options Query options. * @param successCallback Function to call after operation succeeded. * @param errorCallback Function to call when operation fails. */ saveChanges(options: ServiceSaveOptions, successCallback: (result: interfaces.SaveResult) => void, errorCallback: (e: AjaxError) => void); } } /** Base types' implementations. */ namespace impls { /** Default date converter class. Uses browser's default Date object. */ class DefaultDateConverter extends baseTypes.DateConverterBase { constructor(); } /** Knockout observable provider class. Makes given object's properties observable. */ class KoObservableProvider extends baseTypes.ObservableProviderBase { constructor(ko); } /** Property observable provider class. Makes given object's fields properties with getter setter and tracks values. */ class PropertyObservableProvider extends baseTypes.ObservableProviderBase { constructor(); } /** jQuery ajax provider class. Operates ajax operations via jQuery. */ class JQueryAjaxProvider extends baseTypes.AjaxProviderBase { constructor($); } /** Angularjs ajax provider class. Operates ajax operations via angularjs. */ class AngularjsAjaxProvider extends baseTypes.AjaxProviderBase { constructor(angularjs); } /** Angular ajax provider class. Operates ajax operations via angular. */ class AngularAjaxProvider extends baseTypes.AjaxProviderBase { constructor(http, RequestConstructor, HeadersConstructor); } /** Pure javascript ajax provider class. */ class VanillajsAjaxProvider extends baseTypes.AjaxProviderBase { constructor(); } /** Node.js ajax provider class. */ class NodejsAjaxProvider extends baseTypes.AjaxProviderBase { constructor(http, https); } /** JSON serialization class. Deserializes incoming data and serializes outgoing data. */ class JsonSerializationService extends baseTypes.SerializationServiceBase { constructor(); } /** Q promise provider class. */ class QPromiseProvider extends baseTypes.PromiseProviderBase { constructor(Q); } /** Angular.js promise provider. */ class AngularjsPromiseProvider extends baseTypes.PromiseProviderBase { constructor(angularjs); } /** jQuery promise provider. */ class JQueryPromiseProvider extends baseTypes.PromiseProviderBase { constructor($); } /** ES6 promise provider. */ class Es6PromiseProvider extends baseTypes.PromiseProviderBase { constructor(); } } /** Represents a primitive value member. */ namespace metadata { /** Metadata container. */ class MetadataManager { constructor(); constructor(metadataObj: Object); constructor(metadataStr: string); /** All entity types. */ types: interfaces.EntityType[]; /** Type dictionary for easy access by name. */ typesDict: interfaces.Dictionary<interfaces.EntityType>; /** Enum types. */ enums: any[]; name: string; displayName: string; toString(): string; /** * Finds entity type by given entity type name (fully qualified). * @param typeName Full type name. * @param throwIfNotFound Throws an error if given type name could not be found in cache. */ getEntityTypeByFullName(typeName: string, throwIfNotFound?: boolean): interfaces.EntityType; /** * Finds entity type by given entity type short name (only class name). * @param shortName Short type name. * @param throwIfNotFound Throws an error if given type name could not be found in cache. */ getEntityType(shortName: string, throwIfNotFound?: boolean): interfaces.EntityType; getEntityType<T extends IEntity>(constructor: string | (new (...args: any[]) => T), throwIfNotFound?: boolean): interfaces.EntityType; /** * Register constructor and initializer (optional) for the type. * @param shortName Short type name. * @param constructor Constructor function. Called right after the entity object is generated. * @param initializer Initializer function. Called after entity started to being tracked (properties converted to observable). */ registerCtor<T extends IEntity>(type: string | (new (...args: any[]) => T), ctor?: (rawEntity: interfaces.RawEntity) => void, initializer?: (entity: T) => void); /** * Creates an entity for the type. * @param shortName Short type name. * @param initialValues Entity initial values. * @returns Entity with observable properties. */ createEntity(shortName: string, initialValues?: Object): IEntity; createEntity<T extends IEntity>(constructor: string | (new (...args: any[]) => T), initialValues?: Object): T; /** * Creates a raw entity for this type. * @param shortName Short type name. * @param initialValues Entity initial values. * @returns Entity without observable properties. */ createRawEntity(shortName: string, initialValues?: Object): interfaces.RawEntity; createRawEntity<T extends IEntity>(constructor: string | (new (...args: any[]) => T), initialValues?: Object): interfaces.RawEntity; /** * Imports metadata from given parameter. * @param metadataPrm [Metadata Object] or [Metadata string] */ parseBeetleMetadata(metadata: string | Object); } } /** Querying related types. */ namespace querying { /** * Array query, executes against an array. Similar to Linq to Objects. * @example * var array = [{name: 'Test', age: 15}, {name: 'Test2', age: 25}]; * var query = array.asQueryable().where('name == "Test"'); * var result = query.execute(); */ class ArrayQuery<T> implements interfaces.Query<T> { constructor(array: T[]); /** Origin array. Query will be executed against this array. */ array: Array<T>; /** Variable context for the query. */ options: any; /** Indicates wheter or not include total count in result. */ inlineCountEnabled: boolean; // ReSharper disable RedundantQualifier /** * Indicates wheter or not include total count in result. * @param isEnabled When true, total count will be included in result. Default value: true. */ inlineCount(isEnabled?: boolean): beetle.querying.ArrayQuery<T>; /** * If model has inheritance, when querying base type we can tell which derived type we want to load. * @param type Derived type name. */ ofType<TResult extends T>(type: string | (new (...args: any[]) => TResult)): beetle.querying.ArrayQuery<TResult>; /** * Filter query based on given expression. * @param predicate A function to test each element for a condition (can be string expression). * @param varContext Variable context for the expression. */ where(predicate: string | ((entity: T) => boolean), varContext?: any): beetle.querying.ArrayQuery<T>; /** * Sorts results based on given properties. * @param keySelector The properties to sort by. */ orderBy(keySelector?: string | ((entity: T) => any) | ((entity1: T, entity2: T) => number)): beetle.querying.ArrayQuery<T>; /** * Sorts results based on given properties descendingly. * @param keySelector The properties to sort by. */ orderByDesc(keySelector?: string | ((entity: T) => any) | ((entity1: T, entity2: T) => number)): beetle.querying.ArrayQuery<T>; /** Selects only given properties using projection. */ select<TResult>(selector: string | string[] | ((entity: T) => TResult)): beetle.querying.ArrayQuery<TResult>; select<TResult>(...selectors: string[]): beetle.querying.ArrayQuery<TResult>; select(selector: string | string[] | ((entity: T) => any)): beetle.querying.ArrayQuery<any>; select(...selectors: string[]): beetle.querying.ArrayQuery<any>; /** * Skips given count records and start reading. * @paramcount The number of items to skip. */ skip(count: number): beetle.querying.ArrayQuery<T>; /** * Takes only given count records. * @param count The number of items to take. */ take(count: number): beetle.querying.ArrayQuery<T>; /** * Takes only given count records . * @param count The number of items to take. */ top(count: number): beetle.querying.ArrayQuery<T>; /** * Groups query by given keys (projects them into a new type) and returns values (projecting into new type). * @param keySelector A projection to extract the key for each element. * @param valueSelector A projection to create a result value from each group. */ groupBy<TKey, TResult>(keySelector: (entity: T) => TKey, valueSelector: (group: beetle.interfaces.Grouping<T, TKey>) => TResult): beetle.querying.ArrayQuery<TResult>; groupBy<TKey>(keySelector: (entity: T) => TKey): beetle.querying.ArrayQuery<beetle.interfaces.Grouped<T, TKey>>; groupBy<TResult>(keySelector: string | ((entity: T) => any), valueSelector: string | ((group: beetle.interfaces.Grouping<T, any>) => TResult)): beetle.querying.ArrayQuery<TResult>; groupBy(keySelector: string | ((entity: T) => any)): beetle.querying.ArrayQuery<beetle.interfaces.Grouped<T, any>>; groupBy(keySelector: string | ((entity: T) => any), valueSelector: string | ((group: beetle.interfaces.Grouping<T, any>) => any)): beetle.querying.ArrayQuery<any>; /** * Gets only distinct items, when selector is given it will be used as comparer (project and compares projected objects). * @param selector A projection to extract the key for each element. */ distinct(): beetle.querying.ArrayQuery<T>; distinct<TResult>(selector: string | ((entity: T) => TResult)): beetle.querying.ArrayQuery<TResult>; distinct(selector: string | ((entity: T) => any)): beetle.querying.ArrayQuery<any>; /** Reverse the collection. */ reverse(): beetle.querying.ArrayQuery<T>; /** * Selects given collection property for each element and returns all in a new array. * @param properties Properties or PropertyPaths to select (project). */ selectMany<TResult>(selector: string | ((entity: T) => Array<TResult>)): beetle.querying.ArrayQuery<TResult>; selectMany(selector: string | ((entity: T) => any)): beetle.querying.ArrayQuery<any>; /** * Gets all the items after first succesful predicate. * @param predicate A function to test each element for a condition (can be string expression). * @param varContext Variable context for the expression. */ skipWhile(predicate: string | ((entity: T) => boolean), varContext?: any): beetle.querying.ArrayQuery<T>; /** * Gets all the items before first succesful predicate. * @param predicate A function to test each element for a condition (can be string expression). * @param varContext Variable context for the expression. */ takeWhile(predicate: string | ((entity: T) => boolean), varContext?: any): beetle.querying.ArrayQuery<T>; // ReSharper restore RedundantQualifier /** * If all items suits given predication returns true, otherwise false. * @param predicate A function to test each element for a condition (can be string expression). * @param varContext Variable context for the expression. */ all(predicate?: string | ((entity: T) => boolean), varContext?: any): boolean; /** * If there is at least one item in query result (or any item suits given predication) returns true, otherwise false. * @param predicate A function to test each element for a condition (can be string expression). * @param varContext Variable context for the expression. */ any(predicate?: string | ((entity: T) => boolean), varContext?: any): boolean; /** * Calculates average of items of query (or from given projection result). * @param selector Property path to use on calculation. */ avg(selector?: string | ((entity: T) => number)): number; /** * Finds maximum value from items of query (or from given projection result). * @param selector Property path to use on calculation. */ max(selector?: string | ((entity: T) => number)): number; /** * Finds minimum value from items of query (or from given projection result). * @param selector Property path to use on calculation. */ min(selector?: string | ((entity: T) => number)): number; /** * Finds summary value from items of query (or from given projection result). * @param selector Property path to use on calculation. */ sum(selector?: string | ((entity: T) => number)): number; /** * Gets the count of items of query. * @param predicate A function to test each element for a condition (can be string expression). * @param varContext Variable context for the expression. */ count(predicate?: string | ((entity: T) => boolean), varContext?: any): number; /** * Gets the first value from items of query (or from given predication result). When there is no item, throws exception. * @param predicate A function to test each element for a condition (can be string expression). * @param varContext Variable context for the expression. */ first(predicate?: string | ((entity: T) => boolean), varContext?: any): T; /** * Gets the first value (or null when there is no items) from items of query (or from given predication result). * @param predicate A function to test each element for a condition (can be string expression). * @param varContext Variable context for the expression. */ firstOrDefault(predicate?: string | ((entity: T) => boolean), varContext?: any): T; /** * Gets the single value from items (or from given predication result). Where zero or more than one item exists throws exception. * @param predicate A function to test each element for a condition (can be string expression). * @param varContext Variable context for the expression. */ single(predicate?: string | ((entity: T) => boolean), varContext?: any): T; /** * Gets the single value (or null when there is no items) from items (or from given predication result). Where more than one item exists throws exception. * @param predicate A function to test each element for a condition (can be string expression). * @param varContext Variable context for the expression. */ singleOrDefault(predicate?: string | ((entity: T) => boolean), varContext?: any): T; /** * Gets the last value from items of query (or from given predication result). When there is no item, throws exception. * @param predicate A function to test each element for a condition (can be string expression). * @param varContext Variable context for the expression. */ last(predicate?: string | ((entity: T) => boolean), varContext?: any): T; /** * Gets the last value (or null when there is no items) from items of query (or from given predication result). * @param predicate A function to test each element for a condition (can be string expression). * @param varContext Variable context for the expression. */ lastOrDefault(predicate?: string | ((entity: T) => boolean), varContext?: any): T; /** * Executes this query against the related array. * @param options Variable context and query options. */ execute(options?: any): T[]; execute<TResult>(options?: any): TResult; /** * Executes this query against the related array. Shortcut for execute. * @param options Variable context and query options. */ x(options?: any): T[]; x<TResult>(options?: any): TResult; /** Executes this query. */ then(successCallback: (result: beetle.interfaces.QueryResultArray<T>) => void, errorCallback?: (e: AjaxError) => void, options?: any): AjaxCall<beetle.interfaces.QueryResultArray<T>>; /** Sets options to be used at execution. */ withOptions(options: any): ArrayQuery<T>; } class EntityQuery<T> implements interfaces.Query<T> { constructor(resource: string, type: interfaces.EntityType, manager: core.EntityManager); /** Server resource to query against. */ private resource: string; /** Entity type of the query. Will be needed if query will be executed locally. */ private entityType: interfaces.EntityType; /** Entity manager the query related. */ private manager: core.EntityManager; /** Parameters will be passed to server method. */ private parameters: interfaces.EntityQueryParameter[]; /** Query options. */ private options: ManagerQueryOptions; /** Indicates if this query has any beetle specific expression. */ private hasBeetlePrm: boolean; /** Indicates wheter or not include total count in result. */ private inlineCountEnabled: boolean; /** Sets entity type for query (used when executing locally). */ setEntityType(type: string | (new (...args: any[]) => T)): EntityQuery<T>; /** * Indicates wheter or not include total count in result. * @param isEnabled When true, total count will be included in result. Default value: true. */ inlineCount(isEnabled?: boolean): EntityQuery<T>; /** * If model has inheritance, when querying base type we can tell which derived type we want to load. * @param type Derived type name. */ ofType<TResult extends T>(type: string | (new (...args: any[]) => TResult)): EntityQuery<TResult>; /** * Filter query based on given expression. * @param predicate A function to test each element for a condition (can be string expression). * @param varContext Variable context for the expression. */ where(predicate: string | ((entity: T) => boolean), varContext?: any): EntityQuery<T>; /** * Sorts results based on given properties. * @param keySelector The properties to sort by. */ orderBy(keySelector?: string | ((entity: T) => any)): EntityQuery<T>; /** * Sorts results based on given properties descendingly. * @param properties The properties to sort by. */ orderByDesc(keySelector?: string | ((entity: T) => any)): EntityQuery<T>; /** Selects only given properties using projection. */ select<TResult>(selector: string | string[] | ((entity: T) => TResult)): EntityQuery<TResult>; select<TResult>(...selectors: string[]): EntityQuery<TResult>; select(selector: string | string[] | ((entity: T) => any)): EntityQuery<any>; select(...selectors: string[]): EntityQuery<any>; /** * Skips given count records and start reading. * @paramcount The number of items to skip. */ skip(count: number): EntityQuery<T>; /** * Takes only given count records. * @param count The number of items to take. */ take(count: number): EntityQuery<T>; /** * Takes only given count records . * @param count The number of items to take. */ top(count: number): EntityQuery<T>; /** * Groups query by given keys (projects them into a new type) and returns values (projecting into new type). * @param keySelector A projection to extract the key for each element. * @param valueSelector A projection to create a result value from each group. */ groupBy<TKey, TResult>(keySelector: (entity: T) => TKey, valueSelector: (group: interfaces.Grouping<T, TKey>) => TResult): EntityQuery<TResult>; groupBy<TKey>(keySelector: (entity: T) => TKey): EntityQuery<interfaces.Grouped<T, TKey>>; groupBy<TResult>(keySelector: string | ((entity: T) => any), valueSelector: string | ((group: interfaces.Grouping<T, any>) => TResult)): EntityQuery<TResult>; groupBy(keySelector: string | ((entity: T) => any)): EntityQuery<interfaces.Grouped<T, any>>; groupBy(keySelector: string | ((entity: T) => any), valueSelector: string | ((group: interfaces.Grouping<T, any>) => any)): EntityQuery<any>; /** * Gets only distinct items, when selector is given it will be used as comparer (project and compares projected objects). * @param selector A projection to extract the key for each element. */ distinct(): EntityQuery<T>; distinct<TResult>(selector: string | ((entity: T) => TResult)): EntityQuery<TResult>; distinct(selector: string | ((entity: T) => any)): EntityQuery<any>; /** Reverse the collection. */ reverse(): EntityQuery<T>; /** * Selects given collection property for each element and returns all in a new array. * @param properties Properties or PropertyPaths to select (project). */ selectMany<TResult>(selector: string | ((entity: T) => Array<TResult>)): EntityQuery<TResult>; selectMany(selector: string | ((entity: T) => any)): EntityQuery<any>; /** * Gets all the items after first succesful predicate. * @param predicate A function to test each element for a condition (can be string expression). * @param varContext Variable context for the expression. */ skipWhile(predicate: string | ((entity: T) => boolean), varContext?: any): EntityQuery<T>; /** * Gets all the items before first succesful predicate. * @param predicate A function to test each element for a condition (can be string expression). * @param varContext Variable context for the expression. */ takeWhile(predicate: string | ((entity: T) => boolean), varContext?: any): EntityQuery<T>; /** * If all items suits given predication returns true, otherwise false. * @param predicate A function to test each element for a condition (can be string expression). * @param varContext Variable context for the expression. */ all(predicate?: string | ((entity: T) => boolean), varContext?: any): interfaces.ClosedQueryable<boolean, ManagerQueryOptions>; /** * If there is at least one item in query result (or any item suits given predication) returns true, otherwise false. * @param predicate A function to test each element for a condition (can be string expression). * @param varContext Variable context for the expression. */ any(predicate?: string | ((entity: T) => boolean), varContext?: any): interfaces.ClosedQueryable<boolean, ManagerQueryOptions>; /** * Calculates average of items of query (or from given projection result). * @param selector Property path to use on calculation. */ avg(selector?: string | ((entity: T) => number)): interfaces.ClosedQueryable<number, ManagerQueryOptions>; /** * Finds maximum value from items of query (or from given projection result). * @param selector Property path to use on calculation. */ max(selector?: string | ((entity: T) => number)): interfaces.ClosedQueryable<number, ManagerQueryOptions>; /** * Finds minimum value from items of query (or from given projection result). * @param selector Property path to use on calculation. */ min(selector?: string | ((entity: T) => number)): interfaces.ClosedQueryable<number, ManagerQueryOptions>; /** * Finds summary value from items of query (or from given projection result). * @param selector Property path to use on calculation. */ sum(selector?: string | ((entity: T) => number)): interfaces.ClosedQueryable<number, ManagerQueryOptions>; /** * Gets the count of items of query. * @param predicate A function to test each element for a condition (can be string expression). * @param varContext Variable context for the expression. */ count(predicate?: string | ((entity: T) => boolean), varContext?: any): interfaces.ClosedQueryable<number, ManagerQueryOptions>; /** * Gets the first value from items of query (or from given predication result). When there is no item, throws exception. * @param predicate A function to test each element for a condition (can be string expression). * @param varContext Variable context for the expression. */ first(predicate?: string | ((entity: T) => boolean), varContext?: any): interfaces.ClosedQueryable<T, ManagerQueryOptions>; /** * Gets the first value (or null when there is no items) from items of query (or from given predication result). * @param predicate A function to test each element for a condition (can be string expression). * @param varContext Variable context for the expression. */ firstOrDefault(predicate?: string | ((entity: T) => boolean), varContext?: any): interfaces.ClosedQueryable<T, ManagerQueryOptions>; /** * Gets the single value from items (or from given predication result). Where zero or more than one item exists throws exception. * @param predicate A function to test each element for a condition (can be string expression). * @param varContext Variable context for the expression. */ single(predicate?: string | ((entity: T) => boolean), varContext?: any): interfaces.ClosedQueryable<T, ManagerQueryOptions>; /** * Gets the single value (or null when there is no items) from items (or from given predication result). Where more than one item exists throws exception. * @param predicate A function to test each element for a condition (can be string expression). * @param varContext Variable context for the expression. */ singleOrDefault(predicate?: string | ((entity: T) => boolean), varContext?: any): interfaces.ClosedQueryable<T, ManagerQueryOptions>; /** * Gets the last value from items of query (or from given predication result). When there is no item, throws exception. * @param predicate A function to test each element for a condition (can be string expression). * @param varContext Variable context for the expression. */ last(predicate?: string | ((entity: T) => boolean), varContext?: any): interfaces.ClosedQueryable<T, ManagerQueryOptions>; /** * Gets the last value (or null when there is no items) from items of query (or from given predication result). * @param predicate A function to test each element for a condition (can be string expression). * @param varContext Variable context for the expression. */ lastOrDefault(predicate?: string | ((entity: T) => boolean), varContext?: any): interfaces.ClosedQueryable<T, ManagerQueryOptions>; /** Executes this query using related entity manager. */ execute(options?: ManagerQueryOptions, successCallback?: (result: interfaces.QueryResultArray<T>) => void, errorCallback?: (e: AjaxError) => void): AjaxCall<interfaces.QueryResultArray<T>>; execute<TResult>(options?: ManagerQueryOptions, successCallback?: (result: TResult) => void, errorCallback?: (e: AjaxError) => void): AjaxCall<TResult[]>; /** Executes this query using related entity manager. */ x(options?: ManagerQueryOptions, successCallback?: (result: interfaces.QueryResultArray<T>) => void, errorCallback?: (e: AjaxError) => void): AjaxCall<interfaces.QueryResultArray<T>>; x<TResult>(options?: ManagerQueryOptions, successCallback?: (result: TResult) => void, errorCallback?: (e: AjaxError) => void): AjaxCall<TResult[]>; /** Executes this query using related entity manager. Shortcut for 'execute(...).then'. */ then(callback: (result: interfaces.QueryResultArray<T>) => void, errorCallback?: (e: AjaxError) => void, options?: ManagerQueryOptions): AjaxCall<interfaces.QueryResultArray<T>>; /** * Specifies the related objects to include in the query results. * @param propertyPath The dot-separated list of related objects to return in the query results. */ include(propertyPath: string): EntityQuery<T>; /** @see include */ expand(propertyPath: string): EntityQuery<T>; /** Sets given name-value pair as parameter. Parameters will be passed to server method. */ setParameter(name: string, value: any): EntityQuery<T>; /** Adds properties of given value to the body of the request. */ setBodyParameter(value: any): EntityQuery<T>; /** Sets options to be used at execution. */ withOptions(options: ManagerQueryOptions): EntityQuery<T>; /** Set merge option to NoTracking */ asNoTracking(): EntityQuery<T>; /** Set merge option to NoTrackingRaw */ asNoTrackingRaw(): EntityQuery<T>; } } /** Core types. */ namespace core { /** This class wraps given value to allow skipping callbacks. */ class ValueNotifyWrapper { constructor(value: any); value: any; } /** Beetle event class. */ class Event<T> { /** * @constructor * @param name Name of the event. * @param publisher Event's owner. */ constructor(name: string, publisher: any); name: string; toString(): string; /** * Adds given function to subscribe list. Will be notified when this event triggered. * @param subscriber Subscriber function. */ subscribe(subscriber: (args: T) => void); /** * Removes given function from subscriber list. * @param subscriber Subscriber function. */ unsubscribe(subscriber: (args: T) => void); } /** Beetle supported data types. */ namespace dataTypes { var object: interfaces.DataTypeBase; var array: interfaces.DataTypeBase; var func: interfaces.DataTypeBase; var string: interfaces.DataTypeBase; var guid: interfaces.DataTypeBase; var date: interfaces.DataTypeBase; var dateTimeOffset: interfaces.DataTypeBase; var time: interfaces.DataTypeBase; var boolean: interfaces.DataTypeBase; var int: interfaces.DataTypeBase; var number: interfaces.DataTypeBase; var byte: interfaces.DataTypeBase; var binary: interfaces.DataTypeBase; var enumeration: interfaces.DataTypeBase; // enum var geometry: interfaces.DataTypeBase; var geography: interfaces.DataTypeBase; } /** Entity container holds entity sets. */ class EntityContainer { constructor(); toString(): string; /** Adds given entity to each entity set in the inheritance hierarchy. */ push(entity: IEntity); /** Removes given entity from each entity set in the inheritance hierarchy. */ remove(entity: IEntity); /** Gets cached entity list. */ getEntities(): IEntity[]; /** Finds entity with given key by searching entity type's entity set. */ getEntityByKey(key: string, type: interfaces.EntityType): IEntity; /** Gets entities which has given foreign key for given navigation property by searching navigation's entity type's set. */ getRelations(entity: IEntity, navProperty: interfaces.NavigationProperty): IEntity[]; /** After an entity's key changed we need to rebuild the index tables for each entity set in the inheritance hiearachy. */ relocateKey(entity: IEntity, oldKey: string, newKey: string); /** Gets all changed entities from cache (Modified, Added, Deleted). */ getChanges(): IEntity[]; /** Returns cached entity count. */ count(): number; /** Finds entity set for given type in the cache. */ findEntitySet(type: interfaces.EntityType): EntitySet<IEntity>; /** Search entity set for given type in the cache, creates if there isn't any. */ getEntitySet(type: interfaces.EntityType): EntitySet<IEntity>; } /** Entity set works like a repository. */ class EntitySet<T extends IEntity> extends querying.EntityQuery<T> { constructor(type: interfaces.EntityType, manager: EntityManager); local: interfaces.InternalSet<T>; toString(): string; /** Creates a new entity with Added state. */ create(initialValues?: Object): T; /** Creates a new detached entity. */ createDetached(): T; /** Creates a new raw detached entity. */ createRaw(): interfaces.RawEntity; /** Adds the given entity to the manager in the Added state. */ add(T); /** Attaches the given entity to the manager in the Unchanged state. */ attach(T); /** Marks the given entity as Deleted. */ remove(T); } /** Entity manager class. All operations must be made using manager to be properly tracked. */ class EntityManager { constructor(url: string, loadMetadata?: boolean, options?: ManagerOptions); constructor(url: string, metadataManager: metadata.MetadataManager, options?: ManagerOptions); constructor(url: string, metadata: string, options?: ManagerOptions); constructor(url: string, metadata: Object, options?: ManagerOptions); constructor(service: baseTypes.DataServiceBase, options?: ManagerOptions); /** Data service for the manager. */ dataService: baseTypes.DataServiceBase; /** Cached entities are kept in this container. */ entities: EntityContainer; /** Beetle tracks entity states and keeps the change count up to date. */ pendingChangeCount: number; /** Beetle tracks entity valid states and keeps the validation errors up to date. */ validationErrors: interfaces.ValidationError[]; /** Notify when a valid state changed for an entity. */ validationErrorsChanged: Event<interfaces.ValidationErrorsChangedEventArgs>; /** Notify when a state changed for an entity. */ entityStateChanged: Event<interfaces.EntityStateChangedEventArgs>; /** Notify when an entity state is changed or there is no more changed entity. */ hasChangesChanged: Event<interfaces.HasChangesChangedEventArgs>; /** Notify before a query is executed. */ queryExecuting: Event<interfaces.QueryExecutingEventArgs>; /** Notify after a query executed. */ queryExecuted: Event<interfaces.QueryExecutedEventArgs>; /** Notify before manager saves changes. */ saving: Event<interfaces.SaveEventArgs>; /** Notify after manager saves changes. */ saved: Event<interfaces.SaveEventArgs>; /** Automatically fix scalar navigations using foreign keys (fast). */ autoFixScalar: boolean; /** Automatically fix plural navigations looking for foreign references (slow). */ autoFixPlural: boolean; /** Every merged entity will be validated. */ validateOnMerge: boolean; /** Validates entities before save. */ validateOnSave: boolean; /** Every change triggers a re-validation. Effects can be seen on EntityManager's validationErrors property. */ liveValidate: boolean; /** When true, all values will be handled by their value (i.e. some type changes, string->Date). */ handleUnmappedProperties: boolean; /** When true, entities will be updated -even there is no modified property. */ forceUpdate: boolean; /** Use async for ajax operation. Default is true. Be careful, some AjaxProviders does not support sync. */ workAsync: boolean; /** When true, while creating save package; for modified only changed and key properties, for deleted only key properties will be used. */ minimizePackage: boolean; toString(): string; /** Checks if manager is ready. */ isReady(): boolean; /** Subscribe ready callback, returns promise when available. */ ready(callback: () => void): AjaxCall<any>; /** Gets entity type by its short name from data service. */ getEntityType(shortName: string): interfaces.EntityType; /** Gets entity type by its short name from data service. */ getEntityType<T extends IEntity>(constructor: string | (new (...args: any[]) => T)): interfaces.EntityType; /** * Creates a query for a resource. Every data service can have their own query types. * @param resourceName Server resource name to combine with base uri. * @param shortName Entity type's short name. */ createQuery<T>(resourceName: string, shortName?: string): querying.EntityQuery<T>; /** * Creates a query for a resource. Every data service can have their own query types. * @param resourceName Server resource name to combine with base uri. * @param type Type constructor. Beetle can get the name from this function. */ createQuery<T extends IEntity>(resourceName: string, type?: string | (new (...args: any[]) => T)): querying.EntityQuery<T>; /** * Creates a query for a resource. Every data service can have their own query types. * @param resourceName Server resource name to combine with base uri. * @param shortName Entity type's short name. */ createQuery(resourceName: string, shortName?: string): querying.EntityQuery<any>; /** * Creates a query for a resource. Every data service can have their own query types. * @param type Type constructor. Beetle can get the name from this function. * @param resourceName Server resource name to combine with base uri. */ createEntityQuery<T extends IEntity>(type: string | (new (...args: any[]) => T), resourceName?: string): querying.EntityQuery<T>; /** * Creates a query for a resource. Every data service can have their own query types. * @param shortName Entity type's short name. * @param resourceName Server resource name to combine with base uri. */ createEntityQuery(shortName: string, resourceName?: string): querying.EntityQuery<IEntity>; /** * Register constructor and initializer (optional) for the type. * @param constructor Constructor function. Called right after the entity object is generated. * @param initializer Initializer function. Called after entity started to being tracked (properties converted to observable). */ registerCtor<T extends IEntity>(type: string | (new (...args: any[]) => T), ctor?: (rawEntity: interfaces.RawEntity) => void, initializer?: (entity: T) => void); /** Creates an entity for the type and starts tracking by adding to cache with 'Added' state. */ createEntity<T extends IEntity>(type: string | (new (...args: any[]) => T), initialValues?: Object): T; createEntity(shortName: string, initialValues?: Object): IEntity; /** Creates an entity based on metadata information but doesn't attach to manager. */ createDetachedEntity<T extends IEntity>(type: string | (new (...args: any[]) => T), initialValues?: Object): T; createDetachedEntity(shortName: string, initialValues?: Object): IEntity; /** Creates a raw entity for this type. */ createRawEntity(shortName: string, initialValues?: Object): interfaces.RawEntity; createRawEntity<T extends IEntity>(type: string | (new (...args: any[]) => T), initialValues?: Object): interfaces.RawEntity; /* When there is no metadata available services may be able to create entities asynchronously (server side must be able to support this). */ createEntityAsync<T extends IEntity>(type: string | (new (...args: any[]) => T), initialValues?: Object, options?: ManagerQueryOptions, successCallback?: (entity: T) => void, errorCallback?: (e: AjaxError) => void): AjaxCall<T>; createEntityAsync(typeName: string, initialValues?: Object, options?: ManagerQueryOptions, successCallback?: (entity: IEntity) => void, errorCallback?: (e: AjaxError) => void): AjaxCall<IEntity>; /** Creates an entity asynchronously but doesn't attach to manager. */ createDetachedEntityAsync<T extends IEntity>(type: string | (new (...args: any[]) => T), initialValues?: Object, options?: ManagerQueryOptions, successCallback?: (entity: T) => void, errorCallback?: (e: AjaxError) => void): AjaxCall<T>; createDetachedEntityAsync(typeName: string, initialValues?: Object, options?: ManagerQueryOptions, successCallback?: (entity: IEntity) => void, errorCallback?: (e: AjaxError) => void): AjaxCall<IEntity>; /** Creates an entity asynchronously without converting it to observable. */ createRawEntityAsync<T extends IEntity>(type: string | (new (...args: any[]) => T), initialValues?: Object, options?: ManagerQueryOptions, successCallback?: (rawEntity: interfaces.RawEntity) => void, errorCallback?: (e: AjaxError) => void): AjaxCall<interfaces.RawEntity>; createRawEntityAsync(typeName: string, initialValues?: Object, options?: ManagerQueryOptions, successCallback?: (rawEntity: interfaces.RawEntity) => void, errorCallback?: (e: AjaxError) => void): AjaxCall<interfaces.RawEntity>; /** Executes the provided query with rules provided by the options. */ executeQuery<T>(query: querying.EntityQuery<T>, options?: ManagerQueryOptions, successCallback?: (result: T[]) => void, errorCallback?: (e: AjaxError) => void): AjaxCall<T[]>; executeQuery<T>(query: interfaces.ClosedQueryable<T, ManagerQueryOptions>, options?: ManagerQueryOptions, successCallback?: (result: T) => void, errorCallback?: (e: AjaxError) => void): AjaxCall<T>; executeQuery(query: querying.EntityQuery<any>, options?: ManagerQueryOptions, successCallback?: (result: any) => void, errorCallback?: (e: AjaxError) => void): AjaxCall<any>; executeQuery(query: interfaces.ClosedQueryable<any, ManagerQueryOptions>, options?: ManagerQueryOptions, successCallback?: (result: any) => void, errorCallback?: (e: AjaxError) => void): AjaxCall<any>; executeQueryLocally<T>(query: querying.EntityQuery<T>, varContext?: any): T[]; executeQueryLocally<T>(query: interfaces.ClosedQueryable<T, any>, varContext?: any): T; /* Finds entity with given key by searching entity type's entity set. */ getEntityByKey<T extends IEntity>(key: any, type: string | interfaces.EntityType | (new (...args: any[]) => T)): T; /** Marks entity as deleted and clear all navigations. */ deleteEntity(entity: IEntity); /* Adds given entity to manager's entity container. State will be 'Added'. */ addEntity(entity: IEntity | IEntity[], options?: EntityOptions); /* Attaches given entity to manager's entity container. State will be 'Unchanged'. */ attachEntity(entity: IEntity | IEntity[], options?: EntityOptions); /** Detaches entity from manager and stops tracking. */ detachEntity(entity: IEntity | IEntity[], includeRelations?: boolean); /* Reject all changes made to this entity to initial values and detach from context if its newly added. */ rejectChanges(entity: IEntity | IEntity[], includeRelations?: boolean); /* Resets all changes to last accepted values. */ undoChanges(entity: IEntity | IEntity[], includeRelations?: boolean); /* Accept all changes made to this entity (clear changed values). */ acceptChanges(entity: IEntity | IEntity[], includeRelations?: boolean); /* Creates save package with entity raw values and user data. */ createSavePackage(entities?: IEntity[], options?: PackageOptions): interfaces.SavePackage; /* Exports entities from manager to raw list. */ exportEntities(entities?: IEntity[], options?: ExportOptions): interfaces.ExportEntity[]; /* Imports exported entities and starts tracking them. */ importEntities(exportedEntities: interfaces.ExportEntity[], merge?: enums.mergeStrategy); /** Check if there is any pending changes. */ hasChanges(): boolean; /* Gets changes made in this manager's cache. */ getChanges(): IEntity[]; /** * Saves all changes made in this manager to server via Data Service instance. * @param options Options to modify saving behaviour. * @successCallback {successCallback} - Function to call after operation succeeded. * @errorCallback {errorCallback} - Function to call when operation fails. * @returns {Promise} Returns promise if supported. */ saveChanges(options?: ManagerSaveOptions, successCallback?: (result: interfaces.SaveResult) => void, errorCallback?: (e: AjaxError) => void): AjaxCall<interfaces.SaveResult>; savePackage(savePackage: interfaces.SavePackage, options?: PackageSaveOptions, successCallback?: (result: interfaces.SaveResult) => void, errorCallback?: (e: AjaxError) => void): AjaxCall<interfaces.SaveResult>; /* Creates an entity based on metadata information. */ toEntity<T extends IEntity>(object: interfaces.RawEntity): T; toEntity(object: interfaces.RawEntity): IEntity; /** Fix scalar and plural navigations for entity from cache. */ fixNavigations(entity: IEntity); /** Checks if given entity is being tracked by this manager. */ isInManager(entity: IEntity): boolean; /** * Flat relation to a single array. With this we can merge entities with complex navigations. * @example * Lets say we have an Order with 3 OrderDetails and that OrderDetails have Supplier assigned, * with flatting this entity, we can merge Order, OrderDetails and Suppliers with one call. * @param entities Entities to flat. * @returns All entities from all relations. */ flatEntities(entities: IEntity[]): IEntity[]; /* Returns tracking info for given entity. */ entry(entity: IEntity): interfaces.Tracker; /* Creates entity set for given type. */ createSet<T extends IEntity>(type: string | interfaces.EntityType | (new (...args: any[]) => T)): EntitySet<T>; createSet(type: interfaces.EntityType): EntitySet<IEntity>; /* Finds entity set for given type name. */ set<T extends IEntity>(constructor: string | (new (...args: any[]) => T)): EntitySet<T>; set(shortName: string): EntitySet<IEntity>; /** Clears local cache, validation errors and resets change counter to 0.*/ clear(); } /** Base entity class. */ class EntityBase implements IEntity { constructor(type: interfaces.EntityType, manager?: EntityManager, initialValues?: Object); $tracker: interfaces.Tracker; /** Extra information about query (when enabled). */ $extra: interfaces.QueryResultExtra; } } /* Data service implementations like ODataService, BeetleService etc.. */ namespace services { /* Beetle Service class. */ class BeetleService extends baseTypes.DataServiceBase { constructor(url: string, loadMetadata?: boolean, options?: ServiceOptions); constructor(url: string, metadata: metadata.MetadataManager | Object | string, options?: ServiceOptions); /** * Executes given query parameters. * @param resource Server resource to query. * @param parameters The query string parameters. * @param bodyParameter The query body parameter. * @param queryParams The query beetle parameters. * @param options Query options. * @param successCallback Function to call after operation succeeded. * @param errorCallback Function to call when operation fails. */ executeQueryParams(resource: string, parameters: { name: string, value: string }[], bodyParameter: any, queryParams: any, options: ServiceQueryOptions, successCallback: (result: interfaces.SaveResult) => void, errorCallback: (e: AjaxError) => void); /* Fix the relations (like $ref links for circular references) between loaded raw data. */ fixResults(results: any[], makeObservable?: boolean, handleUnmappedProperties?: boolean): interfaces.RawEntity[]; } /* OData Service class. */ class ODataService extends BeetleService { } } /* Beetle enums. */ namespace enums { /** * Entity states. * Possible values: Detached, Unchanged, Added, Deleted, Modified */ enum entityStates { Detached, Unchanged, Added, Deleted, Modified } /** * Merge strategies. Can be passed to execute query method of entity manager. * Possible values: * Preserve: Cached entities are preserved and will be returned as query result (when entity with same key found). * Overwrite: Cached entity values will be overwritten and cached entity will be returned as query result (when entity with same key found). * ThrowError: Error will be thrown (when entity with same key found). * NoTracking: Query result will not be merged into the cache. * NoTrackingRaw: Query results will not be merged into the cache and will not be converted to entities (raw objects will be returned). */ enum mergeStrategy { Preserve, Overwrite, ThrowError, NoTracking, NoTrackingRaw } /** * Query execution strategies. Can be passed to execute query method of entity manager. * Possible values: * Server: Get entities only from server. * Local: Get entities only from local cache. * Both: Get entities from local cache then from server and then mix them up. * LocalIfEmptyServer: Get entities from local cache if no result is found get them from server. */ enum executionStrategy { Server, Local, Both, LocalIfEmptyServer } /** * Property value auto generation type. * Possible values: * Identity: Auto-Increment identity column. * Server: Calculated column. */ enum generationPattern { Identity, Computed } /** * What to do when user sets an observable array's value with a new array. * Possible values: * NotAllowed: An exception will be thrown. * Replace: Old items will be replaced with next array items. * Append: New array items will be appended to existing array. */ enum arraySetBehaviour { NotAllowed, Replace, Append } /** * Supported service types. * Possible values: OData, Beetle */ enum serviceTypes { OData, Beetle } } /* Manager independent static events. */ namespace events { /** Notifies before a query is being executed. You can modify query and options from the args. */ var queryExecuting: core.Event<interfaces.QueryExecutingEventArgs>; /** Notifies after a query is executed. You can modify result from the args. */ var queryExecuted: core.Event<interfaces.QueryExecutedEventArgs>; /** Notifies before save call started. You can modify options from the args. */ var saving: core.Event<interfaces.SaveEventArgs>; /** Notifies after save call completed. */ var saved: core.Event<interfaces.SaveEventArgs>; /** Notifies when a information level event is occurred. */ var info: core.Event<interfaces.MessageEventArgs>; /** Notifies when a warning level event is occurred. */ var warning: core.Event<interfaces.MessageEventArgs>; /** Notifies when a error level event is occurred. */ var error: core.Event<Error>; } /** Beetle settings. */ namespace settings { /** Automatically fix scalar navigations using foreign keys (fast). */ var autoFixScalar: boolean; /** Automatically fix plural navigations looking for foreign references (slow). */ var autoFixPlural: boolean; /** Every merged entity will be validated. */ var validateOnMerge: boolean; /** Validates entities before save. */ var validateOnSave: boolean; /** Every change triggers a re-validation. Effects can be seen on EntityManager's validationErrors property. */ var liveValidate: boolean; /** When true, all values will be handled by their value (i.e. some type changes, string->Date). */ var handleUnmappedProperties: boolean; /** for local queries use case sensitive string comparisons. */ var isCaseSensitive: boolean; /** for local queries trim values before string comparisons. */ var ignoreWhiteSpaces: boolean; /** when true, each entity will be updated -even there is no modified property. */ var forceUpdate: boolean; /** when true, loaded meta-data will be cached for url. */ var cacheMetadata: boolean; /** when true, metadata entities will be registered as classes to manager (tracked entity) and global scope (detached entity). Also, enums will be registered to global scope. */ var registerMetadataTypes: boolean; /** * when not equals to false all Ajax calls will be made asynchronously, * when false createEntityAsync, executeQuery, saveChanges will returns results immediately (when supported). */ var workAsync: boolean; /** default timeout for AJAX calls. this value is used when not given with options argument. */ var ajaxTimeout: number; /** * when true, while creating save package, for modified only changed and key properties, for deleted only key properties will be used. * entities will be created with only sent properties filled, other properties will have default values, please use carefully. */ var minimizePackage: boolean; /** when true, objects will be tracked even when there is no metadata for their types. */ var trackUnknownTypes: boolean; /** when true, throws error when a not nullable property set with null. */ var checkNulls: boolean; /* Gets default observable provider instance. */ function getObservableProvider(): baseTypes.ObservableProviderBase; /* Sets default observable provider instance. Will be used when another instance is not injected. */ function setObservableProvider(value: baseTypes.ObservableProviderBase); /* Gets default promise provider instance. */ function getPromiseProvider(): baseTypes.PromiseProviderBase; /* Sets default promise provider instance. Will be used when another instance is not injected. */ function setPromiseProvider(value: baseTypes.PromiseProviderBase); /* Gets default ajax provider instance. */ function getAjaxProvider(): baseTypes.AjaxProviderBase; /* Sets default ajax provider instance. Will be used when another instance is not injected. */ function setAjaxProvider(value: baseTypes.AjaxProviderBase); /* Gets default serialization service instance. */ function getSerializationService(): baseTypes.SerializationServiceBase; /* Sets default serialization service instance. Will be used when another instance is not injected. */ function setSerializationService(value: baseTypes.SerializationServiceBase); /* Gets array set behaviour. */ function getArraySetBehaviour(): enums.arraySetBehaviour; /* Sets array set behaviour. */ function setArraySetBehaviour(value: enums.arraySetBehaviour | string); /* Gets default service type. */ function getDefaultServiceType(): enums.serviceTypes; /* Sets default service type. Will be used when another instance is not injected. */ function setDefaultServiceType(value: enums.serviceTypes | string); /* Gets date converter. */ function getDateConverter(): baseTypes.DateConverterBase; /* Sets date converter. */ function setDateConverter(value: baseTypes.DateConverterBase); /* Gets the localization function. */ function getLocalizeFunction(): (name: string) => string; /* Sets the localization function. */ function setLocalizeFunction(func: (name: string) => string); } function registerI18N(code: string, i18n: interfaces.I18N, active?: boolean); function setI18N(code: string); /** Metadata container. Shortcut for metadata.MetadataManager. */ class MetadataManager extends metadata.MetadataManager { } /** Entity manager class. All operations must be made using manager to be properly tracked. Shortcut for core.EntityManager. */ class EntityManager extends core.EntityManager { } /** Base entity class. Shortcut for core.EntityBase. */ class EntityBase extends core.EntityBase { } /** Entity set works like a repository. */ class EntitySet<T extends IEntity> extends core.EntitySet<T> { } /* OData Service class. Shortcut for services.ODataService. */ class ODataService extends services.ODataService { } /* Beetle Service class. Shortcut for services.BeetleService. */ class BeetleService extends services.BeetleService { } /** Beetle event class. Shortcut for core.Event<T>. */ class Event<T> extends core.Event<T> { } /** This class wraps given value to allow skipping callbacks. Shortcut for core.ValueNotifyWrapper. */ class ValueNotifyWrapper extends core.ValueNotifyWrapper { } /** Beetle converts plural navigation properties to TrackableArrays to track changes on collections. Shortcut for interfaces.TrackableArray<T>. */ interface TrackableArray<T> extends interfaces.TrackableArray<T> { } /** Beetle client version. */ const version: string; } /** Add missing query functions */ declare global { /** Extend Array objects. */ interface Array<T> { /** Register 'asQueryable' method to Array objects. */ asQueryable(): beetle.querying.ArrayQuery<T>; /** Register 'q' method to Array objects. Shortcut for 'asQueryable'. */ q(): beetle.querying.ArrayQuery<T>; } /** Extend string objects. */ interface String { /** Check if given string is substring of this string. */ substringOf(other: string): boolean; /** Check if this string starts with given string. */ startsWith(other: string): boolean; /** Check if this string ends with given string. */ endsWith(other: string): boolean; } /** Extend number objects. */ interface Number { /** Returns the nearest integral value to this value. */ round(): number; /** Returns the smallest integral value that is greater than or equal to this value. */ ceiling(): number; /** Returns the biggest integral value that is less than or equal to this value. */ floor(): number; } } /** Export all beetle module. */ export = beetle; /** Also export as namespace to support UMD. */ export as namespace beetle;
the_stack
import fs from 'fs'; import mkdirp from 'mkdirp'; import glob from 'globby'; import path from 'path'; import ts from 'typescript'; import yn from 'yn'; import { eggInfoPath, tmpDir } from './config'; import { execSync, exec, ExecOptions } from 'child_process'; import JSON5 from 'json5'; export const JS_CONFIG = { include: [ '**/*' ], }; export const TS_CONFIG: Partial<TsConfigJson> = { compilerOptions: { target: ts.ScriptTarget.ES2017, module: ts.ModuleKind.CommonJS, strict: true, noImplicitAny: false, experimentalDecorators: true, emitDecoratorMetadata: true, allowSyntheticDefaultImports: true, charset: 'utf8', allowJs: false, pretty: true, lib: [ 'es6' ], noEmitOnError: false, noUnusedLocals: true, noUnusedParameters: true, allowUnreachableCode: false, allowUnusedLabels: false, strictPropertyInitialization: false, noFallthroughCasesInSwitch: true, skipLibCheck: true, skipDefaultLibCheck: true, inlineSourceMap: true, }, }; export interface TsConfigJson { extends: string; compilerOptions: ts.CompilerOptions; } export interface GetEggInfoOpt { cwd: string; cacheIndex?: string; customLoader?: any; async?: boolean; env?: PlainObject<string>; callback?: (result: EggInfoResult) => any; } export interface EggPluginInfo { from: string; enable: boolean; package?: string; path: string; etsConfig?: PlainObject; } export interface EggInfoResult { eggPaths?: string[]; plugins?: PlainObject<EggPluginInfo>; config?: PlainObject; timing?: number; } const cacheEggInfo = {}; export function getEggInfo<T extends 'async' | 'sync' = 'sync'>(option: GetEggInfoOpt): T extends 'async' ? Promise<EggInfoResult> : EggInfoResult { const { cacheIndex, cwd, customLoader } = option; const cacheKey = cacheIndex ? `${cacheIndex}${cwd}` : undefined; const caches = cacheKey ? (cacheEggInfo[cacheKey] = cacheEggInfo[cacheKey] || {}) : undefined; const end = (json: EggInfoResult) => { if (caches) { caches.eggInfo = json; caches.cacheTime = Date.now(); } if (option.callback) { return option.callback(json); } return json; }; // check cache if (caches) { if (caches.cacheTime && (Date.now() - caches.cacheTime) < 1000) { return end(caches.eggInfo); } else if (caches.runningPromise) { return caches.runningPromise; } } // get egg info from customLoader if (customLoader) { return end({ config: customLoader.config, plugins: customLoader.plugins, eggPaths: customLoader.eggPaths, }); } // prepare options const cmd = `node ${path.resolve(__dirname, './scripts/eggInfo')}`; const opt: ExecOptions = { cwd, env: { ...process.env, TS_NODE_TYPE_CHECK: 'false', TS_NODE_TRANSPILE_ONLY: 'true', TS_NODE_FILES: 'false', EGG_TYPESCRIPT: 'true', CACHE_REQUIRE_PATHS_FILE: path.resolve(tmpDir, './requirePaths.json'), ...option.env, }, }; if (option.async) { // cache promise caches.runningPromise = new Promise((resolve, reject) => { exec(cmd, opt, err => { caches.runningPromise = null; if (err) reject(err); resolve(end(parseJson(fs.readFileSync(eggInfoPath, 'utf-8')))); }); }); return caches.runningPromise; } try { execSync(cmd, opt); return end(parseJson(fs.readFileSync(eggInfoPath, 'utf-8'))); } catch (e) { return end({}); } } // convert string to same type with default value export function convertString<T>(val: string | undefined, defaultVal: T): T { if (val === undefined) return defaultVal; switch (typeof defaultVal) { case 'boolean': return yn(val, { default: defaultVal }) as any; case 'number': const num = +val; return (isNaN(num) ? defaultVal : num) as any; case 'string': return val as any; default: return defaultVal; } } export function isIdentifierName(s: string) { return /^[$A-Z_][0-9A-Z_$]*$/i.test(s); } // load ts/js files export function loadFiles(cwd: string, pattern?: string | string[]) { pattern = pattern || '**/*.(js|ts)'; pattern = Array.isArray(pattern) ? pattern : [ pattern ]; const fileList = glob.sync(pattern.concat([ '!**/*.d.ts' ]), { cwd }); return fileList.filter(f => { // filter same name js/ts return !( f.endsWith('.js') && fileList.includes(f.substring(0, f.length - 2) + 'ts') ); }); } // write jsconfig.json to cwd export function writeJsConfig(cwd: string) { const jsconfigUrl = path.resolve(cwd, './jsconfig.json'); if (!fs.existsSync(jsconfigUrl)) { fs.writeFileSync(jsconfigUrl, JSON.stringify(JS_CONFIG, null, 2)); return jsconfigUrl; } } // write tsconfig.json to cwd export function writeTsConfig(cwd: string) { const tsconfigUrl = path.resolve(cwd, './tsconfig.json'); if (!fs.existsSync(tsconfigUrl)) { fs.writeFileSync(tsconfigUrl, JSON.stringify(TS_CONFIG, null, 2)); return tsconfigUrl; } } export function checkMaybeIsTsProj(cwd: string, pkgInfo?: any) { pkgInfo = pkgInfo || getPkgInfo(cwd); return (pkgInfo.egg && pkgInfo.egg.typescript) || fs.existsSync(path.resolve(cwd, './tsconfig.json')) || fs.existsSync(path.resolve(cwd, './config/config.default.ts')) || fs.existsSync(path.resolve(cwd, './config/config.ts')); } export function checkMaybeIsJsProj(cwd: string, pkgInfo?: any) { pkgInfo = pkgInfo || getPkgInfo(cwd); const isJs = !checkMaybeIsTsProj(cwd, pkgInfo) && ( fs.existsSync(path.resolve(cwd, './config/config.default.js')) || fs.existsSync(path.resolve(cwd, './jsconfig.json')) ); return isJs; } // load modules to object export function loadModules<T = any>(cwd: string, loadDefault?: boolean, preHandle?: (...args) => any) { const modules: { [key: string]: T } = {}; preHandle = preHandle || (fn => fn); fs .readdirSync(cwd) .filter(f => f.endsWith('.js')) .forEach(f => { const name = f.substring(0, f.lastIndexOf('.')); const obj = require(path.resolve(cwd, name)); if (loadDefault && obj.default) { modules[name] = preHandle!(obj.default); } else { modules[name] = preHandle!(obj); } }); return modules; } // convert string to function export function strToFn(fn) { if (typeof fn === 'string') { return (...args: any[]) => fn.replace(/{{\s*(\d+)\s*}}/g, (_, index) => args[index]); } return fn; } // pick fields from object export function pickFields<T extends string = string>(obj: PlainObject, fields: T[]) { const newObj: PlainObject = {}; fields.forEach(f => (newObj[f] = obj[f])); return newObj; } // log export function log(msg: string, prefix = true) { console.info(`${prefix ? '[egg-ts-helper] ' : ''}${msg}`); } // get import context export function getImportStr( from: string, to: string, moduleName?: string, importStar?: boolean, ) { const extname = path.extname(to); const toPathWithoutExt = to.substring(0, to.length - extname.length); const importPath = path.relative(from, toPathWithoutExt).replace(/\/|\\/g, '/'); const isTS = extname === '.ts' || fs.existsSync(`${toPathWithoutExt}.d.ts`); const importStartStr = isTS && importStar ? '* as ' : ''; const fromStr = isTS ? `from '${importPath}'` : `= require('${importPath}')`; return `import ${importStartStr}${moduleName} ${fromStr};`; } // write file, using fs.writeFileSync to block io that d.ts can create before egg app started. export function writeFileSync(fileUrl, content) { mkdirp.sync(path.dirname(fileUrl)); fs.writeFileSync(fileUrl, content); } // clean same name js/ts export function cleanJs(cwd: string) { const fileList: string[] = []; glob .sync([ '**/*.ts', '**/*.tsx', '!**/*.d.ts', '!**/node_modules' ], { cwd }) .forEach(f => { const jf = removeSameNameJs(path.resolve(cwd, f)); if (jf) fileList.push(path.relative(cwd, jf)); }); if (fileList.length) { console.info('[egg-ts-helper] These file was deleted because the same name ts file was exist!\n'); console.info(' ' + fileList.join('\n ') + '\n'); } } // get moduleName by file path export function getModuleObjByPath(f: string) { const props = f.substring(0, f.lastIndexOf('.')).split('/'); // composing moduleName const moduleName = props.map(prop => camelProp(prop, 'upper')).join(''); return { props, moduleName, }; } // format path sep to / export function formatPath(str: string) { return str.replace(/\/|\\/g, '/'); } export function toArray(pattern?: string | string[]) { return pattern ? (Array.isArray(pattern) ? pattern : [ pattern ]) : []; } // remove same name js export function removeSameNameJs(f: string) { if (!f.match(/\.tsx?$/) || f.endsWith('.d.ts')) { return; } const jf = f.replace(/tsx?$/, 'js'); if (fs.existsSync(jf)) { fs.unlinkSync(jf); return jf; } } // resolve module export function resolveModule(url) { try { return require.resolve(url); } catch (e) { return undefined; } } // check whether module is exist export function moduleExist(mod: string, cwd?: string) { const nodeModulePath = path.resolve(cwd || process.cwd(), 'node_modules', mod); return fs.existsSync(nodeModulePath) || resolveModule(mod); } // require modules export function requireFile(url) { url = url && resolveModule(url); if (!url) { return undefined; } let exp = require(url); if (exp.__esModule && 'default' in exp) { exp = exp.default; } return exp; } // extend export function extend<T = any>(obj, ...args: Array<Partial<T>>): T { args.forEach(source => { let descriptor, prop; if (source) { for (prop in source) { descriptor = Object.getOwnPropertyDescriptor(source, prop); Object.defineProperty(obj, prop, descriptor); } } }); return obj; } // parse json export function parseJson(jsonStr: string) { if (jsonStr) { try { return JSON.parse(jsonStr); } catch (e) { return {}; } } else { return {}; } } // load package.json export function getPkgInfo(cwd: string) { return readJson(path.resolve(cwd, './package.json')); } // read json file export function readJson(jsonUrl: string) { if (!fs.existsSync(jsonUrl)) return {}; return parseJson(fs.readFileSync(jsonUrl, 'utf-8')); } export function readJson5(jsonUrl: string) { if (!fs.existsSync(jsonUrl)) return {}; return JSON5.parse(fs.readFileSync(jsonUrl, 'utf-8')); } // format property export function formatProp(prop: string) { return prop.replace(/[._-][a-z]/gi, s => s.substring(1).toUpperCase()); } // like egg-core/file-loader export function camelProp( property: string, caseStyle: string | ((...args: any[]) => string), ): string { if (typeof caseStyle === 'function') { return caseStyle(property); } // camel transfer property = formatProp(property); let first = property[ 0 ]; // istanbul ignore next switch (caseStyle) { case 'lower': first = first.toLowerCase(); break; case 'upper': first = first.toUpperCase(); break; case 'camel': break; default: break; } return first + property.substring(1); } // load tsconfig.json export function loadTsConfig(tsconfigPath: string): ts.CompilerOptions { tsconfigPath = path.extname(tsconfigPath) === '.json' ? tsconfigPath : `${tsconfigPath}.json`; const tsConfig = readJson5(tsconfigPath) as TsConfigJson; if (tsConfig.extends) { const extendTsConfig = loadTsConfig(path.resolve(path.dirname(tsconfigPath), tsConfig.extends)); return { ...tsConfig.compilerOptions, ...extendTsConfig, }; } return tsConfig.compilerOptions || {}; } /** * ts ast utils */ // find export node from sourcefile. export function findExportNode(code: string) { const sourceFile = ts.createSourceFile('file.ts', code, ts.ScriptTarget.ES2017, true); const cache: Map<ts.__String, ts.Node> = new Map(); const exportNodeList: ts.Node[] = []; let exportDefaultNode: ts.Node | undefined; sourceFile.statements.forEach(node => { // each node in root scope if (modifierHas(node, ts.SyntaxKind.ExportKeyword)) { if (modifierHas(node, ts.SyntaxKind.DefaultKeyword)) { // export default exportDefaultNode = node; } else { // export variable if (ts.isVariableStatement(node)) { node.declarationList.declarations.forEach(declare => exportNodeList.push(declare), ); } else { exportNodeList.push(node); } } } else if (ts.isVariableStatement(node)) { // cache variable statement for (const declaration of node.declarationList.declarations) { if (ts.isIdentifier(declaration.name) && declaration.initializer) { cache.set(declaration.name.escapedText, declaration.initializer); } } } else if ((ts.isFunctionDeclaration(node) || ts.isClassDeclaration(node)) && node.name) { // cache function declaration and class declaration cache.set(node.name.escapedText, node); } else if (ts.isExportAssignment(node)) { // export default {} exportDefaultNode = node.expression; } else if (ts.isExpressionStatement(node) && ts.isBinaryExpression(node.expression)) { if (ts.isPropertyAccessExpression(node.expression.left)) { const obj = node.expression.left.expression; const prop = node.expression.left.name; if (ts.isIdentifier(obj)) { if (obj.escapedText === 'exports') { // exports.xxx = {} exportNodeList.push(node.expression); } else if ( obj.escapedText === 'module' && ts.isIdentifier(prop) && prop.escapedText === 'exports' ) { // module.exports = {} exportDefaultNode = node.expression.right; } } } else if (ts.isIdentifier(node.expression.left)) { // let exportData; // exportData = {}; // export exportData cache.set(node.expression.left.escapedText, node.expression.right); } } }); while (exportDefaultNode && ts.isIdentifier(exportDefaultNode) && cache.size) { const mid = cache.get(exportDefaultNode.escapedText); cache.delete(exportDefaultNode.escapedText); exportDefaultNode = mid; } return { exportDefaultNode, exportNodeList, }; } // check kind in node.modifiers. export function modifierHas(node: ts.Node, kind) { return node.modifiers && node.modifiers.find(mod => kind === mod.kind); }
the_stack
import { Component, Element, Event, EventEmitter, h, Host, Listen, Method, Prop, State, VNode, Watch } from "@stencil/core"; import { guid } from "../../utils/guid"; import { getKey } from "../../utils/key"; import { ColorStop, DataSeries } from "../calcite-graph/interfaces"; import { intersects } from "../../utils/dom"; import { clamp } from "../../utils/math"; import { LabelableComponent, connectLabel, disconnectLabel } from "../../utils/label"; type ActiveSliderProperty = "minValue" | "maxValue" | "value" | "minMaxValue"; @Component({ tag: "calcite-slider", styleUrl: "calcite-slider.scss", shadow: true }) export class CalciteSlider implements LabelableComponent { //-------------------------------------------------------------------------- // // Element // //-------------------------------------------------------------------------- @Element() el: HTMLCalciteSliderElement; //-------------------------------------------------------------------------- // // Properties // //-------------------------------------------------------------------------- /** Disable and gray out the slider */ @Prop({ reflect: true }) disabled = false; /** Indicates if a histogram is present */ @Prop({ reflect: true, mutable: true }) hasHistogram = false; /** Display a histogram above the slider */ @Prop() histogram?: DataSeries; @Watch("histogram") histogramWatcher(newHistogram: DataSeries): void { this.hasHistogram = !!newHistogram; } /** * Array of values describing a single color stop, sorted by offset ascending. */ @Prop() histogramStops: ColorStop[]; /** Label handles with their numeric value */ @Prop({ reflect: true }) labelHandles = false; /** Label tick marks with their numeric value. */ @Prop({ reflect: true }) labelTicks = false; /** Maximum selectable value */ @Prop({ reflect: true }) max = 100; /** Used as an accessible label (aria-label) for second handle if needed (ex. "Temperature, upper bound") */ @Prop() maxLabel?: string; /** Currently selected upper number (if multi-select) */ @Prop({ mutable: true }) maxValue?: number; /** Minimum selectable value */ @Prop({ reflect: true }) min = 0; /** Used as an accessible label (aria-label) for first (or only) handle (ex. "Temperature, lower bound") */ @Prop() minLabel: string; /** Currently selected lower number (if multi-select) */ @Prop({ mutable: true }) minValue?: number; /** * When true, the slider will display values from high to low. * * Note that this value will be ignored if the slider has an associated histogram. */ @Prop({ reflect: true }) mirrored = false; /** Interval to move on page up/page down keys */ @Prop() pageStep?: number; /** Use finer point for handles */ @Prop() precise = false; /** When true, enables snap selection along the step interval */ @Prop() snap = false; /** Interval to move on up/down keys */ @Prop() step?: number = 1; /** Show tick marks on the number line at provided interval */ @Prop() ticks?: number; /** Currently selected number (if single select) */ @Prop({ reflect: true, mutable: true }) value: null | number = null; //-------------------------------------------------------------------------- // // Lifecycle // //-------------------------------------------------------------------------- connectedCallback(): void { connectLabel(this); } disconnectedCallback(): void { disconnectLabel(this); } componentWillLoad(): void { this.isRange = !!(this.maxValue || this.maxValue === 0); this.tickValues = this.generateTickValues(); this.value = this.clamp(this.value); if (this.snap) { this.value = this.getClosestStep(this.value); } if (this.histogram) { this.hasHistogram = true; } } componentDidRender(): void { if (this.labelHandles) { this.adjustHostObscuredHandleLabel("value"); if (this.isRange) { this.adjustHostObscuredHandleLabel("minValue"); if (!(this.precise && this.isRange && !this.hasHistogram)) { this.hyphenateCollidingRangeHandleLabels(); } } } this.hideObscuredBoundingTickLabels(); } render(): VNode { const id = this.el.id || this.guid; const min = this.minValue || this.min; const max = this.maxValue || this.value; const maxProp = this.isRange ? "maxValue" : "value"; const value = this[maxProp]; const useMinValue = this.shouldUseMinValue(); const minInterval = this.getUnitInterval(useMinValue ? this.minValue : min) * 100; const maxInterval = this.getUnitInterval(max) * 100; const mirror = this.shouldMirror(); const leftThumbOffset = `${mirror ? 100 - minInterval : minInterval}%`; const rightThumbOffset = `${mirror ? maxInterval : 100 - maxInterval}%`; const handle = ( <button aria-label={this.isRange ? this.maxLabel : this.minLabel} aria-orientation="horizontal" aria-valuemax={this.max} aria-valuemin={this.min} aria-valuenow={value} class={{ thumb: true, "thumb--value": true, "thumb--active": this.lastDragProp !== "minMaxValue" && this.dragProp === maxProp }} disabled={this.disabled} onBlur={() => (this.activeProp = null)} onFocus={() => (this.activeProp = maxProp)} onPointerDown={() => this.dragStart(maxProp)} ref={(el) => (this.maxHandle = el as HTMLButtonElement)} role="slider" style={{ right: rightThumbOffset }} > <div class="handle" /> </button> ); const labeledHandle = ( <button aria-label={this.isRange ? this.maxLabel : this.minLabel} aria-orientation="horizontal" aria-valuemax={this.max} aria-valuemin={this.min} aria-valuenow={value} class={{ thumb: true, "thumb--value": true, "thumb--active": this.lastDragProp !== "minMaxValue" && this.dragProp === maxProp }} disabled={this.disabled} onBlur={() => (this.activeProp = null)} onFocus={() => (this.activeProp = maxProp)} onPointerDown={() => this.dragStart(maxProp)} ref={(el) => (this.maxHandle = el as HTMLButtonElement)} role="slider" style={{ right: rightThumbOffset }} > <span aria-hidden="true" class="handle__label handle__label--value"> {value ? value.toLocaleString() : value} </span> <span aria-hidden="true" class="handle__label handle__label--value static"> {value ? value.toLocaleString() : value} </span> <span aria-hidden="true" class="handle__label handle__label--value transformed"> {value ? value.toLocaleString() : value} </span> <div class="handle" /> </button> ); const histogramLabeledHandle = ( <button aria-label={this.isRange ? this.maxLabel : this.minLabel} aria-orientation="horizontal" aria-valuemax={this.max} aria-valuemin={this.min} aria-valuenow={value} class={{ thumb: true, "thumb--value": true, "thumb--active": this.lastDragProp !== "minMaxValue" && this.dragProp === maxProp }} disabled={this.disabled} onBlur={() => (this.activeProp = null)} onFocus={() => (this.activeProp = maxProp)} onPointerDown={() => this.dragStart(maxProp)} ref={(el) => (this.maxHandle = el as HTMLButtonElement)} role="slider" style={{ right: rightThumbOffset }} > <div class="handle" /> <span aria-hidden="true" class="handle__label handle__label--value"> {value ? value.toLocaleString() : value} </span> <span aria-hidden="true" class="handle__label handle__label--value static"> {value ? value.toLocaleString() : value} </span> <span aria-hidden="true" class="handle__label handle__label--value transformed"> {value ? value.toLocaleString() : value} </span> </button> ); const preciseHandle = ( <button aria-label={this.isRange ? this.maxLabel : this.minLabel} aria-orientation="horizontal" aria-valuemax={this.max} aria-valuemin={this.min} aria-valuenow={value} class={{ thumb: true, "thumb--value": true, "thumb--active": this.lastDragProp !== "minMaxValue" && this.dragProp === maxProp, "thumb--precise": true }} disabled={this.disabled} onBlur={() => (this.activeProp = null)} onFocus={() => (this.activeProp = maxProp)} onPointerDown={() => this.dragStart(maxProp)} ref={(el) => (this.maxHandle = el as HTMLButtonElement)} role="slider" style={{ right: rightThumbOffset }} > <div class="handle" /> <div class="handle-extension" /> </button> ); const histogramPreciseHandle = ( <button aria-label={this.isRange ? this.maxLabel : this.minLabel} aria-orientation="horizontal" aria-valuemax={this.max} aria-valuemin={this.min} aria-valuenow={value} class={{ thumb: true, "thumb--value": true, "thumb--active": this.lastDragProp !== "minMaxValue" && this.dragProp === maxProp, "thumb--precise": true }} disabled={this.disabled} onBlur={() => (this.activeProp = null)} onFocus={() => (this.activeProp = maxProp)} onPointerDown={() => this.dragStart(maxProp)} ref={(el) => (this.maxHandle = el as HTMLButtonElement)} role="slider" style={{ right: rightThumbOffset }} > <div class="handle-extension" /> <div class="handle" /> </button> ); const labeledPreciseHandle = ( <button aria-label={this.isRange ? this.maxLabel : this.minLabel} aria-orientation="horizontal" aria-valuemax={this.max} aria-valuemin={this.min} aria-valuenow={value} class={{ thumb: true, "thumb--value": true, "thumb--active": this.lastDragProp !== "minMaxValue" && this.dragProp === maxProp, "thumb--precise": true }} disabled={this.disabled} onBlur={() => (this.activeProp = null)} onFocus={() => (this.activeProp = maxProp)} onPointerDown={() => this.dragStart(maxProp)} ref={(el) => (this.maxHandle = el as HTMLButtonElement)} role="slider" style={{ right: rightThumbOffset }} > <span aria-hidden="true" class="handle__label handle__label--value"> {value ? value.toLocaleString() : value} </span> <span aria-hidden="true" class="handle__label handle__label--value static"> {value ? value.toLocaleString() : value} </span> <span aria-hidden="true" class="handle__label handle__label--value transformed"> {value ? value.toLocaleString() : value} </span> <div class="handle" /> <div class="handle-extension" /> </button> ); const histogramLabeledPreciseHandle = ( <button aria-label={this.isRange ? this.maxLabel : this.minLabel} aria-orientation="horizontal" aria-valuemax={this.max} aria-valuemin={this.min} aria-valuenow={value} class={{ thumb: true, "thumb--value": true, "thumb--active": this.lastDragProp !== "minMaxValue" && this.dragProp === maxProp, "thumb--precise": true }} disabled={this.disabled} onBlur={() => (this.activeProp = null)} onFocus={() => (this.activeProp = maxProp)} onPointerDown={() => this.dragStart(maxProp)} ref={(el) => (this.maxHandle = el as HTMLButtonElement)} role="slider" style={{ right: rightThumbOffset }} > <div class="handle-extension" /> <div class="handle" /> <span aria-hidden="true" class="handle__label handle__label--value"> {value ? value.toLocaleString() : value} </span> <span aria-hidden="true" class="handle__label handle__label--value static"> {value ? value.toLocaleString() : value} </span> <span aria-hidden="true" class="handle__label handle__label--value transformed"> {value ? value.toLocaleString() : value} </span> </button> ); const minHandle = ( <button aria-label={this.minLabel} aria-orientation="horizontal" aria-valuemax={this.max} aria-valuemin={this.min} aria-valuenow={this.minValue} class={{ thumb: true, "thumb--minValue": true, "thumb--active": this.dragProp === "minValue" }} disabled={this.disabled} onBlur={() => (this.activeProp = null)} onFocus={() => (this.activeProp = "minValue")} onPointerDown={() => this.dragStart("minValue")} ref={(el) => (this.minHandle = el as HTMLButtonElement)} role="slider" style={{ left: leftThumbOffset }} > <div class="handle" /> </button> ); const minLabeledHandle = ( <button aria-label={this.minLabel} aria-orientation="horizontal" aria-valuemax={this.max} aria-valuemin={this.min} aria-valuenow={this.minValue} class={{ thumb: true, "thumb--minValue": true, "thumb--active": this.dragProp === "minValue" }} disabled={this.disabled} onBlur={() => (this.activeProp = null)} onFocus={() => (this.activeProp = "minValue")} onPointerDown={() => this.dragStart("minValue")} ref={(el) => (this.minHandle = el as HTMLButtonElement)} role="slider" style={{ left: leftThumbOffset }} > <span aria-hidden="true" class="handle__label handle__label--minValue"> {this.minValue && this.minValue.toLocaleString()} </span> <span aria-hidden="true" class="handle__label handle__label--minValue static"> {this.minValue && this.minValue.toLocaleString()} </span> <span aria-hidden="true" class="handle__label handle__label--minValue transformed"> {this.minValue && this.minValue.toLocaleString()} </span> <div class="handle" /> </button> ); const minHistogramLabeledHandle = ( <button aria-label={this.minLabel} aria-orientation="horizontal" aria-valuemax={this.max} aria-valuemin={this.min} aria-valuenow={this.minValue} class={{ thumb: true, "thumb--minValue": true, "thumb--active": this.dragProp === "minValue" }} disabled={this.disabled} onBlur={() => (this.activeProp = null)} onFocus={() => (this.activeProp = "minValue")} onPointerDown={() => this.dragStart("minValue")} ref={(el) => (this.minHandle = el as HTMLButtonElement)} role="slider" style={{ left: leftThumbOffset }} > <div class="handle" /> <span aria-hidden="true" class="handle__label handle__label--minValue"> {this.minValue && this.minValue.toLocaleString()} </span> <span aria-hidden="true" class="handle__label handle__label--minValue static"> {this.minValue && this.minValue.toLocaleString()} </span> <span aria-hidden="true" class="handle__label handle__label--minValue transformed"> {this.minValue && this.minValue.toLocaleString()} </span> </button> ); const minPreciseHandle = ( <button aria-label={this.minLabel} aria-orientation="horizontal" aria-valuemax={this.max} aria-valuemin={this.min} aria-valuenow={this.minValue} class={{ thumb: true, "thumb--minValue": true, "thumb--active": this.dragProp === "minValue", "thumb--precise": true }} disabled={this.disabled} onBlur={() => (this.activeProp = null)} onFocus={() => (this.activeProp = "minValue")} onPointerDown={() => this.dragStart("minValue")} ref={(el) => (this.minHandle = el as HTMLButtonElement)} role="slider" style={{ left: leftThumbOffset }} > <div class="handle-extension" /> <div class="handle" /> </button> ); const minLabeledPreciseHandle = ( <button aria-label={this.minLabel} aria-orientation="horizontal" aria-valuemax={this.max} aria-valuemin={this.min} aria-valuenow={this.minValue} class={{ thumb: true, "thumb--minValue": true, "thumb--active": this.dragProp === "minValue", "thumb--precise": true }} disabled={this.disabled} onBlur={() => (this.activeProp = null)} onFocus={() => (this.activeProp = "minValue")} onPointerDown={() => this.dragStart("minValue")} ref={(el) => (this.minHandle = el as HTMLButtonElement)} role="slider" style={{ left: leftThumbOffset }} > <div class="handle-extension" /> <div class="handle" /> <span aria-hidden="true" class="handle__label handle__label--minValue"> {this.minValue && this.minValue.toLocaleString()} </span> <span aria-hidden="true" class="handle__label handle__label--minValue static"> {this.minValue && this.minValue.toLocaleString()} </span> <span aria-hidden="true" class="handle__label handle__label--minValue transformed"> {this.minValue && this.minValue.toLocaleString()} </span> </button> ); return ( <Host id={id} onTouchStart={this.handleTouchStart}> <div class={{ container: true, "container--range": this.isRange }}> {this.renderGraph()} <div class="track" ref={this.storeTrackRef}> <div class="track__range" onPointerDown={() => this.dragStart("minMaxValue")} style={{ left: `${mirror ? 100 - maxInterval : minInterval}%`, right: `${mirror ? minInterval : 100 - maxInterval}%` }} /> <div class="ticks"> {this.tickValues.map((tick) => { const tickOffset = `${this.getUnitInterval(tick) * 100}%`; let activeTicks = tick >= min && tick <= max; if (useMinValue) { activeTicks = tick >= this.minValue && tick <= this.maxValue; } return ( <span class={{ tick: true, "tick--active": activeTicks }} style={{ left: mirror ? "" : tickOffset, right: mirror ? tickOffset : "" }} > {this.renderTickLabel(tick)} </span> ); })} </div> </div> {!this.precise && !this.labelHandles && this.isRange && minHandle} {!this.hasHistogram && !this.precise && this.labelHandles && this.isRange && minLabeledHandle} {this.precise && !this.labelHandles && this.isRange && minPreciseHandle} {this.precise && this.labelHandles && this.isRange && minLabeledPreciseHandle} {this.hasHistogram && !this.precise && this.labelHandles && this.isRange && minHistogramLabeledHandle} {!this.precise && !this.labelHandles && handle} {!this.hasHistogram && !this.precise && this.labelHandles && labeledHandle} {!this.hasHistogram && this.precise && !this.labelHandles && preciseHandle} {this.hasHistogram && this.precise && !this.labelHandles && histogramPreciseHandle} {!this.hasHistogram && this.precise && this.labelHandles && labeledPreciseHandle} {this.hasHistogram && !this.precise && this.labelHandles && histogramLabeledHandle} {this.hasHistogram && this.precise && this.labelHandles && histogramLabeledPreciseHandle} </div> </Host> ); } private renderGraph(): VNode { return this.histogram ? ( <div class="graph"> <calcite-graph colorStops={this.histogramStops} data={this.histogram} data-style="slider-histogram" height={48} highlightMax={this.isRange ? this.maxValue : this.value} highlightMin={this.isRange ? this.minValue : this.min} width={300} /> </div> ) : null; } private renderTickLabel(tick: number): VNode { const isMinTickLabel = tick === this.min; const isMaxTickLabel = tick === this.max; const tickLabel = ( <span class={{ tick__label: true, "tick__label--min": isMinTickLabel, "tick__label--max": isMaxTickLabel }} > {Math.min(tick, this.max).toLocaleString()} </span> ); if (this.labelTicks && !this.hasHistogram && !this.isRange) { return tickLabel; } if ( this.labelTicks && !this.hasHistogram && this.isRange && !this.precise && !this.labelHandles ) { return tickLabel; } if ( this.labelTicks && !this.hasHistogram && this.isRange && !this.precise && this.labelHandles ) { return tickLabel; } if ( this.labelTicks && !this.hasHistogram && this.isRange && this.precise && (isMinTickLabel || isMaxTickLabel) ) { return tickLabel; } if (this.labelTicks && this.hasHistogram && !this.precise && !this.labelHandles) { return tickLabel; } if ( this.labelTicks && this.hasHistogram && this.precise && !this.labelHandles && (isMinTickLabel || isMaxTickLabel) ) { return tickLabel; } if ( this.labelTicks && this.hasHistogram && !this.precise && this.labelHandles && (isMinTickLabel || isMaxTickLabel) ) { return tickLabel; } if ( this.labelTicks && this.hasHistogram && this.precise && this.labelHandles && (isMinTickLabel || isMaxTickLabel) ) { return tickLabel; } return null; } //-------------------------------------------------------------------------- // // Event Listeners // //-------------------------------------------------------------------------- @Listen("keydown") keyDownHandler(event: KeyboardEvent): void { const mirror = this.shouldMirror(); const { activeProp, max, min, pageStep, step } = this; const value = this[activeProp]; const key = getKey(event.key); if (key === "Enter" || key === " ") { event.preventDefault(); return; } let adjustment: number; if (key === "ArrowUp" || key === "ArrowRight") { const directionFactor = mirror && key === "ArrowRight" ? -1 : 1; adjustment = value + step * directionFactor; } else if (key === "ArrowDown" || key === "ArrowLeft") { const directionFactor = mirror && key === "ArrowLeft" ? -1 : 1; adjustment = value - step * directionFactor; } else if (key === "PageUp") { if (pageStep) { adjustment = value + pageStep; } } else if (key === "PageDown") { if (pageStep) { adjustment = value - pageStep; } } else if (key === "Home") { adjustment = min; } else if (key === "End") { adjustment = max; } if (isNaN(adjustment)) { return; } event.preventDefault(); this.setValue(activeProp, this.clamp(adjustment, activeProp)); } @Listen("click") clickHandler(): void { this.focusActiveHandle(); } @Listen("pointerdown") pointerDownHandler(event: PointerEvent): void { const x = event.clientX || event.pageX; const position = this.translate(x); let prop: ActiveSliderProperty = "value"; if (this.isRange) { const inRange = position >= this.minValue && position <= this.maxValue; if (inRange && this.lastDragProp === "minMaxValue") { prop = "minMaxValue"; } else { const closerToMax = Math.abs(this.maxValue - position) < Math.abs(this.minValue - position); prop = closerToMax || position > this.maxValue ? "maxValue" : "minValue"; } } this.lastDragPropValue = this[prop]; this.dragStart(prop); const isThumbActive = this.el.shadowRoot.querySelector(".thumb:active"); if (!isThumbActive) { this.setValue(prop, this.clamp(position, prop)); } } handleTouchStart(event: TouchEvent): void { // needed to prevent extra click at the end of a handle drag event.preventDefault(); } //-------------------------------------------------------------------------- // // Events // //-------------------------------------------------------------------------- /** * Fires on all updates to the slider. * :warning: Will be fired frequently during drag. If you are performing any * expensive operations consider using a debounce or throttle to avoid * locking up the main thread. */ @Event() calciteSliderInput: EventEmitter; /** * Fires on when the thumb is released on slider * If you need to constantly listen to the drag event, * please use calciteSliderInput instead */ @Event() calciteSliderChange: EventEmitter; /** * Fires on all updates to the slider. * :warning: Will be fired frequently during drag. If you are performing any * expensive operations consider using a debounce or throttle to avoid * locking up the main thread. * @deprecated use calciteSliderInput instead */ @Event() calciteSliderUpdate: EventEmitter; //-------------------------------------------------------------------------- // // Public Methods // //-------------------------------------------------------------------------- /** Sets focus on the component. */ @Method() async setFocus(): Promise<void> { const handle = this.minHandle ? this.minHandle : this.maxHandle; handle.focus(); } //-------------------------------------------------------------------------- // // Private State/Props // //-------------------------------------------------------------------------- labelEl: HTMLCalciteLabelElement; private guid = `calcite-slider-${guid()}`; private isRange = false; private dragProp: ActiveSliderProperty; private lastDragProp: ActiveSliderProperty; private lastDragPropValue: number; private minHandle: HTMLButtonElement; private maxHandle: HTMLButtonElement; private trackEl: HTMLDivElement; @State() private activeProp: ActiveSliderProperty = "value"; @State() private minMaxValueRange: number = null; @State() private minValueDragRange: number = null; @State() private maxValueDragRange: number = null; @State() private tickValues: number[] = []; //-------------------------------------------------------------------------- // // Private Methods // //-------------------------------------------------------------------------- onLabelClick(): void { this.setFocus(); } private shouldMirror(): boolean { return this.mirrored && !this.hasHistogram; } private shouldUseMinValue(): boolean { if (!this.isRange) { return false; } return ( (this.hasHistogram && this.maxValue === 0) || (!this.hasHistogram && this.minValue === 0) ); } private generateTickValues(): number[] { const ticks = []; let current = this.min; while (this.ticks && current < this.max + this.ticks) { ticks.push(current); current = current + this.ticks; } return ticks; } private dragStart(prop: ActiveSliderProperty): void { this.dragProp = prop; this.lastDragProp = this.dragProp; this.activeProp = prop; document.addEventListener("pointermove", this.dragUpdate); document.addEventListener("pointerup", this.dragEnd); document.addEventListener("pointercancel", this.dragEnd); } private focusActiveHandle(): void { switch (this.dragProp) { default: case "maxValue": this.maxHandle.focus(); break; case "minValue": this.minHandle.focus(); break; case "minMaxValue": break; } } private dragUpdate = (event: PointerEvent): void => { event.preventDefault(); if (this.dragProp) { const value = this.translate(event.clientX || event.pageX); if (this.isRange && this.dragProp === "minMaxValue") { if (this.minValueDragRange && this.maxValueDragRange && this.minMaxValueRange) { const newMinValue = value - this.minValueDragRange; const newMaxValue = value + this.maxValueDragRange; if ( newMaxValue <= this.max && newMinValue >= this.min && newMaxValue - newMinValue === this.minMaxValueRange ) { this.minValue = this.clamp(newMinValue, "minValue"); this.maxValue = this.clamp(newMaxValue, "maxValue"); } } else { this.minValueDragRange = value - this.minValue; this.maxValueDragRange = this.maxValue - value; this.minMaxValueRange = this.maxValue - this.minValue; } } else { this.setValue(this.dragProp, this.clamp(value, this.dragProp)); } } }; private emitInput(): void { this.calciteSliderInput.emit(); this.calciteSliderUpdate.emit(); } private emitChange(): void { this.calciteSliderChange.emit(); } private dragEnd = (): void => { document.removeEventListener("pointermove", this.dragUpdate); document.removeEventListener("pointerup", this.dragEnd); document.removeEventListener("pointercancel", this.dragEnd); this.focusActiveHandle(); if (this.lastDragPropValue != this[this.dragProp]) { this.emitChange(); } this.dragProp = null; this.lastDragPropValue = null; this.minValueDragRange = null; this.maxValueDragRange = null; this.minMaxValueRange = null; }; /** * Set the prop value if changed at the component level * @param valueProp * @param value */ private setValue(valueProp: string, value: number): void { const oldValue = this[valueProp]; const valueChanged = oldValue !== value; if (!valueChanged) { return; } this[valueProp] = value; const dragging = this.dragProp; if (!dragging) { this.emitChange(); } this.emitInput(); } /** * Set the reference of the track Element * @internal * @param node */ private storeTrackRef = (node: HTMLDivElement): void => { this.trackEl = node; }; /** * If number is outside range, constrain to min or max * @internal */ private clamp(value: number, prop?: ActiveSliderProperty): number { value = clamp(value, this.min, this.max); // ensure that maxValue and minValue don't swap positions if (prop === "maxValue") { value = Math.max(value, this.minValue); } if (prop === "minValue") { value = Math.min(value, this.maxValue); } return value; } /** * Translate a pixel position to value along the range * @internal */ private translate(x: number): number { const range = this.max - this.min; const { left, width } = this.trackEl.getBoundingClientRect(); const percent = (x - left) / width; const mirror = this.shouldMirror(); let value = this.clamp(this.min + range * (mirror ? 1 - percent : percent)); if (this.snap && this.step) { value = this.getClosestStep(value); } return value; } /** * Get closest allowed value along stepped values * @internal */ private getClosestStep(num: number): number { num = this.clamp(num); if (this.step) { const step = Math.round(num / this.step) * this.step; num = this.clamp(step); } return num; } private getFontSizeForElement(element: HTMLElement): number { return Number(window.getComputedStyle(element).getPropertyValue("font-size").match(/\d+/)[0]); } /** * Get position of value along range as fractional value * @return {number} number in the unit interval [0,1] * @internal */ private getUnitInterval(num: number): number { num = this.clamp(num); const range = this.max - this.min; return (num - this.min) / range; } private adjustHostObscuredHandleLabel(name: "value" | "minValue"): void { const label: HTMLSpanElement = this.el.shadowRoot.querySelector(`.handle__label--${name}`); const labelStatic: HTMLSpanElement = this.el.shadowRoot.querySelector( `.handle__label--${name}.static` ); const labelTransformed: HTMLSpanElement = this.el.shadowRoot.querySelector( `.handle__label--${name}.transformed` ); const labelStaticBounds = labelStatic.getBoundingClientRect(); const labelStaticOffset = this.getHostOffset(labelStaticBounds.left, labelStaticBounds.right); label.style.transform = `translateX(${labelStaticOffset}px)`; labelTransformed.style.transform = `translateX(${labelStaticOffset}px)`; } private hyphenateCollidingRangeHandleLabels(): void { const { shadowRoot } = this.el; const mirror = this.shouldMirror(); const leftModifier = mirror ? "value" : "minValue"; const rightModifier = mirror ? "minValue" : "value"; const leftValueLabel: HTMLSpanElement = shadowRoot.querySelector( `.handle__label--${leftModifier}` ); const leftValueLabelStatic: HTMLSpanElement = shadowRoot.querySelector( `.handle__label--${leftModifier}.static` ); const leftValueLabelTransformed: HTMLSpanElement = shadowRoot.querySelector( `.handle__label--${leftModifier}.transformed` ); const leftValueLabelStaticHostOffset = this.getHostOffset( leftValueLabelStatic.getBoundingClientRect().left, leftValueLabelStatic.getBoundingClientRect().right ); const rightValueLabel: HTMLSpanElement = shadowRoot.querySelector( `.handle__label--${rightModifier}` ); const rightValueLabelStatic: HTMLSpanElement = shadowRoot.querySelector( `.handle__label--${rightModifier}.static` ); const rightValueLabelTransformed: HTMLSpanElement = shadowRoot.querySelector( `.handle__label--${rightModifier}.transformed` ); const rightValueLabelStaticHostOffset = this.getHostOffset( rightValueLabelStatic.getBoundingClientRect().left, rightValueLabelStatic.getBoundingClientRect().right ); const labelFontSize = this.getFontSizeForElement(leftValueLabel); const labelTransformedOverlap = this.getRangeLabelOverlap( leftValueLabelTransformed, rightValueLabelTransformed ); const hyphenLabel = leftValueLabel; const labelOffset = labelFontSize / 2; if (labelTransformedOverlap > 0) { hyphenLabel.classList.add("hyphen"); if (rightValueLabelStaticHostOffset === 0 && leftValueLabelStaticHostOffset === 0) { // Neither handle overlaps the host boundary let leftValueLabelTranslate = labelTransformedOverlap / 2 - labelOffset; leftValueLabelTranslate = Math.sign(leftValueLabelTranslate) === -1 ? Math.abs(leftValueLabelTranslate) : -leftValueLabelTranslate; const leftValueLabelTransformedHostOffset = this.getHostOffset( leftValueLabelTransformed.getBoundingClientRect().left + leftValueLabelTranslate - labelOffset, leftValueLabelTransformed.getBoundingClientRect().right + leftValueLabelTranslate - labelOffset ); let rightValueLabelTranslate = labelTransformedOverlap / 2; const rightValueLabelTransformedHostOffset = this.getHostOffset( rightValueLabelTransformed.getBoundingClientRect().left + rightValueLabelTranslate, rightValueLabelTransformed.getBoundingClientRect().right + rightValueLabelTranslate ); if (leftValueLabelTransformedHostOffset !== 0) { leftValueLabelTranslate += leftValueLabelTransformedHostOffset; rightValueLabelTranslate += leftValueLabelTransformedHostOffset; } if (rightValueLabelTransformedHostOffset !== 0) { leftValueLabelTranslate += rightValueLabelTransformedHostOffset; rightValueLabelTranslate += rightValueLabelTransformedHostOffset; } leftValueLabel.style.transform = `translateX(${leftValueLabelTranslate}px)`; leftValueLabelTransformed.style.transform = `translateX(${ leftValueLabelTranslate - labelOffset }px)`; rightValueLabel.style.transform = `translateX(${rightValueLabelTranslate}px)`; rightValueLabelTransformed.style.transform = `translateX(${rightValueLabelTranslate}px)`; } else if (leftValueLabelStaticHostOffset > 0 || rightValueLabelStaticHostOffset > 0) { // labels overlap host boundary on the left side leftValueLabel.style.transform = `translateX(${ leftValueLabelStaticHostOffset + labelOffset }px)`; rightValueLabel.style.transform = `translateX(${ labelTransformedOverlap + rightValueLabelStaticHostOffset }px)`; rightValueLabelTransformed.style.transform = `translateX(${ labelTransformedOverlap + rightValueLabelStaticHostOffset }px)`; } else if (leftValueLabelStaticHostOffset < 0 || rightValueLabelStaticHostOffset < 0) { // labels overlap host boundary on the right side let leftValueLabelTranslate = Math.abs(leftValueLabelStaticHostOffset) + labelTransformedOverlap - labelOffset; leftValueLabelTranslate = Math.sign(leftValueLabelTranslate) === -1 ? Math.abs(leftValueLabelTranslate) : -leftValueLabelTranslate; leftValueLabel.style.transform = `translateX(${leftValueLabelTranslate}px)`; leftValueLabelTransformed.style.transform = `translateX(${ leftValueLabelTranslate - labelOffset }px)`; } } else { hyphenLabel.classList.remove("hyphen"); leftValueLabel.style.transform = `translateX(${leftValueLabelStaticHostOffset}px)`; leftValueLabelTransformed.style.transform = `translateX(${leftValueLabelStaticHostOffset}px)`; rightValueLabel.style.transform = `translateX(${rightValueLabelStaticHostOffset}px)`; rightValueLabelTransformed.style.transform = `translateX(${rightValueLabelStaticHostOffset}px)`; } } /** * Hides bounding tick labels that are obscured by either handle. */ private hideObscuredBoundingTickLabels(): void { if (!this.hasHistogram && !this.isRange && !this.labelHandles && !this.precise) { return; } if (!this.hasHistogram && !this.isRange && this.labelHandles && !this.precise) { return; } if (!this.hasHistogram && !this.isRange && !this.labelHandles && this.precise) { return; } if (!this.hasHistogram && !this.isRange && this.labelHandles && this.precise) { return; } if (!this.hasHistogram && this.isRange && !this.precise) { return; } if (this.hasHistogram && !this.precise && !this.labelHandles) { return; } const minHandle: HTMLButtonElement | null = this.el.shadowRoot.querySelector(".thumb--minValue"); const maxHandle: HTMLButtonElement | null = this.el.shadowRoot.querySelector(".thumb--value"); const minTickLabel: HTMLSpanElement | null = this.el.shadowRoot.querySelector(".tick__label--min"); const maxTickLabel: HTMLSpanElement | null = this.el.shadowRoot.querySelector(".tick__label--max"); if (!minHandle && maxHandle && minTickLabel && maxTickLabel) { minTickLabel.style.opacity = this.isMinTickLabelObscured(minTickLabel, maxHandle) ? "0" : "1"; maxTickLabel.style.opacity = this.isMaxTickLabelObscured(maxTickLabel, maxHandle) ? "0" : "1"; } if (minHandle && maxHandle && minTickLabel && maxTickLabel) { minTickLabel.style.opacity = this.isMinTickLabelObscured(minTickLabel, minHandle) || this.isMinTickLabelObscured(minTickLabel, maxHandle) ? "0" : "1"; maxTickLabel.style.opacity = this.isMaxTickLabelObscured(maxTickLabel, minHandle) || (this.isMaxTickLabelObscured(maxTickLabel, maxHandle) && this.hasHistogram) ? "0" : "1"; } } /** * Returns an integer representing the number of pixels to offset on the left or right side based on desired position behavior. * @internal */ private getHostOffset(leftBounds: number, rightBounds: number): number { const hostBounds = this.el.getBoundingClientRect(); const buffer = 7; if (leftBounds + buffer < hostBounds.left) { return hostBounds.left - leftBounds - buffer; } if (rightBounds - buffer > hostBounds.right) { return -(rightBounds - hostBounds.right) + buffer; } return 0; } /** * Returns an integer representing the number of pixels that the two given span elements are overlapping, taking into account * a space in between the two spans equal to the font-size set on them to account for the space needed to render a hyphen. * @param leftLabel * @param rightLabel */ private getRangeLabelOverlap(leftLabel: HTMLSpanElement, rightLabel: HTMLSpanElement): number { const leftLabelBounds = leftLabel.getBoundingClientRect(); const rightLabelBounds = rightLabel.getBoundingClientRect(); const leftLabelFontSize = this.getFontSizeForElement(leftLabel); const rangeLabelOverlap = leftLabelBounds.right + leftLabelFontSize - rightLabelBounds.left; return Math.max(rangeLabelOverlap, 0); } /** * Returns a boolean value representing if the minLabel span element is obscured (being overlapped) by the given handle button element. * @param minLabel * @param handle */ private isMinTickLabelObscured(minLabel: HTMLSpanElement, handle: HTMLButtonElement): boolean { const minLabelBounds = minLabel.getBoundingClientRect(); const handleBounds = handle.getBoundingClientRect(); return intersects(minLabelBounds, handleBounds); } /** * Returns a boolean value representing if the maxLabel span element is obscured (being overlapped) by the given handle button element. * @param maxLabel * @param handle */ private isMaxTickLabelObscured(maxLabel: HTMLSpanElement, handle: HTMLButtonElement): boolean { const maxLabelBounds = maxLabel.getBoundingClientRect(); const handleBounds = handle.getBoundingClientRect(); return intersects(maxLabelBounds, handleBounds); } }
the_stack
import { expect } from "chai"; import { GeometryQuery } from "../../curve/GeometryQuery"; import { Geometry } from "../../Geometry"; import { Point2d } from "../../geometry3d/Point2dVector2d"; import { Point3d } from "../../geometry3d/Point3dVector3d"; import { Range3d } from "../../geometry3d/Range"; import { IndexedPolyface, Polyface } from "../../polyface/Polyface"; import { Checker } from "../Checker"; import { GeometryCoreTestIO } from "../GeometryCoreTestIO"; /* eslint-disable no-console */ /** * Context to build a grid with * * XY Coordinates are in a grid within specified range. * * Z coordinates are initially constant * * z values are modified by later directives. */ class SampleGridBuilder { private _range: Range3d; private _numXEdge: number; private _numYEdge: number; private _data: Point3d[][]; public constructor(range: Range3d, numXEdge: number, numYEdge: number, initialZ: number) { this._numXEdge = Math.max(10, numXEdge); this._numYEdge = Math.max(5, numYEdge); this._range = range.clone(); const dx = range.xLength() / this._numXEdge; const dy = range.yLength() / this._numYEdge; const x0 = range.low.x; const y0 = range.low.y; this._data = []; for (let j = 0; j <= this._numYEdge; j++) { const row: Point3d[] = []; for (let i = 0; i <= this._numXEdge; i++) { row.push(Point3d.create(x0 + i * dx, y0 + j * dy, initialZ)); } this._data.push(row); } } /** Return the closest x index for given x value */ public closestXIndex(x: number): number { return this.closestGridIndex(x, this._range.low.x, this._range.high.x, this._numXEdge); } /** Return the closest y index for given y value */ public closestYIndex(y: number): number { return this.closestGridIndex(y, this._range.low.y, this._range.high.y, this._numYEdge); } public closestGridIndex(q: number, q0: number, q1: number, numEdge: number) { if (q < q0) return 0; if (q > q1) return numEdge; return Math.floor(0.5 + numEdge * (q - q0) / (q1 - q0)); } /** * Set grid point z to larger of current and zNew * @param i x direction index * @param j y direction index * @param zNew */ public setGridZToMax(i: number, j: number, zNew: number) { if (i >= 0 && i <= this._numXEdge && j >= 0 && j <= this._numYEdge) { const point = this._data[j][i]; point.z = Math.max(point.z, zNew); } } /** * * Apply zNew to grid point i,j * * for grid points within pyramidDropToZeroCount, apply proportional zNew * * pyramidDropToZeroCount === 0,1 are single point max * * pyramidDropToZeroCount === 2 gives fractional 1/2 zNew at adjacent grid points. * * pyramidDropToZeroCount === 3 gives fractional 2/3 * zNew at adjacent grid points, 1/3*zNew at next layer out. * @param i * @param j * @param zNew * @param pyramidDropToZeroCount INTEGER count of grid edges. */ public setGridBlockZToPyramidMax(iMid: number, jMid: number, zNew: number, pyramidDropToZeroCount: number) { this.setGridZToMax(iMid, jMid, zNew); const n = Math.ceil(pyramidDropToZeroCount); if (pyramidDropToZeroCount > 1) { for (let j = -n; j <= n; j++) { for (let i = -n; i <= n; i++) { const k = Math.abs(i) >= Math.abs(j) ? Math.abs(i) : Math.abs(j); this.setGridZToMax(iMid + i, jMid + j, zNew * (1.0 - k / pyramidDropToZeroCount)); } } } } /** * * Apply zNew to grid point i,j * * for grid points within coneRadius, apply proportional zNew * @param i * @param j * @param zNew * @param pyramidDropToZeroCount INTEGER count of grid edges. */ public setGridZToConeMax(iMid: number, jMid: number, zNew: number, coneRadius: number) { const n = Math.ceil(coneRadius); this.setGridZToMax(iMid, jMid, zNew); if (n > 1) { for (let j = -n; j <= n; j++) { for (let i = -n; i <= n; i++) { const r = Geometry.hypotenuseXY(i, j); if (r < coneRadius) this.setGridZToMax(iMid + i, jMid + j, zNew * (1.0 - r / coneRadius)); } } } } /** * * Apply zNew to grid point i,j * * for grid points within baseRadius, apply cubic (bell-like) falloff * @param i * @param j * @param zNew * @param baseRadius radius of base circle */ public setGridZToCubicMax(iMid: number, jMid: number, zNew: number, baseRadius: number) { const n = Math.ceil(baseRadius); this.setGridZToMax(iMid, jMid, zNew); let u, v, f; if (n > 1) { for (let j = -n; j <= n; j++) { for (let i = -n; i <= n; i++) { const r = Geometry.hypotenuseXY(i, j); if (r < baseRadius) { u = r / baseRadius; v = 1.0 - u; // general cubic bezier on 4 control values a0,a1,a2,a3 is // v^3 a0 + 3 v^2 u a1 + 3 v u^2 a2 + u^3 a3 // here a0 = a1 = 1, a2 = a3 = 0 f = v * v * (v + 3 * u); this.setGridZToMax(iMid + i, jMid + j, zNew * f); } } } } } /** * Turn the grid data into a polyface. * * param data is (0.5, z) for use in texture mapping. */ public createPolyface(): Polyface { const polyface = IndexedPolyface.create(false, true, false); const pointIndex: number[][] = []; for (let j = 0; j <= this._numYEdge; j++) { const indexInRow: number[] = []; for (let i = 0; i <= this._numXEdge; i++) { const index = polyface.data.point.length; const point = this._data[j][i]; polyface.data.point.push(point); polyface.data.param!.push(Point2d.create(0.5, point.z)); indexInRow.push(index); } pointIndex.push(indexInRow); } for (let j0 = 0; j0 < this._numYEdge; j0++) { for (let i0 = 0; i0 < this._numXEdge; i0++) { const i1 = i0 + 1; const j1 = j0 + 1; const i00 = pointIndex[j0][i0]; const i10 = pointIndex[j0][i1]; const i01 = pointIndex[j1][i0]; const i11 = pointIndex[j1][i1]; // lower left triangle polyface.data.pointIndex.push(i00); polyface.data.pointIndex.push(i10); polyface.data.pointIndex.push(i01); polyface.data.paramIndex!.push(i00); polyface.data.paramIndex!.push(i10); polyface.data.paramIndex!.push(i01); polyface.data.edgeVisible.push(true); polyface.data.edgeVisible.push(true); polyface.data.edgeVisible.push(true); polyface.terminateFacet(); // upper right triangle polyface.data.pointIndex.push(i10); polyface.data.pointIndex.push(i11); polyface.data.pointIndex.push(i01); polyface.data.paramIndex!.push(i10); polyface.data.paramIndex!.push(i11); polyface.data.paramIndex!.push(i01); polyface.data.edgeVisible.push(true); polyface.data.edgeVisible.push(true); polyface.data.edgeVisible.push(true); polyface.terminateFacet(); } } polyface.setNewFaceData(); return polyface; } } /** Build a sampled grid with * * grid that covers the range of the given points. * * numLongDirectionEdge on the longer of the x,y directions * * z at grid point is the max over z of all points for which this is the closest grid point. * @templateType 1 is pyramid, 2 is cone, else single point. */ function buildSampledGrid(points: Point3d[], numLongDirectionEdge: number, templateWidth: number, templateType: number = 0): Polyface { const range = Range3d.createArray(points); // range.expandInPlace(2.0); let numXEdge = numLongDirectionEdge; let numYEdge = numLongDirectionEdge; if (range.xLength() > range.yLength()) { const tileSize = range.xLength() / numXEdge; numYEdge = Math.ceil(numLongDirectionEdge * range.yLength() / range.xLength()); range.high.y = range.low.y + numYEdge * tileSize; } else { const tileSize = range.yLength() / numXEdge; numXEdge = Math.ceil(numLongDirectionEdge * range.xLength() / range.yLength()); range.high.x = range.low.x + numXEdge * tileSize; } const grid = new SampleGridBuilder(range, numXEdge, numYEdge, 0.0); for (const point of points) { const i = grid.closestXIndex(point.x); const j = grid.closestYIndex(point.y); if (templateType === 3) grid.setGridZToCubicMax(i, j, point.z, templateWidth); if (templateType === 2) grid.setGridZToConeMax(i, j, point.z, templateWidth); else if (templateType === 1) grid.setGridBlockZToPyramidMax(i, j, point.z, templateWidth); else grid.setGridZToMax(i, j, point.z); } return grid.createPolyface(); } describe("GridSampling", () => { it("NearestGridPointMax", () => { const ck = new Checker(); const allGeometry: GeometryQuery[] = []; const points = [ Point3d.create(1, 2, 0.5), Point3d.create(7, 2, 0.2), Point3d.create(1, 4, 0.2), Point3d.create(7, 4, 0.2), Point3d.create(6, 8, 0.79), Point3d.create(5, 8, 0.79), Point3d.create(4, 8, 0.79), Point3d.create(4, 7.5, 0.79), Point3d.create(4, 7, 0.79), Point3d.create(3.5, 7, 0.79), Point3d.create(4, 2, 0.80), Point3d.create(2, 3, 0.4)]; const zScale = 2.0; for (const p of points) p.z *= zScale; let x0 = 0.0; for (const templateWidth of [0, 2, 3, 4]) { const polyface = buildSampledGrid(points, 20, templateWidth, 2); GeometryCoreTestIO.captureGeometry(allGeometry, polyface, x0, 0); x0 += 10.0; } GeometryCoreTestIO.saveGeometry(allGeometry, "GridSampling", "HelloWorld"); expect(ck.getNumErrors()).equals(0); }); it("Hello5Points", () => { const ck = new Checker(); const allGeometry: GeometryQuery[] = []; const points: Point3d[] = []; const minX = 1.0; const maxX = 10.0; const minY = 2.0; const maxY = 9.0; points.push(Point3d.create(minX, minY, 0.0)); points.push(Point3d.create(maxX, minY, 0.0)); points.push(Point3d.create(maxX, maxY, 0.0)); points.push(Point3d.create(minX, maxY, 0.0)); points.push(Point3d.create(Geometry.interpolate(minX, 0.75, maxX), Geometry.interpolate(minY, 0.8, maxY), 1.0)); const pointA = Point3d.create(1.5, 3.0, 0.25); const pointB = Point3d.create(6.0, 4.0, 1.0); const pointC = Point3d.create(1.5, 7.0, 0.5); const step = 1.0 / 32; for (let f = 0; f < 1.0; f += step) { points.push(pointA.interpolate(f, pointB)); points.push(pointB.interpolate(f, pointC)); } const zScale = 1.0; for (const p of points) p.z *= zScale; let y0 = 0.0; for (const templateType of [1, 2, 3]) { let x0 = 0; for (const templateWidth of [0, 1.5, 2, 2.5, 3, 4.5]) { const polyface = buildSampledGrid(points, 50, templateWidth, templateType); GeometryCoreTestIO.captureGeometry(allGeometry, polyface, x0, y0); x0 += 20.0; } y0 += 10.0; } GeometryCoreTestIO.saveGeometry(allGeometry, "GridSampling", "Hello5Points"); expect(ck.getNumErrors()).equals(0); }); });
the_stack
import { BaseResource, CloudError, AzureServiceClientOptions } from "@azure/ms-rest-azure-js"; import * as msRest from "@azure/ms-rest-js"; export { BaseResource, CloudError }; /** * An access policy entry. */ export interface ServiceAccessPolicyEntry { /** * An Azure AD object ID (User or Apps) that is allowed access to the FHIR service. */ objectId: string; } /** * The settings for the Cosmos DB database backing the service. */ export interface ServiceCosmosDbConfigurationInfo { /** * The provisioned throughput for the backing database. */ offerThroughput?: number; /** * The URI of the customer-managed key for the backing database. */ keyVaultKeyUri?: string; } /** * Authentication configuration information */ export interface ServiceAuthenticationConfigurationInfo { /** * The authority url for the service */ authority?: string; /** * The audience url for the service */ audience?: string; /** * If the SMART on FHIR proxy is enabled */ smartProxyEnabled?: boolean; } /** * The settings for the CORS configuration of the service instance. */ export interface ServiceCorsConfigurationInfo { /** * The origins to be allowed via CORS. */ origins?: string[]; /** * The headers to be allowed via CORS. */ headers?: string[]; /** * The methods to be allowed via CORS. */ methods?: string[]; /** * The max age to be allowed via CORS. */ maxAge?: number; /** * If credentials are allowed via CORS. */ allowCredentials?: boolean; } /** * Export operation configuration information */ export interface ServiceExportConfigurationInfo { /** * The name of the default export storage account. */ storageAccountName?: string; } /** * The Private Endpoint resource. */ export interface PrivateEndpoint { /** * The ARM identifier for Private Endpoint * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly id?: string; } /** * A collection of information about the state of the connection between service consumer and * provider. */ export interface PrivateLinkServiceConnectionState { /** * Indicates whether the connection has been Approved/Rejected/Removed by the owner of the * service. Possible values include: 'Pending', 'Approved', 'Rejected' */ status?: PrivateEndpointServiceConnectionStatus; /** * The reason for approval/rejection of the connection. */ description?: string; /** * A message indicating if changes on the service provider require any updates on the consumer. */ actionsRequired?: string; } /** * An interface representing Resource. */ export interface Resource extends BaseResource { /** * Fully qualified resource Id for the resource. Ex - * /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly id?: string; /** * The name of the resource * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly name?: string; /** * The type of the resource. Ex- Microsoft.Compute/virtualMachines or * Microsoft.Storage/storageAccounts. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly type?: string; } /** * The Private Endpoint Connection resource. */ export interface PrivateEndpointConnection extends Resource { /** * The resource of private end point. */ privateEndpoint?: PrivateEndpoint; /** * A collection of information about the state of the connection between service consumer and * provider. */ privateLinkServiceConnectionState: PrivateLinkServiceConnectionState; /** * The provisioning state of the private endpoint connection resource. Possible values include: * 'Succeeded', 'Creating', 'Deleting', 'Failed' */ provisioningState?: PrivateEndpointConnectionProvisioningState; } /** * The properties of a service instance. */ export interface ServicesProperties { /** * The provisioning state. Possible values include: 'Deleting', 'Succeeded', 'Creating', * 'Accepted', 'Verifying', 'Updating', 'Failed', 'Canceled', 'Deprovisioned' * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly provisioningState?: ProvisioningState; /** * The access policies of the service instance. */ accessPolicies?: ServiceAccessPolicyEntry[]; /** * The settings for the Cosmos DB database backing the service. */ cosmosDbConfiguration?: ServiceCosmosDbConfigurationInfo; /** * The authentication configuration for the service instance. */ authenticationConfiguration?: ServiceAuthenticationConfigurationInfo; /** * The settings for the CORS configuration of the service instance. */ corsConfiguration?: ServiceCorsConfigurationInfo; /** * The settings for the export operation of the service instance. */ exportConfiguration?: ServiceExportConfigurationInfo; /** * The list of private endpoint connections that are set up for this resource. */ privateEndpointConnections?: PrivateEndpointConnection[]; /** * Control permission for data plane traffic coming from public networks while private endpoint * is enabled. Possible values include: 'Enabled', 'Disabled' */ publicNetworkAccess?: PublicNetworkAccess; } /** * The common properties of a service. */ export interface ServicesResource extends BaseResource { /** * The resource identifier. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly id?: string; /** * The resource name. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly name?: string; /** * The resource type. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly type?: string; /** * The kind of the service. Possible values include: 'fhir', 'fhir-Stu3', 'fhir-R4' */ kind: Kind; /** * The resource location. */ location: string; /** * The resource tags. */ tags?: { [propertyName: string]: string }; /** * An etag associated with the resource, used for optimistic concurrency when editing it. */ etag?: string; /** * Setting indicating whether the service has a managed identity associated with it. */ identity?: ServicesResourceIdentity; } /** * The description of the service. */ export interface ServicesDescription extends ServicesResource { /** * The common properties of a service. */ properties?: ServicesProperties; } /** * The description of the service. */ export interface ServicesPatchDescription { /** * Instance tags */ tags?: { [propertyName: string]: string }; /** * Control permission for data plane traffic coming from public networks while private endpoint * is enabled. Possible values include: 'Enabled', 'Disabled' */ publicNetworkAccess?: PublicNetworkAccess; } /** * Setting indicating whether the service has a managed identity associated with it. */ export interface ServicesResourceIdentity { /** * The principal ID of the resource identity. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly principalId?: string; /** * The tenant ID of the resource. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly tenantId?: string; /** * Type of identity being specified, currently SystemAssigned and None are allowed. Possible * values include: 'SystemAssigned', 'None' */ type?: ManagedServiceIdentityType; } /** * Error details. */ export interface ErrorDetailsInternal { /** * The error code. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly code?: string; /** * The error message. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly message?: string; /** * The target of the particular error. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly target?: string; } /** * Error details. */ export interface ErrorDetails { /** * Object containing error details. */ error?: ErrorDetailsInternal; } /** * The object that represents the operation. */ export interface OperationDisplay { /** * Service provider: Microsoft.HealthcareApis * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly provider?: string; /** * Resource Type: Services * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly resource?: string; /** * Name of the operation * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly operation?: string; /** * Friendly description for the operation, * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly description?: string; } /** * Service REST API operation. */ export interface Operation { /** * Operation name: {provider}/{resource}/{read | write | action | delete} * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly name?: string; /** * Default value is 'user,system'. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly origin?: string; /** * The information displayed about the operation. */ display?: OperationDisplay; } /** * Input values. */ export interface CheckNameAvailabilityParameters { /** * The name of the service instance to check. */ name: string; /** * The fully qualified resource type which includes provider namespace. */ type: string; } /** * The properties indicating whether a given service name is available. */ export interface ServicesNameAvailabilityInfo { /** * The value which indicates whether the provided name is available. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly nameAvailable?: boolean; /** * The reason for unavailability. Possible values include: 'Invalid', 'AlreadyExists' * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly reason?: ServiceNameUnavailabilityReason; /** * The detailed reason message. */ message?: string; } /** * The properties indicating the operation result of an operation on a service. */ export interface OperationResultsDescription { /** * The ID of the operation returned. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly id?: string; /** * The name of the operation result. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly name?: string; /** * The status of the operation being performed. Possible values include: 'Canceled', 'Succeeded', * 'Failed', 'Requested', 'Running' * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly status?: OperationResultStatus; /** * The time that the operation was started. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly startTime?: string; /** * Additional properties of the operation result. */ properties?: any; } /** * The resource model definition for a ARM proxy resource. It will have everything other than * required location and tags */ export interface ProxyResource extends Resource { } /** * The resource model definition for a ARM tracked top level resource */ export interface TrackedResource extends Resource { /** * Resource tags. */ tags?: { [propertyName: string]: string }; /** * The geo-location where the resource lives */ location: string; } /** * The resource model definition for a Azure Resource Manager resource with an etag. */ export interface AzureEntityResource extends Resource { /** * Resource Etag. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly etag?: string; } /** * A private link resource */ export interface PrivateLinkResource extends Resource { /** * The private link resource group id. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly groupId?: string; /** * The private link resource required member names. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly requiredMembers?: string[]; /** * The private link resource Private link DNS zone name. */ requiredZoneNames?: string[]; } /** * A list of private link resources */ export interface PrivateLinkResourceListResult { /** * Array of private link resources */ value?: PrivateLinkResource[]; } /** * An interface representing HealthcareApisManagementClientOptions. */ export interface HealthcareApisManagementClientOptions extends AzureServiceClientOptions { baseUri?: string; } /** * @interface * A list of service description objects with a next link. * @extends Array<ServicesDescription> */ export interface ServicesDescriptionListResult extends Array<ServicesDescription> { /** * The link used to get the next page of service description objects. */ nextLink?: string; } /** * @interface * A list of service operations. It contains a list of operations and a URL link to get the next * set of results. * @extends Array<Operation> */ export interface OperationListResult extends Array<Operation> { /** * The link used to get the next page of service description objects. */ nextLink?: string; } /** * @interface * List of private endpoint connection associated with the specified storage account * @extends Array<PrivateEndpointConnection> */ export interface PrivateEndpointConnectionListResult extends Array<PrivateEndpointConnection> { } /** * Defines values for ProvisioningState. * Possible values include: 'Deleting', 'Succeeded', 'Creating', 'Accepted', 'Verifying', * 'Updating', 'Failed', 'Canceled', 'Deprovisioned' * @readonly * @enum {string} */ export type ProvisioningState = 'Deleting' | 'Succeeded' | 'Creating' | 'Accepted' | 'Verifying' | 'Updating' | 'Failed' | 'Canceled' | 'Deprovisioned'; /** * Defines values for PrivateEndpointServiceConnectionStatus. * Possible values include: 'Pending', 'Approved', 'Rejected' * @readonly * @enum {string} */ export type PrivateEndpointServiceConnectionStatus = 'Pending' | 'Approved' | 'Rejected'; /** * Defines values for PrivateEndpointConnectionProvisioningState. * Possible values include: 'Succeeded', 'Creating', 'Deleting', 'Failed' * @readonly * @enum {string} */ export type PrivateEndpointConnectionProvisioningState = 'Succeeded' | 'Creating' | 'Deleting' | 'Failed'; /** * Defines values for PublicNetworkAccess. * Possible values include: 'Enabled', 'Disabled' * @readonly * @enum {string} */ export type PublicNetworkAccess = 'Enabled' | 'Disabled'; /** * Defines values for Kind. * Possible values include: 'fhir', 'fhir-Stu3', 'fhir-R4' * @readonly * @enum {string} */ export type Kind = 'fhir' | 'fhir-Stu3' | 'fhir-R4'; /** * Defines values for ManagedServiceIdentityType. * Possible values include: 'SystemAssigned', 'None' * @readonly * @enum {string} */ export type ManagedServiceIdentityType = 'SystemAssigned' | 'None'; /** * Defines values for ServiceNameUnavailabilityReason. * Possible values include: 'Invalid', 'AlreadyExists' * @readonly * @enum {string} */ export type ServiceNameUnavailabilityReason = 'Invalid' | 'AlreadyExists'; /** * Defines values for OperationResultStatus. * Possible values include: 'Canceled', 'Succeeded', 'Failed', 'Requested', 'Running' * @readonly * @enum {string} */ export type OperationResultStatus = 'Canceled' | 'Succeeded' | 'Failed' | 'Requested' | 'Running'; /** * Contains response data for the get operation. */ export type ServicesGetResponse = ServicesDescription & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: ServicesDescription; }; }; /** * Contains response data for the createOrUpdate operation. */ export type ServicesCreateOrUpdateResponse = ServicesDescription & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: ServicesDescription; }; }; /** * Contains response data for the update operation. */ export type ServicesUpdateResponse = ServicesDescription & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: ServicesDescription; }; }; /** * Contains response data for the list operation. */ export type ServicesListResponse = ServicesDescriptionListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: ServicesDescriptionListResult; }; }; /** * Contains response data for the listByResourceGroup operation. */ export type ServicesListByResourceGroupResponse = ServicesDescriptionListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: ServicesDescriptionListResult; }; }; /** * Contains response data for the checkNameAvailability operation. */ export type ServicesCheckNameAvailabilityResponse = ServicesNameAvailabilityInfo & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: ServicesNameAvailabilityInfo; }; }; /** * Contains response data for the beginCreateOrUpdate operation. */ export type ServicesBeginCreateOrUpdateResponse = ServicesDescription & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: ServicesDescription; }; }; /** * Contains response data for the beginUpdate operation. */ export type ServicesBeginUpdateResponse = ServicesDescription & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: ServicesDescription; }; }; /** * Contains response data for the listNext operation. */ export type ServicesListNextResponse = ServicesDescriptionListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: ServicesDescriptionListResult; }; }; /** * Contains response data for the listByResourceGroupNext operation. */ export type ServicesListByResourceGroupNextResponse = ServicesDescriptionListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: ServicesDescriptionListResult; }; }; /** * Contains response data for the list operation. */ export type OperationsListResponse = OperationListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: OperationListResult; }; }; /** * Contains response data for the listNext operation. */ export type OperationsListNextResponse = OperationListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: OperationListResult; }; }; /** * Contains response data for the get operation. */ export type OperationResultsGetResponse = { /** * The parsed response body. */ body: any; /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: any; }; }; /** * Contains response data for the listByService operation. */ export type PrivateEndpointConnectionsListByServiceResponse = PrivateEndpointConnectionListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: PrivateEndpointConnectionListResult; }; }; /** * Contains response data for the get operation. */ export type PrivateEndpointConnectionsGetResponse = PrivateEndpointConnection & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: PrivateEndpointConnection; }; }; /** * Contains response data for the createOrUpdate operation. */ export type PrivateEndpointConnectionsCreateOrUpdateResponse = PrivateEndpointConnection & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: PrivateEndpointConnection; }; }; /** * Contains response data for the beginCreateOrUpdate operation. */ export type PrivateEndpointConnectionsBeginCreateOrUpdateResponse = PrivateEndpointConnection & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: PrivateEndpointConnection; }; }; /** * Contains response data for the listByService operation. */ export type PrivateLinkResourcesListByServiceResponse = PrivateLinkResourceListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: PrivateLinkResourceListResult; }; }; /** * Contains response data for the get operation. */ export type PrivateLinkResourcesGetResponse = PrivateLinkResource & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: PrivateLinkResource; }; };
the_stack
// The MIT License (MIT) // // vs-deploy (https://github.com/mkloubert/vs-deploy) // Copyright (c) Marcel Joachim Kloubert <marcel.kloubert@gmx.net> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. import * as deploy_contracts from '../contracts'; import * as deploy_helpers from '../helpers'; import * as deploy_objects from '../objects'; import * as deploy_values from '../values'; import * as deploy_workspace from '../workspace'; import * as FS from 'fs'; import * as i18 from '../i18'; import * as Moment from 'moment'; import * as Path from 'path'; const SFTP = require('ssh2-sftp-client'); import * as sshpk from 'sshpk'; import * as TMP from 'tmp'; import * as vscode from 'vscode'; import * as Workflows from 'node-workflows'; interface DeployTargetSFTP extends deploy_contracts.TransformableDeployTarget, deploy_contracts.PasswordObject { dir?: string; hashAlgorithm?: string; hashes?: string | string[]; host?: string; privateKey?: string; privateKeyPassphrase?: string; port?: number; user?: string; password?: string; unix?: { convertCRLF?: boolean; encoding?: string; }; agent?: string; agentForward?: boolean; tryKeyboard?: boolean; readyTimeout?: number; modes?: Object | number | string; beforeUpload?: SSHCommands; uploaded?: SSHCommands; connected?: SSHCommands; closing?: SSHCommands; updateModesOfDirectories?: boolean; noCommandOutput?: boolean; privateKeySourceFormat?: string; privateKeyTargetFormat?: string; } interface FileToUpload { localPath: string; stats: FS.Stats; values: deploy_values.ValueBase[]; } interface SFTPContext { cachedRemoteDirectories: any; connection: any; dataTransformer: deploy_contracts.DataTransformer; dataTransformerOptions?: any; executionValues: { [name: string]: any }; hasCancelled: boolean; noCommandOutput: boolean; user: string; } type SSHCommandEntry = string | { __index?: number; command: string; executeBeforeWriteOutputTo?: string; noOutput?: boolean; outputEncoding?: string; verbose?: boolean; writeOutputTo?: string; }; // whoami type SSHCommands = SSHCommandEntry | SSHCommandEntry[]; const MODE_PAD = '000'; const TOUCH_TIME_FORMAT = 'YYYYMMDDHHmm.ss'; function toHashSafe(hash: string): string { return deploy_helpers.normalizeString(hash); } function toSFTPPath(path: string): string { return deploy_helpers.replaceAllStrings(path, Path.sep, '/'); } class SFtpPlugin extends deploy_objects.DeployPluginWithContextBase<SFTPContext> { protected applyExecActionsToWorkflow(eventName: string, ctx: SFTPContext, wf: Workflows.Workflow, commands: SSHCommands, values?: deploy_values.ValueBase | deploy_values.ValueBase[]) { let me = this; let commandsToExecute = deploy_helpers.asArray(commands) .map((x, i) => { if ('object' !== typeof x) { x = { command: deploy_helpers.toStringSafe(x), }; } x = deploy_helpers.cloneObject(x); x.__index = i; return x; }) .filter(x => !deploy_helpers.isEmptyString(x.command)); const ALL_VALUES = deploy_helpers.asArray(values) .filter(v => v); if (ctx.executionValues) { for (let p in ctx.executionValues) { ALL_VALUES.push(new deploy_values.StaticValue({ name: p, value: ctx.executionValues[p], })); } } commandsToExecute.forEach(uc => { wf.next(() => { return new Promise<any>((resolve, reject) => { try { let cmd = me.context.replaceWithValues(uc.command); cmd = deploy_values.replaceWithValues(ALL_VALUES, cmd); const OUTPUT_CHANNEL = me.context.outputChannel(); const VERBOSE = deploy_helpers.toBooleanSafe(uc.verbose); const WRITE_OUTPUT_TO = deploy_helpers.toStringSafe(uc.writeOutputTo).trim(); let outputEnc = deploy_helpers.normalizeString(uc.outputEncoding); if ('' === outputEnc) { outputEnc = 'utf8'; } let client = ctx.connection.client; OUTPUT_CHANNEL.appendLine(''); OUTPUT_CHANNEL.appendLine(`[SSH command :: ${deploy_helpers.toStringSafe(eventName)} :: #${uc.__index + 1}] Executing '${deploy_helpers.toStringSafe(cmd)}'...`); const NO_OUTPUT = deploy_helpers.toBooleanSafe(uc.noOutput, ctx.noCommandOutput); let execFunc: Function = client['exec']; let execArgs = [ cmd, function (err, stream) { if (err) { reject(err); return; } let commandResult: Buffer = Buffer.alloc(0); let outputFinishedInvoked = false; const OUTPUT_FINISHED = (outputErr: any, cmdOutput?: string) => { if (outputFinishedInvoked) { return; } outputFinishedInvoked = true; if (outputErr) { deploy_helpers.log(i18.t('errors.withCategory', 'plugins.sftp.applyExecActionsToWorkflow(1)', outputErr)); } try { let valueToWrite: any = deploy_helpers.toStringSafe(cmdOutput); if ('' !== WRITE_OUTPUT_TO) { try { const EXECUTE_BEFORE_WRITE_OUTPUT_TO = deploy_helpers.toStringSafe(uc.executeBeforeWriteOutputTo); if ('' !== EXECUTE_BEFORE_WRITE_OUTPUT_TO.trim()) { // execute JavaScript code // BEFORE write output as placeholder const CODE_VALUE = new deploy_values.CodeValue({ name: '', code: EXECUTE_BEFORE_WRITE_OUTPUT_TO, type: "code", }); const CURRENT_OUTPUT_VALUE = new deploy_values.StaticValue({ name: WRITE_OUTPUT_TO, value: valueToWrite, }); CODE_VALUE.otherValueProvider = () => { return ALL_VALUES.concat([ CURRENT_OUTPUT_VALUE ]); }; valueToWrite = CODE_VALUE.value; } } catch (e) { deploy_helpers.log(i18.t('errors.withCategory', 'plugins.sftp.applyExecActionsToWorkflow(2)', e)); } ctx.executionValues[WRITE_OUTPUT_TO] = valueToWrite; } if (VERBOSE) { OUTPUT_CHANNEL.append( deploy_helpers.toStringSafe(valueToWrite) ); } } catch (e) { deploy_helpers.log(i18.t('errors.withCategory', 'plugins.sftp.applyExecActionsToWorkflow(3)', e)); } finally { resolve(); } }; // try get execution result try { if (NO_OUTPUT) { OUTPUT_FINISHED(null); // skip } else { stream.once('error', (streamErr) => { OUTPUT_FINISHED(streamErr); }); stream.once('end', () => { try { OUTPUT_FINISHED(null, commandResult.toString(outputEnc)); } catch (e) { OUTPUT_FINISHED(e); } }); stream.on('data', (data) => { try { if (!Buffer.isBuffer(data)) { data = new Buffer(deploy_helpers.toStringSafe(data), outputEnc); } if (data.length > 0) { commandResult = Buffer.concat([ commandResult, data ]); } } catch (e) { OUTPUT_FINISHED(e); } }); } } catch (e) { OUTPUT_FINISHED(e); } }, ]; execFunc.apply(client, execArgs); } catch (e) { reject(e); } }); }); }); } public get canGetFileInfo(): boolean { return true; } public get canPull(): boolean { return true; } protected createContext(target: DeployTargetSFTP, files: string[], opts: deploy_contracts.DeployFileOptions): Promise<deploy_objects.DeployPluginContextWrapper<SFTPContext>> { let me = this; return new Promise<deploy_objects.DeployPluginContextWrapper<SFTPContext>>((resolve, reject) => { let completed = (err: any, conn?: any) => { if (err) { reject(err); } else { let dataTransformer: deploy_contracts.DataTransformer; if (target.unix) { if (deploy_helpers.toBooleanSafe(target.unix.convertCRLF)) { let textEnc = deploy_helpers.normalizeString(target.unix.encoding); if ('' === textEnc) { textEnc = 'ascii'; } dataTransformer = (ctx) => { return new Promise<Buffer>((resolve2, reject2) => { let completed2 = deploy_helpers.createSimplePromiseCompletedAction<Buffer>(resolve2, reject2); deploy_helpers.isBinaryContent(ctx.data).then((isBinary) => { try { let newData = ctx.data; if (!isBinary) { // seems to be a text file newData = new Buffer(deploy_helpers.replaceAllStrings(newData.toString(textEnc), "\r\n", "\n"), textEnc); } completed2(null, newData); } catch (e) { completed2(e); } }).catch((err2) => { completed2(err2); }); }); }; } } let ctx: SFTPContext = { cachedRemoteDirectories: {}, connection: conn, dataTransformer: deploy_helpers.toDataTransformerSafe(dataTransformer), executionValues: {}, hasCancelled: deploy_helpers.isNullOrUndefined(conn), noCommandOutput: deploy_helpers.toBooleanSafe(target.noCommandOutput, true), user: user, }; me.onCancelling(() => ctx.hasCancelled = true, opts); let connectionEstablishWorkflow = Workflows.create(); let connectionValues: deploy_values.ValueBase[] = []; // user connectionValues.push(new deploy_values.StaticValue({ name: 'user', value: ctx.user, })); let appendTimeValue = (name: string, timeValue: Date) => { connectionValues.push(new deploy_values.StaticValue({ name: name + '_iso', value: Moment(timeValue).toISOString(), })); connectionValues.push(new deploy_values.StaticValue({ name: name + '_iso_utc', value: Moment(timeValue).utc().toISOString(), })); connectionValues.push(new deploy_values.StaticValue({ name: name + '_touch', value: Moment(timeValue).format(TOUCH_TIME_FORMAT), })); connectionValues.push(new deploy_values.StaticValue({ name: name + '_touch_utc', value: Moment(timeValue).utc().format(TOUCH_TIME_FORMAT), })); connectionValues.push(new deploy_values.StaticValue({ name: name + '_unix', value: Moment(timeValue).unix(), })); connectionValues.push(new deploy_values.StaticValue({ name: name + '_unix_utc', value: Moment(timeValue).utc().unix(), })); }; connectionEstablishWorkflow.next((cewfCtx) => { let wrapper: deploy_objects.DeployPluginContextWrapper<SFTPContext> = { context: ctx, destroy: function(): Promise<any> { return new Promise<any>((resolve2, reject2) => { delete ctx.cachedRemoteDirectories; let closingConnectionWorkflow = Workflows.create(); // setup "close" time connectionEstablishWorkflow.next(() => { appendTimeValue('close_time', new Date()); }); // commands to execute BEFORE connection is closed me.applyExecActionsToWorkflow('closing', ctx, closingConnectionWorkflow, target.closing, connectionValues); closingConnectionWorkflow.next(() => { if (conn) { conn.end(); } }); closingConnectionWorkflow.start().then(() => { resolve2(conn); }).catch((e) => { reject2(e); }); }); }, }; cewfCtx.result = wrapper; }); // setup "connection" time connectionEstablishWorkflow.next(() => { appendTimeValue('connected_time', new Date()); }); // commands to execute after // connection has been established me.applyExecActionsToWorkflow('connected', ctx, connectionEstablishWorkflow, target.connected, connectionValues); connectionEstablishWorkflow.start().then((wrapper: deploy_objects.DeployPluginContextWrapper<SFTPContext>) => { resolve(wrapper); }).catch((err) => { reject(err); }); } }; // host & TCP port let host = deploy_helpers.toStringSafe(target.host, deploy_contracts.DEFAULT_HOST); let port = parseInt(deploy_helpers.toStringSafe(target.port, '22').trim()); // username and password let user = deploy_helpers.toStringSafe(target.user); if ('' === user) { user = undefined; } let pwd = deploy_helpers.toStringSafe(target.password); if ('' === pwd) { pwd = undefined; } // supported hashes let hashes = deploy_helpers.asArray(target.hashes) .map(x => toHashSafe(x)) .filter(x => '' !== x); hashes = deploy_helpers.distinctArray(hashes); let hashAlgo = toHashSafe(target.hashAlgorithm); if ('' === hashAlgo) { hashAlgo = 'md5'; } let privateKeyFile = deploy_helpers.toStringSafe(target.privateKey); privateKeyFile = me.context.replaceWithValues(privateKeyFile); if ('' !== privateKeyFile.trim()) { if (!Path.isAbsolute(privateKeyFile)) { privateKeyFile = Path.join(deploy_workspace.getRootPath(), privateKeyFile); } } let agent = deploy_helpers.toStringSafe(target.agent); agent = me.context.replaceWithValues(agent); if ('' === agent.trim()) { agent = undefined; } let agentForward = deploy_helpers.toBooleanSafe(target.agentForward); let tryKeyboard = deploy_helpers.toBooleanSafe(target.tryKeyboard); let readyTimeout = parseInt(deploy_helpers.toStringSafe(target.readyTimeout).trim()); if (isNaN(readyTimeout)) { readyTimeout = undefined; } let privateKeyPassphrase = deploy_helpers.toStringSafe(target.privateKeyPassphrase); if ('' === privateKeyPassphrase) { privateKeyPassphrase = undefined; } try { let privateKey: Buffer; let openConnection = () => { if (!privateKey) { if (!user) { user = 'anonymous'; } } let conn = new SFTP(); if (tryKeyboard) { conn.client.on('keyboard-interactive', (name, instructions, instructionsLang, prompts, finish) => { try { finish([ pwd ]); } catch (e) { deploy_helpers.log(i18.t('errors.withCategory', 'plugins.sftp.keyboard-interactive', e)); } }); } conn.connect({ host: host, port: port, username: user, password: pwd, privateKey: privateKey, passphrase: privateKeyPassphrase, hostHash: hashAlgo, hostVerifier: (hashedKey, cb) => { hashedKey = toHashSafe(hashedKey); if (hashes.length < 1) { return true; } return hashes.indexOf(hashedKey) > -1; }, agent: agent, agentForward: agentForward, tryKeyboard: tryKeyboard, readyTimeout: readyTimeout, }).then(() => { completed(null, conn); }).catch((err) => { completed(err); }); }; let setupPrivateKeyIfNeeded = () => { try { if (privateKey) { let privateKeySourceFormat = deploy_helpers.toStringSafe( me.context.replaceWithValues(target.privateKeySourceFormat) ); privateKeySourceFormat = privateKeySourceFormat.trim(); if ('' !== privateKeySourceFormat) { let privateKeyTargetFormat = deploy_helpers.toStringSafe( me.context.replaceWithValues(target.privateKeyTargetFormat) ); privateKeyTargetFormat = privateKeyTargetFormat.trim(); if ('' === privateKeyTargetFormat) { privateKeyTargetFormat = 'ssh'; } const OPTS = { 'filename': privateKeyFile, 'passphrase': privateKeyPassphrase, }; privateKey = sshpk.parsePrivateKey(privateKey, privateKeySourceFormat, OPTS) .toBuffer(privateKeyTargetFormat, OPTS); } } openConnection(); } catch (e) { completed(e); } }; let askForPasswordIfNeeded = (defaultValueForShowPasswordPrompt: boolean, passwordGetter: () => string, passwordSetter: (pwdToSet: string) => void, cacheKey: string) => { let showPasswordPrompt = false; if (!deploy_helpers.isEmptyString(user) && deploy_helpers.isNullOrUndefined(passwordGetter())) { // user defined, but no password let pwdFromCache = deploy_helpers.toStringSafe(me.context.targetCache().get(target, cacheKey)); if ('' === pwdFromCache) { // nothing in cache showPasswordPrompt = deploy_helpers.toBooleanSafe(target.promptForPassword, defaultValueForShowPasswordPrompt); } else { passwordSetter(pwdFromCache); } } if (showPasswordPrompt) { vscode.window.showInputBox({ ignoreFocusOut: true, placeHolder: i18.t('prompts.inputPassword'), password: true, }).then((passwordFromUser) => { if ('undefined' === typeof passwordFromUser) { completed(null, null); // cancelled } else { passwordSetter(passwordFromUser); me.context.targetCache().set(target, cacheKey, passwordFromUser); setupPrivateKeyIfNeeded(); } }, (err) => { completed(err); }); } else { setupPrivateKeyIfNeeded(); } }; if (deploy_helpers.isNullUndefinedOrEmptyString(privateKeyFile)) { askForPasswordIfNeeded(true, () => pwd, (pwdToSet) => pwd = pwdToSet, 'password'); } else { // try read private key FS.readFile(privateKeyFile, (err, data) => { if (err) { completed(err); return; } privateKey = data; askForPasswordIfNeeded(false, () => privateKeyPassphrase, (pwdToSet) => privateKeyPassphrase = pwdToSet, 'privateKeyPassphrase'); }); } } catch (e) { completed(e); // global error } }); } protected deployFileWithContext(ctx: SFTPContext, file: string, target: DeployTargetSFTP, opts?: deploy_contracts.DeployFileOptions) { let me = this; let completed = (err?: any) => { if (opts.onCompleted) { opts.onCompleted(me, { canceled: ctx.hasCancelled, error: err, file: file, target: target, }); } }; if (ctx.hasCancelled) { completed(); // cancellation requested } else { let relativeFilePath = deploy_helpers.toRelativeTargetPathWithValues(file, target, me.context.values(), opts.baseDirectory); if (false === relativeFilePath) { completed(new Error(i18.t('relativePaths.couldNotResolve', file))); return; } let dir = me.getDirFromTarget(target); let targetFile = toSFTPPath(Path.join(dir, relativeFilePath)); let targetDirectory = toSFTPPath(Path.dirname(targetFile)); let getModeValue = (pathVal: string) => { let mode: number; if (!deploy_helpers.isNullOrUndefined(target.modes)) { let asOctalNumber = (val: any): number => { if (deploy_helpers.isNullUndefinedOrEmptyString(val)) { return; } return parseInt(deploy_helpers.toStringSafe(val).trim(), 8); }; if ('object' === typeof target.modes) { for (let p in target.modes) { let r = new RegExp(p); if (r.test(deploy_helpers.toStringSafe(pathVal))) { mode = asOctalNumber(target.modes[p]); } } } else { // handle as string or number mode = asOctalNumber(target.modes); } } if (deploy_helpers.isNullUndefinedOrEmptyString(mode)) { mode = undefined; } return mode; }; let putOpts: any = {}; putOpts['mode'] = getModeValue(targetFile); if (deploy_helpers.toBooleanSafe(target.updateModesOfDirectories)) { putOpts['dirMode'] = getModeValue(targetDirectory); } // upload the file let uploadFile = (initDirCache?: boolean) => { if (ctx.hasCancelled) { completed(); // cancellation requested return; } if (deploy_helpers.toBooleanSafe(initDirCache)) { ctx.cachedRemoteDirectories[targetDirectory] = []; } FS.readFile(file, (err, untransformedJsonData) => { if (err) { completed(err); return; } try { let subCtx = { file: file, remoteFile: relativeFilePath, sftp: ctx, }; let dtCtx = me.createDataTransformerContext(target, deploy_contracts.DataTransformerMode.Transform, subCtx); dtCtx.data = untransformedJsonData; let dtResult = Promise.resolve(ctx.dataTransformer(dtCtx)); dtResult.then((transformedData) => { try { let subCtx2 = { file: file, remoteFile: relativeFilePath, sftp: ctx, }; let tCtx = me.createDataTransformerContext(target, deploy_contracts.DataTransformerMode.Transform, subCtx2); tCtx.data = transformedData; let tResult = me.loadDataTransformer(target, deploy_contracts.DataTransformerMode.Transform)(tCtx); Promise.resolve(tResult).then((dataToUpload) => { let putWorkflow = Workflows.create(); let putValues: deploy_values.ValueBase[] = []; // get information of the local file putWorkflow.next((wfCtx) => { return new Promise<any>((resolve, reject) => { FS.lstat(file, (err, stats) => { if (err) { reject(err); } else { let ftu: FileToUpload = { localPath: file, stats: stats, values: putValues, }; wfCtx.value = ftu; resolve(); } }); }); }); // "time" values putWorkflow.next((wfCtx) => { let ftu: FileToUpload = wfCtx.value; let timeProperties = [ 'ctime', 'atime', 'mtime', 'birthtime' ]; timeProperties.forEach(tp => { let timeValue: Date = ftu.stats[tp]; if (!timeValue) { return; } ftu.values.push(new deploy_values.StaticValue({ name: tp + '_iso', value: Moment(timeValue).toISOString(), })); ftu.values.push(new deploy_values.StaticValue({ name: tp + '_iso_utc', value: Moment(timeValue).utc().toISOString(), })); ftu.values.push(new deploy_values.StaticValue({ name: tp + '_touch', value: Moment(timeValue).format(TOUCH_TIME_FORMAT), })); ftu.values.push(new deploy_values.StaticValue({ name: tp + '_touch_utc', value: Moment(timeValue).utc().format(TOUCH_TIME_FORMAT), })); ftu.values.push(new deploy_values.StaticValue({ name: tp + '_unix', value: Moment(timeValue).unix(), })); ftu.values.push(new deploy_values.StaticValue({ name: tp + '_unix_utc', value: Moment(timeValue).utc().unix(), })); }); // GID & UID ftu.values.push(new deploy_values.StaticValue({ name: 'gid', value: ftu.stats.gid, })); ftu.values.push(new deploy_values.StaticValue({ name: 'uid', value: ftu.stats.uid, })); // file & directory ftu.values.push(new deploy_values.StaticValue({ name: 'remote_file', value: targetFile, })); ftu.values.push(new deploy_values.StaticValue({ name: 'remote_dir', value: targetDirectory, })); ftu.values.push(new deploy_values.StaticValue({ name: 'remote_name', value: Path.basename(targetFile), })); let modeFull = ftu.stats.mode.toString(8); let modeDec = ftu.stats.mode.toString(); let modeSmall = modeFull; modeSmall = MODE_PAD.substring(0, MODE_PAD.length - modeSmall.length) + modeSmall; if (modeSmall.length >= 3) { modeSmall = modeSmall.substr(-3, 3); } // mode ftu.values.push(new deploy_values.StaticValue({ name: 'mode', value: modeSmall, })); // mode_full ftu.values.push(new deploy_values.StaticValue({ name: 'mode_full', value: modeFull, })); // mode_decimal ftu.values.push(new deploy_values.StaticValue({ name: 'mode_decimal', value: modeDec, })); // user ftu.values.push(new deploy_values.StaticValue({ name: 'user', value: ctx.user, })); }); let applyExecActions = (eventName: string, commands: SSHCommandEntry | SSHCommandEntry[]) => { me.applyExecActionsToWorkflow(eventName, ctx, putWorkflow, commands, putValues); }; // commands to execute BEFORE the upload applyExecActions('beforeUpload', target.beforeUpload); // upload putWorkflow.next(() => { return new Promise<any>((resolve, reject) => { ctx.connection.put(dataToUpload, targetFile).then(() => { if (deploy_helpers.isNullOrUndefined(putOpts['mode'])) { resolve(); } else { ctx.connection.sftp.chmod(targetFile, putOpts['mode'], (err) => { if (err) { reject(err); } else { resolve(); } }); } }).catch((e) => { reject(e); }); }); }); // commands to execute AFTER the upload applyExecActions('uploaded', target.uploaded); putWorkflow.start().then(() => { completed(); }).catch((e) => { completed(e); }); }).catch((e) => { completed(e); }); } catch (e) { completed(e); } }).catch((err) => { completed(err); }); } catch (e) { completed(e); } }); }; if (opts.onBeforeDeploy) { opts.onBeforeDeploy(me, { destination: targetDirectory, file: file, target: target, }); } let changeModForDirectory = (initDirCache?: boolean) => { if (ctx.hasCancelled) { completed(); // cancellation requested return; } if (deploy_helpers.isNullUndefinedOrEmptyString(putOpts['dirMode'])) { uploadFile(initDirCache); } else { ctx.connection.sftp.chmod(targetDirectory, putOpts['dirMode'], (err) => { if (err) { completed(err); } else { uploadFile(initDirCache); } }); } }; if (deploy_helpers.isNullOrUndefined(ctx.cachedRemoteDirectories[targetDirectory])) { // first check if target directory exists ctx.connection.list(targetDirectory).then(() => { changeModForDirectory(true); }).catch((err) => { // no => try to create if (ctx.hasCancelled) { completed(); // cancellation requested return; } ctx.connection.mkdir(targetDirectory, true).then(() => { changeModForDirectory(true); }).catch((err) => { completed(err); }); }); } else { changeModForDirectory(); } } } protected downloadFileWithContext(ctx: SFTPContext, file: string, target: DeployTargetSFTP, opts?: deploy_contracts.DeployFileOptions): Promise<Buffer> { let me = this; return new Promise<Buffer>((resolve, reject) => { let completedInvoked = false; let completed = (err: any, data?: Buffer) => { if (completedInvoked) { return; } completedInvoked = true; if (opts.onCompleted) { opts.onCompleted(me, { canceled: ctx.hasCancelled, error: err, file: file, target: target, }); } if (err) { reject(err); } else { resolve(data); } }; if (ctx.hasCancelled) { completed(null); // cancellation requested } else { let relativeFilePath = deploy_helpers.toRelativeTargetPathWithValues(file, target, me.context.values(), opts.baseDirectory); if (false === relativeFilePath) { completed(new Error(i18.t('relativePaths.couldNotResolve', file))); return; } let dir = me.getDirFromTarget(target); let targetFile = toSFTPPath(Path.join(dir, relativeFilePath)); let targetDirectory = toSFTPPath(Path.dirname(targetFile)); if (opts.onBeforeDeploy) { opts.onBeforeDeploy(me, { destination: targetDirectory, file: file, target: target, }); } ctx.connection.get(targetFile).then((data: NodeJS.ReadableStream) => { if (data) { try { data.once('error', (err) => {; completed(err); }); TMP.tmpName({ keep: true, }, (err, tmpFile) => { if (err) { completed(err); } else { let deleteTempFile = (err: any, data?: Buffer) => { // delete temp file ... FS.exists(tmpFile, (exists) => { if (exists) { // ... if exist FS.unlink(tmpFile, () => { completed(err, data); }); } else { completed(err, data); } }); }; let downloadCompleted = (err: any) => { if (err) { deleteTempFile(err); } else { FS.readFile(tmpFile, (err, transformedData) => { if (err) { deleteTempFile(err); } else { try { let subCtx = { file: file, remoteFile: relativeFilePath, }; let tCtx = me.createDataTransformerContext(target, deploy_contracts.DataTransformerMode.Restore, subCtx); tCtx.data = transformedData; let tResult = me.loadDataTransformer(target, deploy_contracts.DataTransformerMode.Restore)(tCtx); Promise.resolve(tResult).then((untransformedJsonData) => { deleteTempFile(null, untransformedJsonData); }).catch((e) => { deleteTempFile(e); }); } catch (e) { deleteTempFile(e); } } }); } }; try { // copy to temp file let pipe = data.pipe(FS.createWriteStream(tmpFile)); pipe.once('error', (err) => {; downloadCompleted(err); }); data.once('end', () => { downloadCompleted(null); }); } catch (e) { downloadCompleted(e); } } }); } catch (e) { completed(e); } } else { completed(new Error("No data!")); //TODO } }).catch((err) => { completed(err); }); } }); } protected getDirFromTarget(target: DeployTargetSFTP): string { let dir = this.context.replaceWithValues(target.dir); if (deploy_helpers.isEmptyString(dir)) { dir = '/'; } return dir; } protected async getFileInfoWithContext(ctx: SFTPContext, file: string, target: DeployTargetSFTP, opts: deploy_contracts.DeployFileOptions): Promise<deploy_contracts.FileInfo> { let me = this; let relativeFilePath = deploy_helpers.toRelativeTargetPathWithValues(file, target, me.context.values(), opts.baseDirectory); if (false === relativeFilePath) { throw new Error(i18.t('relativePaths.couldNotResolve', file)); } let dir = me.getDirFromTarget(target); let targetFile = toSFTPPath(Path.join(dir, relativeFilePath)); let targetDirectory = toSFTPPath(Path.dirname(targetFile)); let fileName = Path.basename(targetFile); let wf = Workflows.create(); wf.on('action.after', function(err, wfCtx: Workflows.WorkflowActionContext) { if (ctx.hasCancelled) { wfCtx.finish(); } }); wf.next(async () => { let info: deploy_contracts.FileInfo = { exists: false, isRemote: true, }; try { let files = await ctx.connection.list(targetDirectory); let remoteInfo: any; for (let i = 0; i < files.length; i++) { let ri = files[i]; if (ri.name === fileName) { remoteInfo = ri; break; } } if (remoteInfo) { info.exists = true; info.name = remoteInfo.name; info.path = targetDirectory; info.size = remoteInfo.size; try { if (!isNaN(remoteInfo.modifyTime)) { info.modifyTime = Moment(new Date(remoteInfo.modifyTime)); } } catch (e) { me.context.log(i18.t('errors.withCategory', 'SFtpPlugin.getFileInfoWithContext(modifyTime)', e)); } } } catch (e) { // does not exist here } return info; }); // write to result wf.next((wfCtx) => { let info: deploy_contracts.FileInfo = wfCtx.previousValue; wfCtx.result = info; }); if (!ctx.hasCancelled) { return await wf.start(); } } public info(): deploy_contracts.DeployPluginInfo { return { description: i18.t('plugins.sftp.description'), }; } } /** * Creates a new Plugin. * * @param {deploy_contracts.DeployContext} ctx The deploy context. * * @returns {deploy_contracts.DeployPlugin} The new instance. */ export function createPlugin(ctx: deploy_contracts.DeployContext): deploy_contracts.DeployPlugin { return new SFtpPlugin(ctx); }
the_stack
import React, { useEffect, useState, useMemo, } from "react"; import EditorViewHeader from "./EditorViewHeader"; import NoteList from "./NoteList"; import NoteListControls from "./NoteListControls"; import Note from "./Note"; import * as Utils from "../lib/utils"; import * as Config from "../lib/config"; import * as Editor from "../lib/editor"; import ConfirmationServiceContext from "./ConfirmationServiceContext"; import { useNavigate, useParams, } from "react-router-dom"; import useIsSmallScreen from "../hooks/useIsSmallScreen"; import { UserNoteChangeType, } from "../../../lib/notes/interfaces/UserNoteChangeType"; import ActiveNote from "../interfaces/ActiveNote"; import FrontendUserNoteChange from "../interfaces/FrontendUserNoteChange"; import { DialogType } from "../enum/DialogType"; import useConfirmDiscardingUnsavedChangesDialog from "../hooks/useConfirmDiscardingUnsavedChangesDialog"; import useGoToNote from "../hooks/useGoToNote"; import SearchDialog from "./SearchDialog"; import NoteFromUser from "../../../lib/notes/interfaces/NoteFromUser"; const EditorView = ({ databaseProvider, unsavedChanges, setUnsavedChanges, toggleAppMenu, setOpenDialog, openDialog, handleInvalidCredentialsError, refreshNotesList, stats, pinnedNotes, handleSearchInputChange, setPinnedNotes, searchValue, sortMode, handleSortModeChange, noteListItems, numberOfResults, noteListIsBusy, noteListScrollTop, setNoteListScrollTop, page, setPage, setSearchValue, }) => { const newNoteObject:ActiveNote = Utils.getNewNoteObject(); const [activeNote, setActiveNote] = useState<ActiveNote>(newNoteObject); const isSmallScreen = useIsSmallScreen(); const navigate = useNavigate(); const goToNote = useGoToNote(); const { activeNoteId } = useParams(); const confirm = React.useContext(ConfirmationServiceContext) as (any) => void; const confirmDiscardingUnsavedChanges = useConfirmDiscardingUnsavedChangesDialog(); const displayedLinkedNotes = useMemo(() => [ ...(!activeNote.isUnsaved) ? activeNote.linkedNotes.filter((note) => { const isRemoved = activeNote.changes.some((change) => { return ( change.type === UserNoteChangeType.LINKED_NOTE_DELETED && change.noteId === note.id ); }); return !isRemoved; }) : [], ...activeNote.changes .filter((change) => { return change.type === UserNoteChangeType.LINKED_NOTE_ADDED; }) .map((change) => { return change.note; }), ], [activeNote]); const handleLinkAddition = async (note) => { // return if linked note has already been added if (activeNote.changes.some((change) => { return ( change.type === UserNoteChangeType.LINKED_NOTE_ADDED && change.noteId === note.id ); })) { return; } // remove possible LINKED_NOTE_DELETED changes const newChanges = [ ...activeNote.changes.filter((change) => { return !( change.type === UserNoteChangeType.LINKED_NOTE_DELETED && change.noteId === note.id ); }), ]; // if linkedNote is NOT already there and saved, // let's add a LINKED_NOTE_ADDED change if ( !activeNote.linkedNotes.find((linkedNote) => { return linkedNote.id === note.id; }) ) { newChanges.push( { type: UserNoteChangeType.LINKED_NOTE_ADDED, noteId: note.id, note: { id: note.id, title: note.title, updateTime: note.updateTime, }, }, ); } setActiveNote({ ...activeNote, blocks: await Editor.save(), changes: newChanges, }); setUnsavedChanges(true); }; const duplicateNote = async () => { if (activeNote.isUnsaved) return; if (unsavedChanges) { await confirmDiscardingUnsavedChanges(); setUnsavedChanges(false); } const noteToTransmit:NoteFromUser = { title: activeNote.title, blocks: activeNote.blocks, changes: activeNote.linkedNotes.map((linkedNote) => { return { type: UserNoteChangeType.LINKED_NOTE_ADDED, noteId: linkedNote.id, }; }), }; const noteFromServer = await databaseProvider.putNote( noteToTransmit, { ignoreDuplicateTitles: true }, ); refreshNotesList(); goToNote(noteFromServer.id); }; const handleLinkRemoval = async (linkedNoteId) => { if (activeNote.changes.some((change) => { return ( change.type === UserNoteChangeType.LINKED_NOTE_DELETED && change.noteId === linkedNoteId ); })) { return; } setActiveNote({ ...activeNote, blocks: await Editor.save(), changes: [ ...activeNote.changes.filter( (change:FrontendUserNoteChange):boolean => { return !( change.type === UserNoteChangeType.LINKED_NOTE_ADDED && change.noteId === linkedNoteId ); }, ), { type: UserNoteChangeType.LINKED_NOTE_DELETED, noteId: linkedNoteId, }, ], }); setUnsavedChanges(true); }; const loadNote = async (noteId) => { let noteIdNumber = noteId; if (typeof noteIdNumber !== "number") { noteIdNumber = parseInt(noteIdNumber); } if (isNaN(noteIdNumber)) { navigate(Config.paths.editorWithNewNote, { replace: true }); setActiveNote(Utils.getNewNoteObject()); } else { try { const noteFromServer = await databaseProvider.getNote(noteIdNumber); setActiveNote({ ...noteFromServer, isUnsaved: false, changes: [], }); } catch (e) { // if credentials are invalid, go to LoginView. If not, throw. if (e.message === "INVALID_CREDENTIALS") { await handleInvalidCredentialsError(); } else { throw new Error(e); } } } }; const createNewNote = () => { navigate(Config.paths.editorWithNewNote); }; const removeActiveNote = async () => { if (activeNote.isUnsaved) { return; } await databaseProvider.deleteNote(activeNote.id); refreshNotesList(); navigate(Config.paths.editorWithNewNote); }; const prepareNoteToTransmit = async ():Promise<NoteFromUser> => { const noteToTransmit = { title: activeNote.title, blocks: await Editor.save(), changes: activeNote.changes, // eslint-disable-next-line no-undefined id: (!activeNote.isUnsaved) ? activeNote.id : undefined, }; Utils.setNoteTitleByLinkTitleIfUnset( noteToTransmit, Config.DEFAULT_NOTE_TITLE, ); return noteToTransmit; }; const saveActiveNote = async (options) => { const noteToTransmit = await prepareNoteToTransmit(); const noteFromServer = await databaseProvider.putNote( noteToTransmit, options, ); setActiveNote({ ...noteFromServer, isUnsaved: false, changes: [], }); setUnsavedChanges(false); refreshNotesList(); /* when saving the new note for the first time, we get its id from the databaseProvider. then we update the address bar to include the new id */ goToNote(noteFromServer.id, true); }; const handleNoteSaveRequest = async () => { try { await saveActiveNote({ ignoreDuplicateTitles: false }); } catch (e) { if (e.message === "NOTE_WITH_SAME_TITLE_EXISTS") { await confirm({ text: Config.texts.titleAlreadyExistsConfirmation, confirmText: "Save anyway", cancelText: "Cancel", encourageConfirmation: false, }); saveActiveNote({ ignoreDuplicateTitles: true }).catch((e) => { alert(e); }); } } }; const handleKeydown = (e) => { if ( // navigator.platform is deprecated and should be replaced with // navigator.userAgentData.platform at some point (window.navigator.platform.match("Mac") ? e.metaKey : e.ctrlKey) && e.key === "s" ) { handleNoteSaveRequest(); e.preventDefault(); } }; useEffect(() => { window.addEventListener("keydown", handleKeydown); return () => { window.removeEventListener("keydown", handleKeydown); }; }, [handleKeydown]); useEffect(() => { loadNote(activeNoteId); }, [activeNoteId]); useEffect(() => { document.title = activeNote.title.length > 0 ? activeNote.title : Config.DEFAULT_DOCUMENT_TITLE; return () => { document.title = Config.DEFAULT_DOCUMENT_TITLE; }; }, [activeNote]); const pinOrUnpinNote = async () => { let newPinnedNotes; if (pinnedNotes.find((pinnedNote) => pinnedNote.id === activeNote.id)) { newPinnedNotes = await databaseProvider.unpinNote(activeNote.id); } else { newPinnedNotes = await databaseProvider.pinNote(activeNote.id); } setPinnedNotes(newPinnedNotes); }; return <> <EditorViewHeader stats={stats} toggleAppMenu={toggleAppMenu} pinnedNotes={pinnedNotes} activeNote={activeNote} setUnsavedChanges={setUnsavedChanges} unsavedChanges={unsavedChanges} /> <main> { !isSmallScreen ? <div id="left-view"> <NoteListControls onChange={handleSearchInputChange} value={searchValue} sortMode={sortMode} setSortMode={handleSortModeChange} showSearchDialog={() => setOpenDialog(DialogType.SEARCH)} refreshNoteList={refreshNotesList} /> <NoteList notes={noteListItems} numberOfResults={numberOfResults} activeNote={activeNote} displayedLinkedNotes={displayedLinkedNotes} onLinkAddition={handleLinkAddition} onLinkRemoval={handleLinkRemoval} isBusy={noteListIsBusy} searchValue={searchValue} scrollTop={noteListScrollTop} setScrollTop={setNoteListScrollTop} sortMode={sortMode} page={page} setPage={(page) => { setPage(page); setNoteListScrollTop(0); }} stats={stats} itemsAreLinkable={true} setUnsavedChanges={setUnsavedChanges} unsavedChanges={unsavedChanges} /> </div> : null } <div id="right-view"> <Note note={activeNote} setNoteTitle={ (newTitle) => { setActiveNote({ ...activeNote, title: newTitle, }); } } onLinkAddition={handleLinkAddition} onLinkRemoval={handleLinkRemoval} displayedLinkedNotes={displayedLinkedNotes} setUnsavedChanges={setUnsavedChanges} databaseProvider={databaseProvider} createNewNote={createNewNote} handleNoteSaveRequest={handleNoteSaveRequest} removeActiveNote={removeActiveNote} unsavedChanges={unsavedChanges} pinOrUnpinNote={pinOrUnpinNote} duplicateNote={duplicateNote} openInGraphView={() => { navigate( Config.paths.graphWithFocusNote.replace( "%FOCUS_NOTE_ID%", activeNote.id.toString(), ), ); }} /> </div> </main> { openDialog === DialogType.SEARCH ? <SearchDialog setSearchValue={(newSearchValue) => { setSearchValue(newSearchValue); setOpenDialog(null); }} onCancel={() => setOpenDialog(null)} /> : null } </>; }; export default EditorView;
the_stack
import {DOCUMENT} from '@angular/common'; import {Injector} from '@angular/core'; import {fromEvent, Observable, Subject, Subscription} from 'rxjs'; import {filter, takeUntil, withLatestFrom} from 'rxjs/operators'; import {PlaceholderRenderer} from '../../modules/components/placeholder-renderer/placeholder-renderer.service'; import {PickOutService} from '../../modules/pick-out/pick-out.service'; import {Radar} from '../../modules/radar/radar.service'; import {SpotModel} from '../../modules/radar/spot.model'; import {StartWorkingEvent} from '../../modules/tow/events/start-working.event'; import {StopWorkingEvent} from '../../modules/tow/events/stop-working.event'; import {WorkInProgressEvent} from '../../modules/tow/events/work-in-progress.event'; import {TOW} from '../../modules/tow/tow.constant'; import {TowService} from '../../modules/tow/tow.service'; import {IWallUiApi} from '../../wall/components/wall/interfaces/ui-api.interface'; import {VIEW_MODE, WALL_VIEW_API} from '../../wall/components/wall/wall-view.model'; import {IWallModel} from '../../wall/model/interfaces/wall-model.interface'; import {IWallPlugin} from '../../wall/model/interfaces/wall-plugin.interface'; export interface ISelectionOptions { shouldUnselectBrick: (e: MouseEvent) => boolean; } export class SelectionPlugin implements IWallPlugin { name: 'selection'; version: '0.0.0'; doc: Document; isMouseSelection = false; wallModel: IWallModel; private pickOutService: PickOutService; private radar: Radar; private towService: TowService; private placeholderRenderer: PlaceholderRenderer; private nearestBrickToDrop: { spot: SpotModel; type: string; side: string; }; private placeholderHeight = 2; private isEnableDropZoneHighlight = false; private towServiceSubscription: Subscription; private options: ISelectionOptions; private destroyed$ = new Subject(); private uiApi: IWallUiApi; mouseDown$: Observable<MouseEvent>; keyDown$: Observable<KeyboardEvent>; arrowUp$: Observable<any>; arrowDown$: Observable<any>; enter$: Observable<any>; delete$: Observable<any>; escape$: Observable<any>; x$: Observable<any>; constructor(private injector: Injector, options?: ISelectionOptions) { // extension point for client to prevent brick un-selections this.options = { shouldUnselectBrick: () => true, ...options }; } onWallInitialize(wallModel: IWallModel) { this.wallModel = wallModel; this.wallModel.apiRegistered$.pipe( filter((apiName) => { return apiName === WALL_VIEW_API; }), // first(), ).subscribe(() => { this.uiApi = wallModel.api.ui; this.doc = this.injector.get(DOCUMENT); this.pickOutService = this.injector.get(PickOutService); this.radar = this.injector.get(Radar); this.placeholderRenderer = this.injector.get(PlaceholderRenderer); this.towService = this.injector.get(TowService); this.keyDown$ = fromEvent<KeyboardEvent>(this.doc, 'keydown'); this.mouseDown$ = fromEvent<MouseEvent>(this.doc, 'mousedown'); this.arrowDown$ = this.keyDown$.pipe( filter((event) => { return event.key === 'ArrowDown'; }) ); this.arrowUp$ = this.keyDown$.pipe( filter((event) => { return event.key === 'ArrowUp'; }) ); this.enter$ = this.keyDown$.pipe( filter((event) => { return event.key === 'Enter'; }) ); this.delete$ = this.keyDown$.pipe( filter((event) => { return event.key === 'Delete'; }) ); this.escape$ = this.keyDown$.pipe( filter((event) => { return event.key === 'Escape'; }) ); this.x$ = this.keyDown$.pipe( filter((event) => { return event.key === 'x'; }) ); this.arrowUp$.pipe( takeUntil(this.destroyed$), withLatestFrom(this.uiApi.mode.currentMode$), filter(([event, currentMode]) => { return currentMode === VIEW_MODE.NAVIGATION; }) ).subscribe(([event, currentMode]) => { event.preventDefault(); if (event.ctrlKey) { this.uiApi.mode.navigation.moveBricksAbove(); } else { this.uiApi.mode.navigation.moveCursorToPreviousBrick(); } }); this.arrowDown$.pipe( takeUntil(this.destroyed$), withLatestFrom(this.uiApi.mode.currentMode$), filter(([event, currentMode]) => { return currentMode === VIEW_MODE.NAVIGATION; }) ).subscribe(([event, currentMode]) => { event.preventDefault(); if (event.ctrlKey) { this.uiApi.mode.navigation.moveBricksBelow(); } else { this.uiApi.mode.navigation.moveCursorToNextBrick(); } }); this.enter$.pipe( takeUntil(this.destroyed$), withLatestFrom(this.uiApi.mode.currentMode$), filter(([event, currentMode]) => { return currentMode === VIEW_MODE.NAVIGATION; }) ).subscribe(([event, currentMode]) => { event.preventDefault(); this.uiApi.mode.navigation.callBrickPrimaryAction(); }); this.delete$.pipe( takeUntil(this.destroyed$), withLatestFrom( this.uiApi.mode.currentMode$, this.uiApi.mode.navigation.selectedBricks$ ), filter(([event, currentMode, selectedBricks]) => { return currentMode === VIEW_MODE.NAVIGATION; }) ).subscribe(([event, currentMode, selectedBricks]) => { event.preventDefault(); let removeBrickIds; if (Boolean(selectedBricks.length)) { removeBrickIds = selectedBricks; } else { removeBrickIds = [this.uiApi.mode.navigation.cursorPosition]; } this.wallModel.api.core2.removeBricks(removeBrickIds); }); this.escape$.pipe( takeUntil(this.destroyed$), ).subscribe((event) => { event.preventDefault(); this.uiApi.mode.switchMode(); }); // listen to picked out items and select appropriate bricks this.pickOutService.startPickOut$ .pipe( takeUntil(this.destroyed$) ).subscribe(() => { this.isMouseSelection = true; // switch to navigation this.uiApi.mode.switchToNavigationMode(); this.wallModel.api.ui.mediaInteraction.disable(); }); this.pickOutService.endPickOut$ .pipe( takeUntil(this.destroyed$) ).subscribe(() => { this.wallModel.api.ui.mediaInteraction.enable(); }); this.pickOutService.pickOut$ .pipe( takeUntil(this.destroyed$) ).subscribe((brickIds) => { this.uiApi.mode.navigation.selectBricks(brickIds); }); this.x$.pipe( takeUntil(this.destroyed$), withLatestFrom(this.uiApi.mode.currentMode$), filter(([event, currentMode]) => { return currentMode === VIEW_MODE.NAVIGATION; }) ).subscribe(([event, currentMode]) => { event.preventDefault(); this.uiApi.mode.navigation.switchBrickSelection(); }); this.mouseDown$.pipe( takeUntil(this.destroyed$), withLatestFrom(this.uiApi.mode.currentMode$), filter(([event, currentMode]) => { return currentMode === VIEW_MODE.NAVIGATION; }), filter(([event, currentMode]) => { return !this.isMouseOverDraggableBox(event.clientX, event.clientY) && this.options.shouldUnselectBrick(event); }) ).subscribe(() => { this.uiApi.mode.switchToEditMode(); }); // listen for draggable operation and move bricks accordingly this.towServiceSubscription = this.towService.subscribe((e) => { if (e instanceof StartWorkingEvent) { if (this.wallModel.api.core2.getBrickSnapshot(e.slaveId)) { this.isEnableDropZoneHighlight = true; } else { this.isEnableDropZoneHighlight = false; } this.nearestBrickToDrop = null; this.placeholderRenderer.clear(); } if (e instanceof StopWorkingEvent && this.nearestBrickToDrop) { if (this.isEnableDropZoneHighlight) { let movedBrickIds = []; const selectedBrickIds = this.wallModel.api.ui.mode.navigation.getSelectedBrickIds(); if (selectedBrickIds.length > 1) { movedBrickIds = movedBrickIds.concat(selectedBrickIds); } else { movedBrickIds.push(e.slaveId); } if (this.nearestBrickToDrop.type === TOW.dropTypes.horizontal) { if (this.nearestBrickToDrop.side === TOW.dropSides.top) { this.wallModel.api.core2.moveBrickBeforeBrickId( movedBrickIds, this.nearestBrickToDrop.spot.clientData.brickId ); } if (this.nearestBrickToDrop.side === TOW.dropSides.bottom) { this.wallModel.api.core2.moveBrickAfterBrickId( movedBrickIds, this.nearestBrickToDrop.spot.clientData.brickId ); } } this.nearestBrickToDrop = null; this.placeholderRenderer.clear(); } } if (e instanceof WorkInProgressEvent) { if (this.isEnableDropZoneHighlight) { const spots = Array.from(this.radar.spots.values()) .filter((spot: SpotModel) => spot.clientData.isBeacon); let nearestSpot: SpotModel; spots.forEach((spot) => { spot.updateInfo(); if (!nearestSpot) { nearestSpot = spot; } else { const currentSpotMinimalDistance = spot.getMinimalDistanceToPoint( e.mousePosition.clientX, e.mousePosition.clientY ); const nearestSpotMinimalDistance = nearestSpot.getMinimalDistanceToPoint( e.mousePosition.clientX, e.mousePosition.clientY ); if (currentSpotMinimalDistance < nearestSpotMinimalDistance) { nearestSpot = spot; } } }); if (nearestSpot) { const nearestSpotMinimalDistance = nearestSpot.getMinimalDistanceToPoint( e.mousePosition.clientX, e.mousePosition.clientY ); if (nearestSpotMinimalDistance < 50) { this.nearestBrickToDrop = { spot: nearestSpot, side: null, type: null }; if (e.mousePosition.clientX > nearestSpot.position.x && e.mousePosition.clientX < nearestSpot.position.x + nearestSpot.size.width) { this.nearestBrickToDrop.type = TOW.dropTypes.horizontal; const centerYPosition = nearestSpot.position.y + (nearestSpot.size.height / 2); this.nearestBrickToDrop.side = e.mousePosition.clientY < centerYPosition ? TOW.dropSides.top : TOW.dropSides.bottom; } this.renderPlaceholder(); } else { this.nearestBrickToDrop = null; this.placeholderRenderer.clear(); } } else { this.nearestBrickToDrop = null; this.placeholderRenderer.clear(); } } } }); }); } onWallPluginDestroy() { this.wallModel = null; this.towServiceSubscription.unsubscribe(); this.destroyed$.next(); } private isMouseOverDraggableBox(clientX: number, clientY: number): boolean { let currentElement = document.elementFromPoint(clientX, clientY); while (currentElement && !currentElement.classList.contains('wall-canvas-brick__draggable-box')) { currentElement = currentElement.parentElement; } return Boolean(currentElement); } private renderPlaceholder() { let placeholderX; let placeholderY; let placeholderSize; let placeholderIsHorizontal; const spot = this.nearestBrickToDrop.spot; const side = this.nearestBrickToDrop.side; const type = this.nearestBrickToDrop.type; if (type === TOW.dropTypes.horizontal) { placeholderX = spot.position.x; placeholderSize = spot.size.width; if (side === TOW.dropSides.top) { placeholderY = spot.position.y - this.placeholderHeight; } if (side === TOW.dropSides.bottom) { placeholderY = spot.position.y + spot.size.height; } placeholderIsHorizontal = true; } this.placeholderRenderer.render(placeholderX, placeholderY, placeholderSize, placeholderIsHorizontal); } }
the_stack
'use strict'; const async = require('async'); const { debug, info, warn, error } = require('portal-env').Logger('kong-adapter:kong'); const qs = require('querystring'); import * as utils from './utils'; import { KongCollection, KongConsumer, KongPlugin, Callback, ErrorCallback, KongApiConfig } from 'wicked-sdk'; import { KongApiConfigCollection, UpdateApiItem, DeleteApiItem, AddApiItem, AddPluginItem, UpdatePluginItem, DeletePluginItem, ConsumerInfo, AddConsumerItem, UpdateConsumerItem, DeleteConsumerItem, ConsumerApiPluginAddItem, ConsumerApiPluginPatchItem, ConsumerApiPluginDeleteItem, ConsumerPlugin } from './types'; // The maximum number of async I/O calls we fire off against // the Kong instance for one single call. const MAX_PARALLEL_CALLS = 10; const KONG_BATCH_SIZE = 100; // Used when wiping the consumers export const kong = { getKongApis: function (callback: Callback<KongApiConfigCollection>): void { debug('kong.getKongApis()'); utils.kongGetAllApis(function (err, rawApiList) { if (err) return callback(err); let apiList: KongApiConfigCollection = { apis: [] }; // Add an "api" property for the configuration, makes it easier // to compare the portal and Kong configurations. for (let i = 0; i < rawApiList.data.length; ++i) { apiList.apis.push({ api: rawApiList.data[i] }); } // Fire off this sequentially, not in parallel (renders 500's sometimes) async.eachSeries(apiList.apis, function (apiDef: KongApiConfig, callback) { utils.kongGetApiPlugins(apiDef.api.id, function (err, apiConfig) { if (err) return callback(err); apiDef.plugins = apiConfig.data; return callback(null); }); }, function (err) { if (err) return callback(err); // Plugins which are referring to consumers are not global, and must not be taken // into account when comparing. apiList = removeKongConsumerPlugins(apiList); return callback(null, apiList); }); }); }, addKongApis: function (addList: AddApiItem[], done): void { // Bail out early if list empty if (addList.length === 0) { setTimeout(done, 0); return; } debug('addKongApis()'); // Each item in addList contains: // - portalApi: The portal's API definition, including plugins async.eachSeries(addList, function (addItem: AddApiItem, callback) { info(`Creating new API in Kong: ${addItem.portalApi.id}`); utils.kongPostApi(addItem.portalApi.config.api, function (err, apiResponse) { if (err) return done(err); const kongApi = { api: apiResponse }; debug(kongApi); const addList = []; for (let i = 0; i < addItem.portalApi.config.plugins.length; ++i) { addList.push({ portalApi: addItem, portalPlugin: addItem.portalApi.config.plugins[i], kongApi: kongApi, }); } kong.addKongPlugins(addList, callback); }); }, function (err) { if (err) return done(err); done(null); }); }, updateKongApis: function (sync, updateList: UpdateApiItem[], done): void { // Bail out early if list empty if (updateList.length === 0) { setTimeout(done, 0); return; } debug('updateKongApis()'); // Each item in updateList contains // - portalApi: The portal's API definition, including plugins // - kongApi: Kong's API definition, including plugins async.eachSeries(updateList, function (updateItem: UpdateApiItem, callback) { const portalApi = updateItem.portalApi; const kongApi = updateItem.kongApi; debug('portalApi: ' + JSON.stringify(portalApi.config.api, null, 2)); debug('kongApi: ' + JSON.stringify(kongApi.api, null, 2)); const apiUpdateNeeded = !utils.matchObjects(portalApi.config.api, kongApi.api); if (apiUpdateNeeded) { debug("API '" + portalApi.name + "' does not match."); info(`Detected change, patching API definition for API ${portalApi.name} (${kongApi.api.id})`); utils.kongPatchApi(kongApi.api.id, portalApi.config.api, function (err, patchResult) { if (err) return callback(err); // Plugins sync.syncPlugins(portalApi, kongApi, callback); }); } else { debug("API '" + portalApi.name + "' matches."); // Plugins sync.syncPlugins(portalApi, kongApi, callback); } }, done); }, deleteKongApis: function (deleteList: DeleteApiItem[], done): void { // Bail out early if list empty if (deleteList.length === 0) { setTimeout(done, 0); return; } debug('deleteKongApis()'); // Each item in deleteList contains: // - kongApi async.eachSeries(deleteList, function (deleteItem: DeleteApiItem, callback) { info(`Detected unused API ${deleteItem.kongApi.api.name} (${deleteItem.kongApi.api.name}), deleting from Kong.`); utils.kongDeleteApi(deleteItem.kongApi.api.id, callback); }, function (err) { if (err) return done(err); return done(null); }); }, addKongPlugins: function (addList: AddPluginItem[], done) { // Bail out early if list empty if (addList.length === 0) { setTimeout(done, 0); return; } debug('addKongPlugins()'); // Each entry in addList contains: // - portalApi: The portal's API definition // - portalPlugin: The portal's Plugin definition // - kongApi: Kong's API representation (for ids) async.eachSeries(addList, function (addItem: AddPluginItem, callback) { info(`Adding plugin "${addItem.portalPlugin.name}" for API ${addItem.kongApi.api.name} (${addItem.kongApi.api.id})`) utils.kongPostApiPlugin(addItem.kongApi.api.id, addItem.portalPlugin, callback); }, function (err) { if (err) return done(err); return done(null); }); }, updateKongPlugins: function (updateList: UpdatePluginItem[], done) { // Bail out early if list empty if (updateList.length === 0) { setTimeout(done, 0); return; } debug('updateKongPlugins()'); // Each entry in updateList contains: // - portalApi: The portal's API definition // - portalPlugin: The portal's Plugin definition // - kongApi: Kong's API representation (for ids) // - kongPlugin: Kong's Plugin representation (for ids) async.eachSeries(updateList, function (updateItem: UpdatePluginItem, callback) { info(`Detected change in plugin "${updateItem.portalPlugin.name}" for API ${updateItem.kongApi.api.name} (${updateItem.kongApi.api.id}), patching`); utils.kongPatchApiPlugin(updateItem.kongApi.api.id, updateItem.kongPlugin.id, updateItem.portalPlugin, callback); }, function (err) { if (err) return done(err); done(null); }); }, deleteKongPlugins: function (deleteList: DeletePluginItem[], done) { // Bail out early if list empty if (deleteList.length === 0) { setTimeout(done, 0); return; } debug('deleteKongPlugins()'); // Each entry in deleteList contains: // - kongApi: Kong's API representation (for ids) // - kongPlugin: Kong's Plugin representation (for ids) async.eachSeries(deleteList, function (deleteItem: DeletePluginItem, callback) { info(`Detected unused plugin "${deleteItem.kongPlugin.name}" for API ${deleteItem.kongApi.api.name} (${deleteItem.kongApi.api.id}), patching`); utils.kongDeleteApiPlugin(deleteItem.kongApi.api.id, deleteItem.kongPlugin.id, callback); }, function (err) { if (err) return done(err); done(null); }); }, // ======= CONSUMERS ======= /* [ { "consumer": { "username": "my-app$petstore", "custom_id": "5894850948509485094tldkrjglskrzniw3769" }, "plugins": { "key-auth": [ { "key": "flkdfjlkdjflkdjflkdfldf" } ], "acls": [ { "group": "petstore" } ], "oauth2": [ { "name": "My Application", "client_id": "my-app-petstore", "client_secret": "uwortiu4eot8g7he59t87je59thoerizuoh", "uris": ["http://dummy.org"] } ] }, "apiPlugins": [ { "name": "rate-limiting", "config": { "hour": 100, "fault_tolerant": true } } ] } ] */ getKongConsumers: function (portalConsumers: ConsumerInfo[], callback: Callback<ConsumerInfo[]>): void { debug('getKongConsumers()'); async.mapLimit( portalConsumers, MAX_PARALLEL_CALLS, (portalConsumer, callback) => getKongConsumerInfo(portalConsumer, callback), function (err, results) { if (err) { error(err); error(err.stack); return callback(err); } debug('getKongConsumers() succeeded.'); return callback(null, results as ConsumerInfo[]); }); }, getAllKongConsumers: function (callback: Callback<ConsumerInfo[]>): void { debug('getAllKongConsumers()'); utils.kongGetAllConsumers(function (err, allConsumers) { if (err) return callback(err); const kongConsumerInfos: ConsumerInfo[] = []; async.eachLimit(allConsumers.data, MAX_PARALLEL_CALLS, function (kongConsumer: KongConsumer, callback) { enrichConsumerInfo(kongConsumer, function (err, consumerInfo) { if (err) return callback(err); kongConsumerInfos.push(consumerInfo); return callback(null); }); }, function (err) { if (err) return callback(err); return callback(null, kongConsumerInfos); }); }); }, addKongConsumerApiPlugins: function (addList: ConsumerApiPluginAddItem[], consumerId: string, done: ErrorCallback) { // Bail out early if list empty if (addList.length === 0) { setTimeout(done, 0); return; } debug('addKongConsumerApiPlugins()'); async.eachSeries(addList, function (addItem: ConsumerApiPluginAddItem, addCallback) { info(`Adding API plugin ${addItem.portalApiPlugin.name} for consumer ${addItem.portalConsumer.consumer.username}`); addKongConsumerApiPlugin(addItem.portalConsumer, consumerId, addItem.portalApiPlugin, addCallback); }, function (err) { if (err) return done(err); return done(null); }); }, patchKongConsumerApiPlugins: function (patchList: ConsumerApiPluginPatchItem[], callback: ErrorCallback): void { // Bail out early if list empty if (patchList.length === 0) { setTimeout(callback, 0); return; } debug('patchKongConsumerApiPlugins()'); async.eachSeries(patchList, function (patchItem: ConsumerApiPluginPatchItem, patchCallback) { info(`Patching API plugin ${patchItem.portalApiPlugin.name} for consumer ${patchItem.portalConsumer.consumer.username}`); patchKongConsumerApiPlugin(patchItem.portalConsumer, patchItem.kongConsumer, patchItem.portalApiPlugin, patchItem.kongApiPlugin, patchCallback); }, function (err) { if (err) return callback(err); return callback(null); }); }, deleteKongConsumerApiPlugins: function (deleteList: ConsumerApiPluginDeleteItem[], callback: ErrorCallback): void { // Bail out early if list empty if (deleteList.length === 0) { setTimeout(callback, 0); return; } debug('deleteKongConsumerApiPlugins()'); async.eachSeries(deleteList, function (deleteItem: ConsumerApiPluginDeleteItem, deleteCallback) { info(`Deleting API plugin ${deleteItem.kongApiPlugin.name} for consumer ${deleteItem.kongConsumer.consumer.username}`); deleteKongConsumerApiPlugin(deleteItem.kongConsumer, deleteItem.kongApiPlugin, deleteCallback); }, function (err) { if (err) return callback(err); return callback(null); }); }, addKongConsumers: function (addList: AddConsumerItem[], callback: ErrorCallback): void { debug('addKongConsumers()'); // addItem has: // - portalConsumer async.eachSeries(addList, function (addItem: AddConsumerItem, callback) { info(`Adding Kong consumer ${addItem.portalConsumer.consumer.username}`); addKongConsumer(addItem, callback); }, function (err) { if (err) return callback(err); return callback(null); }); }, updateKongConsumers: function (sync, updateList: UpdateConsumerItem[], callback: ErrorCallback): void { debug('updateKongConsumers()'); // updateItem has: // - portalConsumer // - kongConsumer async.eachSeries(updateList, function (updateItem: UpdateConsumerItem, callback) { async.series([ function (asyncCallback) { updateKongConsumer(updateItem.portalConsumer, updateItem.kongConsumer, asyncCallback); }, function (asyncCallback) { updateKongConsumerPlugins(updateItem.portalConsumer, updateItem.kongConsumer, asyncCallback); }, function (asyncCallback) { sync.syncConsumerApiPlugins(updateItem.portalConsumer, updateItem.kongConsumer, asyncCallback); } ], function (pluginsErr) { if (pluginsErr) return callback(pluginsErr); callback(null); }); }, function (err) { if (err) return callback(err); debug("updateKongConsumers() finished."); callback(null); }); }, deleteKongConsumers: function (deleteList: DeleteConsumerItem[], callback: ErrorCallback) { debug('deleteKongConsumers()'); async.eachLimit(deleteList, MAX_PARALLEL_CALLS, function (deleteItem: DeleteConsumerItem, callback) { const consumerId = deleteItem.kongConsumer.consumer.id; info(`Deleting consumer with ID ${consumerId}`); utils.kongDeleteConsumer(consumerId, callback); }, callback); }, deleteConsumerWithUsername: function (username: string, callback: ErrorCallback): void { debug('deleteConsumer() - username: ' + username); utils.kongGetConsumerByName(username, function (err, kongConsumer) { if (err) { // Gracefully accept if already deleted if (err.status === 404) { warn(`Attempted to delete non-present consumer with username ${username}`); return callback(null); } return callback(err); } info(`Deleting consumer with username ${username} (id ${kongConsumer.id})`); utils.kongDeleteConsumer(kongConsumer.id, callback); }); }, deleteConsumerWithCustomId: function (customId: string, callback: ErrorCallback): void { debug('deleteConsumerWithCustomId() - custom_id: ' + customId); utils.kongGetConsumersByCustomId(customId, function (err, consumerList) { if (err) return callback(err); // Gracefully accept if already deleted if (consumerList.data.length <= 0) { warn('Could not find user with custom_id ' + customId + ', cannot delete'); return callback(null); } if (consumerList.data.length > 1) warn('Multiple consumers with custom_id ' + customId + ' found, killing them all.'); // This should be just one call, but the consumer is in an array, so this does not hurt. info(`Deleting consumers with custom ID ${customId}`); async.map(consumerList.data, (consumer, callback) => utils.kongDeleteConsumer(consumer.id, callback), function (err, results) { if (err) return callback(err); callback(null); }); }); }, // Use with care ;-) This will wipe ALL consumers from the Kong database. wipeAllConsumers: function (callback) { debug('wipeAllConsumers()'); wipeConsumerBatch('consumers?size=' + KONG_BATCH_SIZE, callback); } }; function removeKongConsumerPlugins(apiList: KongApiConfigCollection): KongApiConfigCollection { debug('removeKongConsumerPlugins()'); for (let i = 0; i < apiList.apis.length; ++i) { const thisApi = apiList.apis[i]; let consumerPluginIndex = 0; while (consumerPluginIndex >= 0) { consumerPluginIndex = utils.getIndexBy(thisApi.plugins, function (plugin) { return !!plugin.consumer_id; }); if (consumerPluginIndex >= 0) thisApi.plugins.splice(consumerPluginIndex, 1); } } return apiList; } function getKongConsumerInfo(portalConsumer: ConsumerInfo, callback: Callback<ConsumerInfo>): void { debug('getKongConsumerInfo() for ' + portalConsumer.consumer.username); async.waterfall([ callback => getKongConsumer(portalConsumer.consumer.username, callback), (kongConsumer: KongConsumer, callback) => enrichConsumerInfo(kongConsumer, callback) ], function (err, consumerInfo) { if (err) { // console.error(err); // console.error(err.stack); return callback(err); } // Note that the result may be null if the user is not present return callback(null, consumerInfo); }); } function getKongConsumer(username, callback: Callback<KongConsumer>): void { debug('getKongConsumer(): ' + username); utils.kongGetConsumerByName(username, function (err, consumer) { if (err && err.status == 404) { debug('getKongConsumer(): Not found.'); return callback(null, null); // Consider "normal", user not (yet) found } else if (err) { return callback(err); } debug('getKongConsumer(): Success, id=' + consumer.id); return callback(null, consumer); }); } const CONSUMER_PLUGINS = [ "acls", "oauth2", "key-auth", "basic-auth", "hmac-auth" ]; function enrichConsumerInfo(kongConsumer: KongConsumer, callback: Callback<ConsumerInfo>): void { debug('enrichConsumerInfo()'); if (!kongConsumer) { debug('Not applicable, consumer not found.'); return callback(null, null); } const consumerInfo: ConsumerInfo = { consumer: kongConsumer, plugins: {}, apiPlugins: [] }; async.series({ consumerPlugins: function (callback) { enrichConsumerPlugins(consumerInfo, callback); }, apiPlugins: function (callback) { enrichConsumerApiPlugins(consumerInfo, null, callback); } }, function (err) { if (err) return callback(err); return callback(null, consumerInfo); }); } function enrichConsumerPlugins(consumerInfo: ConsumerInfo, callback: Callback<ConsumerInfo>): void { debug('enrichConsumerPlugins()'); async.each(CONSUMER_PLUGINS, function (pluginName, callback) { utils.kongGetConsumerPluginData(consumerInfo.consumer.id, pluginName, function (err, pluginData) { if (err) return callback(err); if (pluginData.data.length > 0) consumerInfo.plugins[pluginName] = pluginData.data; return callback(null); }); }, function (err) { if (err) return callback(err); return callback(null, consumerInfo); }); } function extractApiName(consumerName: string): string { debug('extractApiName()'); // consumer names are like this: portal-application-name$api-name const dollarIndex = consumerName.indexOf('$'); if (dollarIndex >= 0) return consumerName.substring(dollarIndex + 1); const atIndex = consumerName.indexOf('@'); if (atIndex >= 0) return 'portal-api-internal'; return null; } function enrichConsumerApiPlugins(consumerInfo: ConsumerInfo, /* optional */apiId: string, callback: Callback<ConsumerInfo>): void { debug('enrichConsumerApiPlugins'); const consumerId = consumerInfo.consumer.id; // Pass null for apiId if you want to extract it from the consumer's username let apiName = apiId; if (!apiId) apiName = extractApiName(consumerInfo.consumer.username); if (!apiName) { debug('enrichConsumerApiPlugins: Could not extract API name from name "' + consumerInfo.consumer.username + '", and API was not passed into function.'); // Do nothing then, no plugins return; } utils.kongGetApiPluginsByConsumer(apiName, consumerId, function (err, apiPlugins) { if (err) { // 404? If so, this may happen if the API was removed and there are still consumers on it. Ignore. if (err.status == 404) return callback(null, consumerInfo); return callback(err); } if (!apiPlugins.data) return callback(null, consumerInfo); consumerInfo.apiPlugins = apiPlugins.data; callback(null, consumerInfo); }); }; function addKongConsumerApiPlugin(portalConsumer: ConsumerInfo, consumerId: string, portalApiPlugin: KongPlugin, callback): void { debug('addKongConsumerApiPlugin()'); portalApiPlugin.consumer_id = consumerId; // Uargh const apiName = extractApiName(portalConsumer.consumer.username); utils.kongPostApiPlugin(apiName, portalApiPlugin, callback); } function deleteKongConsumerApiPlugin(kongConsumer: ConsumerInfo, kongApiPlugin: KongPlugin, callback): void { debug('deleteKongConsumerApiPlugin()'); // This comes from Kong (the api_id) utils.kongDeleteApiPlugin(kongApiPlugin.api_id, kongApiPlugin.id, callback); } function patchKongConsumerApiPlugin(portalConsumer: ConsumerInfo, kongConsumer: ConsumerInfo, portalApiPlugin: KongPlugin, kongApiPlugin: KongPlugin, callback: ErrorCallback): void { debug('patchKongConsumerApiPlugin()'); // Delete and re-add to make sure we don't have dangling properties // // TODO: This can lead to unwanted effects when updating a consumer; known issue when altering // the OAuth2 redirect URIs: This leads to the oauth2 plugin being removed and re-added, thus // changing the ID of the plugin. This in turn is related to a referenced ID in the oauth2_tokens // table, which are cascaded-deleted with this action. // // See: https://github.com/Haufe-Lexware/wicked.haufe.io/issues/180 async.series([ callback => deleteKongConsumerApiPlugin(kongConsumer, kongApiPlugin, callback), callback => addKongConsumerApiPlugin(portalConsumer, kongConsumer.consumer.id, portalApiPlugin, callback) ], function (err) { if (err) return callback(err); return callback(null); }); } function addKongConsumer(addItem, done) { debug('addKongConsumer()'); debug(JSON.stringify(addItem.portalConsumer.consumer)); utils.kongPostConsumer(addItem.portalConsumer.consumer, function (err, apiResponse) { if (err) return done(err); const consumerId = apiResponse.id; const pluginNames = []; for (let pluginName in addItem.portalConsumer.plugins) pluginNames.push(pluginName); const apiPlugins = addItem.portalConsumer.apiPlugins; // Array [] async.series([ function (pluginsCallback) { // First the auth/consumer plugins async.eachSeries(pluginNames, function (pluginName, callback) { const pluginInfo = addItem.portalConsumer.plugins[pluginName]; addKongConsumerPlugin(consumerId, pluginName, pluginInfo, callback); }, function (err2) { if (err2) return pluginsCallback(err2); pluginsCallback(null); }); }, function (pluginsCallback) { // Then the API level plugins async.eachSeries(apiPlugins, function (apiPlugin, callback) { //addKongConsumerApiPlugin() addKongConsumerApiPlugin(addItem.portalConsumer, consumerId, apiPlugin, callback); }, function (err2) { if (err2) return pluginsCallback(err2); pluginsCallback(null); }); } ], function (pluginsErr) { if (pluginsErr) return done(pluginsErr); return done(null); }); }); } function addKongConsumerPlugin(consumerId: string, pluginName: string, pluginDataList: ConsumerPlugin[], done) { debug('addKongConsumerPlugin()'); async.eachSeries(pluginDataList, function (pluginData: ConsumerPlugin, callback) { info(`Adding consumer plugin ${pluginName} for consumer ${consumerId}`); utils.kongPostConsumerPlugin(consumerId, pluginName, pluginData, callback); }, function (err) { if (err) return done(err); done(null); }); } function deleteKongConsumerPlugin(consumerId, pluginName, pluginDataList, done) { debug('deleteKongConsumerPlugin()'); async.eachSeries(pluginDataList, function (pluginData, callback) { info(`Deleting consumer plugin ${pluginName} for consumer ${consumerId}`); utils.kongDeleteConsumerPlugin(consumerId, pluginName, pluginData.id, callback); }, function (err) { if (err) return done(err); done(null); }); } function updateKongConsumerPlugins(portalConsumer: ConsumerInfo, kongConsumer: ConsumerInfo, callback: ErrorCallback) { debug('updateKongConsumerPlugins() for ' + portalConsumer.consumer.username); async.eachSeries(CONSUMER_PLUGINS, function (pluginName: string, callback) { debug("Checking Consumer plugin '" + pluginName + "'."); let portalHasPlugin = !!portalConsumer.plugins[pluginName]; let kongHasPlugin = !!kongConsumer.plugins[pluginName]; if (portalHasPlugin && !kongHasPlugin) { // Add Plugin let portalPlugin = portalConsumer.plugins[pluginName]; return addKongConsumerPlugin(kongConsumer.consumer.id, pluginName, portalPlugin, callback); } else if (!portalHasPlugin && kongHasPlugin) { // Delete Plugin let kongPlugin = kongConsumer.plugins[pluginName]; return deleteKongConsumerPlugin(kongConsumer.consumer.id, pluginName, kongPlugin, callback); } else if (portalHasPlugin && kongHasPlugin) { // Update Plugin let portalPlugin = portalConsumer.plugins[pluginName]; let kongPlugin = kongConsumer.plugins[pluginName]; if (!utils.matchObjects(portalPlugin, kongPlugin)) { async.series({ deletePlugin: function (innerCallback) { deleteKongConsumerPlugin(kongConsumer.consumer.id, pluginName, kongPlugin, innerCallback); }, addPlugin: function (innerCallback) { addKongConsumerPlugin(kongConsumer.consumer.id, pluginName, portalPlugin, innerCallback); } }, function (err2, results) { if (err2) return callback(err2); debug("updateKongConsumerPlugins - Update finished."); return callback(null); }); } else { // This is a synchronuous call inside async, which assumes it is asynchronuous. process.nextTick defers // execution until the next tick, so that this also gets async. If you don't do this, you will fairly // easily end up in a 'RangeError: Maximum call stack size exceeded' error. return process.nextTick(callback); } // Nothing to do here. } else { // Else: Plugin not used for consumer // See above regarding process.nextTick() return process.nextTick(callback); } }, function (err) { if (err) return callback(err); debug("updateKongConsumerPlugins() finished."); callback(null); }); } function updateKongConsumer(portalConsumer: ConsumerInfo, kongConsumer: ConsumerInfo, callback: ErrorCallback) { // The only thing which may differ here is the custom_id if (portalConsumer.consumer.custom_id === kongConsumer.consumer.custom_id) { debug('Custom ID for consumer username ' + portalConsumer.consumer.username + ' matches: ' + portalConsumer.consumer.custom_id); return callback(null); // Nothing to do. } info('Updating consumer ' + kongConsumer.consumer.id + ' (username ' + kongConsumer.consumer.username + ') with new custom_id: ' + portalConsumer.consumer.custom_id); utils.kongPatchConsumer(kongConsumer.consumer.id, { custom_id: portalConsumer.consumer.custom_id }, callback); } /* consumerData: { total: <...> next: 'http://....' data: [ { ... }, { ... } ] } */ function wipeConsumerBatch(consumerUrl: string, callback: ErrorCallback): void { debug('wipeConsumerBatch() ' + consumerUrl); utils.kongGetRaw(consumerUrl, function (err, consumerData: KongCollection<KongConsumer>) { if (err) return callback(err); async.mapSeries(consumerData.data, function (consumer, callback) { utils.kongDeleteConsumer(consumer.id, callback); }, function (err) { if (err) return callback(err); if (!consumerData.next) // no next link --> we're done return callback(null); // Continue with next batch; get fresh, as we deleted the other ones. wipeConsumerBatch(consumerUrl, callback); }); }); }
the_stack
import { HttpClientTestingModule } from '@angular/common/http/testing'; import { EventEmitter, NO_ERRORS_SCHEMA } from '@angular/core'; import { ComponentFixture, fakeAsync, TestBed, tick, waitForAsync } from '@angular/core/testing'; import { UrlSerializer } from '@angular/router'; import { NgbModal, NgbModalRef } from '@ng-bootstrap/ng-bootstrap'; import { CollectionRightsBackendApiService } from 'domain/collection/collection-rights-backend-api.service'; import { CollectionRights } from 'domain/collection/collection-rights.model'; import { CollectionValidationService } from 'domain/collection/collection-validation.service'; import { Collection } from 'domain/collection/collection.model'; import { UndoRedoService } from 'domain/editor/undo_redo/undo-redo.service'; import { UrlService } from 'services/contextual/url.service'; import { CollectionEditorRoutingService } from '../services/collection-editor-routing.service'; import { CollectionEditorStateService } from '../services/collection-editor-state.service'; import { CollectionEditorNavbarComponent } from './collection-editor-navbar.component'; describe('Collection editor navbar component', () => { let fixture: ComponentFixture<CollectionEditorNavbarComponent>; let componentInstance: CollectionEditorNavbarComponent; let collectionEditorRoutingService: CollectionEditorRoutingService; let collectionEditorStateService: CollectionEditorStateService; let collectionRightsBackendApiService: CollectionRightsBackendApiService; let collectionValidationService: CollectionValidationService; let undoRedoService: UndoRedoService; let urlService: UrlService; let ngbModal: NgbModal; let collectionTitle = 'Collection Title'; let collectionObjective = 'Collection Objective'; let collectionCategory = 'Collection Category'; let languageCode = 'en'; let collectionTags = ['mock tag']; let collectionId = 'collection_id'; let mockCollection = new Collection( collectionId, collectionTitle, collectionObjective, languageCode, collectionTags, null, collectionCategory, 0, 1, []); let mockPrivateCollectionRights = new CollectionRights({ collection_id: collectionId, can_edit: true, can_unpublish: true, is_private: true, owner_names: [] }); beforeEach(waitForAsync(() => { TestBed.configureTestingModule({ imports: [ HttpClientTestingModule ], declarations: [ CollectionEditorNavbarComponent ], providers: [ CollectionEditorRoutingService, CollectionEditorStateService, CollectionRightsBackendApiService, CollectionValidationService, UndoRedoService, UrlSerializer ], schemas: [NO_ERRORS_SCHEMA] }).compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(CollectionEditorNavbarComponent); componentInstance = fixture.componentInstance; collectionEditorRoutingService = TestBed.inject( CollectionEditorRoutingService); collectionEditorStateService = TestBed.inject(CollectionEditorStateService); collectionRightsBackendApiService = TestBed.inject( CollectionRightsBackendApiService); collectionValidationService = TestBed.inject(CollectionValidationService); undoRedoService = TestBed.inject(UndoRedoService); urlService = TestBed.inject(UrlService); ngbModal = TestBed.inject(NgbModal); }); afterEach(() => { componentInstance.ngOnDestroy(); }); it('should initialize', fakeAsync(() => { let mockOnCollectionEventEmitter = new EventEmitter<void>(); let mockUndoRedoChangeAppliedEventEmitter = new EventEmitter<void>(); spyOnProperty(collectionEditorStateService, 'onCollectionInitialized') .and.returnValue(mockOnCollectionEventEmitter); spyOn(undoRedoService, 'getUndoRedoChangeEventEmitter') .and.returnValue(mockUndoRedoChangeAppliedEventEmitter); spyOn(urlService, 'getCollectionIdFromEditorUrl').and.returnValue( collectionId); spyOn(collectionEditorStateService, 'getCollection').and.returnValue( mockCollection); spyOn(collectionEditorStateService, 'getCollectionRights') .and.returnValue(mockPrivateCollectionRights); spyOn( collectionValidationService, 'findValidationIssuesForPrivateCollection') .and.returnValue([]); spyOn( collectionValidationService, 'findValidationIssuesForPublicCollection') .and.returnValue([]); componentInstance.ngOnInit(); spyOn(componentInstance.collectionRights, 'isPrivate') .and.returnValue(true); mockOnCollectionEventEmitter.emit(); tick(); mockUndoRedoChangeAppliedEventEmitter.emit(); tick(); expect(componentInstance.collectionId).toEqual(collectionId); expect(componentInstance.collection).toEqual(mockCollection); expect(urlService.getCollectionIdFromEditorUrl).toHaveBeenCalled(); expect(collectionEditorStateService.getCollection).toHaveBeenCalled(); expect(collectionEditorStateService.getCollectionRights).toHaveBeenCalled(); })); it('should validate public collection', fakeAsync(() => { let mockPublicCollectionRights = new CollectionRights({ collection_id: collectionId, can_edit: true, can_unpublish: true, is_private: false, owner_names: [] }); let mockOnCollectionEventEmitter = new EventEmitter<void>(); let mockUndoRedoChangeAppliedEventEmitter = new EventEmitter<void>(); spyOnProperty(collectionEditorStateService, 'onCollectionInitialized') .and.returnValue(mockOnCollectionEventEmitter); spyOn(undoRedoService, 'getUndoRedoChangeEventEmitter') .and.returnValue(mockUndoRedoChangeAppliedEventEmitter); spyOn(urlService, 'getCollectionIdFromEditorUrl').and.returnValue( collectionId); spyOn(collectionEditorStateService, 'getCollection').and.returnValue( mockCollection); spyOn(collectionEditorStateService, 'getCollectionRights') .and.returnValue(mockPublicCollectionRights); spyOn( collectionValidationService, 'findValidationIssuesForPrivateCollection') .and.returnValue([]); spyOn( collectionValidationService, 'findValidationIssuesForPublicCollection') .and.returnValue([]); componentInstance.ngOnInit(); mockOnCollectionEventEmitter.emit(); tick(); mockUndoRedoChangeAppliedEventEmitter.emit(); tick(); expect(componentInstance.collectionId).toEqual(collectionId); expect(componentInstance.collection).toEqual(mockCollection); expect(urlService.getCollectionIdFromEditorUrl).toHaveBeenCalled(); expect(collectionEditorStateService.getCollection).toHaveBeenCalled(); expect(collectionEditorStateService.getCollectionRights).toHaveBeenCalled(); })); it('should test dropdown toggle functions', () => { componentInstance.editButtonHovering = false; componentInstance.onEditButtonHover(); expect(componentInstance.editButtonHovering).toBeTrue(); componentInstance.playerButtonHovering = false; componentInstance.onPlayerButtonHover(); expect(componentInstance.playerButtonHovering).toBeTrue(); }); it('should test getters', () => { componentInstance.validationIssues = []; componentInstance.collectionRights = { isPrivate: () => true } as CollectionRights; let changeCount = 10; let activeTabName = 'active tab'; spyOn(undoRedoService, 'getChangeCount').and.returnValue(changeCount); spyOn(collectionEditorStateService, 'isLoadingCollection').and.returnValues( true, false); spyOn(collectionEditorStateService, 'isSavingCollection').and.returnValues( true, false); spyOn(collectionEditorRoutingService, 'getActiveTabName').and.returnValue( activeTabName); expect(componentInstance.getWarningsCount()).toEqual(0); expect(componentInstance.getChangeListCount()).toEqual(changeCount); expect(componentInstance.isCollectionSaveable()).toBeTrue(); expect(componentInstance.isCollectionPublishable()).toBeFalse(); expect(componentInstance.isLoadingCollection()).toBeTrue(); expect(componentInstance.isLoadingCollection()).toBeFalse(); expect(componentInstance.isSaveInProgress()).toBeTrue(); expect(componentInstance.isSaveInProgress()).toBeFalse(); expect(componentInstance.getActiveTabName()).toEqual(activeTabName); }); it('should select switch tabs', () => { spyOn(collectionEditorRoutingService, 'navigateToEditTab'); spyOn(collectionEditorRoutingService, 'navigateToSettingsTab'); spyOn(collectionEditorRoutingService, 'navigateToStatsTab'); spyOn(collectionEditorRoutingService, 'navigateToHistoryTab'); componentInstance.selectMainTab(); componentInstance.selectSettingsTab(); componentInstance.selectStatsTab(); componentInstance.selectHistoryTab(); expect(collectionEditorRoutingService.navigateToEditTab).toHaveBeenCalled(); expect(collectionEditorRoutingService.navigateToSettingsTab) .toHaveBeenCalled(); expect(collectionEditorRoutingService.navigateToStatsTab) .toHaveBeenCalled(); expect(collectionEditorRoutingService.navigateToHistoryTab) .toHaveBeenCalled(); }); it('should save changes', () => { let commitMessage = 'success'; componentInstance.collectionRights = mockPrivateCollectionRights; spyOn(ngbModal, 'open').and.returnValue({ componentInstance: { isCollectionPrivate: false }, result: { then: ( successCallback: (commitMessage: string) => void, errorCallback: () => void) => { successCallback(commitMessage); errorCallback(); } } } as NgbModalRef); spyOn(collectionEditorStateService, 'saveCollection'); componentInstance.saveChanges(); expect(collectionEditorStateService.saveCollection).toHaveBeenCalledWith( commitMessage); }); it('should publish collection', fakeAsync(() => { componentInstance.collection = mockCollection; componentInstance.collectionRights = mockPrivateCollectionRights; spyOn(collectionRightsBackendApiService, 'setCollectionPublicAsync') .and.returnValue(Promise.resolve(mockPrivateCollectionRights)); spyOn(collectionEditorStateService, 'setCollectionRights'); componentInstance.publishCollection(); tick(); expect(collectionRightsBackendApiService.setCollectionPublicAsync) .toHaveBeenCalled(); expect(collectionEditorStateService.setCollectionRights).toHaveBeenCalled(); let mockCollectionWithoutMetadata = new Collection( 'id', '', '', '', [], null, '', 0, 1, []); componentInstance.collection = mockCollectionWithoutMetadata; spyOn(ngbModal, 'open').and.returnValue({ result: { then: ( successCallback: (commitMessage: string[]) => void, errorCallback: () => void) => { successCallback([]); errorCallback(); } } } as NgbModalRef); spyOn(collectionEditorStateService, 'saveCollection'); componentInstance.publishCollection(); tick(); expect(collectionEditorStateService.saveCollection).toHaveBeenCalled(); })); });
the_stack
var statusRefreshInterval = 2000; var configRefreshInterval = 120000; var statusWaitingRespTime = 1000; var configWaitingRespTime = 1500; var updateConfigAfterSendingGcodeTime = 200; var axisPrecision = 6; var heaterPrecision = 4; var fanPrecision = 3; var speedPrecision = 4; var configPrecision = 15; var defaultSpeed = 50; var gcodeHistorySize = 20; var sdRootAccessPrefix = '/sdcard'; // Commonly used styles/elements var controlTableClass = 'table table-condensed table-striped control-table'; var controlInputClass = 'form-control control-input'; var controlButtonClass = function(type) { return 'btn btn-'+type+' control-button'; } var controlEditingClass = 'control-editing'; var controlCancelButtonClass = controlButtonClass('default')+' control-cancel-button'; var gcodeTableClass = 'table table-condensed control-table gcode-table'; var removeIcon = <span className="glyphicon glyphicon-remove" style={{verticalAlign: 'middle', marginTop: '-0.1em'}} aria-hidden="true"></span>; function controlAllHead(labelText, buttons) { return ( <div className="flex-row"> <div style={{display: 'inline-block', alignSelf: 'flex-end'}}> {labelText} </div> <div style={{flexGrow: '1'}}> </div> <div className="btn-group"> {$.map(buttons, function(button, btnIndex) { var buttonText = button.text; var inputAttrs = button.attrs; var buttonClass = $has(button, 'class') ? button.class : 'warning'; var highlighted = $has(button, 'highlighted') ? button.highlighted : false; var className = controlButtonClass(buttonClass) + (highlighted ? ' control-button-highlight' : ''); return ( <button key={btnIndex} type="button" className={className} {...inputAttrs} >{buttonText}</button> ); })} </div> </div> ); } // Utility functions function orderObject(obj) { var arr = $.map(obj, function(val, key) { return {key: key, val: val}; }); arr.sort(function(x, y) { return +(x.key > y.key) - +(x.key < y.key); }); return arr; } function preprocessObjectForState(obj) { return { obj: obj, arr: orderObject(obj) }; } function $has(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); } function $bind(obj, func) { var objfunc = obj[func]; return objfunc.bind.apply(objfunc, [obj].concat(Array.prototype.slice.call(arguments, 2))); } function $toNumber(val) { return val - 0; } function $startsWith(data, start) { return data.substring(0, start.length) === start; } function $endsWith(data, end) { return data.substring(data.length - end.length, data.length) === end; } function encodeStrForCmd(val) { val = encodeURIComponent(val); // URI encoding val = val.replace(/%/g, '\\'); // Change % to \ val = val.replace(/\\2F/g, '/'); // Unescape forward-slashes return val; } function removeTrailingZerosInNumStr(num_str) { // 123.0200 => 123.02 // 123.0000 => 123 // 1200 => 1200 return num_str.replace(/(\.|(\.[0-9]*[1-9]))0*$/, function(match, p1, p2) { return typeof(p2) === 'string' ? p2 : ''; }); } function makeAjaxErrorStr(status, error) { var status_str = status+''; var error_str = error+''; var join_str = (status_str === '' || error_str === '') ? '' : ': '; return status_str+join_str+error_str; } // Status stables (axes, heaters, fans, speed) var AxesTable = React.createClass({ componentWillMount: function() { this.props.controller.setComponent(this); }, onInputEnter: function(axis_name) { this.axisGo(axis_name); }, getSpeed: function() { var speed = $toNumber(this.refs.speed.value); if (isNaN(speed) || speed == 0) { return {err: 'Bad speed'}; } return {res: speed*60}; }, axisGo: function(axis_name) { var action = 'Move axis'; var speedRes = this.getSpeed(); if ($has(speedRes, 'err')) { return showError(action, speedRes.err, null); } var target = this.props.controller.getNumberValue(axis_name); if (isNaN(target)) { return showError(action, 'Target value for axis '+axis_name+' is incorrect', null); } sendGcode(action, 'G0 R F'+speedRes.res.toString()+' '+axis_name+target.toString()); this.props.controller.cancel(axis_name); }, allAxesGo: function() { var cmdAxes = ''; var reasonAxes = []; var error = null; $.each(this.props.axes.arr, function(idx, axis) { var axis_name = axis.key; if (!this.props.controller.isEditing(axis_name)) { return; } reasonAxes.push(axis_name); var target = this.props.controller.getNumberValue(axis_name); if (isNaN(target)) { if (error === null) error = 'Target value for axis '+axis_name+' is incorrect'; return; } cmdAxes += ' '+axis_name+target.toString(); }.bind(this)); var axes = (reasonAxes.length > 1) ? 'axes' : 'axis'; var action = 'Move '+axes; if (error !== null) { return showError(action, error, null); } var speedRes = this.getSpeed(); if ($has(speedRes, 'err')) { return showError(action, speedRes.err, null); } if (cmdAxes.length !== 0) { sendGcode(action, 'G0 R F'+speedRes.res.toString()+cmdAxes); this.props.controller.cancelAll(); } }, btnHomeDefault: function() { sendGcode('Home axes', 'G28'); }, btnBedProbing: function() { sendGcode('Probe bed', 'G32'); }, btnMotorsOff: function() { sendGcode('Turn motors off', 'M18'); }, componentDidUpdate: function() { this.props.controller.componentDidUpdate(this.props.axes.obj); }, render: function() { this.props.controller.rendering(this.props.axes.obj); return ( <div className="flex-column"> <div className="flex-row control-bottom-margin"> <button type="button" className={controlButtonClass('primary')+' control-right-margin'} onClick={this.btnHomeDefault}>Home</button> {this.props.probe_present && <button type="button" className={controlButtonClass('primary')+' control-right-margin'} onClick={this.btnBedProbing}>Probe</button> } <button type="button" className={controlButtonClass('primary')} onClick={this.btnMotorsOff}>Motors off</button> <div className="flex-grow1"></div> <label htmlFor="speed" className="control-right-margin control-label">Speed [/s]</label> <input ref="speed" id="speed" type="number" className={controlInputClass} style={{width: '60px'}} defaultValue={defaultSpeed} /> </div> <table className={controlTableClass}> <colgroup> <col span="1" style={{width: '55px'}} /> <col span="1" style={{width: '115px'}} /> <col span="1" style={{width: '205px'}} /> </colgroup> <thead> <tr> <th>Axis</th> <th>Planned</th> <th>{controlAllHead('Go to', [{text: 'Go', attrs: {disabled: !this.props.controller.isEditingAny(), onClick: this.allAxesGo}}])}</th> </tr> </thead> <tbody> {$.map(this.props.axes.arr, function(axis) { var dispPos = axis.val.pos.toPrecision(axisPrecision); var ecInputs = this.props.controller.getRenderInputs(axis.key, dispPos); return ( <tr key={axis.key}> <td className="nowrap"><b>{axis.key}</b></td> <td className="nowrap">{dispPos}</td> <td> <div className="input-group"> <input type="number" className={controlInputClass+' '+ecInputs.class} value={ecInputs.value} ref={'target_'+axis.key} {...makeEcInputProps(ecInputs)} /> <span className="input-group-btn"> <button type="button" className={controlCancelButtonClass} disabled={!ecInputs.editing} onClick={ecInputs.onCancel} aria-label="Cancel">{removeIcon}</button> <button type="button" className={controlButtonClass('warning')} onClick={$bind(this, 'axisGo', axis.key)}>Go</button> </span> </div> </td> </tr> ); }.bind(this))} </tbody> </table> </div> ); } }); var HeatersTable = React.createClass({ componentWillMount: function() { this.props.controller.setComponent(this); }, onInputEnter: function(heater_name) { this.heaterSet(heater_name); }, getHeaterControlCommand: function(heater_name) { var heaterType = heater_name.substring(0, 1); var heaterNumber = heater_name.substring(1); var mCommand; if (heaterType == 'T') { mCommand = 'M104'; } else if (heaterType == 'B') { mCommand = 'M140'; } else if (heaterType == 'C') { mCommand = 'M141'; } else { return {err: 'Unsupported heater type for '+heater_name}; } return {res: mCommand+' P'+heaterNumber}; }, makeSetHeaterGcode: function(heater_name) { var baseCommand = this.getHeaterControlCommand(heater_name); if ($has(baseCommand, 'err')) { return {err: baseCommand.err}; } var target = this.props.controller.getNumberValue(heater_name); if (isNaN(target)) { return {err: 'Target value for heater '+heater_name+' is incorrect'}; } return {res: baseCommand.res+' S'+target.toString()+' F'}; }, heaterSet: function(heater_name) { var action = 'Set heater setpoint'; var makeRes = this.makeSetHeaterGcode(heater_name); if ($has(makeRes, 'err')) { return showError(action, makeRes.err, null); } sendGcode(action, makeRes.res); this.props.controller.cancel(heater_name); }, heaterOff: function(heater_name) { var action = 'Turn off heater'; var baseCommand = this.getHeaterControlCommand(heater_name); if ($has(baseCommand, 'err')) { return showError(action, baseCommand.err, null); } sendGcode(action, baseCommand.res+' Snan F'); this.props.controller.cancel(heater_name); }, allHeatersSet: function() { var cmds = []; var error = null; var reasonHeaters = []; $.each(this.props.heaters.arr, function(idx, heater) { var heater_name = heater.key; if (this.props.controller.isEditing(heater_name)) { reasonHeaters.push(heater_name); var makeRes = this.makeSetHeaterGcode(heater_name); if ($has(makeRes, 'err')) { if (error === null) error = makeRes.err; return; } cmds.push(makeRes.res); } }.bind(this)); var setpoints = (reasonHeaters.length > 1) ? 'setpoints' : 'setpoint'; var action = 'Set heater '+setpoints; if (error !== null) { return showError(action, error, null); } if (cmds.length !== 0) { sendGcodes(action, cmds); this.props.controller.cancelAll(); } }, render: function() { this.props.controller.rendering(this.props.heaters.obj); return ( <table className={controlTableClass}> <colgroup> <col span="1" style={{width: '55px'}} /> <col span="1" style={{width: '60px'}} /> <col span="1" style={{width: '78px'}} /> <col span="1" style={{width: '185px'}} /> </colgroup> <thead> <tr> <th>Heater</th> <th>Actual</th> <th>Target</th> <th>{controlAllHead('Control', [{text: 'Set', attrs: {disabled: !this.props.controller.isEditingAny(), onClick: this.allHeatersSet}}])}</th> </tr> </thead> <tbody> {$.map(this.props.heaters.arr, function(heater) { var dispActual = heater.val.current.toPrecision(heaterPrecision); var isOff = (heater.val.target === -Infinity); var dispTarget = isOff ? 'off' : heater.val.target.toPrecision(heaterPrecision); var editTarget = isOff ? '' : dispTarget; var ecInputs = this.props.controller.getRenderInputs(heater.key, editTarget); return ( <tr key={heater.key}> <td><b>{heater.key}</b>{(heater.val.error ? " ERR" : "")}</td> <td>{dispActual}</td> <td>{dispTarget}</td> <td> <div className="input-group"> <input type="number" className={controlInputClass+' '+ecInputs.class} value={ecInputs.value} ref={'target_'+heater.key} {...makeEcInputProps(ecInputs)} /> <span className="input-group-btn"> <button type="button" className={controlCancelButtonClass} disabled={!ecInputs.editing} onClick={ecInputs.onCancel} aria-label="Cancel">{removeIcon}</button> <button type="button" className={controlButtonClass('warning')} onClick={$bind(this, 'heaterSet', heater.key)}>Set</button> <button type="button" className={controlButtonClass('primary')} onClick={$bind(this, 'heaterOff', heater.key)}>Off</button> </span> </div> </td> </tr> ); }.bind(this))} </tbody> </table> ); }, componentDidUpdate: function() { this.props.controller.componentDidUpdate(this.props.heaters.obj); } }); var FansTable = React.createClass({ componentWillMount: function() { this.props.controller.setComponent(this); }, onInputEnter: function(fan_name) { this.fanSet(fan_name); }, getFanNumber: function(fan_name) { if (fan_name.substring(0, 1) != 'F') { return {err: 'Bad fan name for '+fan_name}; } return {res: fan_name.substring(1)}; }, makeSetFanGcode: function(fan_name) { var fan_number = this.getFanNumber(fan_name); if ($has(fan_number, 'err')) { return {err: fan_number.err}; } var target = this.props.controller.getNumberValue(fan_name); if (isNaN(target)) { return {err: 'Target value for fan '+fan_name+' is incorrect'}; } return {res: 'M106 P'+fan_number.res+' S'+(target/100*255).toPrecision(fanPrecision+3)+' F'}; }, fanSet: function(fan_name) { var action = 'Set fan target'; var makeRes = this.makeSetFanGcode(fan_name); if ($has(makeRes, 'err')) { return showError(action, makeRes.err, null); } sendGcode(action, makeRes.res); this.props.controller.cancel(fan_name); }, fanOff: function(fan_name) { var action = 'Turn off fan'; var fan_number = this.getFanNumber(fan_name); if ($has(fan_number, 'err')) { return showError(action, fan_number.err, null); } sendGcode(action, 'M107 P'+fan_number.res+' F'); this.props.controller.cancel(fan_name); }, allFansSet: function() { var cmds = []; var error = null; var reasonFans = []; $.each(this.props.fans.arr, function(idx, fan) { var fan_name = fan.key; if (this.props.controller.isEditing(fan_name)) { reasonFans.push(fan_name); var makeRes = this.makeSetFanGcode(fan_name); if ($has(makeRes, 'err')) { if (error === null) error = makeRes.err; return; } cmds.push(makeRes.res); } }.bind(this)); var targets = (reasonFans.length > 1) ? 'targets' : 'target'; var action = 'Set fan '+targets; if (error !== null) { return showError(action, error, null); } if (cmds.length !== 0) { sendGcodes(action, cmds); this.props.controller.cancelAll(); } }, render: function() { this.props.controller.rendering(this.props.fans.obj); return ( <table className={controlTableClass}> <colgroup> <col span="1" style={{width: '55px'}} /> <col span="1" style={{width: '83px'}} /> <col span="1" /> <col span="1" style={{width: '200px'}} /> </colgroup> <thead> <tr> <th>Fan</th> <th>Target <span className="notbold">[%]</span></th> <th></th> <th>{controlAllHead('Control', [{text: 'Set', attrs: {disabled: !this.props.controller.isEditingAny(), onClick: this.allFansSet}}])}</th> </tr> </thead> <tbody> {$.map(this.props.fans.arr, function(fan) { var isOff = (fan.val.target === 0); var editTarget = (fan.val.target * 100).toPrecision(fanPrecision); var dispTarget = isOff ? 'off' : editTarget; var ecInputs = this.props.controller.getRenderInputs(fan.key, editTarget); return ( <tr key={fan.key}> <td><b>{fan.key}</b></td> <td>{dispTarget}</td> <td></td> <td> <div className="input-group"> <input type="number" className={controlInputClass+' '+ecInputs.class} value={ecInputs.value} ref={'target_'+fan.key} min="0" max="100" {...makeEcInputProps(ecInputs)} /> <span className="input-group-btn"> <button type="button" className={controlCancelButtonClass} disabled={!ecInputs.editing} onClick={ecInputs.onCancel} aria-label="Cancel">{removeIcon}</button> <button type="button" className={controlButtonClass('warning')} onClick={$bind(this, 'fanSet', fan.key)}>Set</button> <button type="button" className={controlButtonClass('primary')} onClick={$bind(this, 'fanOff', fan.key)}>Off</button> </span> </div> </td> </tr> ); }.bind(this))} </tbody> </table> ); }, componentDidUpdate: function() { this.props.controller.componentDidUpdate(this.props.fans.obj); } }); var SpeedTable = React.createClass({ componentWillMount: function() { this.props.controller.setComponent(this); }, onInputEnter: function(id) { this.speedRatioSet(); }, speedRatioSet: function() { var action = 'Set speed ratio'; var target = this.props.controller.getNumberValue('S'); if (isNaN(target)) { return showError(action, 'Speed ratio value is incorrect', null); } sendGcode(action, 'M220 S'+target.toPrecision(speedPrecision+3)); this.props.controller.cancel('S'); }, speedRatioReset: function() { sendGcode('Reset speed ratio', 'M220 S100'); this.props.controller.cancel('S'); }, componentDidUpdate: function() { this.props.controller.componentDidUpdate({'S': null}); }, render: function() { this.props.controller.rendering({'S': null}); var dispRatio = (this.props.speedRatio*100).toPrecision(speedPrecision); var ecInputs = this.props.controller.getRenderInputs('S', dispRatio); return ( <table className={controlTableClass+' table-noheader'}> <colgroup> <col span="1" style={{width: '120px'}} /> <col span="1" style={{width: '50px'}} /> <col span="1" style={{width: '195px'}} /> </colgroup> <tbody> <tr> <td className="parameter-table-name">Speed ratio <span className="notbold">[%]</span></td> <td>{dispRatio}</td> <td> <div className="input-group"> <input type="number" className={controlInputClass+' '+ecInputs.class} value={ecInputs.value} ref="target_S" min="10" max="1000" {...makeEcInputProps(ecInputs)} /> <span className="input-group-btn"> <button type="button" className={controlCancelButtonClass} disabled={!ecInputs.editing} onClick={ecInputs.onCancel} aria-label="Cancel">{removeIcon}</button> <button type="button" className={controlButtonClass('warning')} onClick={this.speedRatioSet}>Set</button> <button type="button" className={controlButtonClass('primary')} onClick={this.speedRatioReset}>Off</button> </span> </div> </td> </tr> </tbody> </table> ); } }); // Panel at the top var TopPanel = React.createClass({ render: function() { var cmdStatusClass = ''; var cmdStatusText = ''; if (this.props.gcodeQueue.length > 0) { var entry = this.props.gcodeQueue[0]; cmdStatusClass = 'constatus-waitresp'; cmdStatusText = 'Executing: '+entry.reason; } var activeStatusClass = ''; var activeStatusText = ''; if (this.props.active === true) { activeStatusClass = 'activestatus-active'; activeStatusText = 'Active'; } else if (this.props.active === false) { activeStatusClass = 'activestatus-inactive'; activeStatusText = 'Inactive'; } var condition = this.props.statusUpdater.getCondition(); var statusText = ''; var statusClass = ''; if (condition === 'WaitingResponse') { statusText = 'Waiting for machine status'; statusClass = 'constatus-waitresp'; } else if (condition === 'Error') { statusText = 'Communication error'; statusClass = 'constatus-error'; } var fullscreenIcon = this.props.is_fullscreen ? 'glyphicon-unchecked' : 'glyphicon-fullscreen'; var fullscreenAction = this.props.is_fullscreen ? leaveFullscreen : goFullscreen; return ( <div className="flex-row flex-align-center"> <h1>Aprinter Web Interface</h1> <div className="toppanel-spacediv"></div> <span className={'activestatus '+activeStatusClass}>{activeStatusText}</span> <div className="toppanel-spacediv"></div> <span className={'constatus '+cmdStatusClass}>{cmdStatusText}</span> <div className="flex-grow1"></div> <span className={'constatus '+statusClass}>{statusText}</span> <div className="toppanel-spacediv"></div> <button type="button" className={controlButtonClass('info')+' top-btn-margin'} onClick={startRefreshAll}>Refresh</button> <button type="button" className={controlButtonClass('default')+' top-btn-margin'} onClick={() => fullscreenAction()}> <span className={'glyphicon '+fullscreenIcon}></span> </button> </div> ); } }); // Configuration options table function normalizeIpAddr(input) { var comps = input.split('.'); if (comps.length != 4) { return {err: 'Invalid number of address components'}; } var res_comps = []; $.each(comps, function(idx, comp) { if (/^[0-9]{1,3}$/.test(comp)) { var comp_val = parseInt(comp, 10); if (comp_val <= 255) { res_comps.push(comp_val.toString(10)); } } }); if (res_comps.length != 4) { return {err: 'Invalid address component'}; } return {res: res_comps.join('.')}; } function normalizeMacAddr(input) { var comps = input.split(':'); if (comps.length != 6) { return {err: 'Invalid number of address components'}; } var res_comps = []; $.each(comps, function(idx, comp) { if (/^[0-9A-Fa-f]{1,2}$/.test(comp)) { var res_str = parseInt(comp, 16).toString(16); if (res_str.length == 1) { res_str = "0" + res_str; } res_comps.push(res_str); } }); if (res_comps.length != 6) { return {err: 'Invalid address component'}; } return {res: res_comps.join(':').toUpperCase()}; } var ConfigTypes = { 'bool': { display: 'bool', input: {type: 'select', options: ['false', 'true']}, convertForDisp: function(string) { if (string !== '0' && string !== '1') { return {err: 'Not 0 or 1'}; } return {res: string === '0' ? 'false' : 'true'}; }, convertForSet: function(string) { if (string !== 'false' && string !== 'true') { return {err: 'Not false or true'}; } return {res: string === 'false' ? '0' : '1'}; } }, 'double': { display: 'double', input: {type: 'number'}, convertForDisp: function(string) { var num = Number(string); if (isNaN(num)) { return {err: 'Not a numeric string'}; } return {res: removeTrailingZerosInNumStr(num.toPrecision(configPrecision))}; }, convertForSet: function(string) { return {res: string}; } }, 'ip_addr': { display: 'ip-addr', input: {type: 'text'}, convertForDisp: function(string) { return normalizeIpAddr(string); }, convertForSet: function(string) { return normalizeIpAddr(string); } }, 'mac_addr': { display: 'mac-addr', input: {type: 'text'}, convertForDisp: function(string) { return normalizeMacAddr(string); }, convertForSet: function(string) { return normalizeMacAddr(string); } }, 'text': { display: 'unknown', input: {type: 'text'}, convertForDisp: function(string) { return {res: string}; }, convertForSet: function(string) { return {res: string}; } } }; function getOptionTypeImpl(type) { return $has(ConfigTypes, type) ? ConfigTypes[type] : ConfigTypes['text']; } function preprocessOptionsList(options) { var result = {}; $.map(options, function(option) { var eqIndex = option.nameval.indexOf('='); var optionName = option.nameval.substring(0, eqIndex); var optionValue = option.nameval.substring(eqIndex+1); result[optionName] = $.extend({name: optionName, value: optionValue}, option); }); return result; } function updateConfigAfterGcode(entry) { configUpdater.requestUpdate(true); } var ConfigTab = React.createClass({ getInitialState: function() { return { compact: false, }; }, componentWillMount: function() { this.props.controller.setComponent(this); }, onInputEnter: function(option_name) { this.optionSet(option_name); }, makeSetOptionGcode: function(option_name) { var target = this.props.controller.getValue(option_name); var typeImpl = getOptionTypeImpl(this.props.options.obj[option_name].type); var convRes = typeImpl.convertForSet(target); if ($has(convRes, 'err')) { return convRes; } return {res: 'M926 I'+option_name+' V'+encodeStrForCmd(convRes.res)}; }, optionSet: function(option_name) { var action = 'Set option'; var makeRes = this.makeSetOptionGcode(option_name); if ($has(makeRes, 'err')) { return showError(action, makeRes.err, null); } sendGcode(action, makeRes.res, updateConfigAfterGcode); this.props.controller.cancel(option_name); }, allOptionsSet: function() { var cmds = []; var error = null; var reasonOptions = []; $.each(this.props.options.arr, function(idx, option) { var option_name = option.key; if (this.props.controller.isEditing(option_name)) { reasonOptions.push(option_name); var makeRes = this.makeSetOptionGcode(option_name); if ($has(makeRes, 'err')) { if (error === null) error = makeRes.err; return; } cmds.push(makeRes.res); } }.bind(this)); var options = (reasonOptions.length > 1) ? 'options' : 'option'; var action = 'Set '+options; if (error !== null) { return showError(action, error, null); } if (cmds.length !== 0) { sendGcodes(action, cmds, updateConfigAfterGcode); this.props.controller.cancelAll(); } }, applyConfig: function() { sendGcode('Apply config', 'M930'); }, saveConfig: function() { sendGcode('Save config to SD', 'M500'); }, restoreConfig: function() { sendGcode('Restore config from SD', 'M501', updateConfigAfterGcode); }, onContainerResized: function(width) { var compact = width < 520; if (this.state.compact !== compact) { this.setState({compact: compact}); } }, componentDidUpdate: function() { this.props.controller.componentDidUpdate(this.props.options.obj); }, render: function() { this.props.controller.rendering(this.props.options.obj); var condition = this.props.configUpdater.getCondition(); var statusText = ''; var statusClass = ''; if (condition === 'WaitingResponse') { statusText = 'Waiting for current configuration'; statusClass = 'constatus-waitresp'; } else if (condition === 'Error') { statusText = 'Error refreshing configuration'; statusClass = 'constatus-error'; } var colgroup = ( <colgroup> <col span="1" style={{width: '188px'}} /> {this.state.compact ? null : ( <col span="1" style={{width: '72px'}} /> )} <col span="1" style={{width: '230px'}} /> </colgroup> ); return ( <div className="flex-column flex-shrink1 flex-grow1 min-height0"> <div className="flex-row control-bottom-margin"> <button type="button" className={controlButtonClass('primary')+' control-right-margin'} onClick={this.saveConfig}>Save to SD</button> <button type="button" className={controlButtonClass('primary')} onClick={this.restoreConfig}>Restore from SD</button> <div className="flex-grow1"></div> <span className={'constatus-control '+statusClass}>{statusText}</span> </div> <div className="flex-row"> <div className="flex-grow1" style={{width: 0}}> <table className={controlTableClass}> {colgroup} <thead> <tr> <th>Option</th> {this.state.compact ? null : ( <th>Type</th> )} <th>{controlAllHead('Value', [ {text: 'Set', class: 'success', attrs: {disabled: !this.props.controller.isEditingAny(), onClick: this.allOptionsSet}}, {text: 'Apply', highlighted: this.props.configDirty, attrs: {disabled: !this.props.configDirty, onClick: this.applyConfig}} ])}</th> </tr> </thead> </table> </div> <div className="scroll-y" style={{visibility: 'hidden'}} /> </div> <div className="flex-shrink1 flex-grow1 scroll-y config-options-area"> <table className={controlTableClass+' table-noheader config-options-table'}> {colgroup} <tbody> {$.map(this.props.options.arr, function(option) { var optionName = option.key; return <ConfigRow key={optionName} ref={optionName} option={option.val} compact={this.state.compact} parent={this} />; }.bind(this))} </tbody> </table> </div> </div> ); } }); var ConfigRow = React.createClass({ shouldComponentUpdate: function(nextProps, nextState) { return this.props.parent.props.controller.rowIsDirty(this.props.option.name) || nextProps.compact !== this.props.compact; }, componentDidUpdate: function() { this.props.parent.props.controller.rowComponentDidUpdate(this.props.option.name); }, render: function() { var option = this.props.option; var typeImpl = getOptionTypeImpl(option.type); var valueParsed = typeImpl.convertForDisp(option.value); var valueConv = $has(valueParsed, 'err') ? option.value : valueParsed.res; var ecInputs = this.props.parent.props.controller.getRenderInputs(option.name, valueConv); var onClickSet = $bind(this.props.parent, 'optionSet', option.name); return ( <tr> <td><b>{option.name}</b></td> {this.props.compact ? null : ( <td>{typeImpl.display}</td> )} <td> <div className="input-group"> {typeImpl.input.type === 'select' ? ( <select className={controlInputClass+' '+ecInputs.class} value={ecInputs.value} ref="target" {...makeEcInputProps(ecInputs)} > {$.map(typeImpl.input.options, function(option_value, optionIndex) { return <option key={optionIndex} value={option_value}>{option_value}</option>; })} </select> ) : ( <input type={typeImpl.input.type} className={controlInputClass+' '+ecInputs.class} value={ecInputs.value} ref="target" {...makeEcInputProps(ecInputs)} /> )} <span className="input-group-btn"> <button type="button" className={controlCancelButtonClass} disabled={!ecInputs.editing} onClick={ecInputs.onCancel} aria-label="Cancel">{removeIcon}</button> <button type="button" className={controlButtonClass('success')} onClick={onClickSet}>Set</button> </span> </div> </td> </tr> ); } }); // SD-card tab var SdCardTab = React.createClass({ getInitialState: function() { return { desiredDir: '/', uploadFileName: null, destinationPath: '/upload.gcode', compact: false, }; }, doMount: function() { sendGcode('Mount SD-card', 'M21'); }, doUnmount: function() { sendGcode('Unmount SD-card', 'M22'); }, doMountRw: function() { sendGcode('Mount SD-card read-write', 'M21 W'); }, doRemountRo: function() { sendGcode('Remount SD-card read-only', 'M22 R'); }, onDirInputChange: function(event) { this.setState({desiredDir: event.target.value}); }, onDirInputKeyPress: function(event) { if (event.key === 'Enter') { this.doNavigateTo(this.state.desiredDir); } }, navigateToDesiredDir: function() { this.doNavigateTo(this.state.desiredDir); }, onDirUpClick: function() { var controller_dirlist = this.props.controller_dirlist; var loadedDir = controller_dirlist.getLoadedDir(); var loadedResult = controller_dirlist.getLoadedResult(); if (loadedDir !== null && loadedResult.dir !== '/') { var parentDir = getParentDirectory(loadedResult.dir); this.doNavigateTo(parentDir); } }, doNavigateTo: function(desiredDir) { if ($startsWith(desiredDir, '/')) { desiredDir = removeRedundantSlashes(desiredDir); if (this.state.desiredDir !== desiredDir) { this.setState({desiredDir: desiredDir}); } this.props.controller_dirlist.requestDir(desiredDir); this.forceUpdate(); } }, onFileInputChange: function(event) { var uploadFileName = (event.target.files.length > 0) ? event.target.files[0].name : null; // IE raises this event when we manually clear the file-input after // a completed upload (in componentDidUpdate), so we need this check // so that the success message does not disappear immediately. if (uploadFileName !== null) { this.setState({uploadFileName: uploadFileName}); this.props.controller_upload.clearResult(); } }, onDestinationInputChange: function(event) { this.setState({destinationPath: event.target.value}); this.props.controller_upload.clearResult(); }, onUploadClick: function(event) { var controller_upload = this.props.controller_upload; if (!controller_upload.isUploading() && this.refs.file_input.files.length > 0 && isDestPathValid(this.state.destinationPath)) { var file = this.refs.file_input.files[0]; controller_upload.startUpload(file.name, removeRedundantSlashes(this.state.destinationPath), file); this.forceUpdate(); } }, setDestinationPath: function(file_path) { this.setState({destinationPath: file_path}); }, onContainerResized: function(width) { var compact = width < 520; if (this.state.compact !== compact) { this.setState({compact: compact}); } }, componentDidUpdate: function() { var controller_upload = this.props.controller_upload; if (controller_upload.isResultPending()) { controller_upload.ackResult(); var dest_path = controller_upload.getDestinationPath(); var loaded_dir = this.props.controller_dirlist.getLoadedDir(); if (loaded_dir !== null && pathIsInDirectory(dest_path, loaded_dir)) { this.doNavigateTo(loaded_dir); } if (controller_upload.getUploadError() === null) { this.refs.file_input.value = null; this.setState({uploadFileName: null}); } } }, render: function() { var sdcard = this.props.sdcard; var controller_dirlist = this.props.controller_dirlist; var controller_upload = this.props.controller_upload; var canUnmount = (sdcard !== null && sdcard.mntState === 'Mounted'); var canMount = (sdcard !== null && sdcard.mntState === 'NotMounted'); var canRemountRo = (sdcard !== null && sdcard.mntState === 'Mounted' && sdcard.rwState == 'ReadWrite'); var canMountRw = (sdcard !== null && (sdcard.mntState === 'NotMounted' || (sdcard.mntState === 'Mounted' && sdcard.rwState === 'ReadOnly'))); var unmountText = 'Unmount'; var mountText = 'Mount'; var remountRoText = 'Remount R/O'; var mountRwText = 'Mount R/W'; var mountButtons; if (!this.state.compact) { mountButtons = [ <button key="btn_unmount" type="button" className={controlButtonClass('primary')+' control-right-margin'} disabled={!canUnmount} onClick={this.doUnmount}>{unmountText}</button>, <button key="btn_mount" type="button" className={controlButtonClass('primary')+' control-right-margin'} disabled={!canMount} onClick={this.doMount}>{mountText}</button>, <button key="btn_remountro" type="button" className={controlButtonClass('primary')+' control-right-margin'} disabled={!canRemountRo} onClick={this.doRemountRo}>{remountRoText}</button>, <button key="btn_mountrw" type="button" className={controlButtonClass('primary')+' control-right-margin'} disabled={!canMountRw} onClick={this.doMountRw}>{mountRwText}</button> ]; } else { var useMountButton = sdcard === null || sdcard.mntState === 'NotMounted' || sdcard.mntState === 'Mounting'; var useMountRwButton = useMountButton || (sdcard.mntState === 'Mounted' && (sdcard.rwState === 'ReadOnly' || sdcard.rwState === 'MountingRW')); var mnText; var mnAction; var mnEnabled; if (useMountButton) { mnText = mountText; mnAction = this.doMount; mnEnabled = canMount; } else { mnText = unmountText; mnAction = this.doUnmount; mnEnabled = canUnmount; } var rwText; var rwAction; var rwEnabled; if (useMountRwButton) { rwText = mountRwText; rwAction = this.doMountRw; rwEnabled = canMountRw; } else { rwText = remountRoText; rwAction = this.doRemountRo; rwEnabled = canRemountRo; } mountButtons = [ <button key="btn_mn" type="button" className={controlButtonClass('primary')+' fixed-width-button control-right-margin'} disabled={!mnEnabled} onClick={mnAction}>{mnText}</button>, <button key="btn_rw" type="button" className={controlButtonClass('primary')+' fixed-width-button control-right-margin'} disabled={!rwEnabled} onClick={rwAction}>{rwText}</button> ]; } var stateText = (sdcard === null) ? 'Disabled' : ((sdcard.mntState === 'Mounted') ? translateRwState(sdcard.rwState) : translateMntState(sdcard.mntState)); var canNavigate = $startsWith(this.state.desiredDir, '/'); var loadedDir = controller_dirlist.getLoadedDir(); var loadedResult = controller_dirlist.getLoadedResult(); var canGoUp = (loadedDir !== null && loadedResult.dir !== '/'); var loadingDir = controller_dirlist.getLoadingDir(); var uploadFileText = (this.state.uploadFileName !== null) ? this.state.uploadFileName : 'No file chosen'; var uploadFileClass = (this.state.uploadFileName !== null) ? 'label-info' : 'label-default'; var isUploading = controller_upload.isUploading(); var canUpload = (!isUploading && this.state.uploadFileName !== null && isDestPathValid(this.state.destinationPath)); var uploadStatus; var uploadStatusClass; var uploadedFile = null; if (isUploading) { var srcFileName = controller_upload.getSourceFileName(); var destPath = controller_upload.getDestinationPath(); var totalBytes = controller_upload.getTotalBytes(); var uploadedBytes = controller_upload.getUploadedBytes(); var percent = ((totalBytes == 0 ? 0 : (uploadedBytes / totalBytes)) * 100.0).toFixed(0); uploadStatus = 'Uploading '+srcFileName+' to '+destPath+' ('+percent+'%, '+uploadedBytes+'/'+totalBytes+')'; uploadStatusClass = 'upload-status-running'; } else if (controller_upload.haveResult()) { var srcFileName = controller_upload.getSourceFileName(); var destPath = controller_upload.getDestinationPath(); var error = controller_upload.getUploadError(); var result = (error !== null) ? ('failed: '+error) : 'succeeded'; uploadStatus = 'Upload of '+srcFileName+' to '+destPath+' '+result+'.'; uploadStatusClass = (error !== null) ? 'upload-status-error' : 'upload-status-success'; if (error === null) { uploadedFile = destPath; } } else { uploadStatus = 'Upload not started.'; uploadStatusClass = ''; } return ( <div className="flex-column flex-shrink1 flex-grow1 min-height0" ref="self"> <div className="flex-row control-bottom-margin"> {mountButtons} <span className="flex-grow1 sdcard-state">{stateText}</span> </div> <div className="control-bottom-margin items-margin"> <div className="flex-row flex-align-center flex-wrap"> <div className="control-right-margin"> <label className="btn btn-default btn-file control-button control-right-margin"> Select file <input ref="file_input" type="file" style={{display: 'none'}} onChange={this.onFileInputChange} /> </label> <span className={'label '+uploadFileClass}>{uploadFileText}</span> </div> <div className="flex-grow1 flex-row flex-align-center"> <label htmlFor="upload_path" className="control-label control-right-margin">Save to</label> <input type="text" className={controlInputClass+' flex-grow1 control-right-margin'} style={{width: '150px'}} value={this.state.destinationPath} onChange={this.onDestinationInputChange} placeholder="Destination file path" /> <button type="button" className={controlButtonClass('primary')} onClick={this.onUploadClick} disabled={!canUpload}>Upload</button> </div> </div> </div> <div className="flex-row flex-align-center control-bottom-margin"> <span className={uploadStatusClass+ ' flex-shrink1'}> {uploadStatus} {(uploadedFile === null) ? null : ' '} {(uploadedFile === null) ? null : ( <a href="javascript:void(0)" onClick={() => executeSdCardFile(uploadedFile)}>Execute</a> )} </span> <div className="flex-grow1"></div> {(loadingDir === null) ? null : <span className='dirlist-loading-text constatus-waitresp'>Loading directory {loadingDir}</span>} </div> <div className="control-bottom-margin" style={{display: 'table', width: '100%'}}> <div style={{display: 'table-cell', 'width': '100%'}}> <div className="input-group control-right-margin"> <label htmlFor="sdcard_set_dir" className="input-group-addon control-ig-label">Show directory</label> <input id="sdcard_set_dir" type="text" className={controlInputClass} placeholder="Directory to list" value={this.state.desiredDir} onChange={this.onDirInputChange} onKeyPress={this.onDirInputKeyPress} /> <span className="input-group-btn"> <button type="button" className={controlButtonClass('primary')} disabled={!canNavigate} onClick={this.navigateToDesiredDir}>Show</button> </span> </div> </div> <span style={{display: 'table-cell', width: '1%', verticalAlign: 'middle'}}> <button type="button" className={controlButtonClass('primary')} disabled={!canGoUp} onClick={this.onDirUpClick}>Up</button> </span> </div> <SdCardDirList dirlist={loadedResult} compact={this.state.compact} navigateTo={this.doNavigateTo} saveTo={this.setDestinationPath} controller={this.props.controller_dirlist} /> </div> ); } }); var SdCardDirList = React.createClass({ onDirClicked: function(dir_path) { this.props.navigateTo(dir_path); }, onUploadOverClicked: function(file_path) { this.props.saveTo(file_path); }, shouldComponentUpdate: function(nextProps, nextState) { return this.props.controller.isDirty() || nextProps.compact !== this.props.compact; }, componentDidUpdate: function() { this.refs.scroll_div.scrollTop = 0;; }, render: function() { this.props.controller.clearDirty(); var type_width = '65px'; var dirlist = this.props.dirlist; if (dirlist === null) { dirlist = {dir: 'No directory shown', files: []}; } var files_sorted = Array.prototype.slice.call(dirlist.files).sort(); var dir = dirlist.dir; return ( <div className="flex-column flex-shrink1 flex-grow1 min-height0"> <table className={controlTableClass}> <colgroup> {this.props.compact ? null : <col span="1" style={{width: type_width}} />} <col span="1" style={{width: '60px'}} /> <col span="1" /> </colgroup> <thead> <tr> {this.props.compact ? null : <th>Type</th>} <th>Name</th> <th style={{textAlign: 'right'}}>{dirlist.dir}</th> </tr> </thead> </table> <div ref="scroll_div" className="flex-shrink1 flex-grow1 scroll-y dir-list-area"> <table className={controlTableClass+' table-noheader'}> <colgroup> {this.props.compact ? null : <col span="1" style={{width: type_width}} />} <col span="1" /> </colgroup> <tbody> {$.map(files_sorted, function(file, file_idx) { var is_dir = $startsWith(file, '*'); var file_type; var file_name; if (is_dir) { file_type = 'Folder'; file_name = file.substring(1); } else { file_type = 'File'; file_name = file; } var file_path = dir+($endsWith(dir, '/')?'':'/')+file_name; return ( <tr key={file_path} className="dirlist-row"> {this.props.compact ? null : <td style={{verticalAlign: 'top'}}>{file_type}</td>} {is_dir ? ( <td className="control-table-link"> <a href="javascript:void(0)" onClick={this.onDirClicked.bind(this, file_path)}>{file_name}</a> </td> ) : ( <td> <div className="flex-row"> <div className="flex-grow1 width0 files-right-margin">{file_name}</div> <a className="files-right-margin" href={sdRootAccessPrefix+file_path} target="_blank">Download</a> <a className="files-right-margin" href="javascript:void(0)" onClick={this.onUploadOverClicked.bind(this, file_path)}>Upload over</a> <a href="javascript:void(0)" onClick={() => executeSdCardFile(file_path)}>Execute</a> </div> </td> )} </tr> ); }.bind(this))} </tbody> </table> </div> </div> ); } }); function translateMntState(mntState) { if (mntState === 'NotMounted') return 'Not mounted'; if (mntState === 'Mounting') return 'Mounting'; return mntState; } function translateRwState(rwState) { if (rwState === 'ReadOnly') return 'Mounted R/O'; if (rwState === 'MountingRW') return 'Mounting R/W'; if (rwState === 'ReadWrite') return 'Mounted R/W'; if (rwState === 'RemountingRO') return 'Remounting R/O'; return rwState; } function removeRedundantSlashes(str) { str = str.replace(/\/\/+/g, '/'); if (str.length > 1) { str = str.replace(/\/$/, ''); } return str; } function isDestPathValid(str: string) { return ($startsWith(str, '/') && !$endsWith(str, '/')); } function pathIsInDirectory(path: string, dir_path: string) { var dir_prefix = $endsWith(dir_path, '/') ? dir_path : dir_path+'/'; return $startsWith(path, dir_prefix); } function getParentDirectory(path: string) { var parentDir = path.replace(/\/[^\/]+$/, ''); return (path !== '' && parentDir === '') ? '/' : parentDir; } function executeSdCardFile(file_path) { showConfirmDialog('Confirm execution of file from SD-card', file_path, 'Cancel', 'Execute', () => { var cmd = 'M32 F'+encodeStrForCmd(file_path); sendGcode('Execute file', cmd); }); } // Gcode execution component var GcodeTable = React.createClass({ render: function() { var colgroup = ( <colgroup> <col span="1" style={{width: '162px'}} /> <col span="1" style={{width: '200px'}} /> </colgroup> ); return ( <div className="flex-column flex-grow1"> <div className="flex-row"> <div className="flex-grow1" style={{width: 0}}> <table className={gcodeTableClass}> {colgroup} <thead> <tr> <th>Command</th> <th>Result</th> </tr> </thead> </table> </div> <div className="scroll-y" style={{visibility: 'hidden'}} /> </div> <div ref="scroll_div" className="flex-column flex-shrink1 flex-grow1 scroll-y gcode-table-area"> <div style={{flexGrow: '1'}}></div> <table className={gcodeTableClass} style={{width: '100%'}}> {colgroup} <tbody> {$.map(this.props.gcodeHistory, function(entry) { return <GcodeRow key={entry.id} entry={entry} />; }.bind(this))} {$.map(this.props.gcodeQueue, function(entry) { return <GcodeRow key={entry.id} entry={entry} />; }.bind(this))} </tbody> </table> </div> <div className="flex-row"> <GcodeInput /> </div> </div> ); }, componentDidUpdate: function() { var node = this.refs.scroll_div; node.scrollTop = node.scrollHeight; } }); function textToSpans(text) { var lines = text.split('\n'); return linesToSpans(lines); } function linesToSpans(lines) { var lineToSpan = function(line) { return (<span>{line}<br /></span>); }; return $.map(lines, lineToSpan); } var GcodeRow = React.createClass({ shouldComponentUpdate: function(nextProps, nextState) { return this.props.entry.dirty; }, componentDidUpdate: function() { this.props.entry.dirty = false; }, render: function() { var entry = this.props.entry; var cmdText = linesToSpans(entry.cmds); var result = $.trim(entry.response); var resultExtra = !entry.completed ? '(pending)' : (entry.error !== null) ? 'Error: '+entry.error : null; if (resultExtra !== null) { if (result.length !== 0) { result += '\n'; } result += resultExtra; } result = textToSpans(result); return ( <tr data-mod2={entry.id%2} data-pending={!entry.completed} data-error={entry.isError} title={'User action: '+entry.reason}> <td>{cmdText}</td> <td>{result}</td> </tr> ); }, }); var GcodeInput = React.createClass({ doSendCommand: function() { var cmd = this.state.gcodeInput; if (cmd !== '') { sendGcode('Send command', cmd); this.setState({gcodeInput: ''}); } }, onSendClick: function() { this.doSendCommand(); }, onInputChange: function(event) { this.setState({gcodeInput: event.target.value}); }, onInputKeyPress: function(event) { if (event.key === 'Enter') { this.doSendCommand(); } }, getInitialState: function() { return {gcodeInput: ''}; }, render: function() { var sendDisabled = (this.state.gcodeInput === ''); return ( <div className="input-group gcode-input-group"> <input type="text" className={controlInputClass} placeholder="Command to send" value={this.state.gcodeInput} onChange={this.onInputChange} onKeyPress={this.onInputKeyPress} /> <span className="input-group-btn"> <button type="button" className={controlButtonClass('primary')} onClick={this.onSendClick} disabled={sendDisabled}>Send</button> </span> </div> ); } }); // Field editing logic function EditController(row_ref) { this._comp = null; this._row_ref = row_ref; this._editing = {}; this._dirty_all_rows = false; this._dirty_rows = {}; } EditController.prototype.setComponent = function(comp) { this._comp = comp; }; EditController.prototype.getValue = function(id) { return this._input(id).value; }; EditController.prototype.getNumberValue = function(id) { return $toNumber(this.getValue(id)); }; EditController.prototype.isEditing = function(id) { return $has(this._editing, id); }; EditController.prototype.isEditingAny = function() { return !$.isEmptyObject(this._editing); }; EditController.prototype.rowIsDirty = function(id) { return (this._dirty_all_rows || $has(this._dirty_rows, id)); }; EditController.prototype._input = function(id) { return this._row_ref.getRowInput(this._comp, id); }; EditController.prototype._onChange = function(id) { var value = this.getValue(id); var wasEditingAny = this.isEditingAny(); this._editing[id] = value; this.markDirtyRow(id); if (wasEditingAny) { this.updateRow(id); } else { // The combined "set" button may need to change to enabled. this.updateTable(); } }; EditController.prototype._onKeyDown = function(id, event) { if (event.key === 'Escape') { this._input(id).blur(); this.cancel(id); } }; EditController.prototype._onKeyPress = function(id, event) { if (event.key === 'Enter') { if ($has(this._comp, 'onInputEnter')) { return this._comp.onInputEnter(id); } } }; EditController.prototype.markDirtyAllRows = function() { this._dirty_all_rows = true; }; EditController.prototype.markDirtyRow = function(id) { this._dirty_rows[id] = true; }; EditController.prototype.updateTable = function() { this._comp.forceUpdate(); }; EditController.prototype.updateRow = function(id) { this._row_ref.updateRow(this._comp, id); }; EditController.prototype.cancel = function(id) { if (this.isEditing(id)) { delete this._editing[id]; this.markDirtyRow(id); if (this.isEditingAny()) { this.updateRow(id); } else { // The combined "set" button may need to change to disabled. this.updateTable(); } } }; EditController.prototype.cancelAll = function() { $.each(this._editing, function(id, value) { this.markDirtyRow(id); }.bind(this)); this._editing = {}; this.updateTable(); }; EditController.prototype.rendering = function(id_datas) { $.each(this._editing, function(id, value) { if (!$has(id_datas, id)) { delete this._editing[id]; } }.bind(this)); }; EditController.prototype.getRenderInputs = function(id, live_value) { var editing = this.isEditing(id); return { editing: editing, class: editing ? controlEditingClass : '', value: editing ? this._editing[id] : live_value, onCancel: this.cancel.bind(this, id), onChange: this._onChange.bind(this, id), onKeyDown: this._onKeyDown.bind(this, id), onKeyPress: this._onKeyPress.bind(this, id) }; }; EditController.prototype._forAllDirtyRows = function(id_datas, func) { if (this._dirty_all_rows) { $.each(id_datas, func); } else { $.each(this._dirty_rows, function(id) { if ($has(id_datas, id)) { func(id, id_datas[id]); } }); } }; EditController.prototype._updateRowInput = function(id) { var input = this._input(id); if (!this.isEditing(id)) { input.defaultValue = input.value; } }; EditController.prototype.componentDidUpdate = function(id_datas) { this._forAllDirtyRows(id_datas, function(id, data) { this._updateRowInput(id); }.bind(this)); this._dirty_all_rows = false; this._dirty_rows = {}; }; EditController.prototype.rowComponentDidUpdate = function(id) { this._updateRowInput(id); delete this._dirty_rows[id]; }; function RowRefSameComp(prefix) { return { getRowInput: function(comp, id) { return comp.refs[prefix+id]; }, updateRow: function(comp, id) { comp.forceUpdate(); } }; } function RowRefChildComp(child_ref_name) { return { getRowInput: function(comp, id) { return comp.refs[id].refs[child_ref_name]; }, updateRow: function(comp, id) { comp.refs[id].forceUpdate(); } }; } function makeEcInputProps(ecInputs) { return {onChange: ecInputs.onChange, onKeyDown: ecInputs.onKeyDown, onKeyPress: ecInputs.onKeyPress}; } // Generic status updating function StatusUpdater(reqPath, refreshInterval, waitingRespTime, handleNewStatus, handleCondition) { this._reqPath = reqPath; this._refreshInterval = refreshInterval; this._waitingRespTime = waitingRespTime; this._handleNewStatus = handleNewStatus; this._handleCondition = handleCondition; this._reqestInProgress = false; this._needsAnotherUpdate = false; this._timerId = null; this._waitingTimerId = null; this._running = false; this._condition = 'Disabled'; } StatusUpdater.prototype.getCondition = function() { return this._condition; }; StatusUpdater.prototype.setRunning = function(running) { if (running) { if (!this._running) { this._running = true; this.requestUpdate(true); } } else { if (this._running) { this._running = false; this._changeCondition('Disabled'); this._stopTimer(); this._stopWaitingTimer(); this._handleCondition(); } } }; StatusUpdater.prototype.requestUpdate = function(setWaiting) { if (!this._running) { return; } if (setWaiting) { this._changeCondition('WaitingResponse'); this._stopWaitingTimer(); } if (this._reqestInProgress) { this._needsAnotherUpdate = true; } else { this._startRequest(); } }; StatusUpdater.prototype._stopTimer = function() { if (this._timerId !== null) { clearTimeout(this._timerId); this._timerId = null; } }; StatusUpdater.prototype._stopWaitingTimer = function() { if (this._waitingTimerId !== null) { clearTimeout(this._waitingTimerId); this._waitingTimerId = null; } }; StatusUpdater.prototype._startRequest = function() { this._stopTimer(); this._reqestInProgress = true; this._needsAnotherUpdate = false; this._waitingTimerId = setTimeout(this._waitingTimerHandler.bind(this), this._waitingRespTime); $.ajax({ url: this._reqPath, dataType: 'json', cache: false, success: function(new_status) { this._requestCompleted(true, new_status); }.bind(this), error: function(xhr, status, err) { this._requestCompleted(false, null); }.bind(this) }); }; StatusUpdater.prototype._requestCompleted = function(success, new_status) { this._reqestInProgress = false; if (!this._running) { return; } this._stopWaitingTimer(); if (!(this._condition === 'WaitingResponse' && this._needsAnotherUpdate)) { this._changeCondition(success ? 'Okay' : 'Error'); } if (this._needsAnotherUpdate) { this._startRequest(); } else { this._timerId = setTimeout(this._timerHandler.bind(this), this._refreshInterval); } if (success) { this._handleNewStatus(new_status); } }; StatusUpdater.prototype._timerHandler = function() { if (this._running && !this._reqestInProgress) { this._startRequest(); } } StatusUpdater.prototype._waitingTimerHandler = function() { if (this._running && this._waitingTimerId !== null) { this._waitingTimerId = null; if (this._condition !== 'Error') { this._changeCondition('WaitingResponse'); } } } StatusUpdater.prototype._changeCondition = function(condition) { if (this._condition !== condition) { this._condition = condition; this._handleCondition(); } } // Gcode execution var gcodeQueue = []; var gcodeHistory = []; var gcodeIdCounter = 1; var gcodeStatusUpdateTimer = null; function sendGcode(reason, cmd, callback) { sendGcodes(reason, [cmd], callback); } function sendGcodes(reason, cmds, callback) { var entry = { id: gcodeIdCounter, reason: reason, cmds: cmds, callback: callback, completed: false, error: null, response: '', isError: false, dirty: true, }; gcodeQueue.push(entry); gcodeIdCounter = (gcodeIdCounter >= 1000000) ? 1 : (gcodeIdCounter+1); if (gcodeQueue.length === 1) { _sendNextQueuedGcodes(); } while (gcodeQueue.length + gcodeHistory.length > gcodeHistorySize && gcodeHistory.length > 0) { gcodeHistory.shift(); } updateGcode(); } function _sendNextQueuedGcodes() { var entry = gcodeQueue[0]; var cmds_disp = entry.cmds.join('; '); var cmds_exec = entry.cmds.join('\n')+'\n'; var xhr = new XMLHttpRequest(); xhr.open('POST', '/rr_gcode', true); xhr.setRequestHeader('Content-Type', 'text/plain'); xhr.addEventListener('progress', evt => _gcodeXhrProgressEvent(entry, xhr, evt), false); xhr.addEventListener('load', evt => _gcodeXhrLoadEvent(entry, xhr, evt), false); xhr.addEventListener('error', evt => _gcodeXhrErrorEvent(entry, evt), false); xhr.send(cmds_exec); // Start a timer to request an updated machine status shortly, // unless the gcode completes sooner. The intention is that // the active/inactive status on the top-panel doesn't display // "inactive" for too long after the command made the machine active. gcodeStatusUpdateTimer = setTimeout(_gcodeStatusUpdateTimerHandler, updateConfigAfterSendingGcodeTime); } function _checkGcodeRequestInProgress(entry) { return (gcodeQueue.length > 0 && gcodeQueue[0] === entry); } function _gcodeStatusUpdateTimerHandler() { gcodeStatusUpdateTimer = null; statusUpdater.requestUpdate(false); } function _gcodeXhrProgressEvent(entry, xhr, evt) { if (!_checkGcodeRequestInProgress(entry)) { return; } if (xhr.responseText !== null) { entry.response = xhr.responseText; entry.dirty = true; updateGcode(); } } function _gcodeXhrLoadEvent(entry, xhr, evt) { var error = (xhr.status === 200) ? null : ''+xhr.status+' '+xhr.statusText; _currentGcodeCompleted(entry, error, xhr.responseText); } function _gcodeXhrErrorEvent(entry, evt) { _currentGcodeCompleted(entry, 'Network error', null); } function _currentGcodeCompleted(entry, error, response) { if (!_checkGcodeRequestInProgress(entry)) { return; } if (gcodeStatusUpdateTimer !== null) { clearTimeout(gcodeStatusUpdateTimer); gcodeStatusUpdateTimer = null; } var entry = gcodeQueue.shift(); var callback = entry.callback; entry.callback = null; entry.completed = true; entry.error = error; if (response !== null) { entry.response = response; } entry.isError = error !== null || /^Error:/gm.test(entry.response); entry.dirty = true; gcodeHistory.push(entry); if (entry.isError) { var head_str; var body_str; if (entry.error !== null) { head_str = 'Communication error'; body_str = entry.error; } else { head_str = 'The machine responded with:'; body_str = entry.response; } showError(entry.reason, head_str, body_str); } if (gcodeQueue.length !== 0) { _sendNextQueuedGcodes(); } updateGcode(); statusUpdater.requestUpdate(false); if (callback) { callback(entry); } } // Error message display //var dialogIsOpen = false; var currentDialogInfo = null; var dialogQueue = []; var dialogModal = $('#dialog_modal'); var dialogModalLabel = document.getElementById('dialog_modal_label'); var dialogModalBody = document.getElementById('dialog_modal_body'); var dialogModalClose = document.getElementById('dialog_modal_close'); var dialogModalConfirm = document.getElementById('dialog_modal_confirm'); function showError(action_str: string, head_str: string, body_str: string = null) { var haveHead = (head_str !== null); var haveBody = (body_str !== null); console.error('Error in '+action_str+'.'+(haveHead?' '+head_str:'')+(haveBody?'\n'+body_str:'')); var label_str = 'Error in "'+action_str+'".'+(haveHead ? '\n'+head_str : ''); _queueDialog({ label_str: label_str, body_str: body_str, close_text: 'Close', confirm_text: null, confirm_action: null, }); } function showConfirmDialog(label_str: string, body_str: string, cancel_text: string, confirm_text: string, confirm_action: () => void) { _queueDialog({ label_str: label_str, body_str: body_str, close_text: cancel_text, confirm_text: confirm_text, confirm_action: confirm_action, }); } function _queueDialog(info) { if (currentDialogInfo === null) { _showDialog(info); } else { dialogQueue.push(info); } } function _showDialog(info) { var haveBody = info.body_str !== null; dialogModalLabel.innerText = info.label_str; dialogModalBody.innerText = haveBody ? info.body_str : ''; dialogModalBody.hidden = !haveBody; dialogModalClose.innerText = info.close_text; dialogModalConfirm.hidden = info.confirm_action === null; dialogModalConfirm.innerText = (info.confirm_text === null) ? 'Confirm' : info.confirm_text; dialogModalConfirm.onclick = () => _dialogConfirmClicked(info); dialogModal.modal({}); currentDialogInfo = info; } dialogModal.on('hidden.bs.modal', function() { dialogModalLabel.innerText = ''; dialogModalBody.innerText = ''; dialogModalConfirm.innerText = ''; dialogModalConfirm.onclick = null; currentDialogInfo = null; if (dialogQueue.length > 0) { var info = dialogQueue.shift(); _showDialog(info); } }); function _dialogConfirmClicked(info) { if (currentDialogInfo !== info) { return; } dialogModal.modal('hide'); if (info.confirm_action !== null) { var confirm_action = info.confirm_action; info.confirm_action = null; confirm_action(); } } // Directory list controller. class DirListController { private _handle_dir_loaded: () => void; private _requested_dir: string; private _need_rerequest: boolean; private _update_status_then: boolean; private _loaded_dir: string; private _loaded_result: any; private _is_dirty: boolean; private _ever_requested: boolean; constructor(handle_dir_loaded: () => void) { this._handle_dir_loaded = handle_dir_loaded; this._requested_dir = null; this._need_rerequest = false; this._update_status_then = false; this._loaded_dir = null; this._loaded_result = null; this._is_dirty = true; this._ever_requested = false; } requestDir(requested_dir: string) { var old_dir = this._requested_dir; this._requested_dir = requested_dir; if (old_dir !== null) { this._need_rerequest = true; } else { this._startRequest(); } } getLoadingDir(): string { return this._requested_dir; } getLoadedDir(): string { return this._loaded_dir; } getLoadedResult(): any { return this._loaded_result; } getEverRequested(): boolean { return this._ever_requested; } isDirty(): boolean { return this._is_dirty; } clearDirty() { this._is_dirty = false; } private _startRequest() { this._need_rerequest = false; this._update_status_then = (machine_state.sdcard !== null && machine_state.sdcard.mntState !== 'Mounted'); this._ever_requested = true; $.ajax({ url: '/rr_files?flagDirs=1&dir='+encodeURIComponent(this._requested_dir), dataType: 'json', cache: false, success: function(files_resp) { this._requestCompleted(true, files_resp, null); }.bind(this), error: function(xhr, status, error) { this._requestCompleted(false, null, makeAjaxErrorStr(status, error)); }.bind(this) }); } private _requestCompleted(success: boolean, files_resp: any, error: string) { if (this._update_status_then) { statusUpdater.requestUpdate(false); } if (this._need_rerequest) { this._startRequest(); return; } var requested_dir = this._requested_dir; this._requested_dir = null; if (!success) { showError('Load directory '+requested_dir, error, null); return; } this._loaded_dir = requested_dir; this._loaded_result = files_resp; this._is_dirty = true; this._handle_dir_loaded(); } } // File upload controller class FileUploadController { private _handle_update: () => void; private _uploading: boolean; private _sourceFileName: string; private _destinationPath: string; private _totalBytes: number; private _uploadedBytes: number; private _resultPending: boolean; private _haveResult: boolean; private _uploadError: string; constructor(handle_update: () => void) { this._handle_update = handle_update; this._uploading = false; this._sourceFileName = null; this._destinationPath = null; this._totalBytes = 0; this._uploadedBytes = 0; this._resultPending = false; this._haveResult = false; this._uploadError = null; } isUploading(): boolean { return this._uploading; } getSourceFileName(): string { return this._sourceFileName; } getDestinationPath(): string { return this._destinationPath; } getTotalBytes(): number { return this._totalBytes; } getUploadedBytes(): number { return this._uploadedBytes; } isResultPending(): boolean { return this._resultPending; } haveResult(): boolean { return this._haveResult; } getUploadError(): string { return this._uploadError; } ackResult() { console.assert(this._resultPending); this._resultPending = false; } clearResult() { if (!this._uploading) { this._sourceFileName = null; this._destinationPath = null; this._resultPending = false; this._haveResult = false; this._uploadError = null; } } startUpload(sourceFileName: string, destinationPath: string, data: Blob) { console.assert(!this._uploading); this.clearResult(); this._uploading = true; this._sourceFileName = sourceFileName; this._destinationPath = destinationPath; this._totalBytes = data.size; this._uploadedBytes = 0; $.ajax({ type: 'POST', url: '/rr_upload?name='+encodeURIComponent(destinationPath), data: data, processData: false, contentType: false, xhr: function() { var xhr = $.ajaxSettings.xhr(); xhr.upload.addEventListener('progress', evt => this._responseProgress(evt), false); return xhr; }.bind(this), success: function(result) { this._requestCompleted(null); }.bind(this), error: function(xhr, status, error) { this._requestCompleted(makeAjaxErrorStr(status, error)); }.bind(this), }); } private _responseProgress(evt) { if (this._uploading) { if (evt.lengthComputable) { this._totalBytes = evt.total; } this._uploadedBytes = evt.loaded; this._handle_update(); } } private _requestCompleted(error: string) { console.assert(this._uploading); if (error !== null) { showError('Upload file '+this._sourceFileName+' to '+this._destinationPath, error, null); } this._uploading = false; this._resultPending = true; this._haveResult = true; this._uploadError = error; this._handle_update(); } } // Status updating var machine_state = { active: null, speedRatio: null, configDirty: null, sdcard: null, axes: preprocessObjectForState({}), heaters: preprocessObjectForState({}), fans: preprocessObjectForState({}) }; function handleNewStatus(new_machine_state) { machine_state = new_machine_state; machine_state.active = $has(machine_state, 'active') ? machine_state.active : null; machine_state.speedRatio = $has(machine_state, 'speedRatio') ? machine_state.speedRatio : null; machine_state.configDirty = $has(machine_state, 'configDirty') ? machine_state.configDirty : null; machine_state.sdcard = $has(machine_state, 'sdcard') ? machine_state.sdcard : null machine_state.axes = fixupStateObject(machine_state, 'axes'); machine_state.heaters = fixupStateObject(machine_state, 'heaters'); machine_state.fans = fixupStateObject(machine_state, 'fans'); document.getElementById('axes_panel').hidden = (machine_state.axes.arr.length === 0); document.getElementById('heaters_panel').hidden = (machine_state.heaters.arr.length === 0); document.getElementById('fans_panel').hidden = (machine_state.fans.arr.length === 0); document.getElementById('speed_panel').hidden = (machine_state.speedRatio === null); document.getElementById('config_tab').hidden = (machine_state.configDirty === null); document.getElementById('sdcard_tab').hidden = (machine_state.sdcard === null); updateTabs(); configUpdater.setRunning(machine_state.configDirty !== null); markDirtyAndForceUpdate(controller_axes, wrapper_axes); markDirtyAndForceUpdate(controller_heaters, wrapper_heaters); markDirtyAndForceUpdate(controller_fans, wrapper_fans); markDirtyAndForceUpdate(controller_speed, wrapper_speed); wrapper_config.forceUpdate(); wrapper_toppanel.forceUpdate(); wrapper_sdcard.forceUpdate(); if (machine_state.sdcard !== null && !controller_dirlist.getEverRequested()) { wrapper_sdcard.refs.component.navigateToDesiredDir(); } if (configUpdater.getCondition() === 'Error') { configUpdater.requestUpdate(false); } } function handleStatusCondition() { wrapper_toppanel.forceUpdate(); } var statusUpdater = new StatusUpdater('/rr_status', statusRefreshInterval, statusWaitingRespTime, handleNewStatus, handleStatusCondition); function fixupStateObject(state, name) { return preprocessObjectForState($has(state, name) ? state[name] : {}); } function updateTabs() { // If there is no tab selected and there is at least one non-hidden tab, // activate the first non-hidden tab. var active_tab = $('#main_tabs_ul>.active'); if (active_tab.length == 0) { var nonhidden_tabs = $('#main_tabs_ul>*:not([hidden])'); if (nonhidden_tabs.length > 0) { nonhidden_tabs.first().find('>a').tab('show'); } } } // Configuration updating var machine_options = preprocessObjectForState({}); function handleNewConfig(new_config) { machine_options = preprocessObjectForState(preprocessOptionsList(new_config.options)); markDirtyAndForceUpdate(controller_config, wrapper_config); } function handleConfigCondition() { wrapper_config.forceUpdate(); } var configUpdater = new StatusUpdater('/rr_config', configRefreshInterval, configWaitingRespTime, handleNewConfig, handleConfigCondition); // Instantiating the dirlist controller function handleDirLoaded() { wrapper_sdcard.forceUpdate(); } var controller_dirlist = new DirListController(handleDirLoaded); // Instantiating the file upload controller function handleUploadUpdate() { wrapper_sdcard.forceUpdate(); } var controller_upload = new FileUploadController(handleUploadUpdate); // Fullscreen logic var fullscreen_elem = document.body; function isFullscreen() { var fullscreenElement = document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement; return fullscreenElement ? true : false; } function goFullscreen() { var requestFullscreen = fullscreen_elem.requestFullscreen || fullscreen_elem.webkitRequestFullscreen || fullscreen_elem.mozRequestFullScreen || fullscreen_elem.msRequestFullscreen; if (requestFullscreen) { requestFullscreen.call(fullscreen_elem); } } function leaveFullscreen() { var exitFullscreen = document.exitFullscreen || document.webkitExitFullscreen || document.mozCancelFullScreen || document.msExitFullscreen; if (exitFullscreen) { exitFullscreen.call(document); } } function onFullscreenChange(evt) { wrapper_toppanel.forceUpdate(); } for (var eventName of ['fullscreenchange', 'webkitfullscreenchange', 'mozfullscreenchange', 'MSFullscreenChange']) { document.addEventListener(eventName, onFullscreenChange, false); } // Observing elements width to make them adapt themselves to available space var tab_content_div = document.getElementById('tab_content_div'); function refreshTabsWidth() { var width = tab_content_div.offsetWidth; if (width !== 0) { wrapper_sdcard.refs.component.onContainerResized(width); wrapper_config.refs.component.onContainerResized(width); } } require(['droplet/ResizeSensor/ResizeSensorApi'], (ResizeSensorApi) => { ResizeSensorApi.create(tab_content_div, refreshTabsWidth); }); setInterval(refreshTabsWidth, 2000); // Instantiating edit controllers var controller_axes = new EditController(RowRefSameComp('target_')); var controller_heaters = new EditController(RowRefSameComp('target_')); var controller_fans = new EditController(RowRefSameComp('target_')); var controller_speed = new EditController(RowRefSameComp('target_')); var controller_config = new EditController(RowRefChildComp('target')); // Misc functions connecting things function markDirtyAndForceUpdate(controller, component) { controller.markDirtyAllRows(); component.forceUpdate(); } function updateGcode() { wrapper_toppanel.forceUpdate(); wrapper_gcode.forceUpdate(); } function startRefreshAll() { statusUpdater.requestUpdate(true); configUpdater.requestUpdate(true); } // Instantiating React components var ComponentWrapper = React.createClass({ render: function() { return this.props.render(); } }); function render_axes() { return <AxesTable axes={machine_state.axes} probe_present={$has(machine_state, 'bedProbe')} controller={controller_axes} />; } function render_heaters() { return <HeatersTable heaters={machine_state.heaters} controller={controller_heaters} />; } function render_fans() { return <FansTable fans={machine_state.fans} controller={controller_fans} />; } function render_speed() { return <SpeedTable speedRatio={machine_state.speedRatio} controller={controller_speed} />; } function render_toppanel() { return <TopPanel statusUpdater={statusUpdater} gcodeQueue={gcodeQueue} active={machine_state.active} is_fullscreen={isFullscreen()} />; } function render_config() { return <ConfigTab ref="component" options={machine_options} configDirty={machine_state.configDirty} controller={controller_config} configUpdater={configUpdater} />; } function render_sdcard() { return <SdCardTab ref="component" sdcard={machine_state.sdcard} controller_dirlist={controller_dirlist} controller_upload={controller_upload} />; } function render_gcode() { return <GcodeTable gcodeHistory={gcodeHistory} gcodeQueue={gcodeQueue} />; } var wrapper_axes = ReactDOM.render(<ComponentWrapper render={render_axes} />, document.getElementById('axes_div')); var wrapper_heaters = ReactDOM.render(<ComponentWrapper render={render_heaters} />, document.getElementById('heaters_div')); var wrapper_fans = ReactDOM.render(<ComponentWrapper render={render_fans} />, document.getElementById('fans_div')); var wrapper_speed = ReactDOM.render(<ComponentWrapper render={render_speed} />, document.getElementById('speed_div')); var wrapper_toppanel = ReactDOM.render(<ComponentWrapper render={render_toppanel} />, document.getElementById('toppanel_div')); var wrapper_config = ReactDOM.render(<ComponentWrapper render={render_config} />, document.getElementById('config_div')); var wrapper_sdcard = ReactDOM.render(<ComponentWrapper render={render_sdcard} />, document.getElementById('sdcard_div')); var wrapper_gcode = ReactDOM.render(<ComponentWrapper render={render_gcode} />, document.getElementById('gcode_div')); // Initial actions statusUpdater.setRunning(true);
the_stack
import { TestUtils } from '../../test'; // Providers import { ConfigProvider } from '../config/config'; import { FilterProvider } from '../filter/filter'; import { PersistenceProvider } from '../persistence/persistence'; import { RateProvider } from '../rate/rate'; import { TxFormatProvider } from './tx-format'; describe('TxFormatProvider', () => { let configProvider: ConfigProvider; let filterProvider: FilterProvider; let rateProvider: RateProvider; let txFormatProvider: TxFormatProvider; class PersistenceProviderMock { constructor() {} storeConfig() { return Promise.resolve(''); } } beforeEach(() => { const testBed = TestUtils.configureProviderTestingModule([ { provide: PersistenceProvider, useClass: PersistenceProviderMock } ]); txFormatProvider = testBed.get(TxFormatProvider); configProvider = testBed.get(ConfigProvider); rateProvider = testBed.get(RateProvider); filterProvider = testBed.get(FilterProvider); }); describe('toCashAddress', () => { it('should get the address in Cash Address format', () => { let address = 'CcyUyVPZtNRQ5JxhjXLKQwWt1xKr8igncP'; // BCH livenet address let cashAddr: string = txFormatProvider.toCashAddress(address); expect(cashAddr).toEqual('qrs0knp7gal4d8xyxy2w3cq5tpzfa5ywgcuqqlwykf'); }); it('should get the address in Cash Address format, with prefix', () => { let address = 'CcyUyVPZtNRQ5JxhjXLKQwWt1xKr8igncP'; // BCH livenet address let cashAddr: string = txFormatProvider.toCashAddress(address, true); expect(cashAddr).toEqual( 'bitcoincash:qrs0knp7gal4d8xyxy2w3cq5tpzfa5ywgcuqqlwykf' ); }); }); describe('formatAmount', () => { const testVectors: any[] = [ // [coin, amount, fullPrecision, expectedResult] ['bit', 12312312, true, '123,123.12'], ['sat', 12312312, true, '12312312'], ['btc', 0, true, '0.00000000'], ['btc', 0, false, '0.00'], ['btc', 12312312, true, '0.12312312'], ['btc', 1231231223423, true, '12,312.31223423'], ['btc', 1231231223423, false, '12,312.312234'], ['eth', 345345345345345345, true, '0.34534534'], ['eth', 345345345345345345, false, '0.345345'], ['eth', 345345345345345345123123, true, '345,345.34534534'] ]; testVectors.forEach(v => { it( 'should get the formatted amount for ' + v[1] + ' "satoshis" in ' + v[0] + ' and fullPrecision: ' + v[2], () => { let formattedAmount = txFormatProvider.formatAmount(v[0], v[1], v[2]); expect(formattedAmount).toEqual(v[3]); } ); }); }); describe('formatAmountStr', () => { it('should return undefined if satoshis amount are not type of number', () => { expect( txFormatProvider.formatAmountStr('btc', undefined) ).toBeUndefined(); }); it('should return a string with formatted amount', () => { let newOpts = { wallet: { settings: { unitCode: 'btc' } } }; configProvider.set(newOpts); expect(txFormatProvider.formatAmountStr('btc', 12312312)).toEqual( '0.123123 BTC' ); }); }); describe('toFiat', () => { it('should return undefined if satoshis amount are undefined', () => { txFormatProvider.toFiat('btc', undefined, 'USD').then(result => { expect(result).toBeUndefined(); }); }); it('should return null', () => { txFormatProvider.toFiat('btc', 12312312, 'USD').then(result => { expect(result).toBeNull(); }); }); it('should return a string with formatted amount', () => { spyOn(rateProvider, 'toFiat').and.returnValue(1000000); txFormatProvider.toFiat('btc', 12312312, 'USD').then(result => { expect(result).toEqual('1000000.00'); }); }); }); describe('formatToUSD', () => { it('should return undefined if satoshis amount are undefined', () => { txFormatProvider.formatToUSD('btc', undefined).then(result => { expect(result).toBeUndefined(); }); }); it('should return null', () => { txFormatProvider.formatToUSD('btc', 12312312).then(result => { expect(result).toBeNull(); }); }); it('should return a string with formatted amount in USD', () => { spyOn(rateProvider, 'toFiat').and.returnValue(1000000); txFormatProvider.formatToUSD('btc', 12312312).then(result => { expect(result).toEqual('1000000.00'); }); }); }); describe('formatAlternativeStr', () => { beforeEach(() => { let newOpts = { wallet: { settings: { unitCode: 'btc', alternativeIsoCode: 'ARS' } } }; configProvider.set(newOpts); }); it('should return undefined if satoshis amount are undefined', () => { expect( txFormatProvider.formatAlternativeStr('btc', undefined) ).toBeUndefined(); }); it('should return null', () => { let result = txFormatProvider.formatAlternativeStr('btc', 12312312); expect(result).toBeNull(); }); it('should return null', () => { spyOn(filterProvider, 'formatFiatAmount').and.returnValue(undefined); spyOn(rateProvider, 'isCoinAvailable').and.returnValue(true); let result = txFormatProvider.formatAlternativeStr('btc', 12312312); expect(result).toBeNull(); }); it('should return a string with formatted amount in alternative Iso Code setted in wallet', () => { spyOn(rateProvider, 'toFiat').and.returnValue(1000000); spyOn(rateProvider, 'isCoinAvailable').and.returnValue(true); let result = txFormatProvider.formatAlternativeStr('btc', 12312312); expect(result).toEqual('1,000,000 ARS'); }); }); describe('processTx', () => { let tx: any = { action: 'received', amount: 447100, fee: 19440, outputs: [ { alternativeAmountStr: '28.36 USD', amount: 447100, toAddress: 'mxMUZvgFR8D3LRscz5GbXERPXNSp1ww8Bb' } ] }; beforeEach(() => { let newOpts = { wallet: { settings: { unitCode: 'btc', alternativeIsoCode: 'USD' } } }; configProvider.set(newOpts); }); it('should return same tx if tx.action is invalid', () => { tx.action = 'invalid'; expect(txFormatProvider.processTx('btc', tx)).toEqual(tx); }); it('should return tx with defined values if tx.action is received', () => { tx.action = 'received'; let result = txFormatProvider.processTx('btc', tx); expect(tx.toAddress).toBeDefined(); expect(tx.toAddress).toEqual('mxMUZvgFR8D3LRscz5GbXERPXNSp1ww8Bb'); expect(tx.amountStr).toBeDefined(); expect(tx.alternativeAmountStr).toBeDefined(); expect(tx.feeStr).toBeDefined(); expect(result).toEqual(tx); }); it('should return tx.toAddress in CashAddress format if coin is BCH', () => { tx.action = 'received'; tx.outputs[0].toAddress = 'CWtp9bmTjiwBp89SvnZRbshkEkTY9TRZnt'; txFormatProvider.processTx('bch', tx); expect(tx.toAddress).toEqual( 'qz0ys7q7utlsd7fmcsecxtpp9y8j8xhxtsy35kmzka' ); }); it('should return tx.addressTo in CashAddress format if coin is BCH', () => { tx.action = 'received'; tx.addressTo = 'CWtp9bmTjiwBp89SvnZRbshkEkTY9TRZnt'; txFormatProvider.processTx('bch', tx); expect(tx.addressTo.toString()).toEqual( 'qz0ys7q7utlsd7fmcsecxtpp9y8j8xhxtsy35kmzka' ); }); it('should return same tx.amount if only has one output', () => { tx.action = 'sent'; txFormatProvider.processTx('btc', tx); expect(tx.hasMultiplesOutputs).toBeFalsy(); expect(tx.amount).toEqual(447100); }); it('should return reduced tx.amount if has multiple outputs', () => { tx.action = 'sent'; tx.outputs = [ { alternativeAmountStr: '28.36 USD', amount: 447100, toAddress: 'mxMUZvgFR8D3LRscz5GbXERPXNSp1ww8Bb' }, { alternativeAmountStr: '38.36 USD', amount: 647100, toAddress: 'mxMUZvgFR8D3LRscz5GbXERPXNSp1ww8Bb' } ]; txFormatProvider.processTx('btc', tx); expect(tx.hasMultiplesOutputs).toBeTruthy(); expect(tx.amount).toEqual(1094200); }); }); describe('parseAmount', () => { beforeEach(() => { let newOpts = { wallet: { settings: { unitCode: 'btc', alternativeIsoCode: 'USD', unitToSatoshi: 100000000 } } }; configProvider.set(newOpts); }); it('should return amount parsed correctly if the currency is BTC', () => { let result = txFormatProvider.parseAmount('btc', 0.012235, 'BTC', { onlyIntegers: false }); expect(result).toEqual({ amount: '0.01223500', currency: 'BTC', alternativeIsoCode: 'USD', amountSat: 1223500, amountUnitStr: '0.012235 BTC' }); }); it('should return amount parsed correctly if the currency is USD', () => { spyOn(filterProvider, 'formatFiatAmount').and.returnValue('1,505'); spyOn(rateProvider, 'fromFiat').and.returnValue(24117237); let result = txFormatProvider.parseAmount('btc', 1505, 'USD', { onlyIntegers: false }); expect(result).toEqual({ amount: 1505, currency: 'USD', alternativeIsoCode: 'USD', amountSat: 24117237, amountUnitStr: '1,505 USD' }); }); it('should return amount parsed correctly if the currency is JPY and onlyIntegers is true', () => { let newOpts = { wallet: { settings: { unitCode: 'btc', alternativeIsoCode: 'JPY', unitToSatoshi: 100000000 } } }; configProvider.set(newOpts); spyOn(filterProvider, 'formatFiatAmount').and.returnValue('1,505'); spyOn(rateProvider, 'fromFiat').and.returnValue(24117237); let onlyIntegers = true; let result = txFormatProvider.parseAmount('btc', 1505, 'JPY', { onlyIntegers }); expect(result).toEqual({ amount: 1505, currency: 'JPY', alternativeIsoCode: 'JPY', amountSat: 24117237, amountUnitStr: '1,505 JPY' }); }); it('should return amount parsed correctly if the currency is sat', () => { spyOn(filterProvider, 'formatFiatAmount').and.returnValue('1,505'); let result = txFormatProvider.parseAmount('btc', 1505, 'sat', { onlyIntegers: false }); expect(result).toEqual({ amount: '0.00001505', currency: 'BTC', alternativeIsoCode: 'USD', amountSat: 1505, amountUnitStr: '0.000015 BTC' }); }); }); describe('satToUnit', () => { beforeEach(() => { let newOpts = { wallet: { settings: { alternativeIsoCode: 'USD', unitCode: 'btc', unitDecimals: 8, unitToSatoshi: 100000000 } } }; configProvider.set(newOpts); }); it('should return amount in unit format', () => { let result = txFormatProvider.satToUnit(12312312, 'btc'); expect(result).toEqual(0.12312312); }); }); describe('toLTCAddress', () => { it('should get the address in new LTC Address format', () => { let address = '33k1rEnWskMrr8RZEACJdQFRMLWovhSJ5R'; // LTC livenet legacy address (P2SH) let ltcAddr: string = txFormatProvider.toLTCAddress(address); expect(ltcAddr).toEqual('M9xAA8CUpsDHedhTL3BeT3Vpg37FyZyZLk'); }); it('should keep the address if it is a new format', () => { let address = 'M9xAA8CUpsDHedhTL3BeT3Vpg37FyZyZLk'; // LTC livenet new address (P2SH) let ltcAddr: string = txFormatProvider.toLTCAddress(address); expect(ltcAddr).toEqual('M9xAA8CUpsDHedhTL3BeT3Vpg37FyZyZLk'); }); }); });
the_stack
import * as React from 'react'; import { IWebPartContext} from '@microsoft/sp-webpart-base'; import { Environment, EnvironmentType } from '@microsoft/sp-core-library'; import { SPHttpClient, SPHttpClientResponse } from '@microsoft/sp-http'; import { IPropertyFieldSPListQueryPropsInternal, PropertyFieldSPListQueryOrderBy } from './PropertyFieldSPListQuery'; import { Dropdown, IDropdownOption } from 'office-ui-fabric-react/lib/Dropdown'; import { Label } from 'office-ui-fabric-react/lib/Label'; import { Slider } from 'office-ui-fabric-react/lib/Slider'; import { TextField } from 'office-ui-fabric-react/lib/TextField'; import { CommandButton, IButtonProps } from 'office-ui-fabric-react/lib/Button'; import { Spinner, SpinnerType } from 'office-ui-fabric-react/lib/Spinner'; import { Async } from 'office-ui-fabric-react/lib/Utilities'; import * as strings from 'sp-client-custom-fields/strings'; /** * @interface * PropertyFieldSPListQueryHost properties interface * */ export interface IPropertyFieldSPListQueryHostProps extends IPropertyFieldSPListQueryPropsInternal { } export interface IFilter { field?: string; operator?: string; value?: string; } export interface IPropertyFieldSPListQueryHostState { lists: IDropdownOption[]; fields: IDropdownOption[]; arranged: IDropdownOption[]; selectedList?: string; selectedField?: string; selectedArrange?: string; max?: number; operators?: IDropdownOption[]; filters?: IFilter[]; errorMessage?: string; loadedList: boolean; loadedFields: boolean; } /** * @class * Renders the controls for PropertyFieldSPListQuery component */ export default class PropertyFieldSPListQueryHost extends React.Component<IPropertyFieldSPListQueryHostProps, IPropertyFieldSPListQueryHostState> { private latestValidateValue: string; private async: Async; private delayedValidate: (value: string) => void; /** * @function * Constructor */ constructor(props: IPropertyFieldSPListQueryHostProps) { super(props); this.onChangedList = this.onChangedList.bind(this); this.onChangedField = this.onChangedField.bind(this); this.onChangedArranged = this.onChangedArranged.bind(this); this.onChangedMax = this.onChangedMax.bind(this); this.loadFields = this.loadFields.bind(this); this.onClickAddFilter = this.onClickAddFilter.bind(this); this.onClickRemoveFilter = this.onClickRemoveFilter.bind(this); this.onChangedFilterField = this.onChangedFilterField.bind(this); this.onChangedFilterOperator = this.onChangedFilterOperator.bind(this); this.onChangedFilterValue = this.onChangedFilterValue.bind(this); this.state = { loadedList: false, loadedFields: false, lists: [], fields: [], arranged: [{key: 'asc', text: 'Asc'}, {key: 'desc', text: 'Desc'}], selectedList: '', selectedField: '', selectedArrange: '', operators: [ {key: 'eq', text: strings.SPListQueryOperatorEq}, {key: 'ne', text: strings.SPListQueryOperatorNe}, {key: 'startsWith', text: strings.SPListQueryOperatorStartsWith}, {key: 'substringof', text: strings.SPListQueryOperatorSubstringof}, {key: 'lt', text: strings.SPListQueryOperatorLt}, {key: 'le', text: strings.SPListQueryOperatorLe}, {key: 'gt', text: strings.SPListQueryOperatorGt}, {key: 'ge', text: strings.SPListQueryOperatorGe} ], filters: [], max: 20, errorMessage: '' }; this.loadDefaultData(); this.loadLists(); this.async = new Async(this); this.validate = this.validate.bind(this); this.notifyAfterValidate = this.notifyAfterValidate.bind(this); this.delayedValidate = this.async.debounce(this.validate, this.props.deferredValidationTime); } private loadDefaultData(): void { if (this.props.query == null || this.props.query == '') { this.state.loadedFields = true; return; } var indexOfGuid: number = this.props.query.indexOf("lists(guid'"); if (indexOfGuid > -1) { var listId: string = this.props.query.substr(indexOfGuid); listId = listId.replace("lists(guid'", ""); var indexOfEndGuid: number = listId.indexOf("')/items"); listId = listId.substr(0, indexOfEndGuid); this.state.selectedList = listId; } var indexOfOrderBy: number = this.props.query.indexOf("$orderBy="); if (indexOfOrderBy > -1) { var orderBy: string = this.props.query.substr(indexOfOrderBy); orderBy = orderBy.replace("$orderBy=", ""); var indexOfEndOrderBy: number = orderBy.indexOf("%20"); var field: string = orderBy.substr(0, indexOfEndOrderBy); this.state.selectedField = field; var arranged: string = orderBy.substr(indexOfEndOrderBy); arranged = arranged.replace("%20", ""); var indexOfEndArranged: number = arranged.indexOf("&"); arranged = arranged.substr(0, indexOfEndArranged); this.state.selectedArrange = arranged; } var indexOfTop: number = this.props.query.indexOf("$top="); if (indexOfTop > -1) { var top: string = this.props.query.substr(indexOfTop); top = top.replace("$top=", ""); var indexOfEndTop: number = top.indexOf("&"); top = top.substr(0, indexOfEndTop); this.state.max = Number(top); } var indexOfFilters: number = this.props.query.indexOf("$filter="); if (indexOfFilters > -1) { var filter: string = this.props.query.substr(indexOfFilters); filter = filter.replace("$filter=", ""); var indexOfEndFilter: number = filter.indexOf("&"); filter = filter.substr(0, indexOfEndFilter); if (filter != null && filter != '') { var subFilter = filter.split("%20and%20"); for (var i = 0; i < subFilter.length; i++) { var fieldId: string = subFilter[i].substr(0, subFilter[i].indexOf("%20")); var operator: string = subFilter[i].substr(subFilter[i].indexOf("%20")); operator = operator.substr(3); operator = operator.substr(0, operator.indexOf("%20")); var value: string = subFilter[i].substr(subFilter[i].indexOf(operator + "%20")); value = value.replace(operator + "%20", ""); value = value.replace("'", "").replace("'", "").replace("'", ""); if (value == "undefined") value = ''; var newObj: IFilter = {}; newObj.field = fieldId; newObj.operator = operator; newObj.value = value; this.state.filters.push(newObj); } } } if (listId != null && listId != '') this.loadFields(); else this.state.loadedFields = true; } /** * @function * Loads the list from SharePoint current web site */ private loadLists(): void { var listService: SPListPickerService = new SPListPickerService(this.props, this.props.context); listService.getLibs().then((response: ISPLists) => { this.state.lists = []; response.value.map((list: ISPList) => { var isSelected: boolean = false; if (this.state.selectedList == list.Id) { isSelected = true; } this.state.lists.push({ key: list.Id, text: list.Title, isSelected: isSelected }); }); this.state.loadedList = true; this.saveState(); }); } private loadFields(): void { var listService: SPListPickerService = new SPListPickerService(this.props, this.props.context); listService.getFields(this.state.selectedList).then((response: ISPFields) => { this.state.fields = []; response.value.map((field: ISPField) => { var isSelected: boolean = false; if (this.state.selectedField == field.StaticName) { isSelected = true; } this.state.fields.push({ key: field.StaticName, text: field.Title, isSelected: isSelected }); }); this.state.loadedFields = true; this.saveState(); }); } private saveState(): void { this.setState(this.state); } private saveQuery(): void { var queryUrl: string = this.props.context.pageContext.web.absoluteUrl; queryUrl += "/_api/lists(guid'"; queryUrl += this.state.selectedList; queryUrl += "')/items?"; if (this.state.selectedField != null && this.state.selectedField != '') { queryUrl += "$orderBy="; queryUrl += this.state.selectedField; queryUrl += "%20"; queryUrl += this.state.selectedArrange; queryUrl += '&'; } if (this.state.max != null) { queryUrl += '$top='; queryUrl += this.state.max; queryUrl += '&'; } if (this.state.filters != null && this.state.filters.length > 0) { queryUrl += '$filter='; for (var i = 0; i < this.state.filters.length; i++) { if (this.state.filters[i].field != null && this.state.filters[i].operator != null) { if (i > 0) { queryUrl += "%20and%20"; } queryUrl += this.state.filters[i].field; queryUrl += "%20"; queryUrl += this.state.filters[i].operator; queryUrl += "%20'"; queryUrl += this.state.filters[i].value; queryUrl += "'"; } } queryUrl += '&'; } if (this.delayedValidate !== null && this.delayedValidate !== undefined) { this.delayedValidate(queryUrl); } } /** * @function * Validates the new custom field value */ private validate(value: string): void { if (this.props.onGetErrorMessage === null || this.props.onGetErrorMessage === undefined) { this.notifyAfterValidate(this.props.query, value); return; } if (this.latestValidateValue === value) return; this.latestValidateValue = value; var result: string | PromiseLike<string> = this.props.onGetErrorMessage(value || ''); if (result !== undefined) { if (typeof result === 'string') { if (result === undefined || result === '') this.notifyAfterValidate(this.props.query, value); this.state.errorMessage = result; this.setState(this.state); } else { result.then((errorMessage: string) => { if (errorMessage === undefined || errorMessage === '') this.notifyAfterValidate(this.props.query, value); this.state.errorMessage = errorMessage; this.setState(this.state); }); } } else { this.notifyAfterValidate(this.props.query, value); } } /** * @function * Notifies the parent Web Part of a property value change */ private notifyAfterValidate(oldValue: string, newValue: string) { if (this.props.onPropertyChange && newValue != null) { this.props.properties[this.props.targetProperty] = newValue; this.props.onPropertyChange(this.props.targetProperty, oldValue, newValue); if (!this.props.disableReactivePropertyChanges && this.props.render != null) this.props.render(); } } /** * @function * Called when the component will unmount */ public componentWillUnmount() { this.async.dispose(); } /** * @function * Raises when a list has been selected */ private onChangedList(option: IDropdownOption, index?: number): void { this.state.selectedList = option.key as string; this.saveQuery(); this.saveState(); this.loadFields(); } private onChangedField(option: IDropdownOption, index?: number): void { this.state.selectedField = option.key as string; this.saveQuery(); this.saveState(); } private onChangedArranged(option: IDropdownOption, index?: number): void { this.state.selectedArrange = option.key as string; this.saveQuery(); this.saveState(); } private onChangedMax(newValue?: number): void { this.state.max = newValue; this.saveQuery(); this.saveState(); } private onClickAddFilter(elm?: any): void { this.state.filters.push({}); this.saveState(); this.saveQuery(); } private onClickRemoveFilter(index: number): void { if (index > -1) { this.state.filters.splice(index, 1); this.saveState(); this.saveQuery(); } } private onChangedFilterField(option: IDropdownOption, index?: number, selectedIndex?: number): void { this.state.filters[selectedIndex].field = option.key as string; this.saveState(); this.saveQuery(); } private onChangedFilterOperator(option: IDropdownOption, index?: number, selectedIndex?: number): void { this.state.filters[selectedIndex].operator = option.key as string; this.saveState(); this.saveQuery(); } private onChangedFilterValue(value?: string, index?: number): void { this.state.filters[index].value = value; this.saveState(); this.saveQuery(); } /** * @function * Renders the controls */ public render(): JSX.Element { if (this.state.loadedList === false || this.state.loadedFields === false) { return ( <div> <Label>{this.props.label}</Label> <Spinner type={ SpinnerType.normal } /> </div> ); } //Renders content return ( <div> <Label>{this.props.label}</Label> <Dropdown label={strings.SPListQueryList} onChanged={this.onChangedList} options={this.state.lists} selectedKey={this.state.selectedList} disabled={this.props.disabled} /> {this.props.showOrderBy != false ? <div> <Dropdown label={strings.SPListQueryOrderBy} options={this.state.fields} selectedKey={this.state.selectedField} onChanged={this.onChangedField} disabled={this.props.disabled === false && this.state.selectedList != null && this.state.selectedList != '' ? false : true } /> <Dropdown label={strings.SPListQueryArranged} options={this.state.arranged} selectedKey={this.state.selectedArrange} onChanged={this.onChangedArranged} disabled={this.props.disabled === false && this.state.selectedList != null && this.state.selectedList != '' ? false : true } /> </div> : ''} {this.props.showMax != false ? <Slider label={strings.SPListQueryMax} min={0} max={this.props.max == null ? 500 : this.props.max} defaultValue={this.state.max} onChange={this.onChangedMax} disabled={this.props.disabled === false && this.state.selectedList != null && this.state.selectedList != '' ? false : true } /> : ''} {this.state.filters.map((value: IFilter, index: number) => { return ( <div> <Label>Filter</Label> <Dropdown label='' disabled={this.props.disabled} options={this.state.fields} selectedKey={value.field} onChanged={(option: IDropdownOption, selectIndex?: number) => this.onChangedFilterField(option, selectIndex, index)} /> <Dropdown label='' disabled={this.props.disabled} options={this.state.operators} selectedKey={value.operator} onChanged={(option: IDropdownOption, selectIndex?: number) => this.onChangedFilterOperator(option, selectIndex, index)} /> <TextField disabled={this.props.disabled} defaultValue={value.value} onChanged={(value2: string) => this.onChangedFilterValue(value2, index)} /> <CommandButton disabled={this.props.disabled} onClick={() => this.onClickRemoveFilter(index)} iconProps={ { iconName: 'Delete' } }> {strings.SPListQueryRemove} </CommandButton> </div> ); }) } {this.props.showFilters != false ? <CommandButton onClick={this.onClickAddFilter} disabled={this.props.disabled === false && this.state.selectedList != null && this.state.selectedList != '' ? false : true } iconProps={ { iconName: 'Add' } }> {strings.SPListQueryAdd} </CommandButton> : ''} { this.state.errorMessage != null && this.state.errorMessage != '' && this.state.errorMessage != undefined ? <div style={{paddingBottom: '8px'}}><div aria-live='assertive' className='ms-u-screenReaderOnly' data-automation-id='error-message'>{ this.state.errorMessage }</div> <span> <p className='ms-TextField-errorMessage ms-u-slideDownIn20'>{ this.state.errorMessage }</p> </span> </div> : ''} </div> ); } } /** * @interface * Defines a collection of SharePoint lists */ interface ISPLists { value: ISPList[]; } /** * @interface * Defines a SharePoint list */ interface ISPList { Title: string; Id: string; BaseTemplate: string; } interface ISPField { Title: string; StaticName: string; } interface ISPFields { value: ISPField[]; } /** * @class * Service implementation to get list & list items from current SharePoint site */ class SPListPickerService { private context: IWebPartContext; private props: IPropertyFieldSPListQueryHostProps; /** * @function * Service constructor */ constructor(_props: IPropertyFieldSPListQueryHostProps, pageContext: IWebPartContext){ this.props = _props; this.context = pageContext; } public getFields(listId: string): Promise<ISPFields> { if (Environment.type === EnvironmentType.Local) { //If the running environment is local, load the data from the mock return this.getFieldsFromMock(); } else { var queryUrl: string = this.context.pageContext.web.absoluteUrl; queryUrl += "/_api/lists(guid'"; queryUrl += listId; queryUrl += "')/Fields?$select=Title,StaticName&$orderBy=Title&$filter=Hidden%20eq%20false"; return this.context.spHttpClient.get(queryUrl, SPHttpClient.configurations.v1).then((response: SPHttpClientResponse) => { return response.json(); }); } } /** * @function * Gets the collection of libs in the current SharePoint site */ public getLibs(): Promise<ISPLists> { if (Environment.type === EnvironmentType.Local) { //If the running environment is local, load the data from the mock return this.getLibsFromMock(); } else { //If the running environment is SharePoint, request the lists REST service var queryUrl: string = this.context.pageContext.web.absoluteUrl; queryUrl += "/_api/lists?$select=Title,id,BaseTemplate"; if (this.props.orderBy != null) { queryUrl += "&$orderby="; if (this.props.orderBy == PropertyFieldSPListQueryOrderBy.Id) queryUrl += "Id"; else if (this.props.orderBy == PropertyFieldSPListQueryOrderBy.Title) queryUrl += "Title"; } if (this.props.baseTemplate != null && this.props.baseTemplate) { queryUrl += "&$filter=BaseTemplate%20eq%20"; queryUrl += this.props.baseTemplate; if (this.props.includeHidden === false) { queryUrl += "%20and%20Hidden%20eq%20false"; } } else { if (this.props.includeHidden === false) { queryUrl += "&$filter=Hidden%20eq%20false"; } } return this.context.spHttpClient.get(queryUrl, SPHttpClient.configurations.v1).then((response: SPHttpClientResponse) => { return response.json(); }); } } /** * @function * Returns 3 fake SharePoint lists for the Mock mode */ private getLibsFromMock(): Promise<ISPLists> { return SPListPickerMockHttpClient.getLists(this.context.pageContext.web.absoluteUrl).then(() => { const listData: ISPLists = { value: [ { Title: 'Mock List One', Id: '6770c83b-29e8-494b-87b6-468a2066bcc6', BaseTemplate: '109' }, { Title: 'Mock List Two', Id: '2ece98f2-cc5e-48ff-8145-badf5009754c', BaseTemplate: '109' }, { Title: 'Mock List Three', Id: 'bd5dbd33-0e8d-4e12-b289-b276e5ef79c2', BaseTemplate: '109' } ] }; return listData; }) as Promise<ISPLists>; } private getFieldsFromMock(): Promise<ISPFields> { return SPListPickerMockHttpClient.getFields(this.context.pageContext.web.absoluteUrl).then(() => { const listData: ISPFields = { value: [ { Title: 'ID', StaticName: 'ID'}, { Title: 'Title', StaticName: 'Title'}, { Title: 'Created', StaticName: 'Created'}, { Title: 'Modified', StaticName: 'Modified'} ] }; return listData; }) as Promise<ISPFields>; } } /** * @class * Defines a http client to request mock data to use the web part with the local workbench */ class SPListPickerMockHttpClient { /** * @var * Mock SharePoint result sample */ private static _results: ISPLists = { value: []}; private static _resultsF: ISPFields = { value: []}; /** * @function * Mock search People method */ public static getLists(restUrl: string, options?: any): Promise<ISPLists> { return new Promise<ISPLists>((resolve) => { resolve(SPListPickerMockHttpClient._results); }); } public static getFields(restUrl: string, options?: any): Promise<ISPFields> { return new Promise<ISPFields>((resolve) => { resolve(SPListPickerMockHttpClient._resultsF); }); } }
the_stack
export interface DisableRsgAsGroupRequest { /** * 伸缩组 ID */ Id: string; } /** * ExposeService返回参数结构体 */ export interface ExposeServiceResponse { /** * 暴露方式 */ Expose?: ExposeInfo; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * 伸缩组活动关联的节点 */ export interface RsgAsActivityRelatedInstance { /** * 节点 ID */ InstanceId: string; /** * 节点状态 */ InstanceStatus: string; } /** * DeleteJob返回参数结构体 */ export interface DeleteJobResponse { /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * DeleteRuntime返回参数结构体 */ export interface DeleteRuntimeResponse { /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * CreateJob请求参数结构体 */ export interface CreateJobRequest { /** * 任务名称 */ Name: string; /** * 使用的资源组 Id,默认使用共享资源组 */ ResourceGroupId: string; /** * 处理器配置, 单位为1/1000核;范围[100, 256000] */ Cpu: number; /** * 内存配置, 单位为1M;范围[100, 256000] */ Memory: number; /** * 运行集群 */ Cluster?: string; /** * 预测输入 */ PredictInput?: PredictInput; /** * 任务描述 */ Description?: string; /** * 同时处理任务的 Worker 个数 */ WorkerCount?: number; /** * 使用的配置 Id */ ConfigId?: string; /** * GPU算力配置,单位为1/1000 卡,范围 [0, 256000] */ Gpu?: number; /** * 显存配置, 单位为1M,范围 [0, 256000] */ GpuMemory?: number; /** * GPU类型 */ GpuType?: string; /** * 量化输入 */ QuantizationInput?: QuantizationInput; /** * Cls日志主题ID */ LogTopicId?: string; } /** * ExposeService请求参数结构体 */ export interface ExposeServiceRequest { /** * 服务Id */ ServiceId: string; /** * 暴露方式,支持 EXTERNAL(外网暴露),VPC (VPC内网打通) */ ExposeType: string; /** * 暴露方式为 VPC 时,填写需要打通的私有网络Id */ VpcId?: string; /** * 暴露方式为 VPC 时,填写需要打通的子网Id */ SubnetId?: string; } /** * DescribeServiceConfigs返回参数结构体 */ export interface DescribeServiceConfigsResponse { /** * 服务配置 */ ServiceConfigs?: Array<Config>; /** * 服务配置总数 */ TotalCount?: number; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * 扩缩容配置 */ export interface Scaler { /** * 最大副本数,ScaleMode 为 MANUAL 时辞会此值会被置为 StartReplicas 取值 */ MaxReplicas: number; /** * 最小副本数,ScaleMode 为 MANUAL 时辞会此值会被置为 StartReplicas 取值 */ MinReplicas: number; /** * 起始副本数 */ StartReplicas: number; /** * 扩缩容指标,选择自动扩缩容时至少需要选择一个指标,支持CPU-UTIL、MEMORY-UTIL */ HpaMetrics?: Array<Option>; } /** * CreateJob返回参数结构体 */ export interface CreateJobResponse { /** * 任务 */ Job?: Job; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * DeleteService返回参数结构体 */ export interface DeleteServiceResponse { /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * DescribeRsgAsGroups返回参数结构体 */ export interface DescribeRsgAsGroupsResponse { /** * 所查询的伸缩组数组 */ RsgAsGroupSet?: Array<RsgAsGroup>; /** * 伸缩组数组总数目 */ TotalCount?: number; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * UpdateService返回参数结构体 */ export interface UpdateServiceResponse { /** * 服务 */ Service?: ModelService; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * 节点 */ export interface Instance { /** * 节点 ID */ Id: string; /** * 节点所在地区 */ Zone: string; /** * 节点类型 */ InstanceType: string; /** * 节点充值类型 */ InstanceChargeType: string; /** * Cpu 核数 */ Cpu: number; /** * 内存 */ Memory: number; /** * Gpu 核数 */ Gpu: number; /** * 节点状态 */ State: string; /** * 节点故障信息 */ AbnormalReason: string; /** * 创建时间 */ Created: string; /** * 更新时间 */ Updated: string; /** * 到期时间 */ DeadlineTime: string; /** * 所属资源组 ID */ ResourceGroupId: string; /** * 自动续费标签 */ RenewFlag: string; /** * 节点所在地域 */ Region: string; /** * 当前 Cpu 申请使用量 */ CpuRequested: number; /** * 当前 Memory 申请使用量 */ MemoryRequested: number; /** * 当前 Gpu 申请使用量 */ GpuRequested: number; /** * 节点所在伸缩组 ID */ RsgAsGroupId: string; } /** * UpdateRsgAsGroup返回参数结构体 */ export interface UpdateRsgAsGroupResponse { /** * 资源组的伸缩组 */ RsgAsGroup?: RsgAsGroup; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * DescribeServices返回参数结构体 */ export interface DescribeServicesResponse { /** * 服务列表 */ Services?: Array<ModelService>; /** * 服务总数 */ TotalCount?: number; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * DescribeResourceGroups返回参数结构体 */ export interface DescribeResourceGroupsResponse { /** * 资源组总数 */ TotalCount?: number; /** * 资源组列表 注意:此字段可能返回 null,表示取不到有效值。 */ ResourceGroups?: Array<ResourceGroup>; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * DescribeRsgAsGroups请求参数结构体 */ export interface DescribeRsgAsGroupsRequest { /** * 筛选选项 */ Filters?: Array<Filter>; /** * 偏移量,默认为 0 */ Offset?: number; /** * 返回数量,默认为 20,最大值为 200 */ Limit?: number; /** * 输出列表的排列顺序。取值范围:"ASC", "DESC" */ Order?: string; /** * 排序的依据字段, 取值范围 "CREATE_TIME", "UPDATE_TIME", "NAME" */ OrderField?: string; } /** * DeleteResourceGroup请求参数结构体 */ export interface DeleteResourceGroupRequest { /** * 要删除的资源组 ID */ ResourceGroupId: string; } /** * 状态 */ export interface Conditions { /** * 原因 */ Reason: string; /** * 具有相同原因的副本个数 */ Count: number; } /** * DescribeServiceConfigs请求参数结构体 */ export interface DescribeServiceConfigsRequest { /** * 筛选选项,支持按照name等进行筛选 */ Filters?: Array<Filter>; /** * 偏移量,默认为0 */ Offset?: number; /** * 返回数量,默认为20,最大值为1000 */ Limit?: number; /** * 输出列表的排列顺序。取值范围:ASC:升序排列 DESC:降序排列 */ Order?: string; /** * 排序的依据字段, 取值范围 "CREATE_TIME", "UPDATE_TIME", "NAME" */ OrderField?: string; /** * 是否按照配置名分页 */ PageByName?: boolean; } /** * DeleteRsgAsGroup请求参数结构体 */ export interface DeleteRsgAsGroupRequest { /** * 伸缩组 ID */ Id: string; } /** * 实例信息 */ export interface ReplicaInfo { /** * 实例名称 */ Name: string; /** * 弹性网卡模式时,弹性网卡Ip 注意:此字段可能返回 null,表示取不到有效值。 */ EniIp: string; /** * Normal: 正常运行中; Abnormal: 异常;Waiting:等待中 */ Status: string; /** * 当 status为 Abnormal 的时候,一些额外的信息 注意:此字段可能返回 null,表示取不到有效值。 */ Message: string; /** * 启动时间 注意:此字段可能返回 null,表示取不到有效值。 */ StartTime: string; /** * 创建时间 注意:此字段可能返回 null,表示取不到有效值。 */ CreateTime: string; /** * 重启次数 */ Restarted: number; } /** * DeleteServiceConfig返回参数结构体 */ export interface DeleteServiceConfigResponse { /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * UpdateRsgAsGroup请求参数结构体 */ export interface UpdateRsgAsGroupRequest { /** * 伸缩组 ID */ Id: string; /** * 重命名名称 */ Name?: string; /** * 伸缩组最大节点数 */ MaxSize?: number; /** * 伸缩组最小节点数 */ MinSize?: number; /** * 伸缩组期望的节点数 */ DesiredSize?: number; } /** * DeleteRsgAsGroup返回参数结构体 */ export interface DeleteRsgAsGroupResponse { /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * 配置 */ export interface Config { /** * Id */ Id: string; /** * 配置名 */ Name: string; /** * 模型地址 */ ModelUri: string; /** * 创建时间 */ CreateTime: string; /** * 运行环境 */ Runtime: string; /** * 配置版本 */ Version: string; /** * 更新时间 */ UpdateTime: string; /** * 配置描述 注意:此字段可能返回 null,表示取不到有效值。 */ Description: string; } /** * 配置项 */ export interface Option { /** * 名称 */ Name: string; /** * 取值 */ Value: number; } /** * 预测输入 */ export interface PredictInput { /** * 输入路径,支持 cos 格式路径文件夹或文件 */ InputPath: string; /** * 输出路径,支持 cos 格式路径 */ OutputPath: string; /** * 输入数据格式,目前支持:JSON */ InputDataFormat?: string; /** * 输出数据格式,目前支持:JSON */ OutputDataFormat?: string; /** * 预测批大小,默认为 64 */ BatchSize?: number; /** * 模型签名 注意:此字段可能返回 null,表示取不到有效值。 */ SignatureName?: string; } /** * CreateRuntime返回参数结构体 */ export interface CreateRuntimeResponse { /** * 运行环境 */ Runtime?: Runtime; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * 任务 */ export interface Job { /** * 任务 Id */ Id: string; /** * 集群名 注意:此字段可能返回 null,表示取不到有效值。 */ Cluster: string; /** * Region 名 */ Region: string; /** * 任务名称 */ Name: string; /** * Worker 使用的运行环境 注意:此字段可能返回 null,表示取不到有效值。 */ Runtime: string; /** * 任务描述 注意:此字段可能返回 null,表示取不到有效值。 */ Description: string; /** * 配置 Id 注意:此字段可能返回 null,表示取不到有效值。 */ ConfigId: string; /** * 预测输入 注意:此字段可能返回 null,表示取不到有效值。 */ PredictInput: PredictInput; /** * 任务状态 */ Status: JobStatus; /** * 任务创建时间 */ CreateTime: string; /** * 任务开始时间 注意:此字段可能返回 null,表示取不到有效值。 */ StartTime: string; /** * 任务结束时间 注意:此字段可能返回 null,表示取不到有效值。 */ EndTime: string; /** * 任务取消时间 注意:此字段可能返回 null,表示取不到有效值。 */ CancelTime: string; /** * 任务使用资源组 Id 注意:此字段可能返回 null,表示取不到有效值。 */ ResourceGroupId: string; /** * 处理器配置, 单位为1/1000核;范围[100, 256000] 注意:此字段可能返回 null,表示取不到有效值。 */ Cpu: number; /** * 内存配置, 单位为1M;范围[100, 256000] 注意:此字段可能返回 null,表示取不到有效值。 */ Memory: number; /** * GPU算力配置,单位为1/1000 卡,范围 [0, 256000] 注意:此字段可能返回 null,表示取不到有效值。 */ Gpu: number; /** * 显存配置, 单位为1M,范围 [0, 256000] 注意:此字段可能返回 null,表示取不到有效值。 */ GpuMemory: number; /** * 任务使用资源组名称 注意:此字段可能返回 null,表示取不到有效值。 */ ResourceGroupName: string; /** * GPU类型 注意:此字段可能返回 null,表示取不到有效值。 */ GpuType: string; /** * 配置名 注意:此字段可能返回 null,表示取不到有效值。 */ ConfigName: string; /** * 配置版本 注意:此字段可能返回 null,表示取不到有效值。 */ ConfigVersion: string; /** * Job类型 注意:此字段可能返回 null,表示取不到有效值。 */ JobType: string; /** * 量化输入 注意:此字段可能返回 null,表示取不到有效值。 */ QuantizationInput: QuantizationInput; /** * Cls日志主题ID 注意:此字段可能返回 null,表示取不到有效值。 */ LogTopicId: string; } /** * UpdateJob请求参数结构体 */ export interface UpdateJobRequest { /** * 任务 Id */ JobId: string; /** * 任务更新动作,支持:Cancel */ JobAction?: string; /** * 备注 */ Description?: string; } /** * DescribeResourceGroups请求参数结构体 */ export interface DescribeResourceGroupsRequest { /** * 筛选选项 */ Filters?: Array<Filter>; /** * 偏移量,默认为0 */ Offset?: number; /** * 返回数量,默认为20,最大值为200 */ Limit?: number; /** * 输出列表的排列顺序。取值范围:ASC:升序排列 DESC:降序排列 */ Order?: string; /** * 排序的依据字段, 取值范围 "CREATE_TIME", "UPDATE_TIME", "NAME" */ OrderField?: string; } /** * DescribeRuntimes返回参数结构体 */ export interface DescribeRuntimesResponse { /** * TIEMS支持的运行环境列表 */ Runtimes?: Array<Runtime>; /** * 用户对runtime对权限 注意:此字段可能返回 null,表示取不到有效值。 */ UserAccess?: number; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * DeleteInstance返回参数结构体 */ export interface DeleteInstanceResponse { /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * DescribeInstances返回参数结构体 */ export interface DescribeInstancesResponse { /** * 资源组下节点总数 */ TotalCount?: number; /** * 资源组下节点列表 */ Instances?: Array<Instance>; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * DeleteResourceGroup返回参数结构体 */ export interface DeleteResourceGroupResponse { /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * DisableRsgAsGroup返回参数结构体 */ export interface DisableRsgAsGroupResponse { /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * DescribeInstances请求参数结构体 */ export interface DescribeInstancesRequest { /** * 筛选选项 */ Filters?: Array<Filter>; /** * 偏移量,默认为0 */ Offset?: number; /** * 返回数量,默认为20,最大值为200 */ Limit?: number; /** * 输出列表的排列顺序。取值范围:ASC:升序排列 DESC:降序排列 */ Order?: string; /** * 排序的依据字段, 取值范围 "CREATE_TIME", "UPDATE_TIME", "NAME" */ OrderField?: string; /** * 要查询的资源组 ID */ ResourceGroupId?: string; } /** * CreateService返回参数结构体 */ export interface CreateServiceResponse { /** * 服务 */ Service?: ModelService; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * CreateService请求参数结构体 */ export interface CreateServiceRequest { /** * 扩缩容配置 */ Scaler: Scaler; /** * 服务配置Id */ ServiceConfigId: string; /** * 服务名称 */ Name: string; /** * 扩缩容方式,支持AUTO, MANUAL,分别表示自动扩缩容和手动扩缩容 */ ScaleMode: string; /** * 部署要使用的资源组Id,默认为共享资源组 */ ResourceGroupId: string; /** * 处理器配置, 单位为1/1000核;范围[100, 256000] */ Cpu: number; /** * 内存配置, 单位为1M;范围[100, 256000] */ Memory: number; /** * 集群,不填则使用默认集群 */ Cluster?: string; /** * 默认为空,表示不需要鉴权,TOKEN 表示选择 Token 鉴权方式 */ Authentication?: string; /** * GPU算力配置,单位为1/1000 卡,范围 [0, 256000] */ Gpu?: number; /** * 显存配置, 单位为1M,范围 [0, 256000] */ GpuMemory?: number; /** * 备注 */ Description?: string; /** * GPU类型 */ GpuType?: string; /** * Cls日志主题ID */ LogTopicId?: string; } /** * EnableRsgAsGroup返回参数结构体 */ export interface EnableRsgAsGroupResponse { /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * 任务状态 */ export interface JobStatus { /** * 任务状态 */ Status: string; /** * 错误时为错误描述 注意:此字段可能返回 null,表示取不到有效值。 */ Message: string; /** * 预期Worker数量 注意:此字段可能返回 null,表示取不到有效值。 */ DesiredWorkers: number; /** * 当前Worker数量 注意:此字段可能返回 null,表示取不到有效值。 */ CurrentWorkers: number; /** * 副本名 注意:此字段可能返回 null,表示取不到有效值。 */ Replicas: Array<string>; /** * 副本实例 注意:此字段可能返回 null,表示取不到有效值。 */ ReplicaInfos: Array<ReplicaInfo>; } /** * UpdateService请求参数结构体 */ export interface UpdateServiceRequest { /** * 服务Id */ ServiceId: string; /** * 扩缩容配置 */ Scaler?: Scaler; /** * 服务配置Id */ ServiceConfigId?: string; /** * 支持AUTO, MANUAL,分别表示自动扩缩容,手动扩缩容 */ ScaleMode?: string; /** * 支持STOP(停止) RESUME(重启) */ ServiceAction?: string; /** * 备注 */ Description?: string; /** * GPU卡类型 */ GpuType?: string; /** * 处理器配置,单位为 1/1000 核 */ Cpu?: number; /** * 内存配置,单位为1M */ Memory?: number; /** * 显卡配置,单位为 1/1000 卡 */ Gpu?: number; /** * Cls日志主题ID */ LogTopicId?: string; } /** * 筛选项 */ export interface Filter { /** * 名称 */ Name: string; /** * 取值 */ Values: Array<string>; } /** * CreateServiceConfig返回参数结构体 */ export interface CreateServiceConfigResponse { /** * 服务配置 */ ServiceConfig?: Config; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * 暴露信息 */ export interface ExposeInfo { /** * 暴露方式,支持 EXTERNAL(外网暴露),VPC (VPC内网打通) */ ExposeType: string; /** * 暴露Ip。暴露方式为 EXTERNAL 为外网 Ip,暴露方式为 VPC 时为指定 Vpc 下的Vip */ Ip: string; /** * 暴露方式为 VPC 时,打通的私有网络Id 注意:此字段可能返回 null,表示取不到有效值。 */ VpcId: string; /** * 暴露方式为 VPC 时,打通的子网Id 注意:此字段可能返回 null,表示取不到有效值。 */ SubnetId: string; /** * GATEWAY 服务id,ExposeType = GATEWAY 时返回 注意:此字段可能返回 null,表示取不到有效值。 */ GateWayServiceId: string; /** * GATEWAY api id,ExposeType = GATEWAY 时返回 注意:此字段可能返回 null,表示取不到有效值。 */ GateWayAPIId: string; /** * GATEWAY domain,ExposeType = GATEWAY 时返回 注意:此字段可能返回 null,表示取不到有效值。 */ GateWayDomain: string; } /** * 资源组的伸缩组 */ export interface RsgAsGroup { /** * 伸缩组 ID */ Id: string; /** * 伸缩组所在地域 */ Region: string; /** * 伸缩组所在可用区 */ Zone: string; /** * 伸缩组所在集群 */ Cluster: string; /** * 伸缩组所在资源组 ID */ RsgId: string; /** * 伸缩组名称 */ Name: string; /** * 伸缩组允许的最大节点个数 */ MaxSize: number; /** * 伸缩组允许的最小节点个数 */ MinSize: number; /** * 伸缩组创建时间 */ CreateTime: string; /** * 伸缩组更新时间 */ UpdateTime: string; /** * 伸缩组状态 */ Status: string; /** * 伸缩组节点类型 */ InstanceType: string; /** * 伸缩组内节点个数 */ InstanceCount: number; /** * 伸缩组起始节点数 */ DesiredSize: number; } /** * DeleteService请求参数结构体 */ export interface DeleteServiceRequest { /** * 服务Id */ ServiceId: string; } /** * 运行环境 */ export interface Runtime { /** * 运行环境名称 */ Name: string; /** * 运行环境框架 */ Framework: string; /** * 运行环境描述 */ Description: string; /** * 是否为公开运行环境 注意:此字段可能返回 null,表示取不到有效值。 */ Public: boolean; /** * 是否打开健康检查 注意:此字段可能返回 null,表示取不到有效值。 */ HealthCheckOn: boolean; /** * 镜像地址 注意:此字段可能返回 null,表示取不到有效值。 */ Image: string; /** * 创建时间 注意:此字段可能返回 null,表示取不到有效值。 */ CreateTime: string; } /** * CreateRsgAsGroup返回参数结构体 */ export interface CreateRsgAsGroupResponse { /** * 所创建的资源组的伸缩组 */ RsgAsGroup?: RsgAsGroup; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * 服务状态 */ export interface ServiceStatus { /** * 预期副本数 */ DesiredReplicas: number; /** * 当前副本数 */ CurrentReplicas: number; /** * Normal:正常运行中;Abnormal:服务异常,例如容器启动失败等;Waiting:服务等待中,例如容器下载镜像过程等;Stopped:已停止 Stopping 停止中;Resuming:重启中;Updating:服务更新中 */ Status: string; /** * 服务处于当前状态的原因集合 注意:此字段可能返回 null,表示取不到有效值。 */ Conditions: Array<Conditions>; /** * 副本名称 注意:此字段可能返回 null,表示取不到有效值。 */ Replicas: Array<string>; /** * 运行状态对额外信息 注意:此字段可能返回 null,表示取不到有效值。 */ Message: string; /** * 副本信息 注意:此字段可能返回 null,表示取不到有效值。 */ ReplicaInfos: Array<ReplicaInfo>; } /** * 伸缩组活动信息 */ export interface RsgAsGroupActivity { /** * 伸缩组活动 ID */ Id: string; /** * 关联的伸缩组 ID */ RsgAsGroupId: string; /** * 活动类型 */ ActivityType: string; /** * 状态的编码 */ StatusCode: string; /** * 状态的消息 */ StatusMessage: string; /** * 活动原因 */ Cause: string; /** * 活动描述 */ Description: string; /** * 活动开始时间 */ StartTime: string; /** * 活动结束时间 */ EndTime: string; /** * 活动创建时间 */ CreateTime: string; /** * 活动相关联的节点 */ RsgAsActivityRelatedInstance: Array<RsgAsActivityRelatedInstance>; /** * 简略的状态消息 */ StatusMessageSimplified: string; } /** * DescribeRsgAsGroupActivities请求参数结构体 */ export interface DescribeRsgAsGroupActivitiesRequest { /** * 伸缩组 ID */ Id: string; /** * 查询活动的开始时间 */ StartTime?: string; /** * 查询互动的结束时间 */ EndTime?: string; /** * 筛选选项 */ Filters?: Array<Filter>; /** * 偏移量,默认为 0 */ Offset?: number; /** * 返回数量,默认为 20,最大值为 200 */ Limit?: number; /** * 输出列表的排列顺序。取值范围:"ASC", "DESC" */ Order?: string; /** * 排序的依据字段, 取值范围 "CREATE_TIME", "UPDATE_TIME", "NAME" */ OrderField?: string; } /** * 资源组 */ export interface ResourceGroup { /** * 资源组 Id */ Id: string; /** * 地域 */ Region: string; /** * 集群 注意:此字段可能返回 null,表示取不到有效值。 */ Cluster: string; /** * 资源组名称 */ Name: string; /** * 资源组描述 注意:此字段可能返回 null,表示取不到有效值。 */ Description: string; /** * 创建时间 */ Created: string; /** * 更新时间 */ Updated: string; /** * 资源组主机数量 注意:此字段可能返回 null,表示取不到有效值。 */ InstanceCount: number; /** * 使用资源组的服务数量 注意:此字段可能返回 null,表示取不到有效值。 */ ServiceCount: number; /** * 使用资源组的任务数量 注意:此字段可能返回 null,表示取不到有效值。 */ JobCount: number; /** * 资源组是否为公共资源组 注意:此字段可能返回 null,表示取不到有效值。 */ Public: boolean; /** * 机器类型 注意:此字段可能返回 null,表示取不到有效值。 */ InstanceType: string; /** * 资源组状态 注意:此字段可能返回 null,表示取不到有效值。 */ Status: string; /** * 显卡总张数 注意:此字段可能返回 null,表示取不到有效值。 */ Gpu: number; /** * 处理器总核数 注意:此字段可能返回 null,表示取不到有效值。 */ Cpu: number; /** * 内存总量,单位为G 注意:此字段可能返回 null,表示取不到有效值。 */ Memory: number; /** * 可用区 注意:此字段可能返回 null,表示取不到有效值。 */ Zone: string; /** * Gpu类型 注意:此字段可能返回 null,表示取不到有效值。 */ GpuType: Array<string>; /** * 该资源组下是否有预付费资源 注意:此字段可能返回 null,表示取不到有效值。 */ HasPrepaid: boolean; /** * 资源组是否允许预付费或后付费模式 注意:此字段可能返回 null,表示取不到有效值。 */ PayMode: string; } /** * DeleteJob请求参数结构体 */ export interface DeleteJobRequest { /** * 任务 Id */ JobId: string; } /** * DeleteInstance请求参数结构体 */ export interface DeleteInstanceRequest { /** * 要删除的节点 ID */ InstanceId: string; } /** * CreateRsgAsGroup请求参数结构体 */ export interface CreateRsgAsGroupRequest { /** * 资源组 ID */ RsgId: string; /** * 伸缩组允许的最大节点数 */ MaxSize: number; /** * 伸缩组允许的最小节点数 */ MinSize: number; /** * 伸缩组的节点规格 */ InstanceType: string; /** * 资源组所在的集群名 */ Cluster?: string; /** * 伸缩组名称 */ Name?: string; /** * 伸缩组期望的节点数 */ DesiredSize?: number; } /** * DescribeRuntimes请求参数结构体 */ export declare type DescribeRuntimesRequest = null; /** * EnableRsgAsGroup请求参数结构体 */ export interface EnableRsgAsGroupRequest { /** * 伸缩组 ID */ Id: string; } /** * CreateServiceConfig请求参数结构体 */ export interface CreateServiceConfigRequest { /** * 配置名称 */ Name: string; /** * 运行环境 */ Runtime: string; /** * 模型地址,支持cos路径,格式为 cos://bucket名-appid.cos.region名.myqcloud.com/模型文件夹路径。为模型文件的上一层文件夹地址。 */ ModelUri: string; /** * 配置描述 */ Description?: string; } /** * 量化输入 */ export interface QuantizationInput { /** * 量化输入路径 */ InputPath: string; /** * 量化输出路径 */ OutputPath: string; /** * 量化批大小 */ BatchSize?: number; /** * 量化精度,支持:FP32,FP16,INT8 */ Precision?: string; /** * 转换类型 */ ConvertType?: string; } /** * UpdateJob返回参数结构体 */ export interface UpdateJobResponse { /** * 任务 注意:此字段可能返回 null,表示取不到有效值。 */ Job?: Job; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * CreateRuntime请求参数结构体 */ export interface CreateRuntimeRequest { /** * 全局唯一的运行环境名称 */ Name: string; /** * 运行环境镜像地址 */ Image: string; /** * 运行环境框架 */ Framework?: string; /** * 运行环境描述 */ Description?: string; /** * 是否支持健康检查,默认为False */ HealthCheckOn?: boolean; } /** * 模型服务 */ export interface ModelService { /** * 服务ID */ Id: string; /** * 运行集群 注意:此字段可能返回 null,表示取不到有效值。 */ Cluster: string; /** * 服务名称 */ Name: string; /** * 运行环境 */ Runtime: string; /** * 模型地址 */ ModelUri: string; /** * 处理器配置, 单位为1/1000核 */ Cpu: number; /** * 内存配置, 单位为1M */ Memory: number; /** * GPU 配置, 单位为1/1000 卡 */ Gpu: number; /** * 显存配置, 单位为1M */ GpuMemory: number; /** * 创建时间 */ CreateTime: string; /** * 更新时间 */ UpdateTime: string; /** * 支持AUTO, MANUAL */ ScaleMode: string; /** * 弹性伸缩配置 */ Scaler: Scaler; /** * 服务状态 */ Status: ServiceStatus; /** * 访问密钥 注意:此字段可能返回 null,表示取不到有效值。 */ AccessToken: string; /** * 服务配置Id */ ConfigId: string; /** * 服务配置名 */ ConfigName: string; /** * 服务运行时长 */ ServeSeconds: number; /** * 配置版本 注意:此字段可能返回 null,表示取不到有效值。 */ ConfigVersion: string; /** * 服务使用资源组 Id 注意:此字段可能返回 null,表示取不到有效值。 */ ResourceGroupId: string; /** * 暴露方式 注意:此字段可能返回 null,表示取不到有效值。 */ Exposes: Array<ExposeInfo>; /** * Region 名 注意:此字段可能返回 null,表示取不到有效值。 */ Region: string; /** * 服务使用资源组名称 注意:此字段可能返回 null,表示取不到有效值。 */ ResourceGroupName: string; /** * 备注 注意:此字段可能返回 null,表示取不到有效值。 */ Description: string; /** * GPU类型 注意:此字段可能返回 null,表示取不到有效值。 */ GpuType: string; /** * Cls日志主题Id 注意:此字段可能返回 null,表示取不到有效值。 */ LogTopicId: string; } /** * DeleteServiceConfig请求参数结构体 */ export interface DeleteServiceConfigRequest { /** * 服务配置Id */ ServiceConfigId?: string; /** * 服务配置名称 */ ServiceConfigName?: string; } /** * DeleteRuntime请求参数结构体 */ export interface DeleteRuntimeRequest { /** * 要删除的Runtime名 */ Runtime: string; } /** * DescribeRsgAsGroupActivities返回参数结构体 */ export interface DescribeRsgAsGroupActivitiesResponse { /** * 伸缩组活动数组 注意:此字段可能返回 null,表示取不到有效值。 */ RsgAsGroupActivitySet?: Array<RsgAsGroupActivity>; /** * 所查询的伸缩组活动总数目 */ TotalCount?: number; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string; } /** * DescribeServices请求参数结构体 */ export interface DescribeServicesRequest { /** * 筛选选项,支持筛选的字段:id, region, zone, cluster, status, runtime, rsg_id */ Filters?: Array<Filter>; /** * 偏移量,默认为0 */ Offset?: number; /** * 返回数量,默认为20,最大值为100 */ Limit?: number; /** * 输出列表的排列顺序。取值范围:ASC:升序排列 DESC:降序排列 */ Order?: string; /** * 排序的依据字段, 取值范围 "CREATE_TIME" "UPDATE_TIME" */ OrderField?: string; }
the_stack
import { IModelApp, MapLayerSource, NotifyMessageDetails, OutputMessagePriority } from "@itwin/core-frontend"; import { BeEvent, GuidString } from "@itwin/core-bentley"; import { MapLayersUI } from "./mapLayers"; /** @internal */ export interface MapLayerPreferencesContent { url: string; name: string; formatId: string; transparentBackground: boolean | undefined; } /** @internal */ export enum MapLayerSourceChangeType { Added = 0, Removed = 1, Replaced = 2, } /** @internal */ export interface MapLayerSourceArg { readonly source: MapLayerSource; readonly iTwinId: GuidString; readonly iModelId: GuidString; } /** A wrapper around user preferences to provide a way to store [[MapLayerSettings]]. * * Note: This is currently internal only and used directly by the MapLayersExtension. It makes use of the IModelApp.authorizationClient if it exists. * * @internal */ export class MapLayerPreferences { /** Event raised whenever a source is added, replaced or removed: * changeType : Type of changed occurred. * oldSource : Source that was removed or replaced. * newSource : Source that was added or replacement of oldSource. * * @see [[MapLayerSourceChangeType]] */ public static readonly onLayerSourceChanged = new BeEvent<(changeType: MapLayerSourceChangeType, oldSource?: MapLayerSource, newSource?: MapLayerSource) => void>(); // Used to notify the frontend that it needs to update its list of available layers /** Store the Map Layer source preference. If the same setting exists at a higher level, an error will be thrown and the setting will not be updated. * * Returns false if the settings object would override some other settings object in a larger scope i.e. storing settings on model when * a project setting exists with same name or map layer url. * @param source source to be stored on the setting service * @param storeOnIModel if true store the settings object on the model, if false store it on the project */ public static async storeSource(source: MapLayerSource, iTwinId: GuidString, iModelId?: GuidString, storeOnIModel?: boolean): Promise<boolean> { if (!MapLayersUI.iTwinConfig) return false; const accessToken = undefined !== IModelApp.authorizationClient ? (await IModelApp.authorizationClient.getAccessToken()) : undefined; const sourceJSON = source.toJSON(); const mapLayerSetting: MapLayerPreferencesContent = { url: sourceJSON.url, name: sourceJSON.name, formatId: sourceJSON.formatId, transparentBackground: sourceJSON.transparentBackground, }; const result: boolean = await MapLayerPreferences.delete(sourceJSON.url, sourceJSON.name, iTwinId, iModelId, storeOnIModel); if (result) { await MapLayersUI.iTwinConfig.save({ accessToken, content: mapLayerSetting, namespace: MapLayerPreferences._preferenceNamespace, key: sourceJSON.name, iTwinId, iModelId: storeOnIModel ? iModelId : undefined, }); MapLayerPreferences.onLayerSourceChanged.raiseEvent(MapLayerSourceChangeType.Added, undefined, MapLayerSource.fromJSON(mapLayerSetting)); return true; } else { return false; } } /** Replace the old map layer source with a new map layer source. * * The source is replaced at the same level that the original source is defined. (i.e. if the old source is defined at a project level, the new source will also be defined there.) * * @param oldSource * @param newSource * @param iTwinId * @param iModelId */ public static async replaceSource(oldSource: MapLayerSource, newSource: MapLayerSource, iTwinId: GuidString, iModelId?: GuidString): Promise<void> { if (!MapLayersUI.iTwinConfig) return; const accessToken = undefined !== IModelApp.authorizationClient ? (await IModelApp.authorizationClient.getAccessToken()) : undefined; let storeOnIModel = false; try { await MapLayersUI.iTwinConfig.delete({ accessToken, namespace: MapLayerPreferences._preferenceNamespace, key: oldSource.name, iTwinId, iModelId, }); } catch (_err) { await MapLayersUI.iTwinConfig.delete({ accessToken, namespace: MapLayerPreferences._preferenceNamespace, key: oldSource.name, iTwinId, }); storeOnIModel = true; } const mapLayerSetting: MapLayerPreferencesContent = { url: newSource.url, name: newSource.name, formatId: newSource.formatId, transparentBackground: newSource.transparentBackground, }; await MapLayersUI.iTwinConfig.save({ accessToken, key: `${MapLayerPreferences._preferenceNamespace}.${newSource.name}`, iTwinId, iModelId: storeOnIModel ? iModelId : undefined, content: mapLayerSetting, }); MapLayerPreferences.onLayerSourceChanged.raiseEvent(MapLayerSourceChangeType.Replaced, oldSource, newSource); } /** Deletes the provided MapLayerSource by name from both the iTwin or iModel level. * * @param source The source to delete. The name is used to identify the source. * @param iTwinId * @param iModelId */ public static async deleteByName(source: MapLayerSource, iTwinId: GuidString, iModelId?: GuidString): Promise<void> { if (!MapLayersUI.iTwinConfig) return; const accessToken = undefined !== IModelApp.authorizationClient ? (await IModelApp.authorizationClient.getAccessToken()) : undefined; try { await MapLayersUI.iTwinConfig.delete({ accessToken, namespace: MapLayerPreferences._preferenceNamespace, key: source.name, iTwinId, iModelId, }); } catch (_err) { // failed to store based on iModelId, attempt using iTwinId await MapLayersUI.iTwinConfig.delete({ accessToken, namespace: MapLayerPreferences._preferenceNamespace, key: source.name, iTwinId, }); } MapLayerPreferences.onLayerSourceChanged.raiseEvent(MapLayerSourceChangeType.Removed, source, undefined); } /** Deletes the current setting with the provided key if it is defined at the same preference level. * * If the preference is defined within a different level, false will be returned indicating the setting should not be overriden. * * The two potential preference levels are iTwin and iModel. * * @param url * @param name * @param iTwinId * @param iModelId * @param storeOnIModel */ private static async delete(url: string, name: string, iTwinId: GuidString, iModelId?: GuidString, storeOnIModel?: boolean): Promise<boolean> { if (!MapLayersUI.iTwinConfig) return true; const accessToken = undefined !== IModelApp.authorizationClient ? (await IModelApp.authorizationClient.getAccessToken()) : undefined; const iTwinPreferenceByName = await MapLayersUI.iTwinConfig.get({ accessToken, namespace: MapLayerPreferences._preferenceNamespace, key: name, iTwinId, }); if (undefined !== iTwinPreferenceByName && storeOnIModel) { const errorMessage = IModelApp.localization.getLocalizedString("mapLayers:CustomAttach.LayerExistsAsProjectSetting", { layer: iTwinPreferenceByName.name }); IModelApp.notifications.outputMessage(new NotifyMessageDetails(OutputMessagePriority.Error, errorMessage)); return false; } else if (iTwinPreferenceByName) { const infoMessage = IModelApp.localization.getLocalizedString("mapLayers:CustomAttach.LayerExistsOverwriting", { layer: iTwinPreferenceByName.name }); IModelApp.notifications.outputMessage(new NotifyMessageDetails(OutputMessagePriority.Info, infoMessage)); await MapLayersUI.iTwinConfig.delete({ accessToken, namespace: MapLayerPreferences._preferenceNamespace, key: iTwinPreferenceByName.name, iTwinId, }); } // check if setting with url already exists, if it does, delete it const settingFromUrl = await MapLayerPreferences.getByUrl(url, iTwinId, undefined); if (settingFromUrl && storeOnIModel) { const errorMessage = IModelApp.localization.getLocalizedString("mapLayers:CustomAttach.LayerWithUrlExistsAsProjectSetting", { url: settingFromUrl.url, name: settingFromUrl.name }); IModelApp.notifications.outputMessage(new NotifyMessageDetails(OutputMessagePriority.Error, errorMessage)); return false; } else if (settingFromUrl) { const infoMessage = IModelApp.localization.getLocalizedString("mapLayers:CustomAttach.LayerWithUrlExistsOverwriting", { url: settingFromUrl.url, oldName: settingFromUrl.name, newName: name }); IModelApp.notifications.outputMessage(new NotifyMessageDetails(OutputMessagePriority.Info, infoMessage)); await MapLayersUI.iTwinConfig.delete({ accessToken, namespace: MapLayerPreferences._preferenceNamespace, key: settingFromUrl.name, iTwinId, }); } if (iModelId) { // delete any settings on model so user can update them if theres collisions const settingOnIModelFromName = await MapLayersUI.iTwinConfig.get({ accessToken, namespace: MapLayerPreferences._preferenceNamespace, key: name, iTwinId, iModelId, }); const settingFromUrlOnIModel = await MapLayerPreferences.getByUrl(url, iTwinId, iModelId); if (settingOnIModelFromName) { const infoMessage = IModelApp.localization.getLocalizedString("mapLayers:CustomAttach.LayerExistsOverwriting", { layer: settingOnIModelFromName.name }); IModelApp.notifications.outputMessage(new NotifyMessageDetails(OutputMessagePriority.Info, infoMessage)); await MapLayersUI.iTwinConfig.delete({ accessToken, namespace: MapLayerPreferences._preferenceNamespace, key: settingOnIModelFromName.name, iTwinId, iModelId, }); } if (settingFromUrlOnIModel) { const infoMessage = IModelApp.localization.getLocalizedString("mapLayers:CustomAttach.LayerWithUrlExistsOverwriting", { url: settingFromUrlOnIModel.url, oldName: settingFromUrlOnIModel.name, newName: name }); IModelApp.notifications.outputMessage(new NotifyMessageDetails(OutputMessagePriority.Info, infoMessage)); await MapLayersUI.iTwinConfig.delete({ accessToken, namespace: MapLayerPreferences._preferenceNamespace, key: settingFromUrlOnIModel.name, iTwinId, iModelId, }); } } return true; } /** Attempts to get a map layer based off a specific url. * @param url * @param iTwinId * @param iModelId */ public static async getByUrl(url: string, iTwinId: string, iModelId?: string): Promise<MapLayerPreferencesContent | undefined> { if (!MapLayersUI.iTwinConfig) return undefined; const accessToken = undefined !== IModelApp.authorizationClient ? (await IModelApp.authorizationClient.getAccessToken()) : undefined; const settingResponse = await MapLayersUI.iTwinConfig.get({ accessToken, namespace: MapLayerPreferences._preferenceNamespace, key: "", iTwinId, iModelId, }); if (undefined === settingResponse || 0 === settingResponse.length) return undefined; let savedMapLayer; settingResponse.settingsMap?.forEach((savedLayer: any) => { if (savedLayer.url === url) { savedMapLayer = savedLayer; } }); return savedMapLayer; } /** Get all MapLayerSources from the user's preferences, iTwin setting and iModel settings. * @param iTwinId id of the iTwin * @param iModelId id of the iModel * @throws if any of the calls to grab settings fail. */ public static async getSources(iTwinId: GuidString, iModelId?: GuidString): Promise<MapLayerSource[]> { if (!MapLayersUI.iTwinConfig) return []; const accessToken = undefined !== IModelApp.authorizationClient ? (await IModelApp.authorizationClient.getAccessToken()) : undefined; const mapLayerList = []; try { const userResultByProject = await MapLayersUI.iTwinConfig.get({ accessToken, namespace: MapLayerPreferences._preferenceNamespace, key: "", iTwinId, }); if (undefined !== userResultByProject) mapLayerList.push(userResultByProject); } catch (err: any) { throw new Error(IModelApp.localization.getLocalizedString("mapLayers:CustomAttach.ErrorRetrieveUserProject", { errorMessage: err })); } try { const userResultByIModel = await MapLayersUI.iTwinConfig.get({ accessToken, namespace: MapLayerPreferences._preferenceNamespace, key: "", iTwinId, iModelId, }); if (undefined !== userResultByIModel) mapLayerList.push(userResultByIModel); } catch (err: any) { throw new Error(IModelApp.localization.getLocalizedString("mapLayers:CustomAttach.ErrorRetrieveUserProject", { errorMessage: err })); } const savedMapLayerSources: MapLayerSource[] = []; for (const mapLayer of mapLayerList) { mapLayer.forEach((savedLayer: any) => { const mapLayerSource = MapLayerSource.fromJSON(savedLayer as MapLayerPreferencesContent); if (mapLayerSource) savedMapLayerSources.push(mapLayerSource); }); } return savedMapLayerSources; } private static get _preferenceNamespace() { return "MapLayerSource-SettingsService"; } }
the_stack
import {Labels} from '../labels/labels'; import {DebugProtocol} from 'vscode-debugprotocol/lib/debugProtocol'; import {Settings} from '../settings' import {Utility} from '../misc/utility'; import {RefList} from '../misc/reflist'; import {Remote} from '../remotes/remotebase'; import {Format} from '../disassembler/format'; import {DisassemblyClass} from '../misc/disassembly'; import {StepHistory} from '../remotes/cpuhistory'; /** * Represents a variable. * Variables know how to retrieve the data from the remote. */ export class ShallowVar { // Static bools to remember if some data type has been changed. // Is used to inform vscode about changes. public static pcChanged = false; public static spChanged = false; public static otherRegisterChanged = false; // Other than pc and sp public static memoryChanged = false; // Clears all remembered flags. public static clearChanged() { this.pcChanged = false; this.spChanged = false; this.otherRegisterChanged = false; this.memoryChanged = false; } /** * Override this. It should retrieve the contents of the variable. E.g. by communicating with the remote. * @param start The start index of the array. E.g. only the range [100..199] should be displayed. * @param count The number of bytes to display. */ public async getContent(start: number, count: number): Promise<Array<DebugProtocol.Variable>> { return []; } /** * Override if the variable or its properties can be set. * Sets the value of the variable. * The formatted read data is returned in the Promise. * @param name The name of data. * @param value The value to set. * @returns A Promise with the formatted string. undefined if not implemented. */ public async setValue(name: string, value: number): Promise<string> { return undefined as any; }; /** * Checks if allowed to change the value. * If not returns a string with an error message. * Override if necessary. * @param name The name of data. * @returns 'Altering values not allowed in time-travel mode.' or undefined. */ public changeable(name: string): string | undefined { // Change normally not allowed if in reverse debugging if (StepHistory.isInStepBackMode()) return 'Altering values not allowed in time-travel mode.'; // Otherwise allow return undefined; } } /** * Represents a ShallowVar that is const, i.e. not changeable by the user. */ export class ShallowVarConst extends ShallowVar { /** * Not changeable by user. * @param name The name of data. * @returns 'You cannot alter this value.' */ public changeable(name: string): string | undefined { return 'You cannot alter this value.'; } } /** * The DisassemblyVar class knows how to retrieve the disassembly from the remote. */ export class DisassemblyVar extends ShallowVarConst { /// The address the disassembly should start public address: number; /// The number of lines for the disassembly public count: number; /// Pointer to the disassembly history. protected disassemblyHistory: Array<{address: number, text: string}>; /** * Communicates with the Remote to retrieve the disassembly. * @returns A Promise with the disassembly. * A list with all disassembled lines is passed (as variables). */ public async getContent(start: number, count: number): Promise<Array<DebugProtocol.Variable>> { start = start || 0; count = count || (this.count - start); const end = start + count; // Get code memory const size = 4 * this.count; // 4 is the max size of an opcode const data = await Remote.readMemoryDump(this.address, size); // Disassemble const dasmArray = DisassemblyClass.getLines(this.address, data, this.count); // Add extra info const list = new Array<DebugProtocol.Variable>(); const dasmFiltered = dasmArray.filter((value, index) => (index >= start && index < end)); for (const entry of dasmFiltered) { const address = entry.address; // Add to list const addrString = Format.getHexString(address).toUpperCase(); const labels = Labels.getLabelsForNumber64k(address); let addrLabel = addrString; if (labels) addrLabel = labels.join(',\n'); list.push({ name: addrString, type: addrLabel, value: entry.instruction, variablesReference: 0 }); } // Pass data return list; } } /** * The MemorySlotsVar class knows how to retrieve the mapping of * memory slots and banks from Remote. */ export class MemorySlotsVar extends ShallowVarConst { /** * Constructor. */ public constructor() { super(); } /** * Communicates with the Remote to retrieve the memory pages. * @returns A Promise with the memory page data is available. * A list with start/end address and name (bank name) is passed. */ public async getContent(start: number, count: number): Promise<Array<DebugProtocol.Variable>> { start = start || 0; // Get code memory const memoryBanks = await Remote.getMemoryBanks(); count = count || (memoryBanks.length - start); // Convert array let slot = -1; const segments = new Array<DebugProtocol.Variable>(count); for (let i = 0; i < count; i++) { const bank = memoryBanks[i + start]; const name = Utility.getHexString(bank.start, 4) + '-' + Utility.getHexString(bank.end, 4); slot++; const slotString = slot.toString(); segments[i] = { name: slotString + ": " + name, type: "Slot " + slotString, value: bank.name, variablesReference: 0 }; }; // Return return segments; } } /** * The RegistersMainVar class knows how to retrieve the register values from Remote. */ export class RegistersMainVar extends ShallowVar { /** * Communicates with the remote to retrieve the register values. * @returns A Promise with the register values. * A list with all register values is passed (as variables). */ public async getContent(start: number, count: number): Promise<Array<DebugProtocol.Variable>> { start = start || 0; const regNames = this.registerNames(); count = count || (regNames.length - start); const registers = new Array<DebugProtocol.Variable>(count); for (let i = 0; i < count; i++) { const regName = regNames[i + start]; const formattedValue = Remote.getVarFormattedReg(regName); registers[i] = { name: regName, type: formattedValue, value: formattedValue, variablesReference: 0 }; } return registers; } /** * Sets the value of the variable. * The formatted read data is returned in the Promise. * @param name The name of the register, e.g. "HL" or "A" * @param value The value to set. * @returns A Promise with the formatted string. */ public async setValue(name: string, value: number): Promise<string> { // Set value (works always for registers. if (!isNaN(value)) { await Remote.setRegisterValue(name, value); await Remote.getRegistersFromEmulator(); // Handle PC special if (name == "PC") { StepHistory.clear(); ShallowVar.pcChanged = true; } if (name == "SP") { StepHistory.clear(); ShallowVar.spChanged = true; } else { ShallowVar.otherRegisterChanged = true; } } //await Remote.getRegisters() const formatted = Remote.getVarFormattedReg(name); return formatted; } /** * Checks if allowed to change the value. * If not returns a string with an error message. * @param name The name of data. * @returns 'Altering values not allowed in time-travel mode.' or undefined. */ public changeable(name: string): string | undefined { // Change normally not allowed if in reverse debugging if (StepHistory.isInStepBackMode()) return 'Altering values not allowed in time-travel mode.'; // Otherwise allow return undefined; } /** * Returns the register names to show. The 1rst half of the registers. */ protected registerNames(): Array<string> { return ["PC", "SP", "A", "F", "HL", "DE", "BC", "IX", "IY", "B", "C", "D", "E", "H", "L"]; } } /** * The RegistersMainVar class knows how to retrieve the register values from zeasrux. */ export class RegistersSecondaryVar extends RegistersMainVar { /** * Returns the register names to show. The 2nd half of the registers. */ protected registerNames(): Array<string> { return ["A'", "F'", "HL'", "DE'", "BC'", "IXH", "IXL", "IYH", "IYL", "I", "R", "IM"]; } } /** * The StackVar represents the stack variables. I.e. the pushed * registers that are on the stack. This stack contains only the pushed registers * until the next CALL return address. */ export class StackVar extends ShallowVar { private stack: Array<number>; /// The stack objects. private stackAddress: number; /// The start address of the stack. /** * Sets stack array and address. * @param stack The array containing the pushed data (address + value). * @param stackAddress The start address of the stack (the top). The stack grows to bottom. */ public setFrameAddress(stack: Array<number>, stackAddress: number) { this.stack = stack; this.stackAddress = stackAddress; } /** * Formats the stack. * @returns A Promise with the stack values. */ public async getContent(start: number, count: number): Promise<Array<DebugProtocol.Variable>> { start = start || 0; count = count || (this.stack.length - start); // Calculate tabsizing array const format = Settings.launch.formatting.stackVar; const tabSizes = Utility.calculateTabSizes(format, 2); // Create list const stackList = new Array<DebugProtocol.Variable>(count); let undefText = "unknown"; for (let i = 0; i < count; i++) { const index = i + start; const value = this.stack[index]; const formatted = await Utility.numberFormatted('', value, 2, format, tabSizes, undefText); stackList[i] = { name: Utility.getHexString(this.stackAddress - 2 * index, 4), type: formatted, value: formatted, variablesReference: 0 }; // Next undefText = undefined as any; } return stackList; } /** * Sets the value of the pushed stack data. * Value is set and afterwards read. * The formatted read data is returned in the Promise. * @param name The 'name', the address as hex value, e.g. "041Ah". * @param value The value to set. * @returns A Promise with the formatted string. */ public async setValue(name: string, value: number): Promise<string> { // Check if address and value are valid const address = Utility.parseValue(name + 'h'); if (!isNaN(address) && !isNaN(value)) { // Change neg to pos if (value < 0) value += 0x10000; const data = new Uint8Array(2); data[0] = value & 0xFF; data[1] = value >>> 8; await Remote.writeMemoryDump(address, data); ShallowVar.memoryChanged = true; } // Retrieve memory values, to see if they really have been set. const data = await Remote.readMemoryDump(address, 2); const memWord = data[0] + (data[1] << 8); // Pass formatted string to vscode const formattedString = Utility.numberFormatted(name, memWord, 2, Settings.launch.formatting.stackVar, undefined); return formattedString; } } /** * Object used for the SubStructVar to store elements in the array. */ interface SubStructItems { // The corresponding address and size. address: number, // The size (1 or 2). Only used if itemRef is a function call. elemSize: number; // The reference to the variable or (in case of an immediate value) // the callback which return the result string. itemRef: number | (() => string); // In case of array, the count: indexedVariables: number }; /** * The StructVar class is a container class which holds other properties (the elements of the * struct). I.e. SubStructVars. * The StructVar is the parent object which also holds the memory contents. * The SubStructVars refer to it. */ export class SubStructVar extends ShallowVar { // Holds a map with name and with the structure properties. protected propMap = new Map<string, SubStructItems>(); // If the value should be interpreted as little endian or not. protected littleEndian: boolean; /** * Constructor. * @param relIndex The relative address inside the parent's memory dump. * @param count The count of elements to display. The count of elements in the struct * (each can have a different size). * @param elemSize The size of this object. All elements together. * @param struct 'b'=byte, 'w'=word or 'bw' for byte and word. * @param props An array of names of the direct properties of the struct. * @param list The list of variables. The constructor adds the 2 pseudo variables to it. * @param parentStruct The parent object which holds the memory. If undefined createpropArray is not called. */ public constructor(relIndex: number, count: number, elemSize: number, struct: string, props: Array<string>, list: RefList<ShallowVar>, parentStruct?: StructVar) { super(); if (parentStruct) { // In case this is called in the constructor of StructVar this.littleEndian = parentStruct.littleEndian; this.createPropArray(relIndex, count, elemSize, struct, props, list, parentStruct); } } /** * Creates the propArray. * @param relIndex The relative address inside the parent's memory dump. * @param count The count of elements to display. The count of elements in the struct * (each can have a different size). * @param elemSize The size of this object. All elements together. * @param struct 'b'=byte, 'w'=word or 'bw' for byte and word. * @param props An array of names of the direct properties of the struct. * @param list The list of variables. The constructor adds the 2 pseudo variables to it. * @param parentStruct A reference to a parent struct which retrieves the memory for all sub structs. */ protected createPropArray(relIndex: number, count: number, elemSize: number, struct: string, props: Array<string>, list: RefList<ShallowVar>, parentStruct: StructVar) { // Now create a new variable for each const unsortedMap = new Map<number, string>(); for (const prop of props) { // Get the relative address const relAddr = Labels.getNumberFromString64k(struct + '.' + prop); unsortedMap.set(relAddr, prop); } // Sort map by indices const sortedMap = new Map([...unsortedMap.entries()].sort( (a, b) => a[0] - b[0] // Sort numbers (first element) )); // Add an end marker sortedMap.set(-1, ''); // Get all lengths of the leafs and dive into nodes let prevName; let prevIndex; let lastIndex = relIndex + elemSize; for (const [index, name] of sortedMap) { if (prevName) { let len; if (name) { // Create diff of the relative addresses len = index - prevIndex; } else { // Treat last element different // Create diff to the size len = lastIndex - prevIndex; } // Check for leaf or node const fullName = struct + '.' + prevName; const subProps = Labels.getSubLabels(fullName); const memIndex = prevIndex; const address = parentStruct.getAddress() + memIndex; const item: SubStructItems = { address, elemSize: 0, itemRef: 0, indexedVariables: 0 }; if (subProps.length > 0) { // Node item.itemRef = list.addObject(new SubStructVar(prevIndex, 1, len, fullName, subProps, list, parentStruct)); } else { // Leaf // Get value depending on len: 1 byte, 1 word or array. if (len <= 2) { // Byte or word item.elemSize = len; if (len == 0) { // Edge case: STRUCT ends with a label but no size item.itemRef = () => { return ''; } } else { item.itemRef = () => { const mem = parentStruct.getMemory(); const value = Utility.getUintFromMemory(mem, memIndex, len, this.littleEndian); // Is done only for little endian, if wanted it could be extended to big endian const result = Utility.getHexString(value, 2 * len) + 'h'; return result; }; } } else { // Array const memDumpVar = new MemDumpVar(parentStruct.getAddress(), elemSize, 1, parentStruct.littleEndian); memDumpVar.setParent(parentStruct, memIndex); item.itemRef = list.addObject(memDumpVar); item.indexedVariables = len; } } // Add to array this.propMap.set(prevName, item); } // Next prevName = name; prevIndex = index; } } /** * Returns the properties. * Ignores start and count for a struct. * @returns A Promise with the properties. */ public async getContent(start: number, count: number): Promise<Array<DebugProtocol.Variable>> { // Return range const dbgVarArray = new Array<DebugProtocol.Variable>(); for (const [name, item] of this.propMap) { // Add item to array for display let value = ''; let ref = 0; if (typeof item.itemRef == 'number') { // Variables reference ref = item.itemRef; } else { // Callback which retrieves the result value = item.itemRef(); } const result: DebugProtocol.Variable = { name: name, type: Utility.getHexString(item.address, 4) + 'h', value, variablesReference: ref, indexedVariables: item.indexedVariables }; dbgVarArray.push(result); } return dbgVarArray; } /** * Sets the value of the variable. * The formatted read data is returned in the Promise. * @param name The name of data. E.g. '[0]' or '[12]' * @param value The value to set. * @returns A Promise with the formatted string. undefined if not implemented. */ public async setValue(name: string, value: number): Promise<string> { // Get item const item = this.propMap.get(name)!; // Check if value is not an object itself if (typeof item.itemRef == 'number') return ''; // Variables reference // Otherwise change the value. // Get address const address = item.address; // Note: item.elemSize is <= 2 // Write data const dataWrite = new Uint8Array(item.elemSize); Utility.setUintToMemory(value, dataWrite, 0, item.elemSize, this.littleEndian); await Remote.writeMemoryDump(address, dataWrite); ShallowVar.memoryChanged = true; // Retrieve memory values, to see if they really have been set. const data = await Remote.readMemoryDump(address, item.elemSize); let readValue = Utility.getUintFromMemory(data, 0, item.elemSize, this.littleEndian); // Pass formatted string to vscode const formattedString = Utility.numberFormatted(name, readValue, item.elemSize, this.formatString(item.elemSize), undefined); return formattedString; }; /** * The format to use. */ protected formatString(elemSize: number): string { if (elemSize == 1) return Settings.launch.formatting.watchByte; // byte else return Settings.launch.formatting.watchWord; // word } } /** * The StructVar class is a container class which holds other properties (the elements of the * struct). I.e. SubStructVars. * The StructVar is the parent object which also holds the memory contents. * The SubStructVars refer to it. */ export class StructVar extends SubStructVar { // The memory contents (lazy initialized). protected memory: Uint8Array; // To store the base address. protected baseAddress: number; // The total number of bytes to read. protected countBytes: number; /** * Constructor. * @param addr The address of the memory dump * @param count The count of elements to display. The count of elements in the struct * (each can have a different size). * @param size The size of this object. All elements together. * @param struct 'b'=byte, 'w'=word or 'bw' for byte and word. * @param props An array of names of the direct properties of the struct. * @param parentStruct Not used at this level. * @param list The list of variables. The constructor adds the variables to it. * @param littleEndian If the value should be interpreted as little endian or not. */ public constructor(addr: number, count: number, size: number, struct: string, props: Array<string>, list: RefList<ShallowVar>, littleEndian = true) { super(0, count, size, struct, props, list); this.baseAddress = addr; this.littleEndian = littleEndian; this.createPropArray(0, count, size, struct, props, list, undefined as any); // The amount of bytes to retrieve: this.countBytes = count * size; } /** * Creates the propArray. * On top level this is really an array. * @param relIndex The relative address inside the parent's memory dump. * @param count The count of elements to display. The count of elements in the struct * (each can have a different size). * @param elemSize The size of this object. All elements together. * @param struct 'b'=byte, 'w'=word or 'bw' for byte and word. * @param props An array of names of the direct properties of the struct. * @param list The list of variables. The constructor adds the 2 pseudo variables to it. * @param parentStruct If undefined the method does nothing. Otherwise it is the * reference to a parent struct which retrieves the memory for all sub structs. */ protected createPropArray(relIndex: number, count: number, elemSize: number, struct: string, props: Array<string>, list: RefList<ShallowVar>, parentStruct: StructVar) { // But only if more than 1 element if (count <= 1) { super.createPropArray(relIndex, count, elemSize, struct, props, list, this); } else { // Create a number of nodes let relIndex = 0; for (let i = 0; i < count; i++) { let labelVar; const address = this.getAddress() + i * elemSize; const name = '[' + i + ']'; const item: SubStructItems = { address, elemSize: 0, itemRef: 0, indexedVariables: 0 }; if (props.length) { // Sub structure labelVar = new SubStructVar(relIndex, 1, elemSize, struct, props, list, this); } else { // Simple array labelVar = new MemDumpVar(this.getAddress(), elemSize, 1, this.littleEndian); labelVar.setParent(this, relIndex); item.indexedVariables = elemSize; } item.itemRef = list.addObject(labelVar); this.propMap.set(name, item); // Next relIndex += elemSize; } } } /** * Returns the properties. * Retrieves the memory. * @returns A Promise with the properties. */ public async getContent(start: number, count: number): Promise<Array<DebugProtocol.Variable>> { this.memory = await Remote.readMemoryDump(this.getAddress(), this.countBytes); // Check if properties array exists and create return await super.getContent(start, count); } /** * Returns the cached memory. */ public getMemory() { return this.memory; } /** * Returns the base address. */ public getAddress() { return this.baseAddress; } } /** * The MemDumpByteVar class knows how to retrieve a memory dump from remote. * It allows retrieval of byte and word arrays. */ export class MemDumpVar extends ShallowVar { /// The address of the memory dump. protected addr: number; // The element count. protected totalCount: number; // The element size. byte=1, word=2. protected elemSize: number; // The parent of the sub structure (which holds the memory contents. protected parentStruct: StructVar; // The offset (in bytes) where the displayed memory begins. protected memOffset: number; // If the value should be interpreted as little endian or not. protected littleEndian: boolean; /** * Constructor. * @param addr The address of the memory dump. * @param totalCount The element count. * @param elemSize The element size. byte=1, word=2. * @param littleEndian If the value should be interpreted as little endian or not. */ public constructor(addr: number, totalCount: number, elemSize: number, littleEndian = true) { super(); this.addr = addr; this.totalCount = totalCount; this.elemSize = elemSize; this.memOffset = 0; this.littleEndian = littleEndian; } /** * Set a parent which holds the memory. * @param parentStruct The parent object which holds the memory. * @param memOffset The offset (in bytes) where the displayed memory begins. */ public setParent(parentStruct: StructVar, memOffset: number) { this.parentStruct = parentStruct; this.memOffset = memOffset; } /** * Communicates with the remote to retrieve the memory dump. * @param handler This handler is called when the memory dump is available. * @param start The start index of the array. E.g. only the range [100..199] should be displayed. * @param count The number of bytes to display. * Note: start, count are only used for arrays. */ public async getContent(start: number, count: number): Promise<Array<DebugProtocol.Variable>> { start = start || 0; count = count || (this.totalCount - start); let addr = this.addr + start; const elemSize = this.elemSize; const memArray = new Array<DebugProtocol.Variable>(); const format = this.formatString(); // Check for parent let memory; let offset = this.memOffset; if (this.parentStruct) { // Use memory of parent memory = this.parentStruct.getMemory(); offset += elemSize * start!; } else { // Get memory memory = await Remote.readMemoryDump(addr, count * elemSize); } // Calculate tabsizing array const tabSizes = Utility.calculateTabSizes(format, elemSize); // Format all array elements for (let i = 0; i < count!; i++) { // Get value const value = Utility.getUintFromMemory(memory, offset + i * this.elemSize, this.elemSize, this.littleEndian); // Format const addr_i = addr + offset + i * elemSize; const formatted = Utility.numberFormattedSync(value, elemSize, format, false, undefined, undefined, tabSizes); // Add to array const descr = Utility.getHexString(addr_i, 4) + 'h' memArray.push({ name: "[" + (start + i) + "]", type: descr, value: formatted, variablesReference: 0 }); } // Pass data return memArray; } /** * Sets the value of the variable. * The formatted read data is returned in the Promise. * @param name The name of data. E.g. '[0]' or '[12]' * @param value The value to set. * @returns A Promise with the formatted string. undefined if not implemented. */ public async setValue(name: string, value: number): Promise<string> { // Get index (strip brackets) const indexString = name.substr(1, name.length - 2); const index = parseInt(indexString); // Get address const address = this.addr + this.memOffset + index * this.elemSize; // Write data const dataWrite = new Uint8Array(this.elemSize); Utility.setUintToMemory(value, dataWrite, 0, this.elemSize, this.littleEndian); for (let i = 0; i < this.elemSize; i++) { dataWrite[i] = value & 0xFF; value = value >>> 8; } await Remote.writeMemoryDump(address, dataWrite); ShallowVar.memoryChanged = true; // Retrieve memory values, to see if they really have been set. const data = await Remote.readMemoryDump(address, this.elemSize); // Get value const readValue = Utility.getUintFromMemory(data, 0, this.elemSize, this.littleEndian); // Pass formatted string to vscode const formattedString = Utility.numberFormatted(name, readValue, this.elemSize, this.formatString(), undefined); return formattedString; }; /** * The format to use. */ protected formatString(): string { if (this.elemSize == 1) return Settings.launch.formatting.watchByte; // byte else return Settings.launch.formatting.watchWord; // word } } /** * Represents an immediate value. * This has no reference to a variable but directly checks the memory contents. * It may be included in the returned item from the debug adapter 'evaluateLabelExpression'. * It's been used by the ContainerVar. */ export class ImmediateMemoryValue { // The 64k address. protected address64k: number; // The size of the value, the count of bytes. protected size: number; // If the value should be interpreted as little endian or not. protected littleEndian: boolean; /** * Constructor. * Throws an exception if size is bigger than 6. Otherwise there would be an * inaccuracy. * @param addr64k The 64k address. * @param size The size of the value, the count of bytes. * @param littleEndian If the value should be interpreted as little endian or not. */ constructor(addr64k: number, size: number, littleEndian = true) { if (size > 6) throw Error('The size of an element must be smaller than 7.'); this.address64k = addr64k; this.size = size; this.littleEndian = littleEndian; } /** * Reads the memory and returns the value as a string, * formatted as set in the settings. * @returns The value as a string. */ public async getValue(): Promise<string> { const memory = await Remote.readMemoryDump(this.address64k, this.size); const memVal = Utility.getUintFromMemory(memory, 0, this.size, this.littleEndian); return await Utility.numberFormatted('', memVal, this.size, this.formatString(), undefined); }; /** * Sets the value of the variable. * The formatted read data is returned in the Promise. * @param value The value to set. * @returns A Promise with the formatted string. undefined if not implemented. */ public async setValue(value: number): Promise<string> { // Write data const dataWrite = new Uint8Array(this.size); Utility.setUintToMemory(value, dataWrite, 0, this.size, this.littleEndian); await Remote.writeMemoryDump(this.address64k, dataWrite); ShallowVar.memoryChanged = true; // Retrieve memory values, to see if they really have been set. const data = await Remote.readMemoryDump(this.address64k, this.size); // Convert const readValue = Utility.getUintFromMemory(data, 0, this.size, this.littleEndian); // Pass formatted string to vscode const formattedString = Utility.numberFormatted('', readValue, this.size, this.formatString(), undefined); return formattedString; } /** * The format to use. */ protected formatString(): string { switch (this.size) { case 1: return Settings.launch.formatting.watchByte; // byte case 2: return Settings.launch.formatting.watchWord; // word default: return "${hex}h,\t${unsigned}u,\t${signed}i"; } } }
the_stack
import { AttributeContextParameters, CdmAttribute, CdmAttributeContext, cdmAttributeContextType, CdmCollection, CdmCorpusContext, cdmLogCode, CdmObject, CdmObjectBase, cdmObjectType, CdmOperationBase, cdmOperationType, CdmTraitReferenceBase, Logger, ParameterValueSet, ProjectionAttributeState, ProjectionAttributeStateSet, ProjectionContext, ProjectionResolutionCommonUtil, ResolvedAttribute, ResolvedAttributeSet, ResolvedTraitSet, resolveOptions, VisitCallback } from '../../internal'; /** * Class to handle AlterTraits operations */ export class CdmOperationAlterTraits extends CdmOperationBase { private TAG: string = CdmOperationAlterTraits.name; public traitsToAdd: CdmCollection<CdmTraitReferenceBase>; public traitsToRemove: CdmCollection<CdmTraitReferenceBase>; public argumentsContainWildcards?: boolean; public applyTo: string[]; constructor(ctx: CdmCorpusContext) { super(ctx); this.objectType = cdmObjectType.operationAlterTraitsDef; this.type = cdmOperationType.alterTraits; } /** * @inheritdoc */ public copy(resOpt?: resolveOptions, host?: CdmObject): CdmObject { if (!resOpt) { resOpt = new resolveOptions(this, this.ctx.corpus.defaultResolutionDirectives); } const copy: CdmOperationAlterTraits = !host ? new CdmOperationAlterTraits(this.ctx) : host as CdmOperationAlterTraits; if (this.traitsToAdd && this.traitsToAdd.length > 0) { for (const trait of this.traitsToAdd) { copy.traitsToAdd.push(trait.copy() as CdmTraitReferenceBase); } } if (this.traitsToRemove && this.traitsToRemove.length > 0) { for (const trait of this.traitsToRemove) { copy.traitsToRemove.push(trait.copy() as CdmTraitReferenceBase); } } copy.applyTo = this.applyTo ? this.applyTo.slice() : undefined; copy.argumentsContainWildcards = this.argumentsContainWildcards; this.copyProj(resOpt, copy); return copy; } /** * @inheritdoc */ public getName(): string { return 'operationAlterTraits'; } /** * @inheritdoc */ public getObjectType(): cdmObjectType { return cdmObjectType.operationAlterTraitsDef; } /** * @inheritdoc */ public validate(): boolean { const missingFields: string[] = []; if (!this.traitsToAdd && !this.traitsToRemove) { missingFields.push('traitsToAdd'); missingFields.push('traitsToRemove'); } if (missingFields.length > 0) { Logger.error(this.ctx, this.TAG, this.validate.name, this.atCorpusPath, cdmLogCode.ErrValdnIntegrityCheckFailure, this.atCorpusPath, missingFields.map((s: string) => `'${s}'`).join(', ')); return false; } return true; } /** * @inheritdoc */ public visit(pathFrom: string, preChildren: VisitCallback, postChildren: VisitCallback): boolean { const path = this.fetchDeclaredPath(pathFrom); if (preChildren && preChildren(this, path)) { return false; } if (this.traitsToAdd !== undefined && CdmObjectBase.visitArray(this.traitsToAdd, `${path}/traitsToAdd/`, preChildren, postChildren)) { return true; } if (this.traitsToRemove !== undefined && CdmObjectBase.visitArray(this.traitsToRemove, `${path}/traitsToRemove/`, preChildren, postChildren)) { return true; } if (postChildren && postChildren(this, path)) { return true; } return false; } /** * @inheritdoc * @internal */ public appendProjectionAttributeState(projCtx: ProjectionContext, projOutputSet: ProjectionAttributeStateSet, attrCtx: CdmAttributeContext): ProjectionAttributeStateSet { // Create a new attribute context for the operation const attrCtxOpAlterTraitsParam: AttributeContextParameters = { under: attrCtx, type: cdmAttributeContextType.operationAlterTraits, name: `operation/index${this.index}/${this.getName()}` }; const attrCtxOpAlterTraits: CdmAttributeContext = CdmAttributeContext.createChildUnder(projCtx.projectionDirective.resOpt, attrCtxOpAlterTraitsParam); // Get the top-level attribute names of the selected attributes to apply // We use the top-level names because the applyTo list may contain a previous name our current resolved attributes had const topLevelSelectedAttributeNames: Map<string, string> = this.applyTo !== undefined ? ProjectionResolutionCommonUtil.getTopList(projCtx, this.applyTo) : undefined; // Iterate through all the projection attribute states generated from the source's resolved attributes // Each projection attribute state contains a resolved attribute that it is corresponding to for (const currentPAS of projCtx.currentAttributeStateSet.states) { // Check if the current projection attribute state's resolved attribute is in the list of selected attributes // If this attribute is not in the list, then we are including it in the output without changes if (topLevelSelectedAttributeNames === undefined || topLevelSelectedAttributeNames.has(currentPAS.currentResolvedAttribute.resolvedName)) { // Create a new attribute context for the new artifact attribute we will create const attrCtxNewAttrParam: AttributeContextParameters = { under: attrCtxOpAlterTraits, type: cdmAttributeContextType.attributeDefinition, name: currentPAS.currentResolvedAttribute.resolvedName }; const attrCtxNewAttr: CdmAttributeContext = CdmAttributeContext.createChildUnder(projCtx.projectionDirective.resOpt, attrCtxNewAttrParam); let newResAttr: ResolvedAttribute = null; if (currentPAS.currentResolvedAttribute.target instanceof ResolvedAttributeSet) { // Attribute group // Create a copy of resolved attribute set const resAttrNewCopy: ResolvedAttributeSet = currentPAS.currentResolvedAttribute.target.copy(); newResAttr = new ResolvedAttribute(projCtx.projectionDirective.resOpt, resAttrNewCopy, currentPAS.currentResolvedAttribute.resolvedName, attrCtxNewAttr); // the resolved attribute group obtained from previous projection operation may have a different set of traits comparing to the resolved attribute target. // We would want to take the set of traits from the resolved attribute. newResAttr.resolvedTraits = currentPAS.currentResolvedAttribute.resolvedTraits.deepCopy(); } else if (currentPAS.currentResolvedAttribute.target instanceof CdmAttribute) { // Entity Attribute or Type Attribute newResAttr = CdmOperationBase.createNewResolvedAttribute(projCtx, attrCtxNewAttr, currentPAS.currentResolvedAttribute, currentPAS.currentResolvedAttribute.resolvedName); } else { Logger.warning(this.ctx, this.TAG, this.appendProjectionAttributeState.name, this.atCorpusPath, cdmLogCode.ErrProjUnsupportedSource, typeof currentPAS.currentResolvedAttribute.target, this.getName()); projOutputSet.add(currentPAS) break; } newResAttr.resolvedTraits = newResAttr.resolvedTraits.mergeSet(this.resolvedNewTraits(projCtx, currentPAS)); this.removeTraitsInNewAttribute(projCtx.projectionDirective.resOpt, newResAttr); // Create a projection attribute state for the new attribute with new applied traits by creating a copy of the current state // Copy() sets the current state as the previous state for the new one const newPAS: ProjectionAttributeState = currentPAS.copy(); // Update the resolved attribute to be the new attribute we created newPAS.currentResolvedAttribute = newResAttr; projOutputSet.add(newPAS); } else { // Pass through projOutputSet.add(currentPAS); } } return projOutputSet; } private resolvedNewTraits(projCtx: ProjectionContext, currentPAS: ProjectionAttributeState) { let resolvedTraitSet: ResolvedTraitSet = new ResolvedTraitSet(projCtx.projectionDirective.resOpt); const projectionOwnerName: string = projCtx.projectionDirective.originalSourceAttributeName ?? ""; for (const traitRef of this.traitsToAdd) { const traitRefCopy: ResolvedTraitSet = traitRef.fetchResolvedTraits(projCtx.projectionDirective.resOpt).deepCopy(); this.replaceWildcardCharacters(projCtx.projectionDirective.resOpt, traitRefCopy, projectionOwnerName, currentPAS); resolvedTraitSet = resolvedTraitSet.mergeSet(traitRefCopy); } return resolvedTraitSet; } /** * Replace wild characters in the arguments if argumentsContainWildcards is true. */ private replaceWildcardCharacters(resOpt: resolveOptions, resolvedTraitSet: ResolvedTraitSet, projectionOwnerName: string, currentPAS: ProjectionAttributeState): void { if (this.argumentsContainWildcards !== undefined && this.argumentsContainWildcards == true) { resolvedTraitSet.set.forEach(resolvedTrait => { const parameterValueSet: ParameterValueSet = resolvedTrait.parameterValues; for (let i: number = 0; i < parameterValueSet.length; ++i) { var value = parameterValueSet.fetchValue(i); if (typeof value === 'string'){ var newVal = CdmOperationBase.replaceWildcardCharacters(value, projectionOwnerName, currentPAS); if (newVal != value) { parameterValueSet.setParameterValue(resOpt, parameterValueSet.fetchParameterAtIndex(i).getName(), newVal); } } } }); } } /** * Remove traits from the new resolved attribute. */ private removeTraitsInNewAttribute(resOpt: resolveOptions, newResAttr: ResolvedAttribute): void { const traitNamesToRemove:Set<string> = new Set() if (this.traitsToRemove !== undefined) { for (const traitRef of this.traitsToRemove) { const resolvedTraitSet = traitRef.fetchResolvedTraits(resOpt).deepCopy(); resolvedTraitSet.set.forEach(rt => traitNamesToRemove.add(rt.traitName)); } traitNamesToRemove.forEach(traitName => newResAttr.resolvedTraits.remove(resOpt, traitName)); } } }
the_stack
import UPlot, {Options, Series} from 'uplot'; import Yagr from '../../index'; import {DEFAULT_X_SERIE_NAME} from '../../defaults'; export type LegendPosition = 'top' | 'bottom'; export interface LegendOptions { /** Show legend (default: false) */ show?: boolean; /** Root classname */ className?: string; /** Legend placement position */ position?: LegendPosition; /** Maximal space fro legend as a fraction of chart height (default: 0.3) */ maxLegendSpace?: number; /** @TODO Maybe bugs here */ fontSize?: number; } interface LegendState { page: number; pages: number; paginated: boolean; rowsPerPage: number; pageSize: number; } const ALL_SERIES_IDX = 'null'; const TOTAL_LEGEND_VERTICAL_PADDING = 20; const DEFAULT_FONT_SIZE = 12; const DEFAULT_LEGEND_PLACE_RATIO = 0.3; const hasOneVisibleLine = (series: Series[]) => { return series.some(({show, id}) => id !== DEFAULT_X_SERIE_NAME && show); }; const getPrependingTitle = (i18n: Yagr['utils']['i18n'], series: Series[]) => { return series.length > 3 && i18n(hasOneVisibleLine(series) ? 'hide-all' : 'show-all'); }; export default class Legend { yagr: Yagr; uplot?: UPlot; options: LegendOptions; pagesCount: number; state: LegendState; itemsHtml = ''; legendEl?: HTMLElement; items?: HTMLElement; container?: HTMLElement; _onDestroy?: () => void; constructor(yagr: Yagr, options?: LegendOptions) { this.yagr = yagr; this.pagesCount = 0; this.state = { page: 0, pages: 1, pageSize: 0, rowsPerPage: 1, paginated: false, }; this.options = Object.assign( { show: false, position: 'bottom', fontSize: DEFAULT_FONT_SIZE, maxLegendSpace: DEFAULT_LEGEND_PLACE_RATIO, className: undefined, }, options || {}, ); if (this.options.show) { this.calc(); } } redraw() { if (!this.options.show) { return; } this.destroy(); this.calc(); this.prepareLegend(); } destroy() { if (this._onDestroy) { this._onDestroy(); } this.legendEl?.remove(); } init = (u: UPlot) => { this.uplot = u; /** Removing native uPlot legend */ u.root.querySelector('.u-legend')?.remove(); /** Reimplementing appedning u.root to root */ this.yagr.root.appendChild(u.root); if (this.options.show) { this.prepareLegend(); } }; private applyHandlers() { const {yagr, uplot: u} = this; if (!u) { return () => {}; } const series: NodeListOf<HTMLDivElement> = u.root.querySelectorAll('[data-serie-id]'); const unsubsribe: (() => void)[] = []; const onSerieClick = (serieNode: HTMLElement) => () => { const serieId = serieNode.getAttribute('data-serie-id'); const seriesToToggle: [Series, boolean][] = []; if (serieId === ALL_SERIES_IDX) { const nextToggleState = !hasOneVisibleLine(u.series); for (let idx = 1; idx < u.series.length; idx++) { seriesToToggle.push([u.series[idx], nextToggleState]); } } else { const serie = u.series.find(({id}) => id === serieId); if (!serie) { return; } seriesToToggle.push([serie, !serie.show]); } seriesToToggle.forEach(([serie, nextState]) => { const node = u.root.querySelector(`[data-serie-id="${serie.id}"]`); yagr.setVisible(serie.id, nextState); node?.classList[serie.show ? 'remove' : 'add']('yagr-legend__item_hidden'); }); const allSeriesItem = u.root.querySelector(`[data-serie-id="${ALL_SERIES_IDX}"]`); if (allSeriesItem) { const title = getPrependingTitle(this.yagr.utils.i18n, u.series); allSeriesItem.innerHTML = title || ''; } }; const onSerieMouseEnter = (serieNode: HTMLElement) => () => { const serieId = serieNode.getAttribute('data-serie-id'); const targetSerie = this.yagr.uplot.series.find(({id}) => id === serieId); if (serieId === ALL_SERIES_IDX) { return; } if (targetSerie) { yagr.setFocus(targetSerie.id, true); } }; const onSerieMouseLeave = () => { yagr.setFocus(null, true); }; series.forEach((serieNode) => { const onClick = onSerieClick(serieNode); const onFocus = onSerieMouseEnter(serieNode); serieNode.addEventListener('click', onClick); serieNode.addEventListener('mouseenter', onFocus); serieNode.addEventListener('mouseleave', onSerieMouseLeave); unsubsribe.push(() => { serieNode.removeEventListener('click', onClick); serieNode.removeEventListener('mouseenter', onFocus); serieNode.removeEventListener('mouseleave', onSerieMouseLeave); }); }); const destroy = () => unsubsribe.forEach((fn) => fn()); this._onDestroy = destroy; return destroy; } private prepareLegend() { const {uplot: u, options} = this; if (!u) { return; } const wrapEl = u.root.querySelector('.u-wrap') as HTMLElement; const legendEl = document.createElement('div'); legendEl.classList.add('yagr-legend'); if (options?.className) { legendEl.classList.add(options?.className); } if (options?.position) { u.root.classList.add('yagr-legend_' + options?.position); } if (options.position === 'top') { const titleEl = u.root.querySelector('.u-title'); const firstEl = titleEl || wrapEl; firstEl.before(legendEl); } else { wrapEl?.after(legendEl); } this.legendEl = legendEl; if (!this.itemsHtml) { this.calc(); } legendEl.innerHTML = `<div class="yagr-legend__container" style="height: ${this.state.pageSize}px">${this.itemsHtml}</div>`; this.items = legendEl.querySelector('.yagr-legend__items') as HTMLElement; this.container = legendEl.querySelector('.yagr-legend__container') as HTMLElement; if (this.state.paginated) { const pagination = this.renderPagination(); this.container?.after(pagination); } else { this.items.style.justifyContent = 'center'; } const destroy = this.applyHandlers(); this.uplot?.hooks.destroy?.push(() => { destroy(); this.destroy(); }); } private measureLegend = (html: string) => { const rootEl = this.yagr.root; const pseudo = document.createElement('div'); pseudo.classList.add('yagr-legend'); pseudo.innerHTML = html; pseudo.style.visibility = 'hidden'; rootEl.appendChild(pseudo); const items = pseudo.childNodes[0] as HTMLElement; const result = items.getBoundingClientRect(); pseudo.remove(); return result; }; private nextPage = () => { const {state} = this; this.state.page += 1; if (this.items) { this.items.style.transform = `translate(0, ${-1 * state.page * state.pageSize}px)`; this.renderPagination(); } }; private prevPage = () => { const {state} = this; this.state.page -= 1; if (this.items) { this.items.style.transform = `translate(0, ${-1 * state.page * state.pageSize}px)`; this.renderPagination(); } }; private renderPagination() { const {state} = this; let pagination = this.yagr.root.querySelector('.yagr-legend__pagination'); if (pagination) { const nextPage = pagination.querySelector('.yagr-legend__icon-down') as HTMLElement; const prevPage = pagination.querySelector('.yagr-legend__icon-up') as HTMLElement; nextPage.removeEventListener('click', this.nextPage); prevPage.removeEventListener('click', this.prevPage); } else { pagination = document.createElement('div'); pagination.classList.add('yagr-legend__pagination'); } const upClassName = state.page === 0 ? 'yagr-legend__icon-up_disabled' : ''; const downClassName = state.page === state.pages - 1 ? 'yagr-legend__icon-down_disabled' : ''; pagination.innerHTML = `<span class="yagr-legend__icon-up ${upClassName}"></span> <span class="yagr-legend__pagination-text">${state.page + 1}/${state.pages}</span> <span class="yagr-legend__icon-down ${downClassName}"></span>`; const nextPage = pagination.querySelector('.yagr-legend__icon-down') as HTMLElement; const prevPage = pagination.querySelector('.yagr-legend__icon-up') as HTMLElement; if (!downClassName) { nextPage.addEventListener('click', this.nextPage); } if (!upClassName) { prevPage.addEventListener('click', this.prevPage); } return pagination; } private createIconLineElement(serie: Series) { const iconLineElement = document.createElement('span'); iconLineElement.classList.add('yagr-legend__icon', `yagr-legend__icon_${serie.type}`); iconLineElement.style.backgroundColor = serie.color; return iconLineElement; } private createSerieNameElement(serie: Series) { const serieNameElement = document.createElement('span'); serieNameElement.innerText = serie.name || 'unnamed'; return serieNameElement; } private renderItems(uplotOptions: Options) { const title = getPrependingTitle(this.yagr.utils.i18n, uplotOptions.series); const series: (Series | string)[] = title ? [title] : []; for (let i = 1; i < uplotOptions.series.length; i++) { series.push(uplotOptions.series[i]); } const content = series .map((serie) => { let content; let sId; if (typeof serie === 'string') { content = serie; sId = serie; } else { sId = serie.id; const icon = this.createIconLineElement(serie); const name = this.createSerieNameElement(serie); content = `${icon.outerHTML}${name.outerHTML}`; } const visible = typeof serie === 'string' ? true : serie.show !== false; return `<div class="yagr-legend__item ${ visible ? '' : 'yagr-legend__item_hidden' }" data-serie-id="${sId}">${content}</div>`; }) .join(''); return `<div class="yagr-legend__items">${content}</div>`; } private calc() { if (!this.options.show) { return; } const uplotOptions = this.yagr.options; const chartHeight = uplotOptions.height - TOTAL_LEGEND_VERTICAL_PADDING; const html = this.renderItems(uplotOptions); const {height: requiredHeight} = this.measureLegend(html); const rowHeight = (this.options.fontSize as number) + 2; const maxPossiblePlace = chartHeight * (this.options.maxLegendSpace as number); const rowsPerPage = Math.floor(maxPossiblePlace / rowHeight); const itemsRowsPerPage = rowsPerPage - 1; const itemsPageSize = Math.min(itemsRowsPerPage * rowHeight, maxPossiblePlace); const paginatedPageSize = Math.min(rowsPerPage * rowHeight, maxPossiblePlace); const paginated = requiredHeight > itemsPageSize; const requiredSpace = Math.min(paginated ? paginatedPageSize : itemsPageSize, requiredHeight); const pages = Math.ceil(requiredHeight / itemsPageSize); uplotOptions.height = chartHeight - requiredSpace; this.state.paginated = paginated; this.state.page = this.state.page || 0; this.state.pages = pages; this.state.pageSize = itemsPageSize; this.state.rowsPerPage = rowsPerPage; this.itemsHtml = html; } }
the_stack
import { BaseResource, CloudError, AzureServiceClientOptions } from "@azure/ms-rest-azure-js"; import * as msRest from "@azure/ms-rest-js"; export { BaseResource, CloudError }; /** * Identity for the resource. */ export interface Identity { /** * The identity type. */ type: string; /** * The list of identities. */ identityIds: string[]; } /** * The properties that define a step. */ export interface PrePostStep { /** * The resource Id of the step to be run. */ stepId: string; } /** * The properties that define a Step group in a rollout. */ export interface StepGroup { /** * The name of the step group. */ name: string; /** * The list of step group names on which this step group depends on. */ dependsOnStepGroups?: string[]; /** * The list of steps to be run before deploying the target. */ preDeploymentSteps?: PrePostStep[]; /** * The resource Id of service unit to be deployed. The service unit should be from the service * topology referenced in targetServiceTopologyId */ deploymentTargetId: string; /** * The list of steps to be run after deploying the target. */ postDeploymentSteps?: PrePostStep[]; } /** * An interface representing Resource. */ export interface Resource extends BaseResource { /** * Fully qualified resource Id for the resource. Ex - * /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly id?: string; /** * The name of the resource * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly name?: string; /** * The type of the resource. Ex- Microsoft.Compute/virtualMachines or * Microsoft.Storage/storageAccounts. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly type?: string; } /** * The resource model definition for a ARM tracked top level resource */ export interface TrackedResource extends Resource { /** * Resource tags. */ tags?: { [propertyName: string]: string }; /** * The geo-location where the resource lives */ location: string; } /** * Defines the PUT rollout request body. */ export interface RolloutRequest extends TrackedResource { /** * Identity for the resource. */ identity: Identity; /** * The version of the build being deployed. */ buildVersion: string; /** * The reference to the artifact source resource Id where the payload is located. */ artifactSourceId?: string; /** * The resource Id of the service topology from which service units are being referenced in step * groups to be deployed. */ targetServiceTopologyId: string; /** * The list of step groups that define the orchestration. */ stepGroups: StepGroup[]; } /** * The resource that defines the source location where the artifacts are located. */ export interface ArtifactSource extends TrackedResource { /** * The type of artifact source used. */ sourceType: string; /** * The path from the location that the 'authentication' property [say, a SAS URI to the blob * container] refers to, to the location of the artifacts. This can be used to differentiate * different versions of the artifacts. Or, different types of artifacts like binaries or * templates. The location referenced by the authentication property concatenated with this * optional artifactRoot path forms the artifact source location where the artifacts are expected * to be found. */ artifactRoot?: string; /** * The authentication method to use to access the artifact source. */ authentication: AuthenticationUnion; } /** * Contains the possible cases for Authentication. */ export type AuthenticationUnion = Authentication | SasAuthentication; /** * Defines the authentication method and properties to access the artifacts. */ export interface Authentication { /** * Polymorphic Discriminator */ type: "Authentication"; } /** * The properties that define the source location where the artifacts are located. */ export interface ArtifactSourcePropertiesModel { /** * The type of artifact source used. */ sourceType: string; /** * The path from the location that the 'authentication' property [say, a SAS URI to the blob * container] refers to, to the location of the artifacts. This can be used to differentiate * different versions of the artifacts. Or, different types of artifacts like binaries or * templates. The location referenced by the authentication property concatenated with this * optional artifactRoot path forms the artifact source location where the artifacts are expected * to be found. */ artifactRoot?: string; /** * The authentication method to use to access the artifact source. */ authentication: AuthenticationUnion; } /** * Defines the properties to access the artifacts using an Azure Storage SAS URI. */ export interface SasAuthentication { /** * Polymorphic Discriminator */ type: "Sas"; /** * The SAS URI to the Azure Storage blob container. Any offset from the root of the container to * where the artifacts are located can be defined in the artifactRoot. */ sasUri: string; } /** * Detailed error information of any failure. */ export interface CloudErrorBody { /** * Error code string. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly code?: string; /** * Descriptive error information. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly message?: string; /** * Error target */ target?: string; /** * More detailed error information. */ details?: CloudErrorBody[]; } /** * Detailed runtime information of the rollout. */ export interface RolloutOperationInfo { /** * The ordinal count of the number of retry attempts on a rollout. 0 if no retries of the rollout * have been performed. If the rollout is updated with a PUT, this count is reset to 0. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly retryAttempt?: number; /** * True, if all steps that succeeded on the previous run/attempt were chosen to be skipped in * this retry attempt. False, otherwise. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly skipSucceededOnRetry?: boolean; /** * The start time of the rollout in UTC. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly startTime?: Date; /** * The start time of the rollout in UTC. This property will not be set if the rollout has not * completed yet. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly endTime?: Date; /** * The detailed error information for any failure. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly error?: CloudErrorBody; } /** * Detailed information of a specific step run. */ export interface StepOperationInfo { /** * The name of the ARM deployment initiated as part of the step. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly deploymentName?: string; /** * Unique identifier to track the request for ARM-based resources. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly correlationId?: string; /** * Start time of the action in UTC. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly startTime?: Date; /** * End time of the action in UTC. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly endTime?: Date; /** * Last time in UTC this operation was updated. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly lastUpdatedTime?: Date; /** * The errors, if any, for the action. */ error?: CloudErrorBody; } /** * Individual resource operation information. */ export interface ResourceOperation { /** * Name of the resource as specified in the artifacts. For ARM resources, this is the name of the * resource specified in the template. */ resourceName?: string; /** * Unique identifier of the operation. For ARM resources, this is the operationId obtained from * ARM service. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly operationId?: string; /** * Type of the resource as specified in the artifacts. For ARM resources, this is the type of the * resource specified in the template. */ resourceType?: string; /** * State of the resource deployment. For ARM resources, this is the current provisioning state of * the resource. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly provisioningState?: string; /** * Descriptive information of the resource operation. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly statusMessage?: string; /** * Http status code of the operation. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly statusCode?: string; } /** * Supplementary contextual messages during a rollout. */ export interface Message { /** * Time in UTC this message was provided. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly timeStamp?: Date; /** * The actual message text. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly message?: string; } /** * Defines a specific step on a target service unit. */ export interface RolloutStep { /** * Name of the step. */ name: string; /** * Current state of the step. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly status?: string; /** * The step group the current step is part of. */ stepGroup?: string; /** * Detailed information of specific action execution. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly operationInfo?: StepOperationInfo; /** * Set of resource operations that were performed, if any, on an Azure resource. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly resourceOperations?: ResourceOperation[]; /** * Supplementary informative messages during rollout. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly messages?: Message[]; } /** * Defines the properties of a service unit. */ export interface ServiceUnitProperties { /** * The Azure Resource Group to which the resources in the service unit belong to or should be * deployed to. */ targetResourceGroup: string; /** * Describes the type of ARM deployment to be performed on the resource. Possible values include: * 'Incremental', 'Complete' */ deploymentMode: DeploymentMode; /** * The artifacts for the service unit. */ artifacts?: ServiceUnitArtifacts; } /** * Defines a service unit. */ export interface ServiceUnit extends ServiceUnitProperties { /** * Name of the service unit. */ name?: string; /** * Detailed step information, if present. */ steps?: RolloutStep[]; } /** * The properties of a service. */ export interface ServiceProperties { /** * The Azure location to which the resources in the service belong to or should be deployed to. */ targetLocation: string; /** * The subscription to which the resources in the service belong to or should be deployed to. */ targetSubscriptionId: string; } /** * Defines a service. */ export interface Service extends ServiceProperties { /** * Name of the service. */ name?: string; /** * The detailed information about the units that make up the service. */ serviceUnits?: ServiceUnit[]; } /** * Defines the rollout. */ export interface Rollout extends TrackedResource { /** * Identity for the resource. */ identity?: Identity; /** * The version of the build being deployed. */ buildVersion: string; /** * The reference to the artifact source resource Id where the payload is located. */ artifactSourceId?: string; /** * The resource Id of the service topology from which service units are being referenced in step * groups to be deployed. */ targetServiceTopologyId: string; /** * The list of step groups that define the orchestration. */ stepGroups: StepGroup[]; /** * The current status of the rollout. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly status?: string; /** * The cardinal count of total number of retries performed on the rollout at a given time. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly totalRetryAttempts?: number; /** * Operational information of the rollout. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly operationInfo?: RolloutOperationInfo; /** * The detailed information on the services being deployed. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly services?: Service[]; } /** * Defines the properties of a rollout. */ export interface RolloutPropertiesModel { /** * The current status of the rollout. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly status?: string; /** * The cardinal count of total number of retries performed on the rollout at a given time. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly totalRetryAttempts?: number; /** * Operational information of the rollout. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly operationInfo?: RolloutOperationInfo; /** * The detailed information on the services being deployed. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly services?: Service[]; } /** * The resource representation of a service topology. */ export interface ServiceTopologyResource extends TrackedResource { /** * The resource Id of the artifact source that contains the artifacts that can be referenced in * the service units. */ artifactSourceId?: string; } /** * The properties of a service topology. */ export interface ServiceTopologyProperties { /** * The resource Id of the artifact source that contains the artifacts that can be referenced in * the service units. */ artifactSourceId?: string; } /** * The resource representation of a service in a service topology. */ export interface ServiceResource extends TrackedResource { /** * The Azure location to which the resources in the service belong to or should be deployed to. */ targetLocation: string; /** * The subscription to which the resources in the service belong to or should be deployed to. */ targetSubscriptionId: string; } /** * Represents the response of a service unit resource. */ export interface ServiceUnitResource extends TrackedResource { /** * The Azure Resource Group to which the resources in the service unit belong to or should be * deployed to. */ targetResourceGroup: string; /** * Describes the type of ARM deployment to be performed on the resource. Possible values include: * 'Incremental', 'Complete' */ deploymentMode: DeploymentMode; /** * The artifacts for the service unit. */ artifacts?: ServiceUnitArtifacts; } /** * Defines the artifacts of a service unit. */ export interface ServiceUnitArtifacts { /** * The full URI of the ARM template file with the SAS token. */ templateUri?: string; /** * The full URI of the ARM parameters file with the SAS token. */ parametersUri?: string; /** * The path to the ARM template file relative to the artifact source. */ templateArtifactSourceRelativePath?: string; /** * The path to the ARM parameters file relative to the artifact source. */ parametersArtifactSourceRelativePath?: string; } /** * The detail about an operation. */ export interface OperationDetail { /** * The name of the provider that supports the operation. */ provider?: string; /** * The resource type on which this operation can be performed. */ resource?: string; /** * The name of the operation. */ operation?: string; /** * The description of the operation. */ description?: string; } /** * Represents an operation that can be performed on the service. */ export interface Operation { /** * The name of the operation. */ name?: string; /** * The display name of the operation. */ display?: OperationDetail; /** * The origin of the operation. */ origin?: string; /** * The properties of the operation. */ properties?: any; } /** * The operations response. */ export interface OperationsList { /** * The list of supported operations */ value?: Operation; } /** * Contains the possible cases for StepProperties. */ export type StepPropertiesUnion = StepProperties | HealthCheckStepProperties | WaitStepProperties; /** * The properties of a step resource. */ export interface StepProperties { /** * Polymorphic Discriminator */ stepType: "StepProperties"; } /** * The resource representation of a rollout step. */ export interface StepResource extends TrackedResource { /** * The properties that define the step. */ properties: StepPropertiesUnion; } /** * Contains the possible cases for HealthCheckStepAttributes. */ export type HealthCheckStepAttributesUnion = HealthCheckStepAttributes | RestHealthCheckStepAttributes; /** * The attributes for the health check step. */ export interface HealthCheckStepAttributes { /** * Polymorphic Discriminator */ type: "HealthCheckStepAttributes"; /** * The duration in ISO 8601 format for which health check waits idly without any checks. */ waitDuration?: string; /** * The duration in ISO 8601 format for which the health check waits for the resource to become * healthy. Health check fails if it doesn't. Health check starts to enforce healthyStateDuration * once resource becomes healthy. */ maxElasticDuration?: string; /** * The duration in ISO 8601 format for which the resource is expected to be continuously healthy. * If maxElasticDuration is specified, healthy state duration is enforced after the detection of * first healthy signal. */ healthyStateDuration: string; } /** * Defines the properties of a health check step. */ export interface HealthCheckStepProperties { /** * Polymorphic Discriminator */ stepType: "HealthCheck"; /** * The health check step attributes */ attributes: HealthCheckStepAttributesUnion; } /** * Contains the possible cases for RestRequestAuthentication. */ export type RestRequestAuthenticationUnion = RestRequestAuthentication | RolloutIdentityAuthentication | ApiKeyAuthentication; /** * The authentication information required in the REST health check request to the health provider. */ export interface RestRequestAuthentication { /** * Polymorphic Discriminator */ type: "RestRequestAuthentication"; } /** * The properties that make up a REST request */ export interface RestRequest { /** * The HTTP method to use for the request. Possible values include: 'GET', 'POST' */ method: RestRequestMethod; /** * The HTTP URI to use for the request. */ uri: string; /** * The authentication information required in the request to the health provider. */ authentication: RestRequestAuthenticationUnion; } /** * The regular expressions to match the response content with. */ export interface RestResponseRegex { /** * The list of regular expressions. */ matches?: string[]; /** * Indicates whether any or all of the expressions should match with the response content. * Possible values include: 'All', 'Any' */ matchQuantifier?: RestMatchQuantifier; } /** * The properties that make up the expected REST response */ export interface RestResponse { /** * The HTTP status codes expected in a successful health check response. The response is expected * to match one of the given status codes. If no expected status codes are provided, default * expected status code is 200 OK. */ successStatusCodes?: string[]; /** * The regular expressions to match the response content with. */ regex?: RestResponseRegex; } /** * A REST based health check */ export interface RestHealthCheck { /** * A unique name for this check. */ name: string; /** * The request to the health provider. */ request: RestRequest; /** * The expected response from the health provider. If no expected response is provided, the * default is to expect the received response to have an HTTP status code of 200 OK. */ response?: RestResponse; } /** * Defines the REST health check step properties. */ export interface RestHealthCheckStepAttributes { /** * Polymorphic Discriminator */ type: "REST"; /** * The duration in ISO 8601 format for which health check waits idly without any checks. */ waitDuration?: string; /** * The duration in ISO 8601 format for which the health check waits for the resource to become * healthy. Health check fails if it doesn't. Health check starts to enforce healthyStateDuration * once resource becomes healthy. */ maxElasticDuration?: string; /** * The duration in ISO 8601 format for which the resource is expected to be continuously healthy. * If maxElasticDuration is specified, healthy state duration is enforced after the detection of * first healthy signal. */ healthyStateDuration: string; /** * The list of checks that form the health check step. */ healthChecks: RestHealthCheck[]; } /** * RolloutIdentity uses the user-assigned managed identity authentication context specified in the * Identity property during rollout creation. */ export interface RolloutIdentityAuthentication { /** * Polymorphic Discriminator */ type: "RolloutIdentity"; } /** * ApiKey authentication gives a name and a value that can be included in either the request header * or query parameters. */ export interface ApiKeyAuthentication { /** * Polymorphic Discriminator */ type: "ApiKey"; /** * The key name of the authentication key/value pair. */ name: string; /** * The location of the authentication key/value pair in the request. Possible values include: * 'Query', 'Header' */ inProperty: RestAuthLocation; /** * The value of the authentication key/value pair. */ value: string; } /** * The parameters for the wait step. */ export interface WaitStepAttributes { /** * The duration in ISO 8601 format of how long the wait should be. */ duration: string; } /** * Defines the properties of a Wait step. */ export interface WaitStepProperties { /** * Polymorphic Discriminator */ stepType: "Wait"; /** * The Wait attributes */ attributes: WaitStepAttributes; } /** * The resource model definition for a ARM proxy resource. It will have everything other than * required location and tags */ export interface ProxyResource extends Resource { } /** * The resource model definition for a Azure Resource Manager resource with an etag. */ export interface AzureEntityResource extends Resource { /** * Resource Etag. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly etag?: string; } /** * Optional Parameters. */ export interface StepsCreateOrUpdateOptionalParams extends msRest.RequestOptionsBase { /** * The step object. */ stepInfo?: StepResource; } /** * Optional Parameters. */ export interface RolloutsCreateOrUpdateOptionalParams extends msRest.RequestOptionsBase { /** * Source rollout request object that defines the rollout. */ rolloutRequest?: RolloutRequest; } /** * Optional Parameters. */ export interface RolloutsGetOptionalParams extends msRest.RequestOptionsBase { /** * Rollout retry attempt ordinal to get the result of. If not specified, result of the latest * attempt will be returned. */ retryAttempt?: number; } /** * Optional Parameters. */ export interface RolloutsRestartOptionalParams extends msRest.RequestOptionsBase { /** * If true, will skip all succeeded steps so far in the rollout. If false, will execute the * entire rollout again regardless of the current state of individual resources. Defaults to * false if not specified. */ skipSucceeded?: boolean; } /** * Optional Parameters. */ export interface RolloutsBeginCreateOrUpdateOptionalParams extends msRest.RequestOptionsBase { /** * Source rollout request object that defines the rollout. */ rolloutRequest?: RolloutRequest; } /** * Optional Parameters. */ export interface ArtifactSourcesCreateOrUpdateOptionalParams extends msRest.RequestOptionsBase { /** * Source object that defines the resource. */ artifactSourceInfo?: ArtifactSource; } /** * An interface representing AzureDeploymentManagerOptions. */ export interface AzureDeploymentManagerOptions extends AzureServiceClientOptions { baseUri?: string; } /** * Defines headers for CreateOrUpdate operation. */ export interface ServiceUnitsCreateOrUpdateHeaders { /** * Contains the status URL on which clients are expected to poll the status of the operation. */ azureAsyncOperation: string; } /** * Defines headers for CreateOrUpdate operation. */ export interface RolloutsCreateOrUpdateHeaders { /** * Contains the status URL on which clients are expected to poll the status of the operation. */ azureAsyncOperation: string; } /** * Defines values for DeploymentMode. * Possible values include: 'Incremental', 'Complete' * @readonly * @enum {string} */ export type DeploymentMode = 'Incremental' | 'Complete'; /** * Defines values for RestRequestMethod. * Possible values include: 'GET', 'POST' * @readonly * @enum {string} */ export type RestRequestMethod = 'GET' | 'POST'; /** * Defines values for RestMatchQuantifier. * Possible values include: 'All', 'Any' * @readonly * @enum {string} */ export type RestMatchQuantifier = 'All' | 'Any'; /** * Defines values for RestAuthLocation. * Possible values include: 'Query', 'Header' * @readonly * @enum {string} */ export type RestAuthLocation = 'Query' | 'Header'; /** * Contains response data for the createOrUpdate operation. */ export type ServiceTopologiesCreateOrUpdateResponse = ServiceTopologyResource & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: ServiceTopologyResource; }; }; /** * Contains response data for the get operation. */ export type ServiceTopologiesGetResponse = ServiceTopologyResource & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: ServiceTopologyResource; }; }; /** * Contains response data for the list operation. */ export type ServiceTopologiesListResponse = Array<ServiceTopologyResource> & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: ServiceTopologyResource[]; }; }; /** * Contains response data for the createOrUpdate operation. */ export type ServicesCreateOrUpdateResponse = ServiceResource & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: ServiceResource; }; }; /** * Contains response data for the get operation. */ export type ServicesGetResponse = ServiceResource & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: ServiceResource; }; }; /** * Contains response data for the list operation. */ export type ServicesListResponse = Array<ServiceResource> & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: ServiceResource[]; }; }; /** * Contains response data for the createOrUpdate operation. */ export type ServiceUnitsCreateOrUpdateResponse = ServiceUnitResource & ServiceUnitsCreateOrUpdateHeaders & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The parsed HTTP response headers. */ parsedHeaders: ServiceUnitsCreateOrUpdateHeaders; /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: ServiceUnitResource; }; }; /** * Contains response data for the get operation. */ export type ServiceUnitsGetResponse = ServiceUnitResource & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: ServiceUnitResource; }; }; /** * Contains response data for the list operation. */ export type ServiceUnitsListResponse = Array<ServiceUnitResource> & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: ServiceUnitResource[]; }; }; /** * Contains response data for the createOrUpdate operation. */ export type StepsCreateOrUpdateResponse = StepResource & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: StepResource; }; }; /** * Contains response data for the get operation. */ export type StepsGetResponse = StepResource & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: StepResource; }; }; /** * Contains response data for the list operation. */ export type StepsListResponse = Array<StepResource> & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: StepResource[]; }; }; /** * Contains response data for the createOrUpdate operation. */ export type RolloutsCreateOrUpdateResponse = RolloutRequest & RolloutsCreateOrUpdateHeaders & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The parsed HTTP response headers. */ parsedHeaders: RolloutsCreateOrUpdateHeaders; /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: RolloutRequest; }; }; /** * Contains response data for the get operation. */ export type RolloutsGetResponse = Rollout & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: Rollout; }; }; /** * Contains response data for the cancel operation. */ export type RolloutsCancelResponse = Rollout & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: Rollout; }; }; /** * Contains response data for the restart operation. */ export type RolloutsRestartResponse = Rollout & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: Rollout; }; }; /** * Contains response data for the list operation. */ export type RolloutsListResponse = Array<Rollout> & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: Rollout[]; }; }; /** * Contains response data for the createOrUpdate operation. */ export type ArtifactSourcesCreateOrUpdateResponse = ArtifactSource & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: ArtifactSource; }; }; /** * Contains response data for the get operation. */ export type ArtifactSourcesGetResponse = ArtifactSource & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: ArtifactSource; }; }; /** * Contains response data for the list operation. */ export type ArtifactSourcesListResponse = Array<ArtifactSource> & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: ArtifactSource[]; }; }; /** * Contains response data for the list operation. */ export type OperationsListResponse = OperationsList & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: OperationsList; }; };
the_stack
//@ts-check ///<reference path="devkit.d.ts" /> declare namespace DevKit { namespace FormSocial_Activity { interface Header extends DevKit.Controls.IHeader { /** Shows how contact about the social activity originated, such as from Twitter or Facebook. This field is read-only. */ Community: DevKit.Controls.OptionSet; /** Shows the priority so that preferred customers or critical issues are handled quickly. */ PriorityCode: DevKit.Controls.OptionSet; /** Value derived after assessing words commonly associated with a negative, neutral, or positive sentiment that occurs in a social post. Sentiment information can also be reported as numeric values. */ SentimentValue: DevKit.Controls.Double; /** Shows whether the social activity is completed, failed, or processing. This field is read-only. */ StatusCode: DevKit.Controls.OptionSet; } interface Tabs { } interface Body { /** Date and time when the activity was created. */ CreatedOn: DevKit.Controls.DateTime; /** Shows information about the social post content. This field is read-only. */ Description: DevKit.Controls.String; /** Shows the date and time when the record was last updated. The date and time are displayed in the time zone selected in Microsoft Dynamics 365 options. */ ModifiedOn: DevKit.Controls.DateTime; /** Unique identifier of the user or team who owns the activity. */ OwnerId: DevKit.Controls.Lookup; /** For internal use only. */ PostedOn: DevKit.Controls.DateTime; /** Shows the author of the post on the corresponding social channel. */ PostFromProfileId: DevKit.Controls.Lookup; /** Shows if the social post originated as a private or public message. */ PostMessageType: DevKit.Controls.OptionSet; /** Shows the recipients of the social post. */ PostToProfileId: DevKit.Controls.String; /** Shows the URL of the post. */ PostURL: DevKit.Controls.String; /** Shows the record that the social activity relates to. */ RegardingObjectId: DevKit.Controls.Lookup; /** Subject associated with the activity. */ Subject: DevKit.Controls.String; } } class FormSocial_Activity extends DevKit.IForm { /** * DynamicsCrm.DevKit form Social_Activity * @param executionContext the execution context * @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource" */ constructor(executionContext: any, defaultWebResourceName?: string); /** Utility functions/methods/objects for Dynamics 365 form */ Utility: DevKit.Utility; /** The Body section of form Social_Activity */ Body: DevKit.FormSocial_Activity.Body; /** The Header section of form Social_Activity */ Header: DevKit.FormSocial_Activity.Header; } namespace FormSocial_Activity_for_Interactive_experience { interface Header extends DevKit.Controls.IHeader { /** Shows how contact about the social activity originated, such as from Twitter or Facebook. This field is read-only. */ Community: DevKit.Controls.OptionSet; /** Shows the priority so that preferred customers or critical issues are handled quickly. */ PriorityCode: DevKit.Controls.OptionSet; /** Value derived after assessing words commonly associated with a negative, neutral, or positive sentiment that occurs in a social post. Sentiment information can also be reported as numeric values. */ SentimentValue: DevKit.Controls.Double; /** Shows whether the social activity completed. This field is read-only. */ StateCode: DevKit.Controls.OptionSet; } interface tab_tab_2_Sections { Description: DevKit.Controls.Section; tab_2_section_1: DevKit.Controls.Section; tab_2_section_2: DevKit.Controls.Section; } interface tab_tab_2 extends DevKit.Controls.ITab { Section: tab_tab_2_Sections; } interface Tabs { tab_2: tab_tab_2; } interface Body { Tab: Tabs; /** Shows information about the social post content. This field is read-only. */ Description: DevKit.Controls.String; /** Shows the date and time when the record was last updated. The date and time are displayed in the time zone selected in Microsoft Dynamics 365 options. */ ModifiedOn: DevKit.Controls.DateTime; /** Unique identifier of the user or team who owns the activity. */ OwnerId: DevKit.Controls.Lookup; /** For internal use only. */ PostedOn: DevKit.Controls.DateTime; /** For internal use only. */ PostedOn_1: DevKit.Controls.DateTime; /** Shows the author of the post on the corresponding social channel. */ PostFromProfileId: DevKit.Controls.Lookup; /** Shows if the social post originated as a private or public message. */ PostMessageType: DevKit.Controls.OptionSet; /** Shows the recipients of the social post. */ PostToProfileId: DevKit.Controls.String; /** Shows the URL of the post. */ PostURL: DevKit.Controls.String; /** Shows the record that the social activity relates to. */ RegardingObjectId: DevKit.Controls.Lookup; /** Shows the record that the social activity relates to. */ RegardingObjectId_1: DevKit.Controls.Lookup; /** Subject associated with the activity. */ Subject: DevKit.Controls.String; } } class FormSocial_Activity_for_Interactive_experience extends DevKit.IForm { /** * DynamicsCrm.DevKit form Social_Activity_for_Interactive_experience * @param executionContext the execution context * @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource" */ constructor(executionContext: any, defaultWebResourceName?: string); /** Utility functions/methods/objects for Dynamics 365 form */ Utility: DevKit.Utility; /** The Body section of form Social_Activity_for_Interactive_experience */ Body: DevKit.FormSocial_Activity_for_Interactive_experience.Body; /** The Header section of form Social_Activity_for_Interactive_experience */ Header: DevKit.FormSocial_Activity_for_Interactive_experience.Header; } class SocialActivityApi { /** * DynamicsCrm.DevKit SocialActivityApi * @param entity The entity object */ constructor(entity?: any); /** * Get the value of alias * @param alias the alias value * @param isMultiOptionSet true if the alias is multi OptionSet */ getAliasedValue(alias: string, isMultiOptionSet?: boolean): any; /** * Get the formatted value of alias * @param alias the alias value * @param isMultiOptionSet true if the alias is multi OptionSet */ getAliasedFormattedValue(alias: string, isMultiOptionSet?: boolean): string; /** The entity object */ Entity: any; /** The entity name */ EntityName: string; /** The entity collection name */ EntityCollectionName: string; /** The @odata.etag is then used to build a cache of the response that is dependant on the fields that are retrieved */ "@odata.etag": string; /** For internal use only. */ ActivityAdditionalParams: DevKit.WebApi.StringValue; /** Unique identifier of the activity. */ ActivityId: DevKit.WebApi.GuidValue; /** Actual duration of the activity in minutes. */ ActualDurationMinutes: DevKit.WebApi.IntegerValue; /** Actual end time of the activity. */ ActualEnd_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue; /** Actual start time of the activity. */ ActualStart_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue; /** Shows how contact about the social activity originated, such as from Twitter or Facebook. This field is read-only. */ Community: DevKit.WebApi.OptionSetValue; /** Unique identifier of the user who created the activity. */ CreatedBy: DevKit.WebApi.LookupValueReadonly; /** Date and time when the activity was created. */ CreatedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Unique identifier of the delegate user who created the activitypointer. */ CreatedOnBehalfBy: DevKit.WebApi.LookupValueReadonly; /** Shows information about the social post content. This field is read-only. */ Description: DevKit.WebApi.StringValue; /** Select the direction of the post as incoming or outbound. */ DirectionCode: DevKit.WebApi.BooleanValue; /** Shows the conversion rate of the record's currency. The exchange rate is used to convert all money fields in the record from the local currency to the system's default currency. */ ExchangeRate: DevKit.WebApi.DecimalValueReadonly; /** Sequence number of the import that created this record. */ ImportSequenceNumber: DevKit.WebApi.IntegerValue; /** Unique identifier for the responses to a post. For internal use only. */ InResponseTo: DevKit.WebApi.StringValue; /** Information regarding whether the activity was billed as part of resolving a case. */ IsBilled: DevKit.WebApi.BooleanValue; /** Information regarding whether the activity is a regular activity type or event type. */ IsRegularActivity: DevKit.WebApi.BooleanValueReadonly; /** Information regarding whether the activity was created from a workflow rule. */ IsWorkflowCreated: DevKit.WebApi.BooleanValue; /** Contains the date and time stamp of the last on hold time. */ LastOnHoldTime_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue; /** For internal use only. */ ModifiedBy: DevKit.WebApi.LookupValueReadonly; /** Shows the date and time when the record was last updated. The date and time are displayed in the time zone selected in Microsoft Dynamics 365 options. */ ModifiedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** For internal use only. */ ModifiedOnBehalfBy: DevKit.WebApi.LookupValueReadonly; /** Shows how long, in minutes, that the record was on hold. */ OnHoldTime: DevKit.WebApi.IntegerValueReadonly; /** Date and time that the record was migrated. */ OverriddenCreatedOn_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue; /** Enter the user who is assigned to manage the record. This field is updated every time the record is assigned to a different user */ OwnerId_systemuser: DevKit.WebApi.LookupValue; /** Enter the team who is assigned to manage the record. This field is updated every time the record is assigned to a different team */ OwnerId_team: DevKit.WebApi.LookupValue; /** Unique identifier of the business unit that owns the activity. */ OwningBusinessUnit: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the team that owns the activity. */ OwningTeam: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the user who owns the Activity. */ OwningUser: DevKit.WebApi.LookupValueReadonly; postauthor_account: DevKit.WebApi.LookupValue; postauthor_contact: DevKit.WebApi.LookupValue; postauthoraccount_account: DevKit.WebApi.LookupValue; postauthoraccount_contact: DevKit.WebApi.LookupValue; /** For internal use only. */ PostedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue; /** Shows the author of the post on the corresponding social channel. */ PostFromProfileId: DevKit.WebApi.LookupValue; PostFromProfileIdName: DevKit.WebApi.StringValueReadonly; /** Unique identifier of the post. For internal use only. */ PostId: DevKit.WebApi.StringValue; /** Shows if the social post originated as a private or public message. */ PostMessageType: DevKit.WebApi.OptionSetValue; /** Shows the recipients of the social post. */ PostToProfileId: DevKit.WebApi.StringValue; /** Shows the URL of the post. */ PostURL: DevKit.WebApi.StringValue; /** Shows the priority so that preferred customers or critical issues are handled quickly. */ PriorityCode: DevKit.WebApi.OptionSetValue; /** Unique identifier of the Process. */ ProcessId: DevKit.WebApi.GuidValue; /** Shows the record that the social activity relates to. */ regardingobjectid_account_socialactivity: DevKit.WebApi.LookupValue; /** Shows the record that the social activity relates to. */ regardingobjectid_asyncoperation: DevKit.WebApi.LookupValue; /** Shows the record that the social activity relates to. */ regardingobjectid_contact_socialactivity: DevKit.WebApi.LookupValue; /** Shows the record that the social activity relates to. */ regardingobjectid_knowledgearticle_socialactivity: DevKit.WebApi.LookupValue; /** Shows the record that the social activity relates to. */ regardingobjectid_knowledgebaserecord_socialactivity: DevKit.WebApi.LookupValue; RegardingObjectIdYomiName: DevKit.WebApi.StringValue; /** Scheduled duration of the activity, specified in minutes. */ ScheduledDurationMinutes: DevKit.WebApi.IntegerValue; /** Scheduled end time of the activity. */ ScheduledEnd_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue; /** Scheduled start time of the activity. */ ScheduledStart_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue; /** Value derived after assessing words commonly associated with a negative, neutral, or positive sentiment that occurs in a social post. Sentiment information can also be reported as numeric values. */ SentimentValue: DevKit.WebApi.DoubleValue; /** Choose the service level agreement (SLA) that you want to apply to the Social Activity record. */ SLAId: DevKit.WebApi.LookupValue; /** Last SLA that was applied to this Social Activity. This field is for internal use only. */ SLAInvokedId: DevKit.WebApi.LookupValueReadonly; SLAName: DevKit.WebApi.StringValueReadonly; /** For internal use only. */ SocialAdditionalParams: DevKit.WebApi.StringValue; /** Shows the date and time by which the activities are sorted. */ SortDate_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue; /** Unique identifier of the Stage. */ StageId: DevKit.WebApi.GuidValue; /** Shows whether the social activity completed. This field is read-only. */ StateCode: DevKit.WebApi.OptionSetValue; /** Shows whether the social activity is completed, failed, or processing. This field is read-only. */ StatusCode: DevKit.WebApi.OptionSetValue; /** Subject associated with the activity. */ Subject: DevKit.WebApi.StringValue; /** Unique identifier of the social conversation. For internal use only. */ ThreadId: DevKit.WebApi.StringValue; /** For internal use only. */ TimeZoneRuleVersionNumber: DevKit.WebApi.IntegerValue; /** Choose the local currency for the record to make sure budgets are reported in the correct currency. */ TransactionCurrencyId: DevKit.WebApi.LookupValue; /** For internal use only. */ TraversedPath: DevKit.WebApi.StringValue; /** Time zone code that was in use when the record was created. */ UTCConversionTimeZoneCode: DevKit.WebApi.IntegerValue; /** Version number of the social activity. */ VersionNumber: DevKit.WebApi.BigIntValueReadonly; /** The array of object that can cast object to ActivityPartyApi class */ ActivityParties: Array<any>; } } declare namespace OptionSet { namespace SocialActivity { enum Community { /** 1 */ Facebook, /** 0 */ Other, /** 2 */ Twitter } enum PostMessageType { /** 1 */ Private_Message, /** 0 */ Public_Message } enum PriorityCode { /** 2 */ High, /** 0 */ Low, /** 1 */ Normal } enum StateCode { /** 2 */ Canceled, /** 1 */ Completed, /** 0 */ Open } enum StatusCode { /** 5 */ Canceled, /** 1 */ Completed, /** 2 */ Failed, /** 4 */ Open, /** 3 */ Processing } enum RollupState { /** 0 - Attribute value is yet to be calculated */ NotCalculated, /** 1 - Attribute value has been calculated per the last update time in <AttributeSchemaName>_Date attribute */ Calculated, /** 2 - Attribute value calculation lead to overflow error */ OverflowError, /** 3 - Attribute value calculation failed due to an internal error, next run of calculation job will likely fix it */ OtherError, /** 4 - Attribute value calculation failed because the maximum number of retry attempts to calculate the value were exceeded likely due to high number of concurrency and locking conflicts */ RetryLimitExceeded, /** 5 - Attribute value calculation failed because maximum hierarchy depth limit for calculation was reached */ HierarchicalRecursionLimitReached, /** 6 - Attribute value calculation failed because a recursive loop was detected in the hierarchy of the record */ LoopDetected } } } //{'JsForm':['Social Activity','Social Activity for Interactive experience'],'JsWebApi':true,'IsDebugForm':true,'IsDebugWebApi':true,'Version':'2.12.31','JsFormVersion':'v2'}
the_stack
import { CPU } from '../cpu/cpu'; import { AVRUSART, usart0Config } from './usart'; const FREQ_16MHZ = 16e6; const FREQ_11_0529MHZ = 11059200; // CPU registers const SREG = 95; // USART0 Registers const UCSR0A = 0xc0; const UCSR0B = 0xc1; const UCSR0C = 0xc2; const UBRR0L = 0xc4; const UBRR0H = 0xc5; const UDR0 = 0xc6; // Register bit names const U2X0 = 2; const TXEN = 8; const RXEN = 16; const UDRIE = 0x20; const TXCIE = 0x40; const RXC = 0x80; const TXC = 0x40; const UDRE = 0x20; const USBS = 0x08; const UPM0 = 0x10; const UPM1 = 0x20; // Interrupt address const PC_INT_UDRE = 0x26; const PC_INT_TXC = 0x28; const UCSZ0 = 2; const UCSZ1 = 4; const UCSZ2 = 4; describe('USART', () => { it('should correctly calculate the baudRate from UBRR', () => { const cpu = new CPU(new Uint16Array(1024)); const usart = new AVRUSART(cpu, usart0Config, FREQ_11_0529MHZ); cpu.writeData(UBRR0H, 0); cpu.writeData(UBRR0L, 5); expect(usart.baudRate).toEqual(115200); }); it('should correctly calculate the baudRate from UBRR in double-speed mode', () => { const cpu = new CPU(new Uint16Array(1024)); const usart = new AVRUSART(cpu, usart0Config, FREQ_16MHZ); cpu.writeData(UBRR0H, 3); cpu.writeData(UBRR0L, 64); cpu.writeData(UCSR0A, U2X0); expect(usart.baudRate).toEqual(2400); }); it('should call onConfigurationChange when the baudRate changes', () => { const cpu = new CPU(new Uint16Array(1024)); const usart = new AVRUSART(cpu, usart0Config, FREQ_16MHZ); const onConfigurationChange = jest.fn(); usart.onConfigurationChange = onConfigurationChange; cpu.writeData(UBRR0H, 0); expect(onConfigurationChange).toHaveBeenCalled(); onConfigurationChange.mockClear(); cpu.writeData(UBRR0L, 5); expect(onConfigurationChange).toHaveBeenCalled(); onConfigurationChange.mockClear(); cpu.writeData(UCSR0A, U2X0); expect(onConfigurationChange).toHaveBeenCalled(); }); describe('bitsPerChar', () => { it('should return 5-bits per byte when UCSZ = 0', () => { const cpu = new CPU(new Uint16Array(1024)); const usart = new AVRUSART(cpu, usart0Config, FREQ_16MHZ); cpu.writeData(UCSR0C, 0); expect(usart.bitsPerChar).toEqual(5); }); it('should return 6-bits per byte when UCSZ = 1', () => { const cpu = new CPU(new Uint16Array(1024)); const usart = new AVRUSART(cpu, usart0Config, FREQ_16MHZ); cpu.writeData(UCSR0C, UCSZ0); expect(usart.bitsPerChar).toEqual(6); }); it('should return 7-bits per byte when UCSZ = 2', () => { const cpu = new CPU(new Uint16Array(1024)); const usart = new AVRUSART(cpu, usart0Config, FREQ_16MHZ); cpu.writeData(UCSR0C, UCSZ1); expect(usart.bitsPerChar).toEqual(7); }); it('should return 8-bits per byte when UCSZ = 3', () => { const cpu = new CPU(new Uint16Array(1024)); const usart = new AVRUSART(cpu, usart0Config, FREQ_16MHZ); cpu.writeData(UCSR0C, UCSZ0 | UCSZ1); expect(usart.bitsPerChar).toEqual(8); }); it('should return 9-bits per byte when UCSZ = 7', () => { const cpu = new CPU(new Uint16Array(1024)); const usart = new AVRUSART(cpu, usart0Config, FREQ_16MHZ); cpu.writeData(UCSR0C, UCSZ0 | UCSZ1); cpu.writeData(UCSR0B, UCSZ2); expect(usart.bitsPerChar).toEqual(9); }); it('should call onConfigurationChange when bitsPerChar change', () => { const cpu = new CPU(new Uint16Array(1024)); const usart = new AVRUSART(cpu, usart0Config, FREQ_16MHZ); const onConfigurationChange = jest.fn(); usart.onConfigurationChange = onConfigurationChange; cpu.writeData(UCSR0C, UCSZ0 | UCSZ1); expect(onConfigurationChange).toHaveBeenCalled(); onConfigurationChange.mockClear(); cpu.writeData(UCSR0B, UCSZ2); expect(onConfigurationChange).toHaveBeenCalled(); onConfigurationChange.mockClear(); cpu.writeData(UCSR0B, UCSZ2); expect(onConfigurationChange).not.toHaveBeenCalled(); }); }); describe('stopBits', () => { it('should return 1 when USBS = 0', () => { const cpu = new CPU(new Uint16Array(1024)); const usart = new AVRUSART(cpu, usart0Config, FREQ_16MHZ); expect(usart.stopBits).toEqual(1); }); it('should return 2 when USBS = 1', () => { const cpu = new CPU(new Uint16Array(1024)); const usart = new AVRUSART(cpu, usart0Config, FREQ_16MHZ); cpu.writeData(UCSR0C, USBS); expect(usart.stopBits).toEqual(2); }); }); describe('parityEnabled', () => { it('should return false when UPM1 = 0', () => { const cpu = new CPU(new Uint16Array(1024)); const usart = new AVRUSART(cpu, usart0Config, FREQ_16MHZ); expect(usart.parityEnabled).toEqual(false); }); it('should return true when UPM1 = 1', () => { const cpu = new CPU(new Uint16Array(1024)); const usart = new AVRUSART(cpu, usart0Config, FREQ_16MHZ); cpu.writeData(UCSR0C, UPM1); expect(usart.parityEnabled).toEqual(true); }); }); describe('parityOdd', () => { it('should return false when UPM0 = 0', () => { const cpu = new CPU(new Uint16Array(1024)); const usart = new AVRUSART(cpu, usart0Config, FREQ_16MHZ); expect(usart.parityOdd).toEqual(false); }); it('should return true when UPM0 = 1', () => { const cpu = new CPU(new Uint16Array(1024)); const usart = new AVRUSART(cpu, usart0Config, FREQ_16MHZ); cpu.writeData(UCSR0C, UPM0); expect(usart.parityOdd).toEqual(true); }); }); it('should invoke onByteTransmit when UDR0 is written to', () => { const cpu = new CPU(new Uint16Array(1024)); const usart = new AVRUSART(cpu, usart0Config, FREQ_16MHZ); usart.onByteTransmit = jest.fn(); cpu.writeData(UCSR0B, TXEN); cpu.writeData(UDR0, 0x61); expect(usart.onByteTransmit).toHaveBeenCalledWith(0x61); }); describe('txEnable/rxEnable', () => { it('txEnable should equal true when the transitter is enabled', () => { const cpu = new CPU(new Uint16Array(1024)); const usart = new AVRUSART(cpu, usart0Config, FREQ_16MHZ); usart.onByteTransmit = jest.fn(); expect(usart.txEnable).toEqual(false); cpu.writeData(UCSR0B, TXEN); expect(usart.txEnable).toEqual(true); }); it('rxEnable should equal true when the transitter is enabled', () => { const cpu = new CPU(new Uint16Array(1024)); const usart = new AVRUSART(cpu, usart0Config, FREQ_16MHZ); usart.onByteTransmit = jest.fn(); expect(usart.rxEnable).toEqual(false); cpu.writeData(UCSR0B, RXEN); expect(usart.rxEnable).toEqual(true); }); }); describe('tick()', () => { it('should trigger data register empty interrupt if UDRE is set', () => { const cpu = new CPU(new Uint16Array(1024)); new AVRUSART(cpu, usart0Config, FREQ_16MHZ); cpu.writeData(UCSR0B, UDRIE | TXEN); cpu.data[SREG] = 0x80; // SREG: I------- cpu.tick(); expect(cpu.pc).toEqual(PC_INT_UDRE); expect(cpu.cycles).toEqual(2); expect(cpu.data[UCSR0A] & UDRE).toEqual(0); }); it('should trigger data TX Complete interrupt if TXCIE is set', () => { const cpu = new CPU(new Uint16Array(1024)); new AVRUSART(cpu, usart0Config, FREQ_16MHZ); cpu.writeData(UCSR0B, TXCIE | TXEN); cpu.writeData(UDR0, 0x61); cpu.data[SREG] = 0x80; // SREG: I------- cpu.cycles = 1e6; cpu.tick(); expect(cpu.pc).toEqual(PC_INT_TXC); expect(cpu.cycles).toEqual(1e6 + 2); expect(cpu.data[UCSR0A] & TXC).toEqual(0); }); it('should not trigger data TX Complete interrupt if UDR was not written to', () => { const cpu = new CPU(new Uint16Array(1024)); new AVRUSART(cpu, usart0Config, FREQ_16MHZ); cpu.writeData(UCSR0B, TXCIE | TXEN); cpu.data[SREG] = 0x80; // SREG: I------- cpu.tick(); expect(cpu.pc).toEqual(0); expect(cpu.cycles).toEqual(0); }); it('should not trigger any interrupt if interrupts are disabled', () => { const cpu = new CPU(new Uint16Array(1024)); new AVRUSART(cpu, usart0Config, FREQ_16MHZ); cpu.writeData(UCSR0B, UDRIE | TXEN); cpu.writeData(UDR0, 0x61); cpu.data[SREG] = 0; // SREG: 0 (disable interrupts) cpu.cycles = 1e6; cpu.tick(); expect(cpu.pc).toEqual(0); expect(cpu.cycles).toEqual(1e6); expect(cpu.data[UCSR0A]).toEqual(TXC | UDRE); }); }); describe('onLineTransmit', () => { it('should call onLineTransmit with the current line buffer after every newline', () => { const cpu = new CPU(new Uint16Array(1024)); const usart = new AVRUSART(cpu, usart0Config, FREQ_16MHZ); usart.onLineTransmit = jest.fn(); cpu.writeData(UCSR0B, TXEN); cpu.writeData(UDR0, 0x48); // 'H' cpu.writeData(UDR0, 0x65); // 'e' cpu.writeData(UDR0, 0x6c); // 'l' cpu.writeData(UDR0, 0x6c); // 'l' cpu.writeData(UDR0, 0x6f); // 'o' cpu.writeData(UDR0, 0xa); // '\n' expect(usart.onLineTransmit).toHaveBeenCalledWith('Hello'); }); it('should not call onLineTransmit if no newline was received', () => { const cpu = new CPU(new Uint16Array(1024)); const usart = new AVRUSART(cpu, usart0Config, FREQ_16MHZ); usart.onLineTransmit = jest.fn(); cpu.writeData(UCSR0B, TXEN); cpu.writeData(UDR0, 0x48); // 'H' cpu.writeData(UDR0, 0x69); // 'i' expect(usart.onLineTransmit).not.toHaveBeenCalled(); }); it('should clear the line buffer after each call to onLineTransmit', () => { const cpu = new CPU(new Uint16Array(1024)); const usart = new AVRUSART(cpu, usart0Config, FREQ_16MHZ); usart.onLineTransmit = jest.fn(); cpu.writeData(UCSR0B, TXEN); cpu.writeData(UDR0, 0x48); // 'H' cpu.writeData(UDR0, 0x69); // 'i' cpu.writeData(UDR0, 0xa); // '\n' cpu.writeData(UDR0, 0x74); // 't' cpu.writeData(UDR0, 0x68); // 'h' cpu.writeData(UDR0, 0x65); // 'e' cpu.writeData(UDR0, 0x72); // 'r' cpu.writeData(UDR0, 0x65); // 'e' cpu.writeData(UDR0, 0xa); // '\n' expect(usart.onLineTransmit).toHaveBeenCalledWith('there'); }); }); describe('writeByte', () => { it('should return false if called when RX is busy', () => { const cpu = new CPU(new Uint16Array(1024)); const usart = new AVRUSART(cpu, usart0Config, FREQ_16MHZ); cpu.writeData(UCSR0B, RXEN); cpu.writeData(UBRR0L, 103); // baud: 9600 expect(usart.writeByte(10)).toEqual(true); expect(usart.writeByte(10)).toEqual(false); cpu.tick(); expect(usart.writeByte(10)).toEqual(false); }); }); describe('Integration tests', () => { it('should set the TXC bit after ~1.04mS when baud rate set to 9600', () => { const cpu = new CPU(new Uint16Array(1024)); new AVRUSART(cpu, usart0Config, FREQ_16MHZ); cpu.writeData(UCSR0B, TXEN); cpu.writeData(UBRR0L, 103); // baud: 9600 cpu.writeData(UDR0, 0x48); // 'H' cpu.cycles += 16000; // 1ms cpu.tick(); expect(cpu.data[UCSR0A] & TXC).toEqual(0); cpu.cycles += 800; // 0.05ms cpu.tick(); expect(cpu.data[UCSR0A] & TXC).toEqual(TXC); }); it('should be ready to recieve the next byte after ~1.04ms when baudrate set to 9600', () => { const cpu = new CPU(new Uint16Array(1024)); const usart = new AVRUSART(cpu, usart0Config, FREQ_16MHZ); const rxCompleteCallback = jest.fn(); usart.onRxComplete = rxCompleteCallback; cpu.writeData(UCSR0B, RXEN); cpu.writeData(UBRR0L, 103); // baud: 9600 expect(usart.writeByte(0x42)).toBe(true); cpu.cycles += 16000; // 1ms cpu.tick(); expect(cpu.data[UCSR0A] & RXC).toEqual(0); // byte not received yet expect(usart.rxBusy).toBe(true); expect(rxCompleteCallback).not.toHaveBeenCalled(); cpu.cycles += 800; // 0.05ms cpu.tick(); expect(cpu.data[UCSR0A] & RXC).toEqual(RXC); expect(usart.rxBusy).toBe(false); expect(rxCompleteCallback).toHaveBeenCalled(); expect(cpu.readData(UDR0)).toEqual(0x42); expect(cpu.readData(UDR0)).toEqual(0); }); }); });
the_stack
module formFor { /** * TextField $scope. */ interface TextFieldScope extends ng.IScope { /** * Name of the attribute within the parent form-for directive's model object. * This attributes specifies the data-binding target for the input. * Dot notation (ex "address.street") is supported. */ attribute:string; /** * HTML field attributes; passed along so that custom view implementations can access custom parameters. */ attributes:any; /** * Auto-focus the input field. */ autofocus?:boolean; /** * Optional function to be invoked on text input blur. */ blurred?:Function; /** * NgModelController of the input. */ controller:any; /** * Debounce duration (in ms) before input text is applied to model and evaluated. * To disable debounce (update only on blur) specify a value of false. * This value's default is determined by FormForConfiguration. */ debounce?:number; /** * Disable input element. * (Note the name is disable and not disabled to avoid collisions with the HTML5 disabled attribute). */ disable:boolean; /** * Optional help tooltip to display on hover. * By default this makes use of the Angular Bootstrap tooltip directive and the Font Awesome icon set. */ help?:string; /** * Optional function to be invoked on text input focus. */ focused?:Function; /** * Optional CSS class to display as an icon after the input field. * An object with the following keys may also be provided: pristine, valid, invalid * In this case the icon specified by a particular state will be shown based on the field's validation status. */ iconAfter?:string; /** * Optional function to be invoked when the after-icon is clicked. */ iconAfterClicked?:Function; /** * Optional CSS class to display as a icon before the input field. * An object with the following keys may also be provided: pristine, valid, invalid * In this case the icon specified by a particular state will be shown based on the field's validation status. */ iconBefore?:string; /** * Optional function to be invoked when the before-icon is clicked. */ iconBeforeClicked?:Function; /** * Optional field label displayed before the input. * (Although not required, it is strongly suggested that you specify a value for this attribute.) HTML is allowed for this attribute. */ label?:string; /** * Optional class-name for field <label>. */ labelClass?:string; /** * Data shared between formFor and textField directives. */ model:BindableFieldWrapper; /** * Enable multi-line input. */ multiline?:boolean; /** * View should call this method on blur. * This method will ensure that the correct user-specified $scope callback is executed. */ onBlur:Function; /** * View should call this method when the after-icon is clicked. * This method will ensure that the correct user-specified $scope callback is executed. */ onIconAfterClick:Function; /** * View should call this method when the before-icon is clicked. * This method will ensure that the correct user-specified $scope callback is executed. */ onIconBeforeClick:Function; /** * View should call this method on focus. * This method will ensure that the correct user-specified $scope callback is executed. */ onFocus:Function; /** * Optional placeholder text to display if input is empty. */ placeholder?:string; /** * Optional number of rows for a multline `<textarea>`; defaults to 3. */ rows?:number; /** * Optional custom tab index for input; by default this is 0 (tab order chosen by the browser) */ tabIndex?:number; /** * Optional HTML input-type (ex. text, password, etc.). * Defaults to "text". */ type:string; /** * Optional ID to assign to the inner <input type="checkbox"> element; * A unique ID will be auto-generated if no value is provided. */ uid?:string; /** * Exposes special validation rules to the view layer to be passed on to the <input> control. */ validationRules:Object; } var $log_:ng.ILogService; var $timeout_:ng.ITimeoutService; var fieldHelper_:FieldHelper; /** * Displays an HTML &lt;input&gt; or &lt;textarea&gt; element along with an optional label. * * <p>The HTML &lt;input&gt; type can be configured to allow for passwords, numbers, etc. * This directive can also be configured to display an informational tooltip. * In the event of a validation error, this directive will also render an inline error message. * * <p>This directive supports the following HTML attributes in addition to its scope properties: * * <ul> * <li>autofocus: The presence of this attribute will auto-focus the input field. * <li>multiline: The presence of this attribute enables multi-line input. * </ul> * * @example * // To create a password input you might use the following markup: * <text-field attribute="password" label="Password" type="password"></text-field> * * // To create a more advanced input field, with placeholder text and help tooltip you might use the following markup: * <text-field attribute="username" label="Username" * placeholder="Example brianvaughn" * help="Your username will be visible to others!"></text-field> * * // To render a multiline text input (or <textarea>): * <text-field attribute="description" label="Description" multiline></text-field> * * // To render icons based on the status of the field (pristin, invalid, valid) pass an object: * <text-field attribute="username" label="Username" * icon-after="{pristine: 'fa fa-user', invalid: 'fa fa-times', valid: 'fa fa-check'}"> * </text-field> */ export class TextFieldDirective implements ng.IDirective { require:string = '^formFor'; restrict:string = 'EA'; templateUrl:string = ($element, $attributes) => { return $attributes['template'] || 'form-for/templates/text-field.html'; }; scope:any = { attribute: '@', debounce: '@?', disable: '=', focused: '&?', blurred: '&?', help: '@?', iconAfterClicked: '&?', iconBeforeClicked: '&?', placeholder: '@?', rows: '=?', controller: '=?' }; /* @ngInject */ constructor($log:ng.ILogService, $timeout:ng.ITimeoutService, fieldHelper:FieldHelper) { $log_ = $log; $timeout_ = $timeout; fieldHelper_ = fieldHelper; } link($scope:TextFieldScope, $element:ng.IAugmentedJQuery, $attributes:ng.IAttributes, formForController:FormForController):void { if (!$scope.attribute) { $log_.error('Missing required field "attribute"'); return; } // Expose textField attributes to textField template partials for easier customization (see issue #61) $scope.attributes = $attributes; $scope.rows = $scope.rows || 3; $scope.type = $attributes['type'] || 'text'; $scope.multiline = $attributes.hasOwnProperty('multiline') && $attributes['multiline'] !== 'false'; $scope.tabIndex = $attributes['tabIndex'] || 0; $timeout_(() => { $scope.controller = $element.find($scope.multiline ? 'textarea' : 'input').controller('ngModel'); }); if ($attributes.hasOwnProperty('autofocus')) { $timeout_(() => { $element.find($scope.multiline ? 'textarea' : 'input')[0].focus(); }); } fieldHelper_.manageLabel($scope, $attributes, false); fieldHelper_.manageFieldRegistration($scope, $attributes, formForController); // Expose certain validation rules (such as min/max) so that the view layer can pass them along var validationRules:ValidationRules = formForController.getValidationRulesForAttribute($scope.attribute); if (validationRules) { $scope.validationRules = { increment: validationRules.increment, maximum: validationRules.maximum, minimum: validationRules.minimum } // TODO We could pull the text field :type from validation rules as well // But that would be a non-backwards-compatible change. } // Update $scope.iconAfter based on the field state (see class-level documentation for more) if ($attributes['iconAfter']) { var updateIconAfter:(value?:any) => any = () => { if (!$scope.model) { return; } var iconAfter:any = $attributes['iconAfter'].charAt(0) === '{' ? $scope.$eval($attributes['iconAfter']) : $attributes['iconAfter']; if (angular.isObject(iconAfter)) { if ($scope.model.error) { $scope.iconAfter = iconAfter['invalid']; } else if ($scope.model.pristine) { $scope.iconAfter = iconAfter['pristine']; } else { $scope.iconAfter = iconAfter['valid']; } } else { $scope.iconAfter = iconAfter; } }; $attributes.$observe('iconAfter', updateIconAfter); $scope.$watch('model.error', updateIconAfter); $scope.$watch('model.pristine', updateIconAfter); } // Update $scope.iconBefore based on the field state (see class-level documentation for more) if ($attributes['iconBefore']) { var updateIconBefore:(value?:any) => any = () => { if (!$scope.model) { return; } var iconBefore:any = $attributes['iconBefore'].charAt(0) === '{' ? $scope.$eval($attributes['iconBefore']) : $attributes['iconBefore']; if (angular.isObject(iconBefore)) { if ($scope.model.error) { $scope.iconBefore = iconBefore['invalid']; } else if ($scope.model.pristine) { $scope.iconBefore = iconBefore['pristine']; } else { $scope.iconBefore = iconBefore['valid']; } } else { $scope.iconBefore = iconBefore; } }; $attributes.$observe('iconBefore', updateIconBefore); $scope.$watch('model.error', updateIconBefore); $scope.$watch('model.pristine', updateIconBefore); } $scope.onIconAfterClick = () => { if ($scope.hasOwnProperty('iconAfterClicked')) { $scope.iconAfterClicked(); } }; $scope.onIconBeforeClick = () => { if ($scope.hasOwnProperty('iconBeforeClicked')) { $scope.iconBeforeClicked(); } }; $scope.onFocus = () => { if ($scope.hasOwnProperty('focused')) { $scope.focused(); } }; $scope.onBlur = () => { if ($scope.hasOwnProperty('blurred')) { $scope.blurred(); } }; } } angular.module('formFor').directive('textField', ($log, $timeout, FieldHelper) => { return new TextFieldDirective($log, $timeout, FieldHelper); }); }
the_stack
import React, { useRef, useState, useCallback } from "react"; import useResizeObserver from "../"; import { render, cleanup } from "@testing-library/react"; import useRenderTrigger from "./utils/useRenderTrigger"; import awaitNextFrame from "./utils/awaitNextFrame"; import createController from "./utils/createController"; import useMergedCallbackRef from "./utils/useMergedCallbackRef"; import { ObservedSize, supports } from "./utils"; afterEach(() => { cleanup(); }); describe("Testing Lib: Basics", () => { // TODO also make sure this error doesn't happen in the console: "Warning: Can't perform a React state update on an unmounted component..." it("should measure the right sizes", async () => { const controller = createController(); const Test = () => { const { ref, width = 0, height = 0, } = useResizeObserver<HTMLDivElement>(); const mergedCallbackRef = useMergedCallbackRef( ref, (element: HTMLElement) => { controller.provideSetSizeFunction(element); } ); controller.incrementRenderCount(); controller.reportMeasuredSize({ width, height }); return <div ref={mergedCallbackRef} />; }; render(<Test />); // Default response on the first render before an actual measurement took place controller.assertMeasuredSize({ width: 0, height: 0 }); controller.assertRenderCount(1); // Should react to component size changes. await controller.setSize({ width: 100, height: 200 }); controller.assertMeasuredSize({ width: 100, height: 200 }); controller.assertRenderCount(2); }); }); describe("Testing Lib: Resize Observer Instance Counting Block", () => { let resizeObserverInstanceCount = 0; let resizeObserverObserveCount = 0; let resizeObserverUnobserveCount = 0; const NativeResizeObserver = (window as any).ResizeObserver; beforeAll(() => { (window as any).ResizeObserver = function PatchedResizeObserver( cb: Function ) { resizeObserverInstanceCount++; const ro = new NativeResizeObserver(cb) as ResizeObserver; // mock return { observe: (element: Element) => { resizeObserverObserveCount++; return ro.observe(element); }, unobserve: (element: Element) => { resizeObserverUnobserveCount++; return ro.unobserve(element); }, }; }; }); beforeEach(() => { resizeObserverInstanceCount = 0; resizeObserverObserveCount = 0; resizeObserverUnobserveCount = 0; }); afterAll(() => { // Try catches fixes a Firefox issue on Travis: // https://travis-ci.org/github/ZeeCoder/use-resize-observer/builds/677364283 try { (window as any).ResizeObserver = NativeResizeObserver; } catch (error) { // it's fine } }); it("should use a single ResizeObserver instance even if the onResize callback is not memoised", async () => { const controller = createController(); const Test = () => { const { ref } = useResizeObserver<HTMLDivElement>({ // This is only here so that each render passes a different callback // instance through to the hook. onResize: () => {}, }); controller.triggerRender = useRenderTrigger(); return <div ref={ref} />; }; render(<Test />); await awaitNextFrame(); await controller.triggerRender(); // Different onResize instances used to trigger the hook's internal useEffect, // resulting in the hook using a new ResizeObserver instance on each render // regardless of what triggered it. // Now it should handle such cases and keep the previous RO instance. expect(resizeObserverInstanceCount).toBe(1); expect(resizeObserverObserveCount).toBe(1); expect(resizeObserverUnobserveCount).toBe(0); }); it("should not create a new RO instance if the hook is the same and the observed element changes", async () => { const Test = ({ observeNewElement = false }) => { const customRef = useRef<HTMLDivElement>(null); const { ref } = useResizeObserver<HTMLDivElement>({ ref: observeNewElement ? customRef : null, }); // This is a span, so that when we switch over, React actually renders a // new element used with the custom ref, which is the main point of this // test. If this were a div, then React would recycle the old element, // which is not what we want. if (observeNewElement) { return <span ref={customRef} />; } return <div ref={ref} />; }; const { rerender } = render(<Test />); await awaitNextFrame(); expect(resizeObserverInstanceCount).toBe(1); expect(resizeObserverObserveCount).toBe(1); expect(resizeObserverUnobserveCount).toBe(0); rerender(<Test observeNewElement={true} />); await awaitNextFrame(); expect(resizeObserverInstanceCount).toBe(1); expect(resizeObserverObserveCount).toBe(2); // The following unobserve count assertion actually caught the cleanup // functions being called more than one times, so it's especially important // to keep this in place in order to cover that. expect(resizeObserverUnobserveCount).toBe(1); }); it("should not create a ResizeObserver instance until there's an actual element present to be measured", async () => { let renderCount = 0; let measuredWidth: number | undefined; let measuredHeight: number | undefined; const Test = ({ doMeasure }: { doMeasure: boolean }) => { const ref = useRef<HTMLDivElement>(null); const { width, height } = useResizeObserver({ ref: doMeasure ? ref : null, }); renderCount++; measuredWidth = width; measuredHeight = height; return <div ref={ref} style={{ width: 100, height: 200 }} />; }; const { rerender } = render(<Test doMeasure={false} />); // Default behaviour on initial mount with a null ref passed to the hook expect(resizeObserverInstanceCount).toBe(0); expect(renderCount).toBe(1); expect(measuredWidth).toBe(undefined); expect(measuredHeight).toBe(undefined); // Actually kickstarting the hook by switching from null to a real ref. rerender(<Test doMeasure={true} />); await awaitNextFrame(); expect(resizeObserverInstanceCount).toBe(1); expect(renderCount).toBe(3); expect(measuredWidth).toBe(100); expect(measuredHeight).toBe(200); }); // Note that even thought this sort of "works", callback refs are the preferred // method to use in such cases. Relying in this behaviour will certainly cause // issues down the line. it("should work with refs even if the ref value is filled by react later, with a delayed mount", async () => { const controller = createController(); // Mounting later. Previously this wouldn't have been picked up // automatically, and users would've had to wait for the mount, and only // then set the ref from null, to its actual object value. // @see https://github.com/ZeeCoder/use-resize-observer/issues/43#issuecomment-674719609 const Test = ({ mount = false }) => { const { ref, width, height } = useResizeObserver<HTMLDivElement>(); controller.triggerRender = useRenderTrigger(); controller.reportMeasuredSize({ width, height }); if (!mount) { return null; } return <div ref={ref} style={{ width: 100, height: 200 }} />; }; // Reported size should be undefined before the hook kicks in const { rerender } = render(<Test />); controller.assertMeasuredSize({ width: undefined, height: undefined }); // Once the hook supposedly kicked in, it should still be undefined, as the ref is not in use yet. await awaitNextFrame(); controller.assertMeasuredSize({ width: undefined, height: undefined }); // Once mounted, the ref *will* be filled in the next render. However, the // hook has no way of knowing about this, until there's another render call, // where it gets to compare the current values between the previous and // current render. await awaitNextFrame(); rerender(<Test mount={true} />); controller.assertMeasuredSize({ width: undefined, height: undefined }); // Once that render happened, the hook finally gets a chance to measure the element. await awaitNextFrame(); await controller.triggerRender(); controller.assertMeasuredSize({ width: 100, height: 200 }); }); // This is the proper way of handling refs where the component mounts with a delay it("should pick up on delayed mounts", async () => { const controller = createController(); // Mounting later. Previously this wouldn't have been picked up // automatically, and users would've had to wait for the mount, and only // then set the ref from null, to its actual object value. // @see https://github.com/ZeeCoder/use-resize-observer/issues/43#issuecomment-674719609 const Test = ({ mount = false }) => { const { ref, width, height } = useResizeObserver<HTMLDivElement>(); controller.reportMeasuredSize({ width, height }); if (!mount) { return null; } return <div ref={ref} style={{ width: 100, height: 200 }} />; }; // Reported size should be undefined before the hook kicks in const { rerender } = render(<Test />); controller.assertMeasuredSize({ width: undefined, height: undefined }); // Once the hook supposedly kicked in, it should still be undefined, as the ref is not in use yet. await awaitNextFrame(); controller.assertMeasuredSize({ width: undefined, height: undefined }); // Once mounted, the hook should automatically pick the new element up with // the RefCallback. rerender(<Test mount={true} />); await awaitNextFrame(); controller.assertMeasuredSize({ width: 100, height: 200 }); }); it("should work on a normal mount", async () => { const controller = createController(); const Test = () => { const { ref, width, height } = useResizeObserver<HTMLDivElement>(); controller.reportMeasuredSize({ width, height }); return <div ref={ref} style={{ width: 100, height: 200 }} />; }; render(<Test />); controller.assertMeasuredSize({ width: undefined, height: undefined }); await awaitNextFrame(); controller.assertMeasuredSize({ width: 100, height: 200 }); }); it("should work with a regular element as the 'custom ref' too", async () => { const controller = createController(); const Test = () => { // This is a bit of a roundabout way of simulating the case where we have // an Element from somewhere, when we can't simply use a RefCallback. const [element, setElement] = useState<HTMLDivElement | null>(null); const { width, height } = useResizeObserver<HTMLDivElement>({ ref: element, }); // Interestingly, if this callback is not memoised, then on each render, // the callback is called with "null", then again with the element. const receiveElement = useCallback((element: HTMLDivElement) => { setElement(element); }, []); controller.reportMeasuredSize({ width, height }); return <div ref={receiveElement} style={{ width: 100, height: 200 }} />; }; render(<Test />); controller.assertMeasuredSize({ width: undefined, height: undefined }); await awaitNextFrame(); controller.assertMeasuredSize({ width: 100, height: 200 }); }); // todo separate box option testing to a separate describe block // This test will also make sure that firefox works, where the reported sizes are not returned in an array. it("should support switching back-and-forth between box types", async () => { const c1 = createController(); type Controller = { setBox: (box: ResizeObserverBoxOptions) => Promise<void>; }; const c2 = {} as Controller; const Test = () => { const [box, setBox] = useState<ResizeObserverBoxOptions>("border-box"); c2.setBox = useCallback(async (box) => { setBox(box); await awaitNextFrame(); }, []); const { ref, width, height } = useResizeObserver<HTMLDivElement>({ box }); const mergedCallbackRef = useMergedCallbackRef( ref, (element: HTMLElement) => { c1.provideSetSizeFunction(element); } ); c1.incrementRenderCount(); c1.reportMeasuredSize({ width, height }); return ( <div ref={mergedCallbackRef} style={{ padding: "10px 20px", border: "1px solid" }} /> ); }; render(<Test />); // Default response on the first render before an actual measurement took place c1.assertMeasuredSize({ width: undefined, height: undefined }); c1.assertRenderCount(1); // Should react to component size changes. await c1.setSize({ width: 100, height: 200 }); // Should report border-size if (supports.borderBox) { c1.assertRenderCount(2); c1.assertMeasuredSize({ width: 142, height: 222 }); } else { // In non-supporting browser the hook would have nothing to report. c1.assertRenderCount(1); c1.assertMeasuredSize({ width: undefined, height: undefined }); } // Should be able to switch to observing content-box await c2.setBox("content-box"); c1.assertMeasuredSize({ width: 100, height: 200 }); // 2 extra render should be happening: // - One for setting the local `box` state // - Another as a reaction to that coming from the hook, which would report the new values. if (supports.borderBox) { c1.assertRenderCount(4); } else { c1.assertRenderCount(3); } // Switching back yet again should be reported with "undefined" in non-supporting browsers. await c2.setBox("border-box"); if (supports.borderBox) { c1.assertRenderCount(6); c1.assertMeasuredSize({ width: 142, height: 222 }); } else { // In non-supporting browser the hook would have nothing to report. c1.assertRenderCount(5); c1.assertMeasuredSize({ width: undefined, height: undefined }); } }); it("should be able to measure device pixel content box in supporting browsers", async () => { const c1 = createController(); type Controller = { setZoom: (zoom: number) => Promise<void>; }; const c2 = {} as Controller; const Test = () => { const { ref, width, height } = useResizeObserver<HTMLDivElement>({ box: "device-pixel-content-box", }); const localRef = useRef<HTMLDivElement | null>(null); c2.setZoom = useCallback(async (zoom) => { if (localRef.current) { // @ts-ignore localRef.current.style.zoom = String(zoom); await awaitNextFrame(); } }, []); const mergedCallbackRef = useMergedCallbackRef( ref, (element: HTMLDivElement) => { localRef.current = element; if (localRef.current) { // @ts-ignore window.s = localRef.current.style; } c1.provideSetSizeFunction(element); } ); c1.incrementRenderCount(); c1.reportMeasuredSize({ width, height }); return <div ref={mergedCallbackRef} />; }; render(<Test />); // Default response on the first render before an actual measurement took place c1.assertRenderCount(1); c1.assertMeasuredSize({ width: undefined, height: undefined }); await c1.setSize({ width: 100, height: 200 }); if (supports.devicePixelContentBoxSize) { c1.assertRenderCount(2); c1.assertMeasuredSize({ width: Math.round(100 * devicePixelRatio), height: Math.round(200 * devicePixelRatio), }); } else { c1.assertRenderCount(1); c1.assertMeasuredSize({ width: undefined, height: undefined }); } }); it("should not report repeated values with the onResize callback", async () => { const c = createController(); const Test = () => { const [size, setSize] = useState<ObservedSize>({ width: undefined, height: undefined, }); const { ref } = useResizeObserver<HTMLDivElement>({ onResize: setSize }); const mergedCallbackRef = useMergedCallbackRef( ref, (element: HTMLDivElement) => { c.provideSetSizeFunction(element); } ); c.incrementRenderCount(); c.reportMeasuredSize(size); return <div ref={mergedCallbackRef} />; }; render(<Test />); // Default response on the first render before an actual measurement took place c.assertRenderCount(1); c.assertMeasuredSize({ width: undefined, height: undefined }); await c.setSize({ width: 100, height: 200 }); c.assertRenderCount(2); c.assertMeasuredSize({ width: 100, height: 200 }); await c.setSize({ width: 100.2, height: 200.4 }); c.assertRenderCount(2); c.assertMeasuredSize({ width: 100, height: 200 }); }); it("should accept a custom rounding function, and adapt to function instance changes without unnecessary renders", async () => { const c1 = createController(); type Controller = { replaceRoundFunction: (fn: "multiply" | "unset") => void; }; const c2 = {} as Controller; const Test = () => { const [rounder, setRounder] = useState<typeof Math.ceil | undefined>( () => Math.ceil ); const { ref, width, height } = useResizeObserver<HTMLDivElement>({ round: rounder, }); const mergedCallbackRef = useMergedCallbackRef( ref, (element: HTMLDivElement) => { c1.provideSetSizeFunction(element); c2.replaceRoundFunction = async (fn) => { setRounder(() => fn === "multiply" ? (n: number) => Math.round(n * 2) : undefined ); await awaitNextFrame(); }; } ); c1.incrementRenderCount(); c1.reportMeasuredSize({ width, height }); return <div ref={mergedCallbackRef} />; }; render(<Test />); // Default response on the first render before an actual measurement took place c1.assertRenderCount(1); c1.assertMeasuredSize({ width: undefined, height: undefined }); await c1.setSize({ width: 100.1, height: 200.1 }); c1.assertRenderCount(2); c1.assertMeasuredSize({ width: 101, height: 201 }); // Testing normal re-renders await c1.setSize({ width: 200.2, height: 300.2 }); c1.assertRenderCount(3); c1.assertMeasuredSize({ width: 201, height: 301 }); await c2.replaceRoundFunction("multiply"); c1.assertRenderCount(5); c1.assertMeasuredSize({ width: 400, height: 600 }); await c2.replaceRoundFunction("unset"); c1.assertRenderCount(7); c1.assertMeasuredSize({ width: 200, height: 300 }); }); it("should only re-render with a custom rounding function when it produces a new value", async () => { const c = createController(); // A rounding function that "snaps" to its values. const rounder = (n: number) => { if (n < 500) { return 0; } else if (n < 1000) { return 500; } return 1000; }; const Test = () => { const { ref, width, height } = useResizeObserver<HTMLDivElement>({ round: rounder, }); const mergedCallbackRef = useMergedCallbackRef( ref, (element: HTMLDivElement) => { c.provideSetSizeFunction(element); } ); c.incrementRenderCount(); c.reportMeasuredSize({ width, height }); return <div ref={mergedCallbackRef} />; }; render(<Test />); // Default response on the first render before an actual measurement took place c.assertRenderCount(1); c.assertMeasuredSize({ width: undefined, height: undefined }); await c.setSize({ width: 100, height: 100 }); c.assertRenderCount(2); c.assertMeasuredSize({ width: 0, height: 0 }); await c.setSize({ width: 200, height: 200 }); c.assertRenderCount(2); c.assertMeasuredSize({ width: 0, height: 0 }); await c.setSize({ width: 600, height: 600 }); c.assertRenderCount(3); c.assertMeasuredSize({ width: 500, height: 500 }); await c.setSize({ width: 1100, height: 600 }); c.assertRenderCount(4); c.assertMeasuredSize({ width: 1000, height: 500 }); await c.setSize({ width: 1100, height: 800 }); c.assertRenderCount(4); c.assertMeasuredSize({ width: 1000, height: 500 }); await c.setSize({ width: 1100, height: 1100 }); c.assertRenderCount(5); c.assertMeasuredSize({ width: 1000, height: 1000 }); }); });
the_stack
import { ElementRef, Injectable } from '@angular/core'; import { ActiveElement, ChartConfiguration, ChartOptions, ScatterDataPoint } from 'chart.js'; import { AnnotationOptions } from 'chartjs-plugin-annotation'; import { toDate } from 'date-fns'; import { mergeDeepAll } from '../../../helpers/merge-deep'; import { ChartDataLabelOptions, ChartDataset, ChartHighlightedElements, ChartLocale, ChartType, isNumberArray, } from '../chart.types'; import { ChartConfigService } from '../configs/chart-config.service'; import { Chart } from './configured-chart-js'; const CHART_LOCALE_DEFAULT = 'en-US'; @Injectable() export class ChartJSService { private chart: Chart; private dataLabelOptions: ChartDataLabelOptions; private highlightedElements: ChartHighlightedElements; private chartType: ChartType; private locale: ChartLocale; constructor(private chartConfigService: ChartConfigService) {} public renderChart(args: { targetElement: ElementRef<HTMLCanvasElement>; type: ChartType; data: ChartDataset[] | number[]; dataLabels?: string[] | string[][]; customOptions?: ChartOptions; annotations?: AnnotationOptions[]; dataLabelOptions?: ChartDataLabelOptions; highlightedElements?: ChartHighlightedElements; }): void { const { targetElement, type, data, dataLabels, customOptions, annotations, dataLabelOptions, highlightedElements, } = args; this.dataLabelOptions = dataLabelOptions || null; this.highlightedElements = highlightedElements || null; this.chartType = type; this.locale = dataLabelOptions?.locale || CHART_LOCALE_DEFAULT; const datasets = this.createDatasets(data); const options = this.createOptionsObject({ customOptions, annotations, dataLabelOptions, }); let config = this.createConfigurationObject(type, datasets, options, dataLabels); this.initializeNewChart(targetElement.nativeElement, config); } public redrawChart() { this.chart.update(); } public updateData(data: ChartDataset[] | number[]): void { const datasets = this.createDatasets(data); this.chart.data.datasets = datasets; } public updateDataLabels(dataLabels: string[] | string[][]) { this.chart.data.labels = dataLabels; } public updateType(type: ChartType, customOptions?: ChartOptions) { if (type === 'bar' || type === 'column') { /* indexAxis does not update predictably; update by replacing the chart entirely instead */ this.destructivelyUpdateType(type, customOptions); } else { this.nonDestructivelyUpdateType(type, customOptions); } } public setDataLabelOptions(dataLabelOptions: ChartDataLabelOptions) { this.dataLabelOptions = dataLabelOptions; } public updateOptions(customOptions: ChartOptions, type: ChartType) { const annotations = this.getExistingChartAnnotations(); this.chartType = type; this.chart.options = this.createOptionsObject({ customOptions, annotations }); } public updateAnnotations(annotations: AnnotationOptions[]) { const annotationsWithDefaults = this.applyDefaultsToAnnotations(annotations); this.chart.options.plugins.annotation.annotations = annotationsWithDefaults; } public updateHighlightedElements(highlightedElements?: ChartHighlightedElements) { this.highlightedElements = highlightedElements; const oldDatasets = this.chart.data.datasets as ChartDataset[]; // Clear old datasets of highlighted elements oldDatasets.map((dataset) => { if (dataset?.kirbyOptions?.highlightedElements) { delete dataset.kirbyOptions.highlightedElements; } }); this.chart.data.datasets = this.createDatasets(oldDatasets); } private getExistingChartAnnotations(): AnnotationOptions[] { const annotations = this.chart.options.plugins?.annotation?.annotations; /* In browser chart.js might return annotations as a Proxy object; force it to be an array. Each annotationOption in the resulting array will also be a Proxy object. But internally chart.js will just work with them as normal values */ if (annotations !== undefined) { return Object.keys(annotations).map((key) => annotations[key]); } else { return []; } } private destructivelyUpdateType(type: ChartType, customOptions?: ChartOptions) { const datasets = this.chart.data.datasets as ChartDataset[]; const dataLabels = this.chart.data.labels; const annotations = this.getExistingChartAnnotations(); this.chartType = type; const options = this.createOptionsObject({ customOptions, annotations }); const config = this.createConfigurationObject(type, datasets, options, dataLabels); const canvasElement = this.chart.canvas; this.chart.destroy(); this.initializeNewChart(canvasElement, config); } private nonDestructivelyUpdateType(chartType: ChartType, customOptions?: ChartOptions) { const annotations = this.getExistingChartAnnotations(); this.chartType = chartType; const options = this.createOptionsObject({ customOptions, annotations, }); this.chart.options = options; this.chart.config.type = this.chartConfigService.chartTypeToChartJSType(chartType); } private initializeNewChart(canvasElement: HTMLCanvasElement, config: ChartConfiguration) { this.chart = new Chart(canvasElement, config); } private createBlankLabels(datasets: ChartDataset[]): string[] { const largestDataset = datasets.reduce((previousDataset, currentDataset) => previousDataset.data.length > currentDataset.data.length ? previousDataset : currentDataset ); return Array(largestDataset.data.length).fill(''); } private applyDefaultsToAnnotations(annotations: AnnotationOptions[]) { return annotations.map((annotation) => { const annotationTypeDefaults = this.chartConfigService.getAnnotationDefaults(annotation.type); return mergeDeepAll(annotationTypeDefaults, annotation); }); } private createAnnotationPluginOptionsObject(annotations: AnnotationOptions[]) { const annotationsWithDefaults = this.applyDefaultsToAnnotations(annotations); return { plugins: { annotation: { annotations: annotationsWithDefaults, }, }, }; } private applyInteractionFunctionsExtensions(options: ChartOptions): ChartOptions { const interactionFunctionsExtensions = this.chartConfigService.getInteractionFunctionsExtensions(); Object.entries(interactionFunctionsExtensions).forEach(([key, _]) => { const callback = options[key]; options[key] = (e: Event, a: ActiveElement[], c: Chart) => { interactionFunctionsExtensions[key](e, a, c, callback); }; }); return options; } private createStockOptionsObject(dataLabelOptions: ChartDataLabelOptions) { return { locale: this.locale, plugins: { tooltip: { callbacks: { title: (tooltipItems) => { const date = toDate((tooltipItems[0]?.raw as any)?.x); if (date.valueOf()) { return date.toLocaleTimeString(this.locale, { day: 'numeric', month: 'short', hour: '2-digit', minute: '2-digit', }); } }, label: (context) => { // It's not possible to add spacing between color legend and text so we // prefix with a space. return ' ' + context.formattedValue + (dataLabelOptions.valueSuffix || ''); }, }, }, }, scales: { y: { ticks: { callback: (value) => { return value + (dataLabelOptions.valueSuffix || ''); }, }, }, }, }; } private createOptionsObject(args: { customOptions?: ChartOptions; annotations?: AnnotationOptions[]; dataLabelOptions?: ChartDataLabelOptions; }): ChartOptions { const { customOptions, annotations, dataLabelOptions: chartDataLabelOptions } = args; const typeConfig = this.chartConfigService.getTypeConfig(this.chartType); const typeConfigOptions = typeConfig?.options; const annotationPluginOptions = annotations ? this.createAnnotationPluginOptionsObject(annotations) : {}; const stockOptions: ChartOptions = this.chartType === 'stock' ? this.createStockOptionsObject(chartDataLabelOptions) : {}; let options: ChartOptions = mergeDeepAll( stockOptions, typeConfigOptions, customOptions, annotationPluginOptions ); return this.applyInteractionFunctionsExtensions(options); } private getDefaultStockLabels(datasets: ChartDataset[], locale: ChartLocale) { const largestDataset = datasets.reduce((previousDataset, currentDataset) => previousDataset.data.length > currentDataset.data.length ? previousDataset : currentDataset ); return largestDataset.data.map((point: ScatterDataPoint) => toDate(point.x).toLocaleDateString(locale, { month: 'short', day: 'numeric', }) ); } private createConfigurationObject( type: ChartType, datasets: ChartDataset[], options: ChartOptions, dataLabels?: unknown[] ): ChartConfiguration { const typeConfig = this.chartConfigService.getTypeConfig(type); // chartJS requires labels; if none is provided create an empty string array // to make it optional for consumer. // However the stock chart, should have autogenerated labels if no // custom labels are supplied. const isStockType = type === 'stock'; const labels = !dataLabels ? isStockType ? this.getDefaultStockLabels(datasets, this.locale) : this.createBlankLabels(datasets) : dataLabels; return mergeDeepAll(typeConfig, { data: { labels, datasets, }, options, }) as ChartConfiguration; } private addHighlightedElementsToDatasets( highlightedElements: ChartHighlightedElements, datasets: ChartDataset[] ) { highlightedElements.forEach(([datasetIndex, dataIndex]) => { const dataset = datasets[datasetIndex]; if (!dataset) return; if (dataset?.kirbyOptions?.highlightedElements) { dataset.kirbyOptions.highlightedElements.push(dataIndex); } else { dataset.kirbyOptions = { ...dataset.kirbyOptions, highlightedElements: [dataIndex], }; } }); } private createDatasets(data: ChartDataset[] | number[]): ChartDataset[] { // We need to modify the datasets in order to add datalabels. if ( this.dataLabelOptions?.showCurrent || this.dataLabelOptions?.showMax || this.dataLabelOptions?.showMin ) { data = this.addDataLabelsData(data); } let datasets = isNumberArray(data) ? [{ data }] : data; if (this.highlightedElements) this.addHighlightedElementsToDatasets(this.highlightedElements, datasets); return datasets; } /** * Decorate ChartDataset with properties to allow for datalabels. * * @param data * @returns ChartDataset[] */ public addDataLabelsData(data: ChartDataset[] | number[]): ChartDataset[] { if (isNumberArray(data)) { throw Error("Currently it's impossible to add dataLabels to non ScatterDataPoint datasets"); } const decorateDataPoint = ( set: ChartDataset, axis: 'x' | 'y', direction: 'high' | 'low', position: 'bottom' | 'top' | 'left' | 'right' ): void => { const { value, pointer } = this.locateValueIndexInDataset(set, axis, direction); set.data[pointer] = { ...(set.data[pointer] as ScatterDataPoint), datalabel: { value: value + (this.dataLabelOptions.valueSuffix || ''), position, }, } as ScatterDataPoint; }; data.map((set) => { if (this.dataLabelOptions.showMin) { decorateDataPoint(set, 'y', 'low', 'bottom'); } if (this.dataLabelOptions.showMax) { decorateDataPoint(set, 'y', 'high', 'top'); } if (this.dataLabelOptions.showCurrent) { decorateDataPoint(set, 'x', 'high', 'right'); } }); return data; } private locateValueIndexInDataset( dataset: ChartDataset, axis: string, direction: 'low' | 'high' ): { value: number; pointer: number } { let pointer: number; let value: number; dataset.data.forEach((datapoint, index) => { if (direction == 'low' && (!value || datapoint[axis] < value)) { value = datapoint['y']; pointer = index; } if (direction == 'high' && (!value || datapoint[axis] > value)) { value = datapoint['y']; pointer = index; } }); return { value, pointer }; } }
the_stack
import { LoggerService } from '@app/services/logger/logger.service'; import { DefaultScanWorkerJobInfo } from '@app/default-scan/default-scan-worker/default-scan-worker-job-info.interface'; import { DepClient } from '@app/default-scan/dep-clients/common/dep-client.interface'; import { GolangService } from '@app/default-scan/dep-clients/golang/golang.service'; import { MavenService } from '@app/default-scan/dep-clients/maven/maven.service'; import { NpmService } from '@app/default-scan/dep-clients/npm/npm.service'; import { NugetService } from '@app/default-scan/dep-clients/nuget/nuget.service'; import { Python3PipService } from '@app/default-scan/dep-clients/python/python3-pip.service'; import { Scanner } from '@app/default-scan/scanners/common/scanner.interface'; import { DependencyCheckService } from '@app/default-scan/scanners/dependency-check/dependency-check.service'; import { GoLicensesService } from '@app/default-scan/scanners/go-licenses/go-licenses.service'; import { LicenseCheckerService } from '@app/default-scan/scanners/license-checker/license-checker.service'; import { LicenseMavenService } from '@app/default-scan/scanners/license-maven/license-maven.service'; import { LicenseNugetService } from '@app/default-scan/scanners/license-nuget/license-nuget.service'; import { NvdCheckService } from '@app/default-scan/scanners/nvd-check/nvd-check.service'; import { Python3PipLicensesService } from '@app/default-scan/scanners/pip-licenses/python3-pip-licenses.service'; import { ScanCodeService } from '@app/default-scan/scanners/scan-code/scan-code.service'; import { PackageManager, Scan } from '@app/models'; import { PackageManagerEnum } from '@app/models/PackageManager'; import { ProjectAttribution } from '@app/models/ProjectAttribution'; import { ProjectAttributionService } from '@app/services/project-attribution/project-attribution.service'; import { ProjectService } from '@app/services/project/project.service'; import { ScanLogService } from '@app/services/scan-log/scan-log.service'; import { ScanService } from '@app/services/scan/scan.service'; import { fetchBinaryFromUrl } from '@app/shared/util/fetch-binary-from-url'; import { shellExecuteSync } from '@app/shared/util/shell-execute'; import { unarchiveFile } from '@app/shared/util/unarchive-file'; import { forwardRef, Inject, Injectable, Logger } from '@nestjs/common'; import { DoneCallback, Job } from 'bull'; import * as fs from 'fs'; import * as _ from 'lodash'; import * as path from 'path'; import { join } from 'path'; import simpleGit, { SimpleGit } from 'simple-git'; import * as tmp from 'tmp'; import * as url from 'url'; import { Processor, Process } from '@nestjs/bull'; @Injectable() export class DefaultScanWorkerService { private dataDir = tmp.dirSync({ unsafeCleanup: true }); private doneCallback: DoneCallback; private git: SimpleGit = simpleGit(); private job: Job; private jobInfo: DefaultScanWorkerJobInfo; private logger = new LoggerService('DefaultScanWorkerService'); private scanners: Scanner[]; private tmpDir = tmp.dirSync({ unsafeCleanup: true }); constructor( private readonly projectAttributionService: ProjectAttributionService, private readonly projectService: ProjectService, private readonly scanService: ScanService, private readonly scanLogService: ScanLogService, @Inject(forwardRef(() => ScanCodeService)) private readonly scanCodeService: ScanCodeService, @Inject(forwardRef(() => LicenseCheckerService)) private readonly licenseCheckerService: LicenseCheckerService, @Inject(forwardRef(() => LicenseMavenService)) private readonly licenseMavenService: LicenseMavenService, @Inject(forwardRef(() => LicenseNugetService)) private readonly licenseNugetService: LicenseNugetService, @Inject(forwardRef(() => DependencyCheckService)) private readonly dependencyCheckService: DependencyCheckService, @Inject(forwardRef(() => NvdCheckService)) private readonly nvdCheckService: NvdCheckService, private readonly golangService: GolangService, private readonly mavenService: MavenService, private readonly npmService: NpmService, private readonly nugetService: NugetService, private readonly python3Service: Python3PipService, private readonly python3PipLicensesService: Python3PipLicensesService, private readonly goLicenseService: GoLicensesService, ) {} cleanup(info: DefaultScanWorkerJobInfo, error: Error = null, resolve, reject) { try { if (process.env.NODE_ENV) { if (process.env.NODE_ENV.toLowerCase() === 'production') { this.logger.debug( `*** [process.env.NODE_ENV === ${process.env.NODE_ENV}] Deleting temporary scan directories.`, ); this.tmpDir.removeCallback(); this.dataDir.removeCallback(); } else { this.logger.debug( `*** [process.env.NODE_ENV === ${process.env.NODE_ENV}] NOT Deleting temporary scan directories.`, ); } } this.job.progress(100); this.doneCallback(error, { info }); if (error) { this.logger.error(error.toLocaleString()); reject(error); } else { resolve(); } } catch (e) { this.logger.error(e.toLocaleString()); reject(e); } } // Helper Metods depClient(packageManager: PackageManager, workingDirectory: string): DepClient { let client: DepClient; switch (packageManager.code) { case 'golang-modules': { client = this.golangService; break; } case 'maven': { client = this.mavenService; break; } case 'npm': { client = this.npmService; break; } case 'nuget': { client = this.nugetService; break; } case 'python3-pip': { client = this.python3Service; break; } case 'python2_7-pip': { client = this.python3Service; client.packageManagerCode = PackageManagerEnum.PYTHON2_7_PIP; break; } default: { client = null; break; } } return client; } async fetchDependencies(scan: Scan, depClient: DepClient, jobInfo: DefaultScanWorkerJobInfo) { const project = scan.project; let workingDirectory = jobInfo.tmpDir; if (depClient) { const options: any = {}; options.scan = scan; if (project.customPackageManagerPath) { options.customPackageManagerPath = project.customPackageManagerPath; if (project.packageManager.code != PackageManagerEnum.GO.toString()) { workingDirectory = join(jobInfo.tmpDir, project.customPackageManagerPath); } } if (project.customPackageManagerFilename) { options.customPackageManagerFilename = project.customPackageManagerFilename; } else if (project.packageManager.code === PackageManagerEnum.NUGET.toString()) { // If this is a nuget project, let's look for a solution file in the root of the repo if one does not exist. // Let's check for a .sln file since the user did not specify one const slnFiles = fs.readdirSync(workingDirectory).filter((fn) => fn.endsWith('.sln')); if (slnFiles && slnFiles.length > 0) { // If we did find a solution file in the working directory, let's go ahead and take the first one we find // Nuget throws an error if there is more than one and we don't specify which to use. options.customPackageManagerFilename = slnFiles[0]; } } options.useMavenCustomSettings = !this.isGitHubCom(scan.project.gitUrl); this.logger.log('userMavenCustom = ' + options.useMavenCustomSettings); return depClient.fetchDependencies(workingDirectory, options, jobInfo.dataDir); } else { this.logger.log('No package manager configured, not fetching dependencies.'); return Promise.resolve(); } } isGitHubCom(gitUrl: string) { const urlParts = url.parse(gitUrl); return urlParts.hostname.toLowerCase() === 'github.com'; } replaceGitHubPassword(gitUrl: string) { const url = new URL(gitUrl); if (url.password) { return gitUrl.replace(url.password, '*******'); } else { return gitUrl; } } replaceGitHubPasswordInString(content: string, gitUrl: string) { const url = new URL(gitUrl); if (url.password) { return content.replace(url.username + ':' + url.password, url.username + ':*******'); } else { return content; } } deleteFolderRecursive(filePath, ignorePath) { if (ignorePath.replace(/\/+$/, '') === filePath.replace(/\/+$/, '')) { return; } if (fs.existsSync(filePath)) { fs.readdirSync(filePath).forEach((file, index) => { const curPath = path.join(filePath, file); if (fs.lstatSync(curPath).isDirectory()) { // recurse this.deleteFolderRecursive(curPath, ignorePath); } else { // delete file fs.unlinkSync(curPath); } }); } } async scan(job: Job<any>, callback: DoneCallback) { return new Promise<void>(async (resolve, reject) => { this.jobInfo = {}; this.jobInfo.errors = []; this.job = job; this.doneCallback = callback; // Create the Scan with that project const scan: Scan = await this.scanService.db .createQueryBuilder('scan') .leftJoinAndSelect('scan.project', 'project') .leftJoinAndSelect('project.packageManager', 'packageManager') .leftJoinAndSelect('project.developmentType', 'developmentType') .leftJoinAndSelect('scan.deploymentType', 'deploymentType') .whereInIds(job.data.scanId) .getOne(); try { this.jobInfo.appDir = path.resolve(__dirname, '../../../src'); this.jobInfo.tmpDir = this.tmpDir.name; this.jobInfo.dataDir = this.dataDir.name; this.jobInfo.scanId = scan.id; this.jobInfo.projectName = scan.project.name; this.job.progress(5); this.logger.fileTransport(this.jobInfo.dataDir + '/output.txt'); this.logger.scanId = this.jobInfo.scanId; this.logger.log(`this.jobInfo: ${JSON.stringify(this.jobInfo, null, 2)}`); this.logger.log('datadir = ' + this.jobInfo.dataDir); // Let's apply any security credentials we might have for the project const gitUrl = await this.projectService.gitUrlAuthForProject(scan.project); const doScanProcess = async (isSourceCode: boolean = true) => { let progress = 10; this.job.progress(progress); shellExecuteSync('pwd', { cwd: this.jobInfo.tmpDir }, this.jobInfo.dataDir); scan.startedAt = new Date(); await scan.save(); const scannerPromises = []; const scanners = []; // If the project has a gitUrl then let's do a real scan of the source code if (isSourceCode) { const depClient = this.depClient(scan.project.packageManager, this.jobInfo.tmpDir); await this.fetchDependencies(scan, depClient, this.jobInfo); scanners.push(this.dependencyCheckService); if (depClient) { // Let's decide which license services to user based on the package manager. switch (depClient.packageManagerCode) { case PackageManagerEnum.GO: { scanners.push(this.goLicenseService); break; } case PackageManagerEnum.MAVEN: { scanners.push(this.licenseMavenService); break; } case PackageManagerEnum.NPM: { scanners.push(this.licenseCheckerService); break; } case PackageManagerEnum.NUGET: { scanners.push(this.licenseNugetService); break; } case PackageManagerEnum.PYTHON3_PIP: { scanners.push(this.python3PipLicensesService); break; } default: { // If we have a package manager of 'non', let's just scan using scan code even though it's slower scanners.push(this.scanCodeService); break; } } } else { // If we don'thave a package manager, let's just scan using scan code even though it's slower scanners.push(this.scanCodeService); } } else { // If the project does not have a gitUrl then let's just check the NVD scanners.push(this.nvdCheckService); } for (const scanner of scanners) { scannerPromises.push( new Promise<void>(async (scanPromiseResolve) => { this.logger.log(`Starting ${scanner.name}`); await scanner.execute(this.jobInfo); // TODO: Make this report a more accurate progress potentially with a callback within the scanner to capture steps progress = progress + 10; this.job.progress(progress); this.logger.log(`Finished ${scanner.name}`); scanPromiseResolve(); }), ); } await Promise.all(scannerPromises); await scan.reload(); scan.completedAt = new Date(); await scan.save(); this.logger.log('Updating Attributions'); try { const licenseAttribtions = await this.scanService.distinctLicenseAttributions(scan.id); const projectAttribution = new ProjectAttribution(); projectAttribution.attribution = ''; projectAttribution.project = scan.project; licenseAttribtions.forEach((license) => { projectAttribution.attribution += 'Package: '; projectAttribution.attribution += license.packageName + '\n\n'; projectAttribution.attribution += 'License: '; projectAttribution.attribution += license.clearDefined ? license.clearDefined.license !== 'OTHER' ? license.clearDefined.license : license.license : license.license; projectAttribution.attribution += '\n\n'; projectAttribution.attribution += 'Copyrights: \n'; projectAttribution.attribution += license.clearDefined?.copyrights ? license.clearDefined.copyrights : ''; projectAttribution.attribution += '\n\n'; projectAttribution.attribution += 'License Text: \n'; projectAttribution.attribution += license.clearDefined?.licensetext ? license.clearDefined.licensetext !== 'OTHER' ? license.clearDefined.licensetext : license.licenselink : license.licenselink; projectAttribution.attribution += '\n\n'; projectAttribution.attribution += '-------------------------------------------------------------------------------------------------------------------------------'; projectAttribution.attribution += '\n\n'; }); await this.projectAttributionService.insertAttribution(projectAttribution); } catch (error) { this.logger.error(error); } try { await this.scanService.sendMailOnScanCompletion(scan); } catch (error) { this.logger.error(error); } const scanLog = this.scanLogService.db.create(); scanLog.scan = scan; scanLog.log = fs.readFileSync(this.jobInfo.dataDir + '/output.txt').toString(); await scanLog.save(); this.cleanup(this.jobInfo, null, resolve, reject); }; if (!_.isEmpty(scan.project.pathToUploadFileForScanning)) { this.logger.log('Fetching pathToUploadFileForScanning'); const archiveFilename = await fetchBinaryFromUrl( scan.project.pathToUploadFileForScanning, this.jobInfo.tmpDir, ); await unarchiveFile(path.join(this.jobInfo.tmpDir, archiveFilename), this.jobInfo.tmpDir); await doScanProcess(); } else if (!_.isEmpty(gitUrl)) { this.logger.log('Cloning Git Repository = ' + this.replaceGitHubPassword(gitUrl)); const gitBranch = scan.tag; const gitOptions = []; if (gitBranch) { this.logger.log('Branch = ' + gitBranch); gitOptions.push('--branch'); gitOptions.push(gitBranch); } else { this.logger.log('Branch = default branch'); gitOptions.push('--depth'); gitOptions.push('1'); } scan.startedAt = new Date(); await scan.save(); try { await this.git.clone(gitUrl, this.jobInfo.tmpDir, gitOptions); if ( scan.project.customPackageManagerPath && scan.project.packageManager.code != PackageManagerEnum.GO.toString() ) { this.deleteFolderRecursive( this.jobInfo.tmpDir, path.join(this.jobInfo.tmpDir, scan.project.customPackageManagerPath), ); } await doScanProcess(); } catch (cloneError) { await this.logger.error(`Clone Error: ${this.replaceGitHubPasswordInString(cloneError, gitUrl)}`); await scan.reload(); scan.completedAt = new Date(); await scan.save(); const scanLog = this.scanLogService.db.create(); scanLog.scan = scan; scanLog.log = fs.readFileSync(this.jobInfo.dataDir + '/output.txt').toString(); await scanLog.save(); this.cleanup(this.jobInfo, null, resolve, reject); try { await this.scanService.sendMailOnScanCompletion(scan); } catch (error) { this.logger.error(error); } } } else { this.logger.log('No pathToUploadFileForScanning and no gitURL, so isSourceCode = false'); await doScanProcess(false); } } catch (error) { this.logger.error('ScanProcess Error' + error); scan.completedAt = new Date(); await scan.save(); const scanLog = this.scanLogService.db.create(); scanLog.scan = scan; scanLog.log = fs.readFileSync(this.jobInfo.dataDir + '/output.txt').toString(); await scanLog.save(); this.cleanup(this.jobInfo, error, resolve, reject); } }); } }
the_stack
import * as Atom from "atom" import * as ACP from "atom/autocomplete-plus" import * as fuzzaldrin from "fuzzaldrin" import { CompletionEntryDetails, CompletionEntryIdentifier, CompletionsTriggerCharacter, } from "typescript/lib/protocol" import {GetClientFunction, TSClient} from "../../client" import {handlePromise} from "../../utils" import {ApplyEdits} from "../pluginManager" import {codeActionTemplate} from "./codeActionTemplate" import {FileLocationQuery, spanToRange, typeScriptScopes} from "./utils" import {selectListView} from "./views/simpleSelectionView" type SuggestionWithDetails = ACP.TextSuggestion & { replacementRange?: Atom.Range isMemberCompletion?: boolean identifier?: CompletionEntryIdentifier | string hasAction?: boolean } interface Details { details: CompletionEntryDetails rightLabel: string description?: string } export class AutocompleteProvider implements ACP.AutocompleteProvider { public selector = typeScriptScopes() .map((x) => (x.includes(".") ? `.${x}` : x)) .join(", ") public inclusionPriority = atom.config.get("atom-typescript").autocompletionInclusionPriority public suggestionPriority = atom.config.get("atom-typescript").autocompletionSuggestionPriority public excludeLowerPriority = atom.config.get("atom-typescript").autocompletionExcludeLowerPriority private lastSuggestions?: { // Client used to get the suggestions client: TSClient // File and position for the suggestions location: FileLocationQuery // Prefix used prefix: string // The completions that were returned for the position suggestions: SuggestionWithDetails[] details: Map<string, Details> } constructor(private getClient: GetClientFunction, private applyEdits: ApplyEdits) {} public async getSuggestions(opts: ACP.SuggestionsRequestedEvent): Promise<ACP.AnySuggestion[]> { const location = getLocationQuery(opts) const prefix = getPrefix(opts) if (!location) return [] // Don't auto-show autocomplete if prefix is empty unless last character is '.' const triggerCharacter = getTrigger( getLastNonWhitespaceChar(opts.editor.getBuffer(), opts.bufferPosition), ) if (!prefix && !opts.activatedManually && !triggerCharacter) return [] // Don't show autocomplete if we're in a string.template and not in a template expression if ( containsScope(opts.scopeDescriptor.getScopesArray(), "string.template.") && !containsScope(opts.scopeDescriptor.getScopesArray(), "template.expression.") ) { return [] } try { let suggestions = await this.getSuggestionsWithCache({ prefix, location, triggerCharacter, activatedManually: opts.activatedManually, }) const config = atom.config.get("atom-typescript") if (config.autocompletionUseFuzzyFilter) { suggestions = fuzzaldrin.filter(suggestions, prefix, { key: "displayText", }) } else { const ignoreCase = config.autocompletionStrictFilterIgnoreCase const longestFirst = config.autocompletionStrictFilterLongestMatchFirst const score = ignoreCase ? (text: string) => { const pos = text.toLowerCase().indexOf(prefix.toLowerCase()) const length = text.length * (longestFirst ? -1 : 1) const exact = text.includes(prefix) && prefix.toLowerCase() !== prefix ? -10000 : 0 return 100 * pos + exact + length } : (text: string) => { const pos = text.indexOf(prefix) const length = text.length * (longestFirst ? -1 : 1) return 100 * pos + length } const filter = ignoreCase ? (val: {displayText?: string}) => val.displayText?.toLowerCase().includes(prefix.toLowerCase()) : (val: {displayText?: string}) => val.displayText?.includes(prefix) suggestions = suggestions .filter(filter) .sort((a, b) => score(a.displayText!) - score(b.displayText!)) } return suggestions.map((suggestion) => ({ replacementPrefix: suggestion.replacementRange ? opts.editor.getTextInBufferRange(suggestion.replacementRange) : prefix, location, ...this.getDetailsFromCache(suggestion), ...addCallableParens(opts, suggestion), })) } catch (error) { return [] } } public async getSuggestionDetailsOnSelect(suggestion: ACP.AnySuggestion) { if ("text" in suggestion && !("rightLabel" in suggestion)) { return this.getAdditionalDetails(suggestion) } else { return null } } public onDidInsertSuggestion(evt: ACP.SuggestionInsertedEvent) { const s = evt.suggestion as SuggestionWithDetails if (!s.hasAction) return if (!this.lastSuggestions) return const client = this.lastSuggestions.client let details = this.getDetailsFromCache(s) handlePromise( (async () => { if (!details) details = await this.getAdditionalDetails(s) if (!details?.details.codeActions) return let action if (details.details.codeActions.length === 1) { action = details.details.codeActions[0] } else { action = await selectListView({ items: details.details.codeActions, itemTemplate: codeActionTemplate, itemFilterKey: "description", }) } if (!action) return await this.applyEdits(action.changes) if (!action.commands) return await Promise.all( action.commands.map((cmd) => client.execute("applyCodeActionCommand", { command: cmd, }), ), ) })(), ) } private async getAdditionalDetails(suggestion: SuggestionWithDetails) { if (suggestion.identifier === undefined) return null if (!this.lastSuggestions) return null const reply = await this.lastSuggestions.client.execute("completionEntryDetails", { entryNames: [suggestion.identifier], ...this.lastSuggestions.location, }) if (!reply.body) return null const [details] = reply.body // apparently, details can be undefined // tslint:disable-next-line: strict-boolean-expressions if (!details) return null let parts = details.displayParts if ( parts.length >= 3 && parts[0].text === "(" && parts[1].text === suggestion.leftLabel && parts[2].text === ")" ) { parts = parts.slice(3) } let rightLabel = parts.map((d) => d.text).join("") const actionDesc = suggestion.hasAction && details.codeActions?.length === 1 ? `${details.codeActions[0].description}\n\n` : "" if (actionDesc) rightLabel = actionDesc const description = actionDesc + details.displayParts.map((d) => d.text).join("") + (details.documentation ? "\n\n" + details.documentation.map((d) => d.text).join(" ") : "") this.lastSuggestions.details.set(suggestion.displayText!, {details, rightLabel, description}) return { ...suggestion, details, rightLabel, description, } } private getDetailsFromCache(suggestion: SuggestionWithDetails) { if (!this.lastSuggestions) return null const d = this.lastSuggestions.details.get(suggestion.displayText!) if (!d) return null return d } // Try to reuse the last completions we got from tsserver if they're for the same position. private async getSuggestionsWithCache({ prefix, location, triggerCharacter, activatedManually, }: { prefix: string location: FileLocationQuery triggerCharacter?: CompletionsTriggerCharacter activatedManually: boolean }): Promise<SuggestionWithDetails[]> { if (this.lastSuggestions && !activatedManually) { const lastLoc = this.lastSuggestions.location const lastCol = getNormalizedCol(this.lastSuggestions.prefix, lastLoc.offset) const thisCol = getNormalizedCol(prefix, location.offset) if (lastLoc.file === location.file && lastLoc.line === location.line && lastCol === thisCol) { if (this.lastSuggestions.suggestions.length !== 0) { return this.lastSuggestions.suggestions } } } const client = await this.getClient(location.file) const suggestions = await getSuggestionsInternal({ client, location, triggerCharacter: activatedManually ? undefined : triggerCharacter, }) this.lastSuggestions = { client, location, prefix, suggestions, details: new Map(), } return suggestions } } async function getSuggestionsInternal({ client, location, triggerCharacter, }: { client: TSClient location: FileLocationQuery triggerCharacter?: CompletionsTriggerCharacter }) { if (parseInt(client.version.split(".")[0], 10) >= 3) { // use completionInfo const completions = await client.execute("completionInfo", { includeExternalModuleExports: false, includeInsertTextCompletions: true, triggerCharacter, ...location, }) return completions.body!.entries.map( completionEntryToSuggestion.bind(null, completions.body?.isMemberCompletion), ) } else { // use deprecated completions const completions = await client.execute("completions", { includeExternalModuleExports: false, includeInsertTextCompletions: true, ...location, }) return completions.body!.map(completionEntryToSuggestion.bind(null, undefined)) } } // this should more or less match ES6 specification for valid identifiers const identifierMatch = /(?:(?![\u{10000}-\u{10FFFF}])[\$_\p{Lu}\p{Ll}\p{Lt}\p{Lm}\p{Lo}\p{Nl}])(?:(?![\u{10000}-\u{10FFFF}])[\$_\p{Lu}\p{Ll}\p{Lt}\p{Lm}\p{Lo}\p{Nl}\u200C\u200D\p{Mn}\p{Mc}\p{Nd}\p{Pc}])*$/u // Decide what needs to be replaced in the editor buffer when inserting the completion function getPrefix(opts: ACP.SuggestionsRequestedEvent): string { // see https://github.com/TypeStrong/atom-typescript/issues/1528 // for the motivating example. const line = opts.editor .getBuffer() .getTextInRange([[opts.bufferPosition.row, 0], opts.bufferPosition]) const idMatch = line.match(identifierMatch) if (idMatch) return idMatch[0] else return "" } // When the user types each character in ".hello", we want to normalize the column such that it's // the same for every invocation of the getSuggestions. In this case, it would be right after "." function getNormalizedCol(prefix: string, col: number): number { const length = prefix === "." ? 0 : prefix.length return col - length } function getLocationQuery(opts: ACP.SuggestionsRequestedEvent): FileLocationQuery | undefined { const path = opts.editor.getPath() if (path === undefined) { return undefined } return { file: path, line: opts.bufferPosition.row + 1, offset: opts.bufferPosition.column + 1, } } function getLastNonWhitespaceChar(buffer: Atom.TextBuffer, pos: Atom.Point): string | undefined { let lastChar: string | undefined const range = new Atom.Range([0, 0], pos) buffer.backwardsScanInRange( /\S/, range, ({matchText, stop}: {matchText: string; stop: () => void}) => { lastChar = matchText stop() }, ) return lastChar } function containsScope(scopes: ReadonlyArray<string>, matchScope: string): boolean { for (const scope of scopes) { if (scope.includes(matchScope)) { return true } } return false } function completionEntryToSuggestion( isMemberCompletion: boolean | undefined, entry: protocol.CompletionEntry, ): SuggestionWithDetails { return { displayText: entry.name, text: entry.insertText !== undefined ? entry.insertText : entry.name, leftLabel: entry.kind, replacementRange: entry.replacementSpan ? spanToRange(entry.replacementSpan) : undefined, type: kindMap[entry.kind], isMemberCompletion, identifier: entry.source !== undefined ? {name: entry.name, source: entry.source} : entry.name, hasAction: entry.hasAction, } } function parens(opts: ACP.SuggestionsRequestedEvent) { const buffer = opts.editor.getBuffer() const pt = opts.bufferPosition const lookahead = buffer.getTextInRange([pt, [pt.row, buffer.lineLengthForRow(pt.row)]]) return !!lookahead.match(/\s*\(/) } function addCallableParens( opts: ACP.SuggestionsRequestedEvent, s: SuggestionWithDetails, ): ACP.TextSuggestion | ACP.SnippetSuggestion { if ( atom.config.get("atom-typescript.autocompleteParens") && ["function", "method"].includes(s.leftLabel!) && !parens(opts) ) { return {...s, snippet: `${s.text}($1)`, text: undefined} } else return s } /** From : * https://github.com/atom-community/autocomplete-plus/pull/334#issuecomment-85697409 */ type ACPCompletionType = | "variable" | "constant" | "property" | "value" | "method" | "function" | "class" | "type" | "keyword" | "tag" | "import" | "require" | "snippet" const kindMap: {[key in protocol.ScriptElementKind]: ACPCompletionType | undefined} = { directory: "require", module: "import", "external module name": "import", class: "class", "local class": "class", method: "method", property: "property", getter: "property", setter: "property", "JSX attribute": "property", constructor: "method", enum: "type", interface: "type", type: "type", "type parameter": "type", "primitive type": "type", function: "function", "local function": "function", label: "variable", alias: "import", var: "variable", let: "variable", "local var": "variable", parameter: "variable", "enum member": "constant", const: "constant", string: "value", keyword: "keyword", "": undefined, warning: undefined, script: undefined, call: undefined, index: undefined, construct: undefined, } // This may look strange, but it guarantees the list is consistent with the type const triggerCharactersMap: {[K in CompletionsTriggerCharacter]: null} = { ".": null, '"': null, "'": null, "`": null, "/": null, "@": null, "<": null, "#": null, } const triggerCharacters = new Set<CompletionsTriggerCharacter>(Object.keys(triggerCharactersMap)) function getTrigger(prefix: string | undefined): CompletionsTriggerCharacter | undefined { if (prefix === undefined) return undefined if (!prefix) return undefined const c = prefix.slice(-1) if (triggerCharacters.has(c as CompletionsTriggerCharacter)) { return c as CompletionsTriggerCharacter } return undefined }
the_stack
import {ZiGateMessageCode} from "./constants"; export interface ZiGateMessageParameter { name: string; parameterType: string; options?: object; } export interface ZiGateMessageType { response: ZiGateMessageParameter[]; } export const ZiGateMessage: { [k: number]: ZiGateMessageType } = { [ZiGateMessageCode.GetTimeServer]: { response: [ {name: 'timestampUTC', parameterType: 'UINT32'}, // <Timestamp UTC: uint32_t> from 2000-01-01 00:00:00 ] }, [ZiGateMessageCode.DeviceAnnounce]: { response: [ {name: 'shortAddress', parameterType: 'UINT16BE'}, {name: 'ieee', parameterType: 'IEEEADDR'}, {name: 'MACcapability', parameterType: 'MACCAPABILITY'}, // MAC capability // Bit 0 – Alternate PAN Coordinator // Bit 1 – Device Type // Bit 2 – Power source // Bit 3 – Receiver On when Idle // Bit 4,5 – Reserved // Bit 6 – Security capability // Bit 7 – Allocate Address // {name: 'rejoin', parameterType: 'UINT8'}, ] }, [ZiGateMessageCode.Status]: { response: [ {name: 'status', parameterType: 'UINT8'}, // <status:uint8_t> // 0 = Success // 1 = Incorrect parameters // 2 = Unhandled command // 3 = Command failed // eslint-disable-next-line max-len // 4 = Busy (Node is carrying out a lengthy operation and is currently unable to handle the incoming command) // 5 = Stack already started (no new configuration accepted) // 128 – 244 = Failed (ZigBee event codes) // Packet Type: The value of the initiating command request. {name: 'sequence', parameterType: 'UINT8'}, // <sequence number: uint8_t> {name: 'packetType', parameterType: 'UINT16BE'}, // <Packet Type: uint16_t> // from 3.1d // {name: 'requestSent', parameterType: 'MAYBE_UINT8'},// <requestSent: uint8_t> - 1 if a request been sent to // // a device(aps ack/nack 8011 should be expected) , 0 otherwise // {name: 'seqApsNum', parameterType: 'MAYBE_UINT8'},// <seqApsNum: uint8_t> - sqn of the APS layer - used to // // check sqn sent back in aps ack // // // from 3.1e // {name: 'PDUM_u8GetNpduUse', parameterType: 'MAYBE_UINT8'}, // {name: 'u8GetApduUse', parameterType: 'MAYBE_UINT8'}, // // // debug 3.1e++ // {name: 'PDUM_u8GetMaxNpduUse', parameterType: 'MAYBE_UINT8'}, // {name: 'u8GetMaxApduUse', parameterType: 'MAYBE_UINT8'}, ] }, [ZiGateMessageCode.PermitJoinStatus]: { response: [ {name: 'status', parameterType: 'UINT8'}, // <status:uint8_t> ] }, [ZiGateMessageCode.DataIndication]: { response: [ {name: 'status', parameterType: 'UINT8'}, // <status: uint8_t> {name: 'profileID', parameterType: 'UINT16BE'}, // <Profile ID: uint16_t> {name: 'clusterID', parameterType: 'UINT16BE'}, // <cluster ID: uint16_t> {name: 'sourceEndpoint', parameterType: 'UINT8'}, // <source endpoint: uint8_t> {name: 'destinationEndpoint', parameterType: 'UINT8'}, // <destination endpoint: uint8_t> {name: 'sourceAddressMode', parameterType: 'UINT8'}, // <source address mode: uint8_t> {name: 'sourceAddress', parameterType: 'ADDRESS_WITH_TYPE_DEPENDENCY'}, // <source address: uint16_t or uint64_t> {name: 'destinationAddressMode', parameterType: 'UINT8'}, // <destination address mode: uint8_t> {name: 'destinationAddress', parameterType: 'ADDRESS_WITH_TYPE_DEPENDENCY'}, // <destination address: uint16_t or uint64_t> // {name: 'payloadSize', parameterType:'UINT8'}, // <payload size : uint8_t> {name: 'payload', parameterType: 'BUFFER_RAW'}, // <payload : data each element is // uint8_t> ] }, [ZiGateMessageCode.NodeClusterList]: { response: [ {name: 'sourceEndpoint', parameterType: 'UINT8'}, //<source endpoint: uint8_t t> {name: 'profileID', parameterType: 'UINT16'}, // <profile ID: uint16_t> {name: 'clusterCount', parameterType: 'UINT8'}, {name: 'clusterList', parameterType: 'LIST_UINT16'}, // <cluster list: data each entry is uint16_t> ] }, [ZiGateMessageCode.NodeAttributeList]: { response: [ {name: 'sourceEndpoint', parameterType: 'UINT8'}, //<source endpoint: uint8_t t> {name: 'profileID', parameterType: 'UINT16'}, // <profile ID: uint16_t> {name: 'clusterID', parameterType: 'UINT16'}, // <cluster ID: uint16_t> {name: 'attributeCount', parameterType: 'UINT8'}, {name: 'attributeList', parameterType: 'LIST_UINT16'}, // <attribute list: data each entry is uint16_t> ] }, [ZiGateMessageCode.NodeCommandIDList]: { response: [ {name: 'sourceEndpoint', parameterType: 'UINT8'}, //<source endpoint: uint8_t t> {name: 'profileID', parameterType: 'UINT16'}, // <profile ID: uint16_t> {name: 'clusterID', parameterType: 'UINT16'}, // <cluster ID: uint16_t> {name: 'commandIDCount', parameterType: 'UINT8'}, {name: 'commandIDList', parameterType: 'LIST_UINT8'}, // <command ID list:data each entry is uint8_t> ] }, [ZiGateMessageCode.APSDataACK]: { response: [ {name: 'status', parameterType: 'UINT8'}, // <status: uint8_t> // {name: 'sourceEndpoint', parameterType:'UINT8'}, // <source endpoint: uint8_t> // {name: 'destinationAddressMode', parameterType:'UINT8'}, // // <destination address mode: uint8_t> {name: 'destinationAddress', parameterType: 'UINT16BE'}, {name: 'destinationEndpoint', parameterType: 'UINT8'}, // <destination endpoint: uint8_t> {name: 'clusterID', parameterType: 'UINT16BE'}, // // <destination address: uint16_t or uint64_t> {name: 'seqNumber', parameterType: 'UINT8'}, // <seq number: uint8_t> ] }, [ZiGateMessageCode.APSDataConfirm]: { response: [ {name: 'status', parameterType: 'UINT8'}, // <status: uint8_t> {name: 'sourceEndpoint', parameterType: 'UINT8'}, // <source endpoint: uint8_t> {name: 'destinationAddressMode', parameterType: 'UINT8'}, {name: 'destinationAddressMode', parameterType: 'UINT8'}, // <destination address mode: uint8_t> {name: 'destinationAddress', parameterType: 'ADDRESS_WITH_TYPE_DEPENDENCY'}, // <destination address: uint16_t or uint64_t> {name: 'seqNumber', parameterType: 'UINT8'}, // <seq number: uint8_t> // from 3.1e {name: 'PDUM_u8GetNpduUse', parameterType: 'MAYBE_UINT8'}, {name: 'u8GetApduUse', parameterType: 'MAYBE_UINT8'}, ] }, [ZiGateMessageCode.APSDataConfirmFailed]: { response: [ {name: 'status', parameterType: 'UINT8'}, // <status: uint8_t> {name: 'sourceEndpoint', parameterType: 'UINT8'}, // <src endpoint: uint8_t> {name: 'destinationEndpoint', parameterType: 'UINT8'}, // <dst endpoint: uint8_t> {name: 'destinationAddressMode', parameterType: 'UINT8'}, // <dst address mode: uint8_t> {name: 'destinationAddress', parameterType: 'ADDRESS_WITH_TYPE_DEPENDENCY'}, // <destination address: uint64_t> {name: 'seqNumber', parameterType: 'UINT8'}, // <seq number: uint8_t> // from 3.1e {name: 'PDUM_u8GetNpduUse', parameterType: 'MAYBE_UINT8'}, {name: 'u8GetApduUse', parameterType: 'MAYBE_UINT8'}, ] }, [ZiGateMessageCode.NetworkState]: { response: [ {name: 'shortAddress', parameterType: 'UINT16BE'}, // <Short Address: uint16_t> {name: 'extendedAddress', parameterType: 'IEEEADDR'}, // <Extended Address: uint64_t> {name: 'PANID', parameterType: 'UINT16BE'}, // <PAN ID: uint16_t> {name: 'ExtPANID', parameterType: 'IEEEADDR'}, // <Ext PAN ID: uint64_t> {name: 'Channel', parameterType: 'UINT8'}, // <Channel: uint8_t> ] }, [ZiGateMessageCode.VersionList]: { response: [ {name: 'major', parameterType: 'UINT8'}, {name: 'minor', parameterType: 'UINT8'}, {name: 'revision', parameterType: 'UINT16'}, ] }, [ZiGateMessageCode.NetworkJoined]: { response: [ {name: 'status', parameterType: 'UINT8'}, // <status: uint8_t> // Status: // 0 = Joined existing network // 1 = Formed new network // 128 – 244 = Failed (ZigBee event codes) {name: 'shortAddress', parameterType: 'UINT16BE'}, // <short address: uint16_t> // {name: 'extendedAddress', parameterType: 'IEEEADDR'}, // <extended address:uint64_t> // {name: 'channel', parameterType: 'UINT8'}, // <channel: uint8_t> ] }, [ZiGateMessageCode.LeaveIndication]: { response: [ {name: 'extendedAddress', parameterType: 'IEEEADDR'}, // <extended address: uint64_t> {name: 'rejoin', parameterType: 'UINT8'}, // <rejoin status: uint8_t> ] }, [ZiGateMessageCode.ManagementLeaveResponse]: { response: [ {name: 'sqn', parameterType: 'UINT8'}, {name: 'status', parameterType: 'UINT8'}, // <status: uint8_t> ] }, [ZiGateMessageCode.RouterDiscoveryConfirm]: { response: [ {name: 'status', parameterType: 'UINT8'}, // <status: uint8_t> // {name: 'nwkStatus', parameterType: 'UINT8'}, // <nwk status: uint8_t> // {name: 'dstAddress', parameterType: 'UINT16BE'}, // <nwk status: uint16_t> ] }, [ZiGateMessageCode.SimpleDescriptorResponse]: { response: [ {name: 'sourceEndpoint', parameterType: 'UINT8'}, //<source endpoint: uint8_t> {name: 'profile ID', parameterType: 'UINT16BE'}, // <profile ID: uint16_t> {name: 'clusterID', parameterType: 'UINT16BE'}, // <cluster ID: uint16_t> {name: 'attributeList', parameterType: 'LIST_UINT16BE'}, // <attribute list: data each entry is uint16_t> ] }, [ZiGateMessageCode.ManagementLQIResponse]: { response: [ {name: 'sequence', parameterType: 'UINT8'}, // <Sequence number: uint8_t> {name: 'status', parameterType: 'UINT8'}, // <status: uint8_t> {name: 'neighbourTableEntries', parameterType: 'UINT8'}, // <Neighbour Table Entries : uint8_t> {name: 'neighbourTableListCount', parameterType: 'UINT8'}, // <Neighbour Table List Count : uint8_t> {name: 'startIndex', parameterType: 'UINT8'}, // <Start Index : uint8_t> // @TODO list TYPE // <List of Entries elements described below :> // Note: If Neighbour Table list count is 0, there are no elements in the list. {name: 'NWKAddress', parameterType: 'UINT16BE'}, // NWK Address : uint16_t {name: 'Extended PAN ID', parameterType: 'UINT64'}, // Extended PAN ID : uint64_t {name: 'IEEE Address', parameterType: 'IEEEADR'}, // IEEE Address : uint64_t {name: 'Depth', parameterType: 'UINT8'}, // Depth : uint_t {name: 'linkQuality', parameterType: 'UINT8'}, // Link Quality : uint8_t {name: 'bitMap', parameterType: 'UINT8'}, // Bit map of attributes Described below: uint8_t // bit 0-1 Device Type // (0-Coordinator 1-Router 2-End Device) // bit 2-3 Permit Join status // (1- On 0-Off) // bit 4-5 Relationship // (0-Parent 1-Child 2-Sibling) // bit 6-7 Rx On When Idle status // (1-On 0-Off) {name: 'srcAddress', parameterType: 'UINT16BE'}, // <Src Address : uint16_t> ( only from v3.1a) ] }, [ZiGateMessageCode.PDMEvent]: { response: [ {name: 'eventStatus', parameterType: 'UINT8'}, // <event status: uint8_t> {name: 'recordID', parameterType: 'UINT32BE'}, // <record ID: uint32_t> ] }, [ZiGateMessageCode.PDMLoaded]: { response: [ {name: 'length', parameterType: 'UINT8'}, ] }, [ZiGateMessageCode.RestartNonFactoryNew]: { // Non “Factory new” Restart response: [ {name: 'status', parameterType: 'UINT8'}, // <status: uint8_t> // 0 – STARTUP // 1 – RUNNING // 2 – NFN_START ] }, [ZiGateMessageCode.RestartFactoryNew]: { // “Factory New” Restart response: [ {name: 'status', parameterType: 'UINT8'}, // <status: uint8_t> // 0 – STARTUP // 2 – NFN_START // 6 – RUNNING // The node is not yet provisioned. ] }, [ZiGateMessageCode.ExtendedStatusCallBack]: { response: [ {name: 'status', parameterType: 'UINT8'}, // https://github.com/fairecasoimeme/ZiGate/blob/aac14153db332eb5b898cba0f57f5999e5cf11eb/Module%20Radio/Firmware/src/sdk/JN-SW-4170/Components/ZPSNWK/Include/zps_nwk_pub.h#L89 ] }, [0x8001]: { response: [ {name: 'logLevel', parameterType: 'LOG_LEVEL'}, {name: 'log', parameterType: 'STRING'}, ] }, [ZiGateMessageCode.AddGroupResponse]: { response: [ {name: 'status', parameterType: 'UINT16BE'}, {name: 'groupAddress', parameterType: 'UINT16BE'}, ] } };
the_stack
/// <reference types="node" /> import { EventEmitter } from 'events'; import { PNG } from 'pngjs'; declare namespace ATEM { /** 0-indexed, so ME1 = 0, ..., ME4 = 3 */ type MixEffect = 0 | 1 | 2 | 3; /** * - 0: Black * - 1-40: Physical SDI/HDMI inputs * - 1000: Color Bars (test pattern) * - 2001: Color 1 * - 2002: Color 2 * - 3010: Media Player 1 * - 3011: Media Player 1 Key * - 3020: Media Player 2 * - 3021: Media Player 2 Key * - 4010: Key 1 Mask * - 4020: Key 2 Mask * - 4030: Key 3 Mask * - 4040: Key 4 Mask * - 5010: DSK 1 Mask * - 5020: DSK 2 Mask * - 6000: Supersource * - 7001: Clean Feed 1 * - 7002: Clean Feed 2 * - 8001-8006: Aux 1-6 * - 11001: Camera 1 direct * - 10010: ME1 Program * - 10011: ME1 Preview * - 10020: ME2 Program * - 10021: ME2 Preview * - 10030: ME3 Program * - 10031: ME3 Preview * - 10040: ME4 Program * - 10041: ME4 Preview */ type VisionChannelNumber = number; /** * - 1-20: Audio channels 1-20 * - 1101: AES/EBU * - 1201: RCA * - 2001: Media Player 1 * - 2002: Media Player 2 */ type AudioChannelNumber = number; /** * - 1-6: Aux Output 1-6 */ type AuxChannelNumber = number; interface VisionChannel { name: string; label: string; } interface AudioChannel { leftLevel: number; rightLevel: number; /** whether the channel is ON (as opposed to AFV) */ on: boolean; /** whether audio-follows-video is enabled */ afv: boolean; gain: number; rawGain: number; rawPan: number; } /** the current state of a Mix Effect */ interface MixEffectState { /** the currently selected transition style */ transitionStyle: TransitionStyle; /** whether the next transition will fade the BKGD */ upstreamKeyNextBackground: boolean; /** the number of USKs */ numberOfKeyers: number; /** whether the next transition will fade the USKs */ upstreamKeyNextState: { [_: number]: boolean; }; /** the current state (active/inactive) of each USK */ upstreamKeyState: { [_: number]: boolean; }; /** whether FTB is currently active */ fadeToBlack?: boolean; /** current position of the T-bar */ transitionPosition: number; /** whether PREV TRANS is active */ transitionPreview: boolean; /** the current input being sent to the preview bus */ previewInput: VisionChannelNumber; /** the current input being sent to the pgram bus */ programInput: VisionChannelNumber; /** the current transition speed, in frames */ transitionFrameCount: number; } /** the current state of the vision mixer */ interface State { topology: { numberOfMEs: number | null; numberOfSources: number | null; numberOfColorGenerators: number | null; numberOfAUXs: number | null; numberOfDownstreamKeys: number | null; numberOfStingers: number | null; numberOfDVEs: number | null; numberOfSuperSources: number | null; }; tallys: { [tallyNumber: number]: TallyState; }; channels: { [channelNumber: number]: VisionChannel; }; video: { ME: { [meNumber: number]: MixEffectState; }; downstreamKeyOn: { [dskNumber: number]: boolean; }; downstreamKeyTie: { [dskNumber: number]: boolean; }; auxs: { [channelNumber: number]: AuxChannelNumber; }; }; audio: { /** whether the mixer has a physical 3.5mm jack for monitoring audio */ hasMonitor: boolean | null; numberOfChannels: number | null; channels: { [channelNumber: number]: AudioChannel; }; master?: AudioChannel; }; /** a number representing the vision mixer model */ model: number; /** a string representing the vision mixer model */ _pin: string; } interface Options { /** set forceOldStyle if you upgraded this library from from `0.1.x`. state returns extract 1ME stats. */ forceOldStyle?: boolean; /** a random port will be used if not specified */ localPort?: number; } class FileUploader { constructor(atem: ATEM); uploadFromPNGFile(path: string): void; uploadFromPNGBuffer(pngBuffer: Buffer, bankIndex?: number, frameIndex?: number): PNG; convertPNGToYUV422(width: number, height: number, data: number[]): Buffer; } enum Model { TVS = 0x01, '1ME' = 0x02, '2ME' = 0x03, PS4K = 0x04, '1ME4K' = 0x05, '2ME4K' = 0x06, '2MEBS4K' = 0x07, } enum TransitionStyle { MIX = 0x00, DIP = 0x01, WIPE = 0x02, DVE = 0x03, STING = 0x04, } enum TallyState { None = 0x00, Program = 0x01, Preview = 0x02, // TODO: 3 is also a valid option } enum ConnectionState { None = 0x00, SynSent = 0x01, Established = 0x02, Closed = 0x03, } enum PacketFlag { Sync = 0x01, Connect = 0x02, Repeat = 0x04, Error = 0x08, Ack = 0x16, } } declare class ATEM { constructor(options?: ATEM.Options); /** * @param address - the IP address or hostname * @param port - optional: the port, if a custom one is used. Defaults to 9910 * @param localPort - optional: a custom local port */ connect(address: string, port?: number, localPort?: number): void; /** the current state of the vision mixer */ state: ATEM.State; connectionState: ATEM.ConnectionState; localPackedId: number; sessionId: number[]; remotePacketId: number[]; event: EventEmitter; // // switching // /** Route the specified input channel to the program bus for that Mix Effect (the LIVE output) */ changeProgramInput(channel: ATEM.VisionChannelNumber, me?: ATEM.MixEffect): void; /** Route the specified input channel to the preview bus for that Mix Effect */ changePreviewInput(channel: ATEM.VisionChannelNumber, me?: ATEM.MixEffect): void; /** Changes the input channel that routes to the specified aux bus */ changeAuxInput(aux: number, input: ATEM.VisionChannelNumber): void; /** equivilant of pressing AUTO on the mixer */ autoTransition(me?: ATEM.MixEffect): void; /** equivilant of pressing CUT on the mixer */ cutTransition(me?: ATEM.MixEffect): void; /** equivilant of pressing FTB on the mixer */ fadeToBlack(me?: ATEM.MixEffect): void; // // transitions // /** equivilant to moving the T-bar on the mixer */ changeTransitionPosition(position: number, me?: ATEM.MixEffect): void; /** equivilant of pressing PREV TRNS on the mixer */ changeTransitionPreview(me?: ATEM.MixEffect): void; changeTransitionType(type: ATEM.TransitionStyle, me?: ATEM.MixEffect): void; // // USK // /** equivilant of pressing ON AIR on the mixer (for that USK) */ changeUpstreamKeyState(uskNum: number, onAir: boolean, me?: ATEM.MixEffect): void; /** if true: the next transition will fade the BKGD */ changeUpstreamKeyNextBackground(nextTransFadesBkgd: boolean, me?: ATEM.MixEffect): void; /** if true: the next transition will fade this USK */ changeUpstreamKeyNextState(uskNum: number, nextTransFadesUSK: boolean, me?: ATEM.MixEffect): void; // // DSK // /** equivilant of pressing ON AIR on the mixer (for that DSK) */ changeDownstreamKeyOn(dskNum: number, onAir: boolean): void; /** equivilant of pressing TIE on the mixer */ changeDownstreamKeyTie(dskNum: number, tie: boolean): void; /** fades in the DSK */ autoDownstreamKey(dskNum: number): void; // // audio // changeAudioMasterGain(gain: number): void; changeAudioChannelGain(channel: ATEM.AudioChannelNumber, gain: number): void; changeAudioChannelState(channel: ATEM.AudioChannelNumber, status: boolean): void; sendAudioLevelNumber(enable?: boolean): void; // // macros // startRecordMacro(macroId: number, name?: string, description?: string): void; stopRecordMacro(): void; runMacro(macroId: number): void; deleteMacro(macroId: number): void; // // Media Player // lockMediaPool(bankIndex: number, frameIndex: number): void; unlockMediaPool(bankIndex: number): void; /** @deprecated use `ATEM.FileUploader` */ fileSendNotice(id: [unknown, unknown], bankIndex: number, frameIndex: number, size: number, mode?: number): void; /** @deprecated use `ATEM.FileUploader` */ sendFileData(id: [unknown, unknown], buffer: Buffer): void; /** @deprecated use `ATEM.FileUploader` */ sendFileDescription(id: [unknown, unknown], name: string, hash: Buffer): void; // // event listeners // on: { /** called when a state packet is received from the ATEM */ (event: 'stateChanged', callback: (error?: Error, state?: ATEM.State) => void): void; /** called when a ping packet is received from the ATEM at an interval of one second */ (event: 'ping', callback: () => void): void; /** called when the first ping packet is received from the ATEM. */ (event: 'connect', callback: (error: null) => void): void; /** called when we detect that we cannot communicate to the ATEM within `RECONNECT_INTERVAL` seconds */ (event: 'disconnect', callback: (error: null, state: null) => void): void; }; once: ATEM['on']; } export = ATEM;
the_stack
import startsWith from 'lodash/startsWith'; import { getDocument } from '../../utils'; import { AjaxInterface, AjaxOptions, RequestHeaders, SetupOptions, } from '../../types/request'; import { isFormData, toQueryString, urlAppend } from './utils'; import { CONTENT_TYPE, HTTP_REG, PROTOCO_REG, READY_STATE, REQUESTED_WITH, TWO_HUNDO, XML_HTTP_REQUEST, X_DOMAIN_REQUEST, } from './constants'; import globalSetup from './setup'; class Ajax implements AjaxInterface { private options: AjaxOptions; private headNode?: HTMLHeadElement; private request?: XMLHttpRequest; private isAborted: boolean = false; private isTimeout: boolean = false; private timeout?: NodeJS.Timeout; private callbackData?: any; private callbackPrefix: string = 'request_' + new Date(); private uuid: number = 0; private promise?: Promise<any>; private __resolve?: (value: unknown) => void; private __reject?: (reason?: any) => void; /** * 设置全局选项 * @param options 选项 */ static setup = (options: SetupOptions) => { Object.keys(options).forEach((key) => { if (globalSetup[key]) globalSetup[key] = options[key]; }); }; constructor(options: AjaxOptions | string) { if (typeof options === 'string') { options = { url: options, }; } let { url } = options; if (startsWith(url, '//')) { url = window.location.protocol + url; } this.options = { ...globalSetup, ...options, url, context: options.context || window, doc: options.doc || getDocument(), jsonpCallback: options.jsonpCallback || 'callback', method: options.method || 'GET', }; this.headNode = this.options.doc?.getElementsByTagName('head')[0]; this.initPromise(); this.init(); } initPromise() { this.promise = new Promise((resolve, reject) => { this.__resolve = resolve; this.__reject = reject; }).catch(() => {}); } init() { const timedOut = () => { this.isTimeout = true; this.request?.abort(); }; if (this.timeout) { clearTimeout(this.timeout); } this.timeout = undefined; if (this.options.timeout) { this.timeout = setTimeout(timedOut, this.options.timeout); } const error = (errorMsg: string, request?: XMLHttpRequest) => { this.triggerError(errorMsg, request); }; const success = (request: XMLHttpRequest) => { this.triggerSuccess(request); }; this.getRequest(success, error).then((res) => { this.request = res; }); } abort() { this.request?.abort(); } defaultXHR() { const { context, crossOrigin } = this.options; if (!context) return; // is it x-domain if (crossOrigin === true) { const xhrInstance = context[XML_HTTP_REQUEST] ? new context[XML_HTTP_REQUEST]() : null; if (xhrInstance && 'withCredentials' in xhrInstance) { return xhrInstance; } if (context[X_DOMAIN_REQUEST]) { return new context[X_DOMAIN_REQUEST](); } throw new Error('Browser does not support cross-origin requests'); } else if (context[XML_HTTP_REQUEST]) { return new context[XML_HTTP_REQUEST](); } else { return new context.ActiveXObject('Microsoft.XMLHTTP'); } } succeed() { const { url, context } = this.options; const protocol = PROTOCO_REG.exec(url); let protocolValue = protocol ? protocol[1] : ''; if (!protocolValue) { protocolValue = context?.location.protocol || ''; } return HTTP_REG.test(protocolValue) ? TWO_HUNDO.test(this.request?.status?.toString() || '') : !!this.request?.response; } noop() {} handleReadyState( success: (request?: XMLHttpRequest) => void, error: (statusText: string, request?: XMLHttpRequest) => void, ) { // use _aborted to mitigate against IE err c00c023f // (can't read props on aborted request objects) if (this.isAborted) { return error('Request is aborted', this.request); } if (this.isTimeout) { return error('Request is aborted: timeout', this.request); } if (this.request && this.request[READY_STATE] === 4) { this.request.onreadystatechange = this.noop; if (this.succeed()) { success(this.request); } else { error(this.request.statusText, this.request); } } } setHeaders(request: XMLHttpRequest, headers: Record<string, string>) { headers.Accept = headers.Accept || globalSetup.accept[this.options.type || '*']; // breaks cross-origin requests with legacy browsers if (!this.options.crossOrigin && !headers[REQUESTED_WITH]) { headers[REQUESTED_WITH] = globalSetup.requestedWith; } if (!headers[CONTENT_TYPE] && !isFormData(this.options.data)) { headers[CONTENT_TYPE] = this.options.contentType || globalSetup.contentType; } Object.keys(headers).forEach((name) => { request.setRequestHeader(name, headers[name]); }); } setCredentials(request: XMLHttpRequest) { if ( typeof this.options.withCredentials !== 'undefined' && typeof request.withCredentials !== 'undefined' ) { request.withCredentials = !!this.options.withCredentials; } } generalCallback(data: any) { this.callbackData = data; } getCallbackPrefix(id: string | number) { return this.callbackPrefix + '_' + id; } handleJsonp( url: string, success: (data: any) => void, error: (errorMsg: string) => void, ): XMLHttpRequest | undefined { const { jsonpCallback, jsonpCallbackName, doc, context } = this.options; if (!doc || !context) return; const requestId = this.uuid++; const cbkey = jsonpCallback || 'callback'; // the 'callback' key let cbval = jsonpCallbackName || this.getCallbackPrefix(requestId); const cbreg = new RegExp('((^|\\?|&)' + cbkey + ')=([^&]+)'); const match = url.match(cbreg); const script = doc.createElement('script'); let loaded = 0; const isIE10 = navigator.userAgent.indexOf('MSIE 10.0') !== -1; if (match) { if (match[3] === '?') { url = url.replace(cbreg, '$1=' + cbval); // wildcard callback func name } else { cbval = match[3]; // provided callback func name } } else { url = urlAppend(url, cbkey + '=' + cbval); // no callback details, add 'em } context[cbval] = this.generalCallback; script.type = 'text/javascript'; script.src = url; script.async = true; if (typeof script['onreadystatechange'] !== 'undefined' && !isIE10) { // need this for IE due to out-of-order onreadystatechange(), binding script // execution to an event listener gives us control over when the script // is executed. See http://jaubourg.net/2010/07/loading-script-as-onclick-handler-of.html script.htmlFor = script.id = '_request_' + requestId; } script.onload = script['onreadystatechange'] = () => { if ( (script[READY_STATE] && script[READY_STATE] !== 'complete' && script[READY_STATE] !== 'loaded') || loaded ) { return false; } script.onload = script['onreadystatechange'] = null; if (script.onclick) { (script as any).onclick(); } // Call the user callback with the last value stored and clean up values and scripts. success(this.callbackData); this.callbackData = undefined; this.headNode?.removeChild(script); loaded = 1; return true; }; // Add the script to the DOM head this.headNode?.appendChild(script); // Enable JSONP timeout return { abort: () => { script.onload = script['onreadystatechange'] = null; error('Request is aborted: timeout'); this.callbackData = undefined; this.headNode?.removeChild(script); loaded = 1; }, } as XMLHttpRequest; } async getRequest( success: (data: any) => void, error: (errorMsg: string, request?: XMLHttpRequest) => void, ): Promise<XMLHttpRequest | undefined> { const method = this.options.method?.toUpperCase() || 'GET'; // convert non-string objects to query-string form unless o.processData is false const { processData, traditional, type, context, xhr, async, before } = this.options; if (!context) return Promise.resolve(undefined); let { url } = this.options; let data: any = this.options.data; // get data if (typeof data === 'function') { data = await data(); } if ( (this.options.contentType?.indexOf('json') || -1) > -1 && typeof data === 'object' ) { data = JSON.stringify(data); } data = processData !== false && data && typeof data !== 'string' && !isFormData(data) ? toQueryString(data, traditional || globalSetup.traditional) : data || null; let http: XMLHttpRequest | undefined = undefined; let sendWait = false; // if we're working on a GET request and we have data then we should append // query string to end of URL and not post data if ((type === 'jsonp' || method === 'GET') && data) { url = urlAppend(url, data); data = null; } if (type === 'jsonp') { return Promise.resolve(this.handleJsonp(url, success, error)); } // get headers let headers: RequestHeaders = this.options.headers || {}; if (typeof headers === 'function') { headers = await headers(); } // get the xhr from the factory if passed // if the factory returns null, fall-back to ours http = (typeof xhr === 'function' ? xhr(this.options) : xhr) || this.defaultXHR(); if (!http) return; http.open(method, url, async === false ? false : true); this.setHeaders(http, headers); this.setCredentials(http); if ( context[X_DOMAIN_REQUEST] && http instanceof context[X_DOMAIN_REQUEST] ) { http.onload = success; http.onerror = function () { error('http error', http); }; // NOTE: see // http://social.msdn.microsoft.com/Forums/en-US-US/iewebdevelopment/thread/30ef3add-767c-4436-b8a9-f1ca19b4812e http.onprogress = this.noop; sendWait = true; } else { http.onreadystatechange = () => { this.handleReadyState(success, error); }; } if (before) { before(http); } if (sendWait) { setTimeout(() => { http?.send(data); }, 200); } else { http.send(data); } return Promise.resolve(http); } getType(type?: string | null) { // json, javascript, text/plain, text/html, xml if (!type) { return undefined; } if (type.match('json')) { return 'json'; } if (type.match('javascript')) { return 'js'; } if (type.match('text')) { return 'html'; } if (type.match('xml')) { return 'xml'; } return undefined; } triggerSuccess(request: XMLHttpRequest) { const { dataFilter, context, success } = this.options; if (!context) return; let { type } = this.options; // use global data filter on response text const data = (dataFilter || globalSetup.dataFilter)( request.responseText, type, ); if (!type) { type = request && this.getType(request.getResponseHeader('Content-Type')); } // resp can be undefined in IE let response: any = type !== 'jsonp' ? this.request : request; try { response['responseText'] = data; } catch (e) { // can't assign this in IE<=8, just ignore } if (data) { switch (type) { case 'json': try { response = context.JSON.parse(data); } catch (err) { return this.triggerError( 'Could not parse JSON in response', response, ); } break; case 'html': response = data; break; case 'xml': response = response.responseXML && response.responseXML.parseError && response.responseXML.parseError.errorCode && response.responseXML.parseError.reason ? null : response.responseXML; break; default: break; } } if (success) { success(response); } this.triggerComplete(response); if (this.__resolve) this.__resolve(response); } triggerError(errorMsg: string, request?: XMLHttpRequest) { const { error } = this.options; const e = new Error(errorMsg); e['xhr'] = request; if (error) { error(e); } this.triggerComplete(e); if (this.__reject) this.__reject(e); } triggerComplete(request: XMLHttpRequest | Error) { const { complete } = this.options; if (this.timeout) { clearTimeout(this.timeout); } this.timeout = undefined; if (complete) { complete(request); } } retry() { this.initPromise(); this.init(); } then(success: (data: any) => void, fail?: (reason?: any) => void) { return this.promise?.then(success, fail); } always(fn: (data: any) => void) { return this.promise?.then(fn, fn); } fail(fn: (reason?: any) => void) { return this.promise?.then(undefined, fn); } catch(fn: (reason?: any) => void) { return this.fail(fn); } } export default Ajax;
the_stack
import ez = require("TypeScript/ez") import EZ_TEST = require("./TestFramework") export class TestQuat extends ez.TypescriptComponent { /* BEGIN AUTO-GENERATED: VARIABLES */ /* END AUTO-GENERATED: VARIABLES */ constructor() { super() } static RegisterMessageHandlers() { ez.TypescriptComponent.RegisterMessageHandler(ez.MsgGenericEvent, "OnMsgGenericEvent"); } ExecuteTests(): void { // constructor { let q = new ez.Quat(); EZ_TEST.FLOAT(q.x, 0, 0.001); EZ_TEST.FLOAT(q.y, 0, 0.001); EZ_TEST.FLOAT(q.z, 0, 0.001); EZ_TEST.FLOAT(q.w, 1, 0.001); } // Clone / Normalize { let q = new ez.Quat(1, 2, 3, 4); EZ_TEST.BOOL(q.IsIdentical(new ez.Quat(1, 2, 3, 4))); q.Normalize(); EZ_TEST.QUAT(q.Clone(), q, 0.001); } // SetIdentity { let q = new ez.Quat(1, 2, 3, 4); q.SetIdentity(); EZ_TEST.QUAT(q, ez.Quat.IdentityQuaternion(), 0.001); } // IdentityQuaternion { let q = ez.Quat.IdentityQuaternion(); EZ_TEST.FLOAT(q.x, 0, 0.001); EZ_TEST.FLOAT(q.y, 0, 0.001); EZ_TEST.FLOAT(q.z, 0, 0.001); EZ_TEST.FLOAT(q.w, 1, 0.001); } // SetFromAxisAndAngle / RotateVec3 { { let q = new ez.Quat(); q.SetFromAxisAndAngle(new ez.Vec3(1, 0, 0), ez.Angle.DegreeToRadian(90)); let v = new ez.Vec3(0, 1, 0); q.RotateVec3(v); EZ_TEST.VEC3(v, new ez.Vec3(0, 0, 1), 0.0001); let v2 = new ez.Vec3(0, 1, 0); q.InvRotateVec3(v2); EZ_TEST.VEC3(v2, new ez.Vec3(0, 0, -1), 0.0001); } { let q = new ez.Quat(); q.SetFromAxisAndAngle(new ez.Vec3(0, 1, 0), ez.Angle.DegreeToRadian(90)); let v = new ez.Vec3(1, 0, 0); q.RotateVec3(v); EZ_TEST.VEC3(v, new ez.Vec3(0, 0, -1), 0.0001); let v2 = new ez.Vec3(1, 0, 0); q.InvRotateVec3(v2); EZ_TEST.VEC3(v2, new ez.Vec3(0, 0, 1), 0.0001); } { let q = new ez.Quat(); q.SetFromAxisAndAngle(new ez.Vec3(0, 0, 1), ez.Angle.DegreeToRadian(90)); let v = new ez.Vec3(0, 1, 0); q.RotateVec3(v); EZ_TEST.VEC3(v, new ez.Vec3(-1, 0, 0), 0.0001); let v2 = new ez.Vec3(0, 1, 0); q.InvRotateVec3(v2); EZ_TEST.VEC3(v2, new ez.Vec3(1, 0, 0), 0.0001); } } // SetQuat { let q = new ez.Quat(1, 2, 3, 4); let q2 = new ez.Quat(); q2.SetQuat(q); EZ_TEST.FLOAT(q2.x, 1, 0.001); EZ_TEST.FLOAT(q2.y, 2, 0.001); EZ_TEST.FLOAT(q2.z, 3, 0.001); EZ_TEST.FLOAT(q2.w, 4, 0.001); } // SetFromMat3 { let m = new ez.Mat3(); m.SetRotationMatrixZ(ez.Angle.DegreeToRadian(-90)); let q1 = new ez.Quat(); let q2 = new ez.Quat(); let q3 = new ez.Quat(); q1.SetFromMat3(m); q2.SetFromAxisAndAngle(new ez.Vec3(0, 0, -1), ez.Angle.DegreeToRadian(90)); q3.SetFromAxisAndAngle(new ez.Vec3(0, 0, 1), ez.Angle.DegreeToRadian(-90)); EZ_TEST.BOOL(q1.IsEqualRotation(q2, 0.001)); EZ_TEST.BOOL(q1.IsEqualRotation(q3, 0.001)); } // SetSlerp { let q1 = new ez.Quat(); let q2 = new ez.Quat(); let q3 = new ez.Quat(); let qr = new ez.Quat(); q1.SetFromAxisAndAngle(new ez.Vec3(0, 0, 1), ez.Angle.DegreeToRadian(45)); q2.SetFromAxisAndAngle(new ez.Vec3(0, 0, 1), ez.Angle.DegreeToRadian(0)); q3.SetFromAxisAndAngle(new ez.Vec3(0, 0, 1), ez.Angle.DegreeToRadian(90)); qr.SetSlerp(q2, q3, 0.5); EZ_TEST.QUAT(q1, qr, 0.0001); } // GetRotationAxisAndAngle { let q1 = new ez.Quat(); let q2 = new ez.Quat(); let q3 = new ez.Quat(); q1.SetShortestRotation(new ez.Vec3(0, 1, 0), new ez.Vec3(1, 0, 0)); q2.SetFromAxisAndAngle(new ez.Vec3(0, 0, -1), ez.Angle.DegreeToRadian(90)); q3.SetFromAxisAndAngle(new ez.Vec3(0, 0, 1), ez.Angle.DegreeToRadian(-90)); let res = q1.GetRotationAxisAndAngle(); EZ_TEST.VEC3(res.axis, new ez.Vec3(0, 0, -1), 0.001); EZ_TEST.FLOAT(ez.Angle.RadianToDegree(res.angleInRadian), 90, 0.001); res = q2.GetRotationAxisAndAngle(); EZ_TEST.VEC3(res.axis, new ez.Vec3(0, 0, -1), 0.001); EZ_TEST.FLOAT(ez.Angle.RadianToDegree(res.angleInRadian), 90, 0.001); res = q3.GetRotationAxisAndAngle(); EZ_TEST.VEC3(res.axis, new ez.Vec3(0, 0, -1), 0.001); EZ_TEST.FLOAT(ez.Angle.RadianToDegree(res.angleInRadian), 90, 0.001); res = ez.Quat.IdentityQuaternion().GetRotationAxisAndAngle(); EZ_TEST.VEC3(res.axis, new ez.Vec3(1, 0, 0), 0.001); EZ_TEST.FLOAT(ez.Angle.RadianToDegree(res.angleInRadian), 0, 0.001); let otherIdentity = new ez.Quat(0, 0, 0, -1); res = otherIdentity.GetRotationAxisAndAngle(); EZ_TEST.VEC3(res.axis, new ez.Vec3(1, 0, 0), 0.001); EZ_TEST.FLOAT(ez.Angle.RadianToDegree(res.angleInRadian), 360, 0.001); } // GetAsMat3 { let q = new ez.Quat(); q.SetFromAxisAndAngle(new ez.Vec3(0, 0, 1), ez.Angle.DegreeToRadian(90)); let mr = new ez.Mat3(); mr.SetRotationMatrixZ(ez.Angle.DegreeToRadian(90)); let m = q.GetAsMat3(); EZ_TEST.BOOL(mr.IsEqual(m, 0.001)); } // GetAsMat4 { let q = new ez.Quat(); q.SetFromAxisAndAngle(new ez.Vec3(0, 0, 1), ez.Angle.DegreeToRadian(90)); let mr = new ez.Mat4(); mr.SetRotationMatrixZ(ez.Angle.DegreeToRadian(90)); let m = q.GetAsMat4(); EZ_TEST.BOOL(mr.IsEqual(m, 0.001)); } // SetShortestRotation / IsEqualRotation { let q1 = new ez.Quat(); let q2 = new ez.Quat(); let q3 = new ez.Quat(); q1.SetShortestRotation(new ez.Vec3(0, 1, 0), new ez.Vec3(1, 0, 0)); q2.SetFromAxisAndAngle(new ez.Vec3(0, 0, -1), ez.Angle.DegreeToRadian(90)); q3.SetFromAxisAndAngle(new ez.Vec3(0, 0, 1), ez.Angle.DegreeToRadian(-90)); EZ_TEST.BOOL(q1.IsEqualRotation(q2, 0.001)); EZ_TEST.BOOL(q1.IsEqualRotation(q3, 0.001)); EZ_TEST.BOOL(ez.Quat.IdentityQuaternion().IsEqualRotation(ez.Quat.IdentityQuaternion(), 0.001)); EZ_TEST.BOOL(ez.Quat.IdentityQuaternion().IsEqualRotation(new ez.Quat(0, 0, 0, -1), 0.001)); } // SetConcatenatedRotations / ConcatenateRotations { let q1 = new ez.Quat(); let q2 = new ez.Quat(); let q3 = new ez.Quat(); let qr = new ez.Quat(); q1.SetFromAxisAndAngle(new ez.Vec3(0, 0, 1), ez.Angle.DegreeToRadian(60)); q2.SetFromAxisAndAngle(new ez.Vec3(0, 0, 1), ez.Angle.DegreeToRadian(30)); q3.SetFromAxisAndAngle(new ez.Vec3(0, 0, 1), ez.Angle.DegreeToRadian(90)); qr.SetConcatenatedRotations(q1, q2); EZ_TEST.BOOL(qr.IsEqualRotation(q3, 0.0001)); let qr2 = q1.Clone(); qr2.ConcatenateRotations(q2); EZ_TEST.QUAT(qr, qr2, 0.001); } // IsIdentical { let q1 = new ez.Quat(); let q2 = new ez.Quat(); q1.SetFromAxisAndAngle(new ez.Vec3(0, 0, 1), ez.Angle.DegreeToRadian(60)); q2.SetFromAxisAndAngle(new ez.Vec3(0, 0, 1), ez.Angle.DegreeToRadian(30)); EZ_TEST.BOOL(!q1.IsIdentical(q2)); q2.SetFromAxisAndAngle(new ez.Vec3(1, 0, 0), ez.Angle.DegreeToRadian(60)); EZ_TEST.BOOL(!q1.IsIdentical(q2)); q2.SetFromAxisAndAngle(new ez.Vec3(0, 0, 1), ez.Angle.DegreeToRadian(60)); EZ_TEST.BOOL(q1.IsIdentical(q2)); } // Negate / GetNegated { let q = new ez.Quat(); q.SetFromAxisAndAngle(new ez.Vec3(1, 0, 0), ez.Angle.DegreeToRadian(90)); let v = new ez.Vec3(0, 1, 0); q.RotateVec3(v); EZ_TEST.VEC3(v, new ez.Vec3(0, 0, 1), 0.0001); let n1 = q.GetNegated(); let n2 = q.Clone(); n2.Negate(); EZ_TEST.QUAT(n1, n2, 0.001); let v2 = new ez.Vec3(0, 1, 0); n1.RotateVec3(v2); EZ_TEST.VEC3(v2, new ez.Vec3(0, 0, -1), 0.0001); } // SetFromEulerAngles / GetAsEulerAngles { let q = new ez.Quat(); q.SetFromEulerAngles(ez.Angle.DegreeToRadian(90), 0, 0); let euler = q.GetAsEulerAngles(); EZ_TEST.FLOAT(euler.roll, ez.Angle.DegreeToRadian(90), 0.001); EZ_TEST.FLOAT(euler.pitch, ez.Angle.DegreeToRadian(0), 0.001); EZ_TEST.FLOAT(euler.yaw, ez.Angle.DegreeToRadian(0), 0.001); q.SetFromEulerAngles(0, ez.Angle.DegreeToRadian(90), 0); euler = q.GetAsEulerAngles(); EZ_TEST.FLOAT(euler.pitch, ez.Angle.DegreeToRadian(90), 0.001); // due to compilation differences, this the result for this computation can be very different (but equivalent) EZ_TEST.BOOL((ez.Utils.IsNumberEqual(euler.roll, ez.Angle.DegreeToRadian(180), 0.001) && ez.Utils.IsNumberEqual(euler.yaw, ez.Angle.DegreeToRadian(180), 0.001)) || (ez.Utils.IsNumberEqual(euler.roll, ez.Angle.DegreeToRadian(0), 0.001) && ez.Utils.IsNumberEqual(euler.yaw, ez.Angle.DegreeToRadian(0), 0.001))); q.SetFromEulerAngles(0, 0, ez.Angle.DegreeToRadian(90)); euler = q.GetAsEulerAngles(); EZ_TEST.FLOAT(euler.roll, ez.Angle.DegreeToRadian(0), 0.001); EZ_TEST.FLOAT(euler.pitch, ez.Angle.DegreeToRadian(0), 0.001); EZ_TEST.FLOAT(euler.yaw, ez.Angle.DegreeToRadian(90), 0.001); } } OnMsgGenericEvent(msg: ez.MsgGenericEvent): void { if (msg.Message == "TestQuat") { this.ExecuteTests(); msg.Message = "done"; } } }
the_stack
import { UpdateExpression as UpdateExpressionStr } from '../DocumentClient'; import ExpressionAttributeNames from './ExpressionAttributeNames'; import ExpressionAttributeValues from './ExpressionAttributeValues'; import UpdateValueExpression from './UpdateValueExpression'; // Docs: // https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.UpdateExpressions.html export type AddValue<T> = [T] extends [ // eslint-disable-next-line @typescript-eslint/no-explicit-any { type: string; values: any[] } | number | undefined, ] ? T : never; export type DeleteValue<T> = [T] extends [ // eslint-disable-next-line @typescript-eslint/no-explicit-any { type: string; values: any[] } | undefined, ] ? T : never; export type SetValue<T, V> = V | ((exp: UpdateValueExpression<T, V>) => string); export default class UpdateExpression<T> { private names: ExpressionAttributeNames<T>; private values: ExpressionAttributeValues; private sets: { [key: string]: string }; private removes: { [key: string]: 1 }; private adds: { [key: string]: string }; private deletes: { [key: string]: string }; public constructor( names: ExpressionAttributeNames<T>, values: ExpressionAttributeValues, init?: UpdateExpressionStr, ) { this.names = names; this.values = values; this.sets = {}; this.removes = {}; this.adds = {}; this.deletes = {}; if (!init) return; const parts = init .trim() .split(/(?:^|\s+)(SET|REMOVE|ADD|DELETE)(?:\s+)/gi); for (let i = 1; i < parts.length; i += 2) { const action = parts[i]; const terms = parts[i + 1].split(/\s*,\s*/g); switch (action.toUpperCase()) { case 'SET': { for (const term of terms) { const [path, value] = term.split(/\s*=\s*/); this.sets[path] = value; } break; } case 'REMOVE': { for (const term of terms) { this.removes[term] = 1; } break; } case 'ADD': { for (const term of terms) { const [path, value] = term.split(/\s+/); this.adds[path] = value; } break; } case 'DELETE': { for (const term of terms) { const [path, value] = term.split(/\s+/); this.deletes[path] = value; } break; } } } } public set<K1 extends keyof T>( path: K1 | [K1], value: SetValue<T, T[K1]>, ): this; public set<K1 extends keyof T, K2 extends keyof T[K1]>( path: [K1, K2], value: SetValue<T, T[K1][K2]>, ): this; public set< K1 extends keyof T, K2 extends keyof T[K1], K3 extends keyof T[K1][K2], >(path: [K1, K2, K3], value: SetValue<T, T[K1][K2][K3]>): this; public set< K1 extends keyof T, K2 extends keyof T[K1], K3 extends keyof T[K1][K2], K4 extends keyof T[K1][K2][K3], >(path: [K1, K2, K3, K4], value: SetValue<T, T[K1][K2][K3][K4]>): this; public set< K1 extends keyof T, K2 extends keyof T[K1], K3 extends keyof T[K1][K2], K4 extends keyof T[K1][K2][K3], K5 extends keyof T[K1][K2][K3][K4], >( path: [K1, K2, K3, K4, K5], value: SetValue<T, T[K1][K2][K3][K4][K5]>, ): this; public set< K1 extends keyof T, K2 extends keyof T[K1], K3 extends keyof T[K1][K2], K4 extends keyof T[K1][K2][K3], K5 extends keyof T[K1][K2][K3][K4], K6 extends keyof T[K1][K2][K3][K4][K5], >( path: [K1, K2, K3, K4, K5, K6], value: SetValue<T, T[K1][K2][K3][K4][K5][K6]>, ): this; public set< K1 extends keyof T, K2 extends keyof T[K1], K3 extends keyof T[K1][K2], K4 extends keyof T[K1][K2][K3], K5 extends keyof T[K1][K2][K3][K4], K6 extends keyof T[K1][K2][K3][K4][K5], K7 extends keyof T[K1][K2][K3][K4][K5][K6], >( path: [K1, K2, K3, K4, K5, K6, K7], value: SetValue<T, T[K1][K2][K3][K4][K5][K6][K7]>, ): this; public set< K1 extends keyof T, K2 extends keyof T[K1], K3 extends keyof T[K1][K2], K4 extends keyof T[K1][K2][K3], K5 extends keyof T[K1][K2][K3][K4], K6 extends keyof T[K1][K2][K3][K4][K5], K7 extends keyof T[K1][K2][K3][K4][K5][K6], K8 extends keyof T[K1][K2][K3][K4][K5][K6][K7], >( path: [K1, K2, K3, K4, K5, K6, K7, K8], value: SetValue<T, T[K1][K2][K3][K4][K5][K6][K7][K8]>, ): this; public set< K1 extends keyof T, K2 extends keyof T[K1], K3 extends keyof T[K1][K2], K4 extends keyof T[K1][K2][K3], K5 extends keyof T[K1][K2][K3][K4], K6 extends keyof T[K1][K2][K3][K4][K5], K7 extends keyof T[K1][K2][K3][K4][K5][K6], K8 extends keyof T[K1][K2][K3][K4][K5][K6][K7], >( path: K1 | [K1, K2?, K3?, K4?, K5?, K6?, K7?, K8?, ...(string | number)[]], value: SetValue<T, unknown>, ): this { if (!Array.isArray(path)) { path = [path]; } const pathName = this.names.add(...path); const valueKey = String(path[path.length - 1]); this.sets[pathName] = typeof value === 'function' ? value( new UpdateValueExpression( this.names, this.values, pathName, valueKey, ), ) : this.values.add(valueKey, value); return this; } public remove< K1 extends keyof T, K2 extends keyof T[K1], K3 extends keyof T[K1][K2], K4 extends keyof T[K1][K2][K3], K5 extends keyof T[K1][K2][K3][K4], K6 extends keyof T[K1][K2][K3][K4][K5], K7 extends keyof T[K1][K2][K3][K4][K5][K6], K8 extends keyof T[K1][K2][K3][K4][K5][K6][K7], >( ...path: [K1, K2?, K3?, K4?, K5?, K6?, K7?, K8?, ...(string | number)[]] ): this { this.removes[this.names.add(...path)] = 1; return this; } public add<K1 extends keyof T>(path: K1 | [K1], value: AddValue<T[K1]>): this; public add<K1 extends keyof T, K2 extends keyof T[K1]>( path: [K1, K2], value: AddValue<T[K1][K2]>, ): this; public add< K1 extends keyof T, K2 extends keyof T[K1], K3 extends keyof T[K1][K2], >(path: [K1, K2, K3], value: AddValue<T[K1][K2][K3]>): this; public add< K1 extends keyof T, K2 extends keyof T[K1], K3 extends keyof T[K1][K2], K4 extends keyof T[K1][K2][K3], >(path: [K1, K2, K3, K4], value: AddValue<T[K1][K2][K3][K4]>): this; public add< K1 extends keyof T, K2 extends keyof T[K1], K3 extends keyof T[K1][K2], K4 extends keyof T[K1][K2][K3], K5 extends keyof T[K1][K2][K3][K4], >(path: [K1, K2, K3, K4, K5], value: AddValue<T[K1][K2][K3][K4][K5]>): this; public add< K1 extends keyof T, K2 extends keyof T[K1], K3 extends keyof T[K1][K2], K4 extends keyof T[K1][K2][K3], K5 extends keyof T[K1][K2][K3][K4], K6 extends keyof T[K1][K2][K3][K4][K5], >( path: [K1, K2, K3, K4, K5, K6], value: AddValue<T[K1][K2][K3][K4][K5][K6]>, ): this; public add< K1 extends keyof T, K2 extends keyof T[K1], K3 extends keyof T[K1][K2], K4 extends keyof T[K1][K2][K3], K5 extends keyof T[K1][K2][K3][K4], K6 extends keyof T[K1][K2][K3][K4][K5], K7 extends keyof T[K1][K2][K3][K4][K5][K6], >( path: [K1, K2, K3, K4, K5, K6, K7], value: AddValue<T[K1][K2][K3][K4][K5][K6][K7]>, ): this; public add< K1 extends keyof T, K2 extends keyof T[K1], K3 extends keyof T[K1][K2], K4 extends keyof T[K1][K2][K3], K5 extends keyof T[K1][K2][K3][K4], K6 extends keyof T[K1][K2][K3][K4][K5], K7 extends keyof T[K1][K2][K3][K4][K5][K6], K8 extends keyof T[K1][K2][K3][K4][K5][K6][K7], >( path: [K1, K2, K3, K4, K5, K6, K7, K8], value: AddValue<T[K1][K2][K3][K4][K5][K6][K7][K8]>, ): this; public add< K1 extends keyof T, K2 extends keyof T[K1], K3 extends keyof T[K1][K2], K4 extends keyof T[K1][K2][K3], K5 extends keyof T[K1][K2][K3][K4], K6 extends keyof T[K1][K2][K3][K4][K5], K7 extends keyof T[K1][K2][K3][K4][K5][K6], K8 extends keyof T[K1][K2][K3][K4][K5][K6][K7], >( path: K1 | [K1, K2?, K3?, K4?, K5?, K6?, K7?, K8?, ...(string | number)[]], value: unknown, ): this { if (!Array.isArray(path)) { path = [path]; } this.adds[this.names.add(...path)] = this.values.add( String(path[path.length - 1]), value, ); return this; } public delete<K1 extends keyof T>( path: K1 | [K1], value: DeleteValue<T[K1]>, ): this; public delete<K1 extends keyof T, K2 extends keyof T[K1]>( path: [K1, K2], value: DeleteValue<T[K1][K2]>, ): this; public delete< K1 extends keyof T, K2 extends keyof T[K1], K3 extends keyof T[K1][K2], >(path: [K1, K2, K3], value: DeleteValue<T[K1][K2][K3]>): this; public delete< K1 extends keyof T, K2 extends keyof T[K1], K3 extends keyof T[K1][K2], K4 extends keyof T[K1][K2][K3], >(path: [K1, K2, K3, K4], value: DeleteValue<T[K1][K2][K3][K4]>): this; public delete< K1 extends keyof T, K2 extends keyof T[K1], K3 extends keyof T[K1][K2], K4 extends keyof T[K1][K2][K3], K5 extends keyof T[K1][K2][K3][K4], >( path: [K1, K2, K3, K4, K5], value: DeleteValue<T[K1][K2][K3][K4][K5]>, ): this; public delete< K1 extends keyof T, K2 extends keyof T[K1], K3 extends keyof T[K1][K2], K4 extends keyof T[K1][K2][K3], K5 extends keyof T[K1][K2][K3][K4], K6 extends keyof T[K1][K2][K3][K4][K5], >( path: [K1, K2, K3, K4, K5, K6], value: DeleteValue<T[K1][K2][K3][K4][K5][K6]>, ): this; public delete< K1 extends keyof T, K2 extends keyof T[K1], K3 extends keyof T[K1][K2], K4 extends keyof T[K1][K2][K3], K5 extends keyof T[K1][K2][K3][K4], K6 extends keyof T[K1][K2][K3][K4][K5], K7 extends keyof T[K1][K2][K3][K4][K5][K6], >( path: [K1, K2, K3, K4, K5, K6, K7], value: DeleteValue<T[K1][K2][K3][K4][K5][K6][K7]>, ): this; public delete< K1 extends keyof T, K2 extends keyof T[K1], K3 extends keyof T[K1][K2], K4 extends keyof T[K1][K2][K3], K5 extends keyof T[K1][K2][K3][K4], K6 extends keyof T[K1][K2][K3][K4][K5], K7 extends keyof T[K1][K2][K3][K4][K5][K6], K8 extends keyof T[K1][K2][K3][K4][K5][K6][K7], >( path: [K1, K2, K3, K4, K5, K6, K7, K8], value: DeleteValue<T[K1][K2][K3][K4][K5][K6][K7][K8]>, ): this; public delete< K1 extends keyof T, K2 extends keyof T[K1], K3 extends keyof T[K1][K2], K4 extends keyof T[K1][K2][K3], K5 extends keyof T[K1][K2][K3][K4], K6 extends keyof T[K1][K2][K3][K4][K5], K7 extends keyof T[K1][K2][K3][K4][K5][K6], K8 extends keyof T[K1][K2][K3][K4][K5][K6][K7], >( path: K1 | [K1, K2?, K3?, K4?, K5?, K6?, K7?, K8?, ...(string | number)[]], value: DeleteValue<unknown>, ): this { if (!Array.isArray(path)) { path = [path]; } this.deletes[this.names.add(...path)] = this.values.add( String(path[path.length - 1]), value, ); return this; } public serialize(): UpdateExpressionStr | undefined { const exp: string[] = []; const sets = Object.entries(this.sets).map( ([key, value]) => `${key} = ${value}`, ); if (sets.length) { exp.push(`SET ${sets.join(', ')}`); } const removes = Object.keys(this.removes); if (removes.length) { exp.push(`REMOVE ${removes.join(', ')}`); } const adds = Object.entries(this.adds).map( ([key, value]) => `${key} ${value}`, ); if (adds.length) { exp.push(`ADD ${adds.join(', ')}`); } const deletes = Object.entries(this.deletes).map( ([key, value]) => `${key} ${value}`, ); if (deletes.length) { exp.push(`DELETE ${deletes.join(', ')}`); } return exp.join(' ') || undefined; } }
the_stack
import { Vector2, Vector3 } from 'three'; import { flatteningParams } from '../common/Defaults'; import GPUHelper from '../common/GPUHelper'; import MutableTypedArray from '../common/MutableTypedArray'; import { FileParams, FlatteningParams, Type } from '../common/types'; import { arrayIntersection, log } from '../common/utils'; import { BFGSAlgorithm } from './BFGS'; const SQRT_3 = Math.sqrt(3); const tempArray1: number[] = []; const tempArray2: number[] = []; const tempVector1 = new Vector2(); // Temp objects used in specific methods. const _getDist3D_tempVector1 = new Vector3(); const _getDist3D_tempVector2 = new Vector3(); const _getDistSq3D_tempVector1 = new Vector3(); const _getDistSq3D_tempVector2 = new Vector3(); let _BFGS_constraintData: Float32Array; const _BFGS_initialPosition = [0, 0]; const _savePoint2D_position = [0, 0]; export class Embedding2D { gpuHelper: GPUHelper; flatteningParams: FlatteningParams; fileParams: FileParams; // Saved Arrays. points3DList: MutableTypedArray; meshNumbersList: MutableTypedArray; meshNeighborsList: MutableTypedArray; // Computed arrays. points2DList: MutableTypedArray; iterMappedList: MutableTypedArray; meshSizesList: MutableTypedArray; mappedMeshSizesList: MutableTypedArray; mappingAttemptsRemainingList: MutableTypedArray; // Computational helpers. maxMeshNum: number; iterNum = 0; // Keep track of the number of iterations of flattening that have been run. bfgs = new BFGSAlgorithm({ ERROR: 0.00001, MAX_ITERATOR: 20, }); constructor(gpuHelper: GPUHelper, fileParams: FileParams, flatteningParams: FlatteningParams) { this.gpuHelper = gpuHelper; this.flatteningParams = flatteningParams; this.fileParams = fileParams; // Load up previously computed data. this.points3DList = MutableTypedArray.initFromFile(fileParams.OUTPUT_PATH, `${fileParams.FILENAME}_points3DList`); this.meshNumbersList = MutableTypedArray.initFromFile(fileParams.OUTPUT_PATH, `${fileParams.FILENAME}_meshNumbersList`); this.meshNeighborsList = MutableTypedArray.initFromFile(fileParams.OUTPUT_PATH, `${fileParams.FILENAME}_meshNeighborsList`); const NUM_POINTS = this.points3DList.getLength(); // Init a space to store the flattened positions. this.points2DList = new MutableTypedArray(new Float32Array(2 * NUM_POINTS), true, 2); this.points2DList.clear(); // Fill with null to start. // Store the iter num when each point has been mapped (so we can track progress) this.iterMappedList = new MutableTypedArray(new Int32Array(NUM_POINTS), true); this.iterMappedList.clear(); // Fill with null to start. // Init a space to store the next points to check in mapping computation. this.mappingAttemptsRemainingList = new MutableTypedArray(new Uint8Array(NUM_POINTS), false); this.mappingAttemptsRemainingList.clear(); // Fill with zeros to start. // Init an array to store constraint data for BFGS. _BFGS_constraintData = new Float32Array(flatteningParams.MAX_BFGS_CONSTRAINTS * 3); // Init gpu buffers. this.gpuHelper.createGpuBufferFromMutableTypedArray('positions2D', this.points2DList, 'readwrite'); this.gpuHelper.createGpuBufferFromMutableTypedArray('positions3D', this.points3DList, 'readwrite'); this.gpuHelper.createGpuBufferFromMutableTypedArray('neighbors', this.meshNeighborsList, 'read'); this.gpuHelper.createGpuBufferFromMutableTypedArray('meshNumbers', this.meshNumbersList, 'read'); this.gpuHelper.createGpuBufferFromMutableTypedArray('mappingAttemptsRemaining', this.mappingAttemptsRemainingList, 'readwrite'); this.gpuHelper.createGpuBufferFromMutableTypedArray('iterMapped', this.iterMappedList, 'readwrite'); this.gpuHelper.createGPUBuffer('velocities2D', null, 'float*', 'readwrite', NUM_POINTS * 2); this.gpuHelper.zeroBuffer('velocities2D'); this.gpuHelper.createGPUBuffer('nextPositions2D', null, 'float*', 'readwrite', NUM_POINTS * 2); this.gpuHelper.createGPUBuffer('nextVelocities2D', null, 'float*', 'readwrite', NUM_POINTS * 2); // Init flattening simulation program. const maxNatFreq = Math.sqrt(flatteningParams.AXIAL_STIFFNESS / 0.5); // Assume mass 1. const DT = (1 / (2 * Math.PI * maxNatFreq)) * 0.9; // Add a scaling factor. of 0.9 for safety. this.gpuHelper.initProgram('./src/flattening/gpu/flatteningSimProgram.cl', 'flatteningSim', { MAX_NUM_NEIGHBORS: { value: this.meshNeighborsList.numElementsPerIndex, type: 'uint32' as Type, }, AXIAL_STIFFNESS: { value: flatteningParams.AXIAL_STIFFNESS, type: 'float32' as Type, }, DAMPING_FACTOR: { value: flatteningParams.DAMPING_FACTOR, type: 'float32' as Type, }, DT: { value: DT, type: 'float32' as Type, }, }); this.gpuHelper.setBufferArgument('flatteningSim', 0, 'nextPositions2D'); this.gpuHelper.setBufferArgument('flatteningSim', 1, 'nextVelocities2D'); this.gpuHelper.setBufferArgument('flatteningSim', 2, 'positions2D'); this.gpuHelper.setBufferArgument('flatteningSim', 3, 'velocities2D'); this.gpuHelper.setBufferArgument('flatteningSim', 4, 'positions3D'); this.gpuHelper.setBufferArgument('flatteningSim', 5, 'neighbors'); // Init mapping program. this.gpuHelper.initProgram('./src/flattening/gpu/mapPoints2DProgram.cl', 'mapPoints2D', { MAX_NUM_NEIGHBORS: { value: this.meshNeighborsList.numElementsPerIndex, type: 'uint32' as Type, }, MAX_BFGS_CONSTRAINTS: { value: flatteningParams.MAX_BFGS_CONSTRAINTS, type: 'uint32' as Type, }, FLATTENING_EDGE_LENGTH_ERROR_TOL: { value: flatteningParams.FLATTENING_EDGE_LENGTH_ERROR_TOL, type: 'float32' as Type, }, }); this.gpuHelper.setBufferArgument('mapPoints2D', 0, 'positions2D'); this.gpuHelper.setBufferArgument('mapPoints2D', 1, 'positions3D'); this.gpuHelper.setBufferArgument('mapPoints2D', 2, 'neighbors'); this.gpuHelper.setBufferArgument('mapPoints2D', 3, 'meshNumbers'); this.gpuHelper.setBufferArgument('mapPoints2D', 4, 'mappingAttemptsRemaining'); this.gpuHelper.setBufferArgument('mapPoints2D', 5, 'iterMapped'); // Init updateMappingAttemptsRemaining program. this.gpuHelper.initProgram('./src/flattening/gpu/updateMappingAttemptsRemainingProgram.cl', 'updateMappingAttemptsRemaining', { MAX_NUM_NEIGHBORS: { value: this.meshNeighborsList.numElementsPerIndex, type: 'uint32' as Type, }, MAX_NUM_MAPPING_ATTEMPTS: { value: flatteningParams.MAX_NUM_MAPPING_ATTEMPTS, type: 'uint8' as Type, }, }); this.gpuHelper.setBufferArgument('updateMappingAttemptsRemaining', 0, 'positions2D'); this.gpuHelper.setBufferArgument('updateMappingAttemptsRemaining', 1, 'neighbors'); this.gpuHelper.setBufferArgument('updateMappingAttemptsRemaining', 2, 'mappingAttemptsRemaining'); this.gpuHelper.setBufferArgument('updateMappingAttemptsRemaining', 3, 'iterMapped'); // Init an array to store the size of (num points contained within) each mesh component. this.meshSizesList = new MutableTypedArray(new Int32Array(NUM_POINTS), false); this.meshSizesList.clear();// Fill with zero to start. // Init an array to store the current size of each mesh that has been mapped. this.mappedMeshSizesList = new MutableTypedArray(new Int32Array(NUM_POINTS), false); this.mappedMeshSizesList.clear(); // Fill with zero to start. // Compute maximum mesh number. this.maxMeshNum = 0; for (let i = 0; i < NUM_POINTS; i++) { const meshNumber = this.meshNumbersList.get(i); if (meshNumber !== null) { // Increment mesh size. this.meshSizesList.set(meshNumber, this.meshSizesList.get(meshNumber)! + 1); // Increment max mesh num if possible. if (meshNumber > this.maxMeshNum) { this.maxMeshNum = meshNumber; } } } // Start by seeing mesh on cpu. for (let i = 0; i < NUM_POINTS; i++) { if (this.meshSizesList.get(i)) { // log(`\tseeding mesh ${i}`); this._seedMesh(i); } } // Copy data to GPU. this.gpuHelper.copyDataToGPUBuffer('positions2D', this.points2DList.getData() as Float32Array); this.gpuHelper.copyDataToGPUBuffer('iterMapped', this.iterMappedList.getData() as Int32Array); this.gpuHelper.finishAllEvents(); // Add points to seeds until no points can be added. let active = true; while (active) { active = this.iter(); } // Copy data back into CPU. this.gpuHelper.copyDataToMutableTypedArray('positions2D', this.points2DList); this.gpuHelper.copyDataToMutableTypedArray('iterMapped', this.iterMappedList); // Log results. for (let i = 0; i < NUM_POINTS; i++) { if (this.points2DList.getVector2(i, tempVector1)) { const meshNumber = this.meshNumbersList.get(i) as number; this.mappedMeshSizesList.set(meshNumber, this.mappedMeshSizesList.get(meshNumber)! + 1); } } for (let i = 0; i < NUM_POINTS; i++) { if (this.meshSizesList.get(i)) { log(`\tSeed ${i} mapped ${this.mappedMeshSizesList.get(i)} of ${this.meshSizesList.get(i)} points.`); } } // Save seeds to disk. this.points2DList.saveAsBin(fileParams.OUTPUT_PATH, `${fileParams.FILENAME}_points2DList`); this.iterMappedList.saveAsBin(fileParams.OUTPUT_PATH, `${fileParams.FILENAME}_iterMappedList`); } private _getDist3D(index1: number, index2: number) { const point1 = this.points3DList.getVector3(index1, _getDist3D_tempVector1); const point2 = this.points3DList.getVector3(index2, _getDist3D_tempVector2); return point1!.sub(point2!).length(); } private _getDistSq3D(index1: number, index2: number) { const point1 = this.points3DList.getVector3(index1, _getDistSq3D_tempVector1); const point2 = this.points3DList.getVector3(index2, _getDistSq3D_tempVector2); return point1!.sub(point2!).lengthSq(); } private _checkErrorTolsOnEachEdge(position2D: number[], constraintData: Float32Array, NUM_CONSTRAINTS: number) { for (let i = 0; i < NUM_CONSTRAINTS; i++) { const diffX = position2D[0] - constraintData[3 * i]; const diffY = position2D[1] - constraintData[3 * i + 1]; // Calc percent error of each edge. const nominalLength = Math.sqrt(constraintData[3 * i + 2]); const error = Math.sqrt(diffX*diffX + diffY*diffY) - nominalLength; if (error > this.flatteningParams.FLATTENING_EDGE_LENGTH_ERROR_TOL * nominalLength) { return false; } } return true; } private _BFGS(initialPosition: number[], constraintData: Float32Array, NUM_CONSTRAINTS: number) { const result = this.bfgs.run(initialPosition, constraintData, NUM_CONSTRAINTS); if (result === null) { console.log('BFGS failed.') return null; } if (!this._checkErrorTolsOnEachEdge(result, constraintData, NUM_CONSTRAINTS)) { return null; }; return result; } private _savePoint2D(i: number, position2D: number[], meshNumber: number) { // Save 2d position. this.points2DList.set(i, position2D); // this.mappedMeshSizesList.set(meshNumber, this.mappedMeshSizesList.get(meshNumber)! + 1); // Keep track of when this point was added to 2D. this.iterMappedList.set(i, this.iterNum); } private _seedMesh(meshNumber: number, enforceHighQuality = true, startIndex = 0) { const NUM_POINTS = this.points3DList.getLength(); // Grab first point of meshNumber. let point1Index: number | null = null; for (let i = startIndex; i < NUM_POINTS ; i++) { if (this.meshNumbersList.get(i) === meshNumber) { const neighbors = this.meshNeighborsList.get(i, tempArray1); if (neighbors === null) { continue; } if (enforceHighQuality) { // Limit seed search to only points with 8 neighbors, these tend to be higher quality. if (!neighbors || neighbors.length !== 8) { continue; } } point1Index = i; break; } } if (point1Index === null){ if (enforceHighQuality) { // Try again without high quality enforcement. this._seedMesh(meshNumber, false); return; } log(`Unable to seed mesh ${meshNumber}`); return; } // Find two neighbors that are neighbors of each other to form remainder of triangle. let neighbors = this.meshNeighborsList.get(point1Index, tempArray1)!; if (enforceHighQuality) { // Filter to neighbors of high quality (eg each with 8 neighbors of their own). neighbors = neighbors.filter(i => this.meshNeighborsList.get(i, tempArray2)?.length === 8); } let triangleFormed = false; for (let i = 0; i < neighbors.length; i++) { let neighborNeighbors = this.meshNeighborsList.get(neighbors[i], tempArray2); if (!neighborNeighbors) continue; const intersection = arrayIntersection(neighborNeighbors, neighbors); if (intersection.length == 0) { continue; } // Triangle found. // Put first pt on origin. // We don't actually have to do this, bc the value never changes. _BFGS_constraintData[0] = 0; _BFGS_constraintData[1] = 0; // Put second pt on x axis. const point2Index = neighbors[i]; const dist12 = this._getDist3D(point1Index, point2Index); if (dist12 == 0) { console.log("Error calculating distance between neighboring points in seed()."); continue; } _BFGS_constraintData[3] = dist12; _BFGS_constraintData[4] = 0; // Solve for third point. const point3Index = intersection[0]; _BFGS_constraintData[2] = this._getDistSq3D(point1Index, point3Index); _BFGS_constraintData[5] = this._getDistSq3D(point2Index, point3Index); // Start with an estimate of third point. _BFGS_initialPosition[0] = dist12 / 2; _BFGS_initialPosition[1] = dist12 * SQRT_3; const result = this._BFGS(_BFGS_initialPosition, _BFGS_constraintData, 2); if (result === null) { continue; } triangleFormed = true; // Add 2D points. _savePoint2D_position[0] = _BFGS_constraintData[0]; _savePoint2D_position[1] = _BFGS_constraintData[1]; this._savePoint2D(point1Index, _savePoint2D_position, meshNumber); _savePoint2D_position[0] = _BFGS_constraintData[3]; _savePoint2D_position[1] = _BFGS_constraintData[4]; this._savePoint2D(point2Index, _savePoint2D_position, meshNumber); this._savePoint2D(point3Index, result, meshNumber); break; } if (!triangleFormed){ // Continue search if possible this._seedMesh(meshNumber, enforceHighQuality, point1Index + 1); return; } } iter() { const NUM_POINTS = this.points2DList.getLength(); // Keep track of num points checked and successfully added this round. // let numPtsAddedThisRound = 0; let numPtsCheckedThisRound = 0; // Run 100 steps of iter before checking if we're done to reduce the number of data transfers needed. for (let j = 0; j < 100; j++) { if (this.fileParams.SHOULD_SAVE_ANIMATION) { // Copy position data to cpu and save. this.gpuHelper.copyDataToMutableTypedArray('positions2D', this.points2DList); this.points2DList.saveAsBin(`${this.fileParams.OUTPUT_PATH}${this.fileParams.ANIMATION_PATH}`, `${this.fileParams.FILENAME}_points2DList_frame${this.iterNum}`); } // Increment iterNum. this.iterNum += 1; // Update mappingAttemptsRemaining. this.gpuHelper.setKernelArgument('updateMappingAttemptsRemaining', 4, 'int', this.iterNum); this.gpuHelper.runProgram('updateMappingAttemptsRemaining', NUM_POINTS); // Add new points. this.gpuHelper.setKernelArgument('mapPoints2D', 6, 'int', this.iterNum); this.gpuHelper.runProgram('mapPoints2D', NUM_POINTS); // Run relaxation simulation. const HALF_NUM_STEPS = flatteningParams.NUM_FLATTENING_SIM_STEPS / 2; for (let i = 0; i < HALF_NUM_STEPS; i++) { // Run two steps of sim. this.gpuHelper.setBufferArgument('flatteningSim', 0, 'nextPositions2D'); this.gpuHelper.setBufferArgument('flatteningSim', 1, 'nextVelocities2D'); this.gpuHelper.setBufferArgument('flatteningSim', 2, 'positions2D'); this.gpuHelper.setBufferArgument('flatteningSim', 3, 'velocities2D'); this.gpuHelper.runProgram('flatteningSim', NUM_POINTS); this.gpuHelper.setBufferArgument('flatteningSim', 0, 'positions2D'); this.gpuHelper.setBufferArgument('flatteningSim', 1, 'velocities2D'); this.gpuHelper.setBufferArgument('flatteningSim', 2, 'nextPositions2D'); this.gpuHelper.setBufferArgument('flatteningSim', 3, 'nextVelocities2D'); this.gpuHelper.runProgram('flatteningSim', NUM_POINTS); } } // Check to see how many points were checked this round. // Copy data back into CPU. this.gpuHelper.copyDataToMutableTypedArray('mappingAttemptsRemaining', this.mappingAttemptsRemainingList); for (let i = 0; i < NUM_POINTS; i++) { if (this.mappingAttemptsRemainingList.get(i)! > 0) { numPtsCheckedThisRound++; } } // console.log(numPtsCheckedThisRound); // log(`\t${numPtsAddedThisRound} points mapped to 2D this round.`); if (numPtsCheckedThisRound === 0) { return false; } return true; } destroy() { } }
the_stack
import { DbCollectionName } from '../utils/test-utils' import { UserMenuItem } from '../support/commands' import { IUser } from '../../../../src/models/user.models' interface Info { username: string country?: string description: string coverImage: string } interface IMapPin { description: string searchKeyword: string locationName: string } type ILink = IUser['links'][0] & { index: number } describe('[Settings]', () => { beforeEach(() => { cy.visit('/sign-in') }) const selectFocus = (focus: string) => { cy.get(`[data-cy=${focus}]`).click() } const setInfo = (info: Info) => { cy.step('Update Info section') cy.get('[data-cy=username').clear().type(info.username) cy.get('[data-cy=info-description').clear().type(info.description) cy.get('[data-cy=coverImages-0]').find(':file').attachFile(info.coverImage) } const setWorkspaceMapPin = (mapPin: IMapPin) => { cy.step('Update Workspace Map section') cy.get('[data-cy=pin-description]').clear().type(mapPin.description) cy.get('[data-cy=location-search]') .find(':text') .clear() .type(mapPin.searchKeyword) cy.get('[data-cy=location-search]') .find('.ap-suggestion:eq(0)', { timeout: 10000 }) .click() cy.get('[data-cy=location-search]') .find('input') .should('have.value', mapPin.locationName) } const setMemberMapPin = (mapPin: IMapPin) => { cy.step('Update Member section') cy.get('[data-cy=pin-description]').clear().type(mapPin.description) cy.get('[data-cy="osm-geocoding-input"]').clear().type(mapPin.searchKeyword) cy.get('[data-cy="osm-geocoding-results"]') .find('li:eq(0)', { timeout: 10000 }) .click() } const addContactLink = (link: ILink) => { if (link.index > 0) { // click the button to add another set of input fields cy.get('[data-cy=add-link]').click() } // specifies the contact type, such as website or discord cy.selectTag(link.label, `[data-cy=select-link-${link.index}]`) // input the corresponding value cy.get(`[data-cy=input-link-${link.index}]`).clear().type(link.url) } describe('[Focus Workplace]', () => { const freshSettings = { _authID: 'l9N5HFHzSjQvtP9g9MyFnPpkFmM2', _id: 'settings_workplace_new', userName: 'settings_workplace_new', _deleted: false, verified: true, } const expected = { _authID: 'l9N5HFHzSjQvtP9g9MyFnPpkFmM2', _deleted: false, _id: 'settings_workplace_new', about: 'We have some space to run a workplace', coverImages: [ { contentType: 'image/jpeg', fullPath: 'uploads/v3_users/settings_workplace_new/images/profile-cover-1.jpg', name: 'profile-cover-1.jpg', size: 18987, type: 'image/jpeg', }, ], links: [ { label: 'email', url: `${freshSettings.userName}@test.com`, }, { label: 'website', url: `http://www.${freshSettings.userName}.com`, }, ], location: { administrative: 'Ohio', country: 'United States of America', countryCode: 'us', latlng: { lat: 39.9623, lng: -83.0007, }, name: 'Columbus', postcode: '43085', value: 'Columbus, Ohio, United States of America', }, mapPinDescription: "Come in & let's make cool stuff out of plastic!", profileType: 'workspace', userName: 'settings_workplace_new', verified: true, workspaceType: 'shredder', } it('[Editing a new Profile]', () => { cy.login('settings_workplace_new@test.com', 'test1234') cy.step('Go to User Settings') cy.clickMenuItem(UserMenuItem.Settings) selectFocus(expected.profileType) cy.get(`[data-cy=${expected.workspaceType}]`).click() setInfo({ username: expected.userName, description: expected.about, coverImage: 'images/profile-cover-1.jpg', }) cy.step('Update Contact Links') addContactLink({ index: 0, label: 'email', url: `${freshSettings.userName}@test.com`, }) addContactLink({ index: 1, label: 'website', url: `http://www.${freshSettings.userName}.com`, }) setWorkspaceMapPin({ description: expected.mapPinDescription, searchKeyword: 'ohio', locationName: expected.location.value, }) cy.get('[data-cy=save]').click() cy.wait(2000) cy.get('[data-cy=save]').should('not.be.disabled') cy.step('Verify if all changes were saved correctly') cy.queryDocuments( DbCollectionName.users, 'userName', '==', expected.userName, ).then((docs) => { cy.log('queryDocs', docs) expect(docs.length).to.equal(1) cy.wrap(null) .then(() => docs[0]) .should('eqSettings', expected) }) }) }) describe.only('[Focus Member]', () => { const freshSettings = { _authID: 'pbx4jStD8sNj4OEZTg4AegLTl6E3', _id: 'settings_member_new', userName: 'settings_member_new', _deleted: false, verified: true, } const expected = { _authID: 'pbx4jStD8sNj4OEZTg4AegLTl6E3', _deleted: false, _id: 'settings_member_new', about: "I'm a very active member", // note - flag-picker returns country code but displays labels, // so tests will only work for countries that code start same as label country: 'AU', profileType: 'member', userName: 'settings_member_new', verified: true, coverImages: [ { contentType: 'image/jpeg', fullPath: 'uploads/v3_users/settings_member_new/images/profile-cover-1.jpg', name: 'profile-cover-1.jpg', size: 18987, type: 'image/jpeg', }, ], links: [ { label: 'email', url: `${freshSettings.userName}@test.com`, }, ], } it('[Edit a new profile]', () => { cy.login('settings_member_new@test.com', 'test1234') cy.step('Go to User Settings') cy.clickMenuItem(UserMenuItem.Settings) selectFocus(expected.profileType) setInfo({ username: expected.userName, country: expected.country, description: expected.about, coverImage: 'images/profile-cover-1.jpg', }) cy.step('Update Contact Links') addContactLink({ index: 0, label: 'email', url: `${freshSettings.userName}@test.com`, }) cy.get('[data-cy=save]').click() cy.wait(2000) cy.get('[data-cy=save]').should('not.be.disabled') cy.queryDocuments( DbCollectionName.users, 'userName', '==', expected.userName, ).then((docs) => { cy.log('queryDocs', docs) expect(docs.length).to.equal(1) cy.wrap(null) .then(() => docs[0]) .should('eqSettings', expected) }) }) it('[Add a user pin]', () => { const expected = { _authID: 'pbx4jStD8sNj4OEZTg4AegLTl6E3', _deleted: false, _id: 'settings_member_new', about: "I'm a very active member", // note - flag-picker returns country code but displays labels, // so tests will only work for countries that code start same as label country: 'AU', profileType: 'member', userName: 'settings_member_new', verified: true, coverImages: [ { contentType: 'image/jpeg', fullPath: 'uploads/v3_users/settings_member_new/images/profile-cover-1.jpg', name: 'profile-cover-1.jpg', size: 18987, type: 'image/jpeg', }, ], links: [ { label: 'email', url: `${freshSettings.userName}@test.com`, }, ], mapPinDescription: 'Fun, vibrant and full of amazing people', location: { administrative: null, country: 'Singapore', countryCode: 'sg', latlng: { lat: 1.29048, lng: 103.852, }, name: 'Singapore', postcode: '178957', value: 'Singapore, Singapore', }, } cy.login('settings_member_new@test.com', 'test1234') cy.step('Go to User Settings') cy.clickMenuItem(UserMenuItem.Settings) selectFocus(expected.profileType) cy.get('[data-cy=location-dropdown]').should('exist') cy.get('[data-cy="add-a-map-pin"]').click() setInfo({ username: expected.userName, country: expected.country, description: expected.about, coverImage: 'images/profile-cover-1.jpg', }) cy.step('Update Contact Links') addContactLink({ index: 0, label: 'email', url: `${freshSettings.userName}@test.com`, }) setMemberMapPin({ description: expected.mapPinDescription, searchKeyword: 'singapo', locationName: expected.location.value, }) cy.get('[data-cy=location-dropdown]').should('not.exist') cy.step('Remove a user pin') cy.get('[data-cy="remove-a-member-map-pin"]').click() cy.get('[data-cy=location-dropdown]').should('exist') cy.get('[data-cy=save]').click() cy.get('[data-cy=save]').should('not.be.disabled') cy.queryDocuments( DbCollectionName.users, 'userName', '==', expected.userName, ).then((docs) => { cy.log('queryDocs', docs) expect(docs.length).to.equal(1) cy.wrap(null) .then(() => docs[0]) .should('eqSettings', expected) }) }) }) describe('[Focus Machine Builder]', () => { const expected = { _authID: 'wwtBAo7TrkSQ9nAaBN3D93I1sCM2', _deleted: false, _id: 'settings_machine_new', about: "We're mechanics and our jobs are making machines", profileType: 'machine-builder', userName: 'settings_machine_new', verified: true, coverImages: [ { contentType: 'image/png', fullPath: 'uploads/v3_users/settings_machine_new/images/profile-cover-2.png', name: 'profile-cover-2.png', size: 30658, type: 'image/png', }, ], links: [ { label: 'bazar', url: 'http://settings_machine_bazarlink.com', }, ], location: { administrative: null, country: 'Singapore', countryCode: 'sg', latlng: { lat: 1.29048, lng: 103.852, }, name: 'Singapore', postcode: '178957', value: 'Singapore, Singapore', }, mapPinDescription: 'Informative workshop on machines every week', machineBuilderXp: ['electronics', 'welding'], } it('[Edit a new profile]', () => { cy.login('settings_machine_new@test.com', 'test1234') cy.step('Go to User Settings') cy.clickMenuItem(UserMenuItem.Settings) selectFocus(expected.profileType) setInfo({ username: expected.userName, description: expected.about, coverImage: 'images/profile-cover-2.png', }) cy.step('Choose Expertise') cy.get('[data-cy=electronics]').click() cy.get('[data-cy=welding]').click() cy.step('Update Contact Links') addContactLink({ index: 0, label: 'bazar', url: `http://settings_machine_bazarlink.com`, }) setWorkspaceMapPin({ description: expected.mapPinDescription, searchKeyword: 'singapo', locationName: expected.location.value, }) cy.get('[data-cy=save]').click() cy.wait(2000) cy.get('[data-cy=save]').should('not.be.disabled') cy.queryDocuments( DbCollectionName.users, 'userName', '==', expected.userName, ).then((docs) => { cy.log('queryDocs', docs) expect(docs.length).to.equal(1) cy.wrap(null) .then(() => docs[0]) .should('eqSettings', expected) }) }) }) describe('[Focus Community Builder]', () => { const expected = { _authID: 'vWAbQvq21UbvhGldakIy1x4FpeF2', _deleted: false, _id: 'settings_community_new', about: 'An enthusiastic community that makes the world greener!', mapPinDescription: 'Fun, vibrant and full of amazing people', profileType: 'community-builder', userName: 'settings_community_new', verified: true, coverImages: [ { contentType: 'image/jpeg', fullPath: 'uploads/v3_users/settings_community_new/images/profile-cover-1.jpg', name: 'profile-cover-1.jpg', size: 18987, type: 'image/jpeg', }, ], links: [ { label: 'forum', url: 'http://www.settings_community_new-forum.org', }, ], location: { administrative: 'England', country: 'United Kingdom', countryCode: 'gb', latlng: { lat: 51.5073, lng: -0.127647, }, name: 'City of London', postcode: 'EC1A', value: 'City of London, England, United Kingdom', }, } it('[Edit a new profile]', () => { cy.login('settings_community_new@test.com', 'test1234') cy.step('Go to User Settings') cy.clickMenuItem(UserMenuItem.Settings) selectFocus(expected.profileType) setInfo({ username: expected.userName, description: expected.about, coverImage: 'images/profile-cover-1.jpg', }) cy.step('Update Contact Links') expected.links.forEach((link, index) => addContactLink({ index, label: 'website', url: link.url }), ) setWorkspaceMapPin({ description: expected.mapPinDescription, searchKeyword: 'london, city of', locationName: expected.location.value, }) cy.get('[data-cy=save]').click() cy.wait(2000) cy.get('[data-cy=save]').should('not.be.disabled') cy.queryDocuments( DbCollectionName.users, 'userName', '==', expected.userName, ).then((docs) => { cy.log('queryDocs', docs) expect(docs.length).to.equal(1) cy.wrap(null) .then(() => docs[0]) .should('eqSettings', expected) }) }) }) describe('Focus Plastic Collection Point', () => { const freshSettings = { _authID: 'uxupeYR7glagQyhBy8q0blr0chd2', _id: 'settings_plastic_new', userName: 'settings_plastic_new', _deleted: false, verified: true, } const expected = { _authID: 'uxupeYR7glagQyhBy8q0blr0chd2', _deleted: false, _id: 'settings_plastic_new', about: 'We accept plastic currencies: Bottle, Nylon Bags, Plastic Lids/Straws', profileType: 'collection-point', userName: 'settings_plastic_new', verified: true, coverImages: [ { contentType: 'image/jpeg', fullPath: 'uploads/v3_users/settings_plastic_new/images/profile-cover-1.jpg', name: 'profile-cover-1.jpg', size: 18987, type: 'image/jpeg', }, ], links: [ { label: 'social media', url: 'http://www.facebook.com/settings_plastic_new', }, { label: 'social media', url: 'http://www.twitter.com/settings_plastic_new', }, ], location: { administrative: 'Melaka', country: 'Malaysia', countryCode: 'my', latlng: { lat: 2.19082, lng: 102.256, }, name: 'Malacca', postcode: '75000', value: 'Malacca, Melaka, Malaysia', }, mapPinDescription: 'Feed us plastic!', openingHours: [ { day: 'Monday', openFrom: '09:00 AM', openTo: '06:00 PM', }, { day: 'Wednesday', openFrom: '09:00 AM', openTo: '06:00 PM', }, { day: 'Friday', openFrom: '09:00 AM', openTo: '06:00 PM', }, ], collectedPlasticTypes: ['hdpe', 'pvc', 'other'], } interface IOpeningTime { index: number day: string from: string to: string } const selectOption = (selector: string, selectedValue: string) => { cy.selectTag(selectedValue, selector) } const addOpeningTime = (openingTime: IOpeningTime) => { if (openingTime.index > 0) { cy.get('[data-cy=add-opening-time]').click() } selectOption( `[data-cy=opening-time-day-${openingTime.index}]`, openingTime.day, ) selectOption( `[data-cy=opening-time-from-${openingTime.index}]`, openingTime.from, ) selectOption( `[data-cy=opening-time-to-${openingTime.index}]`, openingTime.to, ) } const deleteOpeningTime = (index: number, confirmed: boolean) => { cy.viewport('macbook-13') cy.get(`[data-cy=delete-opening-time-${index}-desk]`).click() if (confirmed) { cy.get('[data-cy=confirm-delete]').click() } else { cy.get('[data-cy=cancel-delete]').click() } } it('[Edit a new profile]', () => { cy.login('settings_plastic_new@test.com', 'test1234') cy.step('Go to User Settings') cy.clickMenuItem(UserMenuItem.Settings) selectFocus(expected.profileType) setInfo({ username: expected.userName, description: expected.about, coverImage: 'images/profile-cover-1.jpg', }) cy.step('Update Contact Links') addContactLink({ index: 0, label: 'social media', url: `http://www.facebook.com/${freshSettings.userName}`, }) addContactLink({ index: 1, label: 'social media', url: `http://www.twitter.com/${freshSettings.userName}`, }) cy.step('Update Collection section') addOpeningTime({ index: 0, day: 'Monday', from: '09:00 AM', to: '06:00 PM', }) addOpeningTime({ index: 1, day: 'Tuesday', from: '09:00 AM', to: '06:00 PM', }) addOpeningTime({ index: 2, day: 'Wednesday', from: '09:00 AM', to: '06:00 PM', }) addOpeningTime({ index: 3, day: 'Friday', from: '09:00 AM', to: '06:00 PM', }) deleteOpeningTime(0, false) deleteOpeningTime(1, true) cy.get('[data-cy=plastic-hdpe]').click() cy.get('[data-cy=plastic-pvc]').click() cy.get('[data-cy=plastic-other]').click() setWorkspaceMapPin({ description: expected.mapPinDescription, searchKeyword: 'Malacca', locationName: expected.location.value, }) cy.get('[data-cy=save]').click() cy.wait(2000) cy.get('[data-cy=save]').should('not.be.disabled') cy.queryDocuments( DbCollectionName.users, 'userName', '==', expected.userName, ).then((docs) => { cy.log('queryDocs', docs) expect(docs.length).to.equal(1) cy.wrap(null) .then(() => docs[0]) .should('eqSettings', expected) }) }) }) })
the_stack
import * as protobuf from 'protobufjs'; import * as gax from './gax'; import * as routingHeader from './routingHeader'; import {Status} from './status'; import {OutgoingHttpHeaders} from 'http'; import { GoogleAuth, OAuth2Client, Compute, JWT, UserRefreshClient, GoogleAuthOptions, BaseExternalAccountClient, } from 'google-auth-library'; import * as objectHash from 'object-hash'; import {OperationsClientBuilder} from './operationsClient'; import {GrpcClientOptions, ClientStubOptions} from './grpc'; import {GaxCall, GRPCCall} from './apitypes'; import {Descriptor, StreamDescriptor} from './descriptor'; import {createApiCall as _createApiCall} from './createApiCall'; import {FallbackServiceError} from './googleError'; import * as fallbackProto from './fallbackProto'; import * as fallbackRest from './fallbackRest'; import {isNodeJS} from './featureDetection'; import {generateServiceStub} from './fallbackServiceStub'; import {StreamType} from '.'; export {FallbackServiceError}; export {PathTemplate} from './pathTemplate'; export {routingHeader}; export {CallSettings, constructSettings, RetryOptions} from './gax'; export const version = require('../../package.json').version + '-fallback'; export { BundleDescriptor, LongrunningDescriptor, PageDescriptor, StreamDescriptor, } from './descriptor'; export {StreamType} from './streamingCalls/streaming'; export const defaultToObjectOptions = { keepCase: false, longs: String, enums: String, defaults: true, oneofs: true, }; const CLIENT_VERSION_HEADER = 'x-goog-api-client'; export interface ServiceMethods { [name: string]: protobuf.Method; } export type AuthClient = | OAuth2Client | Compute | JWT | UserRefreshClient | BaseExternalAccountClient; export class GrpcClient { auth?: OAuth2Client | GoogleAuth; authClient?: AuthClient; fallback: boolean | 'rest' | 'proto'; grpcVersion: string; private static protoCache = new Map<string, protobuf.Root>(); /** * In rare cases users might need to deallocate all memory consumed by loaded protos. * This method will delete the proto cache content. */ static clearProtoCache() { GrpcClient.protoCache.clear(); } /** * gRPC-fallback version of GrpcClient * Implements GrpcClient API for a browser using grpc-fallback protocol (sends serialized protobuf to HTTP/1 $rpc endpoint). * * @param {Object=} options.auth - An instance of OAuth2Client to use in browser, or an instance of GoogleAuth from google-auth-library * to use in Node.js. Required for browser, optional for Node.js. * @constructor */ constructor( options: (GrpcClientOptions | {auth: OAuth2Client}) & { fallback?: boolean | 'rest' | 'proto'; } = {} ) { if (!isNodeJS()) { if (!options.auth) { throw new Error( JSON.stringify(options) + 'You need to pass auth instance to use gRPC-fallback client in browser or other non-Node.js environments. Use OAuth2Client from google-auth-library.' ); } this.auth = options.auth as OAuth2Client; } else { this.auth = (options.auth as GoogleAuth) || new GoogleAuth(options as GoogleAuthOptions); } this.fallback = options.fallback !== 'rest' ? 'proto' : 'rest'; this.grpcVersion = require('../../package.json').version; } /** * gRPC-fallback version of loadProto * Loads the protobuf root object from a JSON object created from a proto file * @param {Object} jsonObject - A JSON version of a protofile created usin protobuf.js * @returns {Object} Root namespace of proto JSON */ loadProto(jsonObject: {}) { const rootObject = protobuf.Root.fromJSON(jsonObject); return rootObject; } loadProtoJSON(json: protobuf.INamespace, ignoreCache = false) { const hash = objectHash(json).toString(); const cached = GrpcClient.protoCache.get(hash); if (cached && !ignoreCache) { return cached; } const root = protobuf.Root.fromJSON(json); GrpcClient.protoCache.set(hash, root); return root; } private static getServiceMethods(service: protobuf.Service): ServiceMethods { const methods: {[name: string]: protobuf.Method} = {}; for (const [methodName, methodObject] of Object.entries(service.methods)) { const methodNameLowerCamelCase = methodName[0].toLowerCase() + methodName.substring(1); methods[methodNameLowerCamelCase] = methodObject; } return methods; } /** * gRPC-fallback version of constructSettings * A wrapper of {@link constructSettings} function under the gRPC context. * * Most of parameters are common among constructSettings, please take a look. * @param {string} serviceName - The fullly-qualified name of the service. * @param {Object} clientConfig - A dictionary of the client config. * @param {Object} configOverrides - A dictionary of overriding configs. * @param {Object} headers - A dictionary of additional HTTP header name to * its value. * @return {Object} A mapping of method names to CallSettings. */ constructSettings( serviceName: string, clientConfig: gax.ClientConfig, configOverrides: gax.ClientConfig, headers: OutgoingHttpHeaders ) { function buildMetadata(abTests: {}, moreHeaders: OutgoingHttpHeaders) { const metadata: OutgoingHttpHeaders = {}; if (!headers) { headers = {}; } // Since gRPC expects each header to be an array, // we are doing the same for fallback here. for (const key in headers) { metadata[key] = Array.isArray(headers[key]) ? (headers[key] as string[]) : ([headers[key]] as string[]); } // gRPC-fallback request must have 'grpc-web/' in 'x-goog-api-client' const clientVersions: string[] = []; if ( metadata[CLIENT_VERSION_HEADER] && ( metadata[CLIENT_VERSION_HEADER] as Array<string | number | string[]> )[0] ) { clientVersions.push( ...(metadata[CLIENT_VERSION_HEADER] as string[])[0].split(' ') ); } clientVersions.push(`grpc-web/${version}`); metadata[CLIENT_VERSION_HEADER] = [clientVersions.join(' ')]; if (!moreHeaders) { return metadata; } for (const key in moreHeaders) { if (key.toLowerCase() !== CLIENT_VERSION_HEADER) { const value = moreHeaders[key]; if (Array.isArray(value)) { if (metadata[key] === undefined) { metadata[key] = value; } else { if (Array.isArray(metadata[key])) { ( metadata[key]! as Array< string | number | string[] | undefined > ).push(...value); } else { throw new Error( `Can not add value ${value} to the call metadata.` ); } } } else { metadata[key] = [value] as string[]; } } } return metadata; } return gax.constructSettings( serviceName, clientConfig, configOverrides, Status, {metadataBuilder: buildMetadata} ); } /** * gRPC-fallback version of createStub * Creates a gRPC-fallback stub with authentication headers built from supplied OAuth2Client instance * * @param {function} CreateStub - The constructor function of the stub. * @param {Object} service - A protobufjs Service object (as returned by lookupService) * @param {Object} opts - Connection options, as described below. * @param {string} opts.servicePath - The hostname of the API endpoint service. * @param {number} opts.port - The port of the service. * @return {Promise} A promise which resolves to a gRPC-fallback service stub, which is a protobuf.js service stub instance modified to match the gRPC stub API */ async createStub( service: protobuf.Service, opts: ClientStubOptions, // For consistency with createStub in grpc.ts, customServicePath is defined: // eslint-disable-next-line @typescript-eslint/no-unused-vars customServicePath?: boolean ) { if (!this.authClient) { if (this.auth && 'getClient' in this.auth) { this.authClient = await this.auth.getClient(); } else if (this.auth && 'getRequestHeaders' in this.auth) { this.authClient = this.auth; } } if (!this.authClient) { throw new Error('No authentication was provided'); } service.resolveAll(); const methods = GrpcClient.getServiceMethods(service); const protocol = opts.protocol || 'https'; let servicePath = opts.servicePath; if ( !servicePath && service.options && service.options['(google.api.default_host)'] ) { servicePath = service.options['(google.api.default_host)']; } if (!servicePath) { throw new Error( `Cannot determine service API path for service ${service.name}.` ); } let servicePort; const match = servicePath!.match(/^(.*):(\d+)$/); if (match) { servicePath = match[1]; servicePort = parseInt(match[2]); } if (opts.port) { servicePort = opts.port; } else if (!servicePort) { servicePort = 443; } const encoder = this.fallback === 'rest' ? fallbackRest.encodeRequest : fallbackProto.encodeRequest; const decoder = this.fallback === 'rest' ? fallbackRest.decodeResponse : fallbackProto.decodeResponse; const serviceStub = generateServiceStub( methods, protocol, servicePath, servicePort, this.authClient, encoder, decoder ); return serviceStub; } } /** * gRPC-fallback version of lro * * @param {Object=} options.auth - An instance of google-auth-library. * @return {Object} A OperationsClientBuilder that will return a OperationsClient */ export function lro(options: GrpcClientOptions) { options = Object.assign({scopes: []}, options); const gaxGrpc = new GrpcClient(options); return new OperationsClientBuilder(gaxGrpc); } /** * gRPC-fallback version of createApiCall * * Converts an rpc call into an API call governed by the settings. * * In typical usage, `func` will be a promise to a callable used to make an rpc * request. This will mostly likely be a bound method from a request stub used * to make an rpc call. It is not a direct function but a Promise instance, * because of its asynchronism (typically, obtaining the auth information). * * The result is a function which manages the API call with the given settings * and the options on the invocation. * * Throws exception on unsupported streaming calls * * @param {Promise<GRPCCall>|GRPCCall} func - is either a promise to be used to make * a bare RPC call, or just a bare RPC call. * @param {CallSettings} settings - provides the settings for this call * @param {Descriptor} descriptor - optionally specify the descriptor for * the method call. * @return {GaxCall} func - a bound method on a request stub used * to make an rpc call. */ export function createApiCall( func: Promise<GRPCCall> | GRPCCall, settings: gax.CallSettings, descriptor?: Descriptor ): GaxCall { if ( descriptor && 'streaming' in descriptor && (descriptor as StreamDescriptor).type !== StreamType.SERVER_STREAMING ) { return () => { throw new Error( 'The gRPC-fallback client library (e.g. browser version of the library) currently does not support client-streaming or bidi-stream calls.' ); }; } return _createApiCall(func, settings, descriptor); } export {protobuf}; export * as protobufMinimal from 'protobufjs/minimal'; // Different environments or bundlers may or may not respect "browser" field // in package.json (e.g. Electron does not respect it, but if you run the code // through webpack first, it will follow the "browser" field). // To make it safer and more compatible, let's make sure that if you do // const gax = require("google-gax"); // you can always ask for gax.fallback, regardless of "browser" field being // understood or not. const fallback = module.exports; export {fallback};
the_stack
import { Nullable } from "../../../../../shared/types"; import * as React from "react"; import Slider from "antd/lib/slider"; import { InputGroup, Tooltip } from "@blueprintjs/core"; import { InspectorUtils } from "../utils"; import { InspectorNotifier } from "../notifier"; import { AbstractFieldComponent } from "./abstract-field"; export interface IInspectorNumberProps { /** * Defines the reference to the object to modify. */ object: any; /** * Defines the property to edit in the object. */ property: string; /** * Defines the label of the field. */ label: string; /** * Defines the step used when dragging the mouse. */ step?: number; /** * Defines the minimum value of the input. */ min?: number; /** * Defines the maximum value of the input. */ max?: number; /** * Defines wether or not the slider should be visible in case of a min and a max value. */ noSlider?: boolean; /** * Defines wether or not the label should be hidden. */ noLabel?: boolean; /** * Defines wether or not automatic undo/redo should be skipped. */ noUndoRedo?: boolean; /** * Defines the optional callback called on the value changes. * @param value defines the new value of the object's property. */ onChange?: (value: number) => void; /** * Defines the optional callack called on the value finished changes. * @param value defines the new value of the object's property. * @param oldValue defines the old value of the property before it has been changed. */ onFinishChange?: (value: number, oldValue: number) => void; } export interface IInspectorNumberState { /** * Defines the current value of the input. */ value: string; } export class InspectorNumber extends AbstractFieldComponent<IInspectorNumberProps, IInspectorNumberState> { private _mouseMoveListener: Nullable<(ev: MouseEvent) => any> = null; private _mouseUpListener: Nullable<(ev: MouseEvent) => any> = null; private _inspectorName: Nullable<string> = null; private _input: Nullable<HTMLInputElement> = null; private _impliedStep: number; private _precision: number; private _isFocused: boolean = false; private _lastMousePosition: number = 0; private _initialValue: number; private static _NumDecimals(value: number): number { const valueString = value.toString(); const dotIndex = valueString.indexOf("."); if (dotIndex > -1) { return valueString.length - dotIndex - 1; } return 0; } private static _RoundToDecimal(value: number, decimals: number): number { const tenTo = Math.pow(10, decimals); return Math.round(value * tenTo) / tenTo; } /** * Constructor. * @param props defines the component's props. */ public constructor(props: IInspectorNumberProps) { super(props); const value = props.object[props.property]; if (typeof (value) !== "number") { throw new Error("Only number are supported for InspectorNumber components."); } if (props.step) { this._impliedStep = props.step; } else { this._impliedStep = value === 0 ? 1 : Math.pow(10, Math.floor(Math.log(Math.abs(value)) / Math.LN10)) / 10; } this._precision = InspectorNumber._NumDecimals(this._impliedStep); this._initialValue = value; this.state = { value: value.toString() }; } /** * Renders the component. */ public render(): React.ReactNode { let sliderNode: React.ReactNode; if (this.props.min !== undefined && this.props.max !== undefined && !this.props.noSlider) { sliderNode = ( <div style={{ width: "55%", float: "left", padding: "0px 5px", marginTop: "0px" }}> <Slider key="min-max-slider" value={parseFloat(this.state.value)} min={this.props.min} max={this.props.max} step={this.props.step} onChange={(v) => this._handleSliderChanged(v)} onAfterChange={() => this._handleMouseUp()} /> </div> ); } let label: React.ReactNode; if (!this.props.noLabel) { label = ( <div style={{ width: "30%", height: "25px", float: "left", borderLeft: "3px solid #2FA1D6", padding: "0 4px 0 5px", overflow: "hidden" }}> <Tooltip content={this.props.label}> <span tabIndex={-1} style={{ lineHeight: "30px", textAlign: "center", whiteSpace: "nowrap" }}>{this.props.label}</span> </Tooltip> </div> ); } let widthPercent = "100%"; if (sliderNode && label) { widthPercent = "15%"; } else if (!sliderNode && label) { widthPercent = "70%"; } else if (sliderNode && !label) { widthPercent = "45%"; } return ( <div style={{ width: "100%", height: "25px" }}> {label} {sliderNode} <div style={{ width: widthPercent, height: "25px", float: "left", marginTop: "3px" }}> <InputGroup small={true} fill={true} value={this.state.value} type="number" step={this.props.step} onFocus={() => this._handleInputFocused()} onBlur={() => this._handleInputBlurred()} onKeyDown={(e) => e.key === "Enter" && this._handleEnterKeyPressed()} onChange={(e) => this._handleValueChanged(e.target.value, false)} onMouseDown={(ev) => this._handleInputClicked(ev)} inputRef={(ref) => this._input = ref} /> </div> </div> ); } /** * Called on the component did mount. */ public componentDidMount(): void { super.componentDidMount?.(); this._inspectorName = InspectorUtils.CurrentInspectorName; InspectorNotifier.Register(this, this.props.object, () => { this.setState({ value: this.props.object[this.props.property] }); }); } /** * Called on the component will unmount. */ public componentWillUnmount(): void { super.componentWillUnmount?.(); InspectorNotifier.Unregister(this); } /** * Called on the input is focused. */ private _handleInputFocused(): void { this._isFocused = true; } /** * Called on the input is blurred. */ private _handleInputBlurred(): void { this._isFocused = false; this._handleValueFinishChanged(); } /** * Called on the value changed in the input. */ private _handleValueChanged(value: string, fromMouseEvent: boolean): void { if (!value) { return this.setState({ value }); } let parsedValue = parseFloat(value); // Min / max if (this.props.min !== undefined && parsedValue < this.props.min) { parsedValue = this.props.min; } if (this.props.max !== undefined && parsedValue > this.props.max) { parsedValue = this.props.max; } // Set value this.props.object[this.props.property] = parsedValue; // Set state if (fromMouseEvent) { this.setState({ value: InspectorNumber._RoundToDecimal(parsedValue, this._precision).toString() }); } else { this.setState({ value }); } // Callback this.props.onChange?.(parsedValue); InspectorNotifier.NotifyChange(this.props.object[this.props.property], { caller: this }); } /** * Called on the slider value changed. */ private _handleSliderChanged(value: number): void { this._handleValueChanged(value.toString(), true); } /** * Called on the user clicked on the input. */ private _handleInputClicked(ev: React.MouseEvent<HTMLInputElement, MouseEvent>): void { if (!this._isFocused) { return; } this._lastMousePosition = ev.pageY; document.addEventListener("mousemove", this._mouseMoveListener = (ev) => { const delta = (this._lastMousePosition - ev.pageY); const newValue = this.props.object[this.props.property] + delta * this._impliedStep; this._handleValueChanged(newValue.toString(), true); this._lastMousePosition = ev.pageY; }); document.addEventListener("mouseup", this._mouseUpListener = () => { this._handleMouseUp(); }); } /** * Called on the mouse button is up on the document. */ private _handleMouseUp(): void { if (this._mouseMoveListener) { document.removeEventListener("mousemove", this._mouseMoveListener); } if (this._mouseUpListener) { document.removeEventListener("mouseup", this._mouseUpListener); } this._mouseMoveListener = null; this._mouseUpListener = null; this._handleValueFinishChanged(); } /** * Called on the value finished change. */ private _handleValueFinishChanged(): void { const value = this.props.object[this.props.property]; if (value === this._initialValue) { return; } this.props.onFinishChange?.(value, this._initialValue); InspectorNotifier.NotifyChange(this.props.object, { caller: this, }); InspectorUtils.NotifyInspectorChanged(this._inspectorName!, { newValue: value, object: this.props.object, oldValue: this._initialValue, property: this.props.property, noUndoRedo: this.props.noUndoRedo ?? false, }); this._initialValue = value; } /** * Called on the user presses the enter key. */ private _handleEnterKeyPressed(): void { this._input?.blur(); this._handleValueFinishChanged(); } }
the_stack
import { CoreBindings, createProxyWithInterceptors, GLOBAL_INTERCEPTOR_NAMESPACE, } from '@loopback/core'; import { RestApplication, RestServer, RestServerConfig, SequenceActions, } from '@loopback/rest'; import { Client, createRestAppClient, expect, givenHttpServerConfig, validateApiSpec, } from '@loopback/testlab'; import {MetricsBindings, MetricsComponent, MetricsOptions} from '../..'; import {metricsControllerFactory} from '../../controllers'; import {MetricsInterceptor} from '../../interceptors'; import {MetricsObserver, MetricsPushObserver} from '../../observers'; import {MockController} from './mock.controller'; describe('Metrics (acceptance)', () => { let app: RestApplication; let request: Client; afterEach(async () => { if (app) await app.stop(); (app as unknown) = undefined; }); context('with default config', () => { beforeEach(async () => { app = givenRestApplication(); app.component(MetricsComponent); await app.start(); request = createRestAppClient(app); }); it('exposes metrics at "/metrics/"', async () => { const res = await request .get('/metrics') .expect(200) .expect('content-type', /text/); expect(res.text).to.match(/# TYPE/); expect(res.text).to.match(/# HELP/); }); it('hides the metrics endpoints from the openapi spec', async () => { const server = await app.getServer(RestServer); const spec = await server.getApiSpec(); expect(spec.paths).to.be.empty(); await validateApiSpec(spec); }); it('adds MetricsObserver, MetricsInterceptor and MetricsController to the application', () => { expect( app.isBound( `${CoreBindings.LIFE_CYCLE_OBSERVERS}.${MetricsObserver.name}`, ), ).to.be.true(); expect( app.isBound( `${GLOBAL_INTERCEPTOR_NAMESPACE}.${MetricsInterceptor.name}`, ), ).to.be.true(); expect( app.isBound( `${CoreBindings.CONTROLLERS}.${metricsControllerFactory().name}`, ), ).to.be.true(); }); it('does not add MetricsPushObserver to the application', () => { expect( app.isBound( `${CoreBindings.LIFE_CYCLE_OBSERVERS}.${MetricsPushObserver.name}`, ), ).to.be.false(); }); }); context('with custom defaultMetrics', () => { it('honors prefix', async () => { await givenAppWithCustomConfig({ defaultMetrics: { // `-` is not allowed prefix: 'myapp_', }, }); await request.get('/metrics').expect(200).expect('content-type', /text/); }); }); context('with custom endpoint basePath', () => { it('honors prefix', async () => { await givenAppWithCustomConfig({ endpoint: { basePath: '/internal/metrics', }, }); await request .get('/internal/metrics') .expect(200) .expect('content-type', /text/); await request.get('/metrics').expect(404); }); }); context('with endpoint disabled', () => { beforeEach(async () => { await givenAppWithCustomConfig({ endpoint: { disabled: true, }, }); }); it('does not expose /metrics', async () => { await request.get('/metrics').expect(404); }); it('does not add MetricsController to the application', () => { expect( app.isBound( `${CoreBindings.CONTROLLERS}.${metricsControllerFactory().name}`, ), ).to.be.false(); }); }); context('with defaultMetrics disabled', () => { beforeEach(async () => { await givenAppWithCustomConfig({ defaultMetrics: { disabled: true, }, }); }); it('does not emit default metrics', async () => { const res = await request .get('/metrics') .expect(200) .expect('content-type', /text/); expect(res.text).to.not.match( /# TYPE process_cpu_user_seconds_total counter/, ); }); it('does not add MetricsObserver to the application', () => { expect( app.isBound( `${CoreBindings.LIFE_CYCLE_OBSERVERS}.${MetricsObserver.name}`, ), ).to.be.false(); }); }); context('with openApiSpec enabled', () => { beforeEach(async () => { await givenAppWithCustomConfig({ openApiSpec: true, }); }); it('adds the metrics endpoint to the openapi spec', async () => { const server = await app.getServer(RestServer); const spec = await server.getApiSpec(); expect(spec.paths).to.have.properties('/metrics'); await validateApiSpec(spec); }); }); context('with collected method invocation metrics', () => { beforeEach(async () => { await givenAppForMetricsCollection(); }); it('reports metrics with targetName label', async () => { await request.get('/success'); const res = await request .get('/metrics') .expect(200) .expect('content-type', /text/); expect(res.text).to.match( /targetName="MockController.prototype.success"/, ); }); it('reports metrics with method and path label', async () => { await request.get('/success'); await request.post('/success'); await request.put('/success'); await request.patch('/success'); await request.delete('/success'); const res = await request .get('/metrics') .expect(200) .expect('content-type', /text/); expect(res.text).to.match(/method="GET",path="\/success"/); expect(res.text).to.match(/method="POST",path="\/success"/); expect(res.text).to.match(/method="PUT",path="\/success"/); expect(res.text).to.match(/method="PATCH",path="\/success"/); expect(res.text).to.match(/method="DELETE",path="\/success"/); }); it('reports metrics with status code label', async () => { await request.get('/success-with-data').expect(200); await request.get('/success').expect(204); await request.get('/redirect').expect(302); await request.get('/bad-request').expect(400); await request.get('/entity-not-found').expect(404); await request.get('/server-error').expect(500); const res = await request .get('/metrics') .expect(200) .expect('content-type', /text/); expect(res.text).to.match(/path="\/success-with-data",statusCode="200"/); expect(res.text).to.match(/path="\/success",statusCode="204"/); expect(res.text).to.match(/path="\/redirect",statusCode="302"/); expect(res.text).to.match(/path="\/bad-request",statusCode="400"/); expect(res.text).to.match(/path="\/entity-not-found",statusCode="404"/); expect(res.text).to.match(/path="\/server-error",statusCode="500"/); }); it('adds the labels to all metric types', async () => { await request.get('/success').expect(204); const res = await request .get('/metrics') .expect(200) .expect('content-type', /text/); expect(res.text).to.match( /loopback_invocation_duration_seconds{targetName="MockController.prototype.success",method="GET",path="\/success",statusCode="204"}/, ); expect(res.text).to.match( /loopback_invocation_duration_histogram_bucket{le="0.01",targetName="MockController.prototype.success",method="GET",path="\/success",statusCode="204"}/, ); expect(res.text).to.match( /loopback_invocation_total{targetName="MockController.prototype.success",method="GET",path="\/success",statusCode="204"}/, ); expect(res.text).to.match( /loopback_invocation_duration_summary{quantile="0.01",targetName="MockController.prototype.success",method="GET",path="\/success",statusCode="204"}/, ); }); it('uses the path pattern instead of the raw path in path labels', async () => { await request.get('/path/1'); await request.get('/path/1/2'); const res = await request .get('/metrics') .expect(200) .expect('content-type', /text/); expect(res.text).to.match(/path="\/path\/{param}"/); expect(res.text).to.match(/path="\/path\/{firstParam}\/{secondParam}"/); }); it('only adds targetName label if the invocation source is an interception proxy', async () => { const proxy = createProxyWithInterceptors(new MockController(), app); await proxy.success(); const res = await request .get('/metrics') .expect(200) .expect('content-type', /text/); expect(res.text).to.match( /targetName="MockController.prototype.success"/, ); expect(res.text).to.not.match(/method=/); expect(res.text).to.not.match(/path=/); expect(res.text).to.not.match(/statusCode=/); }); }); context('with configured default labels', () => { beforeEach(async () => { await givenAppForMetricsCollection({ defaultLabels: { service: 'api', version: '1.0.0', }, }); }); it('adds static labels to default metrics', async () => { const res = await request .get('/metrics') .expect(200) .expect('content-type', /text/); expect(res.text).to.match( /process_cpu_user_seconds_total{service="api",version="1.0.0"}/, ); }); it('adds static labels to method invocation metrics', async () => { await request.get('/success').expect(204); const res = await request .get('/metrics') .expect(200) .expect('content-type', /text/); expect(res.text).to.match( /loopback_invocation_total{targetName="MockController.prototype.success",method="GET",path="\/success",statusCode="204",service="api",version="1.0.0"}/, ); }); }); async function givenAppWithCustomConfig(config: MetricsOptions) { app = givenRestApplication(); app.configure(MetricsBindings.COMPONENT).to(config); app.component(MetricsComponent); await app.start(); request = createRestAppClient(app); } async function givenAppForMetricsCollection(config?: MetricsOptions) { app = givenRestApplication(); app.configure(MetricsBindings.COMPONENT).to(config); app.component(MetricsComponent); app.controller(MockController); app.bind(SequenceActions.LOG_ERROR).to(() => {}); await app.start(); request = createRestAppClient(app); } function givenRestApplication(config?: RestServerConfig) { const rest = Object.assign({}, givenHttpServerConfig(), config); return new RestApplication({rest}); } });
the_stack
import { assert } from 'chai' import feathersVuex, { models } from '../../src/index' import { clearModels } from '../../src/service-module/global-models' import { feathersRestClient as feathersClient } from '../fixtures/feathers-client' import Vuex from 'vuex' describe('Models - `setupInstance` & Relatioships', function () { beforeEach(function () { clearModels() }) it('initializes instance with return value from setupInstance', function () { let calledSetupInstance = false const { makeServicePlugin, BaseModel } = feathersVuex(feathersClient, { serverAlias: 'myApi' }) class Todo extends BaseModel { public static modelName = 'Todo' public id? public description: string public constructor(data, options?) { super(data, options) } } function setupInstance(instance, { models, store }): Todo { calledSetupInstance = true return Object.assign(instance, { extraProp: true }) } const store = new Vuex.Store({ strict: true, plugins: [ makeServicePlugin({ Model: Todo, service: feathersClient.service('service-todos'), setupInstance }) ] }) const createdAt = '2018-05-01T04:42:24.136Z' const todo = new Todo({ description: 'Go on a date.', isComplete: true, createdAt }) assert(calledSetupInstance, 'setupInstance was called') assert(todo.extraProp, 'got the extraProp') }) it('allows setting up relationships between models and other constructors', function () { const { makeServicePlugin, BaseModel } = feathersVuex(feathersClient, { serverAlias: 'myApi' }) class Todo extends BaseModel { public static modelName = 'Todo' public id? public description: string public user: User public constructor(data, options?) { super(data, options) } } class User extends BaseModel { public static modelName = 'User' public _id: string public firstName: string public email: string } function setupInstance(instance, { models, store }): Todo { const { User } = models.myApi return Object.assign(instance, { // If instance.user exists, convert it to a User instance ...(instance.user && { user: new User(instance.user) }), // If instance.createdAt exists, convert it to an actual date ...(instance.createdAt && { createdAt: new Date(instance.createdAt) }) }) } const store = new Vuex.Store({ strict: true, plugins: [ makeServicePlugin({ Model: Todo, service: feathersClient.service('service-todos'), setupInstance }), makeServicePlugin({ Model: User, service: feathersClient.service('users'), idField: '_id' }) ] }) const todo = new Todo({ description: `Show Master Splinter what's up.`, isComplete: true, createdAt: '2018-05-01T04:42:24.136Z', user: { _id: 1, firstName: 'Michaelangelo', email: 'mike@tmnt.com' } }) // Check the date assert( typeof todo.createdAt === 'object', 'module.createdAt is an instance of object' ) assert( todo.createdAt.constructor.name === 'Date', 'module.createdAt is an instance of date' ) // Check the user assert(todo.user instanceof User, 'the user is an instance of User') const user = User.getFromStore(1) assert.equal(todo.user, user, 'user was added to the user store.') }) }) function makeContext() { const { makeServicePlugin, BaseModel } = feathersVuex(feathersClient, { serverAlias: 'myApi' }) class Task extends BaseModel { public static modelName = 'Task' public static instanceDefaults() { return { id: null, description: '', isComplete: false } } public constructor(data, options?) { super(data, options) } } /** * This Model demonstrates how to use a dynamic set of instanceDefaults based on incoming data. */ class Todo extends BaseModel { public static modelName = 'Todo' public static instanceDefaults(data) { const priority = data.priority || 'normal' const defaultsByPriority = { normal: { description: '', isComplete: false, priority: '' }, high: { isHighPriority: true, priority: '' } } return defaultsByPriority[priority] } public static setupInstance(data, { models, store }) { const { Task, Item } = models.myApi return Object.assign(data, { ...(data.task && { task: new Task(data.task) }), ...(data.item && { item: new Item(data.item) }), ...(data.items && { items: data.items.map(item => new Item(item)) }) }) } public constructor(data, options?) { super(data, options) } } class Item extends BaseModel { public static modelName = 'Item' public get todos() { return BaseModel.models.Todo.findInStore({ query: {} }).data } public static instanceDefaults() { return { test: false, todo: 'Todo' } } public static setupInstance(data, { models, store }) { const { Todo } = models.myApi return Object.assign(data, { ...(data.todo && { todo: new Todo(data.todo) }) }) } public constructor(data, options?) { super(data, options) } } const store = new Vuex.Store({ strict: true, plugins: [ makeServicePlugin({ Model: Task, service: feathersClient.service('tasks') }), makeServicePlugin({ Model: Todo, service: feathersClient.service('service-todos') }), makeServicePlugin({ Model: Item, service: feathersClient.service('items'), mutations: { toggleTestBoolean(state, item) { item.test = !item.test } } }) ] }) return { makeServicePlugin, BaseModel, store, Todo, Task, Item } } describe('Models - Relationships', function () { beforeEach(function () { clearModels() }) it('can have different instanceDefaults based on new instance data', function () { const { Todo } = makeContext() const normalTodo = new Todo({ description: 'Normal' }) const highPriorityTodo = new Todo({ description: 'High Priority', priority: 'high' }) assert( !normalTodo.hasOwnProperty('isHighPriority'), 'Normal todos do not have an isHighPriority default attribute' ) assert( highPriorityTodo.isHighPriority, 'High priority todos have a unique attribute' ) }) it('adds model instances containing an id to the store', function () { const { Todo, Task } = makeContext() const todo = new Todo({ task: { id: 1, description: 'test', isComplete: true } }) assert.deepEqual( Task.getFromStore(1), todo.task, 'task was added to the store' ) }) it('works with multiple keys that match Model names', function () { const { Todo, Task, Item } = makeContext() const todo = new Todo({ task: { id: 1, description: 'test', isComplete: true }, item: { id: 2, test: true } }) assert.deepEqual( Task.getFromStore(1), todo.task, 'task was added to the store' ) assert.deepEqual( Item.getFromStore(2), todo.item, 'item was added to the store' ) }) it('handles nested relationships', function () { const { Todo } = makeContext() const todo = new Todo({ task: { id: 1, description: 'test', isComplete: true }, item: { id: 2, test: true, todo: { description: 'nested todo under item' } } }) assert( todo.item.todo.constructor.name === 'Todo', 'the nested todo is an instance of Todo' ) }) it('handles circular nested relationships', function () { const { Todo, Item } = makeContext() const todo = new Todo({ id: 1, description: 'todo description', item: { id: 2, test: true, todo: { id: 1, description: 'todo description' } } }) assert.deepEqual(Todo.getFromStore(1), todo, 'todo was added to the store') assert.deepEqual( Item.getFromStore(2), todo.item, 'item was added to the store' ) assert(todo.item, 'todo still has an item') assert(todo.item.todo, 'todo still nested in itself') }) it('updates related data', function () { const { Todo, Item, store } = makeContext() const module = new Todo({ id: 'todo-1', description: 'todo description', item: { id: 'item-2', test: true, todo: { id: 'todo-1', description: 'todo description' } } }) const storedTodo = Todo.getFromStore('todo-1') const storedItem = Item.getFromStore('item-2') store.commit('items/toggleTestBoolean', storedItem) // module.item.test = false assert.equal( module.item.test, false, 'the nested module.item.test should be false' ) assert.equal( storedTodo.item.test, false, 'the nested item.test should be false' ) assert.equal(storedItem.test, false, 'item.test should be false') }) it(`allows creating more than once relational instance`, function () { const { Todo, Item } = makeContext() const todo1 = new Todo({ id: 'todo-1', description: 'todo description', item: { id: 'item-2', test: true } }) const todo2 = new Todo({ id: 'todo-2', description: 'todo description', item: { id: 'item-3', test: true } }) const storedTodo = Todo.getFromStore('todo-1') const storedItem = Item.getFromStore('item-2') assert.equal( todo1.item.test, true, 'the nested module.item.test should be true' ) assert.equal( todo2.item.test, true, 'the nested module.item.test should be true' ) assert.equal( storedTodo.item.test, true, 'the nested item.test should be true' ) assert.equal(storedItem.test, true, 'item.test should be true') }) it(`handles arrays of related data`, function () { const { Todo, Item } = makeContext() const todo1 = new Todo({ id: 'todo-1', description: 'todo description', items: [ { id: 'item-1', test: true }, { id: 'item-2', test: true } ] }) const todo2 = new Todo({ id: 'todo-2', description: 'todo description', items: [ { id: 'item-3', test: true }, { id: 'item-4', test: true } ] }) assert(todo1, 'todo1 is an instance') assert(todo2, 'todo2 is an instance') const storedTodo1 = Todo.getFromStore('todo-1') const storedTodo2 = Todo.getFromStore('todo-2') const storedItem1 = Item.getFromStore('item-1') const storedItem2 = Item.getFromStore('item-2') const storedItem3 = Item.getFromStore('item-3') const storedItem4 = Item.getFromStore('item-4') assert(storedTodo1, 'should have todo 1') assert(storedTodo2, 'should have todo 2') assert(storedItem1, 'should have item 1') assert(storedItem2, 'should have item 2') assert(storedItem3, 'should have item 3') assert(storedItem4, 'should have item 4') }) it('preserves relationships on clone', function () { const { Todo, Task } = makeContext() const todo = new Todo({ task: { id: 1, description: 'test', isComplete: true } }) const clone = todo.clone() assert(clone.task instanceof Task, 'nested task is a Task') }) it('preserves relationships on commit', function () { const { Todo, Task } = makeContext() const todo = new Todo({ task: { id: 1, description: 'test', isComplete: true } }) const clone = todo.clone() const original = clone.commit() assert(original.task instanceof Task, 'nested task is a Task') }) it('preserves relationship with nested data clone and commit', function () { const { Todo } = makeContext() const todo = new Todo({ task: { id: 1, description: 'test', isComplete: true } }) // Create a clone of the nested task, modify and commit. const taskClone = todo.task.clone() taskClone.isComplete = false taskClone.commit() assert.equal(todo.task.isComplete, false, 'preserved after clone') }) it('returns the same object when an instance is cloned twice', function () { const { Todo } = makeContext() const todo = new Todo({ task: { id: 1, description: 'test', isComplete: true } }) const clone1 = todo.clone() const clone2 = todo.clone() assert(clone1 === clone2, 'there should only ever be one clone in memory for an instance with the same id') }) it('on clone, nested instances do not get cloned', function () { const { Todo } = makeContext() const todo = new Todo({ task: { id: 1, description: 'test', isComplete: true } }) const todoClone = todo.clone() assert(todoClone.task.__isClone === undefined, 'todo.task should still be the original item and not the clone') }) it('on nested commit in instance, original nested instances get updated', function () { const { Todo } = makeContext() const todo = new Todo({ task: { id: 1, description: 'test', isComplete: true } }) const taskClone = todo.task.clone() taskClone.description = 'changed' taskClone.commit() assert(todo.task.description === 'changed', 'the nested task should have been updated') }) it('nested instances get updated in clones and original records', function () { const { Todo } = makeContext() const todo = new Todo({ task: { id: 1, description: 'test', isComplete: true } }) const todoClone = todo.clone() assert(todo.task === todoClone.task, 'the same task instance should be in both the original and clone') }) })
the_stack
declare module com { export module google { export module android { export module gms { export module config { export module proto { export class Config { public static class: java.lang.Class<com.google.android.gms.config.proto.Config>; public static registerAllExtensions(param0: com.google.protobuf.ExtensionRegistryLite): void; } export module Config { export class AppConfigTable extends com.google.protobuf.GeneratedMessageLite<com.google.android.gms.config.proto.Config.AppConfigTable,com.google.android.gms.config.proto.Config.AppConfigTable.Builder> implements com.google.android.gms.config.proto.Config.AppConfigTableOrBuilder { public static class: java.lang.Class<com.google.android.gms.config.proto.Config.AppConfigTable>; public static APP_NAME_FIELD_NUMBER: number; public static NAMESPACE_CONFIG_FIELD_NUMBER: number; public static EXPERIMENT_PAYLOAD_FIELD_NUMBER: number; public getNamespaceConfigList(): java.util.List<com.google.android.gms.config.proto.Config.AppNamespaceConfigTable>; public static parseFrom(param0: com.google.protobuf.CodedInputStream): com.google.android.gms.config.proto.Config.AppConfigTable; public getExperimentPayloadList(): java.util.List<com.google.protobuf.ByteString>; public getExperimentPayloadCount(): number; public static newBuilder(): com.google.android.gms.config.proto.Config.AppConfigTable.Builder; public getAppNameBytes(): com.google.protobuf.ByteString; public static newBuilder(param0: com.google.android.gms.config.proto.Config.AppConfigTable): com.google.android.gms.config.proto.Config.AppConfigTable.Builder; public static parseFrom(param0: com.google.protobuf.ByteString): com.google.android.gms.config.proto.Config.AppConfigTable; public writeTo(param0: com.google.protobuf.CodedOutputStream): void; public static parseFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.android.gms.config.proto.Config.AppConfigTable; public static parseFrom(param0: com.google.protobuf.CodedInputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.android.gms.config.proto.Config.AppConfigTable; public hasAppName(): boolean; public getExperimentPayload(param0: number): com.google.protobuf.ByteString; public static parseDelimitedFrom(param0: java.io.InputStream): com.google.android.gms.config.proto.Config.AppConfigTable; public getAppName(): string; public getNamespaceConfigOrBuilderList(): java.util.List<any>; public getNamespaceConfigCount(): number; public static parseFrom(param0: native.Array<number>): com.google.android.gms.config.proto.Config.AppConfigTable; public static parseFrom(param0: com.google.protobuf.ByteString, param1: com.google.protobuf.ExtensionRegistryLite): com.google.android.gms.config.proto.Config.AppConfigTable; public getNamespaceConfigOrBuilder(param0: number): com.google.android.gms.config.proto.Config.AppNamespaceConfigTableOrBuilder; public dynamicMethod(param0: com.google.protobuf.GeneratedMessageLite.MethodToInvoke, param1: any, param2: any): any; public static getDefaultInstance(): com.google.android.gms.config.proto.Config.AppConfigTable; public static parser(): com.google.protobuf.Parser<com.google.android.gms.config.proto.Config.AppConfigTable>; public static parseFrom(param0: java.io.InputStream): com.google.android.gms.config.proto.Config.AppConfigTable; public static parseFrom(param0: native.Array<number>, param1: com.google.protobuf.ExtensionRegistryLite): com.google.android.gms.config.proto.Config.AppConfigTable; public getSerializedSize(): number; public getNamespaceConfig(param0: number): com.google.android.gms.config.proto.Config.AppNamespaceConfigTable; public static parseDelimitedFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.android.gms.config.proto.Config.AppConfigTable; } export module AppConfigTable { export class Builder extends com.google.protobuf.GeneratedMessageLite.Builder<com.google.android.gms.config.proto.Config.AppConfigTable,com.google.android.gms.config.proto.Config.AppConfigTable.Builder> implements com.google.android.gms.config.proto.Config.AppConfigTableOrBuilder { public static class: java.lang.Class<com.google.android.gms.config.proto.Config.AppConfigTable.Builder>; public addAllExperimentPayload(param0: java.lang.Iterable<any>): com.google.android.gms.config.proto.Config.AppConfigTable.Builder; public getExperimentPayloadCount(): number; public setExperimentPayload(param0: number, param1: com.google.protobuf.ByteString): com.google.android.gms.config.proto.Config.AppConfigTable.Builder; public getNamespaceConfigCount(): number; public clearExperimentPayload(): com.google.android.gms.config.proto.Config.AppConfigTable.Builder; public getNamespaceConfigList(): java.util.List<com.google.android.gms.config.proto.Config.AppNamespaceConfigTable>; public addExperimentPayload(param0: com.google.protobuf.ByteString): com.google.android.gms.config.proto.Config.AppConfigTable.Builder; public setNamespaceConfig(param0: number, param1: com.google.android.gms.config.proto.Config.AppNamespaceConfigTable.Builder): com.google.android.gms.config.proto.Config.AppConfigTable.Builder; public setAppNameBytes(param0: com.google.protobuf.ByteString): com.google.android.gms.config.proto.Config.AppConfigTable.Builder; public addNamespaceConfig(param0: com.google.android.gms.config.proto.Config.AppNamespaceConfigTable): com.google.android.gms.config.proto.Config.AppConfigTable.Builder; public hasAppName(): boolean; public getAppNameBytes(): com.google.protobuf.ByteString; public removeNamespaceConfig(param0: number): com.google.android.gms.config.proto.Config.AppConfigTable.Builder; public setNamespaceConfig(param0: number, param1: com.google.android.gms.config.proto.Config.AppNamespaceConfigTable): com.google.android.gms.config.proto.Config.AppConfigTable.Builder; public addNamespaceConfig(param0: number, param1: com.google.android.gms.config.proto.Config.AppNamespaceConfigTable): com.google.android.gms.config.proto.Config.AppConfigTable.Builder; public getNamespaceConfig(param0: number): com.google.android.gms.config.proto.Config.AppNamespaceConfigTable; public setAppName(param0: string): com.google.android.gms.config.proto.Config.AppConfigTable.Builder; public clearAppName(): com.google.android.gms.config.proto.Config.AppConfigTable.Builder; public getAppName(): string; public addNamespaceConfig(param0: number, param1: com.google.android.gms.config.proto.Config.AppNamespaceConfigTable.Builder): com.google.android.gms.config.proto.Config.AppConfigTable.Builder; public addNamespaceConfig(param0: com.google.android.gms.config.proto.Config.AppNamespaceConfigTable.Builder): com.google.android.gms.config.proto.Config.AppConfigTable.Builder; public getExperimentPayload(param0: number): com.google.protobuf.ByteString; public clearNamespaceConfig(): com.google.android.gms.config.proto.Config.AppConfigTable.Builder; public getExperimentPayloadList(): java.util.List<com.google.protobuf.ByteString>; public addAllNamespaceConfig(param0: java.lang.Iterable<any>): com.google.android.gms.config.proto.Config.AppConfigTable.Builder; } } export class AppConfigTableOrBuilder { public static class: java.lang.Class<com.google.android.gms.config.proto.Config.AppConfigTableOrBuilder>; /** * Constructs a new instance of the com.google.android.gms.config.proto.Config$AppConfigTableOrBuilder interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { hasAppName(): boolean; getAppName(): string; getAppNameBytes(): com.google.protobuf.ByteString; getNamespaceConfigList(): java.util.List<com.google.android.gms.config.proto.Config.AppNamespaceConfigTable>; getNamespaceConfig(param0: number): com.google.android.gms.config.proto.Config.AppNamespaceConfigTable; getNamespaceConfigCount(): number; getExperimentPayloadList(): java.util.List<com.google.protobuf.ByteString>; getExperimentPayloadCount(): number; getExperimentPayload(param0: number): com.google.protobuf.ByteString; }); public constructor(); public getNamespaceConfigList(): java.util.List<com.google.android.gms.config.proto.Config.AppNamespaceConfigTable>; public getExperimentPayloadList(): java.util.List<com.google.protobuf.ByteString>; public getExperimentPayloadCount(): number; public hasAppName(): boolean; public getNamespaceConfig(param0: number): com.google.android.gms.config.proto.Config.AppNamespaceConfigTable; public getExperimentPayload(param0: number): com.google.protobuf.ByteString; public getAppName(): string; public getNamespaceConfigCount(): number; public getAppNameBytes(): com.google.protobuf.ByteString; } export class AppNamespaceConfigTable extends com.google.protobuf.GeneratedMessageLite<com.google.android.gms.config.proto.Config.AppNamespaceConfigTable,com.google.android.gms.config.proto.Config.AppNamespaceConfigTable.Builder> implements com.google.android.gms.config.proto.Config.AppNamespaceConfigTableOrBuilder { public static class: java.lang.Class<com.google.android.gms.config.proto.Config.AppNamespaceConfigTable>; public static NAMESPACE_FIELD_NUMBER: number; public static DIGEST_FIELD_NUMBER: number; public static ENTRY_FIELD_NUMBER: number; public static STATUS_FIELD_NUMBER: number; public getNamespaceBytes(): com.google.protobuf.ByteString; public static getDefaultInstance(): com.google.android.gms.config.proto.Config.AppNamespaceConfigTable; public getEntryList(): java.util.List<com.google.android.gms.config.proto.Config.KeyValue>; public getEntry(param0: number): com.google.android.gms.config.proto.Config.KeyValue; public static parseDelimitedFrom(param0: java.io.InputStream): com.google.android.gms.config.proto.Config.AppNamespaceConfigTable; public static parseFrom(param0: com.google.protobuf.CodedInputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.android.gms.config.proto.Config.AppNamespaceConfigTable; public static parseFrom(param0: java.io.InputStream): com.google.android.gms.config.proto.Config.AppNamespaceConfigTable; public static parseFrom(param0: native.Array<number>, param1: com.google.protobuf.ExtensionRegistryLite): com.google.android.gms.config.proto.Config.AppNamespaceConfigTable; public static parseFrom(param0: com.google.protobuf.ByteString, param1: com.google.protobuf.ExtensionRegistryLite): com.google.android.gms.config.proto.Config.AppNamespaceConfigTable; public static parseFrom(param0: native.Array<number>): com.google.android.gms.config.proto.Config.AppNamespaceConfigTable; public static parseFrom(param0: com.google.protobuf.ByteString): com.google.android.gms.config.proto.Config.AppNamespaceConfigTable; public getNamespace(): string; public getStatus(): com.google.android.gms.config.proto.Config.AppNamespaceConfigTable.NamespaceStatus; public hasStatus(): boolean; public writeTo(param0: com.google.protobuf.CodedOutputStream): void; public getEntryOrBuilderList(): java.util.List<any>; public getEntryCount(): number; public static parseFrom(param0: com.google.protobuf.CodedInputStream): com.google.android.gms.config.proto.Config.AppNamespaceConfigTable; public getDigestBytes(): com.google.protobuf.ByteString; public static newBuilder(param0: com.google.android.gms.config.proto.Config.AppNamespaceConfigTable): com.google.android.gms.config.proto.Config.AppNamespaceConfigTable.Builder; public hasNamespace(): boolean; public static parseDelimitedFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.android.gms.config.proto.Config.AppNamespaceConfigTable; public dynamicMethod(param0: com.google.protobuf.GeneratedMessageLite.MethodToInvoke, param1: any, param2: any): any; public getDigest(): string; public static parseFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.android.gms.config.proto.Config.AppNamespaceConfigTable; public static newBuilder(): com.google.android.gms.config.proto.Config.AppNamespaceConfigTable.Builder; public getSerializedSize(): number; public static parser(): com.google.protobuf.Parser<com.google.android.gms.config.proto.Config.AppNamespaceConfigTable>; public hasDigest(): boolean; public getEntryOrBuilder(param0: number): com.google.android.gms.config.proto.Config.KeyValueOrBuilder; } export module AppNamespaceConfigTable { export class Builder extends com.google.protobuf.GeneratedMessageLite.Builder<com.google.android.gms.config.proto.Config.AppNamespaceConfigTable,com.google.android.gms.config.proto.Config.AppNamespaceConfigTable.Builder> implements com.google.android.gms.config.proto.Config.AppNamespaceConfigTableOrBuilder { public static class: java.lang.Class<com.google.android.gms.config.proto.Config.AppNamespaceConfigTable.Builder>; public getEntryCount(): number; public setDigest(param0: string): com.google.android.gms.config.proto.Config.AppNamespaceConfigTable.Builder; public getNamespace(): string; public getDigestBytes(): com.google.protobuf.ByteString; public addEntry(param0: com.google.android.gms.config.proto.Config.KeyValue.Builder): com.google.android.gms.config.proto.Config.AppNamespaceConfigTable.Builder; public clearDigest(): com.google.android.gms.config.proto.Config.AppNamespaceConfigTable.Builder; public setStatus(param0: com.google.android.gms.config.proto.Config.AppNamespaceConfigTable.NamespaceStatus): com.google.android.gms.config.proto.Config.AppNamespaceConfigTable.Builder; public setEntry(param0: number, param1: com.google.android.gms.config.proto.Config.KeyValue.Builder): com.google.android.gms.config.proto.Config.AppNamespaceConfigTable.Builder; public getNamespaceBytes(): com.google.protobuf.ByteString; public getEntryList(): java.util.List<com.google.android.gms.config.proto.Config.KeyValue>; public getStatus(): com.google.android.gms.config.proto.Config.AppNamespaceConfigTable.NamespaceStatus; public removeEntry(param0: number): com.google.android.gms.config.proto.Config.AppNamespaceConfigTable.Builder; public setNamespaceBytes(param0: com.google.protobuf.ByteString): com.google.android.gms.config.proto.Config.AppNamespaceConfigTable.Builder; public hasStatus(): boolean; public setEntry(param0: number, param1: com.google.android.gms.config.proto.Config.KeyValue): com.google.android.gms.config.proto.Config.AppNamespaceConfigTable.Builder; public addEntry(param0: number, param1: com.google.android.gms.config.proto.Config.KeyValue.Builder): com.google.android.gms.config.proto.Config.AppNamespaceConfigTable.Builder; public clearEntry(): com.google.android.gms.config.proto.Config.AppNamespaceConfigTable.Builder; public getEntry(param0: number): com.google.android.gms.config.proto.Config.KeyValue; public hasDigest(): boolean; public hasNamespace(): boolean; public addAllEntry(param0: java.lang.Iterable<any>): com.google.android.gms.config.proto.Config.AppNamespaceConfigTable.Builder; public getDigest(): string; public clearNamespace(): com.google.android.gms.config.proto.Config.AppNamespaceConfigTable.Builder; public addEntry(param0: number, param1: com.google.android.gms.config.proto.Config.KeyValue): com.google.android.gms.config.proto.Config.AppNamespaceConfigTable.Builder; public clearStatus(): com.google.android.gms.config.proto.Config.AppNamespaceConfigTable.Builder; public setNamespace(param0: string): com.google.android.gms.config.proto.Config.AppNamespaceConfigTable.Builder; public addEntry(param0: com.google.android.gms.config.proto.Config.KeyValue): com.google.android.gms.config.proto.Config.AppNamespaceConfigTable.Builder; public setDigestBytes(param0: com.google.protobuf.ByteString): com.google.android.gms.config.proto.Config.AppNamespaceConfigTable.Builder; } export class NamespaceStatus extends com.google.protobuf.Internal.EnumLite { public static class: java.lang.Class<com.google.android.gms.config.proto.Config.AppNamespaceConfigTable.NamespaceStatus>; public static UPDATE: com.google.android.gms.config.proto.Config.AppNamespaceConfigTable.NamespaceStatus; public static NO_TEMPLATE: com.google.android.gms.config.proto.Config.AppNamespaceConfigTable.NamespaceStatus; public static NO_CHANGE: com.google.android.gms.config.proto.Config.AppNamespaceConfigTable.NamespaceStatus; public static EMPTY_CONFIG: com.google.android.gms.config.proto.Config.AppNamespaceConfigTable.NamespaceStatus; public static NOT_AUTHORIZED: com.google.android.gms.config.proto.Config.AppNamespaceConfigTable.NamespaceStatus; public static UPDATE_VALUE: number; public static NO_TEMPLATE_VALUE: number; public static NO_CHANGE_VALUE: number; public static EMPTY_CONFIG_VALUE: number; public static NOT_AUTHORIZED_VALUE: number; public static values(): native.Array<com.google.android.gms.config.proto.Config.AppNamespaceConfigTable.NamespaceStatus>; public getNumber(): number; public static valueOf(param0: string): com.google.android.gms.config.proto.Config.AppNamespaceConfigTable.NamespaceStatus; public static internalGetValueMap(): com.google.protobuf.Internal.EnumLiteMap<com.google.android.gms.config.proto.Config.AppNamespaceConfigTable.NamespaceStatus>; public static valueOf(param0: number): com.google.android.gms.config.proto.Config.AppNamespaceConfigTable.NamespaceStatus; public static forNumber(param0: number): com.google.android.gms.config.proto.Config.AppNamespaceConfigTable.NamespaceStatus; } } export class AppNamespaceConfigTableOrBuilder { public static class: java.lang.Class<com.google.android.gms.config.proto.Config.AppNamespaceConfigTableOrBuilder>; /** * Constructs a new instance of the com.google.android.gms.config.proto.Config$AppNamespaceConfigTableOrBuilder interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { hasNamespace(): boolean; getNamespace(): string; getNamespaceBytes(): com.google.protobuf.ByteString; hasDigest(): boolean; getDigest(): string; getDigestBytes(): com.google.protobuf.ByteString; getEntryList(): java.util.List<com.google.android.gms.config.proto.Config.KeyValue>; getEntry(param0: number): com.google.android.gms.config.proto.Config.KeyValue; getEntryCount(): number; hasStatus(): boolean; getStatus(): com.google.android.gms.config.proto.Config.AppNamespaceConfigTable.NamespaceStatus; }); public constructor(); public getNamespace(): string; public getDigestBytes(): com.google.protobuf.ByteString; public getStatus(): com.google.android.gms.config.proto.Config.AppNamespaceConfigTable.NamespaceStatus; public hasStatus(): boolean; public getNamespaceBytes(): com.google.protobuf.ByteString; public getEntryList(): java.util.List<com.google.android.gms.config.proto.Config.KeyValue>; public getEntry(param0: number): com.google.android.gms.config.proto.Config.KeyValue; public hasNamespace(): boolean; public getEntryCount(): number; public hasDigest(): boolean; public getDigest(): string; } export class ConfigFetchRequest extends com.google.protobuf.GeneratedMessageLite<com.google.android.gms.config.proto.Config.ConfigFetchRequest,com.google.android.gms.config.proto.Config.ConfigFetchRequest.Builder> implements com.google.android.gms.config.proto.Config.ConfigFetchRequestOrBuilder { public static class: java.lang.Class<com.google.android.gms.config.proto.Config.ConfigFetchRequest>; public static CONFIG_FIELD_NUMBER: number; public static ANDROID_ID_FIELD_NUMBER: number; public static PACKAGE_DATA_FIELD_NUMBER: number; public static DEVICE_DATA_VERSION_INFO_FIELD_NUMBER: number; public static SECURITY_TOKEN_FIELD_NUMBER: number; public static CLIENT_VERSION_FIELD_NUMBER: number; public static GMS_CORE_VERSION_FIELD_NUMBER: number; public static API_LEVEL_FIELD_NUMBER: number; public static DEVICE_COUNTRY_FIELD_NUMBER: number; public static DEVICE_LOCALE_FIELD_NUMBER: number; public static DEVICE_TYPE_FIELD_NUMBER: number; public static DEVICE_SUBTYPE_FIELD_NUMBER: number; public static OS_VERSION_FIELD_NUMBER: number; public static DEVICE_TIMEZONE_ID_FIELD_NUMBER: number; public static newBuilder(): com.google.android.gms.config.proto.Config.ConfigFetchRequest.Builder; public getPackageDataCount(): number; public static parseFrom(param0: native.Array<number>, param1: com.google.protobuf.ExtensionRegistryLite): com.google.android.gms.config.proto.Config.ConfigFetchRequest; public getPackageData(param0: number): com.google.android.gms.config.proto.Config.PackageData; public hasApiLevel(): boolean; public getDeviceLocaleBytes(): com.google.protobuf.ByteString; public getSecurityToken(): number; public static parseFrom(param0: com.google.protobuf.CodedInputStream): com.google.android.gms.config.proto.Config.ConfigFetchRequest; public getPackageDataOrBuilderList(): java.util.List<any>; public getDeviceCountry(): string; public hasClientVersion(): boolean; public static parser(): com.google.protobuf.Parser<com.google.android.gms.config.proto.Config.ConfigFetchRequest>; public static parseFrom(param0: com.google.protobuf.CodedInputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.android.gms.config.proto.Config.ConfigFetchRequest; public getDeviceTimezoneId(): string; public getDeviceDataVersionInfo(): string; public getDeviceTimezoneIdBytes(): com.google.protobuf.ByteString; public dynamicMethod(param0: com.google.protobuf.GeneratedMessageLite.MethodToInvoke, param1: any, param2: any): any; public hasSecurityToken(): boolean; public hasDeviceSubtype(): boolean; public static parseFrom(param0: native.Array<number>): com.google.android.gms.config.proto.Config.ConfigFetchRequest; public getSerializedSize(): number; public getOsVersionBytes(): com.google.protobuf.ByteString; public getConfig(): com.google.android.gms.config.proto.Logs.AndroidConfigFetchProto; public hasOsVersion(): boolean; public getOsVersion(): string; public getDeviceCountryBytes(): com.google.protobuf.ByteString; public getDeviceType(): number; public static parseDelimitedFrom(param0: java.io.InputStream): com.google.android.gms.config.proto.Config.ConfigFetchRequest; public hasDeviceLocale(): boolean; public getPackageDataList(): java.util.List<com.google.android.gms.config.proto.Config.PackageData>; public hasDeviceCountry(): boolean; public hasConfig(): boolean; public static parseFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.android.gms.config.proto.Config.ConfigFetchRequest; public writeTo(param0: com.google.protobuf.CodedOutputStream): void; public getClientVersion(): number; public hasDeviceType(): boolean; public hasAndroidId(): boolean; public static parseFrom(param0: java.io.InputStream): com.google.android.gms.config.proto.Config.ConfigFetchRequest; public static newBuilder(param0: com.google.android.gms.config.proto.Config.ConfigFetchRequest): com.google.android.gms.config.proto.Config.ConfigFetchRequest.Builder; public getAndroidId(): number; public getPackageDataOrBuilder(param0: number): com.google.android.gms.config.proto.Config.PackageDataOrBuilder; public hasDeviceTimezoneId(): boolean; public getDeviceLocale(): string; public getDeviceDataVersionInfoBytes(): com.google.protobuf.ByteString; public hasGmsCoreVersion(): boolean; public getGmsCoreVersion(): number; public static getDefaultInstance(): com.google.android.gms.config.proto.Config.ConfigFetchRequest; public getDeviceSubtype(): number; public static parseFrom(param0: com.google.protobuf.ByteString): com.google.android.gms.config.proto.Config.ConfigFetchRequest; public getApiLevel(): number; public hasDeviceDataVersionInfo(): boolean; public static parseFrom(param0: com.google.protobuf.ByteString, param1: com.google.protobuf.ExtensionRegistryLite): com.google.android.gms.config.proto.Config.ConfigFetchRequest; public static parseDelimitedFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.android.gms.config.proto.Config.ConfigFetchRequest; } export module ConfigFetchRequest { export class Builder extends com.google.protobuf.GeneratedMessageLite.Builder<com.google.android.gms.config.proto.Config.ConfigFetchRequest,com.google.android.gms.config.proto.Config.ConfigFetchRequest.Builder> implements com.google.android.gms.config.proto.Config.ConfigFetchRequestOrBuilder { public static class: java.lang.Class<com.google.android.gms.config.proto.Config.ConfigFetchRequest.Builder>; public hasClientVersion(): boolean; public getOsVersion(): string; public clearPackageData(): com.google.android.gms.config.proto.Config.ConfigFetchRequest.Builder; public hasDeviceSubtype(): boolean; public setDeviceLocaleBytes(param0: com.google.protobuf.ByteString): com.google.android.gms.config.proto.Config.ConfigFetchRequest.Builder; public setDeviceLocale(param0: string): com.google.android.gms.config.proto.Config.ConfigFetchRequest.Builder; public setGmsCoreVersion(param0: number): com.google.android.gms.config.proto.Config.ConfigFetchRequest.Builder; public setConfig(param0: com.google.android.gms.config.proto.Logs.AndroidConfigFetchProto): com.google.android.gms.config.proto.Config.ConfigFetchRequest.Builder; public getDeviceType(): number; public getDeviceCountry(): string; public getDeviceCountryBytes(): com.google.protobuf.ByteString; public clearDeviceTimezoneId(): com.google.android.gms.config.proto.Config.ConfigFetchRequest.Builder; public getGmsCoreVersion(): number; public setOsVersion(param0: string): com.google.android.gms.config.proto.Config.ConfigFetchRequest.Builder; public clearOsVersion(): com.google.android.gms.config.proto.Config.ConfigFetchRequest.Builder; public hasConfig(): boolean; public setDeviceType(param0: number): com.google.android.gms.config.proto.Config.ConfigFetchRequest.Builder; public getDeviceTimezoneId(): string; public hasDeviceType(): boolean; public setConfig(param0: com.google.android.gms.config.proto.Logs.AndroidConfigFetchProto.Builder): com.google.android.gms.config.proto.Config.ConfigFetchRequest.Builder; public getAndroidId(): number; public getPackageDataCount(): number; public getDeviceLocale(): string; public clearDeviceType(): com.google.android.gms.config.proto.Config.ConfigFetchRequest.Builder; public clearDeviceDataVersionInfo(): com.google.android.gms.config.proto.Config.ConfigFetchRequest.Builder; public setDeviceCountryBytes(param0: com.google.protobuf.ByteString): com.google.android.gms.config.proto.Config.ConfigFetchRequest.Builder; public clearConfig(): com.google.android.gms.config.proto.Config.ConfigFetchRequest.Builder; public setDeviceSubtype(param0: number): com.google.android.gms.config.proto.Config.ConfigFetchRequest.Builder; public getSecurityToken(): number; public addPackageData(param0: com.google.android.gms.config.proto.Config.PackageData): com.google.android.gms.config.proto.Config.ConfigFetchRequest.Builder; public getDeviceTimezoneIdBytes(): com.google.protobuf.ByteString; public addPackageData(param0: number, param1: com.google.android.gms.config.proto.Config.PackageData.Builder): com.google.android.gms.config.proto.Config.ConfigFetchRequest.Builder; public setDeviceTimezoneIdBytes(param0: com.google.protobuf.ByteString): com.google.android.gms.config.proto.Config.ConfigFetchRequest.Builder; public removePackageData(param0: number): com.google.android.gms.config.proto.Config.ConfigFetchRequest.Builder; public setClientVersion(param0: number): com.google.android.gms.config.proto.Config.ConfigFetchRequest.Builder; public setDeviceTimezoneId(param0: string): com.google.android.gms.config.proto.Config.ConfigFetchRequest.Builder; public hasAndroidId(): boolean; public clearDeviceSubtype(): com.google.android.gms.config.proto.Config.ConfigFetchRequest.Builder; public hasDeviceCountry(): boolean; public hasApiLevel(): boolean; public hasDeviceDataVersionInfo(): boolean; public clearClientVersion(): com.google.android.gms.config.proto.Config.ConfigFetchRequest.Builder; public hasGmsCoreVersion(): boolean; public hasSecurityToken(): boolean; public getPackageDataList(): java.util.List<com.google.android.gms.config.proto.Config.PackageData>; public addPackageData(param0: number, param1: com.google.android.gms.config.proto.Config.PackageData): com.google.android.gms.config.proto.Config.ConfigFetchRequest.Builder; public getDeviceLocaleBytes(): com.google.protobuf.ByteString; public clearAndroidId(): com.google.android.gms.config.proto.Config.ConfigFetchRequest.Builder; public clearGmsCoreVersion(): com.google.android.gms.config.proto.Config.ConfigFetchRequest.Builder; public hasDeviceLocale(): boolean; public clearDeviceCountry(): com.google.android.gms.config.proto.Config.ConfigFetchRequest.Builder; public setAndroidId(param0: number): com.google.android.gms.config.proto.Config.ConfigFetchRequest.Builder; public setDeviceDataVersionInfo(param0: string): com.google.android.gms.config.proto.Config.ConfigFetchRequest.Builder; public setOsVersionBytes(param0: com.google.protobuf.ByteString): com.google.android.gms.config.proto.Config.ConfigFetchRequest.Builder; public mergeConfig(param0: com.google.android.gms.config.proto.Logs.AndroidConfigFetchProto): com.google.android.gms.config.proto.Config.ConfigFetchRequest.Builder; public setDeviceCountry(param0: string): com.google.android.gms.config.proto.Config.ConfigFetchRequest.Builder; public getConfig(): com.google.android.gms.config.proto.Logs.AndroidConfigFetchProto; public clearApiLevel(): com.google.android.gms.config.proto.Config.ConfigFetchRequest.Builder; public clearDeviceLocale(): com.google.android.gms.config.proto.Config.ConfigFetchRequest.Builder; public setDeviceDataVersionInfoBytes(param0: com.google.protobuf.ByteString): com.google.android.gms.config.proto.Config.ConfigFetchRequest.Builder; public setApiLevel(param0: number): com.google.android.gms.config.proto.Config.ConfigFetchRequest.Builder; public addAllPackageData(param0: java.lang.Iterable<any>): com.google.android.gms.config.proto.Config.ConfigFetchRequest.Builder; public clearSecurityToken(): com.google.android.gms.config.proto.Config.ConfigFetchRequest.Builder; public getDeviceSubtype(): number; public getOsVersionBytes(): com.google.protobuf.ByteString; public getDeviceDataVersionInfoBytes(): com.google.protobuf.ByteString; public setPackageData(param0: number, param1: com.google.android.gms.config.proto.Config.PackageData): com.google.android.gms.config.proto.Config.ConfigFetchRequest.Builder; public getClientVersion(): number; public hasOsVersion(): boolean; public addPackageData(param0: com.google.android.gms.config.proto.Config.PackageData.Builder): com.google.android.gms.config.proto.Config.ConfigFetchRequest.Builder; public getPackageData(param0: number): com.google.android.gms.config.proto.Config.PackageData; public getApiLevel(): number; public hasDeviceTimezoneId(): boolean; public setPackageData(param0: number, param1: com.google.android.gms.config.proto.Config.PackageData.Builder): com.google.android.gms.config.proto.Config.ConfigFetchRequest.Builder; public getDeviceDataVersionInfo(): string; public setSecurityToken(param0: number): com.google.android.gms.config.proto.Config.ConfigFetchRequest.Builder; } } export class ConfigFetchRequestOrBuilder { public static class: java.lang.Class<com.google.android.gms.config.proto.Config.ConfigFetchRequestOrBuilder>; /** * Constructs a new instance of the com.google.android.gms.config.proto.Config$ConfigFetchRequestOrBuilder interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { hasConfig(): boolean; getConfig(): com.google.android.gms.config.proto.Logs.AndroidConfigFetchProto; hasAndroidId(): boolean; getAndroidId(): number; getPackageDataList(): java.util.List<com.google.android.gms.config.proto.Config.PackageData>; getPackageData(param0: number): com.google.android.gms.config.proto.Config.PackageData; getPackageDataCount(): number; hasDeviceDataVersionInfo(): boolean; getDeviceDataVersionInfo(): string; getDeviceDataVersionInfoBytes(): com.google.protobuf.ByteString; hasSecurityToken(): boolean; getSecurityToken(): number; hasClientVersion(): boolean; getClientVersion(): number; hasGmsCoreVersion(): boolean; getGmsCoreVersion(): number; hasApiLevel(): boolean; getApiLevel(): number; hasDeviceCountry(): boolean; getDeviceCountry(): string; getDeviceCountryBytes(): com.google.protobuf.ByteString; hasDeviceLocale(): boolean; getDeviceLocale(): string; getDeviceLocaleBytes(): com.google.protobuf.ByteString; hasDeviceType(): boolean; getDeviceType(): number; hasDeviceSubtype(): boolean; getDeviceSubtype(): number; hasOsVersion(): boolean; getOsVersion(): string; getOsVersionBytes(): com.google.protobuf.ByteString; hasDeviceTimezoneId(): boolean; getDeviceTimezoneId(): string; getDeviceTimezoneIdBytes(): com.google.protobuf.ByteString; }); public constructor(); public getConfig(): com.google.android.gms.config.proto.Logs.AndroidConfigFetchProto; public getPackageDataCount(): number; public hasOsVersion(): boolean; public getOsVersion(): string; public getDeviceCountryBytes(): com.google.protobuf.ByteString; public getPackageData(param0: number): com.google.android.gms.config.proto.Config.PackageData; public hasApiLevel(): boolean; public getDeviceLocaleBytes(): com.google.protobuf.ByteString; public getDeviceType(): number; public getSecurityToken(): number; public hasDeviceLocale(): boolean; public getPackageDataList(): java.util.List<com.google.android.gms.config.proto.Config.PackageData>; public getDeviceCountry(): string; public hasClientVersion(): boolean; public hasDeviceCountry(): boolean; public hasConfig(): boolean; public getClientVersion(): number; public hasDeviceType(): boolean; public hasAndroidId(): boolean; public getDeviceTimezoneId(): string; public getAndroidId(): number; public hasDeviceTimezoneId(): boolean; public getDeviceDataVersionInfo(): string; public getDeviceLocale(): string; public getDeviceDataVersionInfoBytes(): com.google.protobuf.ByteString; public getDeviceTimezoneIdBytes(): com.google.protobuf.ByteString; public hasSecurityToken(): boolean; public hasGmsCoreVersion(): boolean; public hasDeviceSubtype(): boolean; public getGmsCoreVersion(): number; public getDeviceSubtype(): number; public getOsVersionBytes(): com.google.protobuf.ByteString; public getApiLevel(): number; public hasDeviceDataVersionInfo(): boolean; } export class ConfigFetchResponse extends com.google.protobuf.GeneratedMessageLite<com.google.android.gms.config.proto.Config.ConfigFetchResponse,com.google.android.gms.config.proto.Config.ConfigFetchResponse.Builder> implements com.google.android.gms.config.proto.Config.ConfigFetchResponseOrBuilder { public static class: java.lang.Class<com.google.android.gms.config.proto.Config.ConfigFetchResponse>; public static PACKAGE_TABLE_FIELD_NUMBER: number; public static STATUS_FIELD_NUMBER: number; public static INTERNAL_METADATA_FIELD_NUMBER: number; public static APP_CONFIG_FIELD_NUMBER: number; public static parseFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.android.gms.config.proto.Config.ConfigFetchResponse; public static parseFrom(param0: com.google.protobuf.ByteString, param1: com.google.protobuf.ExtensionRegistryLite): com.google.android.gms.config.proto.Config.ConfigFetchResponse; public getInternalMetadataList(): java.util.List<com.google.android.gms.config.proto.Config.KeyValue>; public getInternalMetadataOrBuilder(param0: number): com.google.android.gms.config.proto.Config.KeyValueOrBuilder; public getAppConfigCount(): number; public static parseDelimitedFrom(param0: java.io.InputStream): com.google.android.gms.config.proto.Config.ConfigFetchResponse; public getPackageTableList(): java.util.List<com.google.android.gms.config.proto.Config.PackageTable>; public getAppConfigList(): java.util.List<com.google.android.gms.config.proto.Config.AppConfigTable>; public static getDefaultInstance(): com.google.android.gms.config.proto.Config.ConfigFetchResponse; public static parseFrom(param0: native.Array<number>): com.google.android.gms.config.proto.Config.ConfigFetchResponse; public getAppConfigOrBuilderList(): java.util.List<any>; public hasStatus(): boolean; public getPackageTable(param0: number): com.google.android.gms.config.proto.Config.PackageTable; public writeTo(param0: com.google.protobuf.CodedOutputStream): void; public static parseFrom(param0: com.google.protobuf.CodedInputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.android.gms.config.proto.Config.ConfigFetchResponse; public getPackageTableCount(): number; public getInternalMetadataCount(): number; public static parseFrom(param0: com.google.protobuf.CodedInputStream): com.google.android.gms.config.proto.Config.ConfigFetchResponse; public static parseFrom(param0: java.io.InputStream): com.google.android.gms.config.proto.Config.ConfigFetchResponse; public getAppConfig(param0: number): com.google.android.gms.config.proto.Config.AppConfigTable; public getPackageTableOrBuilder(param0: number): com.google.android.gms.config.proto.Config.PackageTableOrBuilder; public getStatus(): com.google.android.gms.config.proto.Config.ConfigFetchResponse.ResponseStatus; public getAppConfigOrBuilder(param0: number): com.google.android.gms.config.proto.Config.AppConfigTableOrBuilder; public static parseFrom(param0: com.google.protobuf.ByteString): com.google.android.gms.config.proto.Config.ConfigFetchResponse; public dynamicMethod(param0: com.google.protobuf.GeneratedMessageLite.MethodToInvoke, param1: any, param2: any): any; public static parser(): com.google.protobuf.Parser<com.google.android.gms.config.proto.Config.ConfigFetchResponse>; public static parseFrom(param0: native.Array<number>, param1: com.google.protobuf.ExtensionRegistryLite): com.google.android.gms.config.proto.Config.ConfigFetchResponse; public getInternalMetadata(param0: number): com.google.android.gms.config.proto.Config.KeyValue; public getSerializedSize(): number; public static newBuilder(): com.google.android.gms.config.proto.Config.ConfigFetchResponse.Builder; public getPackageTableOrBuilderList(): java.util.List<any>; public getInternalMetadataOrBuilderList(): java.util.List<any>; public static parseDelimitedFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.android.gms.config.proto.Config.ConfigFetchResponse; public static newBuilder(param0: com.google.android.gms.config.proto.Config.ConfigFetchResponse): com.google.android.gms.config.proto.Config.ConfigFetchResponse.Builder; } export module ConfigFetchResponse { export class Builder extends com.google.protobuf.GeneratedMessageLite.Builder<com.google.android.gms.config.proto.Config.ConfigFetchResponse,com.google.android.gms.config.proto.Config.ConfigFetchResponse.Builder> implements com.google.android.gms.config.proto.Config.ConfigFetchResponseOrBuilder { public static class: java.lang.Class<com.google.android.gms.config.proto.Config.ConfigFetchResponse.Builder>; public getAppConfigList(): java.util.List<com.google.android.gms.config.proto.Config.AppConfigTable>; public getAppConfigCount(): number; public addAppConfig(param0: number, param1: com.google.android.gms.config.proto.Config.AppConfigTable.Builder): com.google.android.gms.config.proto.Config.ConfigFetchResponse.Builder; public addPackageTable(param0: com.google.android.gms.config.proto.Config.PackageTable): com.google.android.gms.config.proto.Config.ConfigFetchResponse.Builder; public addPackageTable(param0: com.google.android.gms.config.proto.Config.PackageTable.Builder): com.google.android.gms.config.proto.Config.ConfigFetchResponse.Builder; public getInternalMetadataCount(): number; public clearInternalMetadata(): com.google.android.gms.config.proto.Config.ConfigFetchResponse.Builder; public getPackageTableCount(): number; public addAppConfig(param0: com.google.android.gms.config.proto.Config.AppConfigTable.Builder): com.google.android.gms.config.proto.Config.ConfigFetchResponse.Builder; public clearPackageTable(): com.google.android.gms.config.proto.Config.ConfigFetchResponse.Builder; public getAppConfig(param0: number): com.google.android.gms.config.proto.Config.AppConfigTable; public addAllAppConfig(param0: java.lang.Iterable<any>): com.google.android.gms.config.proto.Config.ConfigFetchResponse.Builder; public setInternalMetadata(param0: number, param1: com.google.android.gms.config.proto.Config.KeyValue.Builder): com.google.android.gms.config.proto.Config.ConfigFetchResponse.Builder; public addAllInternalMetadata(param0: java.lang.Iterable<any>): com.google.android.gms.config.proto.Config.ConfigFetchResponse.Builder; public addInternalMetadata(param0: number, param1: com.google.android.gms.config.proto.Config.KeyValue): com.google.android.gms.config.proto.Config.ConfigFetchResponse.Builder; public setStatus(param0: com.google.android.gms.config.proto.Config.ConfigFetchResponse.ResponseStatus): com.google.android.gms.config.proto.Config.ConfigFetchResponse.Builder; public hasStatus(): boolean; public getPackageTableList(): java.util.List<com.google.android.gms.config.proto.Config.PackageTable>; public setInternalMetadata(param0: number, param1: com.google.android.gms.config.proto.Config.KeyValue): com.google.android.gms.config.proto.Config.ConfigFetchResponse.Builder; public addInternalMetadata(param0: number, param1: com.google.android.gms.config.proto.Config.KeyValue.Builder): com.google.android.gms.config.proto.Config.ConfigFetchResponse.Builder; public removePackageTable(param0: number): com.google.android.gms.config.proto.Config.ConfigFetchResponse.Builder; public addInternalMetadata(param0: com.google.android.gms.config.proto.Config.KeyValue.Builder): com.google.android.gms.config.proto.Config.ConfigFetchResponse.Builder; public getInternalMetadataList(): java.util.List<com.google.android.gms.config.proto.Config.KeyValue>; public removeInternalMetadata(param0: number): com.google.android.gms.config.proto.Config.ConfigFetchResponse.Builder; public addAllPackageTable(param0: java.lang.Iterable<any>): com.google.android.gms.config.proto.Config.ConfigFetchResponse.Builder; public addPackageTable(param0: number, param1: com.google.android.gms.config.proto.Config.PackageTable): com.google.android.gms.config.proto.Config.ConfigFetchResponse.Builder; public clearStatus(): com.google.android.gms.config.proto.Config.ConfigFetchResponse.Builder; public setPackageTable(param0: number, param1: com.google.android.gms.config.proto.Config.PackageTable): com.google.android.gms.config.proto.Config.ConfigFetchResponse.Builder; public getInternalMetadata(param0: number): com.google.android.gms.config.proto.Config.KeyValue; public setAppConfig(param0: number, param1: com.google.android.gms.config.proto.Config.AppConfigTable.Builder): com.google.android.gms.config.proto.Config.ConfigFetchResponse.Builder; public clearAppConfig(): com.google.android.gms.config.proto.Config.ConfigFetchResponse.Builder; public addAppConfig(param0: com.google.android.gms.config.proto.Config.AppConfigTable): com.google.android.gms.config.proto.Config.ConfigFetchResponse.Builder; public addAppConfig(param0: number, param1: com.google.android.gms.config.proto.Config.AppConfigTable): com.google.android.gms.config.proto.Config.ConfigFetchResponse.Builder; public removeAppConfig(param0: number): com.google.android.gms.config.proto.Config.ConfigFetchResponse.Builder; public getPackageTable(param0: number): com.google.android.gms.config.proto.Config.PackageTable; public setPackageTable(param0: number, param1: com.google.android.gms.config.proto.Config.PackageTable.Builder): com.google.android.gms.config.proto.Config.ConfigFetchResponse.Builder; public addInternalMetadata(param0: com.google.android.gms.config.proto.Config.KeyValue): com.google.android.gms.config.proto.Config.ConfigFetchResponse.Builder; public setAppConfig(param0: number, param1: com.google.android.gms.config.proto.Config.AppConfigTable): com.google.android.gms.config.proto.Config.ConfigFetchResponse.Builder; public getStatus(): com.google.android.gms.config.proto.Config.ConfigFetchResponse.ResponseStatus; public addPackageTable(param0: number, param1: com.google.android.gms.config.proto.Config.PackageTable.Builder): com.google.android.gms.config.proto.Config.ConfigFetchResponse.Builder; } export class ResponseStatus extends com.google.protobuf.Internal.EnumLite { public static class: java.lang.Class<com.google.android.gms.config.proto.Config.ConfigFetchResponse.ResponseStatus>; public static SUCCESS: com.google.android.gms.config.proto.Config.ConfigFetchResponse.ResponseStatus; public static NO_PACKAGES_IN_REQUEST: com.google.android.gms.config.proto.Config.ConfigFetchResponse.ResponseStatus; public static SUCCESS_VALUE: number; public static NO_PACKAGES_IN_REQUEST_VALUE: number; public getNumber(): number; public static forNumber(param0: number): com.google.android.gms.config.proto.Config.ConfigFetchResponse.ResponseStatus; public static internalGetValueMap(): com.google.protobuf.Internal.EnumLiteMap<com.google.android.gms.config.proto.Config.ConfigFetchResponse.ResponseStatus>; public static valueOf(param0: string): com.google.android.gms.config.proto.Config.ConfigFetchResponse.ResponseStatus; public static values(): native.Array<com.google.android.gms.config.proto.Config.ConfigFetchResponse.ResponseStatus>; public static valueOf(param0: number): com.google.android.gms.config.proto.Config.ConfigFetchResponse.ResponseStatus; } } export class ConfigFetchResponseOrBuilder { public static class: java.lang.Class<com.google.android.gms.config.proto.Config.ConfigFetchResponseOrBuilder>; /** * Constructs a new instance of the com.google.android.gms.config.proto.Config$ConfigFetchResponseOrBuilder interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { getPackageTableList(): java.util.List<com.google.android.gms.config.proto.Config.PackageTable>; getPackageTable(param0: number): com.google.android.gms.config.proto.Config.PackageTable; getPackageTableCount(): number; hasStatus(): boolean; getStatus(): com.google.android.gms.config.proto.Config.ConfigFetchResponse.ResponseStatus; getInternalMetadataList(): java.util.List<com.google.android.gms.config.proto.Config.KeyValue>; getInternalMetadata(param0: number): com.google.android.gms.config.proto.Config.KeyValue; getInternalMetadataCount(): number; getAppConfigList(): java.util.List<com.google.android.gms.config.proto.Config.AppConfigTable>; getAppConfig(param0: number): com.google.android.gms.config.proto.Config.AppConfigTable; getAppConfigCount(): number; }); public constructor(); public getAppConfig(param0: number): com.google.android.gms.config.proto.Config.AppConfigTable; public hasStatus(): boolean; public getInternalMetadata(param0: number): com.google.android.gms.config.proto.Config.KeyValue; public getPackageTable(param0: number): com.google.android.gms.config.proto.Config.PackageTable; public getInternalMetadataList(): java.util.List<com.google.android.gms.config.proto.Config.KeyValue>; public getAppConfigCount(): number; public getStatus(): com.google.android.gms.config.proto.Config.ConfigFetchResponse.ResponseStatus; public getPackageTableCount(): number; public getPackageTableList(): java.util.List<com.google.android.gms.config.proto.Config.PackageTable>; public getInternalMetadataCount(): number; public getAppConfigList(): java.util.List<com.google.android.gms.config.proto.Config.AppConfigTable>; } export class KeyValue extends com.google.protobuf.GeneratedMessageLite<com.google.android.gms.config.proto.Config.KeyValue,com.google.android.gms.config.proto.Config.KeyValue.Builder> implements com.google.android.gms.config.proto.Config.KeyValueOrBuilder { public static class: java.lang.Class<com.google.android.gms.config.proto.Config.KeyValue>; public static KEY_FIELD_NUMBER: number; public static VALUE_FIELD_NUMBER: number; public static newBuilder(): com.google.android.gms.config.proto.Config.KeyValue.Builder; public static parseFrom(param0: java.io.InputStream): com.google.android.gms.config.proto.Config.KeyValue; public getValue(): com.google.protobuf.ByteString; public static parseDelimitedFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.android.gms.config.proto.Config.KeyValue; public static newBuilder(param0: com.google.android.gms.config.proto.Config.KeyValue): com.google.android.gms.config.proto.Config.KeyValue.Builder; public hasKey(): boolean; public static parseFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.android.gms.config.proto.Config.KeyValue; public static parseFrom(param0: com.google.protobuf.CodedInputStream): com.google.android.gms.config.proto.Config.KeyValue; public static getDefaultInstance(): com.google.android.gms.config.proto.Config.KeyValue; public static parser(): com.google.protobuf.Parser<com.google.android.gms.config.proto.Config.KeyValue>; public getKey(): string; public dynamicMethod(param0: com.google.protobuf.GeneratedMessageLite.MethodToInvoke, param1: any, param2: any): any; public static parseFrom(param0: native.Array<number>, param1: com.google.protobuf.ExtensionRegistryLite): com.google.android.gms.config.proto.Config.KeyValue; public static parseFrom(param0: native.Array<number>): com.google.android.gms.config.proto.Config.KeyValue; public static parseFrom(param0: com.google.protobuf.CodedInputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.android.gms.config.proto.Config.KeyValue; public writeTo(param0: com.google.protobuf.CodedOutputStream): void; public getSerializedSize(): number; public static parseDelimitedFrom(param0: java.io.InputStream): com.google.android.gms.config.proto.Config.KeyValue; public hasValue(): boolean; public static parseFrom(param0: com.google.protobuf.ByteString, param1: com.google.protobuf.ExtensionRegistryLite): com.google.android.gms.config.proto.Config.KeyValue; public static parseFrom(param0: com.google.protobuf.ByteString): com.google.android.gms.config.proto.Config.KeyValue; public getKeyBytes(): com.google.protobuf.ByteString; } export module KeyValue { export class Builder extends com.google.protobuf.GeneratedMessageLite.Builder<com.google.android.gms.config.proto.Config.KeyValue,com.google.android.gms.config.proto.Config.KeyValue.Builder> implements com.google.android.gms.config.proto.Config.KeyValueOrBuilder { public static class: java.lang.Class<com.google.android.gms.config.proto.Config.KeyValue.Builder>; public getKeyBytes(): com.google.protobuf.ByteString; public clearKey(): com.google.android.gms.config.proto.Config.KeyValue.Builder; public hasKey(): boolean; public setKeyBytes(param0: com.google.protobuf.ByteString): com.google.android.gms.config.proto.Config.KeyValue.Builder; public getValue(): com.google.protobuf.ByteString; public setValue(param0: com.google.protobuf.ByteString): com.google.android.gms.config.proto.Config.KeyValue.Builder; public getKey(): string; public hasValue(): boolean; public clearValue(): com.google.android.gms.config.proto.Config.KeyValue.Builder; public setKey(param0: string): com.google.android.gms.config.proto.Config.KeyValue.Builder; } } export class KeyValueOrBuilder { public static class: java.lang.Class<com.google.android.gms.config.proto.Config.KeyValueOrBuilder>; /** * Constructs a new instance of the com.google.android.gms.config.proto.Config$KeyValueOrBuilder interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { hasKey(): boolean; getKey(): string; getKeyBytes(): com.google.protobuf.ByteString; hasValue(): boolean; getValue(): com.google.protobuf.ByteString; }); public constructor(); public getValue(): com.google.protobuf.ByteString; public hasValue(): boolean; public hasKey(): boolean; public getKey(): string; public getKeyBytes(): com.google.protobuf.ByteString; } export class NamedValue extends com.google.protobuf.GeneratedMessageLite<com.google.android.gms.config.proto.Config.NamedValue,com.google.android.gms.config.proto.Config.NamedValue.Builder> implements com.google.android.gms.config.proto.Config.NamedValueOrBuilder { public static class: java.lang.Class<com.google.android.gms.config.proto.Config.NamedValue>; public static NAME_FIELD_NUMBER: number; public static VALUE_FIELD_NUMBER: number; public getValueBytes(): com.google.protobuf.ByteString; public static parseFrom(param0: native.Array<number>): com.google.android.gms.config.proto.Config.NamedValue; public static parseFrom(param0: java.io.InputStream): com.google.android.gms.config.proto.Config.NamedValue; public static newBuilder(): com.google.android.gms.config.proto.Config.NamedValue.Builder; public static newBuilder(param0: com.google.android.gms.config.proto.Config.NamedValue): com.google.android.gms.config.proto.Config.NamedValue.Builder; public static getDefaultInstance(): com.google.android.gms.config.proto.Config.NamedValue; public getName(): string; public getNameBytes(): com.google.protobuf.ByteString; public static parseDelimitedFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.android.gms.config.proto.Config.NamedValue; public static parseFrom(param0: native.Array<number>, param1: com.google.protobuf.ExtensionRegistryLite): com.google.android.gms.config.proto.Config.NamedValue; public static parseFrom(param0: com.google.protobuf.ByteString, param1: com.google.protobuf.ExtensionRegistryLite): com.google.android.gms.config.proto.Config.NamedValue; public static parseFrom(param0: com.google.protobuf.CodedInputStream): com.google.android.gms.config.proto.Config.NamedValue; public dynamicMethod(param0: com.google.protobuf.GeneratedMessageLite.MethodToInvoke, param1: any, param2: any): any; public hasName(): boolean; public writeTo(param0: com.google.protobuf.CodedOutputStream): void; public getSerializedSize(): number; public static parseDelimitedFrom(param0: java.io.InputStream): com.google.android.gms.config.proto.Config.NamedValue; public static parseFrom(param0: com.google.protobuf.CodedInputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.android.gms.config.proto.Config.NamedValue; public hasValue(): boolean; public static parseFrom(param0: com.google.protobuf.ByteString): com.google.android.gms.config.proto.Config.NamedValue; public static parser(): com.google.protobuf.Parser<com.google.android.gms.config.proto.Config.NamedValue>; public getValue(): string; public static parseFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.android.gms.config.proto.Config.NamedValue; } export module NamedValue { export class Builder extends com.google.protobuf.GeneratedMessageLite.Builder<com.google.android.gms.config.proto.Config.NamedValue,com.google.android.gms.config.proto.Config.NamedValue.Builder> implements com.google.android.gms.config.proto.Config.NamedValueOrBuilder { public static class: java.lang.Class<com.google.android.gms.config.proto.Config.NamedValue.Builder>; public clearName(): com.google.android.gms.config.proto.Config.NamedValue.Builder; public clearValue(): com.google.android.gms.config.proto.Config.NamedValue.Builder; public setName(param0: string): com.google.android.gms.config.proto.Config.NamedValue.Builder; public getValue(): string; public setNameBytes(param0: com.google.protobuf.ByteString): com.google.android.gms.config.proto.Config.NamedValue.Builder; public hasName(): boolean; public hasValue(): boolean; public getName(): string; public getNameBytes(): com.google.protobuf.ByteString; public setValueBytes(param0: com.google.protobuf.ByteString): com.google.android.gms.config.proto.Config.NamedValue.Builder; public getValueBytes(): com.google.protobuf.ByteString; public setValue(param0: string): com.google.android.gms.config.proto.Config.NamedValue.Builder; } } export class NamedValueOrBuilder { public static class: java.lang.Class<com.google.android.gms.config.proto.Config.NamedValueOrBuilder>; /** * Constructs a new instance of the com.google.android.gms.config.proto.Config$NamedValueOrBuilder interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { hasName(): boolean; getName(): string; getNameBytes(): com.google.protobuf.ByteString; hasValue(): boolean; getValue(): string; getValueBytes(): com.google.protobuf.ByteString; }); public constructor(); public getValueBytes(): com.google.protobuf.ByteString; public hasName(): boolean; public getName(): string; public hasValue(): boolean; public getNameBytes(): com.google.protobuf.ByteString; public getValue(): string; } export class PackageData extends com.google.protobuf.GeneratedMessageLite<com.google.android.gms.config.proto.Config.PackageData,com.google.android.gms.config.proto.Config.PackageData.Builder> implements com.google.android.gms.config.proto.Config.PackageDataOrBuilder { public static class: java.lang.Class<com.google.android.gms.config.proto.Config.PackageData>; public static VERSION_CODE_FIELD_NUMBER: number; public static DIGEST_FIELD_NUMBER: number; public static CERT_HASH_FIELD_NUMBER: number; public static CONFIG_ID_FIELD_NUMBER: number; public static PACKAGE_NAME_FIELD_NUMBER: number; public static GMP_PROJECT_ID_FIELD_NUMBER: number; public static GAMES_PROJECT_ID_FIELD_NUMBER: number; public static NAMESPACE_DIGEST_FIELD_NUMBER: number; public static CUSTOM_VARIABLE_FIELD_NUMBER: number; public static APP_CERT_HASH_FIELD_NUMBER: number; public static APP_VERSION_CODE_FIELD_NUMBER: number; public static APP_VERSION_FIELD_NUMBER: number; public static APP_INSTANCE_ID_FIELD_NUMBER: number; public static APP_INSTANCE_ID_TOKEN_FIELD_NUMBER: number; public static REQUESTED_HIDDEN_NAMESPACE_FIELD_NUMBER: number; public static SDK_VERSION_FIELD_NUMBER: number; public static ANALYTICS_USER_PROPERTY_FIELD_NUMBER: number; public static REQUESTED_CACHE_EXPIRATION_SECONDS_FIELD_NUMBER: number; public static FETCHED_CONFIG_AGE_SECONDS_FIELD_NUMBER: number; public static ACTIVE_CONFIG_AGE_SECONDS_FIELD_NUMBER: number; public getGamesProjectId(): string; public static parseDelimitedFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.android.gms.config.proto.Config.PackageData; public getNamespaceDigestOrBuilder(param0: number): com.google.android.gms.config.proto.Config.NamedValueOrBuilder; public getAppInstanceIdToken(): string; public getPackageName(): string; public static parseFrom(param0: native.Array<number>): com.google.android.gms.config.proto.Config.PackageData; public hasAppVersion(): boolean; public static newBuilder(param0: com.google.android.gms.config.proto.Config.PackageData): com.google.android.gms.config.proto.Config.PackageData.Builder; public getAppInstanceIdTokenBytes(): com.google.protobuf.ByteString; public hasGamesProjectId(): boolean; public getAnalyticsUserPropertyList(): java.util.List<com.google.android.gms.config.proto.Config.NamedValue>; public static parseFrom(param0: com.google.protobuf.ByteString): com.google.android.gms.config.proto.Config.PackageData; public getVersionCode(): number; public getAnalyticsUserPropertyOrBuilder(param0: number): com.google.android.gms.config.proto.Config.NamedValueOrBuilder; public getFetchedConfigAgeSeconds(): number; public getRequestedHiddenNamespaceCount(): number; public getRequestedHiddenNamespace(param0: number): string; public getActiveConfigAgeSeconds(): number; public getGmpProjectId(): string; public static parser(): com.google.protobuf.Parser<com.google.android.gms.config.proto.Config.PackageData>; public getRequestedHiddenNamespaceBytes(param0: number): com.google.protobuf.ByteString; public static parseFrom(param0: com.google.protobuf.ByteString, param1: com.google.protobuf.ExtensionRegistryLite): com.google.android.gms.config.proto.Config.PackageData; public hasConfigId(): boolean; public getAppInstanceId(): string; public getCustomVariableOrBuilderList(): java.util.List<any>; public getCustomVariable(param0: number): com.google.android.gms.config.proto.Config.NamedValue; public static parseDelimitedFrom(param0: java.io.InputStream): com.google.android.gms.config.proto.Config.PackageData; public dynamicMethod(param0: com.google.protobuf.GeneratedMessageLite.MethodToInvoke, param1: any, param2: any): any; public getCustomVariableList(): java.util.List<com.google.android.gms.config.proto.Config.NamedValue>; public hasAppCertHash(): boolean; public hasFetchedConfigAgeSeconds(): boolean; public getCertHash(): com.google.protobuf.ByteString; public getSerializedSize(): number; public hasSdkVersion(): boolean; public getNamespaceDigestOrBuilderList(): java.util.List<any>; public static newBuilder(): com.google.android.gms.config.proto.Config.PackageData.Builder; public hasDigest(): boolean; public hasRequestedCacheExpirationSeconds(): boolean; public getRequestedCacheExpirationSeconds(): number; public getCustomVariableOrBuilder(param0: number): com.google.android.gms.config.proto.Config.NamedValueOrBuilder; public getSdkVersion(): number; public getAppVersion(): string; public getCustomVariableCount(): number; public hasAppInstanceIdToken(): boolean; public getAppCertHash(): com.google.protobuf.ByteString; public getGamesProjectIdBytes(): com.google.protobuf.ByteString; public getAppVersionCode(): number; public static parseFrom(param0: java.io.InputStream): com.google.android.gms.config.proto.Config.PackageData; public static getDefaultInstance(): com.google.android.gms.config.proto.Config.PackageData; public writeTo(param0: com.google.protobuf.CodedOutputStream): void; public getConfigIdBytes(): com.google.protobuf.ByteString; public getGmpProjectIdBytes(): com.google.protobuf.ByteString; public getAppInstanceIdBytes(): com.google.protobuf.ByteString; public static parseFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.android.gms.config.proto.Config.PackageData; public getConfigId(): string; public getAppVersionBytes(): com.google.protobuf.ByteString; public static parseFrom(param0: com.google.protobuf.CodedInputStream): com.google.android.gms.config.proto.Config.PackageData; public getPackageNameBytes(): com.google.protobuf.ByteString; public getAnalyticsUserPropertyOrBuilderList(): java.util.List<any>; public getAnalyticsUserProperty(param0: number): com.google.android.gms.config.proto.Config.NamedValue; public static parseFrom(param0: com.google.protobuf.CodedInputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.android.gms.config.proto.Config.PackageData; public getDigest(): com.google.protobuf.ByteString; public hasGmpProjectId(): boolean; public static parseFrom(param0: native.Array<number>, param1: com.google.protobuf.ExtensionRegistryLite): com.google.android.gms.config.proto.Config.PackageData; public getNamespaceDigestCount(): number; public hasVersionCode(): boolean; public hasAppInstanceId(): boolean; public hasCertHash(): boolean; public getNamespaceDigestList(): java.util.List<com.google.android.gms.config.proto.Config.NamedValue>; public hasAppVersionCode(): boolean; public getAnalyticsUserPropertyCount(): number; public hasPackageName(): boolean; public hasActiveConfigAgeSeconds(): boolean; public getNamespaceDigest(param0: number): com.google.android.gms.config.proto.Config.NamedValue; public getRequestedHiddenNamespaceList(): java.util.List<string>; } export module PackageData { export class Builder extends com.google.protobuf.GeneratedMessageLite.Builder<com.google.android.gms.config.proto.Config.PackageData,com.google.android.gms.config.proto.Config.PackageData.Builder> implements com.google.android.gms.config.proto.Config.PackageDataOrBuilder { public static class: java.lang.Class<com.google.android.gms.config.proto.Config.PackageData.Builder>; public addAnalyticsUserProperty(param0: number, param1: com.google.android.gms.config.proto.Config.NamedValue): com.google.android.gms.config.proto.Config.PackageData.Builder; public addCustomVariable(param0: com.google.android.gms.config.proto.Config.NamedValue): com.google.android.gms.config.proto.Config.PackageData.Builder; public setGamesProjectIdBytes(param0: com.google.protobuf.ByteString): com.google.android.gms.config.proto.Config.PackageData.Builder; public getAnalyticsUserPropertyCount(): number; public removeCustomVariable(param0: number): com.google.android.gms.config.proto.Config.PackageData.Builder; public addAllRequestedHiddenNamespace(param0: java.lang.Iterable<string>): com.google.android.gms.config.proto.Config.PackageData.Builder; public removeAnalyticsUserProperty(param0: number): com.google.android.gms.config.proto.Config.PackageData.Builder; public setAppInstanceIdBytes(param0: com.google.protobuf.ByteString): com.google.android.gms.config.proto.Config.PackageData.Builder; public getRequestedHiddenNamespaceBytes(param0: number): com.google.protobuf.ByteString; public setPackageNameBytes(param0: com.google.protobuf.ByteString): com.google.android.gms.config.proto.Config.PackageData.Builder; public setGamesProjectId(param0: string): com.google.android.gms.config.proto.Config.PackageData.Builder; public hasAppVersionCode(): boolean; public getNamespaceDigest(param0: number): com.google.android.gms.config.proto.Config.NamedValue; public setAppVersion(param0: string): com.google.android.gms.config.proto.Config.PackageData.Builder; public setGmpProjectId(param0: string): com.google.android.gms.config.proto.Config.PackageData.Builder; public clearAppVersion(): com.google.android.gms.config.proto.Config.PackageData.Builder; public hasAppInstanceIdToken(): boolean; public clearAnalyticsUserProperty(): com.google.android.gms.config.proto.Config.PackageData.Builder; public getCustomVariableList(): java.util.List<com.google.android.gms.config.proto.Config.NamedValue>; public clearGamesProjectId(): com.google.android.gms.config.proto.Config.PackageData.Builder; public addNamespaceDigest(param0: com.google.android.gms.config.proto.Config.NamedValue.Builder): com.google.android.gms.config.proto.Config.PackageData.Builder; public hasConfigId(): boolean; public getAppVersionBytes(): com.google.protobuf.ByteString; public setCustomVariable(param0: number, param1: com.google.android.gms.config.proto.Config.NamedValue.Builder): com.google.android.gms.config.proto.Config.PackageData.Builder; public setRequestedHiddenNamespace(param0: number, param1: string): com.google.android.gms.config.proto.Config.PackageData.Builder; public addAllAnalyticsUserProperty(param0: java.lang.Iterable<any>): com.google.android.gms.config.proto.Config.PackageData.Builder; public setRequestedCacheExpirationSeconds(param0: number): com.google.android.gms.config.proto.Config.PackageData.Builder; public hasDigest(): boolean; public clearCertHash(): com.google.android.gms.config.proto.Config.PackageData.Builder; public setNamespaceDigest(param0: number, param1: com.google.android.gms.config.proto.Config.NamedValue): com.google.android.gms.config.proto.Config.PackageData.Builder; public getAppInstanceIdTokenBytes(): com.google.protobuf.ByteString; public removeNamespaceDigest(param0: number): com.google.android.gms.config.proto.Config.PackageData.Builder; public setConfigId(param0: string): com.google.android.gms.config.proto.Config.PackageData.Builder; public setAnalyticsUserProperty(param0: number, param1: com.google.android.gms.config.proto.Config.NamedValue.Builder): com.google.android.gms.config.proto.Config.PackageData.Builder; public setGmpProjectIdBytes(param0: com.google.protobuf.ByteString): com.google.android.gms.config.proto.Config.PackageData.Builder; public clearPackageName(): com.google.android.gms.config.proto.Config.PackageData.Builder; public setAppInstanceIdTokenBytes(param0: com.google.protobuf.ByteString): com.google.android.gms.config.proto.Config.PackageData.Builder; public addAllCustomVariable(param0: java.lang.Iterable<any>): com.google.android.gms.config.proto.Config.PackageData.Builder; public clearAppInstanceId(): com.google.android.gms.config.proto.Config.PackageData.Builder; public getVersionCode(): number; public clearAppVersionCode(): com.google.android.gms.config.proto.Config.PackageData.Builder; public addNamespaceDigest(param0: number, param1: com.google.android.gms.config.proto.Config.NamedValue): com.google.android.gms.config.proto.Config.PackageData.Builder; public clearFetchedConfigAgeSeconds(): com.google.android.gms.config.proto.Config.PackageData.Builder; public getConfigIdBytes(): com.google.protobuf.ByteString; public getAppVersionCode(): number; public hasAppInstanceId(): boolean; public getConfigId(): string; public getAnalyticsUserProperty(param0: number): com.google.android.gms.config.proto.Config.NamedValue; public clearRequestedCacheExpirationSeconds(): com.google.android.gms.config.proto.Config.PackageData.Builder; public clearNamespaceDigest(): com.google.android.gms.config.proto.Config.PackageData.Builder; public getAppInstanceIdBytes(): com.google.protobuf.ByteString; public setActiveConfigAgeSeconds(param0: number): com.google.android.gms.config.proto.Config.PackageData.Builder; public getDigest(): com.google.protobuf.ByteString; public getGamesProjectIdBytes(): com.google.protobuf.ByteString; public hasGmpProjectId(): boolean; public setAppVersionBytes(param0: com.google.protobuf.ByteString): com.google.android.gms.config.proto.Config.PackageData.Builder; public hasSdkVersion(): boolean; public getRequestedHiddenNamespaceList(): java.util.List<string>; public setSdkVersion(param0: number): com.google.android.gms.config.proto.Config.PackageData.Builder; public clearAppInstanceIdToken(): com.google.android.gms.config.proto.Config.PackageData.Builder; public getGmpProjectIdBytes(): com.google.protobuf.ByteString; public setAppCertHash(param0: com.google.protobuf.ByteString): com.google.android.gms.config.proto.Config.PackageData.Builder; public hasRequestedCacheExpirationSeconds(): boolean; public clearDigest(): com.google.android.gms.config.proto.Config.PackageData.Builder; public getGmpProjectId(): string; public addAnalyticsUserProperty(param0: number, param1: com.google.android.gms.config.proto.Config.NamedValue.Builder): com.google.android.gms.config.proto.Config.PackageData.Builder; public setAppInstanceIdToken(param0: string): com.google.android.gms.config.proto.Config.PackageData.Builder; public setVersionCode(param0: number): com.google.android.gms.config.proto.Config.PackageData.Builder; public clearSdkVersion(): com.google.android.gms.config.proto.Config.PackageData.Builder; public clearVersionCode(): com.google.android.gms.config.proto.Config.PackageData.Builder; public setDigest(param0: com.google.protobuf.ByteString): com.google.android.gms.config.proto.Config.PackageData.Builder; public hasActiveConfigAgeSeconds(): boolean; public getGamesProjectId(): string; public setAppInstanceId(param0: string): com.google.android.gms.config.proto.Config.PackageData.Builder; public addRequestedHiddenNamespaceBytes(param0: com.google.protobuf.ByteString): com.google.android.gms.config.proto.Config.PackageData.Builder; public clearActiveConfigAgeSeconds(): com.google.android.gms.config.proto.Config.PackageData.Builder; public getRequestedHiddenNamespace(param0: number): string; public hasVersionCode(): boolean; public getRequestedHiddenNamespaceCount(): number; public addAllNamespaceDigest(param0: java.lang.Iterable<any>): com.google.android.gms.config.proto.Config.PackageData.Builder; public hasPackageName(): boolean; public setNamespaceDigest(param0: number, param1: com.google.android.gms.config.proto.Config.NamedValue.Builder): com.google.android.gms.config.proto.Config.PackageData.Builder; public getAppCertHash(): com.google.protobuf.ByteString; public setCertHash(param0: com.google.protobuf.ByteString): com.google.android.gms.config.proto.Config.PackageData.Builder; public getSdkVersion(): number; public addCustomVariable(param0: number, param1: com.google.android.gms.config.proto.Config.NamedValue): com.google.android.gms.config.proto.Config.PackageData.Builder; public setCustomVariable(param0: number, param1: com.google.android.gms.config.proto.Config.NamedValue): com.google.android.gms.config.proto.Config.PackageData.Builder; public clearAppCertHash(): com.google.android.gms.config.proto.Config.PackageData.Builder; public addNamespaceDigest(param0: com.google.android.gms.config.proto.Config.NamedValue): com.google.android.gms.config.proto.Config.PackageData.Builder; public addCustomVariable(param0: number, param1: com.google.android.gms.config.proto.Config.NamedValue.Builder): com.google.android.gms.config.proto.Config.PackageData.Builder; public getActiveConfigAgeSeconds(): number; public getNamespaceDigestList(): java.util.List<com.google.android.gms.config.proto.Config.NamedValue>; public hasGamesProjectId(): boolean; public hasFetchedConfigAgeSeconds(): boolean; public getCustomVariableCount(): number; public clearGmpProjectId(): com.google.android.gms.config.proto.Config.PackageData.Builder; public setFetchedConfigAgeSeconds(param0: number): com.google.android.gms.config.proto.Config.PackageData.Builder; public clearCustomVariable(): com.google.android.gms.config.proto.Config.PackageData.Builder; public getAppVersion(): string; public getFetchedConfigAgeSeconds(): number; public addNamespaceDigest(param0: number, param1: com.google.android.gms.config.proto.Config.NamedValue.Builder): com.google.android.gms.config.proto.Config.PackageData.Builder; public getRequestedCacheExpirationSeconds(): number; public getAppInstanceIdToken(): string; public getCertHash(): com.google.protobuf.ByteString; public setConfigIdBytes(param0: com.google.protobuf.ByteString): com.google.android.gms.config.proto.Config.PackageData.Builder; public getNamespaceDigestCount(): number; public addCustomVariable(param0: com.google.android.gms.config.proto.Config.NamedValue.Builder): com.google.android.gms.config.proto.Config.PackageData.Builder; public hasCertHash(): boolean; public addAnalyticsUserProperty(param0: com.google.android.gms.config.proto.Config.NamedValue): com.google.android.gms.config.proto.Config.PackageData.Builder; public addRequestedHiddenNamespace(param0: string): com.google.android.gms.config.proto.Config.PackageData.Builder; public getAppInstanceId(): string; public getPackageName(): string; public hasAppVersion(): boolean; public addAnalyticsUserProperty(param0: com.google.android.gms.config.proto.Config.NamedValue.Builder): com.google.android.gms.config.proto.Config.PackageData.Builder; public getPackageNameBytes(): com.google.protobuf.ByteString; public hasAppCertHash(): boolean; public setAppVersionCode(param0: number): com.google.android.gms.config.proto.Config.PackageData.Builder; public clearRequestedHiddenNamespace(): com.google.android.gms.config.proto.Config.PackageData.Builder; public clearConfigId(): com.google.android.gms.config.proto.Config.PackageData.Builder; public setPackageName(param0: string): com.google.android.gms.config.proto.Config.PackageData.Builder; public getAnalyticsUserPropertyList(): java.util.List<com.google.android.gms.config.proto.Config.NamedValue>; public setAnalyticsUserProperty(param0: number, param1: com.google.android.gms.config.proto.Config.NamedValue): com.google.android.gms.config.proto.Config.PackageData.Builder; public getCustomVariable(param0: number): com.google.android.gms.config.proto.Config.NamedValue; } } export class PackageDataOrBuilder { public static class: java.lang.Class<com.google.android.gms.config.proto.Config.PackageDataOrBuilder>; /** * Constructs a new instance of the com.google.android.gms.config.proto.Config$PackageDataOrBuilder interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { hasVersionCode(): boolean; getVersionCode(): number; hasDigest(): boolean; getDigest(): com.google.protobuf.ByteString; hasCertHash(): boolean; getCertHash(): com.google.protobuf.ByteString; hasConfigId(): boolean; getConfigId(): string; getConfigIdBytes(): com.google.protobuf.ByteString; hasPackageName(): boolean; getPackageName(): string; getPackageNameBytes(): com.google.protobuf.ByteString; hasGmpProjectId(): boolean; getGmpProjectId(): string; getGmpProjectIdBytes(): com.google.protobuf.ByteString; hasGamesProjectId(): boolean; getGamesProjectId(): string; getGamesProjectIdBytes(): com.google.protobuf.ByteString; getNamespaceDigestList(): java.util.List<com.google.android.gms.config.proto.Config.NamedValue>; getNamespaceDigest(param0: number): com.google.android.gms.config.proto.Config.NamedValue; getNamespaceDigestCount(): number; getCustomVariableList(): java.util.List<com.google.android.gms.config.proto.Config.NamedValue>; getCustomVariable(param0: number): com.google.android.gms.config.proto.Config.NamedValue; getCustomVariableCount(): number; hasAppCertHash(): boolean; getAppCertHash(): com.google.protobuf.ByteString; hasAppVersionCode(): boolean; getAppVersionCode(): number; hasAppVersion(): boolean; getAppVersion(): string; getAppVersionBytes(): com.google.protobuf.ByteString; hasAppInstanceId(): boolean; getAppInstanceId(): string; getAppInstanceIdBytes(): com.google.protobuf.ByteString; hasAppInstanceIdToken(): boolean; getAppInstanceIdToken(): string; getAppInstanceIdTokenBytes(): com.google.protobuf.ByteString; getRequestedHiddenNamespaceList(): java.util.List<string>; getRequestedHiddenNamespaceCount(): number; getRequestedHiddenNamespace(param0: number): string; getRequestedHiddenNamespaceBytes(param0: number): com.google.protobuf.ByteString; hasSdkVersion(): boolean; getSdkVersion(): number; getAnalyticsUserPropertyList(): java.util.List<com.google.android.gms.config.proto.Config.NamedValue>; getAnalyticsUserProperty(param0: number): com.google.android.gms.config.proto.Config.NamedValue; getAnalyticsUserPropertyCount(): number; hasRequestedCacheExpirationSeconds(): boolean; getRequestedCacheExpirationSeconds(): number; hasFetchedConfigAgeSeconds(): boolean; getFetchedConfigAgeSeconds(): number; hasActiveConfigAgeSeconds(): boolean; getActiveConfigAgeSeconds(): number; }); public constructor(); public getGamesProjectId(): string; public getAppInstanceIdToken(): string; public getPackageName(): string; public hasAppVersion(): boolean; public getAppInstanceIdTokenBytes(): com.google.protobuf.ByteString; public hasGamesProjectId(): boolean; public getAnalyticsUserPropertyList(): java.util.List<com.google.android.gms.config.proto.Config.NamedValue>; public getVersionCode(): number; public getFetchedConfigAgeSeconds(): number; public getRequestedHiddenNamespaceCount(): number; public getRequestedHiddenNamespace(param0: number): string; public getActiveConfigAgeSeconds(): number; public getGmpProjectId(): string; public getRequestedHiddenNamespaceBytes(param0: number): com.google.protobuf.ByteString; public hasConfigId(): boolean; public getAppInstanceId(): string; public getCustomVariable(param0: number): com.google.android.gms.config.proto.Config.NamedValue; public getCustomVariableList(): java.util.List<com.google.android.gms.config.proto.Config.NamedValue>; public hasAppCertHash(): boolean; public hasFetchedConfigAgeSeconds(): boolean; public getCertHash(): com.google.protobuf.ByteString; public hasSdkVersion(): boolean; public hasDigest(): boolean; public hasRequestedCacheExpirationSeconds(): boolean; public getRequestedCacheExpirationSeconds(): number; public getSdkVersion(): number; public getAppVersion(): string; public getCustomVariableCount(): number; public hasAppInstanceIdToken(): boolean; public getAppCertHash(): com.google.protobuf.ByteString; public getGamesProjectIdBytes(): com.google.protobuf.ByteString; public getAppVersionCode(): number; public getConfigIdBytes(): com.google.protobuf.ByteString; public getGmpProjectIdBytes(): com.google.protobuf.ByteString; public getAppInstanceIdBytes(): com.google.protobuf.ByteString; public getConfigId(): string; public getAppVersionBytes(): com.google.protobuf.ByteString; public getPackageNameBytes(): com.google.protobuf.ByteString; public getAnalyticsUserProperty(param0: number): com.google.android.gms.config.proto.Config.NamedValue; public getDigest(): com.google.protobuf.ByteString; public hasGmpProjectId(): boolean; public getNamespaceDigestCount(): number; public hasVersionCode(): boolean; public hasAppInstanceId(): boolean; public hasCertHash(): boolean; public getNamespaceDigestList(): java.util.List<com.google.android.gms.config.proto.Config.NamedValue>; public hasAppVersionCode(): boolean; public getAnalyticsUserPropertyCount(): number; public hasPackageName(): boolean; public hasActiveConfigAgeSeconds(): boolean; public getNamespaceDigest(param0: number): com.google.android.gms.config.proto.Config.NamedValue; public getRequestedHiddenNamespaceList(): java.util.List<string>; } export class PackageTable extends com.google.protobuf.GeneratedMessageLite<com.google.android.gms.config.proto.Config.PackageTable,com.google.android.gms.config.proto.Config.PackageTable.Builder> implements com.google.android.gms.config.proto.Config.PackageTableOrBuilder { public static class: java.lang.Class<com.google.android.gms.config.proto.Config.PackageTable>; public static PACKAGE_NAME_FIELD_NUMBER: number; public static ENTRY_FIELD_NUMBER: number; public static CONFIG_ID_FIELD_NUMBER: number; public static parseFrom(param0: native.Array<number>, param1: com.google.protobuf.ExtensionRegistryLite): com.google.android.gms.config.proto.Config.PackageTable; public static parseDelimitedFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.android.gms.config.proto.Config.PackageTable; public getEntryList(): java.util.List<com.google.android.gms.config.proto.Config.KeyValue>; public getEntry(param0: number): com.google.android.gms.config.proto.Config.KeyValue; public static parseFrom(param0: com.google.protobuf.CodedInputStream): com.google.android.gms.config.proto.Config.PackageTable; public static parseFrom(param0: java.io.InputStream): com.google.android.gms.config.proto.Config.PackageTable; public getPackageName(): string; public static newBuilder(): com.google.android.gms.config.proto.Config.PackageTable.Builder; public static parseDelimitedFrom(param0: java.io.InputStream): com.google.android.gms.config.proto.Config.PackageTable; public static parseFrom(param0: native.Array<number>): com.google.android.gms.config.proto.Config.PackageTable; public writeTo(param0: com.google.protobuf.CodedOutputStream): void; public getConfigIdBytes(): com.google.protobuf.ByteString; public static getDefaultInstance(): com.google.android.gms.config.proto.Config.PackageTable; public getEntryOrBuilderList(): java.util.List<any>; public getConfigId(): string; public static newBuilder(param0: com.google.android.gms.config.proto.Config.PackageTable): com.google.android.gms.config.proto.Config.PackageTable.Builder; public static parseFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.android.gms.config.proto.Config.PackageTable; public getEntryCount(): number; public getPackageNameBytes(): com.google.protobuf.ByteString; public static parseFrom(param0: com.google.protobuf.CodedInputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.android.gms.config.proto.Config.PackageTable; public static parser(): com.google.protobuf.Parser<com.google.android.gms.config.proto.Config.PackageTable>; public static parseFrom(param0: com.google.protobuf.ByteString, param1: com.google.protobuf.ExtensionRegistryLite): com.google.android.gms.config.proto.Config.PackageTable; public hasConfigId(): boolean; public static parseFrom(param0: com.google.protobuf.ByteString): com.google.android.gms.config.proto.Config.PackageTable; public dynamicMethod(param0: com.google.protobuf.GeneratedMessageLite.MethodToInvoke, param1: any, param2: any): any; public getSerializedSize(): number; public hasPackageName(): boolean; public getEntryOrBuilder(param0: number): com.google.android.gms.config.proto.Config.KeyValueOrBuilder; } export module PackageTable { export class Builder extends com.google.protobuf.GeneratedMessageLite.Builder<com.google.android.gms.config.proto.Config.PackageTable,com.google.android.gms.config.proto.Config.PackageTable.Builder> implements com.google.android.gms.config.proto.Config.PackageTableOrBuilder { public static class: java.lang.Class<com.google.android.gms.config.proto.Config.PackageTable.Builder>; public addEntry(param0: number, param1: com.google.android.gms.config.proto.Config.KeyValue.Builder): com.google.android.gms.config.proto.Config.PackageTable.Builder; public getPackageName(): string; public clearConfigId(): com.google.android.gms.config.proto.Config.PackageTable.Builder; public clearEntry(): com.google.android.gms.config.proto.Config.PackageTable.Builder; public setEntry(param0: number, param1: com.google.android.gms.config.proto.Config.KeyValue.Builder): com.google.android.gms.config.proto.Config.PackageTable.Builder; public addEntry(param0: number, param1: com.google.android.gms.config.proto.Config.KeyValue): com.google.android.gms.config.proto.Config.PackageTable.Builder; public getPackageNameBytes(): com.google.protobuf.ByteString; public getEntryCount(): number; public getEntry(param0: number): com.google.android.gms.config.proto.Config.KeyValue; public clearPackageName(): com.google.android.gms.config.proto.Config.PackageTable.Builder; public setConfigIdBytes(param0: com.google.protobuf.ByteString): com.google.android.gms.config.proto.Config.PackageTable.Builder; public addEntry(param0: com.google.android.gms.config.proto.Config.KeyValue.Builder): com.google.android.gms.config.proto.Config.PackageTable.Builder; public getConfigIdBytes(): com.google.protobuf.ByteString; public setEntry(param0: number, param1: com.google.android.gms.config.proto.Config.KeyValue): com.google.android.gms.config.proto.Config.PackageTable.Builder; public addEntry(param0: com.google.android.gms.config.proto.Config.KeyValue): com.google.android.gms.config.proto.Config.PackageTable.Builder; public hasPackageName(): boolean; public setPackageName(param0: string): com.google.android.gms.config.proto.Config.PackageTable.Builder; public setPackageNameBytes(param0: com.google.protobuf.ByteString): com.google.android.gms.config.proto.Config.PackageTable.Builder; public getConfigId(): string; public getEntryList(): java.util.List<com.google.android.gms.config.proto.Config.KeyValue>; public setConfigId(param0: string): com.google.android.gms.config.proto.Config.PackageTable.Builder; public addAllEntry(param0: java.lang.Iterable<any>): com.google.android.gms.config.proto.Config.PackageTable.Builder; public removeEntry(param0: number): com.google.android.gms.config.proto.Config.PackageTable.Builder; public hasConfigId(): boolean; } } export class PackageTableOrBuilder { public static class: java.lang.Class<com.google.android.gms.config.proto.Config.PackageTableOrBuilder>; /** * Constructs a new instance of the com.google.android.gms.config.proto.Config$PackageTableOrBuilder interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { hasPackageName(): boolean; getPackageName(): string; getPackageNameBytes(): com.google.protobuf.ByteString; getEntryList(): java.util.List<com.google.android.gms.config.proto.Config.KeyValue>; getEntry(param0: number): com.google.android.gms.config.proto.Config.KeyValue; getEntryCount(): number; hasConfigId(): boolean; getConfigId(): string; getConfigIdBytes(): com.google.protobuf.ByteString; }); public constructor(); public getEntryList(): java.util.List<com.google.android.gms.config.proto.Config.KeyValue>; public getEntry(param0: number): com.google.android.gms.config.proto.Config.KeyValue; public getConfigIdBytes(): com.google.protobuf.ByteString; public hasPackageName(): boolean; public hasConfigId(): boolean; public getConfigId(): string; public getPackageName(): string; public getEntryCount(): number; public getPackageNameBytes(): com.google.protobuf.ByteString; } } } } } } } } declare module com { export module google { export module android { export module gms { export module config { export module proto { export class Logs { public static class: java.lang.Class<com.google.android.gms.config.proto.Logs>; public static registerAllExtensions(param0: com.google.protobuf.ExtensionRegistryLite): void; } export module Logs { export class AndroidConfigFetchProto extends com.google.protobuf.GeneratedMessageLite<com.google.android.gms.config.proto.Logs.AndroidConfigFetchProto,com.google.android.gms.config.proto.Logs.AndroidConfigFetchProto.Builder> implements com.google.android.gms.config.proto.Logs.AndroidConfigFetchProtoOrBuilder { public static class: java.lang.Class<com.google.android.gms.config.proto.Logs.AndroidConfigFetchProto>; public static REASON_FIELD_NUMBER: number; public static parseFrom(param0: com.google.protobuf.ByteString): com.google.android.gms.config.proto.Logs.AndroidConfigFetchProto; public static parseFrom(param0: native.Array<number>): com.google.android.gms.config.proto.Logs.AndroidConfigFetchProto; public static parser(): com.google.protobuf.Parser<com.google.android.gms.config.proto.Logs.AndroidConfigFetchProto>; public static newBuilder(param0: com.google.android.gms.config.proto.Logs.AndroidConfigFetchProto): com.google.android.gms.config.proto.Logs.AndroidConfigFetchProto.Builder; public static newBuilder(): com.google.android.gms.config.proto.Logs.AndroidConfigFetchProto.Builder; public static parseDelimitedFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.android.gms.config.proto.Logs.AndroidConfigFetchProto; public static parseFrom(param0: com.google.protobuf.CodedInputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.android.gms.config.proto.Logs.AndroidConfigFetchProto; public dynamicMethod(param0: com.google.protobuf.GeneratedMessageLite.MethodToInvoke, param1: any, param2: any): any; public writeTo(param0: com.google.protobuf.CodedOutputStream): void; public getSerializedSize(): number; public static parseDelimitedFrom(param0: java.io.InputStream): com.google.android.gms.config.proto.Logs.AndroidConfigFetchProto; public static parseFrom(param0: native.Array<number>, param1: com.google.protobuf.ExtensionRegistryLite): com.google.android.gms.config.proto.Logs.AndroidConfigFetchProto; public static parseFrom(param0: java.io.InputStream): com.google.android.gms.config.proto.Logs.AndroidConfigFetchProto; public static parseFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.android.gms.config.proto.Logs.AndroidConfigFetchProto; public static getDefaultInstance(): com.google.android.gms.config.proto.Logs.AndroidConfigFetchProto; public hasReason(): boolean; public static parseFrom(param0: com.google.protobuf.ByteString, param1: com.google.protobuf.ExtensionRegistryLite): com.google.android.gms.config.proto.Logs.AndroidConfigFetchProto; public getReason(): com.google.android.gms.config.proto.Logs.ConfigFetchReason; public static parseFrom(param0: com.google.protobuf.CodedInputStream): com.google.android.gms.config.proto.Logs.AndroidConfigFetchProto; } export module AndroidConfigFetchProto { export class Builder extends com.google.protobuf.GeneratedMessageLite.Builder<com.google.android.gms.config.proto.Logs.AndroidConfigFetchProto,com.google.android.gms.config.proto.Logs.AndroidConfigFetchProto.Builder> implements com.google.android.gms.config.proto.Logs.AndroidConfigFetchProtoOrBuilder { public static class: java.lang.Class<com.google.android.gms.config.proto.Logs.AndroidConfigFetchProto.Builder>; public setReason(param0: com.google.android.gms.config.proto.Logs.ConfigFetchReason): com.google.android.gms.config.proto.Logs.AndroidConfigFetchProto.Builder; public clearReason(): com.google.android.gms.config.proto.Logs.AndroidConfigFetchProto.Builder; public mergeReason(param0: com.google.android.gms.config.proto.Logs.ConfigFetchReason): com.google.android.gms.config.proto.Logs.AndroidConfigFetchProto.Builder; public hasReason(): boolean; public getReason(): com.google.android.gms.config.proto.Logs.ConfigFetchReason; public setReason(param0: com.google.android.gms.config.proto.Logs.ConfigFetchReason.Builder): com.google.android.gms.config.proto.Logs.AndroidConfigFetchProto.Builder; } } export class AndroidConfigFetchProtoOrBuilder { public static class: java.lang.Class<com.google.android.gms.config.proto.Logs.AndroidConfigFetchProtoOrBuilder>; /** * Constructs a new instance of the com.google.android.gms.config.proto.Logs$AndroidConfigFetchProtoOrBuilder interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { hasReason(): boolean; getReason(): com.google.android.gms.config.proto.Logs.ConfigFetchReason; }); public constructor(); public hasReason(): boolean; public getReason(): com.google.android.gms.config.proto.Logs.ConfigFetchReason; } export class ConfigFetchReason extends com.google.protobuf.GeneratedMessageLite<com.google.android.gms.config.proto.Logs.ConfigFetchReason,com.google.android.gms.config.proto.Logs.ConfigFetchReason.Builder> implements com.google.android.gms.config.proto.Logs.ConfigFetchReasonOrBuilder { public static class: java.lang.Class<com.google.android.gms.config.proto.Logs.ConfigFetchReason>; public static TYPE_FIELD_NUMBER: number; public static parseFrom(param0: native.Array<number>): com.google.android.gms.config.proto.Logs.ConfigFetchReason; public static parseFrom(param0: native.Array<number>, param1: com.google.protobuf.ExtensionRegistryLite): com.google.android.gms.config.proto.Logs.ConfigFetchReason; public static parseFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.android.gms.config.proto.Logs.ConfigFetchReason; public static parseDelimitedFrom(param0: java.io.InputStream): com.google.android.gms.config.proto.Logs.ConfigFetchReason; public dynamicMethod(param0: com.google.protobuf.GeneratedMessageLite.MethodToInvoke, param1: any, param2: any): any; public static parseDelimitedFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.android.gms.config.proto.Logs.ConfigFetchReason; public writeTo(param0: com.google.protobuf.CodedOutputStream): void; public static parseFrom(param0: com.google.protobuf.ByteString, param1: com.google.protobuf.ExtensionRegistryLite): com.google.android.gms.config.proto.Logs.ConfigFetchReason; public getSerializedSize(): number; public static getDefaultInstance(): com.google.android.gms.config.proto.Logs.ConfigFetchReason; public static parseFrom(param0: java.io.InputStream): com.google.android.gms.config.proto.Logs.ConfigFetchReason; public static newBuilder(param0: com.google.android.gms.config.proto.Logs.ConfigFetchReason): com.google.android.gms.config.proto.Logs.ConfigFetchReason.Builder; public getType(): com.google.android.gms.config.proto.Logs.ConfigFetchReason.AndroidConfigFetchType; public hasType(): boolean; public static parseFrom(param0: com.google.protobuf.ByteString): com.google.android.gms.config.proto.Logs.ConfigFetchReason; public static newBuilder(): com.google.android.gms.config.proto.Logs.ConfigFetchReason.Builder; public static parser(): com.google.protobuf.Parser<com.google.android.gms.config.proto.Logs.ConfigFetchReason>; public static parseFrom(param0: com.google.protobuf.CodedInputStream): com.google.android.gms.config.proto.Logs.ConfigFetchReason; public static parseFrom(param0: com.google.protobuf.CodedInputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.android.gms.config.proto.Logs.ConfigFetchReason; } export module ConfigFetchReason { export class AndroidConfigFetchType extends com.google.protobuf.Internal.EnumLite { public static class: java.lang.Class<com.google.android.gms.config.proto.Logs.ConfigFetchReason.AndroidConfigFetchType>; public static UNKNOWN: com.google.android.gms.config.proto.Logs.ConfigFetchReason.AndroidConfigFetchType; public static SCHEDULED: com.google.android.gms.config.proto.Logs.ConfigFetchReason.AndroidConfigFetchType; public static BOOT_COMPLETED: com.google.android.gms.config.proto.Logs.ConfigFetchReason.AndroidConfigFetchType; public static PACKAGE_ADDED: com.google.android.gms.config.proto.Logs.ConfigFetchReason.AndroidConfigFetchType; public static PACKAGE_REMOVED: com.google.android.gms.config.proto.Logs.ConfigFetchReason.AndroidConfigFetchType; public static GMS_CORE_UPDATED: com.google.android.gms.config.proto.Logs.ConfigFetchReason.AndroidConfigFetchType; public static SECRET_CODE: com.google.android.gms.config.proto.Logs.ConfigFetchReason.AndroidConfigFetchType; public static UNKNOWN_VALUE: number; public static SCHEDULED_VALUE: number; public static BOOT_COMPLETED_VALUE: number; public static PACKAGE_ADDED_VALUE: number; public static PACKAGE_REMOVED_VALUE: number; public static GMS_CORE_UPDATED_VALUE: number; public static SECRET_CODE_VALUE: number; public static values(): native.Array<com.google.android.gms.config.proto.Logs.ConfigFetchReason.AndroidConfigFetchType>; public getNumber(): number; public static valueOf(param0: number): com.google.android.gms.config.proto.Logs.ConfigFetchReason.AndroidConfigFetchType; public static forNumber(param0: number): com.google.android.gms.config.proto.Logs.ConfigFetchReason.AndroidConfigFetchType; public static valueOf(param0: string): com.google.android.gms.config.proto.Logs.ConfigFetchReason.AndroidConfigFetchType; public static internalGetValueMap(): com.google.protobuf.Internal.EnumLiteMap<com.google.android.gms.config.proto.Logs.ConfigFetchReason.AndroidConfigFetchType>; } export class Builder extends com.google.protobuf.GeneratedMessageLite.Builder<com.google.android.gms.config.proto.Logs.ConfigFetchReason,com.google.android.gms.config.proto.Logs.ConfigFetchReason.Builder> implements com.google.android.gms.config.proto.Logs.ConfigFetchReasonOrBuilder { public static class: java.lang.Class<com.google.android.gms.config.proto.Logs.ConfigFetchReason.Builder>; public setType(param0: com.google.android.gms.config.proto.Logs.ConfigFetchReason.AndroidConfigFetchType): com.google.android.gms.config.proto.Logs.ConfigFetchReason.Builder; public clearType(): com.google.android.gms.config.proto.Logs.ConfigFetchReason.Builder; public hasType(): boolean; public getType(): com.google.android.gms.config.proto.Logs.ConfigFetchReason.AndroidConfigFetchType; } } export class ConfigFetchReasonOrBuilder { public static class: java.lang.Class<com.google.android.gms.config.proto.Logs.ConfigFetchReasonOrBuilder>; /** * Constructs a new instance of the com.google.android.gms.config.proto.Logs$ConfigFetchReasonOrBuilder interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { hasType(): boolean; getType(): com.google.android.gms.config.proto.Logs.ConfigFetchReason.AndroidConfigFetchType; }); public constructor(); public getType(): com.google.android.gms.config.proto.Logs.ConfigFetchReason.AndroidConfigFetchType; public hasType(): boolean; } } } } } } } } declare module com { export module google { export module firebase { export module remoteconfig { export class BuildConfig { public static class: java.lang.Class<com.google.firebase.remoteconfig.BuildConfig>; public static DEBUG: boolean; public static APPLICATION_ID: string; public static BUILD_TYPE: string; public static FLAVOR: string; public static VERSION_CODE: number; public static VERSION_NAME: string; public constructor(); } } } } } declare module com { export module google { export module firebase { export module remoteconfig { export class FirebaseRemoteConfig { public static class: java.lang.Class<com.google.firebase.remoteconfig.FirebaseRemoteConfig>; public static DEFAULT_VALUE_FOR_STRING: string; public static DEFAULT_VALUE_FOR_LONG: number; public static DEFAULT_VALUE_FOR_DOUBLE: number; public static DEFAULT_VALUE_FOR_BOOLEAN: boolean; public static DEFAULT_VALUE_FOR_BYTE_ARRAY: native.Array<number>; public static VALUE_SOURCE_STATIC: number; public static VALUE_SOURCE_DEFAULT: number; public static VALUE_SOURCE_REMOTE: number; public static LAST_FETCH_STATUS_SUCCESS: number; public static LAST_FETCH_STATUS_NO_FETCH_YET: number; public static LAST_FETCH_STATUS_FAILURE: number; public static LAST_FETCH_STATUS_THROTTLED: number; public static TAG: string; public setDefaults(param0: java.util.Map<string,any>): void; public getInfo(): com.google.firebase.remoteconfig.FirebaseRemoteConfigInfo; public static getInstance(): com.google.firebase.remoteconfig.FirebaseRemoteConfig; public ensureInitialized(): com.google.android.gms.tasks.Task<com.google.firebase.remoteconfig.FirebaseRemoteConfigInfo>; public getString(param0: string): string; public fetchAndActivate(): com.google.android.gms.tasks.Task<java.lang.Boolean>; public activate(): com.google.android.gms.tasks.Task<java.lang.Boolean>; public getKeysByPrefix(param0: string): java.util.Set<string>; public setConfigSettings(param0: com.google.firebase.remoteconfig.FirebaseRemoteConfigSettings): void; public setConfigSettingsAsync(param0: com.google.firebase.remoteconfig.FirebaseRemoteConfigSettings): com.google.android.gms.tasks.Task<java.lang.Void>; public getBoolean(param0: string): boolean; public fetch(param0: number): com.google.android.gms.tasks.Task<java.lang.Void>; public setDefaultsAsync(param0: java.util.Map<string,any>): com.google.android.gms.tasks.Task<java.lang.Void>; public fetch(): com.google.android.gms.tasks.Task<java.lang.Void>; public getValue(param0: string): com.google.firebase.remoteconfig.FirebaseRemoteConfigValue; public setDefaultsAsync(param0: number): com.google.android.gms.tasks.Task<java.lang.Void>; public getByteArray(param0: string): native.Array<number>; public activateFetched(): boolean; public getDouble(param0: string): number; public reset(): com.google.android.gms.tasks.Task<java.lang.Void>; public getLong(param0: string): number; public setDefaults(param0: number): void; public getAll(): java.util.Map<string,com.google.firebase.remoteconfig.FirebaseRemoteConfigValue>; public static getInstance(param0: com.google.firebase.FirebaseApp): com.google.firebase.remoteconfig.FirebaseRemoteConfig; } } } } } declare module com { export module google { export module firebase { export module remoteconfig { export class FirebaseRemoteConfigClientException extends com.google.firebase.remoteconfig.FirebaseRemoteConfigException { public static class: java.lang.Class<com.google.firebase.remoteconfig.FirebaseRemoteConfigClientException>; public constructor(param0: string, param1: java.lang.Throwable); public constructor(param0: string); } } } } } declare module com { export module google { export module firebase { export module remoteconfig { export class FirebaseRemoteConfigException { public static class: java.lang.Class<com.google.firebase.remoteconfig.FirebaseRemoteConfigException>; public constructor(param0: string, param1: java.lang.Throwable); public constructor(param0: string); } } } } } declare module com { export module google { export module firebase { export module remoteconfig { export class FirebaseRemoteConfigFetchException extends com.google.firebase.remoteconfig.FirebaseRemoteConfigException { public static class: java.lang.Class<com.google.firebase.remoteconfig.FirebaseRemoteConfigFetchException>; public constructor(param0: string, param1: java.lang.Throwable); public constructor(param0: string); } } } } } declare module com { export module google { export module firebase { export module remoteconfig { export class FirebaseRemoteConfigFetchThrottledException extends com.google.firebase.remoteconfig.FirebaseRemoteConfigFetchException { public static class: java.lang.Class<com.google.firebase.remoteconfig.FirebaseRemoteConfigFetchThrottledException>; public getThrottleEndTimeMillis(): number; public constructor(param0: string, param1: java.lang.Throwable); public constructor(param0: string); public constructor(param0: string, param1: number); public constructor(param0: number); } } } } } declare module com { export module google { export module firebase { export module remoteconfig { export class FirebaseRemoteConfigInfo { public static class: java.lang.Class<com.google.firebase.remoteconfig.FirebaseRemoteConfigInfo>; /** * Constructs a new instance of the com.google.firebase.remoteconfig.FirebaseRemoteConfigInfo interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { getFetchTimeMillis(): number; getLastFetchStatus(): number; getConfigSettings(): com.google.firebase.remoteconfig.FirebaseRemoteConfigSettings; }); public constructor(); public getFetchTimeMillis(): number; public getConfigSettings(): com.google.firebase.remoteconfig.FirebaseRemoteConfigSettings; public getLastFetchStatus(): number; } } } } } declare module com { export module google { export module firebase { export module remoteconfig { export class FirebaseRemoteConfigServerException extends com.google.firebase.remoteconfig.FirebaseRemoteConfigException { public static class: java.lang.Class<com.google.firebase.remoteconfig.FirebaseRemoteConfigServerException>; public getHttpStatusCode(): number; public constructor(param0: string, param1: java.lang.Throwable); public constructor(param0: string); public constructor(param0: number, param1: string, param2: java.lang.Throwable); public constructor(param0: number, param1: string); } } } } } declare module com { export module google { export module firebase { export module remoteconfig { export class FirebaseRemoteConfigSettings { public static class: java.lang.Class<com.google.firebase.remoteconfig.FirebaseRemoteConfigSettings>; public isDeveloperModeEnabled(): boolean; public getMinimumFetchIntervalInSeconds(): number; public getFetchTimeoutInSeconds(): number; public toBuilder(): com.google.firebase.remoteconfig.FirebaseRemoteConfigSettings.Builder; } export module FirebaseRemoteConfigSettings { export class Builder { public static class: java.lang.Class<com.google.firebase.remoteconfig.FirebaseRemoteConfigSettings.Builder>; public setMinimumFetchIntervalInSeconds(param0: number): com.google.firebase.remoteconfig.FirebaseRemoteConfigSettings.Builder; public constructor(); public setFetchTimeoutInSeconds(param0: number): com.google.firebase.remoteconfig.FirebaseRemoteConfigSettings.Builder; public setDeveloperModeEnabled(param0: boolean): com.google.firebase.remoteconfig.FirebaseRemoteConfigSettings.Builder; public build(): com.google.firebase.remoteconfig.FirebaseRemoteConfigSettings; } } } } } } declare module com { export module google { export module firebase { export module remoteconfig { export class FirebaseRemoteConfigValue { public static class: java.lang.Class<com.google.firebase.remoteconfig.FirebaseRemoteConfigValue>; /** * Constructs a new instance of the com.google.firebase.remoteconfig.FirebaseRemoteConfigValue interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { asLong(): number; asDouble(): number; asString(): string; asByteArray(): native.Array<number>; asBoolean(): boolean; getSource(): number; }); public constructor(); public asLong(): number; public asBoolean(): boolean; public getSource(): number; public asByteArray(): native.Array<number>; public asString(): string; public asDouble(): number; } } } } } declare module com { export module google { export module firebase { export module remoteconfig { export class RemoteConfigComponent { public static class: java.lang.Class<com.google.firebase.remoteconfig.RemoteConfigComponent>; public static ACTIVATE_FILE_NAME: string; public static FETCH_FILE_NAME: string; public static DEFAULTS_FILE_NAME: string; public static NETWORK_CONNECTION_TIMEOUT_IN_SECONDS: number; public static DEFAULT_NAMESPACE: string; public constructor(param0: globalAndroid.content.Context, param1: java.util.concurrent.ExecutorService, param2: com.google.firebase.FirebaseApp, param3: com.google.firebase.iid.FirebaseInstanceId, param4: com.google.firebase.abt.FirebaseABTesting, param5: com.google.firebase.analytics.connector.AnalyticsConnector, param6: com.google.firebase.remoteconfig.internal.LegacyConfigsHandler, param7: boolean); public setCustomHeaders(param0: java.util.Map<string,string>): void; public static getCacheClient(param0: globalAndroid.content.Context, param1: string, param2: string, param3: string): com.google.firebase.remoteconfig.internal.ConfigCacheClient; public get(param0: string): com.google.firebase.remoteconfig.FirebaseRemoteConfig; } } } } } declare module com { export module google { export module firebase { export module remoteconfig { export class RemoteConfigConstants { public static class: java.lang.Class<com.google.firebase.remoteconfig.RemoteConfigConstants>; public static FETCH_REGEX_URL: string; } export module RemoteConfigConstants { export class ExperimentDescriptionFieldKey { public static class: java.lang.Class<com.google.firebase.remoteconfig.RemoteConfigConstants.ExperimentDescriptionFieldKey>; /** * Constructs a new instance of the com.google.firebase.remoteconfig.RemoteConfigConstants$ExperimentDescriptionFieldKey interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { }); public constructor(); public static VARIANT_ID: string; public static EXPERIMENT_ID: string; } export class RequestFieldKey { public static class: java.lang.Class<com.google.firebase.remoteconfig.RemoteConfigConstants.RequestFieldKey>; /** * Constructs a new instance of the com.google.firebase.remoteconfig.RemoteConfigConstants$RequestFieldKey interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { }); public constructor(); public static APP_ID: string; public static TIME_ZONE: string; public static LANGUAGE_CODE: string; public static INSTANCE_ID_TOKEN: string; public static PLATFORM_VERSION: string; public static SDK_VERSION: string; public static ANALYTICS_USER_PROPERTIES: string; public static PACKAGE_NAME: string; public static APP_VERSION: string; public static INSTANCE_ID: string; public static COUNTRY_CODE: string; } export class ResponseFieldKey { public static class: java.lang.Class<com.google.firebase.remoteconfig.RemoteConfigConstants.ResponseFieldKey>; /** * Constructs a new instance of the com.google.firebase.remoteconfig.RemoteConfigConstants$ResponseFieldKey interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { }); public constructor(); public static STATE: string; public static EXPERIMENT_DESCRIPTIONS: string; public static ENTRIES: string; } } } } } } declare module com { export module google { export module firebase { export module remoteconfig { export class RemoteConfigRegistrar { public static class: java.lang.Class<com.google.firebase.remoteconfig.RemoteConfigRegistrar>; public constructor(); public getComponents(): java.util.List<com.google.firebase.components.Component<any>>; } } } } } declare module com { export module google { export module firebase { export module remoteconfig { export module internal { export class Code { public static class: java.lang.Class<com.google.firebase.remoteconfig.internal.Code>; /** * Constructs a new instance of the com.google.firebase.remoteconfig.internal.Code interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { }); public constructor(); public static DEADLINE_EXCEEDED: number; public static OUT_OF_RANGE: number; public static NOT_FOUND: number; public static UNAUTHENTICATED: number; public static RESOURCE_EXHAUSTED: number; public static FAILED_PRECONDITION: number; public static ALREADY_EXISTS: number; public static UNIMPLEMENTED: number; public static UNAVAILABLE: number; public static INTERNAL: number; public static UNKNOWN: number; public static ABORTED: number; public static OK: number; public static INVALID_ARGUMENT: number; public static PERMISSION_DENIED: number; public static CANCELLED: number; public static DATA_LOSS: number; } } } } } } declare module com { export module google { export module firebase { export module remoteconfig { export module internal { export class ConfigCacheClient { public static class: java.lang.Class<com.google.firebase.remoteconfig.internal.ConfigCacheClient>; public putWithoutWaitingForDiskWrite(param0: com.google.firebase.remoteconfig.internal.ConfigContainer): com.google.android.gms.tasks.Task<com.google.firebase.remoteconfig.internal.ConfigContainer>; public getBlocking(): com.google.firebase.remoteconfig.internal.ConfigContainer; public static getInstance(param0: java.util.concurrent.ExecutorService, param1: com.google.firebase.remoteconfig.internal.ConfigStorageClient): com.google.firebase.remoteconfig.internal.ConfigCacheClient; public put(param0: com.google.firebase.remoteconfig.internal.ConfigContainer, param1: boolean): com.google.android.gms.tasks.Task<com.google.firebase.remoteconfig.internal.ConfigContainer>; public get(): com.google.android.gms.tasks.Task<com.google.firebase.remoteconfig.internal.ConfigContainer>; public clear(): void; public put(param0: com.google.firebase.remoteconfig.internal.ConfigContainer): com.google.android.gms.tasks.Task<com.google.firebase.remoteconfig.internal.ConfigContainer>; public static clearInstancesForTest(): void; } export module ConfigCacheClient { export class AwaitListener<TResult> extends java.lang.Object { public static class: java.lang.Class<com.google.firebase.remoteconfig.internal.ConfigCacheClient.AwaitListener<any>>; public onFailure(param0: java.lang.Exception): void; public await(param0: number, param1: java.util.concurrent.TimeUnit): boolean; public await(): void; public onSuccess(param0: TResult): void; public onCanceled(): void; } } } } } } } declare module com { export module google { export module firebase { export module remoteconfig { export module internal { export class ConfigContainer { public static class: java.lang.Class<com.google.firebase.remoteconfig.internal.ConfigContainer>; public getFetchTime(): java.util.Date; public static newBuilder(param0: com.google.firebase.remoteconfig.internal.ConfigContainer): com.google.firebase.remoteconfig.internal.ConfigContainer.Builder; public getAbtExperiments(): org.json.JSONArray; public getConfigs(): org.json.JSONObject; public static newBuilder(): com.google.firebase.remoteconfig.internal.ConfigContainer.Builder; public equals(param0: any): boolean; public hashCode(): number; public toString(): string; } export module ConfigContainer { export class Builder { public static class: java.lang.Class<com.google.firebase.remoteconfig.internal.ConfigContainer.Builder>; public constructor(param0: com.google.firebase.remoteconfig.internal.ConfigContainer); public withFetchTime(param0: java.util.Date): com.google.firebase.remoteconfig.internal.ConfigContainer.Builder; public build(): com.google.firebase.remoteconfig.internal.ConfigContainer; public replaceConfigsWith(param0: org.json.JSONObject): com.google.firebase.remoteconfig.internal.ConfigContainer.Builder; public withAbtExperiments(param0: org.json.JSONArray): com.google.firebase.remoteconfig.internal.ConfigContainer.Builder; public replaceConfigsWith(param0: java.util.Map<string,string>): com.google.firebase.remoteconfig.internal.ConfigContainer.Builder; } } } } } } } declare module com { export module google { export module firebase { export module remoteconfig { export module internal { export class ConfigFetchHandler { public static class: java.lang.Class<com.google.firebase.remoteconfig.internal.ConfigFetchHandler>; public static DEFAULT_MINIMUM_FETCH_INTERVAL_IN_SECONDS: number; public constructor(param0: com.google.firebase.iid.FirebaseInstanceId, param1: com.google.firebase.analytics.connector.AnalyticsConnector, param2: java.util.concurrent.Executor, param3: com.google.android.gms.common.util.Clock, param4: java.util.Random, param5: com.google.firebase.remoteconfig.internal.ConfigCacheClient, param6: com.google.firebase.remoteconfig.internal.ConfigFetchHttpClient, param7: com.google.firebase.remoteconfig.internal.ConfigMetadataClient, param8: java.util.Map<string,string>); public getAnalyticsConnector(): com.google.firebase.analytics.connector.AnalyticsConnector; public fetch(): com.google.android.gms.tasks.Task<com.google.firebase.remoteconfig.internal.ConfigFetchHandler.FetchResponse>; public fetch(param0: number): com.google.android.gms.tasks.Task<com.google.firebase.remoteconfig.internal.ConfigFetchHandler.FetchResponse>; } export module ConfigFetchHandler { export class FetchResponse { public static class: java.lang.Class<com.google.firebase.remoteconfig.internal.ConfigFetchHandler.FetchResponse>; public static forBackendUpdatesFetched(param0: com.google.firebase.remoteconfig.internal.ConfigContainer, param1: string): com.google.firebase.remoteconfig.internal.ConfigFetchHandler.FetchResponse; public static forBackendHasNoUpdates(param0: java.util.Date): com.google.firebase.remoteconfig.internal.ConfigFetchHandler.FetchResponse; public static forLocalStorageUsed(param0: java.util.Date): com.google.firebase.remoteconfig.internal.ConfigFetchHandler.FetchResponse; public getFetchedConfigs(): com.google.firebase.remoteconfig.internal.ConfigContainer; } export module FetchResponse { export class Status { public static class: java.lang.Class<com.google.firebase.remoteconfig.internal.ConfigFetchHandler.FetchResponse.Status>; /** * Constructs a new instance of the com.google.firebase.remoteconfig.internal.ConfigFetchHandler$FetchResponse$Status interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { }); public constructor(); public static BACKEND_HAS_NO_UPDATES: number; public static BACKEND_UPDATES_FETCHED: number; public static LOCAL_STORAGE_USED: number; } } } } } } } } declare module com { export module google { export module firebase { export module remoteconfig { export module internal { export class ConfigFetchHttpClient { public static class: java.lang.Class<com.google.firebase.remoteconfig.internal.ConfigFetchHttpClient>; public getReadTimeoutInSeconds(): number; public getConnectTimeoutInSeconds(): number; public constructor(param0: globalAndroid.content.Context, param1: string, param2: string, param3: string, param4: number, param5: number); } } } } } } declare module com { export module google { export module firebase { export module remoteconfig { export module internal { export class ConfigGetParameterHandler { public static class: java.lang.Class<com.google.firebase.remoteconfig.internal.ConfigGetParameterHandler>; public static FRC_BYTE_ARRAY_ENCODING: java.nio.charset.Charset; public getKeysByPrefix(param0: string): java.util.Set<string>; public getDouble(param0: string): number; public getValue(param0: string): com.google.firebase.remoteconfig.FirebaseRemoteConfigValue; public getByteArray(param0: string): native.Array<number>; public getLong(param0: string): number; public getAll(): java.util.Map<string,com.google.firebase.remoteconfig.FirebaseRemoteConfigValue>; public constructor(param0: com.google.firebase.remoteconfig.internal.ConfigCacheClient, param1: com.google.firebase.remoteconfig.internal.ConfigCacheClient); public getString(param0: string): string; public getBoolean(param0: string): boolean; } } } } } } declare module com { export module google { export module firebase { export module remoteconfig { export module internal { export class ConfigMetadataClient { public static class: java.lang.Class<com.google.firebase.remoteconfig.internal.ConfigMetadataClient>; public static LAST_FETCH_TIME_IN_MILLIS_NO_FETCH_YET: number; public getInfo(): com.google.firebase.remoteconfig.FirebaseRemoteConfigInfo; public getFetchTimeoutInSeconds(): number; public getMinimumFetchIntervalInSeconds(): number; public setConfigSettingsWithoutWaitingOnDiskWrite(param0: com.google.firebase.remoteconfig.FirebaseRemoteConfigSettings): void; public constructor(param0: globalAndroid.content.SharedPreferences); public clear(): void; public setConfigSettings(param0: com.google.firebase.remoteconfig.FirebaseRemoteConfigSettings): void; public isDeveloperModeEnabled(): boolean; } export module ConfigMetadataClient { export class BackoffMetadata { public static class: java.lang.Class<com.google.firebase.remoteconfig.internal.ConfigMetadataClient.BackoffMetadata>; } } } } } } } declare module com { export module google { export module firebase { export module remoteconfig { export module internal { export class ConfigStorageClient { public static class: java.lang.Class<com.google.firebase.remoteconfig.internal.ConfigStorageClient>; public clear(): java.lang.Void; public read(): com.google.firebase.remoteconfig.internal.ConfigContainer; public write(param0: com.google.firebase.remoteconfig.internal.ConfigContainer): java.lang.Void; public static getInstance(param0: globalAndroid.content.Context, param1: string): com.google.firebase.remoteconfig.internal.ConfigStorageClient; public static clearInstancesForTest(): void; } } } } } } declare module com { export module google { export module firebase { export module remoteconfig { export module internal { export class DefaultsXmlParser { public static class: java.lang.Class<com.google.firebase.remoteconfig.internal.DefaultsXmlParser>; public constructor(); public static getDefaultsFromXml(param0: globalAndroid.content.Context, param1: number): java.util.Map<string,string>; } } } } } } declare module com { export module google { export module firebase { export module remoteconfig { export module internal { export class FirebaseRemoteConfigInfoImpl extends com.google.firebase.remoteconfig.FirebaseRemoteConfigInfo { public static class: java.lang.Class<com.google.firebase.remoteconfig.internal.FirebaseRemoteConfigInfoImpl>; public getConfigSettings(): com.google.firebase.remoteconfig.FirebaseRemoteConfigSettings; public getLastFetchStatus(): number; public getFetchTimeMillis(): number; } export module FirebaseRemoteConfigInfoImpl { export class Builder { public static class: java.lang.Class<com.google.firebase.remoteconfig.internal.FirebaseRemoteConfigInfoImpl.Builder>; public withLastSuccessfulFetchTimeInMillis(param0: number): com.google.firebase.remoteconfig.internal.FirebaseRemoteConfigInfoImpl.Builder; public build(): com.google.firebase.remoteconfig.internal.FirebaseRemoteConfigInfoImpl; } } } } } } } declare module com { export module google { export module firebase { export module remoteconfig { export module internal { export class FirebaseRemoteConfigValueImpl extends com.google.firebase.remoteconfig.FirebaseRemoteConfigValue { public static class: java.lang.Class<com.google.firebase.remoteconfig.internal.FirebaseRemoteConfigValueImpl>; public asDouble(): number; public getSource(): number; public asLong(): number; public asByteArray(): native.Array<number>; public asString(): string; public asBoolean(): boolean; } } } } } } declare module com { export module google { export module firebase { export module remoteconfig { export module internal { export class LegacyConfigsHandler { public static class: java.lang.Class<com.google.firebase.remoteconfig.internal.LegacyConfigsHandler>; public static EXPERIMENT_ID_KEY: string; public static EXPERIMENT_VARIANT_ID_KEY: string; public static EXPERIMENT_START_TIME_KEY: string; public static EXPERIMENT_TRIGGER_EVENT_KEY: string; public static EXPERIMENT_TRIGGER_TIMEOUT_KEY: string; public static EXPERIMENT_TIME_TO_LIVE_KEY: string; public saveLegacyConfigsIfNecessary(): boolean; public constructor(param0: globalAndroid.content.Context, param1: string); } export module LegacyConfigsHandler { export class NamespaceLegacyConfigs { public static class: java.lang.Class<com.google.firebase.remoteconfig.internal.LegacyConfigsHandler.NamespaceLegacyConfigs>; } } } } } } } declare module com { export module google { export module firebase { export module remoteconfig { export module proto { export class ConfigPersistence { public static class: java.lang.Class<com.google.firebase.remoteconfig.proto.ConfigPersistence>; public static registerAllExtensions(param0: com.google.protobuf.ExtensionRegistryLite): void; } export module ConfigPersistence { export class ConfigHolder extends com.google.protobuf.GeneratedMessageLite<com.google.firebase.remoteconfig.proto.ConfigPersistence.ConfigHolder,com.google.firebase.remoteconfig.proto.ConfigPersistence.ConfigHolder.Builder> implements com.google.firebase.remoteconfig.proto.ConfigPersistence.ConfigHolderOrBuilder { public static class: java.lang.Class<com.google.firebase.remoteconfig.proto.ConfigPersistence.ConfigHolder>; public static NAMESPACE_KEY_VALUE_FIELD_NUMBER: number; public static TIMESTAMP_FIELD_NUMBER: number; public static EXPERIMENT_PAYLOAD_FIELD_NUMBER: number; public static parseDelimitedFrom(param0: java.io.InputStream): com.google.firebase.remoteconfig.proto.ConfigPersistence.ConfigHolder; public static parseFrom(param0: com.google.protobuf.ByteString): com.google.firebase.remoteconfig.proto.ConfigPersistence.ConfigHolder; public static parseFrom(param0: java.io.InputStream): com.google.firebase.remoteconfig.proto.ConfigPersistence.ConfigHolder; public getNamespaceKeyValueCount(): number; public dynamicMethod(param0: com.google.protobuf.GeneratedMessageLite.MethodToInvoke, param1: any, param2: any): any; public getNamespaceKeyValueOrBuilderList(): java.util.List<any>; public static parser(): com.google.protobuf.Parser<com.google.firebase.remoteconfig.proto.ConfigPersistence.ConfigHolder>; public static parseFrom(param0: native.Array<number>, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firebase.remoteconfig.proto.ConfigPersistence.ConfigHolder; public static parseFrom(param0: com.google.protobuf.CodedInputStream): com.google.firebase.remoteconfig.proto.ConfigPersistence.ConfigHolder; public static parseFrom(param0: com.google.protobuf.CodedInputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firebase.remoteconfig.proto.ConfigPersistence.ConfigHolder; public getSerializedSize(): number; public static parseFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firebase.remoteconfig.proto.ConfigPersistence.ConfigHolder; public static newBuilder(): com.google.firebase.remoteconfig.proto.ConfigPersistence.ConfigHolder.Builder; public static parseDelimitedFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firebase.remoteconfig.proto.ConfigPersistence.ConfigHolder; public hasTimestamp(): boolean; public getExperimentPayloadCount(): number; public getExperimentPayloadList(): java.util.List<com.google.protobuf.ByteString>; public getNamespaceKeyValue(param0: number): com.google.firebase.remoteconfig.proto.ConfigPersistence.NamespaceKeyValue; public static parseFrom(param0: com.google.protobuf.ByteString, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firebase.remoteconfig.proto.ConfigPersistence.ConfigHolder; public static parseFrom(param0: native.Array<number>): com.google.firebase.remoteconfig.proto.ConfigPersistence.ConfigHolder; public static getDefaultInstance(): com.google.firebase.remoteconfig.proto.ConfigPersistence.ConfigHolder; public getNamespaceKeyValueList(): java.util.List<com.google.firebase.remoteconfig.proto.ConfigPersistence.NamespaceKeyValue>; public writeTo(param0: com.google.protobuf.CodedOutputStream): void; public static newBuilder(param0: com.google.firebase.remoteconfig.proto.ConfigPersistence.ConfigHolder): com.google.firebase.remoteconfig.proto.ConfigPersistence.ConfigHolder.Builder; public getExperimentPayload(param0: number): com.google.protobuf.ByteString; public getTimestamp(): number; public getNamespaceKeyValueOrBuilder(param0: number): com.google.firebase.remoteconfig.proto.ConfigPersistence.NamespaceKeyValueOrBuilder; } export module ConfigHolder { export class Builder extends com.google.protobuf.GeneratedMessageLite.Builder<com.google.firebase.remoteconfig.proto.ConfigPersistence.ConfigHolder,com.google.firebase.remoteconfig.proto.ConfigPersistence.ConfigHolder.Builder> implements com.google.firebase.remoteconfig.proto.ConfigPersistence.ConfigHolderOrBuilder { public static class: java.lang.Class<com.google.firebase.remoteconfig.proto.ConfigPersistence.ConfigHolder.Builder>; public hasTimestamp(): boolean; public removeNamespaceKeyValue(param0: number): com.google.firebase.remoteconfig.proto.ConfigPersistence.ConfigHolder.Builder; public addAllExperimentPayload(param0: java.lang.Iterable<any>): com.google.firebase.remoteconfig.proto.ConfigPersistence.ConfigHolder.Builder; public getExperimentPayloadList(): java.util.List<com.google.protobuf.ByteString>; public addExperimentPayload(param0: com.google.protobuf.ByteString): com.google.firebase.remoteconfig.proto.ConfigPersistence.ConfigHolder.Builder; public getExperimentPayloadCount(): number; public getNamespaceKeyValueList(): java.util.List<com.google.firebase.remoteconfig.proto.ConfigPersistence.NamespaceKeyValue>; public addAllNamespaceKeyValue(param0: java.lang.Iterable<any>): com.google.firebase.remoteconfig.proto.ConfigPersistence.ConfigHolder.Builder; public getNamespaceKeyValue(param0: number): com.google.firebase.remoteconfig.proto.ConfigPersistence.NamespaceKeyValue; public clearTimestamp(): com.google.firebase.remoteconfig.proto.ConfigPersistence.ConfigHolder.Builder; public setExperimentPayload(param0: number, param1: com.google.protobuf.ByteString): com.google.firebase.remoteconfig.proto.ConfigPersistence.ConfigHolder.Builder; public setTimestamp(param0: number): com.google.firebase.remoteconfig.proto.ConfigPersistence.ConfigHolder.Builder; public addNamespaceKeyValue(param0: number, param1: com.google.firebase.remoteconfig.proto.ConfigPersistence.NamespaceKeyValue.Builder): com.google.firebase.remoteconfig.proto.ConfigPersistence.ConfigHolder.Builder; public setNamespaceKeyValue(param0: number, param1: com.google.firebase.remoteconfig.proto.ConfigPersistence.NamespaceKeyValue): com.google.firebase.remoteconfig.proto.ConfigPersistence.ConfigHolder.Builder; public addNamespaceKeyValue(param0: number, param1: com.google.firebase.remoteconfig.proto.ConfigPersistence.NamespaceKeyValue): com.google.firebase.remoteconfig.proto.ConfigPersistence.ConfigHolder.Builder; public setNamespaceKeyValue(param0: number, param1: com.google.firebase.remoteconfig.proto.ConfigPersistence.NamespaceKeyValue.Builder): com.google.firebase.remoteconfig.proto.ConfigPersistence.ConfigHolder.Builder; public clearNamespaceKeyValue(): com.google.firebase.remoteconfig.proto.ConfigPersistence.ConfigHolder.Builder; public addNamespaceKeyValue(param0: com.google.firebase.remoteconfig.proto.ConfigPersistence.NamespaceKeyValue.Builder): com.google.firebase.remoteconfig.proto.ConfigPersistence.ConfigHolder.Builder; public getExperimentPayload(param0: number): com.google.protobuf.ByteString; public getNamespaceKeyValueCount(): number; public getTimestamp(): number; public addNamespaceKeyValue(param0: com.google.firebase.remoteconfig.proto.ConfigPersistence.NamespaceKeyValue): com.google.firebase.remoteconfig.proto.ConfigPersistence.ConfigHolder.Builder; public clearExperimentPayload(): com.google.firebase.remoteconfig.proto.ConfigPersistence.ConfigHolder.Builder; } } export class ConfigHolderOrBuilder { public static class: java.lang.Class<com.google.firebase.remoteconfig.proto.ConfigPersistence.ConfigHolderOrBuilder>; /** * Constructs a new instance of the com.google.firebase.remoteconfig.proto.ConfigPersistence$ConfigHolderOrBuilder interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { getNamespaceKeyValueList(): java.util.List<com.google.firebase.remoteconfig.proto.ConfigPersistence.NamespaceKeyValue>; getNamespaceKeyValue(param0: number): com.google.firebase.remoteconfig.proto.ConfigPersistence.NamespaceKeyValue; getNamespaceKeyValueCount(): number; hasTimestamp(): boolean; getTimestamp(): number; getExperimentPayloadList(): java.util.List<com.google.protobuf.ByteString>; getExperimentPayloadCount(): number; getExperimentPayload(param0: number): com.google.protobuf.ByteString; }); public constructor(); public hasTimestamp(): boolean; public getExperimentPayloadCount(): number; public getNamespaceKeyValueList(): java.util.List<com.google.firebase.remoteconfig.proto.ConfigPersistence.NamespaceKeyValue>; public getExperimentPayloadList(): java.util.List<com.google.protobuf.ByteString>; public getExperimentPayload(param0: number): com.google.protobuf.ByteString; public getNamespaceKeyValue(param0: number): com.google.firebase.remoteconfig.proto.ConfigPersistence.NamespaceKeyValue; public getTimestamp(): number; public getNamespaceKeyValueCount(): number; } export class KeyValue extends com.google.protobuf.GeneratedMessageLite<com.google.firebase.remoteconfig.proto.ConfigPersistence.KeyValue,com.google.firebase.remoteconfig.proto.ConfigPersistence.KeyValue.Builder> implements com.google.firebase.remoteconfig.proto.ConfigPersistence.KeyValueOrBuilder { public static class: java.lang.Class<com.google.firebase.remoteconfig.proto.ConfigPersistence.KeyValue>; public static KEY_FIELD_NUMBER: number; public static VALUE_FIELD_NUMBER: number; public getValue(): com.google.protobuf.ByteString; public hasValue(): boolean; public static parseDelimitedFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firebase.remoteconfig.proto.ConfigPersistence.KeyValue; public static parseFrom(param0: native.Array<number>): com.google.firebase.remoteconfig.proto.ConfigPersistence.KeyValue; public static parseFrom(param0: com.google.protobuf.ByteString): com.google.firebase.remoteconfig.proto.ConfigPersistence.KeyValue; public static parseFrom(param0: java.io.InputStream): com.google.firebase.remoteconfig.proto.ConfigPersistence.KeyValue; public static parseFrom(param0: com.google.protobuf.CodedInputStream): com.google.firebase.remoteconfig.proto.ConfigPersistence.KeyValue; public getKeyBytes(): com.google.protobuf.ByteString; public static parseFrom(param0: com.google.protobuf.ByteString, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firebase.remoteconfig.proto.ConfigPersistence.KeyValue; public static getDefaultInstance(): com.google.firebase.remoteconfig.proto.ConfigPersistence.KeyValue; public static parseFrom(param0: com.google.protobuf.CodedInputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firebase.remoteconfig.proto.ConfigPersistence.KeyValue; public dynamicMethod(param0: com.google.protobuf.GeneratedMessageLite.MethodToInvoke, param1: any, param2: any): any; public static newBuilder(): com.google.firebase.remoteconfig.proto.ConfigPersistence.KeyValue.Builder; public getKey(): string; public static parser(): com.google.protobuf.Parser<com.google.firebase.remoteconfig.proto.ConfigPersistence.KeyValue>; public writeTo(param0: com.google.protobuf.CodedOutputStream): void; public static parseFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firebase.remoteconfig.proto.ConfigPersistence.KeyValue; public static parseFrom(param0: native.Array<number>, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firebase.remoteconfig.proto.ConfigPersistence.KeyValue; public hasKey(): boolean; public getSerializedSize(): number; public static parseDelimitedFrom(param0: java.io.InputStream): com.google.firebase.remoteconfig.proto.ConfigPersistence.KeyValue; public static newBuilder(param0: com.google.firebase.remoteconfig.proto.ConfigPersistence.KeyValue): com.google.firebase.remoteconfig.proto.ConfigPersistence.KeyValue.Builder; } export module KeyValue { export class Builder extends com.google.protobuf.GeneratedMessageLite.Builder<com.google.firebase.remoteconfig.proto.ConfigPersistence.KeyValue,com.google.firebase.remoteconfig.proto.ConfigPersistence.KeyValue.Builder> implements com.google.firebase.remoteconfig.proto.ConfigPersistence.KeyValueOrBuilder { public static class: java.lang.Class<com.google.firebase.remoteconfig.proto.ConfigPersistence.KeyValue.Builder>; public getValue(): com.google.protobuf.ByteString; public hasValue(): boolean; public hasKey(): boolean; public setValue(param0: com.google.protobuf.ByteString): com.google.firebase.remoteconfig.proto.ConfigPersistence.KeyValue.Builder; public getKey(): string; public setKeyBytes(param0: com.google.protobuf.ByteString): com.google.firebase.remoteconfig.proto.ConfigPersistence.KeyValue.Builder; public clearValue(): com.google.firebase.remoteconfig.proto.ConfigPersistence.KeyValue.Builder; public setKey(param0: string): com.google.firebase.remoteconfig.proto.ConfigPersistence.KeyValue.Builder; public getKeyBytes(): com.google.protobuf.ByteString; public clearKey(): com.google.firebase.remoteconfig.proto.ConfigPersistence.KeyValue.Builder; } } export class KeyValueOrBuilder { public static class: java.lang.Class<com.google.firebase.remoteconfig.proto.ConfigPersistence.KeyValueOrBuilder>; /** * Constructs a new instance of the com.google.firebase.remoteconfig.proto.ConfigPersistence$KeyValueOrBuilder interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { hasKey(): boolean; getKey(): string; getKeyBytes(): com.google.protobuf.ByteString; hasValue(): boolean; getValue(): com.google.protobuf.ByteString; }); public constructor(); public getValue(): com.google.protobuf.ByteString; public getKey(): string; public hasValue(): boolean; public hasKey(): boolean; public getKeyBytes(): com.google.protobuf.ByteString; } export class Metadata extends com.google.protobuf.GeneratedMessageLite<com.google.firebase.remoteconfig.proto.ConfigPersistence.Metadata,com.google.firebase.remoteconfig.proto.ConfigPersistence.Metadata.Builder> implements com.google.firebase.remoteconfig.proto.ConfigPersistence.MetadataOrBuilder { public static class: java.lang.Class<com.google.firebase.remoteconfig.proto.ConfigPersistence.Metadata>; public static LAST_FETCH_STATUS_FIELD_NUMBER: number; public static DEVELOPER_MODE_ENABLED_FIELD_NUMBER: number; public static LAST_KNOWN_EXPERIMENT_START_TIME_FIELD_NUMBER: number; public hasLastKnownExperimentStartTime(): boolean; public getLastKnownExperimentStartTime(): number; public static parseFrom(param0: native.Array<number>, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firebase.remoteconfig.proto.ConfigPersistence.Metadata; public static parseFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firebase.remoteconfig.proto.ConfigPersistence.Metadata; public hasLastFetchStatus(): boolean; public static parseFrom(param0: com.google.protobuf.CodedInputStream): com.google.firebase.remoteconfig.proto.ConfigPersistence.Metadata; public static parseFrom(param0: com.google.protobuf.CodedInputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firebase.remoteconfig.proto.ConfigPersistence.Metadata; public static parseFrom(param0: java.io.InputStream): com.google.firebase.remoteconfig.proto.ConfigPersistence.Metadata; public static getDefaultInstance(): com.google.firebase.remoteconfig.proto.ConfigPersistence.Metadata; public static parseFrom(param0: com.google.protobuf.ByteString, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firebase.remoteconfig.proto.ConfigPersistence.Metadata; public static parseDelimitedFrom(param0: java.io.InputStream): com.google.firebase.remoteconfig.proto.ConfigPersistence.Metadata; public dynamicMethod(param0: com.google.protobuf.GeneratedMessageLite.MethodToInvoke, param1: any, param2: any): any; public static newBuilder(param0: com.google.firebase.remoteconfig.proto.ConfigPersistence.Metadata): com.google.firebase.remoteconfig.proto.ConfigPersistence.Metadata.Builder; public static parseFrom(param0: com.google.protobuf.ByteString): com.google.firebase.remoteconfig.proto.ConfigPersistence.Metadata; public static parser(): com.google.protobuf.Parser<com.google.firebase.remoteconfig.proto.ConfigPersistence.Metadata>; public static parseFrom(param0: native.Array<number>): com.google.firebase.remoteconfig.proto.ConfigPersistence.Metadata; public static parseDelimitedFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firebase.remoteconfig.proto.ConfigPersistence.Metadata; public getLastFetchStatus(): number; public getDeveloperModeEnabled(): boolean; public writeTo(param0: com.google.protobuf.CodedOutputStream): void; public getSerializedSize(): number; public hasDeveloperModeEnabled(): boolean; public static newBuilder(): com.google.firebase.remoteconfig.proto.ConfigPersistence.Metadata.Builder; } export module Metadata { export class Builder extends com.google.protobuf.GeneratedMessageLite.Builder<com.google.firebase.remoteconfig.proto.ConfigPersistence.Metadata,com.google.firebase.remoteconfig.proto.ConfigPersistence.Metadata.Builder> implements com.google.firebase.remoteconfig.proto.ConfigPersistence.MetadataOrBuilder { public static class: java.lang.Class<com.google.firebase.remoteconfig.proto.ConfigPersistence.Metadata.Builder>; public clearLastKnownExperimentStartTime(): com.google.firebase.remoteconfig.proto.ConfigPersistence.Metadata.Builder; public hasLastKnownExperimentStartTime(): boolean; public setLastFetchStatus(param0: number): com.google.firebase.remoteconfig.proto.ConfigPersistence.Metadata.Builder; public getLastKnownExperimentStartTime(): number; public getDeveloperModeEnabled(): boolean; public clearLastFetchStatus(): com.google.firebase.remoteconfig.proto.ConfigPersistence.Metadata.Builder; public clearDeveloperModeEnabled(): com.google.firebase.remoteconfig.proto.ConfigPersistence.Metadata.Builder; public hasLastFetchStatus(): boolean; public getLastFetchStatus(): number; public setDeveloperModeEnabled(param0: boolean): com.google.firebase.remoteconfig.proto.ConfigPersistence.Metadata.Builder; public hasDeveloperModeEnabled(): boolean; public setLastKnownExperimentStartTime(param0: number): com.google.firebase.remoteconfig.proto.ConfigPersistence.Metadata.Builder; } } export class MetadataOrBuilder { public static class: java.lang.Class<com.google.firebase.remoteconfig.proto.ConfigPersistence.MetadataOrBuilder>; /** * Constructs a new instance of the com.google.firebase.remoteconfig.proto.ConfigPersistence$MetadataOrBuilder interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { hasLastFetchStatus(): boolean; getLastFetchStatus(): number; hasDeveloperModeEnabled(): boolean; getDeveloperModeEnabled(): boolean; hasLastKnownExperimentStartTime(): boolean; getLastKnownExperimentStartTime(): number; }); public constructor(); public hasLastKnownExperimentStartTime(): boolean; public getLastKnownExperimentStartTime(): number; public getLastFetchStatus(): number; public getDeveloperModeEnabled(): boolean; public hasLastFetchStatus(): boolean; public hasDeveloperModeEnabled(): boolean; } export class NamespaceKeyValue extends com.google.protobuf.GeneratedMessageLite<com.google.firebase.remoteconfig.proto.ConfigPersistence.NamespaceKeyValue,com.google.firebase.remoteconfig.proto.ConfigPersistence.NamespaceKeyValue.Builder> implements com.google.firebase.remoteconfig.proto.ConfigPersistence.NamespaceKeyValueOrBuilder { public static class: java.lang.Class<com.google.firebase.remoteconfig.proto.ConfigPersistence.NamespaceKeyValue>; public static NAMESPACE_FIELD_NUMBER: number; public static KEY_VALUE_FIELD_NUMBER: number; public getKeyValueList(): java.util.List<com.google.firebase.remoteconfig.proto.ConfigPersistence.KeyValue>; public static parseFrom(param0: com.google.protobuf.CodedInputStream): com.google.firebase.remoteconfig.proto.ConfigPersistence.NamespaceKeyValue; public static parser(): com.google.protobuf.Parser<com.google.firebase.remoteconfig.proto.ConfigPersistence.NamespaceKeyValue>; public dynamicMethod(param0: com.google.protobuf.GeneratedMessageLite.MethodToInvoke, param1: any, param2: any): any; public getNamespaceBytes(): com.google.protobuf.ByteString; public static parseFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firebase.remoteconfig.proto.ConfigPersistence.NamespaceKeyValue; public static getDefaultInstance(): com.google.firebase.remoteconfig.proto.ConfigPersistence.NamespaceKeyValue; public static newBuilder(param0: com.google.firebase.remoteconfig.proto.ConfigPersistence.NamespaceKeyValue): com.google.firebase.remoteconfig.proto.ConfigPersistence.NamespaceKeyValue.Builder; public static parseDelimitedFrom(param0: java.io.InputStream): com.google.firebase.remoteconfig.proto.ConfigPersistence.NamespaceKeyValue; public static parseFrom(param0: native.Array<number>, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firebase.remoteconfig.proto.ConfigPersistence.NamespaceKeyValue; public getSerializedSize(): number; public static parseFrom(param0: com.google.protobuf.ByteString, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firebase.remoteconfig.proto.ConfigPersistence.NamespaceKeyValue; public static parseFrom(param0: com.google.protobuf.ByteString): com.google.firebase.remoteconfig.proto.ConfigPersistence.NamespaceKeyValue; public getNamespace(): string; public getKeyValue(param0: number): com.google.firebase.remoteconfig.proto.ConfigPersistence.KeyValue; public hasNamespace(): boolean; public getKeyValueOrBuilder(param0: number): com.google.firebase.remoteconfig.proto.ConfigPersistence.KeyValueOrBuilder; public static parseFrom(param0: native.Array<number>): com.google.firebase.remoteconfig.proto.ConfigPersistence.NamespaceKeyValue; public static parseDelimitedFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firebase.remoteconfig.proto.ConfigPersistence.NamespaceKeyValue; public writeTo(param0: com.google.protobuf.CodedOutputStream): void; public getKeyValueOrBuilderList(): java.util.List<any>; public getKeyValueCount(): number; public static parseFrom(param0: java.io.InputStream): com.google.firebase.remoteconfig.proto.ConfigPersistence.NamespaceKeyValue; public static parseFrom(param0: com.google.protobuf.CodedInputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firebase.remoteconfig.proto.ConfigPersistence.NamespaceKeyValue; public static newBuilder(): com.google.firebase.remoteconfig.proto.ConfigPersistence.NamespaceKeyValue.Builder; } export module NamespaceKeyValue { export class Builder extends com.google.protobuf.GeneratedMessageLite.Builder<com.google.firebase.remoteconfig.proto.ConfigPersistence.NamespaceKeyValue,com.google.firebase.remoteconfig.proto.ConfigPersistence.NamespaceKeyValue.Builder> implements com.google.firebase.remoteconfig.proto.ConfigPersistence.NamespaceKeyValueOrBuilder { public static class: java.lang.Class<com.google.firebase.remoteconfig.proto.ConfigPersistence.NamespaceKeyValue.Builder>; public addKeyValue(param0: com.google.firebase.remoteconfig.proto.ConfigPersistence.KeyValue): com.google.firebase.remoteconfig.proto.ConfigPersistence.NamespaceKeyValue.Builder; public removeKeyValue(param0: number): com.google.firebase.remoteconfig.proto.ConfigPersistence.NamespaceKeyValue.Builder; public getNamespaceBytes(): com.google.protobuf.ByteString; public addKeyValue(param0: number, param1: com.google.firebase.remoteconfig.proto.ConfigPersistence.KeyValue.Builder): com.google.firebase.remoteconfig.proto.ConfigPersistence.NamespaceKeyValue.Builder; public setKeyValue(param0: number, param1: com.google.firebase.remoteconfig.proto.ConfigPersistence.KeyValue.Builder): com.google.firebase.remoteconfig.proto.ConfigPersistence.NamespaceKeyValue.Builder; public clearKeyValue(): com.google.firebase.remoteconfig.proto.ConfigPersistence.NamespaceKeyValue.Builder; public setNamespaceBytes(param0: com.google.protobuf.ByteString): com.google.firebase.remoteconfig.proto.ConfigPersistence.NamespaceKeyValue.Builder; public hasNamespace(): boolean; public addKeyValue(param0: number, param1: com.google.firebase.remoteconfig.proto.ConfigPersistence.KeyValue): com.google.firebase.remoteconfig.proto.ConfigPersistence.NamespaceKeyValue.Builder; public setKeyValue(param0: number, param1: com.google.firebase.remoteconfig.proto.ConfigPersistence.KeyValue): com.google.firebase.remoteconfig.proto.ConfigPersistence.NamespaceKeyValue.Builder; public getNamespace(): string; public getKeyValueList(): java.util.List<com.google.firebase.remoteconfig.proto.ConfigPersistence.KeyValue>; public clearNamespace(): com.google.firebase.remoteconfig.proto.ConfigPersistence.NamespaceKeyValue.Builder; public addAllKeyValue(param0: java.lang.Iterable<any>): com.google.firebase.remoteconfig.proto.ConfigPersistence.NamespaceKeyValue.Builder; public addKeyValue(param0: com.google.firebase.remoteconfig.proto.ConfigPersistence.KeyValue.Builder): com.google.firebase.remoteconfig.proto.ConfigPersistence.NamespaceKeyValue.Builder; public setNamespace(param0: string): com.google.firebase.remoteconfig.proto.ConfigPersistence.NamespaceKeyValue.Builder; public getKeyValue(param0: number): com.google.firebase.remoteconfig.proto.ConfigPersistence.KeyValue; public getKeyValueCount(): number; } } export class NamespaceKeyValueOrBuilder { public static class: java.lang.Class<com.google.firebase.remoteconfig.proto.ConfigPersistence.NamespaceKeyValueOrBuilder>; /** * Constructs a new instance of the com.google.firebase.remoteconfig.proto.ConfigPersistence$NamespaceKeyValueOrBuilder interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { hasNamespace(): boolean; getNamespace(): string; getNamespaceBytes(): com.google.protobuf.ByteString; getKeyValueList(): java.util.List<com.google.firebase.remoteconfig.proto.ConfigPersistence.KeyValue>; getKeyValue(param0: number): com.google.firebase.remoteconfig.proto.ConfigPersistence.KeyValue; getKeyValueCount(): number; }); public constructor(); public getKeyValueList(): java.util.List<com.google.firebase.remoteconfig.proto.ConfigPersistence.KeyValue>; public getKeyValue(param0: number): com.google.firebase.remoteconfig.proto.ConfigPersistence.KeyValue; public hasNamespace(): boolean; public getKeyValueCount(): number; public getNamespaceBytes(): com.google.protobuf.ByteString; public getNamespace(): string; } export class PersistedConfig extends com.google.protobuf.GeneratedMessageLite<com.google.firebase.remoteconfig.proto.ConfigPersistence.PersistedConfig,com.google.firebase.remoteconfig.proto.ConfigPersistence.PersistedConfig.Builder> implements com.google.firebase.remoteconfig.proto.ConfigPersistence.PersistedConfigOrBuilder { public static class: java.lang.Class<com.google.firebase.remoteconfig.proto.ConfigPersistence.PersistedConfig>; public static FETCHED_CONFIG_HOLDER_FIELD_NUMBER: number; public static ACTIVE_CONFIG_HOLDER_FIELD_NUMBER: number; public static DEFAULTS_CONFIG_HOLDER_FIELD_NUMBER: number; public static METADATA_FIELD_NUMBER: number; public static APPLIED_RESOURCE_FIELD_NUMBER: number; public static parseDelimitedFrom(param0: java.io.InputStream): com.google.firebase.remoteconfig.proto.ConfigPersistence.PersistedConfig; public getActiveConfigHolder(): com.google.firebase.remoteconfig.proto.ConfigPersistence.ConfigHolder; public static parseFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firebase.remoteconfig.proto.ConfigPersistence.PersistedConfig; public dynamicMethod(param0: com.google.protobuf.GeneratedMessageLite.MethodToInvoke, param1: any, param2: any): any; public getAppliedResourceOrBuilderList(): java.util.List<any>; public static parser(): com.google.protobuf.Parser<com.google.firebase.remoteconfig.proto.ConfigPersistence.PersistedConfig>; public static parseFrom(param0: com.google.protobuf.ByteString): com.google.firebase.remoteconfig.proto.ConfigPersistence.PersistedConfig; public getSerializedSize(): number; public static parseFrom(param0: native.Array<number>): com.google.firebase.remoteconfig.proto.ConfigPersistence.PersistedConfig; public getFetchedConfigHolder(): com.google.firebase.remoteconfig.proto.ConfigPersistence.ConfigHolder; public hasActiveConfigHolder(): boolean; public static newBuilder(): com.google.firebase.remoteconfig.proto.ConfigPersistence.PersistedConfig.Builder; public static parseFrom(param0: java.io.InputStream): com.google.firebase.remoteconfig.proto.ConfigPersistence.PersistedConfig; public getDefaultsConfigHolder(): com.google.firebase.remoteconfig.proto.ConfigPersistence.ConfigHolder; public static parseDelimitedFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firebase.remoteconfig.proto.ConfigPersistence.PersistedConfig; public static parseFrom(param0: com.google.protobuf.CodedInputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firebase.remoteconfig.proto.ConfigPersistence.PersistedConfig; public getMetadata(): com.google.firebase.remoteconfig.proto.ConfigPersistence.Metadata; public getAppliedResourceCount(): number; public getAppliedResourceOrBuilder(param0: number): com.google.firebase.remoteconfig.proto.ConfigPersistence.ResourceOrBuilder; public static newBuilder(param0: com.google.firebase.remoteconfig.proto.ConfigPersistence.PersistedConfig): com.google.firebase.remoteconfig.proto.ConfigPersistence.PersistedConfig.Builder; public hasFetchedConfigHolder(): boolean; public writeTo(param0: com.google.protobuf.CodedOutputStream): void; public hasDefaultsConfigHolder(): boolean; public getAppliedResource(param0: number): com.google.firebase.remoteconfig.proto.ConfigPersistence.Resource; public static parseFrom(param0: native.Array<number>, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firebase.remoteconfig.proto.ConfigPersistence.PersistedConfig; public static parseFrom(param0: com.google.protobuf.CodedInputStream): com.google.firebase.remoteconfig.proto.ConfigPersistence.PersistedConfig; public static getDefaultInstance(): com.google.firebase.remoteconfig.proto.ConfigPersistence.PersistedConfig; public getAppliedResourceList(): java.util.List<com.google.firebase.remoteconfig.proto.ConfigPersistence.Resource>; public static parseFrom(param0: com.google.protobuf.ByteString, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firebase.remoteconfig.proto.ConfigPersistence.PersistedConfig; public hasMetadata(): boolean; } export module PersistedConfig { export class Builder extends com.google.protobuf.GeneratedMessageLite.Builder<com.google.firebase.remoteconfig.proto.ConfigPersistence.PersistedConfig,com.google.firebase.remoteconfig.proto.ConfigPersistence.PersistedConfig.Builder> implements com.google.firebase.remoteconfig.proto.ConfigPersistence.PersistedConfigOrBuilder { public static class: java.lang.Class<com.google.firebase.remoteconfig.proto.ConfigPersistence.PersistedConfig.Builder>; public getAppliedResource(param0: number): com.google.firebase.remoteconfig.proto.ConfigPersistence.Resource; public addAllAppliedResource(param0: java.lang.Iterable<any>): com.google.firebase.remoteconfig.proto.ConfigPersistence.PersistedConfig.Builder; public getActiveConfigHolder(): com.google.firebase.remoteconfig.proto.ConfigPersistence.ConfigHolder; public getAppliedResourceList(): java.util.List<com.google.firebase.remoteconfig.proto.ConfigPersistence.Resource>; public setActiveConfigHolder(param0: com.google.firebase.remoteconfig.proto.ConfigPersistence.ConfigHolder): com.google.firebase.remoteconfig.proto.ConfigPersistence.PersistedConfig.Builder; public mergeMetadata(param0: com.google.firebase.remoteconfig.proto.ConfigPersistence.Metadata): com.google.firebase.remoteconfig.proto.ConfigPersistence.PersistedConfig.Builder; public getFetchedConfigHolder(): com.google.firebase.remoteconfig.proto.ConfigPersistence.ConfigHolder; public clearFetchedConfigHolder(): com.google.firebase.remoteconfig.proto.ConfigPersistence.PersistedConfig.Builder; public addAppliedResource(param0: number, param1: com.google.firebase.remoteconfig.proto.ConfigPersistence.Resource): com.google.firebase.remoteconfig.proto.ConfigPersistence.PersistedConfig.Builder; public setDefaultsConfigHolder(param0: com.google.firebase.remoteconfig.proto.ConfigPersistence.ConfigHolder.Builder): com.google.firebase.remoteconfig.proto.ConfigPersistence.PersistedConfig.Builder; public getMetadata(): com.google.firebase.remoteconfig.proto.ConfigPersistence.Metadata; public setMetadata(param0: com.google.firebase.remoteconfig.proto.ConfigPersistence.Metadata): com.google.firebase.remoteconfig.proto.ConfigPersistence.PersistedConfig.Builder; public getDefaultsConfigHolder(): com.google.firebase.remoteconfig.proto.ConfigPersistence.ConfigHolder; public setAppliedResource(param0: number, param1: com.google.firebase.remoteconfig.proto.ConfigPersistence.Resource.Builder): com.google.firebase.remoteconfig.proto.ConfigPersistence.PersistedConfig.Builder; public clearActiveConfigHolder(): com.google.firebase.remoteconfig.proto.ConfigPersistence.PersistedConfig.Builder; public hasFetchedConfigHolder(): boolean; public addAppliedResource(param0: number, param1: com.google.firebase.remoteconfig.proto.ConfigPersistence.Resource.Builder): com.google.firebase.remoteconfig.proto.ConfigPersistence.PersistedConfig.Builder; public setFetchedConfigHolder(param0: com.google.firebase.remoteconfig.proto.ConfigPersistence.ConfigHolder): com.google.firebase.remoteconfig.proto.ConfigPersistence.PersistedConfig.Builder; public setActiveConfigHolder(param0: com.google.firebase.remoteconfig.proto.ConfigPersistence.ConfigHolder.Builder): com.google.firebase.remoteconfig.proto.ConfigPersistence.PersistedConfig.Builder; public mergeActiveConfigHolder(param0: com.google.firebase.remoteconfig.proto.ConfigPersistence.ConfigHolder): com.google.firebase.remoteconfig.proto.ConfigPersistence.PersistedConfig.Builder; public setDefaultsConfigHolder(param0: com.google.firebase.remoteconfig.proto.ConfigPersistence.ConfigHolder): com.google.firebase.remoteconfig.proto.ConfigPersistence.PersistedConfig.Builder; public setFetchedConfigHolder(param0: com.google.firebase.remoteconfig.proto.ConfigPersistence.ConfigHolder.Builder): com.google.firebase.remoteconfig.proto.ConfigPersistence.PersistedConfig.Builder; public hasActiveConfigHolder(): boolean; public setMetadata(param0: com.google.firebase.remoteconfig.proto.ConfigPersistence.Metadata.Builder): com.google.firebase.remoteconfig.proto.ConfigPersistence.PersistedConfig.Builder; public getAppliedResourceCount(): number; public addAppliedResource(param0: com.google.firebase.remoteconfig.proto.ConfigPersistence.Resource.Builder): com.google.firebase.remoteconfig.proto.ConfigPersistence.PersistedConfig.Builder; public clearMetadata(): com.google.firebase.remoteconfig.proto.ConfigPersistence.PersistedConfig.Builder; public removeAppliedResource(param0: number): com.google.firebase.remoteconfig.proto.ConfigPersistence.PersistedConfig.Builder; public hasDefaultsConfigHolder(): boolean; public mergeFetchedConfigHolder(param0: com.google.firebase.remoteconfig.proto.ConfigPersistence.ConfigHolder): com.google.firebase.remoteconfig.proto.ConfigPersistence.PersistedConfig.Builder; public mergeDefaultsConfigHolder(param0: com.google.firebase.remoteconfig.proto.ConfigPersistence.ConfigHolder): com.google.firebase.remoteconfig.proto.ConfigPersistence.PersistedConfig.Builder; public clearDefaultsConfigHolder(): com.google.firebase.remoteconfig.proto.ConfigPersistence.PersistedConfig.Builder; public addAppliedResource(param0: com.google.firebase.remoteconfig.proto.ConfigPersistence.Resource): com.google.firebase.remoteconfig.proto.ConfigPersistence.PersistedConfig.Builder; public clearAppliedResource(): com.google.firebase.remoteconfig.proto.ConfigPersistence.PersistedConfig.Builder; public setAppliedResource(param0: number, param1: com.google.firebase.remoteconfig.proto.ConfigPersistence.Resource): com.google.firebase.remoteconfig.proto.ConfigPersistence.PersistedConfig.Builder; public hasMetadata(): boolean; } } export class PersistedConfigOrBuilder { public static class: java.lang.Class<com.google.firebase.remoteconfig.proto.ConfigPersistence.PersistedConfigOrBuilder>; /** * Constructs a new instance of the com.google.firebase.remoteconfig.proto.ConfigPersistence$PersistedConfigOrBuilder interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { hasFetchedConfigHolder(): boolean; getFetchedConfigHolder(): com.google.firebase.remoteconfig.proto.ConfigPersistence.ConfigHolder; hasActiveConfigHolder(): boolean; getActiveConfigHolder(): com.google.firebase.remoteconfig.proto.ConfigPersistence.ConfigHolder; hasDefaultsConfigHolder(): boolean; getDefaultsConfigHolder(): com.google.firebase.remoteconfig.proto.ConfigPersistence.ConfigHolder; hasMetadata(): boolean; getMetadata(): com.google.firebase.remoteconfig.proto.ConfigPersistence.Metadata; getAppliedResourceList(): java.util.List<com.google.firebase.remoteconfig.proto.ConfigPersistence.Resource>; getAppliedResource(param0: number): com.google.firebase.remoteconfig.proto.ConfigPersistence.Resource; getAppliedResourceCount(): number; }); public constructor(); public hasFetchedConfigHolder(): boolean; public getFetchedConfigHolder(): com.google.firebase.remoteconfig.proto.ConfigPersistence.ConfigHolder; public hasActiveConfigHolder(): boolean; public hasDefaultsConfigHolder(): boolean; public getActiveConfigHolder(): com.google.firebase.remoteconfig.proto.ConfigPersistence.ConfigHolder; public getAppliedResource(param0: number): com.google.firebase.remoteconfig.proto.ConfigPersistence.Resource; public getDefaultsConfigHolder(): com.google.firebase.remoteconfig.proto.ConfigPersistence.ConfigHolder; public getAppliedResourceList(): java.util.List<com.google.firebase.remoteconfig.proto.ConfigPersistence.Resource>; public getMetadata(): com.google.firebase.remoteconfig.proto.ConfigPersistence.Metadata; public hasMetadata(): boolean; public getAppliedResourceCount(): number; } export class Resource extends com.google.protobuf.GeneratedMessageLite<com.google.firebase.remoteconfig.proto.ConfigPersistence.Resource,com.google.firebase.remoteconfig.proto.ConfigPersistence.Resource.Builder> implements com.google.firebase.remoteconfig.proto.ConfigPersistence.ResourceOrBuilder { public static class: java.lang.Class<com.google.firebase.remoteconfig.proto.ConfigPersistence.Resource>; public static RESOURCE_ID_FIELD_NUMBER: number; public static APP_UPDATE_TIME_FIELD_NUMBER: number; public static NAMESPACE_FIELD_NUMBER: number; public hasResourceId(): boolean; public static parseFrom(param0: java.io.InputStream): com.google.firebase.remoteconfig.proto.ConfigPersistence.Resource; public hasNamespace(): boolean; public static parseFrom(param0: com.google.protobuf.ByteString, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firebase.remoteconfig.proto.ConfigPersistence.Resource; public static parseDelimitedFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firebase.remoteconfig.proto.ConfigPersistence.Resource; public static parseFrom(param0: com.google.protobuf.CodedInputStream): com.google.firebase.remoteconfig.proto.ConfigPersistence.Resource; public static getDefaultInstance(): com.google.firebase.remoteconfig.proto.ConfigPersistence.Resource; public static parseFrom(param0: native.Array<number>): com.google.firebase.remoteconfig.proto.ConfigPersistence.Resource; public static parseFrom(param0: native.Array<number>, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firebase.remoteconfig.proto.ConfigPersistence.Resource; public static parseFrom(param0: java.io.InputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firebase.remoteconfig.proto.ConfigPersistence.Resource; public getResourceId(): number; public static newBuilder(): com.google.firebase.remoteconfig.proto.ConfigPersistence.Resource.Builder; public dynamicMethod(param0: com.google.protobuf.GeneratedMessageLite.MethodToInvoke, param1: any, param2: any): any; public getNamespaceBytes(): com.google.protobuf.ByteString; public hasAppUpdateTime(): boolean; public static parseFrom(param0: com.google.protobuf.CodedInputStream, param1: com.google.protobuf.ExtensionRegistryLite): com.google.firebase.remoteconfig.proto.ConfigPersistence.Resource; public writeTo(param0: com.google.protobuf.CodedOutputStream): void; public getAppUpdateTime(): number; public static newBuilder(param0: com.google.firebase.remoteconfig.proto.ConfigPersistence.Resource): com.google.firebase.remoteconfig.proto.ConfigPersistence.Resource.Builder; public getSerializedSize(): number; public static parseFrom(param0: com.google.protobuf.ByteString): com.google.firebase.remoteconfig.proto.ConfigPersistence.Resource; public static parser(): com.google.protobuf.Parser<com.google.firebase.remoteconfig.proto.ConfigPersistence.Resource>; public getNamespace(): string; public static parseDelimitedFrom(param0: java.io.InputStream): com.google.firebase.remoteconfig.proto.ConfigPersistence.Resource; } export module Resource { export class Builder extends com.google.protobuf.GeneratedMessageLite.Builder<com.google.firebase.remoteconfig.proto.ConfigPersistence.Resource,com.google.firebase.remoteconfig.proto.ConfigPersistence.Resource.Builder> implements com.google.firebase.remoteconfig.proto.ConfigPersistence.ResourceOrBuilder { public static class: java.lang.Class<com.google.firebase.remoteconfig.proto.ConfigPersistence.Resource.Builder>; public setAppUpdateTime(param0: number): com.google.firebase.remoteconfig.proto.ConfigPersistence.Resource.Builder; public getNamespaceBytes(): com.google.protobuf.ByteString; public hasNamespace(): boolean; public setNamespace(param0: string): com.google.firebase.remoteconfig.proto.ConfigPersistence.Resource.Builder; public getAppUpdateTime(): number; public hasAppUpdateTime(): boolean; public clearResourceId(): com.google.firebase.remoteconfig.proto.ConfigPersistence.Resource.Builder; public getNamespace(): string; public clearNamespace(): com.google.firebase.remoteconfig.proto.ConfigPersistence.Resource.Builder; public clearAppUpdateTime(): com.google.firebase.remoteconfig.proto.ConfigPersistence.Resource.Builder; public getResourceId(): number; public hasResourceId(): boolean; public setResourceId(param0: number): com.google.firebase.remoteconfig.proto.ConfigPersistence.Resource.Builder; public setNamespaceBytes(param0: com.google.protobuf.ByteString): com.google.firebase.remoteconfig.proto.ConfigPersistence.Resource.Builder; } } export class ResourceOrBuilder { public static class: java.lang.Class<com.google.firebase.remoteconfig.proto.ConfigPersistence.ResourceOrBuilder>; /** * Constructs a new instance of the com.google.firebase.remoteconfig.proto.ConfigPersistence$ResourceOrBuilder interface with the provided implementation. An empty constructor exists calling super() when extending the interface class. */ public constructor(implementation: { hasResourceId(): boolean; getResourceId(): number; hasAppUpdateTime(): boolean; getAppUpdateTime(): number; hasNamespace(): boolean; getNamespace(): string; getNamespaceBytes(): com.google.protobuf.ByteString; }); public constructor(); public hasAppUpdateTime(): boolean; public hasResourceId(): boolean; public hasNamespace(): boolean; public getAppUpdateTime(): number; public getResourceId(): number; public getNamespaceBytes(): com.google.protobuf.ByteString; public getNamespace(): string; } } } } } } } //Generics information: //com.google.firebase.remoteconfig.internal.ConfigCacheClient.AwaitListener:1
the_stack
import { basicLanguages, createEditor, selectedEditor } from './editor'; import { languages, getLanguageEditorId, getLanguageCompiler, languageIsEnabled, pluginSpecs, PluginName, processorIsEnabled, getLanguageByAlias, mapLanguage, createLanguageMenus, } from './languages'; import { createStorage, Item, SavedProject } from './storage'; import { Cache, CodeEditor, CssPresetId, EditorId, EditorLanguages, EditorOptions, Editors, GithubScope, Language, Config, Screen, ShareData, Template, User, ContentConfig, Theme, UserConfig, Await, Code, } from './models'; import { getFormatter } from './formatter'; import { createNotifications } from './notifications'; import { createModal } from './modal'; import { settingsMenuHTML, resultTemplate, customSettingsScreen, resourcesScreen, savePromptScreen, openScreen, restorePromptScreen, } from './html'; import { downloadFile, exportConfig } from './export'; import { createEventsManager } from './events'; import { getStarterTemplates, getTemplate } from './templates'; import { buildConfig, defaultConfig, getConfig, getContentConfig, getParams, getUserConfig, setConfig, upgradeAndValidate, } from './config'; import { importCode, isGithub } from './import'; import { compress, copyToClipboard, debounce, fetchWithHandler, getDate, loadStylesheet, stringify, stringToValidJson, } from './utils'; import { getCompiler, getAllCompilers } from './compiler'; import { createTypeLoader } from './types'; import { createResultPage } from './result'; import * as UI from './UI'; import { createAuthService, sandboxService, shareService } from './services'; import { deploy, deployedConfirmation, getUserPublicRepos } from './deploy'; import { cacheIsValid, getCache, getCachedCode, setCache, updateCache } from './cache'; import { autoCompleteUrl, hintCssUrl, lunaConsoleStylesUrl, lunaObjViewerStylesUrl, snackbarUrl, } from './vendors'; import { configureEmbed } from './embeds'; import { createToolsPane } from './toolspane'; const eventsManager = createEventsManager(); const projectStorage = createStorage(); const templateStorage = createStorage('__livecodes_templates__'); const userConfigStorage = createStorage('__livecodes_user_config__'); const restoreStorage = createStorage('__livecodes_project_restore__'); const typeLoader = createTypeLoader(); const notifications = createNotifications(); const modal = createModal(); const split = UI.createSplitPanes(); const screens: Screen[] = []; let baseUrl: string; let isEmbed: boolean; let compiler: Await<ReturnType<typeof getCompiler>>; let formatter: ReturnType<typeof getFormatter>; let editors: Editors; let toolsPane: any; let authService: ReturnType<typeof createAuthService> | undefined; let editorLanguages: EditorLanguages | undefined; let resultLanguages: Language[] = []; let projectId: string; let isSaved = true; let changingContent = false; let consoleInputCodeCompletion: any; let starterTemplates: Template[]; let editorBuild: EditorOptions['editorBuild'] = 'basic'; const getEditorLanguage = (editorId: EditorId = 'markup') => editorLanguages?.[editorId]; const getEditorLanguages = () => Object.values(editorLanguages || {}); const getActiveEditor = () => editors[getConfig().activeEditor || 'markup']; const setActiveEditor = async (config: Config) => showEditor(config.activeEditor); const isBasicLanguage = (lang: Language) => basicLanguages.includes(lang); const loadStyles = () => Promise.all( [snackbarUrl, hintCssUrl, lunaObjViewerStylesUrl, lunaConsoleStylesUrl].map((url) => loadStylesheet(url, undefined, '#app-styles'), ), ); const createIframe = (container: HTMLElement, result?: string, service = sandboxService) => new Promise((resolve, reject) => { if (!container) { reject('Result container not found'); return; } let iframe: HTMLIFrameElement; const scriptLang = getEditorLanguage('script') || 'javascript'; const compilers = getAllCompilers(languages, getConfig(), baseUrl); const editorsText = `${getConfig().markup.content} ${getConfig().style.content} ${getConfig().script.content} `; const liveReload = compilers[scriptLang]?.liveReload && resultLanguages.includes(scriptLang) && !editorsText.includes('__livecodes_reload__'); if (result && getCache().styleOnlyUpdate) { // load the updated styles only iframe = document.querySelector('iframe#result-frame') as HTMLIFrameElement; const domParser = new DOMParser(); const dom = domParser.parseFromString(result, 'text/html'); const stylesElement = dom.querySelector('#__livecodes_styles__'); if (stylesElement) { const styles = stylesElement.innerHTML; iframe.contentWindow?.postMessage({ styles }, service.getOrigin()); } else { iframe.contentWindow?.postMessage({ result }, service.getOrigin()); } resolve('loaded'); } else if (liveReload) { // allows only sending the updated code to the iframe without full page reload iframe = document.querySelector('iframe#result-frame') as HTMLIFrameElement; iframe.contentWindow?.postMessage({ result }, service.getOrigin()); resolve('loaded'); } else { // full page reload iframe = document.createElement('iframe'); iframe.name = 'result'; iframe.id = 'result-frame'; iframe.setAttribute('allow', 'camera; geolocation; microphone'); iframe.setAttribute('allowfullscreen', 'true'); iframe.setAttribute('allowtransparency', 'true'); iframe.setAttribute( 'sandbox', 'allow-same-origin allow-downloads allow-forms allow-modals allow-orientation-lock allow-pointer-lock allow-popups allow-presentation allow-scripts', ); const { mode } = getConfig(); if (mode !== 'codeblock' && mode !== 'editor') { iframe.src = service.getResultUrl(); } container.innerHTML = ''; container.appendChild(iframe); let loaded = false; eventsManager.addEventListener(iframe, 'load', () => { if (!result || loaded) { resolve('loaded'); return; // prevent infinite loop } iframe.contentWindow?.postMessage({ result }, service.getOrigin()); loaded = true; resolve('loaded'); }); } resultLanguages = getEditorLanguages(); }); const loadModuleTypes = async (editors: Editors, config: Config) => { const scriptLanguage = config.script.language; if ( editors.script && ['typescript', 'javascript'].includes(mapLanguage(scriptLanguage)) && typeof editors.script.addTypes === 'function' ) { const configTypes = { ...getLanguageCompiler(scriptLanguage)?.types, ...config.types, }; const libs = await typeLoader.load(getConfig().script.content || '', configTypes); libs.forEach((lib) => editors.script.addTypes?.(lib)); } }; const setEditorTitle = (editorId: EditorId, title: string) => { const editorTitle = document.querySelector(`#${editorId}-selector span`); if (!editorTitle) return; editorTitle.innerHTML = languages.find((language) => language.name === getLanguageByAlias(title))?.title || ''; }; const createCopyButtons = () => { const editorIds: EditorId[] = ['markup', 'style', 'script']; editorIds.forEach((editorId) => { const copyButton = document.createElement('button'); copyButton.innerHTML = 'copy'; copyButton.classList.add('copy-button'); document.getElementById(editorId)?.appendChild(copyButton); eventsManager.addEventListener(copyButton, 'click', () => { if (copyToClipboard(editors?.[editorId]?.getValue())) { copyButton.innerHTML = 'copied'; setTimeout(() => { copyButton.innerHTML = 'copy'; }, 2000); } }); }); }; const shouldUpdateEditorBuild = (langs?: Language[]) => { const editor = selectedEditor(getConfig()); if (editor === 'monaco') return false; if (editorBuild === 'full') return false; if ( langs?.some((lang) => !isBasicLanguage(lang)) || (editor === 'codemirror' && getConfig().emmet) ) { editorBuild = 'full'; return true; } return false; }; const createEditors = async (config: Config) => { if (editors) { Object.values(editors).forEach((editor: CodeEditor) => editor.destroy()); } const baseOptions = { baseUrl, mode: config.mode, readonly: config.readonly, editor: config.editor, editorType: 'code' as EditorOptions['editorType'], theme: config.theme, }; const markupOptions: EditorOptions = { ...baseOptions, container: UI.getMarkupElement(), language: languageIsEnabled(config.markup.language, config) ? config.markup.language : config.languages?.find((lang) => getLanguageEditorId(lang) === 'markup') || 'html', value: languageIsEnabled(config.markup.language, config) ? config.markup.content || '' : '', }; const styleOptions: EditorOptions = { ...baseOptions, container: UI.getStyleElement(), language: languageIsEnabled(config.style.language, config) ? config.style.language : config.languages?.find((lang) => getLanguageEditorId(lang) === 'style') || 'css', value: languageIsEnabled(config.style.language, config) ? config.style.content || '' : '', }; const scriptOptions: EditorOptions = { ...baseOptions, container: UI.getScriptElement(), language: languageIsEnabled(config.script.language, config) ? config.script.language : config.languages?.find((lang) => getLanguageEditorId(lang) === 'script') || 'javascript', value: languageIsEnabled(config.script.language, config) ? config.script.content || '' : '', }; shouldUpdateEditorBuild([markupOptions.language, styleOptions.language, scriptOptions.language]); const markupEditor = await createEditor({ ...markupOptions, editorBuild }); const styleEditor = await createEditor({ ...styleOptions, editorBuild }); const scriptEditor = await createEditor({ ...scriptOptions, editorBuild }); setEditorTitle('markup', markupOptions.language); setEditorTitle('style', styleOptions.language); setEditorTitle('script', scriptOptions.language); editorLanguages = { markup: markupOptions.language, style: styleOptions.language, script: scriptOptions.language, }; editors = { markup: markupEditor, style: styleEditor, script: scriptEditor, }; (Object.keys(editors) as EditorId[]).forEach(async (editorId) => { const language = editorLanguages?.[editorId] || 'html'; applyLanguageConfigs(language); editors[editorId].registerFormatter(await formatter.getFormatFn(language)); registerRun(editorId, editors); }); if (config.mode === 'codeblock') { createCopyButtons(); } }; const reloadEditors = async (config: Config) => { await createEditors(config); await toolsPane?.compiled.reloadEditor(); updateCompiledCode(); handleChangeContent(); }; const updateEditors = async (editors: Editors, config: Config) => { const editorIds = Object.keys(editors) as Array<keyof Editors>; for (const editorId of editorIds) { const language = getLanguageByAlias(config[editorId].language); if (language) { await changeLanguage(language, config[editorId].content, true); } } }; const showMode = (config: Config) => { const modes = { full: '111', editor: '110', codeblock: '010', result: '001', }; const modeConfig = modes[config.mode] || '111'; const toolbarElement = UI.getToolbarElement(); const editorContainerElement = UI.getEditorContainerElement(); const editorsElement = UI.getEditorsElement(); const outputElement = UI.getOutputElement(); const resultElement = UI.getResultElement(); const gutterElement = UI.getGutterElement(); const runButton = UI.getRunButton(); const codeRunButton = UI.getCodeRunButton(); const showToolbar = modeConfig[0] === '1'; const showEditor = modeConfig[1] === '1'; const showResult = modeConfig[2] === '1'; toolbarElement.style.display = 'flex'; editorsElement.style.display = 'flex'; resultElement.style.display = 'flex'; outputElement.style.display = 'block'; gutterElement.style.display = 'block'; gutterElement.style.display = 'block'; runButton.style.visibility = 'visible'; codeRunButton.style.visibility = 'visible'; if (!showToolbar) { toolbarElement.style.display = 'none'; editorContainerElement.style.height = '100%'; } if (!showEditor) { outputElement.style.flexBasis = '100%'; editorsElement.style.display = 'none'; split.destroy(true); } if (!showResult) { editorsElement.style.flexBasis = '100%'; outputElement.style.display = 'none'; resultElement.style.display = 'none'; codeRunButton.style.display = 'none'; split.destroy(true); } if (config.mode === 'editor' || config.mode === 'codeblock') { runButton.style.visibility = 'hidden'; codeRunButton.style.visibility = 'hidden'; } window.dispatchEvent(new Event('editor-resize')); }; const showEditor = (editorId: EditorId = 'markup', isUpdate = false) => { const titles = UI.getEditorTitles(); const editorIsVisible = () => Array.from(titles) .map((title) => title.dataset.editor) .includes(editorId); if (!editorIsVisible()) { // select first visible editor instead editorId = (titles[0].dataset.editor as EditorId) || 'markup'; } titles.forEach((selector) => selector.classList.remove('active')); const activeTitle = document.getElementById(editorId + '-selector'); activeTitle?.classList.add('active'); const editorDivs = UI.getEditorDivs(); editorDivs.forEach((editor) => (editor.style.display = 'none')); const activeEditor = document.getElementById(editorId) as HTMLElement; activeEditor.style.display = 'block'; editors[editorId].focus(); if (!isUpdate) { setConfig({ ...getConfig(), activeEditor: editorId, }); } updateCompiledCode(); split.show('code'); }; const addConsoleInputCodeCompletion = () => { if (consoleInputCodeCompletion) { consoleInputCodeCompletion.dispose(); } if ( editorLanguages?.script && ['javascript', 'typescript'].includes(mapLanguage(editorLanguages.script)) ) { if (editors.script && typeof editors.script.addTypes === 'function') { consoleInputCodeCompletion = editors.script.addTypes({ content: getConfig().script.content + '\n{}', filename: 'script.js', }); } } }; const phpHelper = ({ editor, code }: { editor?: CodeEditor; code?: string }) => { const addToken = (code: string) => (code.trim().startsWith('<?php') ? code : '<?php\n' + code); if (code) { return addToken(code); } if (editor?.getLanguage() === 'php') { editor.setValue(addToken(editor.getValue())); } return; }; const applyLanguageConfigs = (language: Language) => { const editorId = getLanguageEditorId(language); if (!editorId || !language || !languageIsEnabled(language, getConfig())) return; // apply config }; const changeLanguage = async (language: Language, value?: string, isUpdate = false) => { const editorId = getLanguageEditorId(language); if (!editorId || !language || !languageIsEnabled(language, getConfig())) return; if (shouldUpdateEditorBuild([language])) { await reloadEditors(getConfig()); } const editor = editors[editorId]; editor.setLanguage(language, value ?? (getConfig()[editorId].content || '')); if (editorLanguages) { editorLanguages[editorId] = language; } setEditorTitle(editorId, language); showEditor(editorId, isUpdate); phpHelper({ editor: editors.script }); setTimeout(() => editor.focus()); await compiler.load([language], getConfig()); editor.registerFormatter(await formatter.getFormatFn(language)); if (!isUpdate) { setConfig({ ...getConfig(), activeEditor: editorId, }); await run(); } setSavedStatus(); addConsoleInputCodeCompletion(); loadModuleTypes(editors, getConfig()); applyLanguageConfigs(language); }; // Ctrl/Cmd + Enter triggers run const registerRun = (editorId: EditorId, editors: Editors) => { const editor = editors[editorId]; editor.addKeyBinding('run', editor.keyCodes.CtrlEnter, async () => { await run(); }); }; const updateCompiledCode = () => { const getCompiledLanguage = (editorId: EditorId) => { const defaultLang: { [key in EditorId]: Language } = { markup: 'html', style: 'css', script: 'javascript', }; const lang = getLanguageCompiler(getConfig()[editorId].language)?.compiledCodeLanguage; return { language: lang || defaultLang[editorId], label: lang === 'json' ? 'JSON' : getLanguageByAlias(lang) || lang || defaultLang[editorId], }; }; const compiledLanguages: { [key in EditorId]: { language: Language; label: string } } = { markup: getCompiledLanguage('markup'), style: getCompiledLanguage('style'), script: getCompiledLanguage('script'), }; if (toolsPane && toolsPane.compiled) { const cache = getCache(); Object.keys(cache).forEach((editorId) => { if (editorId !== getConfig().activeEditor) return; let compiledCode = cache[editorId].modified || cache[editorId].compiled || ''; if (editorId === 'script' && getConfig().script.language === 'php') { compiledCode = phpHelper({ code: compiledCode }) || '<?php\n'; } toolsPane.compiled.update( compiledLanguages[editorId].language, compiledCode, compiledLanguages[editorId].label, ); }); } }; const getResultPage = async ({ sourceEditor = undefined as EditorId | undefined, forExport = false, template = resultTemplate, singleFile = true, }) => { updateConfig(); const config = getConfig(); const contentConfig = getContentConfig(config); const markupContent = config.markup.content || ''; const styleContent = config.style.content || ''; const scriptContent = config.script.content || ''; const markupLanguage = config.markup.language; const styleLanguage = config.style.language; const scriptLanguage = config.script.language; const compiledMarkup = await compiler.compile(markupContent, markupLanguage, config); const [compiledStyle, compiledScript] = await Promise.all([ compiler.compile(styleContent, styleLanguage, config, { html: compiledMarkup }), compiler.compile(scriptContent, scriptLanguage, config), ]); const compiledCode: Cache = { ...contentConfig, markup: { ...contentConfig.markup, compiled: compiledMarkup, }, style: { ...contentConfig.style, compiled: compiledStyle, }, script: { ...contentConfig.script, compiled: compiledScript, }, }; const result = createResultPage(compiledCode, config, forExport, template, baseUrl, singleFile); const styleOnlyUpdate = sourceEditor === 'style'; setCache({ ...compiledCode, result, styleOnlyUpdate, }); return result; }; const setLoading = (status: boolean) => { const loading = UI.getToolspaneLoader(); if (!loading) return; if (status === true) { loading.style.display = 'unset'; } else { loading.style.display = 'none'; } }; const setProjectTitle = (setDefault = false) => { const projectTitle = UI.getProjectTitleElement(); if (!projectTitle) return; const defaultTitle = defaultConfig.title; if (setDefault && projectTitle.textContent?.trim() === '') { projectTitle.textContent = defaultTitle; } const title = projectTitle.textContent || defaultTitle; setConfig({ ...getConfig(), title }); setSavedStatus(); if (getConfig().autosave) { save(!projectId, false); } setWindowTitle(); }; const setWindowTitle = () => { const title = getConfig().title; parent.document.title = (title && title !== 'Untitled Project' ? title + ' - ' : '') + 'LiveCodes'; }; const run = async (editorId?: EditorId) => { setLoading(true); const result = await getResultPage({ sourceEditor: editorId }); await createIframe(UI.getResultElement(), result); updateCompiledCode(); }; const updateUrl = (url: string, push = false) => { if (push) { parent.history.pushState(null, '', url); } else { parent.history.replaceState(null, '', url); } }; const format = async () => { await Promise.all([editors.markup.format(), editors.style.format(), editors.script.format()]); updateConfig(); }; const save = async (notify = false, setTitle = true) => { if (setTitle) { setProjectTitle(true); } if (editors && getConfig().formatOnsave) { await format(); } if (!projectId) { projectId = projectStorage.addItem(getConfig()); } else { projectStorage.updateItem(projectId, getConfig()); } setSavedStatus(); if (notify) { notifications.success('Project locally saved to device!'); } await share(); }; const fork = async () => { projectId = ''; loadConfig({ ...getConfig(), title: getConfig().title + ' (fork)' }); await save(); notifications.success('Forked as a new project'); }; const share = async (shortUrl = false, contentOnly = true): Promise<ShareData> => { const content = contentOnly ? getContentConfig(getConfig()) : getConfig(); const contentHash = shortUrl ? '#id/' + (await shareService.shareProject(content)) : '#code/' + compress(JSON.stringify(content)); const url = (location.origin + location.pathname).split('/').slice(0, -1).join('/') + '/'; const shareURL = url + contentHash; updateUrl(shareURL, true); const projectTitle = content.title !== defaultConfig.title ? content.title + ' - ' : ''; return { title: projectTitle + 'LiveCodes', url: shareURL, }; }; const updateConfig = () => { const editorIds: EditorId[] = ['markup', 'style', 'script']; editorIds.forEach((editorId) => { setConfig({ ...getConfig(), [editorId]: { ...getConfig()[editorId], language: getEditorLanguage(editorId), content: editors[editorId].getValue(), }, }); }); }; const loadConfig = async (newConfig: Config | ContentConfig, url?: string) => { changingContent = true; const content = getContentConfig({ ...defaultConfig, ...upgradeAndValidate(newConfig), }); setConfig({ ...getConfig(), ...content, }); setProjectRestore(); // load title const projectTitle = UI.getProjectTitleElement(); projectTitle.textContent = getConfig().title; setWindowTitle(); // reset url params updateUrl(url || location.origin + location.pathname, true); // load config await bootstrap(true); changingContent = false; }; const setUserConfig = (newConfig: Partial<UserConfig> | null) => { const userConfig = getUserConfig({ ...getConfig(), ...(newConfig == null ? getUserConfig(defaultConfig) : newConfig), }); setConfig({ ...getConfig(), ...userConfig, }); userConfigStorage.clear(); userConfigStorage.addItem(userConfig as Config); }; const loadUserConfig = () => { const userConfig = userConfigStorage.getAllData()?.pop()?.pen; if (!userConfig) { setUserConfig(getUserConfig(getConfig())); return; } setConfig({ ...getConfig(), ...userConfig, }); }; const setSavedStatus = () => { updateConfig(); const savedConfig = projectStorage.getItem(projectId)?.pen; isSaved = changingContent || !!( savedConfig && JSON.stringify(getContentConfig(savedConfig)) === JSON.stringify(getContentConfig(getConfig())) ); const projectTitle = UI.getProjectTitleElement(); if (!isSaved) { projectTitle.classList.add('unsaved'); setProjectRestore(); } else { projectTitle.classList.remove('unsaved'); setProjectRestore(true); } }; const checkSavedStatus = (doNotCloseModal = false) => { if (isSaved) { return Promise.resolve('is saved'); } return new Promise((resolve) => { const div = document.createElement('div'); div.innerHTML = savePromptScreen; modal.show(div.firstChild as HTMLElement, { size: 'small' }); eventsManager.addEventListener(UI.getModalSaveButton(), 'click', async () => { await save(true); if (!doNotCloseModal) { modal.close(); } resolve('save'); }); eventsManager.addEventListener(UI.getModalDoNotSaveButton(), 'click', () => { if (!doNotCloseModal) { modal.close(); } resolve('do not save'); }); eventsManager.addEventListener(UI.getModalCancelButton(), 'click', () => { modal.close(); resolve('cancel'); }); }); }; const checkSavedAndExecute = (fn: () => void) => async () => { checkSavedStatus(true).then(() => setTimeout(fn)); }; const setProjectRestore = (reset = false) => { if (isEmbed) return; restoreStorage.clear(); if (reset || !getConfig().enableRestore) return; restoreStorage.addItem(getContentConfig(getConfig())); }; const checkRestoreStatus = () => { if (!getConfig().enableRestore || isEmbed) { return Promise.resolve('restore disabled'); } const unsavedItem = restoreStorage.getAllData().pop(); const unsavedProject = unsavedItem?.pen; if (!unsavedItem || !unsavedProject) { return Promise.resolve('no unsaved project'); } const projectName = unsavedProject.title; return new Promise((resolve) => { const div = document.createElement('div'); div.innerHTML = restorePromptScreen; modal.show(div.firstChild as HTMLElement, { size: 'small', isAsync: true }); UI.getModalUnsavedName().innerHTML = projectName; UI.getModalUnsavedLastModified().innerHTML = new Date( unsavedItem.lastModified, ).toLocaleString(); const disableRestoreCheckbox = UI.getModalDisableRestoreCheckbox(); const setRestoreConfig = (enableRestore: boolean) => { setUserConfig({ enableRestore }); loadSettings(getConfig()); }; eventsManager.addEventListener(UI.getModalRestoreButton(), 'click', async () => { await loadConfig(unsavedProject); setSavedStatus(); setRestoreConfig(!disableRestoreCheckbox.checked); modal.close(); resolve('restore'); }); eventsManager.addEventListener(UI.getModalSavePreviousButton(), 'click', () => { projectStorage.addItem(unsavedProject); notifications.success(`Project "${projectName}" saved to device.`); setRestoreConfig(!disableRestoreCheckbox.checked); modal.close(); setProjectRestore(true); resolve('save and continue'); }); eventsManager.addEventListener(UI.getModalCancelRestoreButton(), 'click', () => { setRestoreConfig(!disableRestoreCheckbox.checked); modal.close(); setProjectRestore(true); resolve('cancel restore'); }); }); }; const configureEmmet = async (config: Config) => { if (shouldUpdateEditorBuild()) { await reloadEditors(getConfig()); } [editors.markup, editors.style].forEach((editor, editorIndex) => { if (editor.monaco && editorIndex > 0) return; // emmet configuration for monaco is global editor.configureEmmet?.(config.emmet); }); }; const getTemplates = async (): Promise<Template[]> => { if (starterTemplates) { return starterTemplates; } starterTemplates = await getStarterTemplates(getConfig(), baseUrl); return starterTemplates; }; const initializeAuth = async () => { /** Lazy load authentication */ if (authService) return; authService = createAuthService(); const user = await authService.getUser(); if (user) { UI.displayLoggedIn(user); } }; const login = async () => new Promise<User | void>((resolve, reject) => { const loginHandler = (scopes: GithubScope[]) => { if (!authService) { reject('Login error!'); } else { authService .signIn(scopes) .then((user) => { if (!user) { reject('Login error!'); } else { const displayName = user.displayName || user.username; const loginSuccessMessage = displayName ? 'Logged in as: ' + displayName : 'Logged in successfully'; notifications.success(loginSuccessMessage); UI.displayLoggedIn(user); resolve(user); } }) .catch(() => { notifications.error('Login error!'); }); } modal.close(); }; const loginContainer = UI.createLoginContainer(eventsManager, loginHandler); modal.show(loginContainer, { size: 'small' }); }).catch(() => { notifications.error('Login error!'); }); const logout = () => { if (!authService) return; authService .signOut() .then(() => { notifications.success('Logged out successfully'); UI.displayLoggedOut(); }) .catch(() => { notifications.error('Logout error!'); }); }; const registerScreen = (screen: Screen['screen'], fn: Screen['show']) => { const registered = screens.find((s) => s.screen.toLowerCase() === screen.toLowerCase()); if (registered) { registered.show = fn; } else { screens.push({ screen: screen.toLowerCase() as Screen['screen'], show: fn }); } }; const showScreen = async (screen: Screen['screen']) => { await screens.find((s) => s.screen.toLowerCase() === screen.toLowerCase())?.show(); const modalElement = document.querySelector('#modal') as HTMLElement; (modalElement.firstElementChild as HTMLElement)?.click(); }; const loadSelectedScreen = () => { const params = Object.fromEntries( (new URLSearchParams(parent.location.search) as unknown) as Iterable<any>, ); const screen = params.screen; if (screen) { showScreen(screen); } }; const getAllEditors = (): CodeEditor[] => [ ...Object.values(editors), ...[toolsPane?.console.getEditor()], ...[toolsPane?.compiled.getEditor()], ]; const setTheme = (theme: Theme) => { const themes = ['light', 'dark']; const root = document.querySelector(':root'); root?.classList.remove(...themes); root?.classList.add(theme); getAllEditors().forEach((editor) => editor?.setTheme(theme)); }; const loadSettings = (config: Config) => { const processorToggles = UI.getProcessorToggles(); processorToggles.forEach((toggle) => { const plugin = toggle.dataset.plugin as PluginName; if (!plugin) return; toggle.checked = config.processors.postcss[plugin]; }); if (isEmbed) return; const autoupdateToggle = UI.getAutoupdateToggle(); autoupdateToggle.checked = config.autoupdate; const autosaveToggle = UI.getAutosaveToggle(); autosaveToggle.checked = config.autosave; const formatOnsaveToggle = UI.getFormatOnsaveToggle(); formatOnsaveToggle.checked = config.formatOnsave; const emmetToggle = UI.getEmmetToggle(); emmetToggle.checked = config.emmet; const themeToggle = UI.getThemeToggle(); themeToggle.checked = config.theme === 'dark'; const restoreToggle = UI.getRestoreToggle(); restoreToggle.checked = config.enableRestore; UI.getCSSPresetLinks().forEach((link) => { link.classList.remove('active'); if (config.cssPreset === link.dataset.preset) { link.classList.add('active'); } if (!config.cssPreset && link.dataset.preset === 'none') { link.classList.add('active'); } }); }; const showLanguageInfo = (languageInfo: HTMLElement) => { modal.show(languageInfo, { size: 'small' }); }; const loadStarterTemplate = async (templateName: string) => { const templates = await getTemplates(); const template = templates.filter((template) => template.name === templateName)?.[0]; if (template) { checkSavedAndExecute(() => { loadConfig( { ...defaultConfig, ...template, }, '?template=' + templateName, ); })().finally(() => { modal.close(); }); } else { notifications.error('Failed loading template'); } }; const showVersion = () => { if (getConfig().showVersion) { // variables added in scripts/build.js const version = process.env.VERSION || ''; const commitSHA = process.env.GIT_COMMIT || ''; const repoUrl = process.env.REPO_URL || ''; // eslint-disable-next-line no-console console.log(`Version: ${version} (${repoUrl}/releases/tag/v${version})`); // eslint-disable-next-line no-console console.log(`Git commit: ${commitSHA} (${repoUrl}/commit/${commitSHA})`); } }; const handleTitleEdit = () => { const projectTitle = UI.getProjectTitleElement(); if (!projectTitle) return; projectTitle.textContent = getConfig().title || defaultConfig.title; setWindowTitle(); eventsManager.addEventListener(projectTitle, 'input', () => setProjectTitle(), false); eventsManager.addEventListener(projectTitle, 'blur', () => setProjectTitle(true), false); eventsManager.addEventListener( projectTitle, 'keypress', ((e: KeyboardEvent) => { if ((e as KeyboardEvent).which === 13) { /* Enter */ (e as KeyboardEvent).preventDefault(); projectTitle.blur(); } }) as any, false, ); }; const handleResize = () => { const resizeEditors = () => { Object.values(editors).forEach((editor: CodeEditor) => { setTimeout(() => { if (editor.layout) { editor.layout(); // resize monaco editor } }); }); }; resizeEditors(); eventsManager.addEventListener(window, 'resize', resizeEditors, false); eventsManager.addEventListener(window, 'editor-resize', resizeEditors, false); }; const handleIframeResize = () => { const gutter = UI.getGutterElement(); const sizeLabel = document.createElement('div'); sizeLabel.id = 'size-label'; gutter.appendChild(sizeLabel); const hideLabel = debounce(() => { setTimeout(() => { sizeLabel.classList.remove('visible'); setTimeout(() => { sizeLabel.style.display = 'none'; }, 100); }, 1000); }, 1000); eventsManager.addEventListener(window, 'message', (event: any) => { const iframe = UI.getResultIFrameElement(); if ( !sizeLabel || !iframe || event.source !== iframe.contentWindow || event.data.type !== 'resize' ) { return; } const sizes = event.data.sizes; sizeLabel.innerHTML = `${sizes.width} x ${sizes.height}`; sizeLabel.style.display = 'block'; sizeLabel.classList.add('visible'); hideLabel(); }); }; const handleSelectEditor = () => { UI.getEditorTitles().forEach((title) => { eventsManager.addEventListener( title, 'click', () => { showEditor(title.dataset.editor as EditorId); setProjectRestore(); }, false, ); }); }; const handlechangeLanguage = () => { if (getConfig().allowLangChange) { UI.getLanguageMenuLinks().forEach((menuItem) => { eventsManager.addEventListener( menuItem, 'mousedown', // fire this event before unhover async () => { await changeLanguage(menuItem.dataset.lang as Language); }, false, ); }); } else { UI.getLanguageMenuButtons().forEach((menuButton) => { menuButton.style.display = 'none'; }); } }; const handleChangeContent = () => { const contentChanged = async (editorId: EditorId, loading: boolean) => { updateConfig(); addConsoleInputCodeCompletion(); if (getConfig().autoupdate && !loading) { await run(editorId); } if (getConfig().autosave) { await save(); } loadModuleTypes(editors, getConfig()); }; const debouncecontentChanged = (editorId: EditorId) => debounce(async () => { await contentChanged(editorId, changingContent); }, getConfig().delay ?? defaultConfig.delay); (Object.keys(editors) as EditorId[]).forEach((editorId) => { editors[editorId].onContentChanged(debouncecontentChanged(editorId)); editors[editorId].onContentChanged(setSavedStatus); }); }; const handleHotKeys = () => { const ctrl = (e: KeyboardEvent) => (navigator.platform.match('Mac') ? e.metaKey : e.ctrlKey); const hotKeys = async (e: KeyboardEvent) => { if (!e) return; // Cmd + p opens the command palette const activeEditor = getActiveEditor(); if (ctrl(e) && e.keyCode === 80 && activeEditor.monaco) { e.preventDefault(); activeEditor.monaco.trigger('anyString', 'editor.action.quickCommand'); return; } // Cmd + d prevents browser bookmark dialog if (ctrl(e) && e.keyCode === 68) { e.preventDefault(); return; } if (isEmbed) return; // Cmd + Shift + S forks the project (save as...) if (ctrl(e) && e.shiftKey && e.keyCode === 83) { e.preventDefault(); await fork(); return; } // Cmd + S saves the project if (ctrl(e) && e.keyCode === 83) { e.preventDefault(); await save(true); return; } }; eventsManager.addEventListener(window, 'keydown', hotKeys as any, true); }; const handleRunButton = () => { const handleRun = async () => { split.show('output'); await run(); }; eventsManager.addEventListener(UI.getRunButton(), 'click', handleRun); eventsManager.addEventListener(UI.getCodeRunButton(), 'click', handleRun); }; const handleResultButton = () => { eventsManager.addEventListener(UI.getResultButton(), 'click', () => split.show('output', true)); }; const handleProcessors = () => { const styleMenu = UI.getstyleMenu(); const pluginList = pluginSpecs.map((plugin) => ({ name: plugin.name, title: plugin.title })); if (!styleMenu || pluginList.length === 0 || !processorIsEnabled('postcss', getConfig())) { return; } pluginList.forEach((plugin) => { const pluginItem = UI.createPluginItem(plugin); styleMenu.append(pluginItem); eventsManager.addEventListener( pluginItem, 'mousedown', async (event) => { event.preventDefault(); event.stopPropagation(); const toggle = pluginItem.querySelector<HTMLInputElement>('input'); if (!toggle) return; toggle.checked = !toggle.checked; const pluginName = toggle.dataset.plugin; if (!pluginName || !(pluginName in getConfig().processors.postcss)) return; setConfig({ ...getConfig(), processors: { ...getConfig().processors, postcss: { ...getConfig().processors.postcss, [pluginName]: toggle.checked, }, }, }); await run(); }, false, ); eventsManager.addEventListener(pluginItem, 'click', async (event) => { event.preventDefault(); event.stopPropagation(); }); }); }; const handleSettingsMenu = () => { const menuContainer = UI.getSettingsMenuScroller(); const settingsButton = UI.getSettingsButton(); if (!menuContainer || !settingsButton) return; menuContainer.innerHTML = settingsMenuHTML; // This fixes the behaviour where : // clicking outside the settings menu but inside settings menu container, // hides the settings menu but not the container // on small screens the conatiner covers most of the screen // which gives the effect of a non-responsive app eventsManager.addEventListener(menuContainer, 'mousedown', (event) => { if (event.target === menuContainer) { menuContainer.classList.add('hidden'); } }); eventsManager.addEventListener(settingsButton, 'mousedown', () => { menuContainer.classList.remove('hidden'); }); }; const handleSettings = () => { const toggles = UI.getSettingToggles(); toggles.forEach((toggle) => { eventsManager.addEventListener(toggle, 'change', async () => { const configKey = toggle.dataset.config; if (!configKey || !(configKey in getConfig())) return; if (configKey === 'theme') { setConfig({ ...getConfig(), theme: toggle.checked ? 'dark' : 'light' }); setTheme(getConfig().theme); } else { setConfig({ ...getConfig(), [configKey]: toggle.checked }); } setUserConfig(getUserConfig(getConfig())); if (configKey === 'autoupdate' && getConfig()[configKey]) { await run(); } if (configKey === 'emmet') { await configureEmmet(getConfig()); } if (configKey === 'enableRestore') { setUserConfig({ enableRestore: toggle.checked, }); setProjectRestore(); } }); }); const cssPresets = UI.getCssPresetLinks(); cssPresets.forEach((link) => { eventsManager.addEventListener( link, 'click', async (event: Event) => { event.preventDefault(); setConfig({ ...getConfig(), cssPreset: link.dataset.preset as CssPresetId, }); cssPresets.forEach((preset) => { preset.classList.remove('active'); }); link.classList.add('active'); await run(); }, false, ); }); }; const handleLogin = () => { eventsManager.addEventListener(UI.getLoginLink(), 'click', login, false); registerScreen('login', login); }; const handleLogout = () => { eventsManager.addEventListener(UI.getLogoutLink(), 'click', logout, false); }; const handleNew = () => { const createTemplatesUI = () => { const templatesContainer = UI.createTemplatesContainer(eventsManager); const noDataMessage = templatesContainer.querySelector('.no-data'); const starterTemplatesList = UI.getStarterTemplatesList(templatesContainer); const loadingText = starterTemplatesList?.firstElementChild; getTemplates() .then((starterTemplates) => { loadingText?.remove(); starterTemplates.forEach((template) => { const link = UI.createStarterTemplateLink(template, starterTemplatesList, baseUrl); eventsManager.addEventListener( link, 'click', (event) => { event.preventDefault(); const { title, thumbnail, ...templateConfig } = template; projectId = ''; loadConfig( { ...defaultConfig, ...templateConfig, }, location.origin + location.pathname + '?template=' + template.name, ); modal.close(); }, false, ); }); }) .catch(() => { loadingText?.remove(); notifications.error('Failed loading starter templates'); }); const userTemplatesScreen = UI.getUserTemplatesScreen(templatesContainer); const userTemplates = templateStorage.getList(); if (userTemplates.length > 0) { userTemplatesScreen.innerHTML = ''; } const list = document.createElement('ul') as HTMLElement; list.classList.add('open-list'); userTemplatesScreen.appendChild(list); userTemplates.forEach((item) => { const li = document.createElement('li'); list.appendChild(li); const link = document.createElement('a'); link.href = '#'; link.dataset.id = item.id; link.classList.add('open-project-link'); link.innerHTML = ` <div class="open-title">${item.title}</div> <div class="modified-date"><span>Last modified: </span>${new Date( item.lastModified, ).toLocaleString()}</div> `; li.appendChild(link); eventsManager.addEventListener( link, 'click', async (event) => { event.preventDefault(); const itemId = (link as HTMLElement).dataset.id || ''; const template = templateStorage.getItem(itemId)?.pen; if (template) { await loadConfig({ ...template, title: defaultConfig.title, }); projectId = ''; } modal.close(); }, false, ); const deleteButton = document.createElement('button'); deleteButton.classList.add('delete-button'); li.appendChild(deleteButton); eventsManager.addEventListener( deleteButton, 'click', () => { templateStorage.deleteItem(item.id); li.classList.add('hidden'); setTimeout(() => { li.style.display = 'none'; if (templateStorage.getList().length === 0 && noDataMessage) { list.remove(); userTemplatesScreen.appendChild(noDataMessage); } }, 500); }, false, ); }); modal.show(templatesContainer, { isAsync: true }); }; eventsManager.addEventListener( UI.getNewLink(), 'click', checkSavedAndExecute(createTemplatesUI), false, ); registerScreen('new', checkSavedAndExecute(createTemplatesUI)); }; const handleSave = () => { eventsManager.addEventListener(UI.getSaveLink(), 'click', async (event) => { (event as Event).preventDefault(); await save(true); }); }; const handleFork = () => { eventsManager.addEventListener(UI.getForkLink(), 'click', async (event) => { (event as Event).preventDefault(); await fork(); }); }; const handleSaveAsTemplate = () => { eventsManager.addEventListener(UI.getSaveAsTemplateLink(), 'click', (event) => { (event as Event).preventDefault(); templateStorage.addItem(getConfig()); notifications.success('Saved as a new template'); }); }; const handleOpen = () => { const createList = () => { const div = document.createElement('div'); div.innerHTML = openScreen; const listContainer = div.firstChild as HTMLElement; const noDataMessage = listContainer.querySelector('.no-data') as HTMLElement; const noMatchMessage = listContainer.querySelector('#no-match.no-data') as HTMLElement; const projectsContainer = listContainer.querySelector('#projects-container') as HTMLElement; const list = document.createElement('ul') as HTMLElement; list.classList.add('open-list'); let savedProjects = projectStorage.getList(); let visibleProjects = savedProjects; const bulkImportButton = UI.getBulkImportButton(listContainer); const exportAllButton = UI.getExportAllButton(listContainer); const deleteAllButton = UI.getDeleteAllButton(listContainer); eventsManager.addEventListener( bulkImportButton, 'click', () => { showScreen('import'); }, false, ); eventsManager.addEventListener( exportAllButton, 'click', () => { const data = projectStorage .getAllData() .filter((item) => visibleProjects.find((p) => p.id === item.id)) .map((item) => ({ ...item, pen: getContentConfig(item.pen), })); const filename = 'livecodes_export_' + getDate(); const content = 'data:text/json;charset=utf-8,' + encodeURIComponent(JSON.stringify(data)); downloadFile(filename, 'json', content); }, false, ); eventsManager.addEventListener( deleteAllButton, 'click', () => { notifications.confirm(`Delete ${visibleProjects.length} projects?`, () => { visibleProjects.forEach((p) => { projectStorage.deleteItem(p.id); if (projectId === p.id) { projectId = ''; } }); visibleProjects = []; savedProjects = projectStorage.getList(); showList(visibleProjects); }); }, false, ); projectsContainer.appendChild(list); const showList = (projects: SavedProject[]) => { visibleProjects = projects; list.innerHTML = ''; projects.forEach((item) => { const { link, deleteButton } = UI.createOpenItem(item, list); eventsManager.addEventListener( link, 'click', async (event) => { event.preventDefault(); const loading = UI.createItemLoader(item); modal.show(loading, { size: 'small' }); const itemId = (link as HTMLElement).dataset.id || ''; const savedPen = projectStorage.getItem(itemId)?.pen; if (savedPen) { await loadConfig(savedPen); projectId = itemId; } modal.close(); loading.remove(); }, false, ); eventsManager.addEventListener( deleteButton, 'click', () => { notifications.confirm(`Delete project: ${item.title}?`, () => { if (item.id === projectId) { projectId = ''; } projectStorage.deleteItem(item.id); visibleProjects = visibleProjects.filter((p) => p.id !== item.id); const li = deleteButton.parentElement as HTMLElement; li.classList.add('hidden'); setTimeout(() => { showList(visibleProjects); }, 500); }); }, false, ); }); if (projects.length === 0) { list.classList.add('hidden'); deleteAllButton.classList.add('hidden'); exportAllButton.classList.add('hidden'); if (projectStorage.getList().length === 0) { noDataMessage.classList.remove('hidden'); noMatchMessage.classList.add('hidden'); } else { noDataMessage.classList.add('hidden'); noMatchMessage.classList.remove('hidden'); } } else { list.classList.remove('hidden'); deleteAllButton.classList.remove('hidden'); exportAllButton.classList.remove('hidden'); noDataMessage.classList.add('hidden'); noMatchMessage.classList.add('hidden'); } }; showList(savedProjects); const getProjects = () => projectStorage.getList(); modal.show(listContainer, { isAsync: true }); UI.organizeProjects(getProjects, showList, eventsManager); }; eventsManager.addEventListener( UI.getOpenLink(), 'click', checkSavedAndExecute(createList), false, ); registerScreen('open', checkSavedAndExecute(createList)); }; const handleImport = () => { const createImportUI = () => { const importContainer = UI.createImportContainer(eventsManager); const importForm = UI.getUrlImportForm(importContainer); const importButton = UI.getUrlImportButton(importContainer); eventsManager.addEventListener(importForm, 'submit', async (e) => { e.preventDefault(); const buttonText = importButton.innerHTML; importButton.innerHTML = 'Loading...'; importButton.disabled = true; const importInput = UI.getUrlImportInput(importContainer); const url = importInput.value; const imported = await importCode(url, {}, defaultConfig, await authService?.getUser()); if (imported && Object.keys(imported).length > 0) { await loadConfig( { ...defaultConfig, ...imported, }, location.origin + location.pathname + '#' + url, ); modal.close(); } else { importButton.innerHTML = buttonText; importButton.disabled = false; notifications.error('failed to load URL'); importInput.focus(); } }); const importJsonUrlForm = UI.getImportJsonUrlForm(importContainer); const importJsonUrlButton = UI.getImportJsonUrlButton(importContainer); eventsManager.addEventListener(importJsonUrlForm, 'submit', async (e) => { e.preventDefault(); const buttonText = importJsonUrlButton.innerHTML; importJsonUrlButton.innerHTML = 'Loading...'; importJsonUrlButton.disabled = true; const importInput = UI.getImportJsonUrlInput(importContainer); const url = importInput.value; fetchWithHandler(url) .then((res) => res.json()) .then((fileConfig) => loadConfig(fileConfig, location.origin + location.pathname + '?config=' + url), ) .then(() => modal.close()) .catch(() => { importJsonUrlButton.innerHTML = buttonText; importJsonUrlButton.disabled = false; notifications.error('Error: failed to load URL'); importInput.focus(); }); }); const bulkImportJsonUrlForm = UI.getBulkImportJsonUrlForm(importContainer); const bulkimportJsonUrlButton = UI.getBulkImportJsonUrlButton(importContainer); eventsManager.addEventListener(bulkImportJsonUrlForm, 'submit', async (e) => { e.preventDefault(); const buttonText = bulkimportJsonUrlButton.innerHTML; bulkimportJsonUrlButton.innerHTML = 'Loading...'; bulkimportJsonUrlButton.disabled = true; const importInput = UI.getBulkImportJsonUrlInput(importContainer); const url = importInput.value; fetchWithHandler(url) .then((res) => res.json()) .then(insertItems) .catch(() => { bulkimportJsonUrlButton.innerHTML = buttonText; bulkimportJsonUrlButton.disabled = false; notifications.error('Error: failed to load URL'); importInput.focus(); }); }); const loadFile = <T>(input: HTMLInputElement) => new Promise<T>((resolve, reject) => { if (input.files?.length === 0) return; const file = (input.files as FileList)[0]; const allowedTypes = ['application/json', 'text/plain']; if (allowedTypes.indexOf(file.type) === -1) { reject('Error: Incorrect file type'); return; } // Max 2 MB allowed const maxSizeAllowed = 2 * 1024 * 1024; if (file.size > maxSizeAllowed) { reject('Error: Exceeded size 2MB'); return; } const reader = new FileReader(); eventsManager.addEventListener(reader, 'load', async (event: any) => { const text = (event.target?.result as string) || ''; try { resolve(JSON.parse(text)); } catch (error) { reject('Invalid configuration file'); } }); eventsManager.addEventListener(reader, 'error', () => { reject('Error: Failed to read file'); }); reader.readAsText(file); }); const insertItems = (items: Item[]) => { if (Array.isArray(items) && items.every((item) => item.pen)) { projectStorage.bulkInsert(items); notifications.success('Import Successful!'); showScreen('open'); return; } return Promise.reject('Error: Invalid file'); }; const fileInput = UI.getImportFileInput(importContainer); eventsManager.addEventListener(fileInput, 'change', () => { loadFile<Config>(fileInput) .then(loadConfig) .then(modal.close) .catch((message) => { notifications.error(message); }); }); const bulkFileInput = UI.getBulkImportFileInput(importContainer); eventsManager.addEventListener(bulkFileInput, 'change', () => { loadFile<Item[]>(bulkFileInput) .then(insertItems) .catch((message) => { notifications.error(message); }); }); const linkToSavedProjects = UI.getLinkToSavedProjects(importContainer); eventsManager.addEventListener(linkToSavedProjects, 'click', (e) => { e.preventDefault(); showScreen('open'); }); modal.show(importContainer, { isAsync: true }); UI.getUrlImportInput(importContainer).focus(); }; eventsManager.addEventListener( UI.getImportLink(), 'click', checkSavedAndExecute(createImportUI), false, ); registerScreen('import', checkSavedAndExecute(createImportUI)); }; const handleExport = () => { eventsManager.addEventListener( UI.getExportJSONLink(), 'click', (event: Event) => { event.preventDefault(); updateConfig(); exportConfig(getConfig(), baseUrl, 'json'); }, false, ); eventsManager.addEventListener( UI.getExportResultLink(), 'click', async (event: Event) => { event.preventDefault(); updateConfig(); exportConfig(getConfig(), baseUrl, 'html', await getResultPage({ forExport: true })); }, false, ); let JSZip: any; eventsManager.addEventListener( UI.getExportSourceLink(), 'click', async (event: Event) => { event.preventDefault(); updateConfig(); const html = await getResultPage({ forExport: true }); exportConfig(getConfig(), baseUrl, 'src', { JSZip, html }); }, false, ); eventsManager.addEventListener( UI.getExportCodepenLink(), 'click', () => { updateConfig(); exportConfig(getConfig(), baseUrl, 'codepen'); }, false, ); eventsManager.addEventListener( UI.getExportJsfiddleLink(), 'click', () => { updateConfig(); exportConfig(getConfig(), baseUrl, 'jsfiddle'); }, false, ); eventsManager.addEventListener( UI.getExportGithubGistLink(), 'click', async () => { updateConfig(); let user = await authService?.getUser(); if (!user) { user = await login(); } if (!user) return; notifications.info('Creating a public GitHub gist...'); exportConfig(getConfig(), baseUrl, 'githubGist', { user }); }, false, ); }; const handleShare = () => { const createShareUI = async () => { const shareContainer = await UI.createShareContainer(share, baseUrl, eventsManager); modal.show(shareContainer, { size: 'small' }); }; eventsManager.addEventListener( UI.getShareLink(), 'click', async (event: Event) => { event.preventDefault(); await createShareUI(); }, false, ); registerScreen('share', createShareUI); }; const handleDeploy = () => { const createDeployUI = async () => { let user = await authService?.getUser(); if (!user) { user = await login(); } if (!user) { notifications.error('Authentication error!'); return; } const deployContainer = UI.createDeployContainer(eventsManager); const newRepoForm = UI.getNewRepoForm(deployContainer); const newRepoButton = UI.getNewRepoButton(deployContainer); const newRepoNameInput = UI.getNewRepoNameInput(deployContainer); const newRepoNameError = UI.getNewRepoNameError(deployContainer); const newRepoMessageInput = UI.getNewRepoMessageInput(deployContainer); const newRepoCommitSource = UI.getNewRepoCommitSource(deployContainer); const existingRepoForm = UI.getExistingRepoForm(deployContainer); const existingRepoButton = UI.getExistingRepoButton(deployContainer); const existingRepoNameInput = UI.getExistingRepoNameInput(deployContainer); const existingRepoMessageInput = UI.getExistingRepoMessageInput(deployContainer); const existingRepoCommitSource = UI.getExistingRepoCommitSource(deployContainer); const publish = async ( user: User, repo: string, message: string, commitSource: boolean, newRepo: boolean, ) => { const forExport = true; const singleFile = false; newRepoNameError.innerHTML = ''; const resultHtml = await getResultPage({ forExport, template: resultTemplate, singleFile, }); const cache = getCache(); const deployResult = await deploy({ user, repo, config: getContentConfig(getConfig()), content: { resultPage: resultHtml, style: cache.style.compiled || '', script: cache.script.compiled || '', }, message, commitSource, singleFile, newRepo, }).catch((error) => { if (error.message === 'Repo name already exists') { newRepoNameError.innerHTML = error.message; } }); if (newRepoNameError.innerHTML !== '') { return false; } else if (deployResult) { const confirmationContianer = deployedConfirmation(deployResult, commitSource); modal.show(confirmationContianer, { size: 'small', closeButton: true }); return true; } else { modal.close(); notifications.error('Deployment failed!'); return true; } }; eventsManager.addEventListener(newRepoForm, 'submit', async (e) => { e.preventDefault(); if (!user) return; const name = newRepoNameInput.value; const message = newRepoMessageInput.value; const commitSource = newRepoCommitSource.checked; const newRepo = true; if (!name) { notifications.error('Repo name is required'); return; } newRepoButton.innerHTML = 'Deploying...'; newRepoButton.disabled = true; const result = await publish(user, name, message, commitSource, newRepo); if (!result) { newRepoButton.innerHTML = 'Deploy'; newRepoButton.disabled = false; } }); eventsManager.addEventListener(existingRepoForm, 'submit', async (e) => { e.preventDefault(); if (!user) return; const name = existingRepoNameInput.value; const message = existingRepoMessageInput.value; const commitSource = existingRepoCommitSource.checked; const newRepo = false; if (!name) { notifications.error('Repo name is required'); return; } existingRepoButton.innerHTML = 'Deploying...'; existingRepoButton.disabled = true; await publish(user, name, message, commitSource, newRepo); }); let autoComplete: any; import(autoCompleteUrl).then(async () => { autoComplete = (globalThis as any).autoComplete; if (!user) return; const publicRepos = await getUserPublicRepos(user); eventsManager.addEventListener(existingRepoNameInput, 'init', () => { existingRepoNameInput.focus(); }); const inputSelector = '#' + existingRepoNameInput.id; if (!document.querySelector(inputSelector)) return; const autoCompleteJS = new autoComplete({ selector: inputSelector, placeHolder: 'Search your public repos...', data: { src: publicRepos, }, resultItem: { highlight: { render: true, }, }, }); eventsManager.addEventListener(autoCompleteJS.input, 'selection', function (event: any) { const feedback = event.detail; autoCompleteJS.input.blur(); const selection = feedback.selection.value; autoCompleteJS.input.value = selection; }); }); modal.show(deployContainer); newRepoNameInput.focus(); }; eventsManager.addEventListener(UI.getDeployLink(), 'click', createDeployUI, false); registerScreen('deploy', createDeployUI); }; const handleProjectInfo = () => { const onSave = (title: string, description: string, tags: string[]) => { setConfig({ ...getConfig(), title, description, tags, }); save(!projectId, true); }; const createProjectInfoUI = () => UI.createProjectInfoUI(getConfig(), projectStorage, modal, eventsManager, onSave); eventsManager.addEventListener(UI.getProjectInfoLink(), 'click', createProjectInfoUI, false); registerScreen('info', createProjectInfoUI); }; const handleExternalResources = () => { const createExrenalResourcesUI = () => { const div = document.createElement('div'); div.innerHTML = resourcesScreen; const resourcesContainer = div.firstChild as HTMLElement; modal.show(resourcesContainer); const externalResources = UI.getExternalResourcesTextareas(); externalResources.forEach((textarea) => { const resourceContent = getConfig()[textarea.dataset.resource as 'stylesheets' | 'scripts']; textarea.value = resourceContent.length !== 0 ? resourceContent.join('\n') + '\n' : ''; }); externalResources[0]?.focus(); eventsManager.addEventListener(UI.getLoadResourcesButton(), 'click', async () => { externalResources.forEach((textarea) => { const resource = textarea.dataset.resource as 'stylesheets' | 'scripts'; setConfig({ ...getConfig(), [resource]: textarea.value ?.split('\n') .map((x) => x.trim()) .filter((x) => x !== '') || [], }); }); setSavedStatus(); modal.close(); await run(); }); }; eventsManager.addEventListener( UI.getExternalResourcesLink(), 'click', createExrenalResourcesUI, false, ); registerScreen('external', createExrenalResourcesUI); }; const handleCustomSettings = () => { const createCustomSettingsUI = async () => { const config = getConfig(); // eslint-disable-next-line prefer-const let customSettingsEditor: CodeEditor | undefined; const div = document.createElement('div'); div.innerHTML = customSettingsScreen; const customSettingsContainer = div.firstChild as HTMLElement; modal.show(customSettingsContainer, { onClose: () => { customSettingsEditor?.destroy(); }, }); const options = { baseUrl, mode: config.mode, readonly: config.readonly, editor: config.editor, editorType: 'code' as EditorOptions['editorType'], editorBuild, container: UI.getCustomSettingsEditor(), language: 'json' as Language, value: stringify(getConfig().customSettings, true), theme: config.theme, }; customSettingsEditor = await createEditor(options); customSettingsEditor.focus(); eventsManager.addEventListener(UI.getLoadCustomSettingsButton(), 'click', async () => { let customSettings: any = {}; const editorContent = customSettingsEditor?.getValue() || '{}'; try { customSettings = JSON.parse(editorContent); } catch { try { customSettings = JSON.parse(stringToValidJson(editorContent)); } catch { notifications.error('Failed parsing settings as JSON'); return; } } if (customSettings !== getConfig().customSettings) { setConfig({ ...getConfig(), customSettings, }); setSavedStatus(); } customSettingsEditor?.destroy(); modal.close(); await run(); }); }; eventsManager.addEventListener( UI.getCustomSettingsLink(), 'click', createCustomSettingsUI, false, ); registerScreen('custom-settings', createCustomSettingsUI); }; const handleResultLoading = () => { eventsManager.addEventListener(window, 'message', (event: any) => { const iframe = UI.getResultIFrameElement(); if (!iframe || event.source !== iframe.contentWindow) { return; } if (event.data.type === 'loading') { setLoading(event.data.payload); } const language = event.data.payload?.language; if (event.data.type === 'compiled' && language && getEditorLanguages().includes(language)) { const editorId = getLanguageEditorId(language); if (!editorId) return; updateCache(editorId, language, event.data.payload.content || ''); updateCompiledCode(); } }); }; const handleUnload = () => { window.onbeforeunload = () => { if (!isSaved) { return 'Changes you made may not be saved.'; } else { return; } }; }; const basicHandlers = () => { handleResize(); handleIframeResize(); handleSelectEditor(); handlechangeLanguage(); handleChangeContent(); handleHotKeys(); handleRunButton(); handleResultButton(); handleProcessors(); handleShare(); handleResultLoading(); }; const extraHandlers = () => { handleTitleEdit(); handleSettingsMenu(); handleSettings(); handleProjectInfo(); handleExternalResources(); handleCustomSettings(); handleLogin(); handleLogout(); handleNew(); handleSave(); handleFork(); handleSaveAsTemplate(); handleOpen(); handleImport(); handleExport(); handleDeploy(); handleUnload(); }; const importExternalContent = async (options: { config?: Config; configUrl?: string; template?: string; url?: string; }) => { const { config = defaultConfig, configUrl, template, url } = options; const editorIds: EditorId[] = ['markup', 'style', 'script']; const hasContentUrls = (conf: Partial<Config>) => editorIds.filter((editorId) => conf[editorId]?.contentUrl && !conf[editorId]?.content).length > 0; if (!configUrl && !template && !url && !hasContentUrls(config)) return; const loadingMessage = document.createElement('div'); loadingMessage.classList.add('modal-message'); loadingMessage.innerHTML = 'Loading Project...'; modal.show(loadingMessage, { size: 'small' }); let importedConfig: Partial<Config> = {}; if (configUrl) { importedConfig = upgradeAndValidate( await fetch(configUrl) .then((res) => res.json()) .catch(() => ({})), ); if (hasContentUrls(importedConfig)) { await importExternalContent({ config: { ...config, ...importedConfig } }); return; } } else if (template) { importedConfig = upgradeAndValidate(await getTemplate(template, config, baseUrl)); } else if (url) { // import code from hash: code / github / github gist / url html / ...etc let user; if (isGithub(url) && !isEmbed) { await initializeAuth(); user = await authService?.getUser(); } importedConfig = await importCode(url, getParams(), getConfig(), user); } else if (hasContentUrls(config)) { // load content from config contentUrl const editorsContent = await Promise.all( editorIds.map((editorId) => { const contentUrl = config[editorId].contentUrl; if (contentUrl && !config[editorId].content) { return fetch(contentUrl) .then((res) => res.text()) .then((content) => ({ ...config[editorId], content, })); } else { return Promise.resolve(config[editorId]); } }), ); importedConfig = { markup: editorsContent[0], style: editorsContent[1], script: editorsContent[2], }; } await loadConfig( { ...config, ...importedConfig, }, parent.location.href, ); modal.close(); }; const bootstrap = async (reload = false) => { await createIframe(UI.getResultElement()); if (reload) { await updateEditors(editors, getConfig()); } phpHelper({ editor: editors.script }); setLoading(true); await setActiveEditor(getConfig()); loadSettings(getConfig()); await configureEmmet(getConfig()); showMode(getConfig()); setTimeout(() => getActiveEditor().focus()); await toolsPane?.load(); updateCompiledCode(); loadModuleTypes(editors, getConfig()); compiler.load(Object.values(editorLanguages || {}), getConfig()).then(async () => { await run(); }); formatter.load(getEditorLanguages()); if (!reload) { loadSelectedScreen(); if (!isEmbed) { initializeAuth(); checkRestoreStatus(); } const params = getParams(); // query string params importExternalContent({ config: getConfig(), configUrl: params.config, template: params.template, url: parent.location.hash.substring(1), }); } }; const initializeApp = async ( options?: { config?: Partial<Config>; baseUrl?: string; isEmbed?: boolean; }, initializeFn?: () => void, ) => { const appConfig = options?.config ?? {}; baseUrl = options?.baseUrl ?? '/livecodes/'; isEmbed = options?.isEmbed ?? false; setConfig(buildConfig(appConfig, baseUrl)); compiler = await getCompiler(getConfig(), baseUrl); formatter = getFormatter(getConfig(), baseUrl); if (isEmbed) { configureEmbed(eventsManager, share); } loadUserConfig(); createLanguageMenus( getConfig(), baseUrl, eventsManager, showLanguageInfo, loadStarterTemplate, importExternalContent, ); shouldUpdateEditorBuild(); await createEditors(getConfig()); toolsPane = createToolsPane(getConfig(), baseUrl, editors, eventsManager); basicHandlers(); initializeFn?.(); loadStyles(); await bootstrap(); setTheme(getConfig().theme); showVersion(); }; const createApi = () => ({ run: async () => { await run(); }, format: async () => format(), getShareUrl: async (shortUrl = false) => (await share(shortUrl)).url, getConfig: (contentOnly = false): Config => { updateConfig(); const config = contentOnly ? getContentConfig(getConfig()) : getConfig(); return JSON.parse(JSON.stringify(config)); }, setConfig: async (newConfig: Config): Promise<Config> => { const newAppConfig = await buildConfig(newConfig, baseUrl); await loadConfig(newAppConfig); return newAppConfig; }, getCode: async (): Promise<Code> => { updateConfig(); if (!cacheIsValid(getCache(), getContentConfig(getConfig()))) { await getResultPage({}); } return JSON.parse(JSON.stringify(getCachedCode())); }, }); export { createApi, initializeApp, extraHandlers };
the_stack
interface RCConversation { watcher: any; watch(_watcher: Function): void; unwatch(_watcher: Function): void; _notify(conversationList: Array<any>): void; } module RongIMLib { export class ServerDataProvider implements DataAccessProvider { userStatusListener: Function = null; Conversation: RCConversation = { watcher: new Observer(), watch: function(_watcher: any) { this.watcher.add(_watcher); let conversationList = RongIMClient._memoryStore.conversationList; this.watcher.emit(conversationList); }, unwatch: function (_watcher: any) { this.watcher.remove(_watcher); }, _notify: function (conversationList: Array<any>) { this.watcher.emit(conversationList); } }; init(appKey: string, options?: any): void { new FeatureDectector(options.appCallback); } connect(token: string, callback: ConnectCallback, userId?: string, option?: any) { RongIMClient.bridge = Bridge.getInstance(); RongIMClient._memoryStore.token = token; RongIMClient._memoryStore.callback = callback; userId = userId || ''; option = option || {}; var isConnecting = false, isConnected = false; if (Bridge._client && Bridge._client.channel) { isConnecting = (Bridge._client.channel.connectionStatus == ConnectionStatus.CONNECTING); isConnected = (Bridge._client.channel.connectionStatus == ConnectionStatus.CONNECTED); } if (isConnected || isConnecting) { return; } var isGreater = (RongIMClient.otherDeviceLoginCount > 5); if (isGreater) { callback.onError(ConnectionStatus.ULTRALIMIT); return; } // 清除本地导航缓存 if (option.force) { RongIMClient._storageProvider.removeItem('servers'); } RongIMClient.bridge.setListener(); RongIMClient.bridge.connect(RongIMClient._memoryStore.appKey, token, { onSuccess: function (data: string) { setTimeout(function () { callback.onSuccess(data); }); }, onError: function (e: ConnectionState) { if (e == ConnectionState.TOKEN_INCORRECT || !e) { setTimeout(function () { callback.onTokenIncorrect(); }); } else { setTimeout(function () { callback.onError(e); }); } } }); } /* config.auto: 默认 false, true 启用自动重连,启用则为必选参数 config.rate: 重试频率 [100, 1000, 3000, 6000, 10000, 18000] 单位为毫秒,可选 config.url: 网络嗅探地址 [http(s)://]cdn.ronghub.com/RongIMLib-2.2.6.min.js 可选 */ reconnect(callback: ConnectCallback, config?: any): void { var store = RongIMLib.RongIMClient._memoryStore; var token = store.token; if (!token) { throw new Error('reconnect: token is empty.'); } if (Bridge._client && Bridge._client.channel && Bridge._client.channel.connectionStatus != ConnectionStatus.CONNECTED && Bridge._client.channel.connectionStatus != ConnectionStatus.CONNECTING) { config = config || {}; var key = config.auto ? 'auto' : 'custom'; var handler: { [key: string]: any } = { auto: function () { var repeatConnect = function (options: any) { var step = options.step(); var done = 'done'; var url = options.url; var ping = function () { RongUtil.request({ url: url, success: function () { options.done(); }, error: function () { repeat(); } }); }; var repeat = function () { var next = step(); if (next == 'done') { var error = ConnectionStatus.NETWORK_UNAVAILABLE; options.done(error); return; } setTimeout(ping, next); }; repeat(); } var protocol = RongIMClient._memoryStore.depend.protocol; var url = config.url || 'cdn.ronghub.com/RongIMLib-2.2.6.min.js'; var pathConfig = { protocol: protocol, path: url }; url = RongUtil.formatProtoclPath(pathConfig); var rate = config.rate || [100, 1000, 3000, 6000, 10000, 18000]; //结束标识 rate.push('done'); var opts = { url: url, step: function () { var index = 0; return function () { var time = rate[index]; index++; return time; } }, done: function (error: ConnectionStatus) { if (error) { callback.onError(error); return; } RongIMClient.connect(token, callback); } }; repeatConnect(opts); }, custom: function () { RongIMClient.connect(token, callback); } }; handler[key](); } } logout(): void { RongIMClient.bridge.disconnect(); RongIMClient.bridge = null; } disconnect(): void { RongIMClient.bridge.disconnect(); } sendReceiptResponse(conversationType: ConversationType, targetId: string, sendCallback: SendMessageCallback): void { var rspkey: string = Bridge._client.userId + conversationType + targetId + 'RECEIVED', me = this; if (RongUtil.supportLocalStorage()) { var valObj: any = JSON.parse(RongIMClient._storageProvider.getItem(rspkey)); if (valObj) { var vals: any[] = []; for (let key in valObj) { var tmp: any = {}; tmp[key] = valObj[key].uIds; valObj[key].isResponse || vals.push(tmp); } if (vals.length == 0) { sendCallback.onSuccess(); return; } var interval = setInterval(function () { if (vals.length == 1) { clearInterval(interval); } var obj = vals.splice(0, 1)[0]; var rspMsg = new RongIMLib.ReadReceiptResponseMessage({ receiptMessageDic: obj }); me.sendMessage(conversationType, targetId, rspMsg, <SendMessageCallback>{ onSuccess: function (msg) { var senderUserId = MessageUtil.getFirstKey(obj); valObj[senderUserId].isResponse = true; RongIMClient._storageProvider.setItem(rspkey, JSON.stringify(valObj)); sendCallback.onSuccess(msg); }, onError: function (error: ErrorCode, msg: Message) { sendCallback.onError(error, msg); } }); }, 200); } else { sendCallback.onSuccess(); } } else { sendCallback.onSuccess(); } } sendTypingStatusMessage(conversationType: ConversationType, targetId: string, messageName: string, sendCallback: SendMessageCallback): void { var me = this; if (messageName in RongIMClient.MessageParams) { me.sendMessage(conversationType, targetId, TypingStatusMessage.obtain(RongIMClient.MessageParams[messageName].objectName, ""), <SendMessageCallback>{ onSuccess: function () { setTimeout(function () { sendCallback.onSuccess(); }); }, onError: function (errorCode: ErrorCode) { setTimeout(function () { sendCallback.onError(errorCode, null); }); }, onBefore: function () { } }); } } sendRecallMessage(content: any, sendMessageCallback: SendMessageCallback): void { var msg = new RecallCommandMessage({ conversationType: content.conversationType, targetId: content.targetId, sentTime: content.sentTime, messageUId: content.messageUId, extra: content.extra, user: content.user }); this.sendMessage(content.conversationType, content.senderUserId, msg, sendMessageCallback, false, null, null, 2); } sendTextMessage(conversationType: ConversationType, targetId: string, content: string, sendMessageCallback: SendMessageCallback): void { var msgContent = TextMessage.obtain(content); this.sendMessage(conversationType, targetId, msgContent, sendMessageCallback); } getRemoteHistoryMessages(conversationType: ConversationType, targetId: string, timestamp: number, count: number, callback: GetHistoryMessagesCallback, config?: any): void { if (count <= 1) { throw new Error("the count must be greater than 1."); } config = config || {}; var order = config.order || 0; var getKey = function () { return [conversationType, targetId, '_', order].join(''); }; var key = getKey(); if (!RongUtil.isNumber(timestamp)) { timestamp = RongIMClient._memoryStore.lastReadTime.get(key); } var memoryStore = RongIMClient._memoryStore; var historyMessageLimit = memoryStore.historyMessageLimit; /* limit 属性: var limit = { time: '时间戳, 最后一次拉取时间', hasMore: '是否还有历史消息, bool 值' }; */ var limit: any = historyMessageLimit.get(key) || {}; var hasMore = limit.hasMore; var isFecth = (hasMore || limit.time != timestamp); // 正序获取消息时不做限制,防止有新消息导致无法获取 if (!isFecth && order == 0) { return callback.onSuccess([], hasMore); } var modules = new RongIMClient.Protobuf.HistoryMsgInput(), self = this; modules.setTargetId(targetId); modules.setTime(timestamp); modules.setCount(count); modules.setOrder(order); var topic = HistoryMsgType[conversationType] || HistoryMsgType[RongIMLib.ConversationType.PRIVATE]; RongIMClient.bridge.queryMsg(topic, MessageUtil.ArrayForm(modules.toArrayBuffer()), targetId, { onSuccess: function (data: any) { var fetchTime = MessageUtil.int64ToTimestamp(data.syncTime); RongIMClient._memoryStore.lastReadTime.set(key, fetchTime); historyMessageLimit.set(key, { hasMore: !!data.hasMsg, time: fetchTime }); var list = data.list.reverse(), tempMsg: Message = null, tempDir: any; var read = RongIMLib.SentStatus.READ; if (RongUtil.supportLocalStorage()) { for (var i = 0, len = list.length; i < len; i++) { tempMsg = MessageUtil.messageParser(list[i]); tempDir = JSON.parse(RongIMClient._storageProvider.getItem(Bridge._client.userId + tempMsg.messageUId + "SENT")); if (tempDir) { tempMsg.receiptResponse || (tempMsg.receiptResponse = {}); tempMsg.receiptResponse[tempMsg.messageUId] = tempDir.count; } tempMsg.sentStatus = read tempMsg.targetId = targetId; list[i] = tempMsg; } } else { for (var i = 0, len = list.length; i < len; i++) { var tempMsg: Message = MessageUtil.messageParser(list[i]); tempMsg.sentStatus = read; list[i] = tempMsg; } } setTimeout(function () { callback.onSuccess(list, !!data.hasMsg); }); }, onError: function (error: ErrorCode) { setTimeout(function () { callback.onError(error); }); } }, "HistoryMessagesOuput"); } hasRemoteUnreadMessages(token: string, callback: ResultCallback<Boolean>): void { var xss: any = null; window.RCCallback = function (x: any) { setTimeout(function () { callback.onSuccess(!!+x.status); }); xss.parentNode.removeChild(xss); }; xss = document.createElement("script"); xss.src = RongIMClient._memoryStore.depend.api + "/message/exist.js?appKey=" + encodeURIComponent(RongIMClient._memoryStore.appKey) + "&token=" + encodeURIComponent(token) + "&callBack=RCCallback&_=" + RongUtil.getTimestamp(); document.body.appendChild(xss); xss.onerror = function () { setTimeout(function () { callback.onError(ErrorCode.UNKNOWN); }); xss.parentNode.removeChild(xss); }; } getRemoteConversationList(callback: ResultCallback<Conversation[]>, conversationTypes: ConversationType[], count: number): void { var modules = new RongIMClient.Protobuf.RelationsInput(), self = this; modules.setType(1); if (typeof count == 'undefined') { modules.setCount(0); } else { modules.setCount(count); } RongIMClient.bridge.queryMsg(26, MessageUtil.ArrayForm(modules.toArrayBuffer()), Bridge._client.userId, { onSuccess: function (list: any) { if (list.info) { list.info = list.info.reverse(); for (var i = 0, len = list.info.length; i < len; i++) { RongIMClient.getInstance().pottingConversation(list.info[i]); } } var conversations = RongIMClient._memoryStore.conversationList; setTimeout(function () { if (conversationTypes) { return callback.onSuccess(self.filterConversations(conversationTypes, conversations)); } callback.onSuccess(conversations); }); }, onError: function (error: ErrorCode) { callback.onError(error); } }, "RelationsOutput"); } addMemberToDiscussion(discussionId: string, userIdList: string[], callback: OperationCallback): void { var modules = new RongIMClient.Protobuf.ChannelInvitationInput(); modules.setUsers(userIdList); RongIMClient.bridge.queryMsg(0, MessageUtil.ArrayForm(modules.toArrayBuffer()), discussionId, { onSuccess: function () { setTimeout(function () { callback.onSuccess(); }); }, onError: function (error: ErrorCode) { setTimeout(function () { callback.onError(error); }); } }); } createDiscussion(name: string, userIdList: string[], callback: CreateDiscussionCallback): void { var modules = new RongIMClient.Protobuf.CreateDiscussionInput(), self = this; modules.setName(name); RongIMClient.bridge.queryMsg(1, MessageUtil.ArrayForm(modules.toArrayBuffer()), Bridge._client.userId, { onSuccess: function (discussId: string) { if (userIdList.length > 0) { self.addMemberToDiscussion(discussId, userIdList, <OperationCallback>{ onSuccess: function () { }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }); } setTimeout(function () { callback.onSuccess(discussId); }); }, onError: function (error: ErrorCode) { setTimeout(function () { callback.onError(error); }); } }, "CreateDiscussionOutput"); } getDiscussion(discussionId: string, callback: ResultCallback<Discussion>): void { var modules = new RongIMClient.Protobuf.ChannelInfoInput(); modules.setNothing(1); RongIMClient.bridge.queryMsg(4, MessageUtil.ArrayForm(modules.toArrayBuffer()), discussionId, { onSuccess: function (data: any) { setTimeout(function () { callback.onSuccess(data); }); }, onError: function (errorCode: ErrorCode) { setTimeout(function () { callback.onError(errorCode); }); } }, "ChannelInfoOutput"); } quitDiscussion(discussionId: string, callback: OperationCallback): void { var modules = new RongIMClient.Protobuf.LeaveChannelInput(); modules.setNothing(1); RongIMClient.bridge.queryMsg(7, MessageUtil.ArrayForm(modules.toArrayBuffer()), discussionId, { onSuccess: function () { setTimeout(function () { callback.onSuccess(); }); }, onError: function (errorCode: ErrorCode) { setTimeout(function () { callback.onError(errorCode); }); } }); } removeMemberFromDiscussion(discussionId: string, userId: string, callback: OperationCallback): void { var modules = new RongIMClient.Protobuf.ChannelEvictionInput(); modules.setUser(userId); RongIMClient.bridge.queryMsg(9, MessageUtil.ArrayForm(modules.toArrayBuffer()), discussionId, { onSuccess: function () { setTimeout(function () { callback.onSuccess(); }); }, onError: function (errorCode: ErrorCode) { setTimeout(function () { callback.onError(errorCode); }); } }); } setDiscussionInviteStatus(discussionId: string, status: DiscussionInviteStatus, callback: OperationCallback): void { var modules = new RongIMClient.Protobuf.ModifyPermissionInput(); modules.setOpenStatus(status.valueOf()); RongIMClient.bridge.queryMsg(11, MessageUtil.ArrayForm(modules.toArrayBuffer()), discussionId, { onSuccess: function (x: any) { setTimeout(function () { callback.onSuccess(); }); }, onError: function (error: ErrorCode) { setTimeout(function () { callback.onError(error); }); } }); } setDiscussionName(discussionId: string, name: string, callback: OperationCallback): void { var modules = new RongIMClient.Protobuf.RenameChannelInput(); modules.setName(name); RongIMClient.bridge.queryMsg(12, MessageUtil.ArrayForm(modules.toArrayBuffer()), discussionId, { onSuccess: function () { setTimeout(function () { callback.onSuccess(); }); }, onError: function (errcode: ErrorCode) { callback.onError(errcode); } }); } joinChatRoom(chatroomId: string, messageCount: number, callback: OperationCallback): void { var e = new RongIMClient.Protobuf.ChrmInput(); e.setNothing(1); Bridge._client.chatroomId = chatroomId; RongIMClient.bridge.queryMsg(19, MessageUtil.ArrayForm(e.toArrayBuffer()), chatroomId, { onSuccess: function () { var navi: any = RongIMClient.getInstance().getNavi(); var isOpenKVStorage = navi.kvStorage; if (isOpenKVStorage) { RongIMClient._dataAccessProvider.pullChatroomEntry(chatroomId, 0, { onSuccess: function (result:any) { RongIMLib.ChrmKVHandler.setEntries(chatroomId, result); setTimeout(function () { callback.onSuccess(); }); }, onError: function (errorCode:ErrorCode) { setTimeout(function () { callback.onError(errorCode); }); } }) } else { setTimeout(function () { callback.onSuccess(); }); } var modules = new RongIMClient.Protobuf.ChrmPullMsg(); messageCount == 0 && (messageCount = -1); modules.setCount(messageCount); modules.setSyncTime(0); Bridge._client.queryMessage("chrmPull", MessageUtil.ArrayForm(modules.toArrayBuffer()), chatroomId, 1, { onSuccess: function (collection: any) { var list = collection.list; var sync = RongIMLib.MessageUtil.int64ToTimestamp(collection.syncTime); var latestMessage = list[list.length - 1]; if (latestMessage) { latestMessage = RongIMLib.MessageUtil.messageParser(latestMessage); sync = latestMessage.sentTime; } RongIMClient._memoryStore.lastReadTime.set(chatroomId + RongIMLib.Bridge._client.userId + "CST", sync); var _client = RongIMLib.Bridge._client; for (var i = 0, mlen = list.length; i < mlen; i++) { var uId = 'R' + list[i].msgId; if (!(uId in _client.cacheMessageIds)) { _client.cacheMessageIds[uId] = true; var cacheUIds = RongUtil.keys(_client.cacheMessageIds); if (cacheUIds.length > 10) { uId = cacheUIds[0]; delete _client.cacheMessageIds[uId]; } if (RongIMLib.RongIMClient._memoryStore.filterMessages.length > 0) { for (var j = 0, flen = RongIMLib.RongIMClient._memoryStore.filterMessages.length; j < flen; j++) { if (RongIMLib.RongIMClient.MessageParams[RongIMLib.RongIMClient._memoryStore.filterMessages[j]].objectName != list[i].classname) { _client.handler.onReceived(list[i]); } } } else { _client.handler.onReceived(list[i]); } } } }, onError: function (x: any) { setTimeout(function () { callback.onError(ErrorCode.CHATROOM_HISMESSAGE_ERROR); }); } }, "DownStreamMessages"); }, onError: function (error: ErrorCode) { setTimeout(function () { callback.onError(error); }); } }, "ChrmOutput"); } getChatRoomInfo(chatRoomId: string, count: number, order: GetChatRoomType, callback: ResultCallback<any>): void { var modules = new RongIMClient.Protobuf.QueryChatroomInfoInput(); modules.setCount(count); modules.setOrder(order); RongIMClient.bridge.queryMsg("queryChrmI", MessageUtil.ArrayForm(modules.toArrayBuffer()), chatRoomId, { onSuccess: function (ret: any) { var userInfos = ret.userInfos; userInfos.forEach(function (item: any) { item.time = RongIMLib.MessageUtil.int64ToTimestamp(item.time) }); setTimeout(function () { callback.onSuccess(ret); }); }, onError: function (errcode: ErrorCode) { setTimeout(function () { callback.onError(errcode); }); } }, "QueryChatroomInfoOutput"); } quitChatRoom(chatroomId: string, callback: OperationCallback): void { var e = new RongIMClient.Protobuf.ChrmInput(); e.setNothing(1); RongIMClient.bridge.queryMsg(17, MessageUtil.ArrayForm(e.toArrayBuffer()), chatroomId, { onSuccess: function () { setTimeout(function () { callback.onSuccess(); }); }, onError: function (errcode: ErrorCode) { setTimeout(function () { callback.onError(errcode); }); } }, "ChrmOutput"); } setChatroomHisMessageTimestamp(chatRoomId: string, timestamp: number): void { RongIMClient._memoryStore.lastReadTime.set('chrhis_' + chatRoomId, timestamp); } getChatRoomHistoryMessages(chatRoomId: string, count: number, order: number, callback: any): void { var modules = new RongIMClient.Protobuf.HistoryMsgInput(); modules.setTargetId(chatRoomId); var timestamp = RongIMClient._memoryStore.lastReadTime.get('chrhis_' + chatRoomId) || 0; modules.setTime(timestamp); modules.setCount(count); modules.setOrder(order); RongIMClient.bridge.queryMsg(34, MessageUtil.ArrayForm(modules.toArrayBuffer()), Bridge._client.userId, { onSuccess: function (data: any) { RongIMClient._memoryStore.lastReadTime.set('chrhis_' + chatRoomId, MessageUtil.int64ToTimestamp(data.syncTime)) var list = data.list.reverse(); for (var i = 0, len = list.length; i < len; i++) { list[i] = MessageUtil.messageParser(list[i]); } setTimeout(function () { callback.onSuccess(list, !!data.hasMsg); }); }, onError: function (error: ErrorCode) { setTimeout(function () { callback.onError(error); }); } }, "HistoryMsgOuput"); } setChatroomEntry(chatroomId: string, chatroomEntry: ChatroomEntry, callback: ResultCallback<any>): void { var opt = ChatroomEntityOpt.UPDATE; var key = chatroomEntry.key, value = chatroomEntry.value; var isKeyInValid = !RongUtil.isLengthLimit(key, ChatroomEntityLimit.KEY, 1) || !ChrmKVHandler.isKeyValid(key); var isValueInValid = !RongUtil.isLengthLimit(value, ChatroomEntityLimit.VALUE, 1); if (isKeyInValid || isValueInValid) { setTimeout(function () { callback.onError(ErrorCode.BIZ_ERROR_INVALID_PARAMETER); }); } else { this.refreshChatroomEntry(chatroomId, chatroomEntry, opt, callback); } } forceSetChatroomEntry(chatroomId: string, chatroomEntry: ChatroomEntry, callback: ResultCallback<any>): void { chatroomEntry.isOverwrite = true; this.setChatroomEntry(chatroomId, chatroomEntry, callback); } removeChatroomEntry(chatroomId: string, chatroomEntry: ChatroomEntry, callback: ResultCallback<any>): void { var opt = ChatroomEntityOpt.DELETE; var key = chatroomEntry.key; var isKeyInValid = !RongUtil.isLengthLimit(key, ChatroomEntityLimit.KEY, 1) || !ChrmKVHandler.isKeyValid(key); if (isKeyInValid) { setTimeout(function () { callback.onError(ErrorCode.BIZ_ERROR_INVALID_PARAMETER); }); } else { this.refreshChatroomEntry(chatroomId, chatroomEntry, opt, callback); } } forceRemoveChatroomEntry(chatroomId: string, chatroomEntry: ChatroomEntry, callback: ResultCallback<any>): void { chatroomEntry.isOverwrite = true; this.removeChatroomEntry(chatroomId, chatroomEntry, callback); } refreshChatroomEntry(chatroomId: string, chatroomEntry: ChatroomEntry, chatroomEntryOpt: ChatroomEntityOpt, callback: ResultCallback<any>): void { var modules: any, topic: string; var key = chatroomEntry.key, value = chatroomEntry.value || '', extra = chatroomEntry.notificationExtra if (chatroomEntryOpt === ChatroomEntityOpt.DELETE) { modules = new RongIMClient.Protobuf.DeleteChrmKV(); topic = 'delKV'; } else { modules = new RongIMClient.Protobuf.SetChrmKV(); topic = 'setKV'; } var status = RongInnerTools.getChrmEntityStatus(chatroomEntry, chatroomEntryOpt); var currentUserId = RongIMClient.getInstance().getCurrentUserId(); var entry: any = { key: key, value: value, uid: currentUserId }; if (status) { entry.status = status; } modules.setEntry(entry); if (chatroomEntry.isSendNotification) { modules.setBNotify(true); var msgModules = new RongIMClient.Protobuf.UpStreamMessage(); var msg = new RongIMLib.ChrmKVNotificationMessage({ key: key, value: value, extra: extra, type: chatroomEntryOpt }); msgModules.setSessionId(RongIMClient.MessageParams[msg.messageName].msgTag.getMessageTag()); msgModules.setClassname(RongIMClient.MessageParams[msg.messageName].objectName); msgModules.setContent(msg.encode()); modules.setNotification(msgModules); // 默认设置为 聊天室消息 modules.setType(RongIMLib.ConversationType.CHATROOM); } RongIMClient.bridge.queryMsg(topic, MessageUtil.ArrayForm(modules.toArrayBuffer()), chatroomId, { onSuccess: function (ret: any) { var currentUserId = RongIMClient.getInstance().getCurrentUserId(); ChrmKVHandler.setEntry(chatroomId, chatroomEntry, status, currentUserId); setTimeout(function () { callback.onSuccess(ret); }); }, onError: function (error: ErrorCode) { setTimeout(function () { callback.onError(error); }); } }, 'ChrmOutput'); } getChatroomEntry(chatroomId: string, key: string, callback: ResultCallback<any>): void { var value = ChrmKVHandler.getEntityValue(chatroomId, key); setTimeout(function () { if (RongUtil.isEmpty(value)) { callback.onError(ErrorCode.CHATROOM_KEY_NOT_EXIST); } else { callback.onSuccess(value); } }); } getAllChatroomEntries(chatroomId: string, callback: ResultCallback<any>): void { setTimeout(function () { var entries = ChrmKVHandler.getAllEntityValue(chatroomId); callback.onSuccess(entries); }); } pullChatroomEntry(chatroomId: string, time: number, callback: ResultCallback<any>) { var modules = new RongIMClient.Protobuf.QueryChrmKV(); modules.setTimestamp(time); RongIMClient.bridge.queryMsg('pullKV', MessageUtil.ArrayForm(modules.toArrayBuffer()), chatroomId, { onSuccess: function (data: any) { setTimeout(function () { callback.onSuccess(data); }); }, onError: function (error: ErrorCode) { setTimeout(function () { callback.onError(error); }); } }, "ChrmKVOutput"); } setMessageStatus(conversationType: ConversationType, targetId: string, timestamp: number, status: string, callback: ResultCallback<Boolean>): void { setTimeout(function () { callback.onSuccess(true); }); } addToBlacklist(userId: string, callback: OperationCallback): void { var modules = new RongIMClient.Protobuf.Add2BlackListInput(); modules.setUserId(userId); RongIMClient.bridge.queryMsg(21, MessageUtil.ArrayForm(modules.toArrayBuffer()), userId, { onSuccess: function () { setTimeout(function () { callback.onSuccess(); }); }, onError: function (error: ErrorCode) { setTimeout(function () { callback.onError(error); }); } }); } getBlacklist(callback: GetBlacklistCallback): void { var modules = new RongIMClient.Protobuf.QueryBlackListInput(); modules.setNothing(1); RongIMClient.bridge.queryMsg(23, MessageUtil.ArrayForm(modules.toArrayBuffer()), Bridge._client.userId, { onSuccess: function (list: any) { setTimeout(function () { callback.onSuccess(list); }); }, onError: function (error: ErrorCode) { setTimeout(function () { callback.onError(error); }); } }, "QueryBlackListOutput"); } getBlacklistStatus(userId: string, callback: ResultCallback<string>): void { var modules = new RongIMClient.Protobuf.BlackListStatusInput(); modules.setUserId(userId); RongIMClient.bridge.queryMsg(24, MessageUtil.ArrayForm(modules.toArrayBuffer()), userId, { onSuccess: function (status: number) { setTimeout(function () { callback.onSuccess(BlacklistStatus[status]); }); }, onError: function (error: ErrorCode) { setTimeout(function () { callback.onError(error); }); } }); } removeFromBlacklist(userId: string, callback: OperationCallback): void { var modules = new RongIMClient.Protobuf.RemoveFromBlackListInput(); modules.setUserId(userId); RongIMClient.bridge.queryMsg(22, MessageUtil.ArrayForm(modules.toArrayBuffer()), userId, { onSuccess: function () { setTimeout(function () { callback.onSuccess(); }); }, onError: function (error: ErrorCode) { setTimeout(function () { callback.onError(error); }); } }); } getFileToken(fileType: FileType, callback: ResultCallback<string>): void { if (!(/(1|2|3|4)/.test(fileType.toString()))) { setTimeout(function () { callback.onError(ErrorCode.QNTKN_FILETYPE_ERROR); }) return; } var modules = new RongIMClient.Protobuf.GetQNupTokenInput(); modules.setType(fileType); RongIMClient.bridge.queryMsg(30, MessageUtil.ArrayForm(modules.toArrayBuffer()), Bridge._client.userId, { onSuccess: function (data: any) { setTimeout(function () { callback.onSuccess(data); }); }, onError: function (errcode: ErrorCode) { setTimeout(function () { callback.onError(errcode); }); } }, "GetQNupTokenOutput"); } getFileUrl(fileType: FileType, fileName: string, oriName: string, callback: ResultCallback<string>): void { if (!(/(1|2|3|4)/.test(fileType.toString()))) { setTimeout(function () { callback.onError(ErrorCode.QNTKN_FILETYPE_ERROR); }); return; } var modules = new RongIMClient.Protobuf.GetQNdownloadUrlInput(); modules.setType(fileType); modules.setKey(fileName); if (oriName) { modules.setFileName(oriName); } RongIMClient.bridge.queryMsg(31, MessageUtil.ArrayForm(modules.toArrayBuffer()), Bridge._client.userId, { onSuccess: function (data: any) { setTimeout(function () { callback.onSuccess(data); }); }, onError: function (errcode: ErrorCode) { setTimeout(function () { callback.onError(errcode); }); } }, "GetQNdownloadUrlOutput"); } getPullSetting(callback: ResultCallback<any>) { var modules = new RongIMClient.Protobuf.PullUserSettingInput(); var version = parseInt(RongIMClient.sdkver); modules.setVersion(version); RongIMClient.bridge.queryMsg('pullUS', MessageUtil.ArrayForm(modules.toArrayBuffer()), Bridge._client.userId, { onSuccess: function (result: any) { result = result || {}; result.version = MessageUtil.int64ToTimestamp(result.version); setTimeout(function () { callback.onSuccess(result); }); }, onError: function (errcode: ErrorCode) { setTimeout(function () { callback.onError(errcode); }); } }, 'PullUserSettingOutput'); } setOfflineMessageDuration(duration: number, callback: ResultCallback<boolean>): void { this.getPullSetting({ onSuccess: function (result:any) { /** * GetQNupTokenOutput 第一位为 int64, 第二位为 string, 与设置离线消息一致 * 为避免修改 Protobuf 带来的更新成本. 仅复用, 不重新命名 */ var modules = new RongIMClient.Protobuf.GetQNupTokenOutput(); var version = result.version; modules.setDeadline(version); modules.setToken(duration + ''); RongIMClient.bridge.queryMsg('setOfflineMsgDur', MessageUtil.ArrayForm(modules.toArrayBuffer()), Bridge._client.userId, { onSuccess: function (data: any) { setTimeout(function () { callback.onSuccess(data); }); }, onError: function (errcode: ErrorCode) { setTimeout(function () { callback.onError(errcode); }); } }); }, onError: callback.onError }); } /* methodType 1 : 多客服(客服后台使用); 2 : 消息撤回 params.userIds : 定向消息接收者 */ sendMessage(conversationType: ConversationType, targetId: string, messageContent: MessageContent, sendCallback: SendMessageCallback, mentiondMsg?: boolean, pushText?: string, appData?: string, methodType?: number, params?: any): void { if (!Bridge._client.channel) { setTimeout(function () { sendCallback.onError(RongIMLib.ErrorCode.RC_NET_UNAVAILABLE, null); }); return; } if (!Bridge._client.channel.socket.socket.connected) { setTimeout(function () { sendCallback.onError(ErrorCode.TIMEOUT, null); }); throw new Error("connect is timeout! postion:sendMessage"); } var isGroup = (conversationType == ConversationType.DISCUSSION || conversationType == ConversationType.GROUP); var modules = new RongIMClient.Protobuf.UpStreamMessage(); if (mentiondMsg && isGroup) { modules.setSessionId(7); } else { modules.setSessionId(RongIMClient.MessageParams[messageContent.messageName].msgTag.getMessageTag()); } pushText && modules.setPushText(pushText); appData && modules.setAppData(appData); if (isGroup && messageContent.messageName == RongIMClient.MessageType["ReadReceiptResponseMessage"]) { var rspMsg: ReadReceiptResponseMessage = <ReadReceiptResponseMessage>messageContent; if (rspMsg.receiptMessageDic) { var ids: string[] = []; for (var key in rspMsg.receiptMessageDic) { ids.push(key); } modules.setUserId(ids); } } if (isGroup && messageContent.messageName == RongIMClient.MessageType["SyncReadStatusMessage"]) { modules.setUserId(Bridge._client.userId); } params = params || {}; var userIds = params.userIds; if (userIds) { modules.setUserId(userIds); } var flag = 0; if (params.isPush || params.isVoipPush){ // 原本为 isPush, 但 isPush 不准确. 为兼容老版, 保留 isVoipPush flag |= 0x01; } if(params.isFilerWhiteBlacklist){ flag |= 0x02; } modules.setConfigFlag(flag); modules.setClassname(RongIMClient.MessageParams[messageContent.messageName].objectName); modules.setContent(messageContent.encode()); var content: any = modules.toArrayBuffer(); if (Object.prototype.toString.call(content) == "[object ArrayBuffer]") { content = [].slice.call(new Int8Array(content)); } var me = this, msg: Message = new RongIMLib.Message(); var c: Conversation = this.getConversation(conversationType, targetId); if (RongIMClient.MessageParams[messageContent.messageName].msgTag.getMessageTag() == 3) { if (!c) { c = RongIMClient.getInstance().createConversation(conversationType, targetId, ""); } c.sentTime = new Date().getTime(); c.sentStatus = SentStatus.SENDING; c.senderUserName = ""; c.senderUserId = Bridge._client.userId; c.notificationStatus = ConversationNotificationStatus.DO_NOT_DISTURB; c.latestMessage = msg; c.unreadMessageCount = 0; RongIMClient._dataAccessProvider.addConversation(c, <ResultCallback<boolean>>{ onSuccess: function (data) { } }); } RongIMClient._memoryStore.converStore = c; msg.content = messageContent; msg.conversationType = conversationType; msg.senderUserId = Bridge._client.userId; msg.objectName = RongIMClient.MessageParams[messageContent.messageName].objectName; msg.targetId = targetId; msg.sentTime = new Date().getTime(); msg.messageDirection = MessageDirection.SEND; msg.sentStatus = SentStatus.SENT; msg.messageType = messageContent.messageName; RongIMClient.bridge.pubMsg(conversationType.valueOf(), content, targetId, { onSuccess: function (data: any) { if (data && data.timestamp) { RongIMClient._memoryStore.lastReadTime.set('converST_' + Bridge._client.userId + conversationType + targetId, data.timestamp); } if ((conversationType == ConversationType.DISCUSSION || conversationType == ConversationType.GROUP) && messageContent.messageName == RongIMClient.MessageType["ReadReceiptRequestMessage"]) { var reqMsg: ReadReceiptRequestMessage = <ReadReceiptRequestMessage>msg.content; var sentkey: string = Bridge._client.userId + reqMsg.messageUId + "SENT"; RongIMClient._storageProvider.setItem(sentkey, JSON.stringify({ count: 0, dealtime: data.timestamp, userIds: {} })); } if (RongIMClient.MessageParams[msg.messageType].msgTag.getMessageTag() == 3) { var cacheConversation = RongIMClient._memoryStore.converStore; cacheConversation.sentStatus = msg.sentStatus; cacheConversation.latestMessage = msg; me.updateConversation(cacheConversation); var Conversation = RongIMClient._dataAccessProvider.Conversation; Conversation._notify(RongIMClient._memoryStore.conversationList); RongIMClient._dataAccessProvider.addMessage(conversationType, targetId, msg, { onSuccess: function (ret: Message) { msg = ret; msg.messageUId = data.messageUId; msg.sentTime = data.timestamp; msg.sentStatus = SentStatus.SENT; msg.messageId = data.messageId; RongIMClient._dataAccessProvider.updateMessage(msg); }, onError: function () { } }); } setTimeout(function () { cacheConversation && me.updateConversation(cacheConversation); msg.sentTime = data.timestamp; msg.messageUId = data.messageUId; sendCallback.onSuccess(msg); }); }, onError: function (errorCode: ErrorCode, _msg: any) { msg.sentStatus = SentStatus.FAILED; if (_msg) { msg.messageUId = _msg.messageUId; msg.sentTime = _msg.sentTime; } if (RongIMClient.MessageParams[msg.messageType].msgTag.getMessageTag() == 3) { RongIMClient._memoryStore.converStore.latestMessage = msg; } RongIMClient._dataAccessProvider.addMessage(conversationType, targetId, msg, { onSuccess: function (ret: Message) { msg.messageId = ret.messageId; RongIMClient._dataAccessProvider.updateMessage(msg); }, onError: function () { } }); setTimeout(function () { sendCallback.onError(errorCode, msg); }); } }, null, methodType); sendCallback.onBefore && sendCallback.onBefore(RongIMLib.MessageIdHandler.messageId); msg.messageId = RongIMLib.MessageIdHandler.messageId + ""; } setConnectionStatusListener(listener: ConnectionStatusListener): void { if (RongUtil.isObject(listener) && RongUtil.isFunction(listener.onChanged)) { RongIMClient.statusListeners.push(listener.onChanged); } } setOnReceiveMessageListener(listener: OnReceiveMessageListener): void { if (RongUtil.isObject(listener) && RongUtil.isFunction(listener.onReceived)) { RongIMClient.messageListeners.push(listener.onReceived); } } registerMessageType(messageType: string, objectName: string, messageTag: MessageTag, messageContent: any, searchProps: string[]): void { if (!messageType) { throw new Error("messageType can't be empty,postion -> registerMessageType"); } if (!objectName) { throw new Error("objectName can't be empty,postion -> registerMessageType"); } if (Object.prototype.toString.call(messageContent) == "[object Array]") { var regMsg = RongIMLib.ModelUtil.modleCreate(messageContent, messageType); RongIMClient.RegisterMessage[messageType] = regMsg; } else if (Object.prototype.toString.call(messageContent) == "[object Function]" || Object.prototype.toString.call(messageContent) == "[object Object]") { if (!messageContent.encode) { throw new Error("encode method has not realized or messageName is undefined-> registerMessageType"); } if (!messageContent.decode) { throw new Error("decode method has not realized -> registerMessageType"); } } else { throw new Error("The index of 3 parameter was wrong type must be object or function or array-> registerMessageType"); } registerMessageTypeMapping[objectName] = messageType; } registerMessageTypes(messages: any): void { var types: any = []; var getProtos = function (proto: any) { var protos: any = []; for (var p in proto) { protos.push(p); } return protos; }; //转换消息为自定义消息参数格式 for (var name in messages) { var message = messages[name]; var proto = message.proto; var protos = getProtos(proto); var flag = message.flag || 3; var tag = MessageTag.getTagByStatus(flag); flag = new RongIMLib.MessageTag(tag.isCounted, tag.isPersited); types.push({ type: name, name: message.name, flag: flag, protos: protos }); } var register = function (message: any) { var type = message.type; var name = message.name; var flag = message.flag; var protos = message.protos; RongIMClient.registerMessageType(type, name, flag, protos); }; for (var i = 0, len = types.length; i < len; i++) { var message: any = types[i]; register(message); } } addConversation(conversation: Conversation, callback: ResultCallback<boolean>) { var isAdd: boolean = true; for (let i = 0, len = RongIMClient._memoryStore.conversationList.length; i < len; i++) { if (RongIMClient._memoryStore.conversationList[i].conversationType === conversation.conversationType && RongIMClient._memoryStore.conversationList[i].targetId === conversation.targetId) { // RongIMClient._memoryStore.conversationList[i] = conversation; RongIMClient._memoryStore.conversationList.unshift(RongIMClient._memoryStore.conversationList.splice(i, 1)[0]); isAdd = false; break; } } if (isAdd) { RongIMClient._memoryStore.conversationList.unshift(conversation); } callback && callback.onSuccess(true); } updateConversation(conversation: Conversation): Conversation { var conver: Conversation; for (let i = 0, len = RongIMClient._memoryStore.conversationList.length; i < len; i++) { var item = RongIMClient._memoryStore.conversationList[i]; if (conversation.conversationType === item.conversationType && conversation.targetId === item.targetId) { conversation.conversationTitle && (item.conversationTitle = conversation.conversationTitle); conversation.senderUserName && (item.senderUserName = conversation.senderUserName); conversation.senderPortraitUri && (item.senderPortraitUri = conversation.senderPortraitUri); conversation.latestMessage && (item.latestMessage = conversation.latestMessage); conversation.sentStatus && (item.sentStatus = conversation.sentStatus); break; } } return conver; } removeConversation(conversationType: ConversationType, targetId: string, callback: ResultCallback<boolean>) { var mod = new RongIMClient.Protobuf.RelationsInput(); mod.setType(conversationType); RongIMClient.bridge.queryMsg(27, MessageUtil.ArrayForm(mod.toArrayBuffer()), targetId, { onSuccess: function () { var isRemoved = false; var conversations = RongIMClient._memoryStore.conversationList var len = conversations.length; for (var i = 0; i < len; i++) { if (conversations[i].conversationType == conversationType && targetId == conversations[i].targetId) { conversations.splice(i, 1); isRemoved = true; break; } } isRemoved && RongIMClient._dataAccessProvider.Conversation._notify(RongIMClient._memoryStore.conversationList); callback.onSuccess(true); }, onError: function (error: ErrorCode) { setTimeout(function () { callback.onError(error); }); } }); } getMessage(messageId: string, callback: ResultCallback<Message>) { callback.onSuccess(new Message()); } addMessage(conversationType: ConversationType, targetId: string, message: Message, callback?: ResultCallback<Message>) { if (callback) { callback.onSuccess(message); } } removeMessage(conversationType: ConversationType, targetId: string, messages: Array<Message>, callback: ResultCallback<boolean>) { RongIMClient.getInstance().deleteRemoteMessages(conversationType, targetId, messages, callback); } removeLocalMessage(conversationType: ConversationType, targetId: string, timestamps: number[], callback: ResultCallback<boolean>) { callback.onSuccess(true); } updateMessage(message: Message, callback?: ResultCallback<Message>) { if (callback) { callback.onSuccess(message); } } deleteRemoteMessages(conversationType: ConversationType, targetId: string, messages: Array<Message>, callback: ResultCallback<boolean>) { if (!RongIMClient.Protobuf.DeleteMsgInput) { throw new Error('SDK Protobuf version is too low'); } var modules = new RongIMClient.Protobuf.DeleteMsgInput(); var msgs: Array<DeleteMessage> = []; RongUtil.forEach(messages, function (msg:Message) { msgs.push({ msgId: msg.messageUId, msgDataTime: msg.sentTime, direct: msg.messageDirection }); }); modules.setType(conversationType); modules.setConversationId(targetId); modules.setMsgs(msgs); RongIMClient.bridge.queryMsg('delMsg', MessageUtil.ArrayForm(modules.toArrayBuffer()), targetId, { onSuccess: function (result:any) { callback.onSuccess(result); }, onError: function (error: ErrorCode) { setTimeout(function () { callback.onError(error); }); } }, 'DeleteMsgOutput'); } clearRemoteHistoryMessages(params: any, callback: ResultCallback<boolean>) { var modules = new RongIMClient.Protobuf.CleanHisMsgInput(); var conversationType = params.conversationType; var _topic: { [s: string]: any } = { 1: 'cleanPMsg', 2: 'cleanDMsg', 3: 'cleanGMsg', 5: 'cleanCMsg', 6: 'cleanSMsg' }; var topic = _topic[conversationType]; if (!topic) { callback.onError(ErrorCode.CLEAR_HIS_TYPE_ERROR); return; } var timestamp = params.timestamp; if (typeof timestamp != 'number') { callback.onError(ErrorCode.CLEAR_HIS_TIME_ERROR); return; } modules.setDataTime(timestamp); var targetId = params.targetId; modules.setTargetId(targetId); RongIMClient.bridge.queryMsg(topic, MessageUtil.ArrayForm(modules.toArrayBuffer()), targetId, { onSuccess: function (result: any) { callback.onSuccess(!result); }, onError: function (error: ErrorCode) { // error 1 历史消息云存储没有开通、传入时间大于服务器时间 清除失败,1 与其他错误码冲突,所以自定义错误码返回 if (error == 1) { error = ErrorCode.CLEAR_HIS_ERROR; } setTimeout(function () { callback.onError(error); }); } }); } clearHistoryMessages(params: any, callback: ResultCallback<boolean>): void { this.clearRemoteHistoryMessages(params, callback); } // 兼容老版本 clearMessages(conversationType: ConversationType, targetId: string, callback: ResultCallback<boolean>): void { } updateMessages(conversationType: ConversationType, targetId: string, key: string, value: any, callback: ResultCallback<boolean>) { var me = this; if (key == "readStatus") { if (RongIMClient._memoryStore.conversationList.length > 0) { me.getConversationList(<ResultCallback<Conversation[]>>{ onSuccess: function (list: Conversation[]) { Array.forEach(list, function (conver: Conversation) { if (conver.conversationType == conversationType && conver.targetId == targetId) { conver.unreadMessageCount = 0; } }); }, onError: function (errorCode: ErrorCode) { setTimeout(function () { callback.onError(errorCode); }); } }, null); } } setTimeout(function () { callback.onSuccess(true); }); } getConversation(conversationType: ConversationType, targetId: string, callback?: ResultCallback<Conversation>): Conversation { var conver: Conversation = null; for (let i = 0, len = RongIMClient._memoryStore.conversationList.length; i < len; i++) { if (RongIMClient._memoryStore.conversationList[i].conversationType == conversationType && RongIMClient._memoryStore.conversationList[i].targetId == targetId) { conver = RongIMClient._memoryStore.conversationList[i]; if (RongUtil.supportLocalStorage()) { // var count = RongIMClient._storageProvider.getItem("cu" + Bridge._client.userId + conversationType + targetId); var count = UnreadCountHandler.get(conversationType, targetId); if (conver.unreadMessageCount == 0) { conver.unreadMessageCount = Number(count); } } } } setTimeout(function () { callback && callback.onSuccess(conver); }); return conver; } filterConversations(types: ConversationType[], list: Conversation[]): Conversation[] { var conversaions: Conversation[] = []; RongUtil.forEach(types, function (type: number) { RongUtil.forEach(list, function (conversation: Conversation) { if (conversation.conversationType == type) { conversaions.push(conversation); } }); }); return conversaions; } getConversationList(callback: ResultCallback<Conversation[]>, conversationTypes?: ConversationType[], count?: number, isHidden?: boolean) { var that = this; var isSync = RongIMClient._memoryStore.isSyncRemoteConverList; var list = RongIMClient._memoryStore.conversationList; var isLocalInclude = list.length > count; if (!isSync && isLocalInclude) { setTimeout(function () { var localList = list.slice(0, count); if (conversationTypes) { localList = that.filterConversations(conversationTypes, localList); } callback.onSuccess(localList); }); return; } RongIMClient.getInstance().getRemoteConversationList(<ResultCallback<Conversation[]>>{ onSuccess: function (list: Conversation[]) { if (RongUtil.supportLocalStorage()) { Array.forEach(RongIMClient._memoryStore.conversationList, function (item: Conversation) { // var count = RongIMClient._storageProvider.getItem("cu" + Bridge._client.userId + item.conversationType + item.targetId); var count = UnreadCountHandler.get(item.conversationType, item.targetId); if (item.unreadMessageCount == 0) { item.unreadMessageCount = Number(count); } }); } RongIMClient._memoryStore.isSyncRemoteConverList = false; setTimeout(function () { callback.onSuccess(list); }); }, onError: function (errorcode: ErrorCode) { setTimeout(function () { callback.onError(errorcode); }); } }, conversationTypes, count, isHidden); } clearCache() { var memoryStore = RongIMClient._memoryStore || {}; memoryStore.conversationList = []; memoryStore.isSyncRemoteConverList = true; } clearConversations(conversationTypes: ConversationType[], callback: ResultCallback<boolean>) { Array.forEach(conversationTypes, function (conversationType: ConversationType) { Array.forEach(RongIMClient._memoryStore.conversationList, function (conver: Conversation) { if (conversationType == conver.conversationType) { RongIMClient.getInstance().removeConversation(conver.conversationType, conver.targetId, { onSuccess: function () { }, onError: function () { } }); } }); }); setTimeout(function () { callback.onSuccess(true); }); } setMessageContent(messageId: number, content: any, objectname: string): void { }; setMessageSearchField(messageId: number, content: any, searchFiles: string): void { }; getHistoryMessages(conversationType: ConversationType, targetId: string, timestamp: number, count: number, callback: GetHistoryMessagesCallback, objectname?: string, order?: boolean) { var config = { objectname: objectname, order: order }; RongIMClient.getInstance().getRemoteHistoryMessages(conversationType, targetId, timestamp, count, callback, config); } getTotalUnreadCount(callback: ResultCallback<number>, conversationTypes?: number[]) { var count = UnreadCountHandler.getAll(conversationTypes); callback.onSuccess(count); } getConversationUnreadCount(conversationTypes: ConversationType[], callback: ResultCallback<number>) { var count: number = 0; Array.forEach(conversationTypes, function (converType: number) { Array.forEach(RongIMClient._memoryStore.conversationList, function (conver: Conversation) { if (conver.conversationType == converType) { count += conver.unreadMessageCount; } }); }); setTimeout(function () { callback.onSuccess(count); }); } //由于 Web 端未读消息数按会话统计,撤回消息会导致未读数不准确,提供设置未读数接口,桌面版不实现此方法 setUnreadCount(conversationType: ConversationType, targetId: string, count: number, sentTime?: number) { sentTime = sentTime || new Date().getTime(); UnreadCountHandler.set(conversationType, targetId, count, sentTime); } getUnreadCount(conversationType: ConversationType, targetId: string, callback: ResultCallback<number>) { var unreadCount = UnreadCountHandler.get(conversationType, targetId); setTimeout(function () { callback.onSuccess(unreadCount || 0); }); } cleanMentioneds(conver: Conversation) { if (conver) { conver.mentionedMsg = null; var targetId = conver.targetId; var conversationType = conver.conversationType; var mentioneds = RongIMClient._storageProvider.getItem("mentioneds_" + Bridge._client.userId + '_' + conversationType + '_' + targetId); if (mentioneds) { var info: any = JSON.parse(mentioneds); delete info[conversationType + "_" + targetId]; if (!MessageUtil.isEmpty(info)) { RongIMClient._storageProvider.setItem("mentioneds_" + Bridge._client.userId + '_' + conversationType + '_' + targetId, JSON.stringify(info)); } else { RongIMClient._storageProvider.removeItem("mentioneds_" + Bridge._client.userId + '_' + conversationType + '_' + targetId); } } } } clearUnreadCountByTimestamp(conversationType: ConversationType, targetId: string, timestamp: number, callback: ResultCallback<boolean>): void { setTimeout(function () { callback.onSuccess(true); }); } clearUnreadCount(conversationType: ConversationType, targetId: string, callback: ResultCallback<boolean>) { var me = this; // RongIMClient._storageProvider.removeItem("cu" + Bridge._client.userId + conversationType + targetId); UnreadCountHandler.remove(conversationType, targetId); this.getConversation(conversationType, targetId, { onSuccess: function (conver: Conversation) { conver = conver || new Conversation(); let isNotifyConversation = conver.unreadMessageCount; if (conver) { conver.unreadMessageCount = 0; me.cleanMentioneds(conver); } setTimeout(function () { callback.onSuccess(true); isNotifyConversation && RongIMClient._dataAccessProvider.Conversation._notify(RongIMClient._memoryStore.conversationList); }); }, onError: function (error: ErrorCode) { setTimeout(function () { callback.onError(error); }); } }); } clearTotalUnreadCount(callback: ResultCallback<boolean>) { var list = RongIMClient._memoryStore.conversationList; var me = this; var isNotifyConversation = false; if (list) { // 清除 mentioneds、清除 list 中的 unreadMessageCount for (var i = 0; i < list.length; i++) { var conver = list[i]; if (conver) { isNotifyConversation = conver.unreadMessageCount ? true : isNotifyConversation; conver.unreadMessageCount = 0; me.cleanMentioneds(conver); } } } UnreadCountHandler.clear(); setTimeout(() => { callback.onSuccess(true); isNotifyConversation && RongIMClient._dataAccessProvider.Conversation._notify(RongIMClient._memoryStore.conversationList); }); } setConversationToTop(conversationType: ConversationType, targetId: string, isTop: boolean, callback: ResultCallback<boolean>) { var me = this; this.getConversation(conversationType, targetId, { onSuccess: function (conver: Conversation) { conver.isTop = isTop; me.addConversation(conver, callback); setTimeout(function () { callback.onSuccess(true); }); }, onError: function (error: ErrorCode) { setTimeout(function () { callback.onError(error); }); } }); } getConversationNotificationStatus(params: any, callback: any): void { var targetId = params.targetId; var conversationType = params.conversationType; var notification = RongIMClient._memoryStore.notification; var getKey = function () { return conversationType + '_' + targetId; }; var key = getKey(); var status = notification[key]; if (typeof status == 'number') { callback.onSuccess(status); return; } var topics: any = { 1: 'qryPPush', 3: 'qryDPush' }; var topic = topics[conversationType]; if (!topic) { var error = 8001; callback.onError(error); return; } var modules = new RongIMClient.Protobuf.BlockPushInput(); modules.setBlockeeId(targetId); var userId = RongIMLib.Bridge._client.userId; var success = function (status: any) { notification[key] = status; setTimeout(function () { callback.onSuccess(status); }); }; RongIMLib.RongIMClient.bridge.queryMsg(topic, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), userId, { onSuccess: function (status: any) { success(status); }, onError: function (e: any) { if (e == 1) { success(e); } else { setTimeout(function () { callback.onError(e); }); } } }); } setConversationNotificationStatus(params: any, callback: any): void { var conversationType = params.conversationType; var targetId = params.targetId; var status = params.status; var getKey = function () { return conversationType + '_' + status; }; var topics: any = { '1_1': 'blkPPush', '3_1': 'blkDPush', '1_0': 'unblkPPush', '3_0': 'unblkDPush' }; var key = getKey(); var notification = RongIMClient._memoryStore.notification; notification[key] = status; var topic = topics[key]; if (!topic) { var error = 8001; setTimeout(function () { callback.onError(error); }); return; } var modules = new RongIMClient.Protobuf.BlockPushInput(); modules.setBlockeeId(targetId); var userId = RongIMLib.Bridge._client.userId; RongIMLib.RongIMClient.bridge.queryMsg(topic, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), userId, { onSuccess: function (status: any) { setTimeout(function () { callback.onSuccess(status); }); }, onError: function (e: any) { setTimeout(function () { callback.onError(e); }); } }); } getUserStatus(userId: string, callback: ResultCallback<UserStatus>): void { var modules = new RongIMClient.Protobuf.GetUserStatusInput(); userId = RongIMLib.Bridge._client.userId; RongIMLib.RongIMClient.bridge.queryMsg(35, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), userId, { onSuccess: function (status: any) { status = RongInnerTools.convertUserStatus(status); setTimeout(function () { callback.onSuccess(status); }); }, onError: function (e: any) { setTimeout(function () { callback.onError(e); }); } }, 'GetUserStatusOutput'); // callback.onSuccess(new UserStatus()); } setUserStatus(status: number, callback: ResultCallback<boolean>): void { var modules = new RongIMClient.Protobuf.SetUserStatusInput(); var userId: string = RongIMLib.Bridge._client.userId; if (status) { modules.setStatus(status); } RongIMLib.RongIMClient.bridge.queryMsg(36, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), userId, { onSuccess: function (status: any) { setTimeout(function () { callback.onSuccess(true); }); }, onError: function (e: any) { setTimeout(function () { callback.onError(e); }); } }, 'SetUserStatusOutput'); } subscribeUserStatus(userIds: string[], callback?: ResultCallback<boolean>): void { var modules = new RongIMClient.Protobuf.SubUserStatusInput(); var userId = RongIMLib.Bridge._client.userId; modules.setUserid(userIds); RongIMLib.RongIMClient.bridge.queryMsg(37, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), userId, { onSuccess: function (status: any) { setTimeout(function () { callback && callback.onSuccess(true); }); }, onError: function (e: any) { setTimeout(function () { callback && callback.onError(e); }); } }, 'SubUserStatusOutput'); } setUserStatusListener(params: any, callback?: Function): void { RongIMClient.userStatusListener = callback; var userIds = params.userIds || []; if (userIds.length) { RongIMClient._dataAccessProvider.subscribeUserStatus(userIds); } } clearListeners(): void { } setServerInfo(info: any): void { } getUnreadMentionedMessages(conversationType: ConversationType, targetId: string): any { return null; } setConversationHidden(conversationType: ConversationType, targetId: string, isHidden: boolean): void { } setMessageExtra(messageId: string, value: string, callback: ResultCallback<boolean>) { setTimeout(function () { callback.onSuccess(true); }); } setMessageReceivedStatus(messageId: string, receivedStatus: ReceivedStatus, callback: ResultCallback<boolean>) { setTimeout(function () { callback.onSuccess(true); }); } setMessageSentStatus(messageId: string, sentStatus: SentStatus, callback: ResultCallback<boolean>) { setTimeout(function () { callback.onSuccess(true); }); } getAllConversations(callback: ResultCallback<Conversation[]>): void { setTimeout(function () { callback.onSuccess([]); }); } getConversationByContent(keywords: string, callback: ResultCallback<Conversation[]>): void { setTimeout(function () { callback.onSuccess([]); }); } getMessagesFromConversation(conversationType: ConversationType, targetId: string, keywords: string, callback: ResultCallback<Message[]>): void { setTimeout(function () { callback.onSuccess([]); }); } searchConversationByContent(keyword: string, callback: ResultCallback<Conversation[]>, conversationTypes?: ConversationType[]): void { setTimeout(function () { callback.onSuccess([]); }); } searchMessageByContent(conversationType: ConversationType, targetId: string, keyword: string, timestamp: number, count: number, total: number, callback: ResultCallback<Message[]>): void { setTimeout(function () { callback.onSuccess([]); }); } getDelaTime(): number { return RongIMClient._memoryStore.deltaTime; } getCurrentConnectionStatus(): number { var client: any = RongIMLib.Bridge._client || {}; var channel = client.channel || {}; var status = RongIMLib.ConnectionStatus.CONNECTION_CLOSED; if (typeof channel.connectionStatus == 'number') { status = channel.connectionStatus; } return status; } getAgoraDynamicKey(engineType: number, channelName: string, callback: ResultCallback<string>) { var modules = new RongIMClient.Protobuf.VoipDynamicInput(); modules.setEngineType(engineType); modules.setChannelName(channelName); RongIMClient.bridge.queryMsg(32, MessageUtil.ArrayForm(modules.toArrayBuffer()), Bridge._client.userId, { onSuccess: function (result: any) { setTimeout(function () { callback.onSuccess(result); }); }, onError: function (errorCode: ErrorCode) { setTimeout(function () { callback.onError(errorCode); }); } }, "VoipDynamicOutput"); } setDeviceInfo(deviceId: string): void { } setEnvironment(isPrivate: boolean): void { } clearData(): boolean { return true; } getPublicServiceProfile(publicServiceType: ConversationType, publicServiceId: string, callback: ResultCallback<PublicServiceProfile>) { var profile: PublicServiceProfile = RongIMClient._memoryStore.publicServiceMap.get(publicServiceType, publicServiceId); setTimeout(function () { callback.onSuccess(profile); }); } getRemotePublicServiceList(callback?: ResultCallback<PublicServiceProfile[]>, pullMessageTime?: any) { if (RongIMClient._memoryStore.depend.openMp) { var modules = new RongIMClient.Protobuf.PullMpInput(), self = this; if (!pullMessageTime) { modules.setTime(0); } else { modules.setTime(pullMessageTime); } modules.setMpid(""); RongIMClient.bridge.queryMsg(28, MessageUtil.ArrayForm(modules.toArrayBuffer()), Bridge._client.userId, { onSuccess: function (data: Array<PublicServiceProfile>) { //TODO 找出最大时间 // self.lastReadTime.set(conversationType + targetId, MessageUtil.int64ToTimestamp(data.syncTime)); RongIMClient._memoryStore.publicServiceMap.publicServiceList.length = 0; RongIMClient._memoryStore.publicServiceMap.publicServiceList = data; setTimeout(function () { callback && callback.onSuccess(data); }); }, onError: function (errorCode: ErrorCode) { setTimeout(function () { callback && callback.onError(errorCode); }); } }, "PullMpOutput"); } } getRTCUserInfoList(room: Room, callback: ResultCallback<any>) { var modules = new RongIMClient.Protobuf.RtcQueryListInput(); // 1 是正序,2是倒序 modules.setOrder(2); RongIMClient.bridge.queryMsg("rtcUData", MessageUtil.ArrayForm(modules.toArrayBuffer()), room.id, { onSuccess: function (result: any) { var users: { [s: string]: any } = {}; var list = result.list; RongUtil.forEach(list, function (item: any) { var userId = item.userId; var tmpData: { [s: string]: any } = {}; RongUtil.forEach(item.userData, function (data: any) { var key = data.key; var value = data.value; tmpData[key] = value; }); users[userId] = tmpData; }); callback.onSuccess(users); }, onError: function (errorCode: ErrorCode) { callback.onError(errorCode); } }, "RtcUserListOutput"); } getRTCUserList(room: Room, callback: ResultCallback<any>) { var modules = new RongIMClient.Protobuf.RtcQueryListInput(); modules.setOrder(2); RongIMClient.bridge.queryMsg("rtcUList", MessageUtil.ArrayForm(modules.toArrayBuffer()), room.id, { onSuccess: function (result: any) { callback.onSuccess({ users: result.list }); }, onError: function (errorCode: ErrorCode) { callback.onError(errorCode); } }, "RtcUserListOutput"); } setRTCUserInfo(room: Room, info: any, callback: ResultCallback<boolean>) { var modules = new RongIMClient.Protobuf.RtcValueInfo(); modules.setKey(info.key); modules.setValue(info.value); RongIMClient.bridge.queryMsg("rtcUPut", MessageUtil.ArrayForm(modules.toArrayBuffer()), room.id, { onSuccess: function () { callback.onSuccess(true); }, onError: function (errorCode: ErrorCode) { callback.onError(errorCode); } }); } removeRTCUserInfo(room: Room, info: any, callback: ResultCallback<boolean>) { var modules = new RongIMClient.Protobuf.RtcKeyDeleteInput(); var keys = info.keys || []; if (!RongUtil.isArray(keys)) { keys = [keys]; } modules.setKey(keys); RongIMClient.bridge.queryMsg("rtcUDel", MessageUtil.ArrayForm(modules.toArrayBuffer()), room.id, { onSuccess: function () { callback.onSuccess(true); }, onError: function (errorCode: ErrorCode) { callback.onError(errorCode); } }); } getRTCRoomInfo(room: Room, callback: ResultCallback<any>) { var modules = new RongIMClient.Protobuf.RtcQueryListInput(); modules.setOrder(2); RongIMClient.bridge.queryMsg("rtcRInfo", MessageUtil.ArrayForm(modules.toArrayBuffer()), room.id, { onSuccess: function (result: any) { var room: { [s: string]: any } = { id: result.roomId, total: result.userCount }; RongUtil.forEach(result.roomData, function (data: any) { room[data.key] = data.value; }); callback.onSuccess(room); }, onError: function (errorCode: ErrorCode) { callback.onError(errorCode); } }, "RtcRoomInfoOutput"); } setRTCRoomInfo(room: Room, info: any, callback: ResultCallback<boolean>) { var modules = new RongIMClient.Protobuf.RtcValueInfo(); modules.setKey(info.key); modules.setValue(info.value); RongIMClient.bridge.queryMsg("rtcRPut", MessageUtil.ArrayForm(modules.toArrayBuffer()), room.id, { onSuccess: function () { callback.onSuccess(true); }, onError: function (errorCode: ErrorCode) { callback.onError(errorCode); } }); } removeRTCRoomInfo(room: Room, info: any, callback: ResultCallback<boolean>) { var modules = new RongIMClient.Protobuf.RtcKeyDeleteInput(); var keys = info.keys || []; if (!RongUtil.isArray(keys)) { keys = [keys]; } modules.setKey(keys); RongIMClient.bridge.queryMsg("rtcRDel", MessageUtil.ArrayForm(modules.toArrayBuffer()), room.id, { onSuccess: function () { callback.onSuccess(true); }, onError: function (errorCode: ErrorCode) { callback.onError(errorCode); } }); } joinRTCRoom(room: Room, callback: ResultCallback<any>) { var modules = new RongIMClient.Protobuf.RtcInput(); var mode = room.mode || 0; modules.setRoomType(mode); if (room.broadcastType) { modules.setBroadcastType(room.broadcastType); } RongIMClient.bridge.queryMsg("rtcRJoin_data", MessageUtil.ArrayForm(modules.toArrayBuffer()), room.id, { onSuccess: function (result: any) { var users: { [s: string]: any } = {}; var list = result.list, token = result.token, sessionId = result.sessionId; RongUtil.forEach(list, function (item: any) { var userId = item.userId; var tmpData: { [s: string]: any } = {}; RongUtil.forEach(item.userData, function (data: any) { var key = data.key; var value = data.value; tmpData[key] = value; }); users[userId] = tmpData; }); callback.onSuccess({ users: users, token: token, sessionId: sessionId }); }, onError: function (errorCode: ErrorCode) { callback.onError(errorCode); } }, "RtcUserListOutput"); } quitRTCRoom(room: Room, callback: ResultCallback<boolean>) { var modules = new RongIMClient.Protobuf.SetUserStatusInput(); RongIMClient.bridge.queryMsg("rtcRExit", MessageUtil.ArrayForm(modules.toArrayBuffer()), room.id, { onSuccess: function () { callback.onSuccess(true); }, onError: function (errorCode: ErrorCode) { callback.onError(errorCode); } }); } RTCPing(room: Room, callback: ResultCallback<boolean>) { var modules = new RongIMClient.Protobuf.RtcInput(); var mode = room.mode || 0; modules.setRoomType(mode); if (room.broadcastType) { modules.setBroadcastType(room.broadcastType); } RongIMClient.bridge.queryMsg("rtcPing", MessageUtil.ArrayForm(modules.toArrayBuffer()), room.id, callback); } setRTCData(roomId: string, key: string, value: string, isInner: boolean, apiType: RTCAPIType, callback: ResultCallback<boolean>, message?: any) { var modules = new RongIMClient.Protobuf.RtcSetDataInput(); modules.setInterior(isInner); modules.setTarget(apiType); modules.setKey(key); modules.setValue(value); message = message || {}; var name = message.name; var content = message.content; if (name) { modules.setObjectName(name); } if (content) { if (!RongUtil.isString(content)) { content = JSON.stringify(content); } modules.setContent(content); } RongIMClient.bridge.queryMsg("rtcSetData", MessageUtil.ArrayForm(modules.toArrayBuffer()), roomId, callback, "RtcOutput"); } getRTCData(roomId: string, keys: string[], isInner: boolean, apiType: RTCAPIType, callback: ResultCallback<any>) { var modules = new RongIMClient.Protobuf.RtcDataInput(); modules.setInterior(isInner); modules.setTarget(apiType); modules.setKey(keys); RongIMClient.bridge.queryMsg("rtcQryData", MessageUtil.ArrayForm(modules.toArrayBuffer()), roomId, { onSuccess: function (result: any) { var props: { [s: string]: any } = {}; var list = result.outInfo; RongUtil.forEach(list, function (item: any) { props[item.key] = item.value; }); callback.onSuccess(props); }, onError: callback.onError }, "RtcQryOutput"); } removeRTCData(roomId: string, keys: string[], isInner: boolean, apiType: RTCAPIType, callback: ResultCallback<boolean>, message?: any) { var modules = new RongIMClient.Protobuf.RtcDataInput(); modules.setInterior(isInner); modules.setTarget(apiType); modules.setKey(keys); message = message || {}; var name = message.name; var content = message.content; if (name) { modules.setObjectName(name); } if (content) { if (!RongUtil.isString(content)) { content = JSON.stringify(content); } modules.setContent(content); } RongIMClient.bridge.queryMsg("rtcDelData", MessageUtil.ArrayForm(modules.toArrayBuffer()), roomId, callback, "RtcOutput"); } setRTCUserData(roomId: string, key: string, value: string, isInner: boolean, callback: ResultCallback<boolean>, message?: any) { this.setRTCData(roomId, key, value, isInner, RTCAPIType.PERSON, callback, message); } getRTCUserData(roomId: string, keys: string[], isInner: boolean, callback: ResultCallback<any>, message?: any) { this.getRTCData(roomId, keys, isInner, RTCAPIType.PERSON, callback); } removeRTCUserData(roomId: string, keys: string[], isInner: boolean, callback: ResultCallback<boolean>, message?: any) { this.removeRTCData(roomId, keys, isInner, RTCAPIType.PERSON, callback, message); } setRTCRoomData(roomId: string, key: string, value: string, isInner: boolean, callback: ResultCallback<boolean>, message?: any) { this.setRTCData(roomId, key, value, isInner, RTCAPIType.ROOM, callback, message); } getRTCRoomData(roomId: string, keys: string[], isInner: boolean, callback: ResultCallback<any>, message?: any) { this.getRTCData(roomId, keys, isInner, RTCAPIType.ROOM, callback); } removeRTCRoomData(roomId: string, keys: string[], isInner: boolean, callback: ResultCallback<boolean>, message?: any) { this.removeRTCData(roomId, keys, isInner, RTCAPIType.ROOM, callback, message); } // 信令 SDK 新增 setRTCOutData(roomId: string, data: any, type: number, callback: ResultCallback<boolean>, message?: any) { var modules = new RongIMClient.Protobuf.RtcSetOutDataInput(); modules.setTarget(type); if (!RongUtil.isArray(data)) { data = [data]; } for (var i = 0; i < data.length; i++) { var item = data[i]; if(item.key){ item.key = item.key.toString(); } if(item.value){ item.value = item.value.toString(); } } modules.setValueInfo(data); message = message || {}; var name = message.name; var content = message.content; if (name) { modules.setObjectName(name); } if (content) { if (!RongUtil.isString(content)) { content = JSON.stringify(content); } modules.setContent(content); } RongIMClient.bridge.queryMsg("rtcSetOutData", MessageUtil.ArrayForm(modules.toArrayBuffer()), roomId, callback, "RtcOutput"); } // 信令 SDK 新增 getRTCOutData(roomId: string, userIds: string[], callback: ResultCallback<any>) { var modules = new RongIMClient.Protobuf.RtcQryUserOutDataInput(); modules.setUserId(userIds); RongIMClient.bridge.queryMsg("rtcQryUserOutData", MessageUtil.ArrayForm(modules.toArrayBuffer()), roomId, callback, "RtcUserOutDataOutput"); } getNavi() { var navi = RongIMClient._storageProvider.getItem("fullnavi") || "{}"; return JSON.parse(navi); } getRTCToken(room: any, callback: ResultCallback<any>) { var modules = new RongIMClient.Protobuf.RtcInput(); var mode = room.mode || 0; modules.setRoomType(mode); if (room.broadcastType) { modules.setBroadcastType(room.broadcastType); } RongIMClient.bridge.queryMsg("rtcToken", MessageUtil.ArrayForm(modules.toArrayBuffer()), room.id, { onSuccess: function (result: any) { callback.onSuccess(result); }, onError: function (errorCode: ErrorCode) { callback.onError(errorCode); } }, "RtcTokenOutput"); } setRTCState(room: any, content: any, callback: ResultCallback<any>) { // MCFollowInput 为 PB 复用,字段:一个必传 string(第一位) var modules = new RongIMClient.Protobuf.MCFollowInput(); var report = content.report; modules.setId(report); RongIMClient.bridge.queryMsg("rtcUserState", MessageUtil.ArrayForm(modules.toArrayBuffer()), room.id, { onSuccess: function (result: any) { callback.onSuccess(result); }, onError: function (errorCode: ErrorCode) { callback.onError(errorCode); } }, "RtcOutput"); } } }
the_stack
import fs from 'fs' import path from 'path' import execa from 'execa' import globby from 'globby' import cheerio from 'cheerio' import { install } from '../lib/install' import runJscodeshift from '../lib/run-jscodeshift' import htmlToReactAttributes from '../lib/html-to-react-attributes' import { indexContext } from '../lib/cra-to-next/index-to-component' import { globalCssContext } from '../lib/cra-to-next/global-css-transform' const feedbackMessage = `Please share any feedback on the migration here: https://github.com/vercel/next.js/discussions/25858` // log error and exit without new stacktrace function fatalMessage(...logs) { console.error(...logs, `\n${feedbackMessage}`) process.exit(1) } const craTransformsPath = path.join('../lib/cra-to-next') const globalCssTransformPath = require.resolve( path.join(craTransformsPath, 'global-css-transform.js') ) const indexTransformPath = require.resolve( path.join(craTransformsPath, 'index-to-component.js') ) class CraTransform { private appDir: string private pagesDir: string private isVite: boolean private isCra: boolean private isDryRun: boolean private indexPage: string private installClient: string private shouldLogInfo: boolean private packageJsonPath: string private shouldUseTypeScript: boolean private packageJsonData: { [key: string]: any } private jscodeShiftFlags: { [key: string]: boolean } constructor(files: string[], flags: { [key: string]: boolean }) { this.isDryRun = flags.dry this.jscodeShiftFlags = flags this.appDir = this.validateAppDir(files) this.packageJsonPath = path.join(this.appDir, 'package.json') this.packageJsonData = this.loadPackageJson() this.shouldLogInfo = flags.print || flags.dry this.pagesDir = this.getPagesDir() this.installClient = this.checkForYarn() ? 'yarn' : 'npm' const { dependencies, devDependencies } = this.packageJsonData const hasDep = (dep) => dependencies?.[dep] || devDependencies?.[dep] this.isCra = hasDep('react-scripts') this.isVite = !this.isCra && hasDep('vite') if (!this.isCra && !this.isVite) { fatalMessage( `Error: react-scripts was not detected, is this a CRA project?` ) } this.shouldUseTypeScript = fs.existsSync(path.join(this.appDir, 'tsconfig.json')) || globby.sync('src/**/*.{ts,tsx}', { cwd: path.join(this.appDir, 'src'), }).length > 0 this.indexPage = globby.sync( [`${this.isCra ? 'index' : 'main'}.{js,jsx,ts,tsx}`], { cwd: path.join(this.appDir, 'src'), } )[0] if (!this.indexPage) { fatalMessage('Error: unable to find `src/index`') } } public async transform() { console.log('Transforming CRA project at:', this.appDir) // convert src/index.js to a react component to render // inside of Next.js instead of the custom render root const indexTransformRes = await runJscodeshift( indexTransformPath, { ...this.jscodeShiftFlags, silent: true, verbose: 0 }, [path.join(this.appDir, 'src', this.indexPage)] ) if (indexTransformRes.error > 0) { fatalMessage( `Error: failed to apply transforms for src/${this.indexPage}, please check for syntax errors to continue` ) } if (indexContext.multipleRenderRoots) { fatalMessage( `Error: multiple ReactDOM.render roots in src/${this.indexPage}, migrate additional render roots to use portals instead to continue.\n` + `See here for more info: https://reactjs.org/docs/portals.html` ) } if (indexContext.nestedRender) { fatalMessage( `Error: nested ReactDOM.render found in src/${this.indexPage}, please migrate this to a top-level render (no wrapping functions) to continue` ) } // comment out global style imports and collect them // so that we can add them to _app const globalCssRes = await runJscodeshift( globalCssTransformPath, { ...this.jscodeShiftFlags }, [this.appDir] ) if (globalCssRes.error > 0) { fatalMessage( `Error: failed to apply transforms for src/${this.indexPage}, please check for syntax errors to continue` ) } if (!this.isDryRun) { await fs.promises.mkdir(path.join(this.appDir, this.pagesDir)) } this.logCreate(this.pagesDir) if (globalCssContext.reactSvgImports.size > 0) { // This de-opts webpack 5 since svg/webpack doesn't support webpack 5 yet, // so we don't support this automatically fatalMessage( `Error: import {ReactComponent} from './logo.svg' is not supported, please use normal SVG imports to continue.\n` + `React SVG imports found in:\n${[ ...globalCssContext.reactSvgImports, ].join('\n')}` ) } await this.updatePackageJson() await this.createNextConfig() await this.updateGitIgnore() await this.createPages() } private checkForYarn() { try { const userAgent = process.env.npm_config_user_agent if (userAgent) { return Boolean(userAgent && userAgent.startsWith('yarn')) } execa.sync('yarnpkg', ['--version'], { stdio: 'ignore' }) return true } catch (e) { console.log('error', e) return false } } private logCreate(...args: any[]) { if (this.shouldLogInfo) { console.log('Created:', ...args) } } private logModify(...args: any[]) { if (this.shouldLogInfo) { console.log('Modified:', ...args) } } private logInfo(...args: any[]) { if (this.shouldLogInfo) { console.log(...args) } } private async createPages() { // load public/index.html and add tags to _document const htmlContent = await fs.promises.readFile( path.join(this.appDir, `${this.isCra ? 'public/' : ''}index.html`), 'utf8' ) const $ = cheerio.load(htmlContent) // note: title tag and meta[viewport] needs to be placed in _app // not _document const titleTag = $('title')[0] const metaViewport = $('meta[name="viewport"]')[0] const headTags = $('head').children() const bodyTags = $('body').children() const pageExt = this.shouldUseTypeScript ? 'tsx' : 'js' const appPage = path.join(this.pagesDir, `_app.${pageExt}`) const documentPage = path.join(this.pagesDir, `_document.${pageExt}`) const catchAllPage = path.join(this.pagesDir, `[[...slug]].${pageExt}`) const gatherTextChildren = (children: CheerioElement[]) => { return children .map((child) => { if (child.type === 'text') { return child.data } return '' }) .join('') } const serializeAttrs = (attrs: CheerioElement['attribs']) => { const attrStr = Object.keys(attrs || {}) .map((name) => { const reactName = htmlToReactAttributes[name] || name const value = attrs[name] // allow process.env access to work dynamically still if (value.match(/%([a-zA-Z0-9_]{0,})%/)) { return `${reactName}={\`${value.replace( /%([a-zA-Z0-9_]{0,})%/g, (subStr) => { return `\${process.env.${subStr.slice(1, -1)}}` } )}\`}` } return `${reactName}="${value}"` }) .join(' ') return attrStr.length > 0 ? ` ${attrStr}` : '' } const serializedHeadTags: string[] = [] const serializedBodyTags: string[] = [] headTags.map((_index, element) => { if ( element.tagName === 'title' || (element.tagName === 'meta' && element.attribs.name === 'viewport') ) { return element } let hasChildren = element.children.length > 0 let serializedAttrs = serializeAttrs(element.attribs) if (element.tagName === 'script' || element.tagName === 'style') { hasChildren = false serializedAttrs += ` dangerouslySetInnerHTML={{ __html: \`${gatherTextChildren( element.children ).replace(/`/g, '\\`')}\` }}` } serializedHeadTags.push( hasChildren ? `<${element.tagName}${serializedAttrs}>${gatherTextChildren( element.children )}</${element.tagName}>` : `<${element.tagName}${serializedAttrs} />` ) return element }) bodyTags.map((_index, element) => { if (element.tagName === 'div' && element.attribs.id === 'root') { return element } let hasChildren = element.children.length > 0 let serializedAttrs = serializeAttrs(element.attribs) if (element.tagName === 'script' || element.tagName === 'style') { hasChildren = false serializedAttrs += ` dangerouslySetInnerHTML={{ __html: \`${gatherTextChildren( element.children ).replace(/`/g, '\\`')}\` }}` } serializedHeadTags.push( hasChildren ? `<${element.tagName}${serializedAttrs}>${gatherTextChildren( element.children )}</${element.tagName}>` : `<${element.tagName}${serializedAttrs} />` ) return element }) if (!this.isDryRun) { await fs.promises.writeFile( path.join(this.appDir, appPage), `${ globalCssContext.cssImports.size === 0 ? '' : [...globalCssContext.cssImports] .map((file) => { if (!this.isCra) { file = file.startsWith('/') ? file.slice(1) : file } return `import '${ file.startsWith('/') ? path.relative( path.join(this.appDir, this.pagesDir), file ) : file }'` }) .join('\n') + '\n' }${titleTag ? `import Head from 'next/head'` : ''} export default function MyApp({ Component, pageProps}) { ${ titleTag || metaViewport ? `return ( <> <Head> ${ titleTag ? `<title${serializeAttrs(titleTag.attribs)}>${gatherTextChildren( titleTag.children )}</title>` : '' } ${metaViewport ? `<meta${serializeAttrs(metaViewport.attribs)} />` : ''} </Head> <Component {...pageProps} /> </> )` : 'return <Component {...pageProps} />' } } ` ) await fs.promises.writeFile( path.join(this.appDir, documentPage), `import Document, { Html, Head, Main, NextScript } from 'next/document' class MyDocument extends Document { render() { return ( <Html${serializeAttrs($('html').attr())}> <Head> ${serializedHeadTags.join('\n ')} </Head> <body${serializeAttrs($('body').attr())}> <Main /> <NextScript /> ${serializedBodyTags.join('\n ')} </body> </Html> ) } } export default MyDocument ` ) const relativeIndexPath = path.relative( path.join(this.appDir, this.pagesDir), path.join(this.appDir, 'src', this.isCra ? '' : 'main') ) // TODO: should we default to ssr: true below and recommend they // set it to false if they encounter errors or prefer the more safe // option to prevent their first start from having any errors? await fs.promises.writeFile( path.join(this.appDir, catchAllPage), `// import NextIndexWrapper from '${relativeIndexPath}' // next/dynamic is used to prevent breaking incompatibilities // with SSR from window.SOME_VAR usage, if this is not used // next/dynamic can be removed to take advantage of SSR/prerendering import dynamic from 'next/dynamic' // try changing "ssr" to true below to test for incompatibilities, if // no errors occur the above static import can be used instead and the // below removed const NextIndexWrapper = dynamic(() => import('${relativeIndexPath}'), { ssr: false }) export default function Page(props) { return <NextIndexWrapper {...props} /> } ` ) } this.logCreate(appPage) this.logCreate(documentPage) this.logCreate(catchAllPage) } private async updatePackageJson() { // rename react-scripts -> next and react-scripts test -> jest // add needed dependencies for webpack compatibility const newDependencies: Array<{ name: string version: string }> = [ // TODO: do we want to install jest automatically? { name: 'next', version: 'latest', }, ] const packageName = this.isCra ? 'react-scripts' : 'vite' const packagesToRemove = { [packageName]: undefined, } const neededDependencies: string[] = [] const { devDependencies, dependencies, scripts } = this.packageJsonData for (const dep of newDependencies) { if (!devDependencies?.[dep.name] && !dependencies?.[dep.name]) { neededDependencies.push(`${dep.name}@${dep.version}`) } } this.logInfo( `Installing ${neededDependencies.join(' ')} with ${this.installClient}` ) if (!this.isDryRun) { await fs.promises.writeFile( this.packageJsonPath, JSON.stringify( { ...this.packageJsonData, scripts: Object.keys(scripts).reduce((prev, cur) => { const command = scripts[cur] prev[cur] = command if (command === packageName) { prev[cur] = 'next dev' } if (command.includes(`${packageName} `)) { prev[cur] = command.replace( `${packageName} `, command.includes(`${packageName} test`) ? 'jest ' : 'next ' ) } if (cur === 'eject') { prev[cur] = undefined } // TODO: do we want to map start -> next start instead of CRA's // default of mapping starting to dev mode? if (cur === 'start') { prev[cur] = prev[cur].replace('next start', 'next dev') prev['start-production'] = 'next start' } return prev }, {} as { [key: string]: string }), dependencies: { ...dependencies, ...packagesToRemove, }, devDependencies: { ...devDependencies, ...packagesToRemove, }, }, null, 2 ) ) await install(this.appDir, neededDependencies, { useYarn: this.installClient === 'yarn', // do we want to detect offline as well? they might not // have next in the local cache already isOnline: true, }) } } private async updateGitIgnore() { // add Next.js specific items to .gitignore e.g. '.next' const gitignorePath = path.join(this.appDir, '.gitignore') let ignoreContent = await fs.promises.readFile(gitignorePath, 'utf8') const nextIgnores = ( await fs.promises.readFile( path.join(path.dirname(globalCssTransformPath), 'gitignore'), 'utf8' ) ).split('\n') if (!this.isDryRun) { for (const ignore of nextIgnores) { if (!ignoreContent.includes(ignore)) { ignoreContent += `\n${ignore}` } } await fs.promises.writeFile(gitignorePath, ignoreContent) } this.logModify('.gitignore') } private async createNextConfig() { if (!this.isDryRun) { const { proxy, homepage } = this.packageJsonData const homepagePath = new URL(homepage || '/', 'http://example.com') .pathname await fs.promises.writeFile( path.join(this.appDir, 'next.config.js'), `module.exports = {${ proxy ? ` async rewrites() { return { fallback: [ { source: '/:path*', destination: '${proxy}' } ] } },` : '' } env: { PUBLIC_URL: '${homepagePath === '/' ? '' : homepagePath || ''}' }, experimental: { craCompat: true, }, // Remove this to leverage Next.js' static image handling // read more here: https://nextjs.org/docs/api-reference/next/image images: { disableStaticImages: true } } ` ) } this.logCreate('next.config.js') } private getPagesDir() { // prefer src/pages as CRA uses the src dir by default // and attempt falling back to top-level pages dir let pagesDir = 'src/pages' if (fs.existsSync(path.join(this.appDir, pagesDir))) { pagesDir = 'pages' } if (fs.existsSync(path.join(this.appDir, pagesDir))) { fatalMessage( `Error: a "./pages" directory already exists, please rename to continue` ) } return pagesDir } private loadPackageJson() { let packageJsonData try { packageJsonData = JSON.parse( fs.readFileSync(this.packageJsonPath, 'utf8') ) } catch (err) { fatalMessage( `Error: failed to load package.json from ${this.packageJsonPath}, ensure provided directory is root of CRA project` ) } return packageJsonData } private validateAppDir(files: string[]) { if (files.length > 1) { fatalMessage( `Error: only one directory should be provided for the cra-to-next transform, received ${files.join( ', ' )}` ) } const appDir = path.join(process.cwd(), files[0]) let isValidDirectory = false try { isValidDirectory = fs.lstatSync(appDir).isDirectory() } catch (err) { // not a valid directory } if (!isValidDirectory) { fatalMessage( `Error: invalid directory provided for the cra-to-next transform, received ${appDir}` ) } return appDir } } export default async function transformer(files, flags) { try { const craTransform = new CraTransform(files, flags) await craTransform.transform() console.log(`CRA to Next.js migration complete`, `\n${feedbackMessage}`) } catch (err) { fatalMessage(`Error: failed to complete transform`, err) } }
the_stack
import FocusTrap from 'focus-trap-react'; import { Set } from 'immutable'; import React, {useMemo, useState} from 'react'; import { useSelector } from 'react-redux'; import { useHistory, useParams } from 'react-router'; import { Link } from 'react-router-dom'; import AutoSizer from 'react-virtualized-auto-sizer'; import { VariableSizeList } from 'react-window'; import { IArticleAttributes, IArticleModel, ICategoryModel, ModelId } from '../../../models'; import { ArticleControlIcon, AssignModerators, MagicTimestamp } from '../../components'; import * as icons from '../../components/Icons'; import { Scrim } from '../../components/Scrim'; import {CustomScrollbarsVirtualList} from '../../components/VirtualListScrollbar'; import { updateArticle, updateArticleModerators, updateCategoryModerators, } from '../../platform/dataService'; import { getArticles } from '../../stores/articles'; import { getCategoryMap, ISummaryCounts } from '../../stores/categories'; import { getUsers } from '../../stores/users'; import { flexCenter, HEADER_HEIGHT, NICE_LIGHTEST_BLUE, NICE_MIDDLE_BLUE, SCRIM_STYLE, } from '../../styles'; import { COMMON_STYLES, medium } from '../../stylesx'; import { css, IPossibleStyle, stylesheet, useBindEscape } from '../../utilx'; import { articleBase, categoryBase, dashboardLink, IDashboardPathParams, moderatedCommentsPageLink, NEW_COMMENTS_DEFAULT_TAG, newCommentsPageLink, } from '../routes'; import { ModeratorsWidget, TITLE_CELL_STYLES, TitleCell } from './components'; import { FilterSidebar } from './FilterSidebar'; import { ARTICLE_TABLE_STYLES, CELL_HEIGHT } from './styles'; import { NOT_SET, SORT_APPROVED, SORT_DEFERRED, SORT_FLAGGED, SORT_HIGHLIGHTED, SORT_LAST_MODERATED, SORT_NEW, SORT_REJECTED, SORT_TITLE, SORT_UPDATED, } from './utils'; import { executeFilter, executeSort, getFilterString, getSortString, IFilterItem, isFilterActive, parseFilter, parseSort, } from './utils'; const STYLES = stylesheet({ scrimPopup: { background: 'rgba(0, 0, 0, 0.4)', ...flexCenter, alignContent: 'center', }, pagingBar: { height: `${HEADER_HEIGHT}px`, width: '100%', display: 'flex', justifyContent: 'center', textSize: '18px', color: 'white', }, directionIndicator: { position: 'absolute', left: 0, right: 0, textAlign: 'center', lineHeight: 'initial', }, }); const POPUP_MODERATORS = 'moderators'; const POPUP_CONTROLS = 'controls'; const POPUP_FILTERS = 'filters'; const POPUP_SAVING = 'saving'; function renderTime(time: string | null) { if (!time) { return 'Never'; } return <MagicTimestamp timestamp={time} inFuture={false}/>; } interface ICountsInfoProps { counts: ISummaryCounts; cellStyle: IPossibleStyle; getLink(disposition: string): string; } function CountsInfo(props: ICountsInfoProps) { const {getLink, cellStyle, counts} = props; return ( <> <div {...css(cellStyle, ARTICLE_TABLE_STYLES.numberCell)}> <Link to={getLink('new')} {...css(COMMON_STYLES.cellLink)}> {counts.unmoderatedCount} </Link> </div> <div {...css(cellStyle, ARTICLE_TABLE_STYLES.numberCell)}> <Link to={getLink('approved')} {...css(COMMON_STYLES.cellLink)}> {counts.approvedCount} </Link> </div> <div {...css(cellStyle, ARTICLE_TABLE_STYLES.numberCell)}> <Link to={getLink('rejected')} {...css(COMMON_STYLES.cellLink)}> {counts.rejectedCount} </Link> </div> <div {...css(cellStyle, ARTICLE_TABLE_STYLES.numberCell)}> <Link to={getLink('deferred')} {...css(COMMON_STYLES.cellLink)}> {counts.deferredCount} </Link> </div> <div {...css(cellStyle, ARTICLE_TABLE_STYLES.numberCell)}> <Link to={getLink('highlighted')} {...css(COMMON_STYLES.cellLink)}> {counts.highlightedCount} </Link> </div> <div {...css(cellStyle, ARTICLE_TABLE_STYLES.numberCell)}> <Link to={getLink('flagged')} {...css(COMMON_STYLES.cellLink)}> {counts.flaggedCount} </Link> </div> </> ); } interface IRowActions { clearPopups(): void; openControls(article: IArticleModel): void; saveControls(isCommentingEnabled: boolean, isAutoModerated: boolean): void; openSetModerators( targetId: ModelId, moderatorIds: Array<ModelId>, superModeratorIds: Array<ModelId>, isCategory: boolean, ): void; } interface IArticleRowProps extends IRowActions { article: IArticleModel; selectedArticle?: ModelId | null; } function ArticleRow(props: IArticleRowProps) { const {article, selectedArticle} = props; const categories = useSelector(getCategoryMap); const users = useSelector(getUsers); const lastModerated = renderTime(article.lastModeratedAt); const category = categories.get(article.categoryId); function getLink(disposition: string) { if (disposition === 'new') { return newCommentsPageLink({context: articleBase, contextId: article.id, tag: NEW_COMMENTS_DEFAULT_TAG}); } return moderatedCommentsPageLink({context: articleBase, contextId: article.id, disposition}); } const targetId = article.id; const moderatorIds = article.assignedModerators; const superModeratorIds = category?.assignedModerators; function openSetModerators() { props.openSetModerators(targetId, moderatorIds, superModeratorIds, false); } const cellStyle = ARTICLE_TABLE_STYLES.dataCell; return ( <div {...css(cellStyle, ARTICLE_TABLE_STYLES.dataBody)}> <div {...css(cellStyle, ARTICLE_TABLE_STYLES.textCell)}> <TitleCell category={categories.get(article.categoryId)} article={article} link={getLink('new')} /> </div> <CountsInfo counts={article} cellStyle={cellStyle} getLink={getLink}/> <div {...css(cellStyle, ARTICLE_TABLE_STYLES.timeCell)}> <MagicTimestamp timestamp={article.updatedAt} inFuture={false}/> </div> <div {...css(cellStyle, ARTICLE_TABLE_STYLES.timeCell)}> {lastModerated} </div> <div {...css(cellStyle, ARTICLE_TABLE_STYLES.iconCell)}> <div {...css({display: 'inline-block'})}> <ArticleControlIcon article={article} open={selectedArticle && selectedArticle === article.id} clearPopups={props.clearPopups} openControls={props.openControls} saveControls={props.saveControls} /> </div> </div> <div {...css(cellStyle, ARTICLE_TABLE_STYLES.iconCell)}> {targetId && ( <ModeratorsWidget users={users} moderatorIds={moderatorIds} superModeratorIds={superModeratorIds} openSetModerators={openSetModerators} /> )} </div> </div> ); } interface ISummaryRowProps extends IRowActions { summary: IArticleModel; } function SummaryRow(props: ISummaryRowProps) { const {summary} = props; const categories = useSelector(getCategoryMap); const users = useSelector(getUsers); const category = categories.get(summary.categoryId); function getLink(disposition: string) { const categoryId = category ? category.id : 'all'; if (disposition === 'new') { return newCommentsPageLink({context: categoryBase, contextId: categoryId, tag: NEW_COMMENTS_DEFAULT_TAG}); } return moderatedCommentsPageLink({context: categoryBase, contextId: categoryId, disposition}); } const targetId = category?.id; const moderatorIds = category?.assignedModerators; function openSetModerators() { props.openSetModerators(targetId, moderatorIds, null, true); } const cellStyle = ARTICLE_TABLE_STYLES.summaryCell; return ( <div {...css(cellStyle, ARTICLE_TABLE_STYLES.dataBody)}> <div {...css(cellStyle, ARTICLE_TABLE_STYLES.textCell)}> <Link to={getLink('new')} {...css(COMMON_STYLES.cellLink, TITLE_CELL_STYLES.mainTextText)}> {summary.title} </Link> </div> <CountsInfo counts={summary} cellStyle={cellStyle} getLink={getLink}/> <div {...css(cellStyle, ARTICLE_TABLE_STYLES.timeCell)}/> <div {...css(cellStyle, ARTICLE_TABLE_STYLES.timeCell)}/> <div {...css(cellStyle, ARTICLE_TABLE_STYLES.iconCell)}> <div {...css({display: 'inline-block'})}/> </div> <div {...css(cellStyle, ARTICLE_TABLE_STYLES.iconCell)}> {targetId && ( <ModeratorsWidget users={users} moderatorIds={moderatorIds} superModeratorIds={null} openSetModerators={openSetModerators} /> )} </div> </div> ); } function DirectionIndicatorUp() { return ( <div {...css(STYLES.directionIndicator, {top: '-15px'})}> <icons.KeyUpIcon/> </div> ); } function DirectionIndicatorDown() { return ( <div {...css(STYLES.directionIndicator, {bottom: '-18px'})}> <icons.KeyDownIcon/> </div> ); } export interface IArticleTableProps { } function calculateSummaryCounts(articles: Array<IArticleModel>) { const columns = [ 'unmoderatedCount', 'approvedCount', 'rejectedCount', 'deferredCount', 'highlightedCount', 'flaggedCount', ]; const summary: Partial<IArticleAttributes> & {[key: string]: number} = {}; for (const i of columns) { summary['count'] = 0; summary[i] = 0; } articles.reduce((s: any, a) => { s['count'] ++; for (const i of columns) { s[i] += (a as any)[i]; } return s; }, summary); return summary; } function sortArticles(articles: Array<IArticleModel>, sort: Array<string>) { const sortFn = (sort.length > 0) ? executeSort(sort) : executeSort([`+${SORT_NEW}`]); return articles.sort(sortFn); } function filterArticles( articles: Array<IArticleModel>, filter: Array<IFilterItem>, categories: Map<ModelId, ICategoryModel>, ): Array<IArticleModel> { if (filter.length === 0) { return articles; } return articles.filter(executeFilter(filter, {categories})); } export function ArticleTable(_props: IArticleTableProps) { const history = useHistory(); const params = useParams<IDashboardPathParams>(); const articlesContainerHeight = window.innerHeight - HEADER_HEIGHT * 2; const categories = useSelector(getCategoryMap); const articles = useSelector(getArticles); const users = useSelector(getUsers); const filterString = params.filter || NOT_SET; const sortString = params.sort || NOT_SET; const filter = useMemo(() => parseFilter(filterString), [filterString]); const sort = useMemo(() => parseSort(sortString), [sortString]); const sortedArticles = useMemo(() => sortArticles(articles, sort), [articles, sort]); const filteredArticles = useMemo( () => filterArticles(sortedArticles, filter, categories), [sortedArticles, filter, categories], ); const summary = useMemo(() => calculateSummaryCounts(filteredArticles), [filteredArticles]); // Use users map from store const count = summary['count']; summary['id'] = 'summary'; summary['title'] = ` ${count} Title` + (count !== 1 ? 's' : ''); const categoryMatch = /category=(\d+)/.exec(filterString); const selectedCategory = categoryMatch ? categories.get(categoryMatch[1]) : null; if (selectedCategory) { summary['categoryId'] = selectedCategory.id; summary['title'] += ` in section ${selectedCategory.label}`; } if (filter.length > 1 || (filter.length === 1 && filter[0].key !== 'category')) { summary['title'] += ' matching filter'; } const [popupToShow, setPopupToShow] = useState<string>(null); const [selectedArticle, setSelectedArticle] = useState<IArticleModel>(null); const [targetIsCategory, setTargetIsCategory] = useState<boolean>(null); const [targetId, setTargetId] = useState<ModelId>(null); const [moderatorIds, setModeratorIds] = useState<Set<ModelId>>(null); const [superModeratorIds, setSuperModeratorIds] = useState<Set<ModelId>>(null); const currentFilter = getFilterString(filter); const currentSort = getSortString(sort); function clearPopups() { setPopupToShow(null); setSelectedArticle(null); setTargetIsCategory(null); setTargetId(null); setModeratorIds(null); setSuperModeratorIds(null); } useBindEscape(clearPopups); function openSetModerators( iTargetId: ModelId, iModeratorIds: Array<ModelId>, iSuperModeratorIds: Array<ModelId>, isCategory: boolean, ) { clearPopups(); setPopupToShow(POPUP_MODERATORS); setTargetIsCategory(isCategory); setTargetId(iTargetId); setModeratorIds(Set<ModelId>(iModeratorIds)); setSuperModeratorIds(Set<ModelId>(iSuperModeratorIds)); } function openFilters() { clearPopups(); setPopupToShow(POPUP_FILTERS); } function openControls(article: IArticleModel) { setPopupToShow(POPUP_CONTROLS); setSelectedArticle(article); } function renderFilterPopup() { function setFilter(newFilter: Array<IFilterItem>) { history.push(dashboardLink({filter: getFilterString(newFilter), sort: currentSort})); } return ( <FilterSidebar key="filter-sidebar" open={popupToShow === POPUP_FILTERS} filterString={filterString} filter={filter} users={users.valueSeq()} setFilter={setFilter} clearPopups={clearPopups} /> ); } async function saveControls(isCommentingEnabled: boolean, isAutoModerated: boolean) { clearPopups(); setPopupToShow(POPUP_SAVING); await updateArticle(selectedArticle.id, isCommentingEnabled, isAutoModerated); clearPopups(); } function onAddModerator(userId: string) { setModeratorIds(moderatorIds.add(userId)); } function onRemoveModerator(userId: string) { setModeratorIds(moderatorIds.remove(userId)); } async function saveModerators() { clearPopups(); setPopupToShow(POPUP_SAVING); if (targetIsCategory) { await updateCategoryModerators(targetId, moderatorIds.toArray()); } else { await updateArticleModerators(targetId, moderatorIds.toArray()); } clearPopups(); } function renderSaving() { if (popupToShow === POPUP_SAVING) { return ( <Scrim key="saving" isVisible onBackgroundClick={clearPopups} scrimStyles={STYLES.scrimPopup}> <div tabIndex={0} {...css(SCRIM_STYLE.popup)}> Saving.... </div> </Scrim> ); } return null; } function renderSetModerators() { if (popupToShow !== POPUP_MODERATORS) { return null; } return ( <Scrim key="set-moderators" isVisible onBackgroundClick={clearPopups} scrimStyles={STYLES.scrimPopup}> <FocusTrap focusTrapOptions={{clickOutsideDeactivates: true}}> <div tabIndex={0} {...css(SCRIM_STYLE.popup, {position: 'relative'})}> <AssignModerators label={targetIsCategory ? 'Assign a category moderator' : 'Assign a moderator'} moderatorIds={moderatorIds} superModeratorIds={superModeratorIds} onAddModerator={onAddModerator} onRemoveModerator={onRemoveModerator} onClickDone={saveModerators} onClickClose={clearPopups} /> </div> </FocusTrap> </Scrim> ); } function rowHeight(index: number) { if (index === 0) { return HEADER_HEIGHT; } return CELL_HEIGHT; } function renderRow(index: number, style: any) { if (index === 0) { return ( <div key={'summary'} style={style}> <SummaryRow summary={summary as IArticleModel} clearPopups={clearPopups} openControls={openControls} saveControls={saveControls} openSetModerators={openSetModerators} /> </div> ); } const article = filteredArticles[index - 1]; return ( <div key={index} style={style}> <ArticleRow article={article} selectedArticle={selectedArticle?.id} clearPopups={clearPopups} openControls={openControls} saveControls={saveControls} openSetModerators={openSetModerators} /> </div> ); } const HeaderItem: React.FunctionComponent<{sortField: string}> = (props) => { const {sortField, children} = props; let directionIndicator: string | JSX.Element = ''; let nextSortItem = `+${sortField}`; for (const item of sort) { if (item.endsWith(sortField)) { if (item[0] === '+') { directionIndicator = DirectionIndicatorDown(); nextSortItem = `-${sortField}`; } else if (item[0] === '-') { directionIndicator = DirectionIndicatorUp(); nextSortItem = ''; } break; } } // const newSort = sortString(updateSort(sort, nextSortItem)); implements multi sort const newSort = getSortString([nextSortItem]); return ( <Link to={dashboardLink({filter: currentFilter, sort: newSort})} {...css(COMMON_STYLES.cellLink)}> <span {...css({position: 'relative'})}> {children} {directionIndicator} </span> </Link> ); }; const filterActive = isFilterActive(filter); return ( <div key="main"> <div key="header" {...css(ARTICLE_TABLE_STYLES.dataHeader)}> <div key="title" {...css(ARTICLE_TABLE_STYLES.headerCell, ARTICLE_TABLE_STYLES.textCell)}> <HeaderItem sortField={SORT_TITLE}>Title</HeaderItem> </div> <div key="new" {...css(ARTICLE_TABLE_STYLES.headerCell, ARTICLE_TABLE_STYLES.numberCell)}> <HeaderItem sortField={SORT_NEW}>New</HeaderItem> </div> <div key="approved" {...css(ARTICLE_TABLE_STYLES.headerCell, ARTICLE_TABLE_STYLES.numberCell)}> <HeaderItem sortField={SORT_APPROVED}>Approved</HeaderItem> </div> <div key="rejected" {...css(ARTICLE_TABLE_STYLES.headerCell, ARTICLE_TABLE_STYLES.numberCell)}> <HeaderItem sortField={SORT_REJECTED}>Rejected</HeaderItem> </div> <div key="deferred" {...css(ARTICLE_TABLE_STYLES.headerCell, ARTICLE_TABLE_STYLES.numberCell)}> <HeaderItem sortField={SORT_DEFERRED}>Deferred</HeaderItem> </div> <div key="highlighted" {...css(ARTICLE_TABLE_STYLES.headerCell, ARTICLE_TABLE_STYLES.numberCell)}> <HeaderItem sortField={SORT_HIGHLIGHTED}>Highlighted</HeaderItem> </div> <div key="flagged" {...css(ARTICLE_TABLE_STYLES.headerCell, ARTICLE_TABLE_STYLES.numberCell)}> <HeaderItem sortField={SORT_FLAGGED}>Flagged</HeaderItem> </div> <div key="modified" {...css(ARTICLE_TABLE_STYLES.headerCell, ARTICLE_TABLE_STYLES.timeCell)}> <HeaderItem sortField={SORT_UPDATED}>Modified</HeaderItem> </div> <div key="moderated" {...css(ARTICLE_TABLE_STYLES.headerCell, ARTICLE_TABLE_STYLES.timeCell)}> <HeaderItem sortField={SORT_LAST_MODERATED}>Moderated</HeaderItem> </div> <div key="flags" {...css(ARTICLE_TABLE_STYLES.headerCell, ARTICLE_TABLE_STYLES.iconCell)}/> <div key="mods" {...css(ARTICLE_TABLE_STYLES.headerCell, ARTICLE_TABLE_STYLES.iconCell)}> <div {...css({width: '100%', height: '100%', ...flexCenter})}> <div {...css({width: '44px', height: '44px', borderRadius: '50%', ...flexCenter, backgroundColor: filterActive ? NICE_LIGHTEST_BLUE : NICE_MIDDLE_BLUE, color: filterActive ? NICE_MIDDLE_BLUE : NICE_LIGHTEST_BLUE})} > <icons.FilterIcon {...css(medium)} onClick={openFilters}/> </div> </div> </div> </div> <div key="content" style={{height: `${articlesContainerHeight}px`, backgroundColor: 'white'}}> <AutoSizer> {({width, height}) => ( <VariableSizeList outerElementType={CustomScrollbarsVirtualList} itemSize={rowHeight} itemCount={filteredArticles.length + 1} height={height} width={width} overscanCount={10} > {({index, style}) => ( renderRow(index, style) )} </VariableSizeList> )} </AutoSizer> </div> {renderFilterPopup()} {renderSaving()} {renderSetModerators()} </div> ); }
the_stack
import * as React from "react"; import Tree from "antd/lib/tree/Tree"; import { ContextMenu, Menu, MenuItem, MenuDivider, Classes, Tooltip, Position, InputGroup, FormGroup, Switch, ButtonGroup, Button, Popover, Pre, Intent, Code, Tag, } from "@blueprintjs/core"; import { Nullable, Undefinable } from "../../../shared/types"; import { Node, Scene, Mesh, Light, Camera, TransformNode, InstancedMesh, AbstractMesh, MultiMaterial, IParticleSystem, ParticleSystem, Sound, SubMesh, } from "babylonjs"; import { Editor } from "../editor"; import { Icon } from "../gui/icon"; import { EditableText } from "../gui/editable-text"; import { Tools } from "../tools/tools"; import { undoRedo } from "../tools/undo-redo"; import { IMeshMetadata } from "../tools/types"; import { Prefab } from "../prefab/prefab"; import { SceneSettings } from "../scene/settings"; import { SceneTools } from "../scene/tools"; import { SoundAssets } from "../assets/sounds"; import { IDragAndDroppedAssetComponentItem } from "../assets/abstract-assets"; export interface IGraphProps { /** * Defines the editor reference. */ editor: Editor; /** * Defines the reference to the scene to traverse. */ scene?: Undefinable<Scene>; } export interface IGraphState { /** * Defines the list of all nodes to be draws in the editor. */ nodes: JSX.Element[]; /** * Defines the list of all expanded nodes. */ expandedNodeIds?: Undefinable<string[]>; /** * Defines the list of all selected nodes. */ selectedNodeIds?: Undefinable<string[]>; /** * Defines the current filter to search nodes. */ filter: string; /** * Defines wether or not the graphs options should be drawn. */ showOptions: boolean; /** * Defines wether or not the instances should be shown in the graph. */ showInstances: boolean; /** * Defines wether or not the lights should be shown in the graph. */ showLights: boolean; } interface _ITreeDropInfo { event: React.MouseEvent; node: any; dragNode: any; dragNodesKeys: (string | number)[]; dropPosition: number; dropToGap: boolean; } export class Graph extends React.Component<IGraphProps, IGraphState> { private _editor: Editor; private _firstUpdate: boolean = true; private _filter: string = ""; private _copiedTransform: Nullable<AbstractMesh | Light | Camera> = null; /** * Defines the last selected node in the graph. */ public lastSelectedObject: Nullable<Node | IParticleSystem | Sound> = null; /** * Constructor. * @param props the component's props. */ public constructor(props: IGraphProps) { super(props); this._editor = props.editor; if (!props.scene) { this._editor.graph = this; } this.state = { nodes: [], expandedNodeIds: [], selectedNodeIds: [], filter: "", showOptions: false, showInstances: true, showLights: true, }; } /** * Renders the component. */ public render(): JSX.Element { if (!this.state.nodes.length) { return null!; } return ( <div style={{ width: "100%", height: "100%", overflow: "hidden" }}> <InputGroup className={Classes.FILL} leftIcon={"search"} type="search" placeholder="Search..." onChange={(e) => this._handleFilterChanged(e.target.value)}></InputGroup> <Popover fill={true} isOpen={this.state.showOptions} position={Position.BOTTOM} popoverClassName={Classes.POPOVER_CONTENT_SIZING} usePortal={true} inheritDarkTheme={true} onClose={() => this.setState({ showOptions: false })} lazy={true} content={ <FormGroup label="Graph" labelInfo="Options" > <Switch label="Show Instances" checked={this.state.showInstances} onChange={(e) => this.setState({ showInstances: e.currentTarget.checked }, () => this.refresh())} /> <Switch label="Show Lights" checked={this.state.showLights} onChange={(e) => this.setState({ showLights: e.currentTarget.checked }, () => this.refresh())} /> </FormGroup> } > <ButtonGroup fill={true}> <Button text="Options..." onClick={() => this.setState({ showOptions: true })} /> </ButtonGroup> </Popover> <div style={{ width: "100%", height: "calc(100% - 60px)", overflow: "auto" }}> <Tree.DirectoryTree className="draggable-tree" draggable={true} multiple={true} showIcon={true} checkable={false} key={"Graph"} style={{ height: "calc(100% - 32px)" }} blockNode={true} expandedKeys={this.state.expandedNodeIds ?? []} onExpand={(k) => this._handleExpandedNode(k as string[])} onRightClick={(e) => this._handleNodeContextMenu(e.event, e.node)} onSelect={(k) => this._handleSelectedNodes(k as string[])} autoExpandParent={false} selectedKeys={this.state.selectedNodeIds ?? []} expandAction="doubleClick" onDragEnter={(n) => this._handleDragEnter(n)} onDragStart={(n) => this._handleDragStart(n)} onDrop={(i) => this._handleDrop(i)} > {this.state.nodes} </Tree.DirectoryTree> </div> </div> ); } /** * Refreshes the graph. * @param done called on the refresh process finished. */ public refresh(done?: Undefinable<() => void>): void { const nodes = this._parseScene(); const expandedNodeIds = this._firstUpdate ? undefined : this.state.expandedNodeIds; this.setState({ nodes, expandedNodeIds }, () => done && done()); this._firstUpdate = false; } /** * Clears the graph. */ public clear(): void { this.setState({ nodes: [], selectedNodeIds: [], expandedNodeIds: [] }); this._firstUpdate = true; } /** * Selecs the given node in the graph. * @param node the node to select in the graph. * @param appendToSelected defines wether or not the selected node should be appended to the currently selected nodes. */ public setSelected(node: Node | IParticleSystem | Sound, appendToSelected?: boolean): void { let expanded = this.state.expandedNodeIds?.slice(); if (expanded) { let parent: Nullable<Node>; if (node instanceof Node) { parent = node.parent; } else if (node instanceof Sound) { parent = node["_connectedTransformNode"]; } else { parent = node.emitter as AbstractMesh; } while (parent) { const pid = parent.id; if (expanded.indexOf(pid) === -1) { expanded.push(pid); } parent = parent.parent; } } this.lastSelectedObject = node; const id = node instanceof Sound ? node.metadata?.id : node.id; this.setState({ selectedNodeIds: (appendToSelected ? (this.state.selectedNodeIds ?? []) : []).concat([id]), expandedNodeIds: expanded ?? [], }); } /** * Refreshes the graph and selects the given node. Mainly used by assets. * @param node the node to select in the graph. */ public refreshAndSelect(node: Node): void { this.refresh(() => { setTimeout(() => this.setSelected(node)); }); } /** * Returns the list of all selected nodes (node, particle system, sound). */ public getAllSelected(): (Node | IParticleSystem | Sound)[] { const result:(Node | IParticleSystem | Sound)[] = []; const selectedIds = this.state.selectedNodeIds ?? []; selectedIds.forEach((sid) => { const node = this._getNodeById(sid); if (node) { result.push(node); } }); return result; } /** * Clones the given node. * @param node the node to clone. */ public cloneObject(node: Node | IParticleSystem): Nullable<Node | IParticleSystem> { let clone: Nullable<Node | IParticleSystem> = null; if (node instanceof Mesh) { const clonedMesh = node.clone(node.name, node.parent, false, true); if (node.skeleton) { let id = 0; while (this._editor.scene!.getSkeletonById(id as any)) { id++; } clonedMesh.skeleton = node.skeleton.clone(node.skeleton.name, id as any); } if (clonedMesh.parent) { clonedMesh.physicsImpostor?.forceUpdate(); } clonedMesh.physicsImpostor?.sleep(); clone = clonedMesh; } else if (node instanceof Light) { clone = node.clone(node.name); } else if (node instanceof Camera) { clone = node.clone(node.name); } else if (node instanceof TransformNode) { clone = node.clone(node.name, node.parent, false); } else if (node instanceof ParticleSystem) { clone = node.clone(node.name, node.emitter); } if (clone) { clone.id = Tools.RandomId(); if (clone instanceof Node) { const metadata = { ...clone.metadata } as IMeshMetadata; delete metadata._waitingUpdatedReferences; clone.metadata = Tools.CloneObject(metadata); const descendants = clone.getDescendants(false); descendants.forEach((d) => { d.id = Tools.RandomId(); d.metadata = Tools.CloneObject(d.metadata); }); // Notify this._editor.selectedNodeObservable.notifyObservers(clone); } else if (clone instanceof ParticleSystem) { // Notify this._editor.selectedParticleSystemObservable.notifyObservers(clone); } } return clone; } /** * Removes the given node. * @param node the node to remove. */ public removeObject(node: Node | IParticleSystem | Sound): void { const descendants = [node].concat(node instanceof Node ? node.getDescendants() : []); const actions = descendants.map((d) => this._removeObject(d)); undoRedo.push({ description: `Removed objects from graph: [${descendants.map((d) => d.name).join(", ")}]`, common: () => { this.refresh(); }, redo: () => { actions.forEach((a) => a.redo()); }, undo: () => { actions.forEach((a) => a.undo()); }, }); } /** * Removes the given node. * @param node the node to remove. * @hidden */ public _removeObject(node: Node | IParticleSystem | Sound): { redo: () => void; undo: () => void; } { let removeFunc: Nullable<(n: Node | IParticleSystem | Sound) => void> = null; let addFunc: Nullable<(n: Node | IParticleSystem | Sound) => void> = null; let caller: any = this._editor.scene!; if (node instanceof AbstractMesh) { removeFunc = this._editor.scene!.removeMesh; addFunc = this._editor.scene!.addMesh; } else if (node instanceof InstancedMesh) { removeFunc = node.sourceMesh.removeInstance; addFunc = node.sourceMesh.addInstance; caller = node.sourceMesh; } else if (node instanceof Light) { removeFunc = this._editor.scene!.removeLight; addFunc = this._editor.scene!.addLight; } else if (node instanceof Camera) { removeFunc = this._editor.scene!.removeCamera; addFunc = this._editor.scene!.addCamera; } else if (node instanceof TransformNode) { removeFunc = this._editor.scene!.removeTransformNode; addFunc = this._editor.scene!.addTransformNode; } else if (node instanceof ParticleSystem) { removeFunc = this._editor.scene!.removeParticleSystem; addFunc = this._editor.scene!.addParticleSystem; } else if (node instanceof Sound) { removeFunc = this._editor.scene!.mainSoundTrack.removeSound; addFunc = this._editor.scene!.mainSoundTrack.addSound; caller = this._editor.scene!.mainSoundTrack; } if (!removeFunc || !addFunc) { return { redo: () => { }, undo: () => { } }; } const parent = node instanceof Node ? node.parent : node instanceof Sound ? node["_connectedTransformNode"] : node.emitter as AbstractMesh; const lods = node instanceof Mesh ? node.getLODLevels().slice() : []; const particleSystems = this._editor.scene!.particleSystems.filter((ps) => ps.emitter === node); const shadowLights = this._editor.scene!.lights.filter((l) => l.getShadowGenerator()?.getShadowMap()?.renderList) .filter((l) => l.getShadowGenerator()!.getShadowMap()!.renderList!.indexOf(node as AbstractMesh) !== -1); const sounds: Sound[] = []; [this._editor.scene!.mainSoundTrack].concat(this._editor.scene!.soundTracks ?? []).forEach((st) => { if (!st) { return; } st.soundCollection?.forEach((s) => s["_connectedTransformNode"] === node && sounds.push(s)); }); return ({ redo: () => { if (node instanceof Node) { node.parent = null; } removeFunc?.call(caller, node); if (node instanceof Sound) { if (parent) { node.detachFromMesh(); } this._editor.assets.forceRefresh(SoundAssets); } if (node instanceof InstancedMesh) { node.sourceMesh.removeInstance(node); } if (node instanceof Mesh) { node.doNotSerialize = true; lods.forEach((lod) => { node.removeLODLevel(lod.mesh!); if (lod.mesh) { lod.mesh.doNotSerialize = true; this._editor.scene!.removeMesh(lod.mesh); } }); } particleSystems.forEach((ps) => this._editor.scene!.removeParticleSystem(ps)); if (node instanceof Node) { this._editor.removedNodeObservable.notifyObservers(node); } else if (node instanceof Sound) { this._editor.removedSoundObservable.notifyObservers(node); } else { this._editor.removedParticleSystemObservable.notifyObservers(node); } shadowLights.forEach((sl) => { const renderList = sl.getShadowGenerator()?.getShadowMap()?.renderList; if (renderList) { const index = renderList.indexOf(node as AbstractMesh); if (index !== -1) { renderList.splice(index, 1); } } }); sounds.forEach((s) => { s.detachFromMesh(); s.spatialSound = false; }); }, undo: () => { addFunc?.call(caller, node); if (node instanceof Mesh) { node.doNotSerialize = false; lods.forEach((lod) => { if (lod.mesh) { lod.mesh.doNotSerialize = false; this._editor.scene!.addMesh(lod.mesh); } node.addLODLevel(lod.distance, lod.mesh); }); } if (node instanceof InstancedMesh) { node.sourceMesh.addInstance(node); } if (node instanceof Node) { node.parent = parent; } if (node instanceof Sound) { if (parent) { node.attachToMesh(parent); } this._editor.assets.forceRefresh(SoundAssets); } particleSystems.forEach((ps) => this._editor.scene!.addParticleSystem(ps)); if (node instanceof Node) { this._editor.addedNodeObservable.notifyObservers(node); } else if (node instanceof Sound) { this._editor.addedSoundObservable.notifyObservers(node); } else { this._editor.addedParticleSystemObservable.notifyObservers(node); } shadowLights.forEach((sl) => { sl.getShadowGenerator()?.getShadowMap()?.renderList?.push(node as AbstractMesh); }); sounds.forEach((s) => s.attachToMesh(node as TransformNode)); }, }); } /** * Called on the user wants to filter the nodes. */ private _handleFilterChanged(filter: string): void { this._filter = filter; this.setState({ filter, nodes: this._parseScene() }); } /** * Returns the game instance used by the graph. */ private get _scene(): Scene { return this.props.scene ?? this._editor.scene!; } /** * Recursively parses the stage to adds the nodes to the props. */ private _parseScene(): JSX.Element[] { const nodes = this._scene.rootNodes.map((n) => this._parseNode(n)).filter((n) => n !== null); const scene = ( <Tree.TreeNode active={true} expanded={true} title={<span>Scene</span>} key="__editor__scene__" isLeaf={true} icon={<Icon src="camera-retro.svg" />} /> ); const soundsChildren = this._editor.scene!.mainSoundTrack.soundCollection.filter((s) => !s.spatialSound).map((s) => { s.metadata = s.metadata ?? { }; if (!s.metadata.id) { s.metadata.id = Tools.RandomId(); } return ( <Tree.TreeNode active={true} expanded={true} title={<span>{s.name}</span>} key={s.metadata.id} isLeaf={true} icon={<Icon src={s.isPlaying ? "volume-up.svg" : "volume-mute.svg"} />} children={sounds} /> ); }); const sounds = ( <Tree.TreeNode active={true} expanded={true} title={<span>Sounds</span>} key="sounds" isLeaf={soundsChildren.length === 0} icon={<Icon src="volume-off.svg" />} children={soundsChildren} /> ); return [scene, sounds].concat(nodes as JSX.Element[]); } /** * Parses the given node and returns the new treenode object. * @param node the node to parse. */ private _parseNode(node: Node): Nullable<JSX.Element> { if (node instanceof Mesh && node._masterMesh) { return null; } if (node === SceneSettings.Camera) { return null; } let disabled = false; node.metadata = node.metadata ?? { }; if (node instanceof AbstractMesh) { disabled = (node.metadata?.collider ?? null) !== null; node.metadata.isPickable = disabled ? false : node.metadata.isPickable ?? node.isPickable; node.isPickable = !disabled; node.subMeshes?.forEach((sm) => sm._id = sm._id ?? Tools.RandomId()); } node.id = node.id ?? Tools.RandomId(); node.name = node.name ?? "Node"; // Filters if (node instanceof InstancedMesh && !this.state.showInstances) { return null; } if (node instanceof Light && !this.state.showLights) { return null; } const ctor = Tools.GetConstructorName(node); const name = node.name ?? ctor; const style: React.CSSProperties = { marginLeft: "5px", textOverflow: "ellipsis", whiteSpace: "nowrap" }; if (node.metadata.doNotExport) { style.opacity = "0.5"; style.textDecoration = "line-through"; } if (node.metadata.isLocked) { style.opacity = "0.5"; } if (node.metadata.script?.name && node.metadata.script.name !== "None") { style.color = "#48aff0"; } if (disabled) { style.color = "grey"; } if (node.metadata?.editorGraphStyles) { Object.assign(style, node.metadata.editorGraphStyles); } // Filter let matchesFilter: boolean = true; if (this._filter) { const all = [node].concat(node.getDescendants()); matchesFilter = all.find((c) => (c.name ?? Tools.GetConstructorName(c)).toLowerCase().indexOf(this._filter.toLowerCase()) !== -1) !== undefined; } let children: JSX.Element[] = []; if (matchesFilter) { children = node.getChildren().map((c: Node) => this._parseNode(c)).filter((n) => n !== null) as JSX.Element[]; } // Mesh and skeleton? if (node instanceof AbstractMesh && node.skeleton) { children.splice(0, 0, ( <Tree.TreeNode active expanded title={node.skeleton.name} key={`${node.skeleton.name}-${node.skeleton.id}`} isLeaf icon={<Icon src="human-skull.svg" />} /> )); } // Search for particle systems. this._editor.scene!.particleSystems.forEach((ps) => { if (ps.emitter !== node) { return; } children.push( <Tree.TreeNode active={true} expanded={true} title={ <Tooltip content={<span>{Tools.GetConstructorName(ps)}</span>} position={Position.RIGHT} usePortal={false} > <span style={style}>{ps.name}</span> </Tooltip> } key={ps.id} isLeaf={true} icon={<Icon src="wind.svg" />} ></Tree.TreeNode> ); }); // Search for sounds this._editor.scene!.mainSoundTrack.soundCollection.forEach((s) => { if (s["_connectedTransformNode"] !== node) { return; } s.metadata = s.metadata ?? { }; if (!s.metadata.id) { s.metadata.id = Tools.RandomId(); } children.push( <Tree.TreeNode active={true} expanded={true} title={ <Tooltip content={<span>{Tools.GetConstructorName(s)}</span>} position={Position.RIGHT} usePortal={false} > <span style={style}>{s.name}</span> </Tooltip> } key={s.metadata.id} isLeaf={true} icon={<Icon src={s.isPlaying ? "volume-up.svg" : "volume-mute.svg"} />} ></Tree.TreeNode> ); }); // Update references let updateReferences: React.ReactNode; if (node.metadata?._waitingUpdatedReferences && Object.values(node.metadata?._waitingUpdatedReferences).find((v) => v !== undefined)) { updateReferences = ( <Tag interactive={true} intent={Intent.WARNING} style={{ marginLeft: "10px" }} onClick={(e) => { const mesh = node as Mesh; const meshMedatata = Tools.GetMeshMetadata(mesh); let updateGeometry: React.ReactNode; let updateMaterial: React.ReactNode; if (meshMedatata._waitingUpdatedReferences?.geometry != undefined) { updateGeometry = (<MenuItem text="Update Geometry" onClick={() => { meshMedatata._waitingUpdatedReferences!.geometry!.geometry?.applyToMesh(mesh); mesh.skeleton = meshMedatata._waitingUpdatedReferences!.geometry!.skeleton ?? null; if (meshMedatata._waitingUpdatedReferences!.geometry!.subMeshes) { mesh.subMeshes = []; meshMedatata._waitingUpdatedReferences!.geometry!.subMeshes?.forEach((sm) => { new SubMesh(sm.materialIndex, sm.verticesStart, sm.verticesCount, sm.indexStart, sm.indexCount, mesh, mesh, true, true); }); } delete meshMedatata._waitingUpdatedReferences!.geometry; this.refresh(); }} />); } if (meshMedatata._waitingUpdatedReferences?.material !== undefined) { updateMaterial = (<MenuItem text="Update Material" onClick={() => { mesh.material = meshMedatata._waitingUpdatedReferences?.material ?? null; delete meshMedatata._waitingUpdatedReferences!.material; this.refresh(); }} />); } ContextMenu.show( <Menu className={Classes.DARK}> <Tag>Changes available from source file</Tag> {updateGeometry} {updateMaterial} <MenuDivider /> <MenuItem text="Update All" onClick={() => { if (meshMedatata._waitingUpdatedReferences?.geometry) { meshMedatata._waitingUpdatedReferences.geometry.geometry?.applyToMesh(mesh); mesh.skeleton = meshMedatata._waitingUpdatedReferences.geometry.skeleton ?? null; if (meshMedatata._waitingUpdatedReferences!.geometry!.subMeshes) { mesh.subMeshes = []; meshMedatata._waitingUpdatedReferences!.geometry!.subMeshes?.forEach((sm) => { new SubMesh(sm.materialIndex, sm.verticesStart, sm.verticesCount, sm.indexStart, sm.indexCount, mesh, mesh, true, true); }); } } if (meshMedatata._waitingUpdatedReferences?.material !== undefined) { mesh.material = meshMedatata._waitingUpdatedReferences?.material ?? null; } delete meshMedatata._waitingUpdatedReferences; this.refresh(); }} /> </Menu>, { left: e.clientX, top: e.clientY } ); }} >...</Tag> ); } return ( <Tree.TreeNode active={true} disabled={disabled} expanded={true} title={ <Tooltip content={<span>{ctor}</span>} usePortal={true} > <> <span style={style}>{name}</span> {updateReferences} </> </Tooltip> } key={node.id} isLeaf={!children.length} icon={<Icon src={this._getIcon(node)} />} > {children} </Tree.TreeNode> ); } /** * Returns the appropriate icon according to the given node type. * @param node the node reference. */ private _getIcon(node: Node): string { if (node instanceof AbstractMesh) { return "vector-square.svg"; } if (node instanceof Light) { return "lightbulb.svg"; } if (node instanceof Camera) { return "camera.svg"; } return "clone.svg"; } /** * Called on the user right-clicks on a node. * @param e the event object coming from react. * @param graphNode the node being right-clicked in the tree. */ private _handleNodeContextMenu(e: React.MouseEvent, graphNode: any): void { if (graphNode.disabled) { return; } let node = this._getNodeById(graphNode.key); if (!node || node === SceneSettings.Camera) { return; } if (node instanceof Node && node.doNotSerialize) { return; } const name = node.name ?? Tools.GetConstructorName(node); const subMeshesItems: React.ReactNode[] = []; if (node instanceof Mesh && node.subMeshes?.length && node.subMeshes.length > 1) { const multiMaterial = node.material && node.material instanceof MultiMaterial ? node.material : null; subMeshesItems.push(<MenuDivider />); subMeshesItems.push(<Code>Sub-Meshes:</Code>); node.subMeshes.forEach((sm, index) => { const material = multiMaterial && sm.getMaterial(); const text = material ? (material.name ?? Tools.GetConstructorName(material)) : `Sub Mesh "${index}`; const key = `${(node as Mesh)!.id}-${index}`; const extraMenu = <MenuItem key={key} text={text} icon={<Icon src="vector-square.svg" />} onClick={() => this._editor.selectedSubMeshObservable.notifyObservers(sm)} />; subMeshesItems.push(extraMenu); }); } let mergeMeshesItem: React.ReactNode; let doNotExportItem: React.ReactNode; let lockedMeshesItem: React.ReactNode; if (this.state.selectedNodeIds) { const all = this.state.selectedNodeIds.map((id) => this._getNodeById(id)) as Mesh[]; const notAllMeshes = all.find((n) => !(n instanceof Mesh)); const notAllAbstractMeshes = all.find((n) => !(n instanceof AbstractMesh)); const notAllNodes = all.find((n) => !(n instanceof Node)); if (!notAllMeshes && all.length > 1) { mergeMeshesItem = ( <> <MenuDivider /> <MenuItem text="Merge Meshes..." onClick={() => SceneTools.MergeMeshes(this._editor, all as Mesh[])} /> </> ); } if (!notAllNodes) { all.forEach((n) => { n.metadata = n.metadata ?? { }; n.metadata.doNotExport = n.metadata.doNotExport ?? false; }); doNotExportItem = ( <> <MenuDivider /> <MenuItem text="Do Not Export" icon={(node as Node).metadata.doNotExport ? <Icon src="check.svg" /> : undefined} onClick={() => { all.forEach((n) => { n.metadata.doNotExport = !n.metadata.doNotExport; }); this.refresh(); }} /> </> ) } if (!notAllAbstractMeshes) { lockedMeshesItem = ( <> <MenuDivider /> <MenuItem text="Locked" icon={(node as Mesh).metadata?.isLocked ? <Icon src="check.svg" /> : undefined} onClick={() => { all.forEach((m) => { m.metadata = m.metadata ?? { }; m.metadata.isLocked = m.metadata.isLocked ?? false; m.metadata.isLocked = !m.metadata.isLocked; }); this.refresh(); }} /> </> ); } } // Copy paste let copyPasteTransform: React.ReactNode; if (node instanceof AbstractMesh || node instanceof Light || node instanceof Camera) { const copyTransform = (property: string) => { if (this._copiedTransform?.[property]) { const base = node![property]?.clone(); const target = this._copiedTransform[property].clone(); undoRedo.push({ description: `Changed transform information of object "${node?.["name"] ?? "undefiend"}" from "${base.toString()}" to "${target.toString()}"`, common: () => this._editor.inspector.refreshDisplay(), undo: () => node![property] = base, redo: () => node![property] = target, }); } this._editor.inspector.refreshDisplay(); }; copyPasteTransform = ( <> <MenuItem text="Copy Transform" icon="duplicate" onClick={() => this._copiedTransform = node as any} /> <MenuItem text="Paste Transform" icon="clipboard" label={`(${this._copiedTransform?.name ?? "None"})`} disabled={this._copiedTransform === null}> <MenuItem text="All" onClick={() => { copyTransform("position"); copyTransform("rotationQuaternion"); copyTransform("rotation"); copyTransform("scaling"); copyTransform("direction"); }} /> <MenuDivider /> <MenuItem text="Position" disabled={(this._copiedTransform?.["position"] ?? null) === null} onClick={() => { copyTransform("position"); }} /> <MenuItem text="Rotation" disabled={((this._copiedTransform?.["rotationQuaternion"] ?? null) || (this._copiedTransform?.["rotation"] ?? null)) === null} onClick={() => { copyTransform("rotationQuaternion"); copyTransform("rotation"); }} /> <MenuItem text="Scaling" disabled={(this._copiedTransform?.["scaling"] ?? null) === null} onClick={() => { copyTransform("scaling"); }} /> <MenuDivider /> <MenuItem text="Direction" disabled={(this._copiedTransform?.["direction"] ?? null) === null} onClick={() => { copyTransform("direction"); }} /> </MenuItem> <MenuDivider /> </> ); } ContextMenu.show( <Menu className={Classes.DARK}> <Pre> <p style={{ color: "white", marginBottom: "0px" }}>Name</p> <EditableText disabled={node instanceof Sound} value={name} intent={Intent.PRIMARY} multiline={true} confirmOnEnterKey={true} selectAllOnFocus={true} className={Classes.FILL} onConfirm={(v) => { const oldName = node!.name; undoRedo.push({ description: `Changed name of node "${node?.name ?? "undefined"}" from "${oldName}" to "${v}"`, common: () => this.refresh(), redo: () => node!.name = v, undo: () => node!.name = oldName, }); }} /> </Pre> <MenuDivider /> <MenuItem text="Clone" disabled={node instanceof Sound} icon={<Icon src="clone.svg" />} onClick={() => this._handleCloneObject()} /> <MenuDivider /> <MenuItem text="Focus..." onClick={() => this._editor.preview.focusNode(node!, false)} /> <MenuDivider /> {copyPasteTransform} <MenuItem text="Prefab"> <MenuItem text="Create Prefab..." disabled={!(node instanceof Mesh)} icon={<Icon src="plus.svg" />} onClick={() => Prefab.CreateMeshPrefab(this._editor, node as Mesh, false)} /> <MenuItem text="Create Prefab As..." disabled={!(node instanceof Mesh)} icon={<Icon src="plus.svg" />} onClick={() => Prefab.CreateMeshPrefab(this._editor, node as Mesh, true)} /> </MenuItem> <MenuItem text="Export"> <MenuItem text="Export as Babylon..." disabled={!(node instanceof Mesh)} onClick={() => SceneTools.ExportMeshToBabylonJSFormat(this._editor, node as Mesh)} /> </MenuItem> {mergeMeshesItem} {doNotExportItem} {lockedMeshesItem} <MenuDivider /> <MenuItem text="Remove" icon={<Icon src="times.svg" />} onClick={() => this._handleRemoveObject()} /> {subMeshesItems} </Menu>, { left: e.clientX, top: e.clientY } ); const selectedNodeIds = this.state.selectedNodeIds?.slice() ?? []; if (selectedNodeIds.indexOf(graphNode.key) !== -1) { return; } if (e.ctrlKey) { selectedNodeIds.push(graphNode.key); this.setState({ selectedNodeIds }); } else { this.setState({ selectedNodeIds: [graphNode.key] }); } } /** * Removes the given node from the graph and destroys its data. */ private _handleRemoveObject(): void { if (!this.state.selectedNodeIds) { return; } const selectedNodeIds = this.state.selectedNodeIds.slice(); this.state.selectedNodeIds.forEach((id) => { const node = this._getNodeById(id); if (!node) { return; } const index = selectedNodeIds.indexOf(id); if (index !== -1) { selectedNodeIds.splice(index, 1); } this.removeObject(node); }); this.refresh(() => this.setState({ selectedNodeIds })); } /** * Clones all selected nodes. */ private _handleCloneObject(): void { if (!this.state.selectedNodeIds) { return; } this.state.selectedNodeIds.forEach((id) => { const node = this._getNodeById(id); if (!node || node instanceof Sound) { return; } this.cloneObject(node); }); this.refresh(); } /** * Called on the user selects keys in the graph. */ private _handleSelectedNodes(keys: string[]): void { this.setState({ selectedNodeIds: keys }); const id = keys[keys.length - 1]; // Scene? if (id === "__editor__scene__") { this._editor.selectedSceneObservable.notifyObservers(this._editor.scene!); return; } // Skeleton? const skeleton = this._scene.skeletons.find((s) => id === `${s.name}-${s.id}`); if (skeleton) { this._editor.selectedSkeletonObservable.notifyObservers(skeleton); return; } // Node let lastSelected = this._getNodeById(id); if (!lastSelected) { return; } if (lastSelected instanceof Node) { this._editor.selectedNodeObservable.notifyObservers(lastSelected, undefined, this); } else if (lastSelected instanceof Sound) { this._editor.selectedSoundObservable.notifyObservers(lastSelected, undefined, this); } else if (lastSelected instanceof ParticleSystem) { this._editor.selectedParticleSystemObservable.notifyObservers(lastSelected, undefined, this); } this.lastSelectedObject = lastSelected; } /** * Called on the user expands given node keys. */ private _handleExpandedNode(keys: string[]): void { this.setState({ expandedNodeIds: keys }); } /** * Called on the drag event tries to enter in an existing node. */ private _handleDragEnter(_: any): void { // Nothing to do now. } /** * Called on the user starts dragging a node. */ private _handleDragStart(info: any): void { const draggedNodeId = info.node?.key; if (!draggedNodeId) { return; } if (info.event.ctrlKey) { if (this.state.selectedNodeIds?.indexOf(draggedNodeId) === -1) { this.setState({ selectedNodeIds: this.state.selectedNodeIds.concat([draggedNodeId]) }); } } else { if (this.state.selectedNodeIds?.indexOf(draggedNodeId) === -1) { this.setState({ selectedNodeIds: [draggedNodeId] }); } } const event = info.event.nativeEvent as DragEvent; if (event) { event.dataTransfer?.setData("graph/node", JSON.stringify({ nodeId: draggedNodeId, })); } } /** * Called on a node is dropped in the graph. */ private _handleDrop(info: _ITreeDropInfo): void { if (!this.state.selectedNodeIds) { return; } if (!info.dragNode) { return this._handleDropAsset(info); } const source = this._getNodeById(info.dragNode.key); if (!source) { return; } const all = this.state.selectedNodeIds.map((s) => this._getNodeById(s)).filter((n) => n) as (Node | IParticleSystem | Sound)[]; // Sound? if (info.node.key === "sounds") { all.filter((a) => a instanceof Sound).forEach((s: Sound) => { s.detachFromMesh(); s.spatialSound = false; }); return this.refresh(); } const target = this._getNodeById(info.node.key); if (!target || !(target instanceof Node)) { return; } if (info.node.dragOver) { all.forEach((n) => { if (n instanceof Node) { return (n.parent = target); } if (target instanceof AbstractMesh) { if (n instanceof ParticleSystem) { n.emitter = target; } else if (n instanceof Sound) { n.attachToMesh(target); n.spatialSound = true; } } }); } else { all.forEach((n) => { if (n instanceof Node) { return (n.parent = target.parent); } if (target.parent instanceof AbstractMesh) { if (n instanceof ParticleSystem) { n.emitter = target.parent; } else if (n instanceof Sound) { n.attachToMesh(target.parent); n.spatialSound = true; } } }); } this.refresh(); } /** * Called on an asset has been dropped on the node. */ private _handleDropAsset(info: _ITreeDropInfo): void { const ev = info.event as unknown as DragEvent; if (!ev.dataTransfer) { return; } const target = this._getNodeById(info.node.key); if (!(target instanceof Node)) { return; } let nodes = [target]; if (this.state.selectedNodeIds && this.state.selectedNodeIds.indexOf(target.id) !== -1) { nodes = this.state.selectedNodeIds .map((s) => this._getNodeById(s)) .filter((n) => n instanceof Node && nodes.indexOf(n) === -1) .concat(nodes) as Node[]; } const components = this._editor.assets.getAssetsComponents(); for (const c of components) { if (!c._id || !c._ref?.dragAndDropType) { continue; } try { const data = JSON.parse(ev.dataTransfer.getData(c._ref.dragAndDropType)) as IDragAndDroppedAssetComponentItem; if (c._id !== data.assetComponentId) { continue; } if (c._ref.onGraphDropAsset(data, nodes)) { break; } } catch (e) { // Catch silently. } } this.refresh(); } /** * Returns the node in the stage identified by the given id. * @param id the id of the node to find. */ private _getNodeById(id: string): Undefinable<Node | IParticleSystem | Sound> { const all = Tools.getAllSceneNodes(this._editor.scene!); const node = all.find((c) => c.id === id); if (node) { return node; } const ps = this._editor.scene!.getParticleSystemByID(id); if (ps) { return ps; } const sound = this._editor.scene!.mainSoundTrack.soundCollection.find((s) => s.metadata?.id === id); if (sound) { return sound; } return undefined; } }
the_stack
import { asapScheduler, animationFrameScheduler } from 'rxjs'; import { filter, take, tap, observeOn, switchMap, map, mapTo, startWith, pairwise } from 'rxjs/operators'; import { AfterViewInit, Component, ElementRef, Input, Injector, ChangeDetectionStrategy, ViewChild, ViewChildren, QueryList, AfterContentInit, ViewEncapsulation, OnChanges, OnDestroy, SimpleChanges, ChangeDetectorRef, TemplateRef, ViewContainerRef, EmbeddedViewRef, NgZone, isDevMode, forwardRef, Attribute, Optional, } from '@angular/core'; import { Direction, Directionality } from '@angular/cdk/bidi'; import { BooleanInput, coerceBooleanProperty, coerceNumberProperty, NumberInput } from '@angular/cdk/coercion'; import { CdkHeaderRowDef, CdkFooterRowDef, CdkRowDef } from '@angular/cdk/table'; import { PblNgridConfigService, PblNgridPaginatorKind, DataSourcePredicate, DataSourceFilterToken, PblNgridSortDefinition, PblDataSource, DataSourceOf, createDS, PblNgridOnDataSourceEvent, PblNgridColumnDefinitionSet, PblMetaRowDefinitions, deprecatedWarning, unrx, } from '@pebula/ngrid/core'; import { PBL_NGRID_COMPONENT } from '../tokens'; import { EXT_API_TOKEN, PblNgridExtensionApi, PblNgridInternalExtensionApi } from '../ext/grid-ext-api'; import { PblNgridPluginController, PblNgridPluginContext } from '../ext/plugin-control'; import { PblNgridRegistryService } from './registry/registry.service'; import { PblCdkTableComponent } from './pbl-cdk-table/pbl-cdk-table.component'; import { PblColumn, PblNgridColumnSet, } from './column/model'; import { PblColumnStore, ColumnApi, AutoSizeToFitOptions } from './column/management'; import { PblNgridCellContext, PblNgridMetaCellContext, PblNgridContextApi, PblNgridRowContext } from './context/index'; import { PblCdkVirtualScrollViewportComponent } from './features/virtual-scroll/virtual-scroll-viewport.component'; import { PblNgridMetaRowService } from './meta-rows/meta-row.service'; import { RowsApi } from './row'; import { createApis } from './api-factory'; export function internalApiFactory(grid: { _extApi: PblNgridExtensionApi; }) { return grid._extApi; } export function pluginControllerFactory(grid: { _plugin: PblNgridPluginContext; }) { return grid._plugin.controller; } export function metaRowServiceFactory(grid: { _extApi: PblNgridExtensionApi; }) { return grid._extApi.rowsApi.metaRowService; } declare module '../ext/types' { interface OnPropChangedSources { grid: PblNgridComponent; } interface OnPropChangedProperties { grid: Pick<PblNgridComponent, 'showFooter' | 'showHeader' | 'rowClassUpdate' | 'rowClassUpdateFreq'>; } } @Component({ selector: 'pbl-ngrid', templateUrl: './ngrid.component.html', providers: [ {provide: PBL_NGRID_COMPONENT, useExisting: PblNgridComponent}, PblNgridRegistryService, { provide: PblNgridPluginController, useFactory: pluginControllerFactory, deps: [forwardRef(() => PblNgridComponent)], }, { provide: EXT_API_TOKEN, useFactory: internalApiFactory, deps: [forwardRef(() => PblNgridComponent)], }, { provide: PblNgridMetaRowService, useFactory: metaRowServiceFactory, deps: [forwardRef(() => PblNgridComponent)], } ], changeDetection: ChangeDetectionStrategy.OnPush, encapsulation: ViewEncapsulation.None, }) export class PblNgridComponent<T = any> implements AfterContentInit, AfterViewInit, OnChanges, OnDestroy { /** * Show/Hide the header row. * Default: true */ @Input() get showHeader(): boolean { return this._showHeader; }; set showHeader(value: boolean) { this._extApi.notifyPropChanged(this, 'showHeader', this._showHeader, this._showHeader = coerceBooleanProperty(value)); } _showHeader: boolean; /** * Show/Hide the footer row. * Default: false */ @Input() get showFooter(): boolean { return this._showFooter; }; set showFooter(value: boolean) { this._extApi.notifyPropChanged(this, 'showFooter', this._showFooter, this._showFooter = coerceBooleanProperty(value)); } _showFooter: boolean; /** * When true, the filler is disabled. */ @Input() get noFiller(): boolean { return this._noFiller; }; set noFiller(value: boolean) { this._noFiller = coerceBooleanProperty(value); } _noFiller: boolean; /** * Set's the behavior of the grid when tabbing. * The default behavior is none (rows and cells are not focusable) * * Note that the focus mode has an effect on other functions, for example a detail row will toggle (open/close) using * ENTER / SPACE only when focusMode is set to `row`. */ @Input() focusMode: 'row' | 'cell' | 'none' | '' | false | undefined; /** * The grid's source of data * * @remarks * The grid's source of data, which can be provided in 2 ways: * * - DataSourceOf<T> * - PblDataSource<T> * * The grid only works with `PblDataSource<T>`, `DataSourceOf<T>` is a shortcut for providing * the data array directly. * * `DataSourceOf<T>` can be: * * - Simple data array (each object represents one grid row) * - Promise for a data array * - Stream that emits a data array each time the array changes * * When a `DataSourceOf<T>` is provided it is converted into an instance of `PblDataSource<T>`. * * To access the `PblDataSource<T>` instance use the `ds` property (readonly). * * It is highly recommended to use `PblDataSource<T>` directly, the datasource factory makes it easy. * For example, when an array is provided the factory is used to convert it to a datasource: * * ```typescript * const collection: T[] = []; * const pblDataSource = createDS<T>().onTrigger( () => collection ).create(); * ``` * * > This is a write-only (setter) property that triggers the `setDataSource` method. */ @Input() set dataSource(value: PblDataSource<T> | DataSourceOf<T>) { if (value instanceof PblDataSource) { this.setDataSource(value); } else { this.setDataSource(createDS<T>().onTrigger( () => value || [] ).create()); } } get ds(): PblDataSource<T> { return this._dataSource; }; @Input() get usePagination(): PblNgridPaginatorKind | false | '' { return this._pagination; } set usePagination(value: PblNgridPaginatorKind | false | '') { if ((value as any) === '') { value = 'pageNumber'; } if ( value !== this._pagination ) { this._pagination = value as any; this._extApi.logicaps.pagination(); } } @Input() get noCachePaginator(): boolean { return this._noCachePaginator; } set noCachePaginator(value: boolean) { value = coerceBooleanProperty(value); if (this._noCachePaginator !== value) { this._noCachePaginator = value; if (this.ds && this.ds.paginator) { this.ds.paginator.noCacheMode = value; } } } /** * The column definitions for this grid. */ @Input() columns: PblNgridColumnSet | PblNgridColumnDefinitionSet; @Input() rowClassUpdate: undefined | ( (context: PblNgridRowContext<T>) => ( string | string[] | Set<string> | { [klass: string]: any } )); @Input() rowClassUpdateFreq: 'item' | 'ngDoCheck' | 'none' = 'item'; rowFocus: 0 | '' = ''; cellFocus: 0 | '' = ''; /** * The minimum height to assign to the data viewport (where data rows are shown) * * The data viewport is the scrollable area where all data rows are visible, and some metadata rows might also be there * depending on their type (fixed/row/sticky) as well as outer section items. * * By default, the data viewport has no size and it will grow based on the available space it has left within the container. * The container will first assign height to any fixed rows and dynamic content (before/after) provided. * * If the container height is fixed (e.g. `<pbl-ngrid style="height: 500px"></pbl-ngrid>`) and there is no height left * for the data viewport then it will get no height (0 height). * * To deal with this issue there are 2 options: * * 1. Do not limit the height of the container * 2. Provide a default minimum height for the data viewport * * Option number 1 is not practical, it will disable all scrolling in the table, making it a long box scrollable by the host container. * * This is where we use option number 2. * By defining a default minimum height we ensure visibility and since there's a scroll there, the user can view all of the data. * * There are 2 types of inputs: * * A. Default minimum height in PX * B. Default minimum height in ROW COUNT * * For A, provide a positive value, for B provide a negative value. * * For example: * * - Minimum data viewport of 100 pixels: `<pbl-ngrid minDataViewHeight="100"></pbl-ngrid>` * - Minimum data viewport of 2 ros: `<pbl-ngrid minDataViewHeight="-2"></pbl-ngrid>` * * Notes when using rows: * - The row height is calculated based on an initial row pre-loaded by the grid, this row will get it's height from the CSS theme defined. * - The ROW COUNT is the lower value between the actual row count provided and the total rows to render. * * ## Container Overflow: * * Note that when using a default minimum height, if the minimum height of the data viewport PLUS the height of all other elements in the container EXCEEDS any fixed * height assigned to the container, the container will render a scrollbar which results in the possibility of 2 scrollbars, 1 for the container and the seconds * for the data viewport, if it has enough data rows. */ @Input() get minDataViewHeight(): number { return this.minDataViewHeight; } set minDataViewHeight(value: number) { value = coerceNumberProperty(value); if (this._minDataViewHeight !== value) { this._minDataViewHeight = value; } } /** * @deprecated Will be removed in v5, see `minDataViewHeight` */ @Input() get fallbackMinHeight(): number { if (typeof ngDevMode === 'undefined' || ngDevMode) { deprecatedWarning('PblNgridComponent.fallbackMinHeight', '4', 'PblNgridComponent.minDataViewHeight'); } return this._minDataViewHeight > 0 ? this._minDataViewHeight : undefined; } set fallbackMinHeight(value: number) { if (typeof ngDevMode === 'undefined' || ngDevMode) { deprecatedWarning('PblNgridComponent.fallbackMinHeight', '4', 'PblNgridComponent.minDataViewHeight'); } this.minDataViewHeight = value; } get dir(): Direction { return this._dir }; private _dir: Direction = 'ltr'; private _minDataViewHeight = 0; private _dataSource: PblDataSource<T>; @ViewChild('beforeTable', { read: ViewContainerRef, static: true }) _vcRefBeforeTable: ViewContainerRef; @ViewChild('beforeContent', { read: ViewContainerRef, static: true }) _vcRefBeforeContent: ViewContainerRef; @ViewChild('afterContent', { read: ViewContainerRef, static: true }) _vcRefAfterContent: ViewContainerRef; @ViewChild('fbTableCell', { read: TemplateRef, static: true }) _fbTableCell: TemplateRef<PblNgridCellContext<T>>; @ViewChild('fbHeaderCell', { read: TemplateRef, static: true }) _fbHeaderCell: TemplateRef<PblNgridMetaCellContext<T>>; @ViewChild('fbFooterCell', { read: TemplateRef, static: true }) _fbFooterCell: TemplateRef<PblNgridMetaCellContext<T>>; @ViewChild(CdkRowDef, { static: true }) _tableRowDef: CdkRowDef<T>; @ViewChildren(CdkHeaderRowDef) _headerRowDefs: QueryList<CdkHeaderRowDef>; @ViewChildren(CdkFooterRowDef) _footerRowDefs: QueryList<CdkFooterRowDef>; /** * When true, the virtual paging feature is enabled because the virtual content size exceed the supported height of the browser so paging is enable. */ get virtualPagingActive() { return this.viewport.virtualPagingActive; } get metaHeaderRows() { return this._store.metaHeaderRows; } get metaFooterRows() { return this._store.metaFooterRows; } get metaColumns(): PblColumnStore['metaColumns'] { return this._store.metaColumns; } get columnRowDef(): { header: PblMetaRowDefinitions; footer: PblMetaRowDefinitions; } { return { header: this._store.headerColumnDef, footer: this._store.footerColumnDef }; } /** * True when the component is initialized (after AfterViewInit) */ readonly isInit: boolean; readonly columnApi: ColumnApi<T>; readonly rowsApi: RowsApi<T>; readonly contextApi: PblNgridContextApi<T>; get viewport() { return this._viewport; } get innerTableMinWidth() { return this._cdkTable?.minWidth } private _store: PblColumnStore; private _pagination: PblNgridPaginatorKind | false; private _noCachePaginator = false; private _plugin: PblNgridPluginContext; private _extApi: PblNgridInternalExtensionApi<T>; private _cdkTable: PblCdkTableComponent<T>; private _viewport: PblCdkVirtualScrollViewportComponent; constructor(injector: Injector, vcRef: ViewContainerRef, private elRef: ElementRef<HTMLElement>, private ngZone: NgZone, private cdr: ChangeDetectorRef, private config: PblNgridConfigService, // TODO: Make private in v5 /** @deprecated Will be removed in v5 */ public registry: PblNgridRegistryService, @Attribute('id') public readonly id: string, @Optional() dir?: Directionality) { this._extApi = createApis(this, { config, registry, ngZone, injector, vcRef, elRef, cdRef: cdr, dir }); dir?.change .pipe( unrx(this, 'dir'), startWith(dir.value) ) .subscribe(value => this._dir = value); const gridConfig = config.get('table'); this.showHeader = gridConfig.showHeader; this.showFooter = gridConfig.showFooter; this.noFiller = gridConfig.noFiller; this._extApi.onConstructed(() => { this._viewport = this._extApi.viewport; this._cdkTable = this._extApi.cdkTable; }); this.contextApi = this._extApi.contextApi; this._store = this._extApi.columnStore; this._plugin = this._extApi.plugin; this.columnApi = this._extApi.columnApi; this.rowsApi = this._extApi.rowsApi; } ngAfterContentInit(): void { this._extApi.logicaps.bindRegistry(); } ngAfterViewInit(): void { this.invalidateColumns(); Object.defineProperty(this, 'isInit', { value: true }); this._plugin.emitEvent({ source: 'grid', kind: 'onInit' }); this._extApi.logicaps.pagination(); this.contextApi.focusChanged .subscribe( event => { if (event.curr) { this.rowsApi .findDataRowByIdentity(event.curr.rowIdent) ?.getCellById(this.columnApi.columnIds[event.curr.colIndex]) ?.focus(); } }); } ngOnChanges(changes: SimpleChanges): void { let processColumns = false; if (changes.focusMode) { this.rowFocus = this.focusMode === 'row' ? 0 : ''; this.cellFocus = this.focusMode === 'cell' ? 0 : ''; } if ( changes.columns && this.isInit ) { processColumns = true; } if ( processColumns === true ) { this.invalidateColumns(); this.ngZone.onStable.pipe(take(1)).subscribe(() => this.rowsApi.syncRows('all', true)); } } ngOnDestroy(): void { this._store.dispose(); const destroy = () => { this._plugin.destroy(); this.viewport.detachViewPort(); unrx.kill(this); }; let p: Promise<void>; this._plugin.emitEvent({ source: 'grid', kind: 'onDestroy', wait: (_p: Promise<void>) => p = _p }); if (p) { p.then(destroy).catch(destroy); } else { destroy(); } } trackBy(index: number, item: T): any { return index; } /** * Clear the current sort definitions. * This method is a proxy to `PblDataSource.setSort`, For more information see `PblDataSource.setSort` * * @param skipUpdate When true will not update the datasource, use this when the data comes sorted and you want to sync the definitions with the current data set. * default to false. */ setSort(skipUpdate?: boolean): void; /** * Set the sorting definition for the current data set. * * This method is a proxy to `PblDataSource.setSort` with the added sugar of providing column by string that match the `id` or `alias` properties. * For more information see `PblDataSource.setSort` * * @param columnOrAlias A column instance or a string matching `PblColumn.alias` or `PblColumn.id`. * @param skipUpdate When true will not update the datasource, use this when the data comes sorted and you want to sync the definitions with the current data set. * default to false. */ setSort(columnOrAlias: PblColumn | string, sort: PblNgridSortDefinition, skipUpdate?: boolean): void; setSort(columnOrAlias?: PblColumn | string | boolean, sort?: PblNgridSortDefinition, skipUpdate = false): void { if (!columnOrAlias || typeof columnOrAlias === 'boolean') { this.ds.setSort(!!columnOrAlias); return; } let column: PblColumn; if (typeof columnOrAlias === 'string') { column = this._store.visibleColumns.find( c => c.alias ? c.alias === columnOrAlias : (c.sort && c.id === columnOrAlias) ); if (!column && isDevMode()) { console.warn(`Could not find column with alias "${columnOrAlias}".`); return; } } else { column = columnOrAlias; } this.ds.setSort(column, sort, skipUpdate); } /** * Clear the filter definition for the current data set. * * This method is a proxy to `PblDataSource.setFilter`, For more information see `PblDataSource.setFilter`. */ setFilter(): void; /** * Set the filter definition for the current data set using a function predicate. * * This method is a proxy to `PblDataSource.setFilter` with the added sugar of providing column by string that match the `id` property. * For more information see `PblDataSource.setFilter` */ setFilter(value: DataSourcePredicate, columns?: PblColumn[] | string[]): void; /** * Set the filter definition for the current data set using a value to compare with and a list of columns with the values to compare to. * * This method is a proxy to `PblDataSource.setFilter` with the added sugar of providing column by string that match the `id` property. * For more information see `PblDataSource.setFilter` */ setFilter(value: any, columns: PblColumn[] | string[]): void; setFilter(value?: DataSourceFilterToken, columns?: PblColumn[] | string[]): void { if (arguments.length > 0) { let columnInstances: PblColumn[]; if (Array.isArray(columns) && typeof columns[0] === 'string') { columnInstances = []; for (const colId of columns) { const column = this._store.visibleColumns.find( c => c.alias ? c.alias === colId : (c.id === colId) ); if (!column && isDevMode()) { console.warn(`Could not find column with alias ${colId} "${colId}".`); return; } columnInstances.push(column); } } else { columnInstances = columns as any; } this.ds.setFilter(value, columnInstances); } else { this.ds.setFilter(); } } setDataSource(value: PblDataSource<T>): void { if (this._dataSource !== value) { // KILL ALL subscriptions for the previous datasource. if (this._dataSource) { unrx.kill(this, this._dataSource); } const prev = this._dataSource; this._dataSource = value; this._cdkTable.dataSource = value as any; this._extApi.logicaps.pagination(); this._extApi.logicaps.noData(false); if (prev?.hostGrid === this) { prev._detachEmitter(); } this._dataSource._attachEmitter(this._plugin); this._plugin.emitEvent({ source: 'ds', kind: 'onDataSource', prev, curr: value } as PblNgridOnDataSourceEvent); // clear the context, new datasource this._extApi.contextApi.clear(); if ( value ) { if (isDevMode()) { value.onError.pipe(unrx(this, value)).subscribe(console.error.bind(console)); } // We register to this event because it fires before the entire data-changing process starts. // This is required because `onRenderDataChanging` is fired async, just before the data is emitted. // Its not enough to clear the context when `setDataSource` is called, we also need to handle `refresh` calls which will not // trigger this method. value.onSourceChanging .pipe(unrx(this, value)) .subscribe( () => { if (this.config.get('table').clearContextOnSourceChanging) { this._extApi.contextApi.clear(); } }); // Run CD, scheduled as a micro-task, after each rendering value.onRenderDataChanging .pipe( filter( ({event}) => !event.isInitial && (event.pagination.changed || event.sort.changed || event.filter.changed)), // Context between the operations are not supported at the moment // Event for client side operations... // TODO: can we remove this? we clear the context with `onSourceChanging` tap( () => !this._store.primary && this._extApi.contextApi.clear() ), switchMap( () => value.onRenderedDataChanged.pipe(take(1), mapTo(this.ds.renderLength)) ), observeOn(asapScheduler), unrx(this, value) ) .subscribe( previousRenderLength => { // If the number of rendered items has changed the grid will update the data and run CD on it. // so we only update the rows. if (previousRenderLength === this.ds.renderLength) { this.rowsApi.syncRows(true); } else { this.rowsApi.syncRows('header', true); this.rowsApi.syncRows('footer', true); } }); // Handling no data overlay // Handling fallback minimum height. value.onRenderedDataChanged .pipe( map( () => this.ds.renderLength ), startWith(null), pairwise(), tap( ([prev, curr]) => { const noDataShowing = !!this._extApi.logicaps.noData.viewActive; if ( (curr > 0 && noDataShowing) || (curr === 0 && !noDataShowing) ) { this._extApi.logicaps.noData(); } }), observeOn(animationFrameScheduler), // ww want to give the browser time to remove/add rows unrx(this, value) ) .subscribe(() => { const el = this.viewport.element; if (this.ds.renderLength > 0 && this._minDataViewHeight) { let h: number; if (this._minDataViewHeight > 0) { h = Math.min(this._minDataViewHeight, this.viewport.measureRenderedContentSize()); } else { const rowHeight = this.findInitialRowHeight(); const rowCount = Math.min(this.ds.renderLength, this._minDataViewHeight * -1); h = rowHeight * rowCount; } el.style.minHeight = h + 'px'; // We need to trigger CD when not using virtual scroll or else the rows won't show on initial load, only after user interactions if (!this.viewport.enabled) { this.rowsApi.syncRows(true); } } }); } } } /** * Invalidates the header, including a full rebuild of column headers */ invalidateColumns(): void { this._plugin.emitEvent({ source: 'grid', kind: 'beforeInvalidateHeaders' }); this._extApi.contextApi.clear(); this._store.invalidate(this.columns); this._store.attachCustomCellTemplates(); this._store.attachCustomHeaderCellTemplates(); this._cdkTable.clearHeaderRowDefs(); this._cdkTable.clearFooterRowDefs(); // this.cdr.markForCheck(); this.cdr.detectChanges(); // after invalidating the headers we now have optional header/headerGroups/footer rows added // we need to update the template with this data which will create new rows (header/footer) this.resetHeaderRowDefs(); this.resetFooterRowDefs(); this.cdr.markForCheck(); // Each row will rebuild it's own cells. // This will be done in the RowsApi, which listens to `onInvalidateHeaders` this._plugin.emitEvent({ source: 'grid', kind: 'onInvalidateHeaders' }); } /** * Create an embedded view before or after the user projected content. */ createView<C>(location: 'beforeTable' | 'beforeContent' | 'afterContent', templateRef: TemplateRef<C>, context?: C, index?: number): EmbeddedViewRef<C> { const vcRef = this.getInternalVcRef(location); const view = vcRef.createEmbeddedView(templateRef, context, index); view.detectChanges(); return view; } /** * Remove an already created embedded view. * @param view - The view to remove * @param location - The location, if not set defaults to `before` * @returns true when a view was removed, false when not. (did not exist in the view container for the provided location) */ removeView(view: EmbeddedViewRef<any>, location: 'beforeTable' | 'beforeContent' | 'afterContent'): boolean { const vcRef = this.getInternalVcRef(location); const idx = vcRef.indexOf(view); if (idx === -1) { return false; } else { vcRef.remove(idx); return true; } } /** * Resize all visible columns to fit content of the grid. * @param forceFixedWidth - When true will resize all columns with absolute pixel values, otherwise will keep the same format as originally set (% or none) */ autoSizeColumnToFit(options?: AutoSizeToFitOptions): void { const { innerWidth, outerWidth } = this.viewport; // calculate auto-size on the width without scroll bar and take box model gaps into account // TODO: if no scroll bar exists the calc will not include it, next if more rows are added a scroll bar will appear... this.columnApi.autoSizeToFit(outerWidth - (outerWidth - innerWidth), options); } findInitialRowHeight(): number { let rowElement: HTMLElement; const row = this.rowsApi.findDataRowByIndex(0); if (row) { const height = getComputedStyle(row.element).height; return parseInt(height, 10); } else if (this._vcRefBeforeContent) { rowElement = this._vcRefBeforeContent.length > 0 ? (this._vcRefBeforeContent.get(0) as EmbeddedViewRef<any>).rootNodes[0] : this._vcRefBeforeContent.element.nativeElement ; rowElement = rowElement.previousElementSibling as HTMLElement; rowElement.style.display = ''; const height = getComputedStyle(rowElement).height; rowElement.style.display = 'none'; return parseInt(height, 10); } } addClass(...cls: string[]): void { for (const c of cls) { this.elRef.nativeElement.classList.add(c); } } removeClass(...cls: string[]): void { for (const c of cls) { this.elRef.nativeElement.classList.remove(c); } } private getInternalVcRef(location: 'beforeTable' | 'beforeContent' | 'afterContent'): ViewContainerRef { return location === 'beforeTable' ? this._vcRefBeforeTable : location === 'beforeContent' ? this._vcRefBeforeContent : this._vcRefAfterContent ; } private resetHeaderRowDefs(): void { if (this._headerRowDefs) { // The grid header (main, with column names) is always the last row def (index 0) // Because we want it to show last (after custom headers, group headers...) we first need to pull it and then push. this._cdkTable.clearHeaderRowDefs(); const arr = this._headerRowDefs.toArray(); arr.push(arr.shift()); for (const rowDef of arr) { this._cdkTable.addHeaderRowDef(rowDef); } } } private resetFooterRowDefs(): void { if (this._footerRowDefs) { this._cdkTable.clearFooterRowDefs(); for (const rowDef of this._footerRowDefs.toArray()) { this._cdkTable.addFooterRowDef(rowDef); } } } static ngAcceptInputType_showHeader: BooleanInput; static ngAcceptInputType_showFooter: BooleanInput; static ngAcceptInputType_noFiller: BooleanInput; static ngAcceptInputType_noCachePaginator: BooleanInput; static ngAcceptInputType_minDataViewHeight: NumberInput; }
the_stack
import { mobiscroll } from '../core/dom'; import { $, extend, MbscCoreOptions } from '../core/core'; import { MbscFrameOptions } from '../classes/frame'; import { AfterViewInit, // Component, // ContentChild, // ContentChildren, Directive, DoCheck, ElementRef, EventEmitter, // forwardRef, // Inject, Injectable, Input, // ModuleWithProviders, NgModule, NgZone, // OnChanges, OnDestroy, OnInit, // Optional, Output, // QueryList, SimpleChanges, // ViewChild, // ViewChildren, ViewContainerRef, // Injector, // ChangeDetectionStrategy, // ChangeDetectorRef } from '@angular/core'; // // angular2 import { trigger, state, animate, transition, style } from '@angular/core'; // Angular 2.x // // angular2 /* // import { trigger, state, animate, transition, style } from '@angular/animations'; // Angular 4.x // // angular2 */ import { CommonModule } from '@angular/common'; import { NgControl, ControlValueAccessor, // FormsModule } from '@angular/forms'; import { Observable } from '../util/observable'; import { MbscFormValueBase } from '../input.angular'; export class MbscRouterToken { } @Injectable() export class MbscOptionsService { private _options: any; get options(): any { return this._options; } set options(o: any) { this._options = o; } } @Injectable() export class MbscInputService { private _controlSet: boolean = false; get isControlSet(): boolean { return this._controlSet; } set isControlSet(v: boolean) { this._controlSet = v; } private _componentRef: MbscFormValueBase = undefined; get input(): MbscFormValueBase { return this._componentRef; } set input(v: MbscFormValueBase) { this._componentRef = v; } } @Injectable() export class MbscListService { private addRemoveObservable: Observable<any> = new Observable(); notifyAddRemove(item: any) { this.addRemoveObservable.next(item); } onAddRemove(): Observable<any> { return this.addRemoveObservable; } } @Directive({ selector: '[mbsc-b]' }) export class MbscBase implements AfterViewInit, OnDestroy { /** * The mobiscroll settings for the directive are passed through this input. */ @Input('mbsc-options') options: MbscCoreOptions = {}; @Input() cssClass: string; @Input() theme: string; @Input() themeVariant: 'auto' | 'dark' | 'light'; @Input() lang: string; @Input() rtl: boolean; @Input() responsive: object; @Output() onInit: EventEmitter<{ inst: any }> = new EventEmitter(); @Output() onDestroy: EventEmitter<{ inst: any }> = new EventEmitter(); inlineOptionsObj: any = {}; pendingValue: any = undefined; getInlineEvents() { for (let prop in this) { if ((this[prop] as any) instanceof (EventEmitter) && (!this.options || !((this.options as any)[prop]))) { this.inlineOptionsObj[prop] = (event: any, inst: any) => { event.inst = inst; (this[prop] as any).emit(event); }; } } } /** * Used to add theme classes to the host on components - the mbsc-input components need to have a wrapper * with that css classes for the style to work */ themeClassesSet = false; setThemeClasses() { $(this.initialElem.nativeElement).addClass(this.getThemeClasses()); this.themeClassesSet = true; } clearThemeClasses() { $(this.initialElem.nativeElement).removeClass(this.getThemeClasses()); } getThemeClasses() { let s = this.instance.settings; return 'mbsc-control-ng mbsc-' + s.theme + (s.baseTheme ? ' mbsc-' + s.baseTheme : ''); } /** * Reference to the initialized mobiscroll instance */ instance: any = null; /** * Reference to the html element the mobiscroll is initialized on. */ element: any = null; /** * Sets the element, the mobiscroll should be initialized on * The initialElement is set if an input is not found inside of it. * NOTE: Should be called after the view was initialized! */ protected setElement() { this.element = this.initialElem.nativeElement; let contentInput: any = $('input', this.initialElem.nativeElement); if (contentInput.length) { this.element = contentInput[0]; } } constructor(public initialElem: ElementRef, protected zone: NgZone) { this.inlineOptionsObj.zone = zone; } /* AfterViewInit Interface */ /** * Called after the view is initialized. * All the elements are in the DOM and ready for the initialization of the mobiscroll. */ ngAfterViewInit() { this.setElement(); this.startInit(); } startInit() { this.getInlineEvents(); let ionInput = this.getIonInput(); if (ionInput && (ionInput.getInputElement || ionInput.then) && this.element.nodeName !== "INPUT") { if (ionInput.getInputElement) { ionInput.getInputElement().then((inp: any) => { this.setElement(); this.initControl(); }); } else { // in the case of angular 9 the `ionInput` will be a promise that resolve with the ion-input instance ionInput.then((ionInpComponent: any) => { ionInpComponent .getInputElement() .then((inp: any) => { this.setElement(); this.initControl(); }); }); } } else if (!this.instance) { this.initControl(); } } /** * Returns either the ion input component, or a promise that resolves with it or falsy if there's no ion-input * * NOTE: Starting from Angular 9, the ViewContainerRef no longer has the reference to the component. The component * instance in these cases can be aquired (not officially) from the nativeElement like below (componentOnReady fn.). */ getIonInput() { const v = (this as any)._view; const native = this.initialElem.nativeElement; const ionInputNode = native.nodeName === "ION-INPUT"; const inp1 = ionInputNode && v && v._data && v._data.componentView && v._data.componentView.component; const inp2 = ionInputNode && native.componentOnReady && native.componentOnReady(); return inp1 || inp2; } initControl() { } /* OnDestroy Interface */ ngOnDestroy() { if (this.instance) { this.instance.destroy(); } } updateOptions(newOptions: any, optionChanged: boolean, invalidChanged: boolean, dataChanged: boolean) { if (optionChanged || invalidChanged) { setTimeout(() => { if (newOptions.theme && this.themeClassesSet) { this.clearThemeClasses(); } this.instance.option(newOptions, undefined, this.pendingValue); if (newOptions.theme && this.themeClassesSet) { this.setThemeClasses(); } }); } else if (dataChanged) { (this as any).refreshData((this as any).data); } else if (this.instance.redraw) { this.instance.redraw(); } } ngOnChanges(changes: SimpleChanges) { var optionChange = false, cloneChange = false, invalidChange = false, dataChange = false, newOptions: any = {}; for (var prop in changes) { if (!changes[prop].firstChange && prop !== 'options' && prop !== 'value') { if ((this as any).cloneDictionary && (this as any).cloneDictionary[prop]) { (this as any).makeClone(prop, changes[prop].currentValue); if (this.instance) { // do we need this check? this.instance.settings[prop] = changes[prop].currentValue; } if (prop == 'invalid') { invalidChange = true; } if (prop == 'data') { dataChange = true; } cloneChange = true; } else { newOptions[prop] = changes[prop].currentValue; optionChange = true; } } else if (!changes[prop].firstChange && prop !== 'value') { newOptions = extend(changes[prop].currentValue, newOptions); optionChange = true; } else if (changes[prop].firstChange) { if (prop !== 'options' && prop !== 'value') { this.inlineOptionsObj[prop] = changes[prop].currentValue; } } } if (cloneChange) { extend(newOptions, (this as any).cloneDictionary); } if (optionChange || cloneChange) { this.updateOptions(newOptions, optionChange, invalidChange, dataChange); } } } @Directive({ selector: '[mbsc-v-b]' }) export class MbscValueBase extends MbscBase { /** * This method is called when the model changes, and the new value should propagate * to mobiscroll instance. * Should be implemented by the decendant classes * @param v The new value to be set */ setNewValue(v: any): void { }; /** * Constructor for the base mobiscroll control * @param initialElem Reference to the initial element the directive is put on * @param zone Reference to the NgZone service */ constructor(initialElem: ElementRef, zone: NgZone) { super(initialElem, zone); } /** * Used to store the initial value of the model, until the mobiscroll instance is ready to take it */ initialValue: any = undefined; /** * Saves the initial value when the instance is not ready yet. * In some cases the initial value is set when there is no view yet. * This proxy function saves the initial value and calls the appropriate setNewValue. * NOTE: after the instance is created, a setVal should be called to set the initial value to the instance * @param v The new value to set (it comes from the model) */ protected setNewValueProxy(v: any) { if (!this.instance) { this.initialValue = v; } this.setNewValue(v); } } @Directive({ selector: '[mbsc-c-b]' }) export class MbscCloneBase extends MbscValueBase implements DoCheck, OnInit { constructor(initElem: ElementRef, zone: NgZone) { super(initElem, zone); } cloneDictionary: any = {}; makeClone(setting: string, value: Array<any>) { if (value) { this.cloneDictionary[setting] = []; for (let i = 0; i < value.length; i++) { this.cloneDictionary[setting].push(value[i]); } } else { this.cloneDictionary[setting] = value; } } /** * Runs in every cycle and checks if the options changed from a previous value * The previous values are cloned and stored in the cloneDictionary * Checks for options only specified in the cloneDictionary */ ngDoCheck() { let changed = false, data = false, invalid = false; for (let key in this.cloneDictionary) { if ((this as any)[key] !== undefined && !deepEqualsArray((this as any)[key], this.cloneDictionary[key])) { this.makeClone(key, (this as any)[key]); this.instance.settings[key] = (this as any)[key]; changed = true; if (key == 'invalid') { invalid = true; } if (key == 'data') { data = true; } } } if (changed && this.instance) { this.updateOptions(this.cloneDictionary, false, invalid, data); } } ngOnInit() { for (let key in this.cloneDictionary) { this.makeClone(key, (this as any)[key]); } } } @Directive({ selector: '[mbsc-cc-b]' }) export class MbscControlBase extends MbscCloneBase implements ControlValueAccessor { // Not part of settings @Input('label-style') labelStyle: 'stacked' | 'inline' | 'floating'; @Input('input-style') inputStyle: 'underline' | 'box' | 'outline'; /** * Inputs needed for manualy editing the input element */ @Input() showOnFocus: boolean; @Input() showOnTap: boolean; /** * Used to disable the control state in components */ @Input() disabled: boolean; /** * Returns an object containing the extensions of the option object */ get optionExtensions(): any { let externalOnClose = this.options && (this.options as any).onClose; let externalOnFill = this.options && (this.options as any).onFill; let onCloseEmitter = (this as any).onClose; return { onFill: (event: any, inst: any) => { // call the oldAccessor writeValue if it was overwritten if (this.oldAccessor) { this.oldAccessor.writeValue(event.valueText); } else { let ionInput = this.getIonInput(); if (ionInput) { ionInput.value = event.valueText; } } if (externalOnFill) { externalOnFill(event, inst); } }, onClose: (event: any, inst: any) => { // Call the onTouch function when the scroller closes - sets the form control touched this.onTouch(); if (externalOnClose) { externalOnClose(event, inst); } if (onCloseEmitter) { event.inst = inst; (onCloseEmitter as EventEmitter<{ inst: any }>).emit(event); } } } } get enableManualEdit(): boolean { var nsf = this.showOnFocus === false || (this.options as any).showOnFocus === false, nst = this.showOnTap === false || (this.options as any).showOnTap === false; return nsf && nst; } _needsTimeout: boolean = true; /** * This function propagates the value to the model * It's overwrittem in registerOnChange (if formControl is used) */ onChange: (value: any) => any = () => { }; /** * This function has to be called when the control is touched, to notify the validators (if formControl is used) * It's overwritter in registerOnTouched */ onTouch: (ev?: any) => any = () => { }; /** * EventEmitter for the value change * Used only without FormControl */ onChangeEmitter: EventEmitter<any> = new EventEmitter<any>(); /** * Registers the change event handler on the element * Patches the FormControl value or emits the change emitter depending on * whether the FormControl is used or not */ protected handleChange(element?: any): void { let that = this; $(element || this.element).on('change', function () { that.zone.run(function () { const elmValue = that.element.value; const instValue = that.instance._value; // the element's value cannot be null, if the element is empty, it will be an empty string // also the instance _value cannot be an empty string, bc. if the value is empty, under the hood // the _value will be set to null // SO the null and '' values are treated as equal, and there should not be a setVal call when these are to be used, // otherwise it will be an infinite loop. if (elmValue !== instValue && (instValue !== null || elmValue !== '') && that.enableManualEdit) { that.instance.setVal(elmValue, true, true); } else { let value = that.instance.getVal(); if (that.control) { if (!valueEquals(value, (that.control as any).model)) { that.onChange(value); that.control.control.patchValue(value); } } else { that.onChangeEmitter.emit(value); } } }) }); function valueEquals(v1: any, v2: any) { if (v1 === v2) { return true; } if (v1 instanceof Date && v2 instanceof Date) { return (+v1) === (+v2); } return false; } } public oldAccessor: any = null; /** * Constructs the Base Control for value changes * @param initialElement Reference to the initial element the directive is used on * @param zone Reference to the NgZone service * @param control Reference to the FormControl if used (ngModel or formControl) */ constructor(initialElement: ElementRef, zone: NgZone, protected control: NgControl, public _inputService: MbscInputService, public _view: ViewContainerRef) { super(initialElement, zone); this.overwriteAccessor(); if (_inputService) { _inputService.isControlSet = true; } } overwriteAccessor() { if (this.control) { if (this.control.valueAccessor !== this) { this.oldAccessor = this.control.valueAccessor; } this.control.valueAccessor = this; } } ngAfterViewInit() { super.ngAfterViewInit(); this.handleChange(); this.overwriteAccessor(); // Register the control again to overwrite onTouch and onChange if (this.control && (this.control as any)._setUpControl) { (this.control as any)._setUpControl(); } } /* ControlValueAccessor Interface */ registerOnChange(fn: any): void { this.onChange = fn; } registerOnTouched(fn: any): void { this.onTouch = fn; } setDisabledState(isDisabled: boolean): void { this.disabled = isDisabled; if (this.oldAccessor && this.oldAccessor.setDisabledState) { this.oldAccessor.setDisabledState(isDisabled); } if (this.instance && this.instance.disable && this.instance.enable) { if (isDisabled) { this.instance.disable(); } else { this.instance.enable(); } } } /** * Called when the model changed * @param v the new value of the model */ writeValue(v: any): void { if (this._needsTimeout) { this.pendingValue = v; setTimeout(() => { this.pendingValue = undefined; this.setNewValueProxy(v); }); } else { this.setNewValueProxy(v); } } } @Directive({ selector: '[mbsc-fr-b]' }) export class MbscFrameBase extends MbscControlBase implements OnInit { @Input() options: MbscFrameOptions; @Input() dropdown: boolean; // Settings @Input() anchor: string | HTMLElement; @Input() animate: boolean | 'fade' | 'flip' | 'pop' | 'swing' | 'slidevertical' | 'slidehorizontal' | 'slidedown' | 'slideup'; @Input() buttons: Array<any>; @Input() closeOnOverlayTap: boolean; @Input() context: string | HTMLElement; @Input() display: 'top' | 'bottom' | 'bubble' | 'inline' | 'center'; @Input() showInput: boolean; @Input() focusOnClose: boolean | string | HTMLElement; @Input() focusTrap: boolean; @Input() headerText: string | boolean | ((formattedValue: string) => string); @Input() scrollLock: boolean; @Input() touchUi: boolean; // Events @Output() onBeforeClose: EventEmitter<{ valueText: string, button: string, inst: any }> = new EventEmitter(); @Output() onBeforeShow: EventEmitter<{ inst: any }> = new EventEmitter(); @Output() onCancel: EventEmitter<{ valuteText: string, inst: any }> = new EventEmitter(); @Output() onClose: EventEmitter<{ valueText: string, inst: any }> = new EventEmitter(); @Output() onFill: EventEmitter<{ inst: any }> = new EventEmitter(); @Output() onMarkupReady: EventEmitter<{ target: HTMLElement, inst: any }> = new EventEmitter(); @Output() onPosition: EventEmitter<{ target: HTMLElement, windowWidth: number, windowHeight: number, inst: any }> = new EventEmitter(); @Output() onShow: EventEmitter<{ target: HTMLElement, valueText: string, inst: any }> = new EventEmitter(); get inline(): boolean { return (this.display || (this.options && this.options.display)) === 'inline'; } constructor(initialElem: ElementRef, zone: NgZone, control: NgControl, _inputService: MbscInputService, view: ViewContainerRef) { super(initialElem, zone, control, _inputService, view); } ngOnInit() { this.cloneDictionary.invalid = []; this.cloneDictionary.valid = []; super.ngOnInit(); } } @Directive({ selector: '[mbsc-s-b]' }) export class MbscScrollerBase extends MbscFrameBase { // Settings @Input() circular: boolean | Array<boolean>; @Input() height: number; @Input() layout: 'liquid' | 'fixed'; @Input() maxWidth: number | Array<number>; @Input() minWidth: number | Array<number>; @Input() multiline: number; @Input() readonly: boolean | Array<boolean>; @Input() rows: number; @Input() showLabel: boolean; @Input() showScrollArrows: boolean; @Input() wheels: Array<any>; @Input() width: number | Array<number>; /** Special event handler for validation * Needs to support return parameters, so it needs to be an @Input */ @Input() validate: (event: { values: Array<any>, index: number, direction: number }, inst: any) => (void | { disabled?: Array<any>, valid?: Array<any> }); // Localization settings @Input() cancelText: string; @Input() clearText: string; @Input() selectedText: string; @Input() setText: string; @Input() formatValue: (data: Array<any>) => string; @Input() parseValue: (valueText: string) => any; // Events @Output('onChange') onWheelChange: EventEmitter<{ valueText?: string, inst: any }> = new EventEmitter(); @Output() onSet: EventEmitter<{ valueText?: string, inst: any }> = new EventEmitter(); @Output() onItemTap: EventEmitter<{ inst: any }> = new EventEmitter(); @Output() onClear: EventEmitter<{ inst: any }> = new EventEmitter(); constructor(initialElement: ElementRef, zone: NgZone, control: NgControl, _inputService: MbscInputService, view: ViewContainerRef) { super(initialElement, zone, control, _inputService, view); } } @NgModule({ imports: [CommonModule], declarations: [MbscBase, MbscValueBase, MbscCloneBase, MbscControlBase], }) export class MbscBaseModule { } @NgModule({ imports: [CommonModule, MbscBaseModule], declarations: [MbscFrameBase], }) export class MbscFrameBaseModule { } @NgModule({ imports: [CommonModule, MbscFrameBaseModule], declarations: [MbscScrollerBase], }) export class MbscScrollerBaseModule { } function deepEqualsArray(a1: Array<any>, a2: Array<any>): boolean { if (a1 === a2) { return true; } else if (!a1 || !a2 || a1.length !== a2.length) { return false; } else { for (let i = 0; i < a1.length; i++) { if (a1[i] !== a2[i]) { return false; } } return true; } } function isDateEqual(d1: any, d2: any): boolean { if ((d1 && !d2) || (d2 && !d1)) { // one of them is truthy and other is not return false; } else if (!d1 && !d2) { return true; // both of them are falsy } else { return d1 && d2 && d1.toString() === d2.toString(); } } /** * Checks if the value passed is empty or the true string. * Used for determining if certain attributes are used on components. * FYI: when an attribute is used without a value, empty string is provided to this function. Ex. readonly * @param val The value of the attribute. */ function emptyOrTrue(val: any) { return (typeof (val) === 'string' && (val === 'true' || val === '')) || !!val; } const INPUT_TEMPLATE = `<mbsc-input *ngIf="!inline || showInput" [controlNg]="false" [name]="name" [theme]="theme" [themeVariant]="themeVariant" [label-style]="labelStyle" [input-style]="inputStyle" [disabled]="disabled" [dropdown]="dropdown" [placeholder]="placeholder" [error]="error" [errorMessage]="errorMessage" [icon]="inputIcon" [icon-align]="iconAlign"> <ng-content></ng-content> </mbsc-input>`; export { $, extend, mobiscroll, deepEqualsArray, isDateEqual, emptyOrTrue, INPUT_TEMPLATE, // AfterViewInit, // CommonModule, // Component, // ContentChild, // ContentChildren, // ControlValueAccessor, // Directive, // DoCheck, // ElementRef, // EventEmitter, // FormsModule, // forwardRef, // Inject, // Injectable, // Input, // ModuleWithProviders, // NgControl, // NgModule, // NgZone, Observable, // OnChanges, // OnDestroy, // OnInit, // Optional, // Output, // QueryList, // SimpleChanges, // ViewChild, // ViewChildren, // ViewContainerRef, // Injector, // ChangeDetectionStrategy, // ChangeDetectorRef, //trigger, state, animate, transition, style }
the_stack
import { INumberDictionary, Undefinable, Nullable } from "../../../../../shared/types"; import { FBXReaderNode } from "fbx-parser"; import { Geometry, VertexData, Scene, FloatArray, Vector3, Vector4, Matrix } from "babylonjs"; import { FBXUtils } from "../utils"; import { IFBXLoaderRuntime } from "../loader"; import { IFBXSkeleton } from "./skeleton"; import { Tools } from "../../../tools/tools"; interface IFBXParsedGeometryData { dataSize: number; buffer: number[]; indices: number[]; mappingType: string; referenceType: string; } interface IFBXWeightTable { id: number; weight: number; } interface IFBXBuffers { uvs: number[]; normals: number[]; indices: number[]; positions: number[]; matricesIndices: number[]; matricesWeights: number[]; } interface IFBXInBuffers { indices: number[]; positions: number[]; uvs?: IFBXParsedGeometryData; normals?: IFBXParsedGeometryData; skeleton?: IFBXSkeleton; weightTable: INumberDictionary<IFBXWeightTable[]>; } interface IFBXFaceInfo { outputBuffers: IFBXBuffers; sourceBuffers: IFBXInBuffers; faceLength: number; facePositionIndexes: number[]; faceUVs: number[]; faceNormals: number[]; faceWeights: number[]; faceWeightIndices: number[]; } export class FBXGeometry { /** * Parses all available geometries. * @param runtime defines the reference to the current FBX runtime. */ public static ParseGeometries(runtime: IFBXLoaderRuntime): void { for (const g of runtime.geometries) { const geometryId = g.prop(0, "number")!; const relationShips = runtime.connections.get(geometryId); const model = relationShips?.parents.map((p) => { return runtime.objects.nodes("Model").find((m) => m.prop(0, "number") === p.id); })[0]; const skeleton = relationShips?.children.reduce<IFBXSkeleton | undefined>((skeleton, child) => { if (runtime.cachedSkeletons[child.id] !== undefined) { skeleton = runtime.cachedSkeletons[child.id]; } return skeleton; }, undefined); let importedGeometry = runtime.cachedGeometries[geometryId]; if (!importedGeometry) { importedGeometry = this.Import(g, runtime.scene, skeleton, model); runtime.result.geometries.push(importedGeometry); runtime.cachedGeometries[geometryId] = importedGeometry; } } } /** * Imports the given Geometry node and returns its reference. * @param node defines the reference to the Geometry FBX node. * @param scene defines the reference to the scene where to add the geometry. * @param skeleton defines the optional reference to the skeleton linked to the geometry. * @returns the reference to the parsed geometry. */ public static Import(node: FBXReaderNode, scene: Scene, skeleton?: IFBXSkeleton, model?: FBXReaderNode): Geometry { const positions = node.node("Vertices")?.prop(0, "number[]"); if (!positions) { throw new Error("Failed to parse positions of geometry"); } const indices = node.node("PolygonVertexIndex")?.prop(0, "number[]"); if (!indices) { throw new Error("Failed to parse indices of geometry"); } const uvs = this._ParseUvs(node.node("LayerElementUV")); const normals = this._ParseNormals(node.node("LayerElementNormal")); const weightTable: INumberDictionary<IFBXWeightTable[]> = {}; if (skeleton) { skeleton.rawBones.forEach((bone, boneIndex) => { bone.indices.forEach((indice, indiceIndex) => { if (!weightTable[indice]) { weightTable[indice] = []; } weightTable[indice].push({ id: boneIndex, weight: bone.weights[indiceIndex], }); }); }); } const buffers = this._GenerateBuffers({ positions, indices, normals, uvs, skeleton, weightTable }); const vertexData = new VertexData(); vertexData.indices = buffers.indices; vertexData.positions = buffers.positions; if (buffers.uvs.length) { vertexData.uvs = buffers.uvs; } if (buffers.normals.length) { vertexData.normals = buffers.normals; } if (buffers.matricesIndices.length) { vertexData.matricesIndices = buffers.matricesIndices; } if (buffers.matricesWeights.length) { vertexData.matricesWeights = buffers.matricesWeights; } if (skeleton && vertexData.matricesIndices && vertexData.matricesWeights) { this._CleanWeights(skeleton, vertexData.matricesIndices as number[], vertexData.matricesWeights as number[]); this._NormalizeWeights(vertexData.matricesWeights); this._NormalizeWeights(vertexData.matricesWeightsExtra); } if (model) { const properties = model.node("Properties70")?.nodes("P") ?? []; let scale = Vector3.One(); let rotation = Vector3.Zero(); let translation = Vector3.Zero(); let eulerOrder = "ZYX"; const rotationOrder = properties.find((p) => p.prop(0, "string") === "RotationOrder"); if (rotationOrder) { eulerOrder = rotationOrder.prop(4, "string") ?? eulerOrder; } const geometricTranslation = properties.find((p) => p.prop(0, "string") === "GeometricTranslation"); if (geometricTranslation) { translation.set(geometricTranslation.prop(4, "number")!, geometricTranslation.prop(5, "number")!, geometricTranslation.prop(6, "number")!); } const geometricRotation = properties.find((p) => p.prop(0, "string") === "GeometricRotation"); if (geometricRotation) { rotation.set(geometricRotation.prop(4, "number")!, geometricRotation.prop(5, "number")!, geometricRotation.prop(6, "number")!); } const geometricScaling = properties.find((p) => p.prop(0, "string") === "GeometricScaling"); if (geometricScaling) { scale.set(geometricScaling.prop(4, "number")!, geometricScaling.prop(5, "number")!, geometricScaling.prop(6, "number")!); } const matrix = Matrix.Compose(scale, FBXUtils.GetRotationQuaternionFromVector(rotation, eulerOrder), translation); if (!matrix.isIdentity()) { vertexData.transform(matrix); } } return new Geometry(Tools.RandomId(), scene, vertexData, false); } /** * Normalizes the given skin weights buffer. */ private static _NormalizeWeights(skinWeights: Nullable<FloatArray>): void { if (!skinWeights) { return; } const vector = Vector4.Zero(); for (let i = 0, l = skinWeights.length; i < l; i++) { vector.x = skinWeights[i]; vector.y = skinWeights[i + 1]; vector.z = skinWeights[i + 2]; vector.w = skinWeights[i + 3]; const scale = 1.0 / vector.length(); if (scale !== Infinity) { vector.multiplyByFloats(scale, scale, scale, scale); } else { vector.set(1, 0, 0, 0); } skinWeights[i] = vector.x; skinWeights[i + 1] = vector.y; skinWeights[i + 2] = vector.z; skinWeights[i + 3] = vector.w; } } /** * Cleans the given weights and indices. */ private static _CleanWeights(skeleton: IFBXSkeleton, matricesIndices: number[], matricesWeights: number[]): void { const epsilon: number = 1e-3; const noInfluenceBoneIndex = skeleton.rawBones.length; let influencers = 4; let size = matricesWeights.length; for (var i = 0; i < size; i += 4) { let weight = 0.0; let firstZeroWeight = -1; for (var j = 0; j < 4; j++) { let w = matricesWeights[i + j]; weight += w; if (w < epsilon && firstZeroWeight < 0) { firstZeroWeight = j; } } if (firstZeroWeight < 0 || firstZeroWeight > influencers - 1) { firstZeroWeight = influencers - 1; } if (weight > epsilon) { let mweight = 1.0 / weight; for (var j = 0; j < 4; j++) { matricesWeights[i + j] *= mweight; } } else { if (firstZeroWeight < 4) { matricesWeights[i + firstZeroWeight] = 1.0 - weight; matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex; } } } } /** * Generates the final buffers. */ private static _GenerateBuffers(sourceBuffers: IFBXInBuffers): IFBXBuffers { const outputBuffers: IFBXBuffers = { uvs: [], indices: [], normals: [], positions: [], matricesIndices: [], matricesWeights: [], }; let faceLength = 0; let polygonIndex = 0; // these will hold data for a single face let faceUVs: number[] = []; let faceWeights: number[] = []; let faceNormals: number[] = []; let faceWeightIndices: number[] = []; let facePositionIndexes: number[] = []; sourceBuffers.indices.forEach((vertexIndex, polygonVertexIndex) => { let endOfFace = false; // Face index and vertex index arrays are combined in a single array // A cube with quad faces looks like this: // PolygonVertexIndex: *24 { // a: 0, 1, 3, -3, 2, 3, 5, -5, 4, 5, 7, -7, 6, 7, 1, -1, 1, 7, 5, -4, 6, 0, 2, -5 // } // Negative numbers mark the end of a face - first face here is 0, 1, 3, -3 // to find index of last vertex bit shift the index: ^ - 1 if (vertexIndex < 0) { vertexIndex = vertexIndex ^ -1; // equivalent to ( x * -1 ) - 1 endOfFace = true; } let weights: number[] = []; let weightIndices: number[] = []; facePositionIndexes.push(vertexIndex * 3, vertexIndex * 3 + 1, vertexIndex * 3 + 2); if (sourceBuffers.normals) { const data = this._GetData(polygonVertexIndex, polygonIndex, vertexIndex, sourceBuffers.normals); faceNormals.push(data[0], data[1], data[2]); } if (sourceBuffers.uvs) { const data = this._GetData(polygonVertexIndex, polygonIndex, vertexIndex, sourceBuffers.uvs); faceUVs.push(data[0], data[1]); } if (sourceBuffers.skeleton) { if (sourceBuffers.weightTable[vertexIndex] !== undefined) { sourceBuffers.weightTable[vertexIndex].forEach((wt) => { weights.push(wt.weight); weightIndices.push(wt.id); }); } if (weights.length > 4) { const weightIndices2 = [0, 0, 0, 0]; const weights2 = [0, 0, 0, 0]; weights.forEach(function (weight, weightIndex) { let currentWeight = weight; let currentIndex = weightIndices[weightIndex]; weights2.forEach((comparedWeight, comparedWeightIndex, comparedWeightArray) => { if (currentWeight > comparedWeight) { comparedWeightArray[comparedWeightIndex] = currentWeight; currentWeight = comparedWeight; const tmp = weightIndices2[comparedWeightIndex]; weightIndices2[comparedWeightIndex] = currentIndex; currentIndex = tmp; } }); }); weights = weights2; weightIndices = weightIndices2; } // if the weight array is shorter than 4 pad with 0s while (weights.length < 4) { weights.push(0); weightIndices.push(0); } for (let i = 0; i < 4; ++i) { faceWeights.push(weights[i]); faceWeightIndices.push(weightIndices[i]); } } faceLength++; if (endOfFace) { this._GenerateFace({ sourceBuffers, outputBuffers, facePositionIndexes, faceLength, faceUVs, faceNormals, faceWeights, faceWeightIndices }); polygonIndex++; faceLength = 0; // reset arrays for the next face faceUVs = []; faceNormals = []; faceWeights = []; faceWeightIndices = []; facePositionIndexes = []; } }); return outputBuffers; } /** * Generates a face according the to given face infos. */ private static _GenerateFace(face: IFBXFaceInfo): void { for (var i = 2; i < face.faceLength; i++) { // Positions face.outputBuffers.positions.push(-face.sourceBuffers.positions[face.facePositionIndexes[0]]); face.outputBuffers.positions.push(face.sourceBuffers.positions[face.facePositionIndexes[1]]); face.outputBuffers.positions.push(face.sourceBuffers.positions[face.facePositionIndexes[2]]); face.outputBuffers.positions.push(-face.sourceBuffers.positions[face.facePositionIndexes[(i - 1) * 3]]); face.outputBuffers.positions.push(face.sourceBuffers.positions[face.facePositionIndexes[(i - 1) * 3 + 1]]); face.outputBuffers.positions.push(face.sourceBuffers.positions[face.facePositionIndexes[(i - 1) * 3 + 2]]); face.outputBuffers.positions.push(-face.sourceBuffers.positions[face.facePositionIndexes[i * 3]]); face.outputBuffers.positions.push(face.sourceBuffers.positions[face.facePositionIndexes[i * 3 + 1]]); face.outputBuffers.positions.push(face.sourceBuffers.positions[face.facePositionIndexes[i * 3 + 2]]); // Index const index = face.outputBuffers.indices.length; face.outputBuffers.indices.push(index); face.outputBuffers.indices.push(index + 1); face.outputBuffers.indices.push(index + 2); // Normals if (face.sourceBuffers.normals) { face.outputBuffers.normals.push(-face.faceNormals[0]); face.outputBuffers.normals.push(face.faceNormals[1]); face.outputBuffers.normals.push(face.faceNormals[2]); face.outputBuffers.normals.push(-face.faceNormals[(i - 1) * 3]); face.outputBuffers.normals.push(face.faceNormals[(i - 1) * 3 + 1]); face.outputBuffers.normals.push(face.faceNormals[(i - 1) * 3 + 2]); face.outputBuffers.normals.push(-face.faceNormals[i * 3]); face.outputBuffers.normals.push(face.faceNormals[i * 3 + 1]); face.outputBuffers.normals.push(face.faceNormals[i * 3 + 2]); } // UVs if (face.sourceBuffers.uvs) { face.outputBuffers.uvs.push(face.faceUVs[0]); face.outputBuffers.uvs.push(face.faceUVs[1]); face.outputBuffers.uvs.push(face.faceUVs[(i - 1) * 2]); face.outputBuffers.uvs.push(face.faceUVs[(i - 1) * 2 + 1]); face.outputBuffers.uvs.push(face.faceUVs[i * 2]); face.outputBuffers.uvs.push(face.faceUVs[i * 2 + 1]); } // Skeleton if (face.sourceBuffers.skeleton) { face.outputBuffers.matricesWeights.push(face.faceWeights[0]); face.outputBuffers.matricesWeights.push(face.faceWeights[1]); face.outputBuffers.matricesWeights.push(face.faceWeights[2]); face.outputBuffers.matricesWeights.push(face.faceWeights[3]); face.outputBuffers.matricesWeights.push(face.faceWeights[(i - 1) * 4]); face.outputBuffers.matricesWeights.push(face.faceWeights[(i - 1) * 4 + 1]); face.outputBuffers.matricesWeights.push(face.faceWeights[(i - 1) * 4 + 2]); face.outputBuffers.matricesWeights.push(face.faceWeights[(i - 1) * 4 + 3]); face.outputBuffers.matricesWeights.push(face.faceWeights[i * 4]); face.outputBuffers.matricesWeights.push(face.faceWeights[i * 4 + 1]); face.outputBuffers.matricesWeights.push(face.faceWeights[i * 4 + 2]); face.outputBuffers.matricesWeights.push(face.faceWeights[i * 4 + 3]); face.outputBuffers.matricesIndices.push(face.faceWeightIndices[0]); face.outputBuffers.matricesIndices.push(face.faceWeightIndices[1]); face.outputBuffers.matricesIndices.push(face.faceWeightIndices[2]); face.outputBuffers.matricesIndices.push(face.faceWeightIndices[3]); face.outputBuffers.matricesIndices.push(face.faceWeightIndices[(i - 1) * 4]); face.outputBuffers.matricesIndices.push(face.faceWeightIndices[(i - 1) * 4 + 1]); face.outputBuffers.matricesIndices.push(face.faceWeightIndices[(i - 1) * 4 + 2]); face.outputBuffers.matricesIndices.push(face.faceWeightIndices[(i - 1) * 4 + 3]); face.outputBuffers.matricesIndices.push(face.faceWeightIndices[i * 4]); face.outputBuffers.matricesIndices.push(face.faceWeightIndices[i * 4 + 1]); face.outputBuffers.matricesIndices.push(face.faceWeightIndices[i * 4 + 2]); face.outputBuffers.matricesIndices.push(face.faceWeightIndices[i * 4 + 3]); } } } /** * Parses the given UVs FBX node and returns its parsed geometry data. */ private static _ParseUvs(node?: FBXReaderNode): Undefinable<IFBXParsedGeometryData> { if (!node) { return undefined; } const mappingType = node.node("MappingInformationType")?.prop(0, "string")!; const referenceType = node.node("ReferenceInformationType")?.prop(0, "string")!; const buffer = node.node("UV")?.prop(0, "number[]")!; let indices: number[] = []; if (referenceType === "IndexToDirect") { indices = node.node("UVIndex")!.prop(0, "number[]")!; } return { buffer, indices, dataSize: 2, mappingType: mappingType, referenceType: referenceType, }; } /** * Parses the given normals FBX node and returns its parsed geometry data. */ private static _ParseNormals(node?: FBXReaderNode): Undefinable<IFBXParsedGeometryData> { if (!node) { return undefined; } const mappingType = node.node("MappingInformationType")!.prop(0, "string")!; const referenceType = node.node("ReferenceInformationType")!.prop(0, "string")!; const buffer = node.node("Normals")!.prop(0, "number[]")!; let indices: number[] = []; if (referenceType === "IndexToDirect") { indices = (node.node("NormalIndex") ?? node.node("NormalsIndex"))!.prop(0, "number[]")!; } return { buffer, indices, dataSize: 3, mappingType: mappingType, referenceType: referenceType, }; } /** * Returns the data associated to the given parsed geometry data. */ private static _GetData(polygonVertexIndex: number, polygonIndex: number, vertexIndex: number, infoObject: IFBXParsedGeometryData): number[] { let index = polygonVertexIndex; switch (infoObject.mappingType) { case "ByPolygonVertex": index = polygonVertexIndex; break; case "ByPolygon": index = polygonIndex; break; case "ByVertice": index = vertexIndex; break; case "AllSame": index = infoObject.indices[0]; break; default: break; } if (infoObject.referenceType === "IndexToDirect") { index = infoObject.indices[index]; } var from = index * infoObject.dataSize; var to = from + infoObject.dataSize; return this._Slice(infoObject.buffer, from, to); } /** * Slices the given array. */ private static _Slice(b: number[], from: number, to: number): number[] { const a: number[] = []; for (var i = from, j = 0; i < to; i++, j++) { a[j] = b[i]; } return a; } }
the_stack
import { SimpleChange } from '@angular/core'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import { FormsModule } from '@angular/forms'; import { By } from '@angular/platform-browser'; import { UMLDiagramType, UMLElement, UMLModel, UMLRelationship } from '@ls1intum/apollon'; import { Feedback, FeedbackCorrectionErrorType, FeedbackType } from 'app/entities/feedback.model'; import { ModelingAssessmentComponent } from 'app/exercises/modeling/assess/modeling-assessment.component'; import { ModelingExplanationEditorComponent } from 'app/exercises/modeling/shared/modeling-explanation-editor.component'; import { ScoreDisplayComponent } from 'app/shared/score-display/score-display.component'; import { MockDirective, MockModule, MockPipe, MockProvider } from 'ng-mocks'; import { ArtemisTestModule } from '../../test.module'; import { ArtemisTranslatePipe } from 'app/shared/pipes/artemis-translate.pipe'; import { NgbTooltip } from '@ng-bootstrap/ng-bootstrap'; import { ModelElementCount } from 'app/entities/modeling-submission.model'; import { GradingInstruction } from 'app/exercises/shared/structured-grading-criterion/grading-instruction.model'; describe('ModelingAssessmentComponent', () => { let fixture: ComponentFixture<ModelingAssessmentComponent>; let comp: ModelingAssessmentComponent; let translatePipe: ArtemisTranslatePipe; const generateMockModel = (elementId: string, elementId2: string, relationshipId: string) => { return { version: '2.0.0', type: 'ClassDiagram', size: { width: 740, height: 660 }, interactive: { elements: [], relationships: [] }, elements: [ { id: elementId, name: 'Package', type: 'Package', owner: null, bounds: { x: 160, y: 40, width: 200, height: 100 }, highlight: undefined, }, { id: elementId2, name: 'Class', type: 'Class', owner: null, bounds: { x: 280, y: 320, width: 200, height: 100 }, attributes: [], methods: [], highlight: undefined, }, ], relationships: [ { id: relationshipId, name: '', type: 'ClassBidirectional', owner: null, bounds: { x: 120, y: 0, width: 265, height: 320 }, path: [ { x: 260, y: 320 }, { x: 260, y: 280 }, { x: 0, y: 280 }, { x: 0, y: 0 }, { x: 140, y: 0 }, { x: 140, y: 40 }, ], source: { direction: 'Up', element: elementId2, }, target: { direction: 'Up', element: elementId, }, } as UMLRelationship, ], assessments: [], } as UMLModel; }; const mockModel = generateMockModel('elementId1', 'elementId2', 'relationshipId'); const mockFeedbackWithReference = { text: 'FeedbackWithReference', referenceId: 'relationshipId', reference: 'reference', credits: 30, correctionStatus: 'CORRECT', } as Feedback; const mockFeedbackWithReferenceCopied = { text: 'FeedbackWithReference Copied', referenceId: 'relationshipId', reference: 'reference', credits: 35, copiedFeedbackId: 12, } as Feedback; const mockFeedbackWithoutReference = { text: 'FeedbackWithoutReference', credits: 30, type: FeedbackType.MANUAL_UNREFERENCED } as Feedback; const mockFeedbackInvalid = { text: 'FeedbackInvalid', referenceId: '4', reference: 'reference', correctionStatus: FeedbackCorrectionErrorType.INCORRECT_SCORE }; const mockValidFeedbacks = [mockFeedbackWithReference, mockFeedbackWithoutReference]; const mockFeedbacks = [...mockValidFeedbacks, mockFeedbackInvalid]; const mockFeedbackWithGradingInstruction = { text: 'FeedbackWithGradingInstruction', referenceId: 'relationshipId', reference: 'reference', credits: 30, gradingInstruction: new GradingInstruction(), } as Feedback; beforeEach(() => { TestBed.configureTestingModule({ imports: [ArtemisTestModule, MockModule(FormsModule)], declarations: [ModelingAssessmentComponent, ScoreDisplayComponent, ModelingExplanationEditorComponent, MockDirective(NgbTooltip), MockPipe(ArtemisTranslatePipe)], providers: [MockProvider(ArtemisTranslatePipe)], }) .compileComponents() .then(() => { fixture = TestBed.createComponent(ModelingAssessmentComponent); comp = fixture.componentInstance; translatePipe = fixture.debugElement.injector.get(ArtemisTranslatePipe); }); }); afterEach(() => { jest.restoreAllMocks(); }); it('should show title if any', () => { const title = 'Test Title'; comp.title = title; fixture.detectChanges(); const el = fixture.debugElement.query((de) => de.nativeElement.textContent === title); expect(el).not.toBeNull(); }); describe('score display', () => { let totalScore: number; let maxScore: number; beforeEach(() => { totalScore = 40; comp.totalScore = totalScore; maxScore = 66; comp.maxScore = maxScore; }); it('should display score display with right values', () => { comp.displayPoints = true; fixture.detectChanges(); const scoreDisplay = fixture.debugElement.query(By.directive(ScoreDisplayComponent)); expect(scoreDisplay).not.toBeNull(); expect(scoreDisplay.componentInstance.score).toEqual(totalScore); expect(scoreDisplay.componentInstance.maxPoints).toEqual(maxScore); }); it('should not display score if displayPoints wrong', () => { comp.displayPoints = false; fixture.detectChanges(); const scoreDisplay = fixture.debugElement.query(By.directive(ScoreDisplayComponent)); expect(scoreDisplay).toBeNull(); }); }); it('should display explanation editor if there is an explanation', () => { const explanation = 'Explanation'; comp.explanation = explanation; fixture.detectChanges(); const explanationEditor = fixture.debugElement.query(By.directive(ModelingExplanationEditorComponent)); expect(explanationEditor).not.toBeNull(); expect(explanationEditor.componentInstance.explanation).toEqual(explanation); expect(explanationEditor.componentInstance.readOnly).toEqual(true); }); it('should initialize apollon editor', () => { comp.umlModel = mockModel; comp.diagramType = UMLDiagramType.ClassDiagram; fixture.detectChanges(); expect(comp.apollonEditor).not.toBeNull(); }); it('should filter references', () => { comp.umlModel = mockModel; comp.readOnly = true; comp.feedbacks = mockFeedbacks; fixture.detectChanges(); expect(comp.referencedFeedbacks).toEqual([mockFeedbackWithReference]); expect(comp.unreferencedFeedbacks).toEqual([mockFeedbackWithoutReference]); expect(comp.feedbacks).toEqual(mockFeedbacks); }); it('should filter references by result feedbacks', () => { expect(comp.referencedFeedbacks).toBeEmpty(); expect(comp.feedbacks).toBe(undefined); comp.umlModel = mockModel; comp.resultFeedbacks = mockFeedbacks; expect(comp.referencedFeedbacks).toEqual([mockFeedbackWithReference, mockFeedbackInvalid]); expect(comp.feedbacks).toEqual(mockFeedbacks); }); it('should calculate drop info', () => { const spy = jest.spyOn(translatePipe, 'transform'); comp.umlModel = mockModel; comp.resultFeedbacks = [mockFeedbackWithGradingInstruction]; expect(spy).toHaveBeenCalledWith('artemisApp.assessment.messages.removeAssessmentInstructionLink'); expect(spy).toHaveBeenCalledWith('artemisApp.exercise.assessmentInstruction'); expect(spy).toHaveBeenCalledWith('artemisApp.assessment.feedbackHint'); expect(mockModel.assessments[0].dropInfo.instruction).toBe(mockFeedbackWithGradingInstruction.gradingInstruction); // toHaveBeenCalledTimes(5): 2 from calculateLabel() + 3 from calculateDropInfo() expect(spy).toHaveBeenCalledTimes(5); }); it('should update element counts', () => { function getElementCounts(model: UMLModel): ModelElementCount[] { // Not sure whether this is the correct logic to build OtherModelElementCounts. return model.elements.map((el) => ({ elementId: el.id, numberOfOtherElements: model.elements.length - 1, })); } comp.umlModel = mockModel; const elementCounts = getElementCounts(mockModel); comp.elementCounts = elementCounts; const spy = jest.spyOn(translatePipe, 'transform'); fixture.detectChanges(); elementCounts.forEach((elementCount) => expect(spy).toHaveBeenCalledWith('modelingAssessment.impactWarning', { affectedSubmissionsCount: elementCount.numberOfOtherElements }), ); expect(spy).toHaveBeenCalledTimes(elementCounts.length); }); it('should generate feedback from assessment', () => { comp.umlModel = mockModel; comp.resultFeedbacks = [mockFeedbackWithGradingInstruction]; fixture.detectChanges(); comp.generateFeedbackFromAssessment(mockModel.assessments); expect(comp.elementFeedback.get(mockFeedbackWithGradingInstruction.referenceId!)).toEqual(mockFeedbackWithGradingInstruction); }); it('should highlight elements', () => { const highlightedElements = new Map(); highlightedElements.set('elementId1', 'red'); highlightedElements.set('relationshipId', 'blue'); comp.umlModel = mockModel; comp.highlightedElements = highlightedElements; fixture.detectChanges(); expect(comp.apollonEditor).not.toBeNull(); const apollonModel = comp.apollonEditor!.model; const elements: UMLElement[] = apollonModel.elements; const highlightedElement = elements.find((el) => el.id === 'elementId1'); const notHighlightedElement = elements.find((el) => el.id === 'elementId2'); const relationship = apollonModel.relationships[0]; expect(highlightedElement).not.toBeNull(); expect(highlightedElement!.highlight).toEqual('red'); expect(notHighlightedElement).not.toBeNull(); expect(notHighlightedElement!.highlight).toBeUndefined(); expect(relationship).not.toBeNull(); expect(relationship!.highlight).toEqual('blue'); }); it('should update model', () => { const newModel = generateMockModel('newElement1', 'newElement2', 'newRelationship'); const changes = { model: { currentValue: newModel } as SimpleChange }; fixture.detectChanges(); const apollonSpy = jest.spyOn(comp.apollonEditor!, 'model', 'set'); comp.ngOnChanges(changes); expect(apollonSpy).toHaveBeenCalledWith(newModel); }); it('should update highlighted elements', () => { const highlightedElements = new Map(); highlightedElements.set('elementId2', 'green'); const changes = { highlightedElements: { currentValue: highlightedElements } as SimpleChange }; comp.umlModel = mockModel; fixture.detectChanges(); comp.highlightedElements = highlightedElements; comp.ngOnChanges(changes); expect(comp.apollonEditor).not.toBeNull(); const apollonModel = comp.apollonEditor!.model; const elements: UMLElement[] = apollonModel.elements; const highlightedElement = elements.find((el) => el.id === 'elementId2'); const notHighlightedElement = elements.find((el) => el.id === 'elementId1'); const relationship = apollonModel.relationships[0]; expect(highlightedElement).not.toBeNull(); expect(highlightedElement!.highlight).toEqual('green'); expect(notHighlightedElement).not.toBeNull(); expect(notHighlightedElement!.highlight).toBeUndefined(); expect(relationship).not.toBeNull(); expect(relationship!.highlight).toBeUndefined(); }); it('should update highlighted assessments first round', () => { const changes = { highlightDifferences: { currentValue: true } as SimpleChange }; comp.highlightDifferences = true; comp.umlModel = mockModel; fixture.detectChanges(); comp.feedbacks = [mockFeedbackWithReference]; comp.referencedFeedbacks = [mockFeedbackWithReference]; jest.spyOn(translatePipe, 'transform').mockReturnValue('Second correction round'); comp.ngOnChanges(changes); expect(comp.apollonEditor).not.toBeNull(); const apollonModel = comp.apollonEditor!.model; const assessments: any = apollonModel.assessments; expect(assessments[0].labelColor).toEqual(comp.secondCorrectionRoundColor); expect(assessments[0].label).toEqual('Second correction round'); expect(assessments[0].score).toEqual(30); }); it('should update highlighted assessments', () => { const changes = { highlightDifferences: { currentValue: true } as SimpleChange }; comp.highlightDifferences = true; comp.umlModel = mockModel; fixture.detectChanges(); comp.feedbacks = [mockFeedbackWithReferenceCopied]; comp.referencedFeedbacks = [mockFeedbackWithReferenceCopied]; jest.spyOn(translatePipe, 'transform').mockReturnValue('First correction round'); comp.ngOnChanges(changes); expect(comp.apollonEditor).not.toBeNull(); const apollonModel = comp.apollonEditor!.model; const assessments: any = apollonModel.assessments; expect(assessments[0].labelColor).toEqual(comp.firstCorrectionRoundColor); expect(assessments[0].label).toEqual('First correction round'); expect(assessments[0].score).toEqual(35); }); it('should update feedbacks', () => { const newMockFeedbackWithReference = { text: 'NewFeedbackWithReference', referenceId: 'relationshipId', reference: 'reference', credits: 30 } as Feedback; const newMockFeedbackWithoutReference = { text: 'NewFeedbackWithoutReference', credits: 30, type: FeedbackType.MANUAL_UNREFERENCED } as Feedback; const newMockFeedbackInvalid = { text: 'NewFeedbackInvalid', referenceId: '4', reference: 'reference' }; const newMockValidFeedbacks = [newMockFeedbackWithReference, newMockFeedbackWithoutReference]; const newMockFeedbacks = [...newMockValidFeedbacks, newMockFeedbackInvalid]; comp.umlModel = mockModel; comp.readOnly = true; fixture.detectChanges(); const changes = { feedbacks: { currentValue: newMockFeedbacks } as SimpleChange }; comp.ngOnChanges(changes); expect(comp.feedbacks).toEqual(newMockFeedbacks); expect(comp.referencedFeedbacks).toEqual([newMockFeedbackWithReference]); }); });
the_stack
import { describe, it, expect } from "@jest/globals"; import { NamedNode } from "@rdfjs/types"; import { DataFactory } from "n3"; import { createThing, getThing, getThingAll, setThing } from "../thing/thing"; import { addAgent, addNoneOfMatcherUrl, addAnyOfMatcherUrl, addAllOfMatcherUrl, createMatcher, getAgentAll, getNoneOfMatcherUrlAll, getAnyOfMatcherUrlAll, getAllOfMatcherUrlAll, removeNoneOfMatcherUrl, removeAnyOfMatcherUrl, removeAllOfMatcherUrl, getMatcher, hasAuthenticated, hasPublic, removeAgent, Matcher, setAgent, setAuthenticated, setNoneOfMatcherUrl, setAnyOfMatcherUrl, setPublic, setAllOfMatcherUrl, getMatcherAll, setMatcher, hasCreator, setCreator, matcherAsMarkdown, removeMatcher, getClientAll, setClient, addClient, removeClient, hasAnyClient, setAnyClient, removePublic, removeAuthenticated, removeCreator, removeAnyClient, getResourceMatcher, getResourceMatcherAll, removeResourceMatcher, setResourceMatcher, createResourceMatcherFor, } from "./matcher"; import { Policy } from "./policy"; import { createSolidDataset } from "../resource/solidDataset"; import { setUrl } from "../thing/set"; import { Thing, ThingPersisted, Url } from "../interfaces"; import { acp, rdf } from "../constants"; import { getIri, getIriAll, getSourceUrl, mockSolidDatasetFrom, } from "../index"; import { addMockAcrTo, mockAcrFor } from "./mock"; import { internal_getAcr } from "./control.internal"; import { addUrl } from "../thing/add"; import { getUrl, getUrlAll } from "../thing/get"; // Vocabulary terms const ACP_ANY = DataFactory.namedNode("http://www.w3.org/ns/solid/acp#anyOf"); const ACP_ALL = DataFactory.namedNode("http://www.w3.org/ns/solid/acp#allOf"); const ACP_NONE = DataFactory.namedNode("http://www.w3.org/ns/solid/acp#noneOf"); const RDF_TYPE = DataFactory.namedNode( "http://www.w3.org/1999/02/22-rdf-syntax-ns#type" ); const ACP_MATCHER = DataFactory.namedNode( "http://www.w3.org/ns/solid/acp#Matcher" ); const ACP_AGENT = DataFactory.namedNode("http://www.w3.org/ns/solid/acp#agent"); const ACP_CLIENT = DataFactory.namedNode( "http://www.w3.org/ns/solid/acp#client" ); const ACP_PUBLIC = DataFactory.namedNode( "http://www.w3.org/ns/solid/acp#PublicAgent" ); const ACP_AUTHENTICATED = DataFactory.namedNode( "http://www.w3.org/ns/solid/acp#AuthenticatedAgent" ); const ACP_CREATOR = DataFactory.namedNode( "http://www.w3.org/ns/solid/acp#CreatorAgent" ); const SOLID_PUBLIC_CLIENT = DataFactory.namedNode( "http://www.w3.org/ns/solid/terms#PublicOidcClient" ); // Test data const MOCKED_POLICY_IRI = DataFactory.namedNode( "https://some.pod/policy-resource#policy" ); const MOCKED_MATCHER_IRI = DataFactory.namedNode( "https://some.pod/matcher-resource#a-matcher" ); const OTHER_MOCKED_MATCHER_IRI = DataFactory.namedNode( "https://some.pod/matcher-resource#another-matcher" ); const ALLOF_MATCHER_IRI = DataFactory.namedNode( "https://some.pod/matcher-resource#allOf-matcher" ); const ANYOF_MATCHER_IRI = DataFactory.namedNode( "https://some.pod/matcher-resource#anyOf-matcher" ); const NONEOF_MATCHER_IRI = DataFactory.namedNode( "https://some.pod/matcher-resource#noneOf-matcher" ); const MOCK_WEBID_ME = DataFactory.namedNode("https://my.pod/profile#me"); const MOCK_WEBID_YOU = DataFactory.namedNode("https://your.pod/profile#you"); const MOCK_CLIENT_WEBID_1 = DataFactory.namedNode( "https://my.app/registration#it" ); const MOCK_CLIENT_WEBID_2 = DataFactory.namedNode( "https://your.app/registration#it" ); const addAllObjects = ( thing: ThingPersisted, predicate: NamedNode, objects: Url[] ): ThingPersisted => { return objects.reduce((thingAcc, object) => { return addUrl(thingAcc, predicate, object); }, thing); }; const addAllThingObjects = ( thing: ThingPersisted, predicate: NamedNode, objects: Thing[] ): ThingPersisted => { return objects.reduce((thingAcc, object) => { return addUrl(thingAcc, predicate, object); }, thing); }; const mockMatcher = ( url: Url, content?: { agents?: Url[]; public?: boolean; authenticated?: boolean; creator?: boolean; clients?: Url[]; publicClient?: boolean; } ): Matcher => { let mockedMatcher = createThing({ url: url.value, }); mockedMatcher = addUrl(mockedMatcher, RDF_TYPE, ACP_MATCHER); if (content?.agents) { mockedMatcher = addAllObjects(mockedMatcher, ACP_AGENT, content.agents); } if (content?.clients) { mockedMatcher = addAllObjects(mockedMatcher, ACP_CLIENT, content.clients); } if (content?.public) { mockedMatcher = addUrl(mockedMatcher, ACP_AGENT, ACP_PUBLIC); } if (content?.authenticated) { mockedMatcher = addUrl(mockedMatcher, ACP_AGENT, ACP_AUTHENTICATED); } if (content?.creator) { mockedMatcher = addUrl(mockedMatcher, ACP_AGENT, ACP_CREATOR); } if (content?.publicClient) { mockedMatcher = addUrl(mockedMatcher, ACP_CLIENT, SOLID_PUBLIC_CLIENT); } return mockedMatcher; }; const mockPolicy = ( url: NamedNode, matchers?: { allOf?: Matcher[]; anyOf?: Matcher[]; noneOf?: Matcher[] } ): Policy => { let mockPolicy = createThing({ url: url.value }); if (matchers?.noneOf) { mockPolicy = addAllThingObjects(mockPolicy, ACP_NONE, matchers.noneOf); } if (matchers?.anyOf) { mockPolicy = addAllThingObjects(mockPolicy, ACP_ANY, matchers.anyOf); } if (matchers?.allOf) { mockPolicy = addAllThingObjects(mockPolicy, ACP_ALL, matchers.allOf); } return mockPolicy; }; describe("addNoneOfMatcherUrl", () => { it("adds the matcher in the noneOf matchers of the policy", () => { const myPolicy = addNoneOfMatcherUrl( mockPolicy(MOCKED_POLICY_IRI), mockMatcher(MOCKED_MATCHER_IRI) ); expect(getUrlAll(myPolicy, ACP_NONE)).toContain(MOCKED_MATCHER_IRI.value); }); it("does not remove the existing noneOf matchers", () => { const mockedPolicy = mockPolicy(MOCKED_POLICY_IRI, { noneOf: [mockMatcher(OTHER_MOCKED_MATCHER_IRI)], }); const myPolicy = addNoneOfMatcherUrl( mockedPolicy, mockMatcher(MOCKED_MATCHER_IRI) ); expect(getUrlAll(myPolicy, ACP_NONE)).toContain( OTHER_MOCKED_MATCHER_IRI.value ); }); it("does not change the existing allOf and anyOf matchers", () => { const mockedPolicy = mockPolicy(MOCKED_POLICY_IRI, { anyOf: [mockMatcher(ANYOF_MATCHER_IRI)], allOf: [mockMatcher(ALLOF_MATCHER_IRI)], }); const myPolicy = addNoneOfMatcherUrl( mockedPolicy, mockMatcher(NONEOF_MATCHER_IRI) ); expect(getUrlAll(myPolicy, ACP_ALL)).toContain(ALLOF_MATCHER_IRI.value); expect(getUrlAll(myPolicy, ACP_ANY)).toContain(ANYOF_MATCHER_IRI.value); }); it("does not change the input policy", () => { const myPolicy = mockPolicy(MOCKED_POLICY_IRI); const updatedPolicy = addNoneOfMatcherUrl( myPolicy, mockMatcher(MOCKED_MATCHER_IRI) ); expect(myPolicy).not.toStrictEqual(updatedPolicy); }); }); describe("addAnyOfMatcherUrl", () => { it("adds the matcher in the anyOf matchers of the policy", () => { const myPolicy = addAnyOfMatcherUrl( mockPolicy(MOCKED_POLICY_IRI), mockMatcher(MOCKED_MATCHER_IRI) ); expect(getUrlAll(myPolicy, ACP_ANY)).toContain(MOCKED_MATCHER_IRI.value); }); it("does not remove the existing anyOf matchers", () => { const mockedPolicy = mockPolicy(MOCKED_POLICY_IRI, { anyOf: [mockMatcher(OTHER_MOCKED_MATCHER_IRI)], }); const myPolicy = addAnyOfMatcherUrl( mockedPolicy, mockMatcher(MOCKED_POLICY_IRI) ); expect(getUrlAll(myPolicy, ACP_ANY)).toContain( OTHER_MOCKED_MATCHER_IRI.value ); }); it("does not change the existing allOf and noneOf matchers", () => { const mockedPolicy = mockPolicy(MOCKED_POLICY_IRI, { noneOf: [mockMatcher(NONEOF_MATCHER_IRI)], allOf: [mockMatcher(ALLOF_MATCHER_IRI)], }); const myPolicy = addAnyOfMatcherUrl( mockedPolicy, mockMatcher(ANYOF_MATCHER_IRI) ); expect(getUrlAll(myPolicy, ACP_ALL)).toContain(ALLOF_MATCHER_IRI.value); expect(getUrlAll(myPolicy, ACP_NONE)).toContain(NONEOF_MATCHER_IRI.value); }); it("does not change the input policy", () => { const myPolicy = mockPolicy(MOCKED_POLICY_IRI); const updatedPolicy = addAnyOfMatcherUrl( myPolicy, mockMatcher(MOCKED_MATCHER_IRI) ); expect(myPolicy).not.toStrictEqual(updatedPolicy); }); }); describe("addAllOfMatcherUrl", () => { it("adds the matcher in the allOf matchers of the policy", () => { const myPolicy = addAllOfMatcherUrl( mockPolicy(MOCKED_POLICY_IRI), mockMatcher(MOCKED_MATCHER_IRI) ); expect(getUrlAll(myPolicy, ACP_ALL)).toContain(MOCKED_MATCHER_IRI.value); }); it("does not remove the existing allOf matchers", () => { const mockedPolicy = mockPolicy(MOCKED_POLICY_IRI, { allOf: [mockMatcher(OTHER_MOCKED_MATCHER_IRI)], }); const myPolicy = addAllOfMatcherUrl( mockedPolicy, mockMatcher(MOCKED_MATCHER_IRI) ); expect(getUrlAll(myPolicy, ACP_ALL)).toContain( OTHER_MOCKED_MATCHER_IRI.value ); }); it("does not change the existing anyOf and noneOf matchers", () => { const mockedPolicy = mockPolicy(MOCKED_POLICY_IRI, { noneOf: [mockMatcher(NONEOF_MATCHER_IRI)], anyOf: [mockMatcher(ANYOF_MATCHER_IRI)], }); const myPolicy = addAllOfMatcherUrl( mockedPolicy, mockMatcher(ANYOF_MATCHER_IRI) ); expect(getUrlAll(myPolicy, ACP_ANY)).toContain(ANYOF_MATCHER_IRI.value); expect(getUrlAll(myPolicy, ACP_NONE)).toContain(NONEOF_MATCHER_IRI.value); }); it("does not change the input policy", () => { const myPolicy = mockPolicy(MOCKED_POLICY_IRI); const updatedPolicy = addAnyOfMatcherUrl( myPolicy, mockMatcher(MOCKED_MATCHER_IRI) ); expect(myPolicy).not.toStrictEqual(updatedPolicy); }); }); describe("setNoneOfMatcherUrl", () => { it("sets the provided matchers as the noneOf matchers for the policy", () => { const myPolicy = setNoneOfMatcherUrl( mockPolicy(MOCKED_POLICY_IRI), mockMatcher(MOCKED_MATCHER_IRI) ); expect(getUrlAll(myPolicy, ACP_NONE)).toContain(MOCKED_MATCHER_IRI.value); }); it("removes any previous noneOf matchers for on the policy", () => { const mockedPolicy = mockPolicy(MOCKED_POLICY_IRI, { noneOf: [mockMatcher(OTHER_MOCKED_MATCHER_IRI)], }); const myPolicy = setNoneOfMatcherUrl( mockedPolicy, mockMatcher(MOCKED_MATCHER_IRI) ); expect(getUrlAll(myPolicy, ACP_NONE)).not.toContain( OTHER_MOCKED_MATCHER_IRI.value ); }); it("does not change the existing anyOf and allOf matchers on the policy", () => { const mockedPolicy = mockPolicy(MOCKED_POLICY_IRI, { anyOf: [mockMatcher(ANYOF_MATCHER_IRI)], allOf: [mockMatcher(ALLOF_MATCHER_IRI)], }); const myPolicy = setNoneOfMatcherUrl( mockedPolicy, mockMatcher(NONEOF_MATCHER_IRI) ); expect(getUrlAll(myPolicy, ACP_ALL)).toContain(ALLOF_MATCHER_IRI.value); expect(getUrlAll(myPolicy, ACP_ANY)).toContain(ANYOF_MATCHER_IRI.value); }); it("does not change the input policy", () => { const myPolicy = mockPolicy(MOCKED_POLICY_IRI); const updatedPolicy = setNoneOfMatcherUrl( myPolicy, mockMatcher(MOCKED_MATCHER_IRI) ); expect(myPolicy).not.toStrictEqual(updatedPolicy); }); }); describe("setAnyOfMatcherUrl", () => { it("sets the provided matchers as the anyOf matchers for the policy", () => { const myPolicy = setAnyOfMatcherUrl( mockPolicy(MOCKED_POLICY_IRI), mockMatcher(MOCKED_MATCHER_IRI) ); expect(getUrlAll(myPolicy, ACP_ANY)).toContain(MOCKED_MATCHER_IRI.value); }); it("removes any previous anyOf matchers for on the policy", () => { const mockedPolicy = mockPolicy(MOCKED_POLICY_IRI, { anyOf: [mockMatcher(OTHER_MOCKED_MATCHER_IRI)], }); const myPolicy = setAnyOfMatcherUrl( mockedPolicy, mockMatcher(MOCKED_MATCHER_IRI) ); expect(getUrlAll(myPolicy, ACP_ANY)).not.toContain( OTHER_MOCKED_MATCHER_IRI.value ); }); it("does not change the existing noneOf and allOf matchers on the policy", () => { const mockedPolicy = mockPolicy(MOCKED_POLICY_IRI, { noneOf: [mockMatcher(NONEOF_MATCHER_IRI)], allOf: [mockMatcher(ALLOF_MATCHER_IRI)], }); const myPolicy = setAnyOfMatcherUrl( mockedPolicy, mockMatcher(ANYOF_MATCHER_IRI) ); expect(getUrlAll(myPolicy, ACP_ALL)).toContain(ALLOF_MATCHER_IRI.value); expect(getUrlAll(myPolicy, ACP_NONE)).toContain(NONEOF_MATCHER_IRI.value); }); it("does not change the input policy", () => { const myPolicy = mockPolicy(MOCKED_POLICY_IRI); const updatedPolicy = setAnyOfMatcherUrl( myPolicy, mockMatcher(MOCKED_MATCHER_IRI) ); expect(myPolicy).not.toStrictEqual(updatedPolicy); }); }); describe("setAllOfMatcherUrl", () => { it("sets the provided matchers as the allOf matchers for the policy", () => { const myPolicy = setAllOfMatcherUrl( mockPolicy(MOCKED_POLICY_IRI), mockMatcher(MOCKED_MATCHER_IRI) ); expect(getUrlAll(myPolicy, ACP_ALL)).toContain(MOCKED_MATCHER_IRI.value); }); it("removes any previous allOf matchers for on the policy", () => { const mockedPolicy = mockPolicy(MOCKED_POLICY_IRI, { allOf: [mockMatcher(OTHER_MOCKED_MATCHER_IRI)], }); const myPolicy = setAllOfMatcherUrl( mockedPolicy, mockMatcher(MOCKED_MATCHER_IRI) ); expect(getUrlAll(myPolicy, ACP_ALL)).not.toContain( OTHER_MOCKED_MATCHER_IRI.value ); }); it("does not change the existing noneOf and anyOf matchers on the policy", () => { const mockedPolicy = mockPolicy(MOCKED_POLICY_IRI, { noneOf: [mockMatcher(NONEOF_MATCHER_IRI)], anyOf: [mockMatcher(ANYOF_MATCHER_IRI)], }); const myPolicy = setAllOfMatcherUrl( mockedPolicy, mockMatcher(ALLOF_MATCHER_IRI) ); expect(getUrlAll(myPolicy, ACP_ANY)).toContain(ANYOF_MATCHER_IRI.value); expect(getUrlAll(myPolicy, ACP_NONE)).toContain(NONEOF_MATCHER_IRI.value); }); it("does not change the input policy", () => { const myPolicy = mockPolicy(MOCKED_POLICY_IRI); const updatedPolicy = setAllOfMatcherUrl( myPolicy, mockMatcher(MOCKED_MATCHER_IRI) ); expect(myPolicy).not.toStrictEqual(updatedPolicy); }); }); describe("getNoneOfMatcherUrlAll", () => { it("returns all the noneOf matchers for the given policy", () => { const mockedPolicy = mockPolicy(MOCKED_POLICY_IRI, { noneOf: [ mockMatcher(MOCKED_MATCHER_IRI), mockMatcher(OTHER_MOCKED_MATCHER_IRI), ], }); const noneOfMatchers = getNoneOfMatcherUrlAll(mockedPolicy); expect(noneOfMatchers).toContain(MOCKED_MATCHER_IRI.value); expect(noneOfMatchers).toContain(OTHER_MOCKED_MATCHER_IRI.value); expect(noneOfMatchers).toHaveLength(2); }); it("returns only the noneOf matchers for the given policy", () => { const mockedPolicy = mockPolicy(MOCKED_POLICY_IRI, { noneOf: [mockMatcher(NONEOF_MATCHER_IRI)], anyOf: [mockMatcher(ANYOF_MATCHER_IRI)], allOf: [mockMatcher(ALLOF_MATCHER_IRI)], }); const noneOfMatchers = getNoneOfMatcherUrlAll(mockedPolicy); expect(noneOfMatchers).not.toContain(ANYOF_MATCHER_IRI.value); expect(noneOfMatchers).not.toContain(ALLOF_MATCHER_IRI.value); expect(noneOfMatchers).toHaveLength(1); }); }); describe("getAnyOfMatcherUrlAll", () => { it("returns all the anyOf matchers for the given policy", () => { const mockedPolicy = mockPolicy(MOCKED_POLICY_IRI, { anyOf: [ mockMatcher(MOCKED_MATCHER_IRI), mockMatcher(OTHER_MOCKED_MATCHER_IRI), ], }); const anyOfMatchers = getAnyOfMatcherUrlAll(mockedPolicy); expect(anyOfMatchers).toContain(MOCKED_MATCHER_IRI.value); expect(anyOfMatchers).toContain(OTHER_MOCKED_MATCHER_IRI.value); expect(anyOfMatchers).toHaveLength(2); }); it("returns only the anyOf matchers for the given policy", () => { const mockedPolicy = mockPolicy(MOCKED_POLICY_IRI, { noneOf: [mockMatcher(NONEOF_MATCHER_IRI)], anyOf: [mockMatcher(ANYOF_MATCHER_IRI)], allOf: [mockMatcher(ALLOF_MATCHER_IRI)], }); const anyOfMatchers = getAnyOfMatcherUrlAll(mockedPolicy); expect(anyOfMatchers).not.toContain(NONEOF_MATCHER_IRI.value); expect(anyOfMatchers).not.toContain(ALLOF_MATCHER_IRI.value); expect(anyOfMatchers).toHaveLength(1); }); }); describe("getAllOfMatcherUrlAll", () => { it("returns all the allOf matchers for the given policy", () => { const mockedPolicy = mockPolicy(MOCKED_POLICY_IRI, { allOf: [ mockMatcher(MOCKED_MATCHER_IRI), mockMatcher(OTHER_MOCKED_MATCHER_IRI), ], }); const allOfMatchers = getAllOfMatcherUrlAll(mockedPolicy); expect(allOfMatchers).toContain(MOCKED_MATCHER_IRI.value); expect(allOfMatchers).toContain(OTHER_MOCKED_MATCHER_IRI.value); expect(allOfMatchers).toHaveLength(2); }); it("returns only the allOf matchers for the given policy", () => { const mockedPolicy = mockPolicy(MOCKED_POLICY_IRI, { noneOf: [mockMatcher(NONEOF_MATCHER_IRI)], anyOf: [mockMatcher(ANYOF_MATCHER_IRI)], allOf: [mockMatcher(ALLOF_MATCHER_IRI)], }); const allOfMatchers = getAllOfMatcherUrlAll(mockedPolicy); expect(allOfMatchers).not.toContain(NONEOF_MATCHER_IRI.value); expect(allOfMatchers).not.toContain(ANYOF_MATCHER_IRI.value); expect(allOfMatchers).toHaveLength(1); }); }); describe("removeAllOfMatcherUrl", () => { it("removes the matcher from the allOf matchers for the given policy", () => { const mockedMatcher = mockMatcher(MOCKED_MATCHER_IRI); const mockedPolicy = mockPolicy(MOCKED_POLICY_IRI, { allOf: [mockedMatcher], }); const result = removeAllOfMatcherUrl(mockedPolicy, mockedMatcher); expect(getUrlAll(result, ACP_ALL)).not.toContain(MOCKED_MATCHER_IRI.value); }); it("does not remove the matcher from the anyOf/noneOf matchers for the given policy", () => { const mockedMatcher = mockMatcher(MOCKED_MATCHER_IRI); const mockedPolicy = mockPolicy(MOCKED_POLICY_IRI, { anyOf: [mockedMatcher], noneOf: [mockedMatcher], }); const result = removeAllOfMatcherUrl(mockedPolicy, mockedMatcher); expect(getUrlAll(result, ACP_ANY)).toContain(MOCKED_MATCHER_IRI.value); expect(getUrlAll(result, ACP_NONE)).toContain(MOCKED_MATCHER_IRI.value); }); }); describe("removeAnyOfMatcherUrl", () => { it("removes the matcher from the allOf matchers for the given policy", () => { const mockedMatcher = mockMatcher(MOCKED_MATCHER_IRI); const mockedPolicy = mockPolicy(MOCKED_POLICY_IRI, { anyOf: [mockedMatcher], }); const result = removeAnyOfMatcherUrl(mockedPolicy, mockedMatcher); expect(getUrlAll(result, ACP_ANY)).not.toContain(MOCKED_MATCHER_IRI.value); }); it("does not remove the matcher from the allOf/noneOf matchers for the given policy", () => { const mockedMatcher = mockMatcher(MOCKED_MATCHER_IRI); const mockedPolicy = mockPolicy(MOCKED_POLICY_IRI, { allOf: [mockedMatcher], noneOf: [mockedMatcher], }); const result = removeAnyOfMatcherUrl(mockedPolicy, mockedMatcher); expect(getUrlAll(result, ACP_ALL)).toContain(MOCKED_MATCHER_IRI.value); expect(getUrlAll(result, ACP_NONE)).toContain(MOCKED_MATCHER_IRI.value); }); }); describe("removeNoneOfMatcherUrl", () => { it("removes the matcher from the noneOf matchers for the given policy", () => { const mockedMatcher = mockMatcher(MOCKED_MATCHER_IRI); const mockedPolicy = mockPolicy(MOCKED_POLICY_IRI, { noneOf: [mockedMatcher], }); const result = removeNoneOfMatcherUrl(mockedPolicy, mockedMatcher); expect(getUrlAll(result, ACP_NONE)).not.toContain(MOCKED_MATCHER_IRI.value); }); it("does not remove the matcher from the allOf/anyOf matchers for the given policy", () => { const mockedMatcher = mockMatcher(MOCKED_MATCHER_IRI); const mockedPolicy = mockPolicy(MOCKED_POLICY_IRI, { allOf: [mockedMatcher], anyOf: [mockedMatcher], }); const result = removeNoneOfMatcherUrl(mockedPolicy, mockedMatcher); expect(getUrlAll(result, ACP_ALL)).toContain(MOCKED_MATCHER_IRI.value); expect(getUrlAll(result, ACP_ANY)).toContain(MOCKED_MATCHER_IRI.value); }); }); describe("createMatcher", () => { it("returns a acp:Matcher", () => { const myMatcher = createMatcher(MOCKED_MATCHER_IRI.value); expect(getUrl(myMatcher, RDF_TYPE)).toBe(ACP_MATCHER.value); }); it("returns an **empty** matcher", () => { const myMatcher = createMatcher("https://my.pod/matcher-resource#matcher"); // The matcher should only contain a type triple. expect(Object.keys(myMatcher.predicates)).toHaveLength(1); }); }); describe("createResourceMatcherFor", () => { it("returns a acp:Matcher", () => { const mockedAcr = mockAcrFor("https://some.pod/resource"); const mockedResourceWithAcr = addMockAcrTo( mockSolidDatasetFrom("https://some.pod/resource"), mockedAcr ); const myMatcher = createResourceMatcherFor( mockedResourceWithAcr, "myMatcher" ); expect(getIri(myMatcher, RDF_TYPE)).toBe(ACP_MATCHER.value); }); it("returns an **empty** matcher", () => { const mockedAcr = mockAcrFor("https://some.pod/resource"); const mockedResourceWithAcr = addMockAcrTo( mockSolidDatasetFrom("https://some.pod/resource"), mockedAcr ); const myMatcher = createResourceMatcherFor( mockedResourceWithAcr, "myMatcher" ); // The matcher should only contain a type triple. expect(Object.keys(myMatcher.predicates)).toHaveLength(1); }); }); describe("getMatcher", () => { it("returns the matcher with a matching IRI", () => { const matcher = mockMatcher(MOCKED_MATCHER_IRI); const dataset = setThing(createSolidDataset(), matcher); const result = getMatcher(dataset, MOCKED_MATCHER_IRI.value); expect(result).not.toBeNull(); }); it("does not return a Thing with a matching IRI but the wrong type", () => { const notAMatcher = createThing({ url: "https://my.pod/matcher-resource#not-a-matcher", }); const dataset = setThing( createSolidDataset(), setUrl(notAMatcher, RDF_TYPE, "http://example.org/ns#NotMatcherType") ); const result = getMatcher( dataset, "https://my.pod/matcher-resource#not-a-matcher" ); expect(result).toBeNull(); }); it("does not return a matcher with a mismatching IRI", () => { const matcher = mockMatcher(MOCKED_MATCHER_IRI); const dataset = setThing(createSolidDataset(), matcher); const result = getMatcher(dataset, OTHER_MOCKED_MATCHER_IRI); expect(result).toBeNull(); }); }); describe("getResourceMatcher", () => { it("returns the matcher with a matching name", () => { let mockedAcr = mockAcrFor("https://some.pod/resource"); let mockedMatcher = createThing({ url: `${getSourceUrl(mockedAcr)}#matcher`, }); mockedMatcher = setUrl(mockedMatcher, rdf.type, acp.Matcher); mockedAcr = setThing(mockedAcr, mockedMatcher); const mockedResourceWithAcr = addMockAcrTo( mockSolidDatasetFrom("https://some.pod/resource"), mockedAcr ); const result = getResourceMatcher(mockedResourceWithAcr, "matcher"); expect(result).not.toBeNull(); }); it("does not return a Thing with a matching IRI but the wrong type", () => { let mockedAcr = mockAcrFor("https://some.pod/resource"); let mockedMatcher = createThing({ url: `${getSourceUrl(mockedAcr)}#matcher`, }); mockedMatcher = setUrl( mockedMatcher, rdf.type, "http://example.org/ns#NotMatcherType" ); mockedAcr = setThing(mockedAcr, mockedMatcher); const mockedResourceWithAcr = addMockAcrTo( mockSolidDatasetFrom("https://some.pod/resource"), mockedAcr ); const result = getResourceMatcher(mockedResourceWithAcr, "matcher"); expect(result).toBeNull(); }); it("does not return a matcher with a mismatching IRI", () => { let mockedAcr = mockAcrFor("https://some.pod/resource"); let mockedMatcher = createThing({ url: `${getSourceUrl(mockedAcr)}#matcher`, }); mockedMatcher = setUrl(mockedMatcher, rdf.type, acp.Matcher); mockedAcr = setThing(mockedAcr, mockedMatcher); const mockedResourceWithAcr = addMockAcrTo( mockSolidDatasetFrom("https://some.pod/resource"), mockedAcr ); const result = getResourceMatcher(mockedResourceWithAcr, "other-matcher"); expect(result).toBeNull(); }); }); describe("getMatcherAll", () => { it("returns an empty array if there are no matchers in the given Dataset", () => { expect(getMatcherAll(createSolidDataset())).toHaveLength(0); }); it("returns all the matchers in a matcher resource", () => { const matcher = mockMatcher(MOCKED_MATCHER_IRI); const dataset = setThing(createSolidDataset(), matcher); let result = getMatcherAll(dataset); expect(result).toHaveLength(1); const anotherMatcher = mockMatcher(OTHER_MOCKED_MATCHER_IRI); const newDataset = setThing(dataset, anotherMatcher); result = getMatcherAll(newDataset); expect(result).toHaveLength(2); }); }); describe("getResourceMatcherAll", () => { it("returns an empty array if there are no matchers in the given Resource's ACR", () => { const mockedAcr = mockAcrFor("https://some.pod/resource"); const mockedResourceWithAcr = addMockAcrTo( mockSolidDatasetFrom("https://some.pod/resource"), mockedAcr ); expect(getResourceMatcherAll(mockedResourceWithAcr)).toHaveLength(0); }); it("returns all the matchers in a Resource's ACR", () => { let mockedAcr = mockAcrFor("https://some.pod/resource"); let mockedMatcher1 = createThing({ url: `${getSourceUrl(mockedAcr)}#matcher1`, }); mockedMatcher1 = setUrl(mockedMatcher1, rdf.type, acp.Matcher); let mockedMatcher2 = createThing({ url: `${getSourceUrl(mockedAcr)}#matcher2`, }); mockedMatcher2 = setUrl(mockedMatcher2, rdf.type, acp.Matcher); mockedAcr = setThing(mockedAcr, mockedMatcher1); mockedAcr = setThing(mockedAcr, mockedMatcher2); const mockedResourceWithAcr = addMockAcrTo( mockSolidDatasetFrom("https://some.pod/resource"), mockedAcr ); const result = getResourceMatcherAll(mockedResourceWithAcr); expect(result).toHaveLength(2); }); }); describe("removeMatcher", () => { it("removes the matcher from the given empty Dataset", () => { const matcher = mockMatcher(MOCKED_MATCHER_IRI); const dataset = setThing(createSolidDataset(), matcher); const updatedDataset = removeMatcher(dataset, MOCKED_MATCHER_IRI); expect(getThingAll(updatedDataset)).toHaveLength(0); }); }); describe("removeResourceMatcher", () => { it("removes the matcher from the given Resource's Access control Resource", () => { let mockedAcr = mockAcrFor("https://some.pod/resource"); let mockedMatcher = createThing({ url: `${getSourceUrl(mockedAcr)}#matcher`, }); mockedMatcher = setUrl(mockedMatcher, rdf.type, acp.Matcher); mockedAcr = setThing(mockedAcr, mockedMatcher); const mockedResourceWithAcr = addMockAcrTo( mockSolidDatasetFrom("https://some.pod/resource"), mockedAcr ); const updatedDataset = removeResourceMatcher( mockedResourceWithAcr, mockedMatcher ); expect(getResourceMatcherAll(updatedDataset)).toHaveLength(0); }); it("accepts a plain name to remove a matcher", () => { let mockedAcr = mockAcrFor("https://some.pod/resource"); let mockedMatcher = createThing({ url: `${getSourceUrl(mockedAcr)}#matcher`, }); mockedMatcher = setUrl(mockedMatcher, rdf.type, acp.Matcher); mockedAcr = setThing(mockedAcr, mockedMatcher); const mockedResourceWithAcr = addMockAcrTo( mockSolidDatasetFrom("https://some.pod/resource"), mockedAcr ); const updatedDataset = removeResourceMatcher( mockedResourceWithAcr, "matcher" ); expect(getResourceMatcherAll(updatedDataset)).toHaveLength(0); }); it("accepts a full URL to remove a matcher", () => { let mockedAcr = mockAcrFor("https://some.pod/resource"); let mockedMatcher = createThing({ url: `${getSourceUrl(mockedAcr)}#matcher`, }); mockedMatcher = setUrl(mockedMatcher, rdf.type, acp.Matcher); mockedAcr = setThing(mockedAcr, mockedMatcher); const mockedResourceWithAcr = addMockAcrTo( mockSolidDatasetFrom("https://some.pod/resource"), mockedAcr ); const updatedDataset = removeResourceMatcher( mockedResourceWithAcr, `${getSourceUrl(mockedAcr)}#matcher` ); expect(getResourceMatcherAll(updatedDataset)).toHaveLength(0); }); it("accepts a Named Node to remove a matcher", () => { let mockedAcr = mockAcrFor("https://some.pod/resource"); let mockedMatcher = createThing({ url: `${getSourceUrl(mockedAcr)}#matcher`, }); mockedMatcher = setUrl(mockedMatcher, rdf.type, acp.Matcher); mockedAcr = setThing(mockedAcr, mockedMatcher); const mockedResourceWithAcr = addMockAcrTo( mockSolidDatasetFrom("https://some.pod/resource"), mockedAcr ); const updatedDataset = removeResourceMatcher( mockedResourceWithAcr, DataFactory.namedNode(`${getSourceUrl(mockedAcr)}#matcher`) ); expect(getResourceMatcherAll(updatedDataset)).toHaveLength(0); }); it("does not remove a non-matcher with the same name", () => { let mockedAcr = mockAcrFor("https://some.pod/resource"); let mockedMatcher = createThing({ url: `${getSourceUrl(mockedAcr)}#matcher`, }); mockedMatcher = setUrl( mockedMatcher, rdf.type, "https://example.vocab/not-a-matcher" ); mockedAcr = setThing(mockedAcr, mockedMatcher); const mockedResourceWithAcr = addMockAcrTo( mockSolidDatasetFrom("https://some.pod/resource"), mockedAcr ); const updatedDataset = removeResourceMatcher( mockedResourceWithAcr, "matcher" ); const updatedAcr = internal_getAcr(updatedDataset); expect( getThing(updatedAcr, `${getSourceUrl(mockedAcr)}#matcher`) ).not.toBeNull(); }); }); describe("setMatcher", () => { it("sets the matcher in the given empty Dataset", () => { const matcher = mockMatcher(MOCKED_MATCHER_IRI); const dataset = setMatcher(createSolidDataset(), matcher); const result = getThing(dataset, MOCKED_MATCHER_IRI); expect(result).not.toBeNull(); expect(getIriAll(result as Thing, rdf.type)).toContain(acp.Matcher); }); }); describe("setResourceMatcher", () => { it("sets the matcher in the given Resource's ACR", () => { const mockedAcr = mockAcrFor("https://some.pod/resource"); const mockedResourceWithAcr = addMockAcrTo( mockSolidDatasetFrom("https://some.pod/resource"), mockedAcr ); let mockedMatcher = createThing({ url: `${getSourceUrl(mockedAcr)}#matcher`, }); mockedMatcher = setUrl(mockedMatcher, rdf.type, acp.Matcher); const updatedResource = setResourceMatcher( mockedResourceWithAcr, mockedMatcher ); expect(getResourceMatcherAll(updatedResource)).toHaveLength(1); }); }); describe("getAgentAll", () => { it("returns all the agents a matcher applies to by WebID", () => { const matcher = mockMatcher(MOCKED_MATCHER_IRI, { agents: [MOCK_WEBID_ME, MOCK_WEBID_YOU], }); const agents = getAgentAll(matcher); expect(agents).toContain(MOCK_WEBID_ME.value); expect(agents).toContain(MOCK_WEBID_YOU.value); expect(agents).toHaveLength(2); }); it("does not return the public/authenticated/creator/clients a matcher applies to", () => { const matcher = mockMatcher(MOCKED_MATCHER_IRI, { public: true, authenticated: true, creator: true, clients: [MOCK_CLIENT_WEBID_1], }); const agents = getAgentAll(matcher); expect(agents).not.toContain(ACP_CREATOR.value); expect(agents).not.toContain(ACP_AUTHENTICATED.value); expect(agents).not.toContain(ACP_PUBLIC.value); expect(agents).toHaveLength(0); }); }); describe("setAgent", () => { it("sets the given agents for the matcher", () => { const matcher = mockMatcher(MOCKED_MATCHER_IRI); const result = setAgent(matcher, MOCK_WEBID_ME.value); expect(getUrlAll(result, ACP_AGENT)).toContain(MOCK_WEBID_ME.value); }); it("deletes any agents previously set for the matcher", () => { const matcher = mockMatcher(MOCKED_MATCHER_IRI, { agents: [MOCK_WEBID_YOU], }); const result = setAgent(matcher, MOCK_WEBID_ME.value); expect(getUrlAll(result, ACP_AGENT)).toContain(MOCK_WEBID_ME.value); expect(getUrlAll(result, ACP_AGENT)).not.toContain(MOCK_WEBID_YOU.value); }); it("does not change the input matcher", () => { const matcher = mockMatcher(MOCKED_MATCHER_IRI, { agents: [MOCK_WEBID_YOU], }); setAgent(matcher, MOCK_WEBID_ME.value); expect(getUrlAll(matcher, ACP_AGENT)).not.toContain(MOCK_WEBID_ME.value); expect(getUrlAll(matcher, ACP_AGENT)).toContain(MOCK_WEBID_YOU.value); }); it("does not overwrite public, authenticated and creator agents", () => { const matcher = mockMatcher(MOCKED_MATCHER_IRI, { public: true, authenticated: true, creator: true, }); const result = setAgent(matcher, MOCK_WEBID_YOU.value); expect(getUrlAll(result, ACP_AGENT)).toContain(ACP_PUBLIC.value); expect(getUrlAll(result, ACP_AGENT)).toContain(ACP_AUTHENTICATED.value); expect(getUrlAll(result, ACP_AGENT)).toContain(ACP_CREATOR.value); }); }); describe("addAgent", () => { it("adds the given agent to the matcher", () => { const matcher = mockMatcher(MOCKED_MATCHER_IRI); const result = addAgent(matcher, MOCK_WEBID_YOU.value); expect(getUrlAll(result, ACP_AGENT)).toContain(MOCK_WEBID_YOU.value); }); it("does not override existing agents/public/authenticated", () => { const matcher = mockMatcher(MOCKED_MATCHER_IRI, { agents: [MOCK_WEBID_ME], public: true, authenticated: true, }); const result = addAgent(matcher, MOCK_WEBID_YOU.value); expect(getUrlAll(result, ACP_AGENT)).toContain(MOCK_WEBID_ME.value); expect(getUrlAll(result, ACP_AGENT)).toContain(MOCK_WEBID_YOU.value); expect(getUrlAll(result, ACP_AGENT)).toContain(ACP_PUBLIC.value); expect(getUrlAll(result, ACP_AGENT)).toContain(ACP_AUTHENTICATED.value); }); }); describe("removeAgent", () => { it("removes the given agent from the matcher", () => { const matcher = mockMatcher(MOCKED_MATCHER_IRI, { agents: [MOCK_WEBID_YOU], }); const result = removeAgent(matcher, MOCK_WEBID_YOU.value); expect(getUrlAll(result, ACP_AGENT)).not.toContain(MOCK_WEBID_YOU.value); }); it("does not delete unrelated agents", () => { const matcher = mockMatcher(MOCKED_MATCHER_IRI, { agents: [MOCK_WEBID_ME, MOCK_WEBID_YOU], public: true, authenticated: true, }); const result = removeAgent(matcher, MOCK_WEBID_YOU.value); expect(getUrlAll(result, ACP_AGENT)).not.toContain(MOCK_WEBID_YOU.value); expect(getUrlAll(result, ACP_AGENT)).toContain(MOCK_WEBID_ME.value); expect(getUrlAll(result, ACP_AGENT)).toContain(ACP_PUBLIC.value); expect(getUrlAll(result, ACP_AGENT)).toContain(ACP_AUTHENTICATED.value); }); }); describe("hasPublic", () => { it("returns true if the matcher applies to the public agent", () => { const matcher = mockMatcher(MOCKED_MATCHER_IRI, { public: true, }); expect(hasPublic(matcher)).toBe(true); }); it("returns false if the matcher only applies to other agent", () => { const matcher = mockMatcher(MOCKED_MATCHER_IRI, { public: false, authenticated: true, agents: [MOCK_WEBID_ME], }); expect(hasPublic(matcher)).toBe(false); }); }); describe("setPublic", () => { it("applies the given matcher to the public agent", () => { const matcher = mockMatcher(MOCKED_MATCHER_IRI); const result = setPublic(matcher); expect(getUrlAll(result, ACP_AGENT)).toContain(ACP_PUBLIC.value); }); it("does not change the input matcher", () => { const matcher = mockMatcher(MOCKED_MATCHER_IRI); setPublic(matcher); expect(getUrlAll(matcher, ACP_AGENT)).not.toContain(ACP_PUBLIC.value); }); it("does not change the other agents", () => { const matcher = mockMatcher(MOCKED_MATCHER_IRI, { authenticated: true, agents: [MOCK_WEBID_ME], }); const result = setPublic(matcher); expect(getUrlAll(result, ACP_AGENT)).toContain(ACP_AUTHENTICATED.value); expect(getUrlAll(result, ACP_AGENT)).toContain(MOCK_WEBID_ME.value); }); it("throws an error when you attempt to use the deprecated API", () => { const matcher = mockMatcher(MOCKED_MATCHER_IRI); expect( // @ts-expect-error The type signature should warn about passing a second argument: () => setPublic(matcher, true) ).toThrow( "The function `setPublic` no longer takes a second parameter. It is now used together with `removePublic` instead." ); }); }); describe("removePublic", () => { it("prevents the matcher from applying to the public agent", () => { const matcher = mockMatcher(MOCKED_MATCHER_IRI, { public: true, }); const result = removePublic(matcher); expect(getUrlAll(result, ACP_AGENT)).not.toContain(ACP_PUBLIC.value); }); it("does not change the input matcher", () => { const matcher = mockMatcher(MOCKED_MATCHER_IRI, { public: true }); removePublic(matcher); expect(getUrlAll(matcher, ACP_AGENT)).toContain(ACP_PUBLIC.value); }); it("does not change the other agents", () => { const matcher = mockMatcher(MOCKED_MATCHER_IRI, { authenticated: true, agents: [MOCK_WEBID_ME], public: true, }); const result = removePublic(matcher); expect(getUrlAll(result, ACP_AGENT)).toContain(ACP_AUTHENTICATED.value); expect(getUrlAll(result, ACP_AGENT)).toContain(MOCK_WEBID_ME.value); }); }); describe("hasAuthenticated", () => { it("returns true if the matcher applies to authenticated agents", () => { const matcher = mockMatcher(MOCKED_MATCHER_IRI, { authenticated: true, }); expect(hasAuthenticated(matcher)).toBe(true); }); it("returns false if the matcher only applies to other agent", () => { const matcher = mockMatcher(MOCKED_MATCHER_IRI, { public: true, authenticated: false, agents: [MOCK_WEBID_ME], }); expect(hasAuthenticated(matcher)).toBe(false); }); }); describe("setAuthenticated", () => { it("applies to given matcher to authenticated agents", () => { const matcher = mockMatcher(MOCKED_MATCHER_IRI); const result = setAuthenticated(matcher); expect(getUrlAll(result, ACP_AGENT)).toContain(ACP_AUTHENTICATED.value); }); it("does not change the input matcher", () => { const matcher = mockMatcher(MOCKED_MATCHER_IRI); setAuthenticated(matcher); expect(getUrlAll(matcher, ACP_AGENT)).not.toContain( ACP_AUTHENTICATED.value ); }); it("does not change the other agents", () => { const matcher = mockMatcher(MOCKED_MATCHER_IRI, { public: true, agents: [MOCK_WEBID_ME], }); const result = setAuthenticated(matcher); expect(getUrlAll(result, ACP_AGENT)).toContain(ACP_PUBLIC.value); expect(getUrlAll(result, ACP_AGENT)).toContain(MOCK_WEBID_ME.value); }); it("throws an error when you attempt to use the deprecated API", () => { const matcher = mockMatcher(MOCKED_MATCHER_IRI); expect( // @ts-expect-error The type signature should warn about passing a second argument: () => setAuthenticated(matcher, true) ).toThrow( "The function `setAuthenticated` no longer takes a second parameter. It is now used together with `removeAuthenticated` instead." ); }); }); describe("removeAuthenticated", () => { it("prevents the matcher from applying to authenticated agents", () => { const matcher = mockMatcher(MOCKED_MATCHER_IRI, { authenticated: true, }); const result = removeAuthenticated(matcher); expect(getUrlAll(result, ACP_AGENT)).not.toContain(ACP_AUTHENTICATED.value); }); it("does not change the input matcher", () => { const matcher = mockMatcher(MOCKED_MATCHER_IRI, { authenticated: true }); removeAuthenticated(matcher); expect(getUrlAll(matcher, ACP_AGENT)).toContain(ACP_AUTHENTICATED.value); }); it("does not change the other agents", () => { const matcher = mockMatcher(MOCKED_MATCHER_IRI, { public: true, authenticated: true, agents: [MOCK_WEBID_ME], }); const result = removeAuthenticated(matcher); expect(getUrlAll(result, ACP_AGENT)).toContain(ACP_PUBLIC.value); expect(getUrlAll(result, ACP_AGENT)).toContain(MOCK_WEBID_ME.value); }); }); describe("hasCreator", () => { it("returns true if the matcher applies to the Resource's creator", () => { const matcher = mockMatcher(MOCKED_MATCHER_IRI, { creator: true, }); expect(hasCreator(matcher)).toBe(true); }); it("returns false if the matcher only applies to other agents", () => { const matcher = mockMatcher(MOCKED_MATCHER_IRI, { public: true, creator: false, agents: [MOCK_WEBID_ME], }); expect(hasCreator(matcher)).toBe(false); }); }); describe("setCreator", () => { it("applies the given matcher to the Resource's creator", () => { const matcher = mockMatcher(MOCKED_MATCHER_IRI); const result = setCreator(matcher); expect(getUrlAll(result, ACP_AGENT)).toContain(ACP_CREATOR.value); }); it("does not change the input matcher", () => { const matcher = mockMatcher(MOCKED_MATCHER_IRI); setCreator(matcher); expect(getUrlAll(matcher, ACP_AGENT)).not.toContain(ACP_CREATOR.value); }); it("does not change the other agents", () => { const matcher = mockMatcher(MOCKED_MATCHER_IRI, { public: true, agents: [MOCK_WEBID_ME], }); const result = setCreator(matcher); expect(getUrlAll(result, ACP_AGENT)).toContain(ACP_PUBLIC.value); expect(getUrlAll(result, ACP_AGENT)).toContain(MOCK_WEBID_ME.value); }); it("throws an error when you attempt to use the deprecated API", () => { const matcher = mockMatcher(MOCKED_MATCHER_IRI); expect( // @ts-expect-error The type signature should warn about passing a second argument: () => setCreator(matcher, true) ).toThrow( "The function `setCreator` no longer takes a second parameter. It is now used together with `removeCreator` instead." ); }); }); describe("removeCreator", () => { it("prevents the matcher from applying to the Resource's creator", () => { const matcher = mockMatcher(MOCKED_MATCHER_IRI, { creator: true, }); const result = removeCreator(matcher); expect(getUrlAll(result, ACP_AGENT)).not.toContain(ACP_CREATOR.value); }); it("does not change the input matcher", () => { const matcher = mockMatcher(MOCKED_MATCHER_IRI, { creator: true }); removeCreator(matcher); expect(getUrlAll(matcher, ACP_AGENT)).toContain(ACP_CREATOR.value); }); it("does not change the other agents", () => { const matcher = mockMatcher(MOCKED_MATCHER_IRI, { creator: true, public: true, agents: [MOCK_WEBID_ME], }); const result = removeCreator(matcher); expect(getUrlAll(result, ACP_AGENT)).toContain(ACP_PUBLIC.value); expect(getUrlAll(result, ACP_AGENT)).toContain(MOCK_WEBID_ME.value); }); }); describe("getClientAll", () => { it("returns all the clients a matcher applies to by WebID", () => { const matcher = mockMatcher(MOCKED_MATCHER_IRI, { clients: [MOCK_CLIENT_WEBID_1, MOCK_CLIENT_WEBID_2], }); const clients = getClientAll(matcher); expect(clients).toContain(MOCK_CLIENT_WEBID_1.value); expect(clients).toContain(MOCK_CLIENT_WEBID_2.value); expect(clients).toHaveLength(2); }); it("does not return the agents/public client a matcher applies to", () => { const matcher = mockMatcher(MOCKED_MATCHER_IRI, { agents: [MOCK_WEBID_ME], public: true, authenticated: true, creator: true, publicClient: true, }); const clients = getClientAll(matcher); expect(clients).not.toContain(ACP_CREATOR.value); expect(clients).not.toContain(ACP_AUTHENTICATED.value); expect(clients).not.toContain(ACP_PUBLIC.value); expect(clients).toHaveLength(0); }); }); describe("setClient", () => { it("sets the given clients for the matcher", () => { const matcher = mockMatcher(MOCKED_MATCHER_IRI); const result = setClient(matcher, MOCK_CLIENT_WEBID_1.value); expect(getUrlAll(result, ACP_CLIENT)).toContain(MOCK_CLIENT_WEBID_1.value); }); it("deletes any clients previously set for the matcher", () => { const matcher = mockMatcher(MOCKED_MATCHER_IRI, { clients: [MOCK_CLIENT_WEBID_1], }); const result = setClient(matcher, MOCK_CLIENT_WEBID_2.value); expect(getUrlAll(result, ACP_CLIENT)).toContain(MOCK_CLIENT_WEBID_2.value); expect(getUrlAll(result, ACP_CLIENT)).not.toContain( MOCK_CLIENT_WEBID_1.value ); }); it("does not change the input matcher", () => { const matcher = mockMatcher(MOCKED_MATCHER_IRI, { clients: [MOCK_CLIENT_WEBID_1], }); setClient(matcher, MOCK_CLIENT_WEBID_2.value); expect(getUrlAll(matcher, ACP_CLIENT)).not.toContain( MOCK_CLIENT_WEBID_2.value ); expect(getUrlAll(matcher, ACP_CLIENT)).toContain(MOCK_CLIENT_WEBID_1.value); }); it("does not overwrite the public client class", () => { const matcher = mockMatcher(MOCKED_MATCHER_IRI, { publicClient: true, }); const result = setClient(matcher, MOCK_CLIENT_WEBID_1.value); expect(getUrlAll(result, ACP_CLIENT)).toContain(SOLID_PUBLIC_CLIENT.value); }); }); describe("addClient", () => { it("adds the given client to the matcher", () => { const matcher = mockMatcher(MOCKED_MATCHER_IRI); const result = addClient(matcher, MOCK_CLIENT_WEBID_1.value); expect(getUrlAll(result, ACP_CLIENT)).toContain(MOCK_CLIENT_WEBID_1.value); }); it("does not override existing clients/the public client class", () => { const matcher = mockMatcher(MOCKED_MATCHER_IRI, { clients: [MOCK_CLIENT_WEBID_1], publicClient: true, }); const result = addClient(matcher, MOCK_CLIENT_WEBID_2.value); expect(getUrlAll(result, ACP_CLIENT)).toContain(MOCK_CLIENT_WEBID_1.value); expect(getUrlAll(result, ACP_CLIENT)).toContain(MOCK_CLIENT_WEBID_2.value); expect(getUrlAll(result, ACP_CLIENT)).toContain(SOLID_PUBLIC_CLIENT.value); }); }); describe("removeClient", () => { it("removes the given client from the matcher", () => { const matcher = mockMatcher(MOCKED_MATCHER_IRI, { clients: [MOCK_CLIENT_WEBID_1], }); const result = removeClient(matcher, MOCK_CLIENT_WEBID_1.value); expect(getUrlAll(result, ACP_CLIENT)).not.toContain( MOCK_CLIENT_WEBID_1.value ); }); it("does not delete unrelated clients", () => { const matcher = mockMatcher(MOCKED_MATCHER_IRI, { clients: [MOCK_CLIENT_WEBID_1, MOCK_CLIENT_WEBID_2], publicClient: true, }); const result = removeClient(matcher, MOCK_CLIENT_WEBID_2.value); expect(getUrlAll(result, ACP_CLIENT)).not.toContain( MOCK_CLIENT_WEBID_2.value ); expect(getUrlAll(result, ACP_CLIENT)).toContain(MOCK_CLIENT_WEBID_1.value); expect(getUrlAll(result, ACP_CLIENT)).toContain(SOLID_PUBLIC_CLIENT.value); }); it("does not remove agents, even with a matching IRI", () => { const matcher = mockMatcher(MOCKED_MATCHER_IRI, { agents: [MOCK_WEBID_ME], }); const result = removeClient(matcher, MOCK_WEBID_ME.value); expect(getUrlAll(result, ACP_AGENT)).toContain(MOCK_WEBID_ME.value); }); }); describe("hasAnyClient", () => { it("returns true if the matcher applies to any client", () => { const matcher = mockMatcher(MOCKED_MATCHER_IRI, { publicClient: true, }); expect(hasAnyClient(matcher)).toBe(true); }); it("returns false if the matcher only applies to individual clients", () => { const matcher = mockMatcher(MOCKED_MATCHER_IRI, { clients: [MOCK_CLIENT_WEBID_1], }); expect(hasAnyClient(matcher)).toBe(false); }); }); describe("setAnyClient", () => { it("applies to given matcher to the public client class", () => { const matcher = mockMatcher(MOCKED_MATCHER_IRI); const result = setAnyClient(matcher); expect(getUrlAll(result, ACP_CLIENT)).toContain(SOLID_PUBLIC_CLIENT.value); }); it("does not change the input matcher", () => { const matcher = mockMatcher(MOCKED_MATCHER_IRI); setAnyClient(matcher); expect(getUrlAll(matcher, ACP_CLIENT)).not.toContain( SOLID_PUBLIC_CLIENT.value ); }); it("does not change the other clients", () => { const matcher = mockMatcher(MOCKED_MATCHER_IRI, { clients: [MOCK_CLIENT_WEBID_1], }); const result = setAnyClient(matcher); expect(getUrlAll(result, ACP_CLIENT)).toContain(MOCK_CLIENT_WEBID_1.value); }); }); describe("removeAnyClient", () => { it("prevents the matcher from applying to the public client class", () => { const matcher = mockMatcher(MOCKED_MATCHER_IRI, { publicClient: true, }); const result = removeAnyClient(matcher); expect(getUrlAll(result, ACP_CLIENT)).not.toContain( SOLID_PUBLIC_CLIENT.value ); }); it("does not change the input matcher", () => { const matcher = mockMatcher(MOCKED_MATCHER_IRI, { publicClient: true }); removeAnyClient(matcher); expect(getUrlAll(matcher, ACP_CLIENT)).toContain(SOLID_PUBLIC_CLIENT.value); }); it("does not change the other clients", () => { const matcher = mockMatcher(MOCKED_MATCHER_IRI, { publicClient: true, clients: [MOCK_CLIENT_WEBID_1], }); const result = removeAnyClient(matcher); expect(getUrlAll(result, ACP_CLIENT)).toContain(MOCK_CLIENT_WEBID_1.value); }); }); describe("matcherAsMarkdown", () => { it("shows when a matcher is empty", () => { const matcher = createMatcher("https://some.pod/policyResource#matcher"); expect(matcherAsMarkdown(matcher)).toBe( "## Matcher: https://some.pod/policyResource#matcher\n" + "\n" + "<empty>\n" ); }); it("can show everything to which the matcher applies", () => { let matcher = createMatcher("https://some.pod/policyResource#matcher"); matcher = setCreator(matcher); matcher = setAuthenticated(matcher); matcher = setPublic(matcher); matcher = setAnyClient(matcher); matcher = addAgent(matcher, "https://some.pod/profile#agent"); matcher = addAgent(matcher, "https://some-other.pod/profile#agent"); matcher = addClient(matcher, "https://some.app/registration#it"); expect(matcherAsMarkdown(matcher)).toBe( "## Matcher: https://some.pod/policyResource#matcher\n" + "\n" + "This Matcher matches:\n" + "- Everyone\n" + "- All authenticated agents\n" + "- The creator of this resource\n" + "- Users of any client application\n" + "- The following agents:\n" + " - https://some.pod/profile#agent\n" + " - https://some-other.pod/profile#agent\n" + "- Users of the following client applications:\n" + " - https://some.app/registration#it\n" ); }); });
the_stack
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ import { ATN } from "antlr4ts/atn/ATN"; import { ATNDeserializer } from "antlr4ts/atn/ATNDeserializer"; import { FailedPredicateException } from "antlr4ts/FailedPredicateException"; import { NotNull } from "antlr4ts/Decorators"; import { NoViableAltException } from "antlr4ts/NoViableAltException"; import { Override } from "antlr4ts/Decorators"; import { Parser } from "antlr4ts/Parser"; import { ParserRuleContext } from "antlr4ts/ParserRuleContext"; import { ParserATNSimulator } from "antlr4ts/atn/ParserATNSimulator"; import { ParseTreeListener } from "antlr4ts/tree/ParseTreeListener"; import { ParseTreeVisitor } from "antlr4ts/tree/ParseTreeVisitor"; import { RecognitionException } from "antlr4ts/RecognitionException"; import { RuleContext } from "antlr4ts/RuleContext"; //import { RuleVersion } from "antlr4ts/RuleVersion"; import { TerminalNode } from "antlr4ts/tree/TerminalNode"; import { Token } from "antlr4ts/Token"; import { TokenStream } from "antlr4ts/TokenStream"; import { Vocabulary } from "antlr4ts/Vocabulary"; import { VocabularyImpl } from "antlr4ts/VocabularyImpl"; import * as Utils from "antlr4ts/misc/Utils"; import { LGFileParserListener } from "./LGFileParserListener"; import { LGFileParserVisitor } from "./LGFileParserVisitor"; export class LGFileParser extends Parser { public static readonly NEWLINE = 1; public static readonly OPTION = 2; public static readonly COMMENT = 3; public static readonly IMPORT = 4; public static readonly TEMPLATE_NAME_LINE = 5; public static readonly INLINE_MULTILINE = 6; public static readonly MULTILINE_PREFIX = 7; public static readonly TEMPLATE_BODY = 8; public static readonly INVALID_LINE = 9; public static readonly MULTILINE_SUFFIX = 10; public static readonly ESCAPE_CHARACTER = 11; public static readonly MULTILINE_TEXT = 12; public static readonly RULE_file = 0; public static readonly RULE_paragraph = 1; public static readonly RULE_commentDefinition = 2; public static readonly RULE_importDefinition = 3; public static readonly RULE_optionDefinition = 4; public static readonly RULE_errorDefinition = 5; public static readonly RULE_templateDefinition = 6; public static readonly RULE_templateNameLine = 7; public static readonly RULE_templateBody = 8; public static readonly RULE_templateBodyLine = 9; // tslint:disable:no-trailing-whitespace public static readonly ruleNames: string[] = [ "file", "paragraph", "commentDefinition", "importDefinition", "optionDefinition", "errorDefinition", "templateDefinition", "templateNameLine", "templateBody", "templateBodyLine", ]; private static readonly _LITERAL_NAMES: Array<string | undefined> = [ undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, "'```'", ]; private static readonly _SYMBOLIC_NAMES: Array<string | undefined> = [ undefined, "NEWLINE", "OPTION", "COMMENT", "IMPORT", "TEMPLATE_NAME_LINE", "INLINE_MULTILINE", "MULTILINE_PREFIX", "TEMPLATE_BODY", "INVALID_LINE", "MULTILINE_SUFFIX", "ESCAPE_CHARACTER", "MULTILINE_TEXT", ]; public static readonly VOCABULARY: Vocabulary = new VocabularyImpl(LGFileParser._LITERAL_NAMES, LGFileParser._SYMBOLIC_NAMES, []); // @Override // @NotNull public get vocabulary(): Vocabulary { return LGFileParser.VOCABULARY; } // tslint:enable:no-trailing-whitespace // @Override public get grammarFileName(): string { return "LGFileParser.g4"; } // @Override public get ruleNames(): string[] { return LGFileParser.ruleNames; } // @Override public get serializedATN(): string { return LGFileParser._serializedATN; } constructor(input: TokenStream) { super(input); this._interp = new ParserATNSimulator(LGFileParser._ATN, this); } // @RuleVersion(0) public file(): FileContext { let _localctx: FileContext = new FileContext(this._ctx, this.state); this.enterRule(_localctx, 0, LGFileParser.RULE_file); try { let _alt: number; this.enterOuterAlt(_localctx, 1); { this.state = 21; this._errHandler.sync(this); _alt = 1 + 1; do { switch (_alt) { case 1 + 1: { { this.state = 20; this.paragraph(); } } break; default: throw new NoViableAltException(this); } this.state = 23; this._errHandler.sync(this); _alt = this.interpreter.adaptivePredict(this._input, 0, this._ctx); } while (_alt !== 1 && _alt !== ATN.INVALID_ALT_NUMBER); this.state = 25; this.match(LGFileParser.EOF); } } catch (re) { if (re instanceof RecognitionException) { _localctx.exception = re; this._errHandler.reportError(this, re); this._errHandler.recover(this, re); } else { throw re; } } finally { this.exitRule(); } return _localctx; } // @RuleVersion(0) public paragraph(): ParagraphContext { let _localctx: ParagraphContext = new ParagraphContext(this._ctx, this.state); this.enterRule(_localctx, 2, LGFileParser.RULE_paragraph); try { this.state = 34; this._errHandler.sync(this); switch (this._input.LA(1)) { case LGFileParser.TEMPLATE_NAME_LINE: this.enterOuterAlt(_localctx, 1); { this.state = 27; this.templateDefinition(); } break; case LGFileParser.IMPORT: this.enterOuterAlt(_localctx, 2); { this.state = 28; this.importDefinition(); } break; case LGFileParser.OPTION: this.enterOuterAlt(_localctx, 3); { this.state = 29; this.optionDefinition(); } break; case LGFileParser.INVALID_LINE: this.enterOuterAlt(_localctx, 4); { this.state = 30; this.errorDefinition(); } break; case LGFileParser.COMMENT: this.enterOuterAlt(_localctx, 5); { this.state = 31; this.commentDefinition(); } break; case LGFileParser.NEWLINE: this.enterOuterAlt(_localctx, 6); { this.state = 32; this.match(LGFileParser.NEWLINE); } break; case LGFileParser.EOF: this.enterOuterAlt(_localctx, 7); { this.state = 33; this.match(LGFileParser.EOF); } break; default: throw new NoViableAltException(this); } } catch (re) { if (re instanceof RecognitionException) { _localctx.exception = re; this._errHandler.reportError(this, re); this._errHandler.recover(this, re); } else { throw re; } } finally { this.exitRule(); } return _localctx; } // @RuleVersion(0) public commentDefinition(): CommentDefinitionContext { let _localctx: CommentDefinitionContext = new CommentDefinitionContext(this._ctx, this.state); this.enterRule(_localctx, 4, LGFileParser.RULE_commentDefinition); try { this.enterOuterAlt(_localctx, 1); { this.state = 36; this.match(LGFileParser.COMMENT); this.state = 38; this._errHandler.sync(this); switch ( this.interpreter.adaptivePredict(this._input, 2, this._ctx) ) { case 1: { this.state = 37; this.match(LGFileParser.NEWLINE); } break; } } } catch (re) { if (re instanceof RecognitionException) { _localctx.exception = re; this._errHandler.reportError(this, re); this._errHandler.recover(this, re); } else { throw re; } } finally { this.exitRule(); } return _localctx; } // @RuleVersion(0) public importDefinition(): ImportDefinitionContext { let _localctx: ImportDefinitionContext = new ImportDefinitionContext(this._ctx, this.state); this.enterRule(_localctx, 6, LGFileParser.RULE_importDefinition); try { this.enterOuterAlt(_localctx, 1); { this.state = 40; this.match(LGFileParser.IMPORT); this.state = 42; this._errHandler.sync(this); switch ( this.interpreter.adaptivePredict(this._input, 3, this._ctx) ) { case 1: { this.state = 41; this.match(LGFileParser.NEWLINE); } break; } } } catch (re) { if (re instanceof RecognitionException) { _localctx.exception = re; this._errHandler.reportError(this, re); this._errHandler.recover(this, re); } else { throw re; } } finally { this.exitRule(); } return _localctx; } // @RuleVersion(0) public optionDefinition(): OptionDefinitionContext { let _localctx: OptionDefinitionContext = new OptionDefinitionContext(this._ctx, this.state); this.enterRule(_localctx, 8, LGFileParser.RULE_optionDefinition); try { this.enterOuterAlt(_localctx, 1); { this.state = 44; this.match(LGFileParser.OPTION); this.state = 46; this._errHandler.sync(this); switch ( this.interpreter.adaptivePredict(this._input, 4, this._ctx) ) { case 1: { this.state = 45; this.match(LGFileParser.NEWLINE); } break; } } } catch (re) { if (re instanceof RecognitionException) { _localctx.exception = re; this._errHandler.reportError(this, re); this._errHandler.recover(this, re); } else { throw re; } } finally { this.exitRule(); } return _localctx; } // @RuleVersion(0) public errorDefinition(): ErrorDefinitionContext { let _localctx: ErrorDefinitionContext = new ErrorDefinitionContext(this._ctx, this.state); this.enterRule(_localctx, 10, LGFileParser.RULE_errorDefinition); try { this.enterOuterAlt(_localctx, 1); { this.state = 48; this.match(LGFileParser.INVALID_LINE); this.state = 50; this._errHandler.sync(this); switch ( this.interpreter.adaptivePredict(this._input, 5, this._ctx) ) { case 1: { this.state = 49; this.match(LGFileParser.NEWLINE); } break; } } } catch (re) { if (re instanceof RecognitionException) { _localctx.exception = re; this._errHandler.reportError(this, re); this._errHandler.recover(this, re); } else { throw re; } } finally { this.exitRule(); } return _localctx; } // @RuleVersion(0) public templateDefinition(): TemplateDefinitionContext { let _localctx: TemplateDefinitionContext = new TemplateDefinitionContext(this._ctx, this.state); this.enterRule(_localctx, 12, LGFileParser.RULE_templateDefinition); try { this.enterOuterAlt(_localctx, 1); { this.state = 52; this.templateNameLine(); this.state = 53; this.templateBody(); } } catch (re) { if (re instanceof RecognitionException) { _localctx.exception = re; this._errHandler.reportError(this, re); this._errHandler.recover(this, re); } else { throw re; } } finally { this.exitRule(); } return _localctx; } // @RuleVersion(0) public templateNameLine(): TemplateNameLineContext { let _localctx: TemplateNameLineContext = new TemplateNameLineContext(this._ctx, this.state); this.enterRule(_localctx, 14, LGFileParser.RULE_templateNameLine); try { this.enterOuterAlt(_localctx, 1); { this.state = 55; this.match(LGFileParser.TEMPLATE_NAME_LINE); this.state = 57; this._errHandler.sync(this); switch ( this.interpreter.adaptivePredict(this._input, 6, this._ctx) ) { case 1: { this.state = 56; this.match(LGFileParser.NEWLINE); } break; } } } catch (re) { if (re instanceof RecognitionException) { _localctx.exception = re; this._errHandler.reportError(this, re); this._errHandler.recover(this, re); } else { throw re; } } finally { this.exitRule(); } return _localctx; } // @RuleVersion(0) public templateBody(): TemplateBodyContext { let _localctx: TemplateBodyContext = new TemplateBodyContext(this._ctx, this.state); this.enterRule(_localctx, 16, LGFileParser.RULE_templateBody); try { let _alt: number; this.enterOuterAlt(_localctx, 1); { this.state = 62; this._errHandler.sync(this); _alt = this.interpreter.adaptivePredict(this._input, 7, this._ctx); while (_alt !== 2 && _alt !== ATN.INVALID_ALT_NUMBER) { if (_alt === 1) { { { this.state = 59; this.templateBodyLine(); } } } this.state = 64; this._errHandler.sync(this); _alt = this.interpreter.adaptivePredict(this._input, 7, this._ctx); } } } catch (re) { if (re instanceof RecognitionException) { _localctx.exception = re; this._errHandler.reportError(this, re); this._errHandler.recover(this, re); } else { throw re; } } finally { this.exitRule(); } return _localctx; } // @RuleVersion(0) public templateBodyLine(): TemplateBodyLineContext { let _localctx: TemplateBodyLineContext = new TemplateBodyLineContext(this._ctx, this.state); this.enterRule(_localctx, 18, LGFileParser.RULE_templateBodyLine); let _la: number; try { this.state = 83; this._errHandler.sync(this); switch (this._input.LA(1)) { case LGFileParser.INLINE_MULTILINE: case LGFileParser.MULTILINE_PREFIX: case LGFileParser.TEMPLATE_BODY: this.enterOuterAlt(_localctx, 1); { { this.state = 77; this._errHandler.sync(this); switch (this._input.LA(1)) { case LGFileParser.TEMPLATE_BODY: { this.state = 65; this.match(LGFileParser.TEMPLATE_BODY); } break; case LGFileParser.INLINE_MULTILINE: { this.state = 66; this.match(LGFileParser.INLINE_MULTILINE); } break; case LGFileParser.MULTILINE_PREFIX: { { this.state = 67; this.match(LGFileParser.MULTILINE_PREFIX); this.state = 71; this._errHandler.sync(this); _la = this._input.LA(1); while (_la === LGFileParser.ESCAPE_CHARACTER || _la === LGFileParser.MULTILINE_TEXT) { { { this.state = 68; _la = this._input.LA(1); if (!(_la === LGFileParser.ESCAPE_CHARACTER || _la === LGFileParser.MULTILINE_TEXT)) { this._errHandler.recoverInline(this); } else { if (this._input.LA(1) === Token.EOF) { this.matchedEOF = true; } this._errHandler.reportMatch(this); this.consume(); } } } this.state = 73; this._errHandler.sync(this); _la = this._input.LA(1); } this.state = 75; this._errHandler.sync(this); _la = this._input.LA(1); if (_la === LGFileParser.MULTILINE_SUFFIX) { { this.state = 74; this.match(LGFileParser.MULTILINE_SUFFIX); } } } } break; default: throw new NoViableAltException(this); } this.state = 80; this._errHandler.sync(this); switch ( this.interpreter.adaptivePredict(this._input, 11, this._ctx) ) { case 1: { this.state = 79; this.match(LGFileParser.NEWLINE); } break; } } } break; case LGFileParser.NEWLINE: this.enterOuterAlt(_localctx, 2); { this.state = 82; this.match(LGFileParser.NEWLINE); } break; default: throw new NoViableAltException(this); } } catch (re) { if (re instanceof RecognitionException) { _localctx.exception = re; this._errHandler.reportError(this, re); this._errHandler.recover(this, re); } else { throw re; } } finally { this.exitRule(); } return _localctx; } public static readonly _serializedATN: string = "\x03\uC91D\uCABA\u058D\uAFBA\u4F53\u0607\uEA8B\uC241\x03\x0EX\x04\x02" + "\t\x02\x04\x03\t\x03\x04\x04\t\x04\x04\x05\t\x05\x04\x06\t\x06\x04\x07" + "\t\x07\x04\b\t\b\x04\t\t\t\x04\n\t\n\x04\v\t\v\x03\x02\x06\x02\x18\n\x02" + "\r\x02\x0E\x02\x19\x03\x02\x03\x02\x03\x03\x03\x03\x03\x03\x03\x03\x03" + "\x03\x03\x03\x03\x03\x05\x03%\n\x03\x03\x04\x03\x04\x05\x04)\n\x04\x03" + "\x05\x03\x05\x05\x05-\n\x05\x03\x06\x03\x06\x05\x061\n\x06\x03\x07\x03" + "\x07\x05\x075\n\x07\x03\b\x03\b\x03\b\x03\t\x03\t\x05\t<\n\t\x03\n\x07" + "\n?\n\n\f\n\x0E\nB\v\n\x03\v\x03\v\x03\v\x03\v\x07\vH\n\v\f\v\x0E\vK\v" + "\v\x03\v\x05\vN\n\v\x05\vP\n\v\x03\v\x05\vS\n\v\x03\v\x05\vV\n\v\x03\v" + "\x03\x19\x02\x02\f\x02\x02\x04\x02\x06\x02\b\x02\n\x02\f\x02\x0E\x02\x10" + "\x02\x12\x02\x14\x02\x02\x03\x03\x02\r\x0E\x02`\x02\x17\x03\x02\x02\x02" + "\x04$\x03\x02\x02\x02\x06&\x03\x02\x02\x02\b*\x03\x02\x02\x02\n.\x03\x02" + "\x02\x02\f2\x03\x02\x02\x02\x0E6\x03\x02\x02\x02\x109\x03\x02\x02\x02" + "\x12@\x03\x02\x02\x02\x14U\x03\x02\x02\x02\x16\x18\x05\x04\x03\x02\x17" + "\x16\x03\x02\x02\x02\x18\x19\x03\x02\x02\x02\x19\x1A\x03\x02\x02\x02\x19" + "\x17\x03\x02\x02\x02\x1A\x1B\x03\x02\x02\x02\x1B\x1C\x07\x02\x02\x03\x1C" + "\x03\x03\x02\x02\x02\x1D%\x05\x0E\b\x02\x1E%\x05\b\x05\x02\x1F%\x05\n" + "\x06\x02 %\x05\f\x07\x02!%\x05\x06\x04\x02\"%\x07\x03\x02\x02#%\x07\x02" + "\x02\x03$\x1D\x03\x02\x02\x02$\x1E\x03\x02\x02\x02$\x1F\x03\x02\x02\x02" + "$ \x03\x02\x02\x02$!\x03\x02\x02\x02$\"\x03\x02\x02\x02$#\x03\x02\x02" + "\x02%\x05\x03\x02\x02\x02&(\x07\x05\x02\x02\')\x07\x03\x02\x02(\'\x03" + "\x02\x02\x02()\x03\x02\x02\x02)\x07\x03\x02\x02\x02*,\x07\x06\x02\x02" + "+-\x07\x03\x02\x02,+\x03\x02\x02\x02,-\x03\x02\x02\x02-\t\x03\x02\x02" + "\x02.0\x07\x04\x02\x02/1\x07\x03\x02\x020/\x03\x02\x02\x0201\x03\x02\x02" + "\x021\v\x03\x02\x02\x0224\x07\v\x02\x0235\x07\x03\x02\x0243\x03\x02\x02" + "\x0245\x03\x02\x02\x025\r\x03\x02\x02\x0267\x05\x10\t\x0278\x05\x12\n" + "\x028\x0F\x03\x02\x02\x029;\x07\x07\x02\x02:<\x07\x03\x02\x02;:\x03\x02" + "\x02\x02;<\x03\x02\x02\x02<\x11\x03\x02\x02\x02=?\x05\x14\v\x02>=\x03" + "\x02\x02\x02?B\x03\x02\x02\x02@>\x03\x02\x02\x02@A\x03\x02\x02\x02A\x13" + "\x03\x02\x02\x02B@\x03\x02\x02\x02CP\x07\n\x02\x02DP\x07\b\x02\x02EI\x07" + "\t\x02\x02FH\t\x02\x02\x02GF\x03\x02\x02\x02HK\x03\x02\x02\x02IG\x03\x02" + "\x02\x02IJ\x03\x02\x02\x02JM\x03\x02\x02\x02KI\x03\x02\x02\x02LN\x07\f" + "\x02\x02ML\x03\x02\x02\x02MN\x03\x02\x02\x02NP\x03\x02\x02\x02OC\x03\x02" + "\x02\x02OD\x03\x02\x02\x02OE\x03\x02\x02\x02PR\x03\x02\x02\x02QS\x07\x03" + "\x02\x02RQ\x03\x02\x02\x02RS\x03\x02\x02\x02SV\x03\x02\x02\x02TV\x07\x03" + "\x02\x02UO\x03\x02\x02\x02UT\x03\x02\x02\x02V\x15\x03\x02\x02\x02\x0F" + "\x19$(,04;@IMORU"; public static __ATN: ATN; public static get _ATN(): ATN { if (!LGFileParser.__ATN) { LGFileParser.__ATN = new ATNDeserializer().deserialize(Utils.toCharArray(LGFileParser._serializedATN)); } return LGFileParser.__ATN; } } export class FileContext extends ParserRuleContext { public EOF(): TerminalNode { return this.getToken(LGFileParser.EOF, 0); } public paragraph(): ParagraphContext[]; public paragraph(i: number): ParagraphContext; public paragraph(i?: number): ParagraphContext | ParagraphContext[] { if (i === undefined) { return this.getRuleContexts(ParagraphContext); } else { return this.getRuleContext(i, ParagraphContext); } } constructor(parent: ParserRuleContext | undefined, invokingState: number) { super(parent, invokingState); } // @Override public get ruleIndex(): number { return LGFileParser.RULE_file; } // @Override public enterRule(listener: LGFileParserListener): void { if (listener.enterFile) { listener.enterFile(this); } } // @Override public exitRule(listener: LGFileParserListener): void { if (listener.exitFile) { listener.exitFile(this); } } // @Override public accept<Result>(visitor: LGFileParserVisitor<Result>): Result { if (visitor.visitFile) { return visitor.visitFile(this); } else { return visitor.visitChildren(this); } } } export class ParagraphContext extends ParserRuleContext { public templateDefinition(): TemplateDefinitionContext | undefined { return this.tryGetRuleContext(0, TemplateDefinitionContext); } public importDefinition(): ImportDefinitionContext | undefined { return this.tryGetRuleContext(0, ImportDefinitionContext); } public optionDefinition(): OptionDefinitionContext | undefined { return this.tryGetRuleContext(0, OptionDefinitionContext); } public errorDefinition(): ErrorDefinitionContext | undefined { return this.tryGetRuleContext(0, ErrorDefinitionContext); } public commentDefinition(): CommentDefinitionContext | undefined { return this.tryGetRuleContext(0, CommentDefinitionContext); } public NEWLINE(): TerminalNode | undefined { return this.tryGetToken(LGFileParser.NEWLINE, 0); } public EOF(): TerminalNode | undefined { return this.tryGetToken(LGFileParser.EOF, 0); } constructor(parent: ParserRuleContext | undefined, invokingState: number) { super(parent, invokingState); } // @Override public get ruleIndex(): number { return LGFileParser.RULE_paragraph; } // @Override public enterRule(listener: LGFileParserListener): void { if (listener.enterParagraph) { listener.enterParagraph(this); } } // @Override public exitRule(listener: LGFileParserListener): void { if (listener.exitParagraph) { listener.exitParagraph(this); } } // @Override public accept<Result>(visitor: LGFileParserVisitor<Result>): Result { if (visitor.visitParagraph) { return visitor.visitParagraph(this); } else { return visitor.visitChildren(this); } } } export class CommentDefinitionContext extends ParserRuleContext { public COMMENT(): TerminalNode { return this.getToken(LGFileParser.COMMENT, 0); } public NEWLINE(): TerminalNode | undefined { return this.tryGetToken(LGFileParser.NEWLINE, 0); } constructor(parent: ParserRuleContext | undefined, invokingState: number) { super(parent, invokingState); } // @Override public get ruleIndex(): number { return LGFileParser.RULE_commentDefinition; } // @Override public enterRule(listener: LGFileParserListener): void { if (listener.enterCommentDefinition) { listener.enterCommentDefinition(this); } } // @Override public exitRule(listener: LGFileParserListener): void { if (listener.exitCommentDefinition) { listener.exitCommentDefinition(this); } } // @Override public accept<Result>(visitor: LGFileParserVisitor<Result>): Result { if (visitor.visitCommentDefinition) { return visitor.visitCommentDefinition(this); } else { return visitor.visitChildren(this); } } } export class ImportDefinitionContext extends ParserRuleContext { public IMPORT(): TerminalNode { return this.getToken(LGFileParser.IMPORT, 0); } public NEWLINE(): TerminalNode | undefined { return this.tryGetToken(LGFileParser.NEWLINE, 0); } constructor(parent: ParserRuleContext | undefined, invokingState: number) { super(parent, invokingState); } // @Override public get ruleIndex(): number { return LGFileParser.RULE_importDefinition; } // @Override public enterRule(listener: LGFileParserListener): void { if (listener.enterImportDefinition) { listener.enterImportDefinition(this); } } // @Override public exitRule(listener: LGFileParserListener): void { if (listener.exitImportDefinition) { listener.exitImportDefinition(this); } } // @Override public accept<Result>(visitor: LGFileParserVisitor<Result>): Result { if (visitor.visitImportDefinition) { return visitor.visitImportDefinition(this); } else { return visitor.visitChildren(this); } } } export class OptionDefinitionContext extends ParserRuleContext { public OPTION(): TerminalNode { return this.getToken(LGFileParser.OPTION, 0); } public NEWLINE(): TerminalNode | undefined { return this.tryGetToken(LGFileParser.NEWLINE, 0); } constructor(parent: ParserRuleContext | undefined, invokingState: number) { super(parent, invokingState); } // @Override public get ruleIndex(): number { return LGFileParser.RULE_optionDefinition; } // @Override public enterRule(listener: LGFileParserListener): void { if (listener.enterOptionDefinition) { listener.enterOptionDefinition(this); } } // @Override public exitRule(listener: LGFileParserListener): void { if (listener.exitOptionDefinition) { listener.exitOptionDefinition(this); } } // @Override public accept<Result>(visitor: LGFileParserVisitor<Result>): Result { if (visitor.visitOptionDefinition) { return visitor.visitOptionDefinition(this); } else { return visitor.visitChildren(this); } } } export class ErrorDefinitionContext extends ParserRuleContext { public INVALID_LINE(): TerminalNode { return this.getToken(LGFileParser.INVALID_LINE, 0); } public NEWLINE(): TerminalNode | undefined { return this.tryGetToken(LGFileParser.NEWLINE, 0); } constructor(parent: ParserRuleContext | undefined, invokingState: number) { super(parent, invokingState); } // @Override public get ruleIndex(): number { return LGFileParser.RULE_errorDefinition; } // @Override public enterRule(listener: LGFileParserListener): void { if (listener.enterErrorDefinition) { listener.enterErrorDefinition(this); } } // @Override public exitRule(listener: LGFileParserListener): void { if (listener.exitErrorDefinition) { listener.exitErrorDefinition(this); } } // @Override public accept<Result>(visitor: LGFileParserVisitor<Result>): Result { if (visitor.visitErrorDefinition) { return visitor.visitErrorDefinition(this); } else { return visitor.visitChildren(this); } } } export class TemplateDefinitionContext extends ParserRuleContext { public templateNameLine(): TemplateNameLineContext { return this.getRuleContext(0, TemplateNameLineContext); } public templateBody(): TemplateBodyContext { return this.getRuleContext(0, TemplateBodyContext); } constructor(parent: ParserRuleContext | undefined, invokingState: number) { super(parent, invokingState); } // @Override public get ruleIndex(): number { return LGFileParser.RULE_templateDefinition; } // @Override public enterRule(listener: LGFileParserListener): void { if (listener.enterTemplateDefinition) { listener.enterTemplateDefinition(this); } } // @Override public exitRule(listener: LGFileParserListener): void { if (listener.exitTemplateDefinition) { listener.exitTemplateDefinition(this); } } // @Override public accept<Result>(visitor: LGFileParserVisitor<Result>): Result { if (visitor.visitTemplateDefinition) { return visitor.visitTemplateDefinition(this); } else { return visitor.visitChildren(this); } } } export class TemplateNameLineContext extends ParserRuleContext { public TEMPLATE_NAME_LINE(): TerminalNode { return this.getToken(LGFileParser.TEMPLATE_NAME_LINE, 0); } public NEWLINE(): TerminalNode | undefined { return this.tryGetToken(LGFileParser.NEWLINE, 0); } constructor(parent: ParserRuleContext | undefined, invokingState: number) { super(parent, invokingState); } // @Override public get ruleIndex(): number { return LGFileParser.RULE_templateNameLine; } // @Override public enterRule(listener: LGFileParserListener): void { if (listener.enterTemplateNameLine) { listener.enterTemplateNameLine(this); } } // @Override public exitRule(listener: LGFileParserListener): void { if (listener.exitTemplateNameLine) { listener.exitTemplateNameLine(this); } } // @Override public accept<Result>(visitor: LGFileParserVisitor<Result>): Result { if (visitor.visitTemplateNameLine) { return visitor.visitTemplateNameLine(this); } else { return visitor.visitChildren(this); } } } export class TemplateBodyContext extends ParserRuleContext { public templateBodyLine(): TemplateBodyLineContext[]; public templateBodyLine(i: number): TemplateBodyLineContext; public templateBodyLine(i?: number): TemplateBodyLineContext | TemplateBodyLineContext[] { if (i === undefined) { return this.getRuleContexts(TemplateBodyLineContext); } else { return this.getRuleContext(i, TemplateBodyLineContext); } } constructor(parent: ParserRuleContext | undefined, invokingState: number) { super(parent, invokingState); } // @Override public get ruleIndex(): number { return LGFileParser.RULE_templateBody; } // @Override public enterRule(listener: LGFileParserListener): void { if (listener.enterTemplateBody) { listener.enterTemplateBody(this); } } // @Override public exitRule(listener: LGFileParserListener): void { if (listener.exitTemplateBody) { listener.exitTemplateBody(this); } } // @Override public accept<Result>(visitor: LGFileParserVisitor<Result>): Result { if (visitor.visitTemplateBody) { return visitor.visitTemplateBody(this); } else { return visitor.visitChildren(this); } } } export class TemplateBodyLineContext extends ParserRuleContext { public TEMPLATE_BODY(): TerminalNode | undefined { return this.tryGetToken(LGFileParser.TEMPLATE_BODY, 0); } public INLINE_MULTILINE(): TerminalNode | undefined { return this.tryGetToken(LGFileParser.INLINE_MULTILINE, 0); } public NEWLINE(): TerminalNode | undefined { return this.tryGetToken(LGFileParser.NEWLINE, 0); } public MULTILINE_PREFIX(): TerminalNode | undefined { return this.tryGetToken(LGFileParser.MULTILINE_PREFIX, 0); } public MULTILINE_SUFFIX(): TerminalNode | undefined { return this.tryGetToken(LGFileParser.MULTILINE_SUFFIX, 0); } public MULTILINE_TEXT(): TerminalNode[]; public MULTILINE_TEXT(i: number): TerminalNode; public MULTILINE_TEXT(i?: number): TerminalNode | TerminalNode[] { if (i === undefined) { return this.getTokens(LGFileParser.MULTILINE_TEXT); } else { return this.getToken(LGFileParser.MULTILINE_TEXT, i); } } public ESCAPE_CHARACTER(): TerminalNode[]; public ESCAPE_CHARACTER(i: number): TerminalNode; public ESCAPE_CHARACTER(i?: number): TerminalNode | TerminalNode[] { if (i === undefined) { return this.getTokens(LGFileParser.ESCAPE_CHARACTER); } else { return this.getToken(LGFileParser.ESCAPE_CHARACTER, i); } } constructor(parent: ParserRuleContext | undefined, invokingState: number) { super(parent, invokingState); } // @Override public get ruleIndex(): number { return LGFileParser.RULE_templateBodyLine; } // @Override public enterRule(listener: LGFileParserListener): void { if (listener.enterTemplateBodyLine) { listener.enterTemplateBodyLine(this); } } // @Override public exitRule(listener: LGFileParserListener): void { if (listener.exitTemplateBodyLine) { listener.exitTemplateBodyLine(this); } } // @Override public accept<Result>(visitor: LGFileParserVisitor<Result>): Result { if (visitor.visitTemplateBodyLine) { return visitor.visitTemplateBodyLine(this); } else { return visitor.visitChildren(this); } } }
the_stack
export interface RequestOption { uri?: string | undefined; headers?: any; json?: any; timeout?: any; metricRequestID?: string | undefined; metricUserName?: string | undefined; metricLogger?: any; } export interface Project { general_token: string; project_token: string; glance: Glance; neutron: Neutron; nova: Nova; octavia: Octavia; } export function getSimpleProject(username: string, password: string, project_id: string, keystone_url: string, cb: (...args: any[]) => any): void; export class Nova { request: any; mangler: any; mangleObject: any; url: any; token: any; timeout: any; request_id: any; user_name: any; logger: any; constructor(endpoint_url: string, auth_token: string); setTimeout(new_timeout: any): void; setRequestID(request_id: any): void; setUserName(user_name: string): void; setLogger(logger: any): void; setRequest(request_lib: any): void; setMangler(mangle_lib: any): void; getRequestOptions(path: string, json_value: any, extra_headers: any): RequestOption; listServers(cb: (...args: any[]) => any): any; getServer(id: string, cb: (...args: any[]) => any): any; createServer(data: any, cb: (...args: any[]) => any): any; renameServer(id: string, name: string, cb: (...args: any[]) => any): any; resizeServer(id: string, flavor: any, cb: (...args: any[]) => any): any; confirmResizeServer(id: string, cb: (...args: any[]) => any): any; revertResizeServer(id: string, cb: (...args: any[]) => any): any; removeServer(id: string, cb: (...args: any[]) => any): any; rebootServer(id: string, cb: (...args: any[]) => any): any; forceRebootServer(id: string, cb: (...args: any[]) => any): any; stopServer(id: string, cb: (...args: any[]) => any): any; startServer(id: string, cb: (...args: any[]) => any): any; pauseServer(id: string, cb: (...args: any[]) => any): any; suspendServer(id: string, cb: (...args: any[]) => any): any; resumeServer(is: string, cb: (...args: any[]) => any): any; getServerConsoleURL(type: any, id: string, cb: (...args: any[]) => any): any; getServerLog(id: string, length: any, cb: (...args: any[]) => any): any; createServerImage(id: string , data: any, cb: (...args: any[]) => any): any; setServerMetadata(id: string , data: any, cb: (...args: any[]) => any): any; listFlavors(cb: (...args: any[]) => any): any; getFlavor(id: string, cb: (...args: any[]) => any): any; listFloatingIps(cb: (...args: any[]) => any): any; getFloatingIp(id: string, cb: (...args: any[]) => any): any; createFloatingIp(data: any, cb: (...args: any[]) => any): any; removeFloatingIp(id: string, cb: (...args: any[]) => any): any; associateFloatingIp(instance_id: any, ip_address: any, cb: (...args: any[]) => any): any; disassociateFloatingIp(instance_id: any, ip_address: any, cb: (...args: any[]) => any): any; listFloatingIpPools(cb: (...args: any[]) => any): any; getFloatingIpPool(id: string, cb: (...args: any[]) => any): any; listAvailabilityZones(cb: (...args: any[]) => any): any; getAvailabilityZone(id: string, cb: (...args: any[]) => any): any; listKeyPairs(cb: (...args: any[]) => any): any; getKeyPair(id: string, cb: (...args: any[]) => any): any; createKeyPair(name: string, public_key: any, cb: (...args: any[]) => any): any; removeKeyPair(id: string, cb: (...args: any[]) => any): any; getQuotaSet(project_id: string, cb: (...args: any[]) => any): any; setQuotaSet(project_id: string, data: any, cb: (...args: any[]) => any): any; getTenantUsage(project_id: string, start_date_obj: any, end_date_obj: any, cb: (...args: any[]) => any): any; assignSecurityGroup(security_group_name: string, instance_id: string, cb: (...args: any[]) => any): any; removeSecurityGroup(security_group_name: string, instance_id: string, cb: (...args: any[]) => any): any; getImageMetaData(id: string, cb: (...args: any[]) => any): any; setImageMetaData(id: string, data: any, cb: (...args: any[]) => any): any; } export class Glance { request: any; mangler: any; mangleObject: any; url: any; token: any; timeout: any; request_id: any; user_name: any; logger: any; constructor(endpoint_url: string, auth_token: string); setTimeout(new_timeout: any): void; setRequestID(request_id: any): void; setUserName(user_name: string): void; setLogger(logger: any): void; setRequest(request_lib: any): void; setMangler(mangle_lib: any): void; getRequestOptions(path: string, json_value: any, extra_headers: any): RequestOption; listImages(cb: (...args: any[]) => any): any; getImage(id: any, cb: (...args: any[]) => any): any; queueImage(data: any, cb: (...args: any[]) => any): any; uploadImage(id: any, stream: any, cb: (...args: any[]) => any): any; updateImage(id: any, data: any, cb: (...args: any[]) => any): any; removeImage(id: any, cb: (...args: any[]) => any): any; } export class Keystone { request: any; mangler: any; mangleObject: any; url: any; timeout: any; request_id: any; user_name: any; logger: any; constructor(endpoint_url: string); setTimeout(new_timeout: any): void; setRequestID(request_id: any): void; setUserName(user_name: string): void; setLogger(logger: any): void; setRequest(request_lib: any): void; setMangler(mangle_lib: any): void; getRequestOptions(path: string, json_value: any, extra_headers: any): RequestOption; getToken(username: string, password: string, cb: (...args: any[]) => any): any; getProjectTokenForReal(auth_data: any, cb: (...args: any[]) => any): any; getProjectToken(access_token: any, project_id: any, cb: (...args: any[]) => any): any; getProjectTokenByName(access_token: any, domain_id: any, project_name: string, cb: (...args: any[]) => any): any; listProjects(admin_access_token: any, cb: (...args: any[]) => any): any; listUserProjects(username: any, access_token: any, cb: (...args: any[]) => any): any; getProjectByName(admin_access_token: any, project_name: any, cb: (...args: any[]) => any): any; listRoles(project_token: any, cb: (...args: any[]) => any): any; listRoleAssignments(project_token: any, project_id: any, cb: (...args: any[]) => any): any; addRoleAssignment(project_token: any, project_id: any, entry_id: any, entry_type: any, role_id: any, cb: (...args: any[]) => any): any; removeRoleAssignment(project_token: any, project_id: any, entry_id: any, entry_type: any, role_id: any, cb: (...args: any[]) => any): any; listMetaEnvironments(auth_token: any, cb: (...args: any[]) => any): any; listMetaOwningGroups(auth_token: any, cb: (...args: any[]) => any): any; listProjectMeta(project_token: any, project_id: any, cb: (...args: any[]) => any): any; updateProjectMeta(project_token: any, project_id: any, new_meta: any, cb: (...args: any[]) => any): any; } export class Neutron { request: any; mangler: any; mangleObject: any; url: any; token: any; timeout: any; request_id: any; user_name: any; logger: any; constructor(endpoint_url: string, auth_token: string); setTimeout(new_timeout: any): void; setRequestID(request_id: any): void; setUserName(user_name: string): void; setLogger(logger: any): void; setRequest(request_lib: any): void; setMangler(mangle_lib: any): void; getRequestOptions(path: string, json_value: any, extra_headers: any): RequestOption; listNetworks(cb: (...args: any[]) => any): any; getNetwork(network_id: string, cb: (...args: any[]) => any): any; listSubnets(cb: (...args: any[]) => any): any; getSubnet(subnet_id: any, cb: (...args: any[]) => any): any; listRouters(cb: (...args: any[]) => any): any; getRouter(router_id: any, cb: (...args: any[]) => any): any; createFloatingIp(floating_network_id: any, cb: (...args: any[]) => any): any; listFloatingIps(options: any, cb: (...args: any[]) => any): any; getFloatingIp(ip_id: any, cb: (...args: any[]) => any): any; updateFloatingIp(ip_id: any, port_id: any, cb: (...args: any[]) => any): any; removeFloatingIp(ip_id: any, cb: (...args: any[]) => any): any; listPorts(options: any, cb: (...args: any[]) => any): any; getPort(port_id: any, cb: (...args: any[]) => any): any; updatePort(port_id: any, data: any, cb: (...args: any[]) => any): any; listSecurityGroups(project_id: any, cb: (...args: any[]) => any): any; getSecurityGroup(group_id: any, cb: (...args: any[]) => any): any; createSecurityGroup(group_name: any, data: any, cb: (...args: any[]) => any): any; updateSecurityGroup(group_id: any, data: any, cb: (...args: any[]) => any): any; removeSecurityGroup(group_id: any, cb: (...args: any[]) => any): any; listSecurityGroupRules(cb: (...args: any[]) => any): any; getSecurityGroupRule(rule_id: any, cb: (...args: any[]) => any): any; createSecurityGroupRule(group_id: any, data: any, cb: (...args: any[]) => any): any; removeSecurityGroupRule(rule_id: any, cb: (...args: any[]) => any): any; listLoadBalancers(cb: (...args: any[]) => any): any; getLoadBalancer(lb_id: any, cb: (...args: any[]) => any): any; createLoadBalancer(tenant_id: any, vip_subnet_id: any, cb: (...args: any[]) => any): any; updateLoadBalancer(lb_id: any, data: any, cb: (...args: any[]) => any): any; removeLoadBalancer(lb_id: any, cb: (...args: any[]) => any): any; listLBListeners(cb: (...args: any[]) => any): any; getLBListener(lb_id: any, cb: (...args: any[]) => any): any; createLBListener(tenant_id: any, loadbalancer_id: any, description: any, protocol: any, data: any, cb: (...args: any[]) => any): any; updateLBListener(listener_id: any, data: any, cb: (...args: any[]) => any): any; removeLBListener(listener_id: any, cb: (...args: any[]) => any): any; listLBPools(cb: (...args: any[]) => any): any; getLBPool(pool_id: any, cb: (...args: any[]) => any): any; createLBPool(tenant_id: any, protocol: any, lb_algorithm: any, listener_id: any, data: any, cb: (...args: any[]) => any): any; updateLBPool(pool_id: any, data: any, cb: (...args: any[]) => any): any; removeLBPool(pool_id: any, cb: (...args: any[]) => any): any; listLBPoolMembers(pool_id: any, cb: (...args: any[]) => any): any; getLBPoolMember(pool_id: any, member_id: any, cb: (...args: any[]) => any): any; createLBPoolMember(pool_id: any, tenant_id: any, address: any, protocol_port: any, data: any, cb: (...args: any[]) => any): any; updateLBPoolMember(pool_id: any, member_id: any, data: any, cb: (...args: any[]) => any): any; removeLBPoolMember(pool_id: any, member_id: any, cb: (...args: any[]) => any): any; listLBHealthMonitors(cb: (...args: any[]) => any): any; getLBHealthMonitor(health_monitor_id: any, cb: (...args: any[]) => any): any; createLBHealthMonitor(tenant_id: any, type: any, delay: any, timeout: any, max_retries: any, pool_id: any, data: any, cb: (...args: any[]) => any): any; updateLBHealthMonitor(health_monitor_id: any, data: any, cb: (...args: any[]) => any): any; removeLBHealthMonitor(health_monitor_id: any, cb: (...args: any[]) => any): any; getLBStats(lb_id: any, cb: (...args: any[]) => any): any; } export class Octavia { url: any; token: any; timeout: any; request_id: any; user_name: string; logger: any; retries: number; retry_delay: number; constructor(endpoint_url: string, auth_token: string); setTimeout(new_timeout: any): void; setRequestID(request_id: any): void; setUserName(user_name: string): void; setLogger(logger: any): void; setRequest(request_lib: any): void; setRetries(retries: number): void; setRetryDelay(retry_delay: number): void; getRequestOptions(path: string, json_value: any): RequestOption; listLoadBalancers(cb: (...args: any[]) => any): any; getLoadBalancer(lb_id: string, cb: (...args: any[]) => any): any; createLoadBalancer(project_id: string, data: any, cb: (...args: any[]) => any): any; updateLoadBalancer(lb_id: string, data: any, cb: (...args: any[]) => any): any; removeLoadBalancer(lb_id: string, cb: (...args: any[]) => any): any; listLBListeners(cb: (...args: any[]) => any): any; getLBListener(listener_id: string, cb: (...args: any[]) => any): any; createLBListener(loadbalancer_id: string, protocol: any, data: any, cb: (...args: any[]) => any): any; updateLBListener(listener_id: string, data: any, cb: (...args: any[]) => any): any; removeLBListener(listener_id: string, cb: (...args: any[]) => any): any; listLBPools(cb: (...args: any[]) => any): any; getLBPool(pool_id: string, cb: (...args: any[]) => any): any; createLBPool(protocol: any, lb_algorithm: any, data: any, cb: (...args: any[]) => any): any; updateLBPool(pool_id: string, data: any, cb: (...args: any[]) => any): any; removeLBPool(pool_id: string, cb: (...args: any[]) => any): any; listLBPoolMembers(pool_id: string, cb: (...args: any[]) => any): any; getLBPoolMember(pool_id: string, member_id: string, cb: (...args: any[]) => any): any; createLBPoolMember(pool_id: string, address: any, protocol_port: any, data: any, cb: (...args: any[]) => any): any; updateLBPoolMember(pool_id: string, member_id: string, data: any, cb: (...args: any[]) => any): any; removeLBPoolMember(pool_id: string, member_id: string, cb: (...args: any[]) => any): any; listLBHealthMonitors(cb: (...args: any[]) => any): any; getLBHealthMonitor(health_monitor_id: string, cb: (...args: any[]) => any): any; createLBHealthMonitor(pool_id: string, type: any, delay: number, timeout: number, max_retries: number, data: any, cb: (...args: any[]) => any): any; updateLBHealthMonitor(health_monitor_id: string, data: any, cb: (...args: any[]) => any): any; removeLBHealthMonitor(health_monitor_id: string, cb: (...args: any[]) => any): any; getLBStats(lb_id: string, cb: (...args: any[]) => any): any; }
the_stack
import { AfterViewInit, Component, DoCheck, ElementRef, EventEmitter, Injector, Input, OnDestroy, OnInit, Output, ViewChild } from '@angular/core'; import {Alert} from '@common/util/alert.util'; import {CommonConstant} from '@common/constant/common.constant'; import {EventBroadcaster} from '@common/event/event.broadcaster'; import {AbstractComponent} from '@common/component/abstract.component'; import {ChartType, FunctionValidator} from '@common/component/chart/option/define/common'; import {InclusionFilter, InclusionSelectorType} from '@domain/workbook/configurations/filter/inclusion-filter'; import {Widget} from '@domain/dashboard/widget/widget'; import {PageWidget, PageWidgetConfiguration} from '@domain/dashboard/widget/page-widget'; import {LayoutMode} from '@domain/dashboard/dashboard'; import {Datasource} from '@domain/datasource/datasource'; import {FilterWidgetConfiguration} from '@domain/dashboard/widget/filter-widget'; import {Filter} from '@domain/workbook/configurations/filter/filter'; import {DashboardUtil} from '../../util/dashboard.util'; @Component({ selector: 'dashboard-widget-header', templateUrl: './dashboard.widget.header.component.html' }) export class DashboardWidgetHeaderComponent extends AbstractComponent implements OnInit, OnDestroy, AfterViewInit, DoCheck { /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Private Variables |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ @ViewChild('controlContainer') private controlContainer: ElementRef; // 차트 기능 확인기 private _chartFuncValidator: FunctionValidator = new FunctionValidator(); /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Public Variables |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Public - Input&Ouput Variables |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ @Input() public widget: Widget; @Input() public layoutMode: LayoutMode; @Input() public isShowTitle: boolean = true; // Title 표시 여부 @Output() public eventHeaderControls = new EventEmitter(); public isEditTitle: boolean = false; // 타이틀 public isMiniHeader: boolean = false; // 미니 헤더 적용 여부 public isShowMore: boolean = false; // 미니 헤더 More 적용 여부 public isMissingDataSource: boolean = false; public limitInfo: { id: string, isShow: boolean, currentCnt: number, maxCnt: number } = { id: '', isShow: false, currentCnt: 0, maxCnt: 0 }; /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Constructor |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ // 생성자 constructor(private broadCaster: EventBroadcaster, protected elementRef: ElementRef, protected injector: Injector) { super(elementRef, injector); } /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Override Method |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ /** * 클래스 초기화 */ public ngOnInit() { super.ngOnInit(); } // function - ngOnInit /** * 화면 초기화 이후 처리 */ public ngAfterViewInit() { // Header 내 아이콘이 그러지지 않는 상황에 대한 임시 해결 setTimeout(() => { if (this.isPageWidget && this.widget) { const pageWidgetConf: PageWidgetConfiguration = this.widget.configuration as PageWidgetConfiguration; if (ChartType.MAP === pageWidgetConf.chart.type) { if (pageWidgetConf.shelf.layers .filter(layer => layer.name !== CommonConstant.MAP_ANALYSIS_LAYER_NAME) .some(layer => { return this.isNullOrUndefined(this.widget.dashBoard.dataSources.find(item => item.engineName === layer.ref)); })) { this.isMissingDataSource = true; } } else { const widgetDataSource: Datasource = DashboardUtil.getDataSourceFromBoardDataSource(this.widget.dashBoard, pageWidgetConf.dataSource); this.isMissingDataSource = !widgetDataSource; } } else { this.isMissingDataSource = false; } this.safelyDetectChanges(); }, 200); // Event for Chart Limit this.subscriptions.push( this.broadCaster.on<any>('WIDGET_LIMIT_INFO').subscribe( (data: { id: string, isShow: boolean, currentCnt: number, maxCnt: number }) => { if (this.widget.id === data.id) { this.limitInfo = data; this.safelyDetectChanges(); } }) ); } // function - ngAfterViewInit // Destory public ngOnDestroy() { super.ngOnDestroy(); } // function - ngOnDestroy /** * 너비 변경을 체크하기 위한 작업 * ( 너무 빈번한 호출로. 퍼포먼스 문제가 있음.. 후에 변경되어야 함 ) */ public ngDoCheck() { if (this.isEditMode()) { this.isMiniHeader = (300 > this.controlContainer.nativeElement.offsetWidth); } } // function - ngDoCheck /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Public Method |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ /** * 데이터소스 이름 조회 * @return {string} */ public getDataSourceName(): string { let strName: string = ''; if (this.isPageWidget && this.widget) { const widgetConf: PageWidgetConfiguration = this.widget.configuration as PageWidgetConfiguration; if (ChartType.MAP === widgetConf.chart.type && widgetConf.shelf.layers) { strName = widgetConf.shelf.layers.reduce((acc, currVal) => { const dsInfo: Datasource = this.widget.dashBoard.dataSources.find(item => item.engineName === currVal.ref); if (dsInfo) { acc = ('' === acc) ? acc + dsInfo.name : acc + ',' + dsInfo.name; } return acc; }, ''); } else if (widgetConf.dataSource) { const widgetDataSource: Datasource = DashboardUtil.getDataSourceFromBoardDataSource(this.widget.dashBoard, widgetConf.dataSource); (widgetDataSource) && (strName = widgetDataSource.name); } // enf if - widgetConf.dataSource } // end if - widget return strName; } // function - getDataSourceName /** * 피봇 정보 존재 여부 * @param {string} category * @return {boolean} */ public existPivot(category: string): boolean { return (this.widget && this.widget.configuration['pivot'] && this.widget.configuration['pivot'][category] && 0 < this.widget.configuration['pivot'][category].length); } // function - existPivot /** * 선반의 필드 목록 반환 * @param {string} category * @return {string} */ public getPivotFieldsStr(category: string): string { let strFields: string = ''; if (this.widget && this.widget.configuration['pivot']) { const pivotData = this.widget.configuration['pivot'][category]; if (pivotData) { strFields = pivotData.map(item => item.name).join(','); } } return strFields; } // function - getPivotFieldsStr /** * 범례 설정이 유효한 차트인지 여부 * @returns {boolean} */ public isValidLegend(): boolean { if (this.isPageWidget && this.widget) { const chartConf = this.widget.configuration['chart']; return (this._chartFuncValidator.checkUseLegendByTypeString(chartConf.type) && 'grid' !== (this.widget as PageWidget).mode); } else { return false; } } // function - isValidLegend /** * 차트 필터 존재 여부 * @return {boolean} */ public existChartFilter(): boolean { return (this.isPageWidget && this.widget && (this.widget.configuration as PageWidgetConfiguration).filters && 0 < (this.widget.configuration as PageWidgetConfiguration).filters.length); } // function - existChartFilter /** * 차트 필터 필드 목록 반환 * @return {string} */ public getChartFilterStr(): string { let strFields: string = ''; if (this.isPageWidget && this.widget && (this.widget.configuration as PageWidgetConfiguration).filters) { strFields = (this.widget.configuration as PageWidgetConfiguration).filters.map(item => item.field).join(','); } return strFields; } // function - getChartFilterStr public isValidMiniMap(): boolean { if (this.isPageWidget && this.widget) { const chartConf = this.widget.configuration['chart']; return (this._chartFuncValidator.checkUseMiniMapByTypeString(chartConf.type) && 'grid' !== (this.widget as PageWidget).mode); } else { return false; } } public isRealTimeDashboard(): boolean { if (this.isPageWidget && this.widget) { const boardConf = this.widget.dashBoard.configuration; return (boardConf.options.sync && boardConf.options.sync.enabled); } else { return false; } } public isRealTimeWidget(): boolean { if (this.isPageWidget && this.widget) { return false !== (this.widget.configuration as PageWidgetConfiguration).sync; } else { return false; } } /** * 범례 표시 여부 * @returns {boolean} */ public isShowLegend(): boolean { // if( this.widget ) { // const chartConf = this.widget.configuration['chart']; // return ( chartConf && chartConf.legend && 'grid' !== chartConf.type) ? chartConf.legend.auto : false; // } else { // return false; // } return this.widget.configuration['chart'].legend.auto; } // function - isShowLegend /** * 미니맵 표시 여부 * @returns {boolean} */ public isShowMiniMap(): boolean { if (this.widget) { const chartConf = this.widget.configuration['chart']; return (chartConf && chartConf.chartZooms && 'grid' !== chartConf.type && chartConf.chartZooms) ? chartConf.chartZooms[0].auto : false; } else { return false; } } // function - isShowMiniMap /** * 이름 편집 모드로 변경 * @param {MouseEvent} $event */ public editModeName($event: MouseEvent) { $event.stopImmediatePropagation(); this.isEditTitle = true; this.changeDetect.detectChanges(); } // function - editModeName /** * 이름 변경 등록 * @param {string} inputName */ public changeWidgetName(inputName: string) { this.isEditTitle = false; inputName = inputName ? inputName.trim() : ''; if (inputName && 0 < inputName.length) { this.widget.name = inputName; this.broadCaster.broadcast('WIDGET_CHANGE_TITLE', { widgetId: this.widget.id, value: inputName }); } else { Alert.warning(this.translateService.instant('msg.alert.edit.name.empty')); } } // function - changeWidgetName /** * 그리드 모드의 차트위젯 여부 */ public get isGridModePageWidget() { return (this.widget) ? 'grid' === (this.widget as PageWidget).mode : false; } // function - isGridModePageWidget /** * 페이지 위젯 여부 * @returns {boolean} */ public get isPageWidget(): boolean { return (this.widget) ? 'page' === this.widget.type : false; } // function - isPageWidget /** * Dimension 필터 위젯 여부 * @returns {boolean} */ public get isDimensionFilterWidget(): boolean { return (this.widget && 'filter' === this.widget.type && 'include' === (this.widget.configuration as FilterWidgetConfiguration).filter.type); } // function - isDimensionFilterWidget /** * List 형태 여부 - Dimension Filter * @return {boolean} */ public get isListDimensionFilter(): boolean { const filter: Filter = (this.widget.configuration as FilterWidgetConfiguration).filter; if ('include' === filter.type) { const selector: InclusionSelectorType = (filter as InclusionFilter).selector; return -1 < selector.toString().indexOf('LIST'); } else { return false; } } // function - isListDimensionFilter /** * 텍스트 위젯 여부 * @returns {boolean} */ public get isTextWidget(): boolean { return (this.widget) ? 'text' === this.widget.type : false; } // function - isTextWidget /** * 편집 모드 여부를 반환한다. * @returns {boolean} */ public isEditMode(): boolean { return this.layoutMode === LayoutMode.EDIT; } // function - siEditMode /** * 제목 표시 변경 * * @param event - 마우스이벤트 */ public toggleTitle(event: MouseEvent) { event.stopPropagation(); event.preventDefault(); this.isShowTitle = !this.isShowTitle; this.broadCaster.broadcast('TOGGLE_TITLE', { widgetId: this.widget.id, widgetType: this.widget.type, mode: this.isShowTitle }); } // function - toggleTitle /** * 범례 표시 변경 * * @param event - 마우스이벤트 */ public toggleLegend(event: MouseEvent) { event.stopPropagation(); event.preventDefault(); this.broadCaster.broadcast('TOGGLE_LEGEND', {widgetId: this.widget.id}); } // function - toggleLegend /** * 미니맵 표시 변경 * * @param event - 마우스이벤트 */ public toggleMiniMap(event: MouseEvent) { event.stopPropagation(); event.preventDefault(); this.broadCaster.broadcast('TOGGLE_MINIMAP', {widgetId: this.widget.id}); } // function - toggleMiniMap public toggleSync() { this.broadCaster.broadcast('TOGGLE_SYNC', {widgetId: this.widget.id}); } /** * 위젯 수정 */ public editWidget() { if (this.isMissingDataSource) { Alert.warning(this.translateService.instant('msg.board.alert.can-not-edit-missing-datasource')); return; } this.broadCaster.broadcast('EDIT_WIDGET', {widgetId: this.widget.id, widgetType: this.widget.type}); } // function - editWidget /** * 위젯 복제 */ public copyPageWidget() { if (this.isMissingDataSource) { Alert.warning(this.translateService.instant('msg.board.alert.can-not-copy-missing-datasource')); return; } this.broadCaster.broadcast('COPY_WIDGET', {widgetId: this.widget.id}); } // function - copyPageWidget /** * 위젯 모드 변경 * @param {string} mode */ public onChangeWidgetMode(mode: string) { if (this.isPageWidget) { (this.widget as PageWidget).mode = mode; this.broadCaster.broadcast('CHANGE_MODE', {widgetId: this.widget.id, mode: mode}); } } // function - onChangeWidgetMode /** * 위젯 삭제 */ public removeWidget() { this.broadCaster.broadcast('REMOVE', {widgetId: this.widget.id, widgetType: this.widget.type}); } // function - removeWidget /** * 그리드 버튼 표시 여부 * @param {PageWidget} widget * @returns {boolean} */ public isAvailableGrid(widget: Widget) { const chartType = (widget.configuration as PageWidgetConfiguration).chart.type.toString(); const invalidChart = ['grid', 'scatter', 'pie']; return (-1 === invalidChart.indexOf(chartType)); } // function - isAvailableGrid /** * Dimension Filter 의 Selector Type - List 로 변경 */ public setSelectorTypeList() { const filter: Filter = (this.widget.configuration as FilterWidgetConfiguration).filter; if ('include' === filter.type) { const selector: InclusionSelectorType = (filter as InclusionFilter).selector; switch (selector) { case InclusionSelectorType.SINGLE_LIST : case InclusionSelectorType.SINGLE_COMBO : (filter as InclusionFilter).selector = InclusionSelectorType.SINGLE_LIST; break; case InclusionSelectorType.MULTI_LIST : case InclusionSelectorType.MULTI_COMBO : (filter as InclusionFilter).selector = InclusionSelectorType.MULTI_LIST; break; } (this.widget.configuration as FilterWidgetConfiguration).filter = filter; this.broadCaster.broadcast('CHANGE_FILTER_SELECTOR', {widget: this.widget, filter: filter}); } } // function - setSelectorTypeList /** * Dimension Filter 의 Selector Type - Combo 로 변경 */ public setSelectorTypeCombo() { const filter: Filter = (this.widget.configuration as FilterWidgetConfiguration).filter; if ('include' === filter.type) { const selector: InclusionSelectorType = (filter as InclusionFilter).selector; switch (selector) { case InclusionSelectorType.SINGLE_LIST : case InclusionSelectorType.SINGLE_COMBO : (filter as InclusionFilter).selector = InclusionSelectorType.SINGLE_COMBO; break; case InclusionSelectorType.MULTI_LIST : case InclusionSelectorType.MULTI_COMBO : (filter as InclusionFilter).selector = InclusionSelectorType.MULTI_COMBO; break; } (this.widget.configuration as FilterWidgetConfiguration).filter = filter; this.broadCaster.broadcast('CHANGE_FILTER_SELECTOR', {widget: this.widget, filter: filter}); } } // function - setSelectorTypeCombo /** * 추가 설정 레이어 표시 On/Off */ public toggleDisplayMoreLayer() { this.isShowMore = !this.isShowMore; if (this.isShowMore) { this.mouseOverHeader(); } else { this.mouseOutHeader(true); } } // function - toggleDisplayMoreLayer /** * Header 에 마우스 오버 했을 때의 동작 */ public mouseOverHeader() { if (0 === $('.sys-widget-header-layer:visible').length) { this.$element.closest('.lm_header') .attr('style', 'display: block; height: 25px; z-index:21 !important;'); } } // function - mouseOverHeader /** * Header 에 마우스 아웃 했을 때의 상황 */ public mouseOutHeader(isForce: boolean = false) { if (isForce || !this.isShowMore) { this.$element.closest('.lm_header') .attr('style', 'display: block; height: 25px;'); this.isShowMore = false; } } // function - mouseOutHeader /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Private Method |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ }
the_stack
import msRestAzure = require("./azure-arm-common"); import tl = require('vsts-task-lib/task'); import util = require("util"); import webClient = require("./webClient"); import azureServiceClient = require("./AzureServiceClient"); import Model = require("./azureModels"); import Q = require("q"); export class ComputeManagementClient extends azureServiceClient.ServiceClient { public virtualMachines: VirtualMachines; public virtualMachineExtensions: VirtualMachineExtensions; public virtualMachineScaleSets: VirtualMachineScaleSets; constructor(credentials: msRestAzure.ApplicationTokenCredentials, subscriptionId, baseUri?: any, options?: any) { super(credentials, subscriptionId); this.acceptLanguage = 'en-US'; this.generateClientRequestId = true; this.apiVersion = (credentials.isAzureStackEnvironment) ? '2015-06-15' : '2016-03-30'; if (!options) options = {}; if (baseUri) { this.baseUri = baseUri; } if (options.acceptLanguage) { this.acceptLanguage = options.acceptLanguage; } if (options.longRunningOperationRetryTimeout) { this.longRunningOperationRetryTimeout = options.longRunningOperationRetryTimeout; } if (options.generateClientRequestId) { this.generateClientRequestId = options.generateClientRequestId; } this.virtualMachines = new VirtualMachines(this); this.virtualMachineExtensions = new VirtualMachineExtensions(this); this.virtualMachineScaleSets = new VirtualMachineScaleSets(this); } } export class VirtualMachines { private client: ComputeManagementClient; constructor(client) { this.client = client; } public list(resourceGroupName, options, callback: azureServiceClient.ApiCallback) { if (!callback && typeof options === 'function') { callback = options; options = null; } if (!callback) { throw new Error(tl.loc("CallbackCannotBeNull")); } // Validate try { this.client.isValidResourceGroupName(resourceGroupName); } catch (error) { return callback(error); } var httpRequest = new webClient.WebRequest(); httpRequest.method = 'GET'; httpRequest.headers = this.client.setCustomHeaders(options); httpRequest.uri = this.client.getRequestUri('//subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines', { '{resourceGroupName}': resourceGroupName } ); var result = []; this.client.beginRequest(httpRequest).then(async (response: webClient.WebResponse) => { if (response.statusCode == 200) { if (response.body.value) { result = result.concat(response.body.value); } if (response.body.nextLink) { var nextResult = await this.client.accumulateResultFromPagedResult(response.body.nextLink); if (nextResult.error) { return new azureServiceClient.ApiResult(nextResult.error); } result = result.concat(nextResult.result); } return new azureServiceClient.ApiResult(null, result); } else { return new azureServiceClient.ApiResult(azureServiceClient.ToError(response)); } }).then((apiResult: azureServiceClient.ApiResult) => callback(apiResult.error, apiResult.result), (error) => callback(error)); } public get(resourceGroupName, vmName, options, callback: azureServiceClient.ApiCallback) { var client = this.client; if (!callback && typeof options === 'function') { callback = options; options = null; } if (!callback) { throw new Error(tl.loc("CallbackCannotBeNull")); } var expand = (options && options.expand !== undefined) ? options.expand : undefined; // Validate try { this.client.isValidResourceGroupName(resourceGroupName); if (vmName === null || vmName === undefined || typeof vmName.valueOf() !== 'string') { throw new Error(tl.loc("VMNameCannotBeNull")); } if (expand) { var allowedValues = ['instanceView']; if (!allowedValues.some(function (item) { return item === expand; })) { throw new Error(tl.loc("InvalidValue", expand, allowedValues)); } } } catch (error) { return callback(error); } var httpRequest = new webClient.WebRequest(); httpRequest.method = 'GET'; httpRequest.uri = this.client.getRequestUri('//subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}', { '{resourceGroupName}': resourceGroupName, '{vmName}': vmName }, ['$expand=' + encodeURIComponent(expand)] ); // Set Headers httpRequest.headers = this.client.setCustomHeaders(options); this.client.beginRequest(httpRequest).then((response: webClient.WebResponse) => { var deferred = Q.defer<azureServiceClient.ApiResult>(); if (response.statusCode == 200) { var result = response.body; deferred.resolve(new azureServiceClient.ApiResult(null, result)); } else { deferred.resolve(new azureServiceClient.ApiResult(azureServiceClient.ToError(response))); } return deferred.promise; }).then((apiResult: azureServiceClient.ApiResult) => callback(apiResult.error, apiResult.result), (error) => callback(error)); } public restart(resourceGroupName: string, vmName: string, callback: azureServiceClient.ApiCallback) { var client = this.client; if (!callback) { throw new Error(tl.loc("CallbackCannotBeNull")); } // Validate try { this.client.isValidResourceGroupName(resourceGroupName); if (vmName === null || vmName === undefined || typeof vmName.valueOf() !== 'string') { throw new Error(tl.loc("VMNameCannotBeNull")); } } catch (error) { return callback(error); } // Create object var httpRequest = new webClient.WebRequest(); httpRequest.method = 'POST'; httpRequest.uri = this.client.getRequestUri('//subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/restart', { '{resourceGroupName}': resourceGroupName, '{vmName}': vmName } ); // Set Headers httpRequest.headers = this.client.setCustomHeaders(null); httpRequest.body = null; this.client.beginRequest(httpRequest).then((response: webClient.WebResponse) => { var deferred = Q.defer<azureServiceClient.ApiResult>(); if (response.statusCode != 202) { deferred.resolve(new azureServiceClient.ApiResult(azureServiceClient.ToError(response))); } else { this.client.getLongRunningOperationResult(response).then((operationResponse: webClient.WebResponse) => { if (operationResponse.body.status == "Succeeded") { deferred.resolve(new azureServiceClient.ApiResult(null, operationResponse.body)); } else { deferred.resolve(new azureServiceClient.ApiResult(azureServiceClient.ToError(operationResponse))); } }, (error) => deferred.reject(error)); } return deferred.promise; }).then((apiResult: azureServiceClient.ApiResult) => callback(apiResult.error, apiResult.result), (error) => callback(error)); } public start(resourceGroupName: string, vmName: string, callback: azureServiceClient.ApiCallback) { var client = this.client; if (!callback) { throw new Error(tl.loc("CallbackCannotBeNull")); } // Validate try { this.client.isValidResourceGroupName(resourceGroupName); if (vmName === null || vmName === undefined || typeof vmName.valueOf() !== 'string') { throw new Error(tl.loc("VMNameCannotBeNull")); } } catch (error) { return callback(error); } var httpRequest = new webClient.WebRequest(); httpRequest.method = 'POST'; httpRequest.uri = this.client.getRequestUri('//subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/start', { '{resourceGroupName}': resourceGroupName, '{vmName}': vmName }); httpRequest.headers = this.client.setCustomHeaders(null); httpRequest.body = null; this.client.beginRequest(httpRequest).then((response: webClient.WebResponse) => { var deferred = Q.defer<azureServiceClient.ApiResult>(); var statusCode = response.statusCode; if (statusCode != 202) { deferred.resolve(new azureServiceClient.ApiResult(azureServiceClient.ToError(response))); } else { this.client.getLongRunningOperationResult(response).then((operationResponse: webClient.WebResponse) => { if (operationResponse.body.status == "Succeeded") { deferred.resolve(new azureServiceClient.ApiResult(null, operationResponse.body)); } else { deferred.resolve(new azureServiceClient.ApiResult(azureServiceClient.ToError(operationResponse))); } }, (error) => deferred.reject(error)); } return deferred.promise; }).then((apiResult: azureServiceClient.ApiResult) => callback(apiResult.error, apiResult.result), (error) => callback(error)); } public powerOff(resourceGroupName: string, vmName: string, callback: azureServiceClient.ApiCallback) { var client = this.client; if (!callback) { throw new Error(tl.loc("CallbackCannotBeNull")); } // Validate try { this.client.isValidResourceGroupName(resourceGroupName); if (vmName === null || vmName === undefined || typeof vmName.valueOf() !== 'string') { throw new Error(tl.loc("VMNameCannotBeNull")); } } catch (error) { return callback(error); } var httpRequest = new webClient.WebRequest(); httpRequest.method = 'POST'; httpRequest.headers = this.client.setCustomHeaders(null); httpRequest.uri = this.client.getRequestUri('//subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/powerOff', { '{resourceGroupName}': resourceGroupName, '{vmName}': vmName } ); this.client.beginRequest(httpRequest).then((response: webClient.WebResponse) => { var deferred = Q.defer<azureServiceClient.ApiResult>(); var statusCode = response.statusCode; if (statusCode != 202) { deferred.resolve(new azureServiceClient.ApiResult(azureServiceClient.ToError(response))); } else { this.client.getLongRunningOperationResult(response).then((operationResponse: webClient.WebResponse) => { if (operationResponse.body.status == "Succeeded") { deferred.resolve(new azureServiceClient.ApiResult(null, operationResponse.body)); } else { deferred.resolve(new azureServiceClient.ApiResult(azureServiceClient.ToError(operationResponse))); } }, (error) => deferred.reject(error)); } return deferred.promise; }).then((apiResult: azureServiceClient.ApiResult) => callback(apiResult.error, apiResult.result), (error) => callback(error)); } public deallocate(resourceGroupName: string, vmName: string, callback: azureServiceClient.ApiCallback) { var client = this.client; if (!callback) { throw new Error(tl.loc("CallbackCannotBeNull")); } // Validate try { this.client.isValidResourceGroupName(resourceGroupName); if (vmName === null || vmName === undefined || typeof vmName.valueOf() !== 'string') { throw new Error(tl.loc("VMNameCannotBeNull")); } } catch (error) { return callback(error); } var httpRequest = new webClient.WebRequest(); httpRequest.method = 'POST'; httpRequest.headers = this.client.setCustomHeaders(null); httpRequest.uri = this.client.getRequestUri('//subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}/deallocate', { '{resourceGroupName}': resourceGroupName, '{vmName}': vmName } ); this.client.beginRequest(httpRequest).then((response: webClient.WebResponse) => { var deferred = Q.defer<azureServiceClient.ApiResult>(); var statusCode = response.statusCode; if (statusCode != 202) { deferred.resolve(new azureServiceClient.ApiResult(azureServiceClient.ToError(response))); } else { this.client.getLongRunningOperationResult(response).then((operationResponse: webClient.WebResponse) => { if (operationResponse.body.status == "Succeeded") { deferred.resolve(new azureServiceClient.ApiResult(null, operationResponse.body)); } else { deferred.resolve(new azureServiceClient.ApiResult(azureServiceClient.ToError(operationResponse))); } }, (error) => deferred.reject(error)); } return deferred.promise; }).then((apiResult: azureServiceClient.ApiResult) => callback(apiResult.error, apiResult.result), (error) => callback(error)); } public deleteMethod(resourceGroupName: string, vmName: string, callback: azureServiceClient.ApiCallback) { var client = this.client; if (!callback) { throw new Error(tl.loc("CallbackCannotBeNull")); } // Validate try { this.client.isValidResourceGroupName(resourceGroupName); if (vmName === null || vmName === undefined || typeof vmName.valueOf() !== 'string') { throw new Error(tl.loc("VMNameCannotBeNull")); } } catch (error) { return callback(error); } // Create object var httpRequest = new webClient.WebRequest(); httpRequest.method = 'DELETE'; httpRequest.headers = this.client.setCustomHeaders(null); httpRequest.uri = this.client.getRequestUri('//subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmName}', { '{resourceGroupName}': resourceGroupName, '{vmName}': vmName } ); httpRequest.body = null; this.client.beginRequest(httpRequest).then((response: webClient.WebResponse) => { var deferred = Q.defer<azureServiceClient.ApiResult>(); var statusCode = response.statusCode; if (statusCode != 202 && statusCode != 204) { deferred.resolve(new azureServiceClient.ApiResult(azureServiceClient.ToError(response))); } else { this.client.getLongRunningOperationResult(response).then((operationResponse: webClient.WebResponse) => { if (operationResponse.body.status === "Succeeded") { // Generate Response deferred.resolve(new azureServiceClient.ApiResult(null, operationResponse.body)); } else { deferred.resolve(new azureServiceClient.ApiResult(azureServiceClient.ToError(operationResponse))); } }, (error) => deferred.reject(error)); } return deferred.promise; }).then((apiResult: azureServiceClient.ApiResult) => callback(apiResult.error, apiResult.result), (error) => callback(error)); } } export class VirtualMachineExtensions { private client: ComputeManagementClient; constructor(client: ComputeManagementClient) { this.client = client; } public list(resourceGroupName: string, resourceName: string, resourceType: Model.ComputeResourceType, options, callback: azureServiceClient.ApiCallback) { if (!callback && typeof options === 'function') { callback = options; options = null; } if (!callback) { throw new Error(tl.loc("CallbackCannotBeNull")); } // Validate try { this.client.isValidResourceGroupName(resourceGroupName); if (resourceName === null || resourceName === undefined || typeof resourceName.valueOf() !== 'string') { throw new Error(tl.loc("ResourceNameCannotBeNull")); } } catch (error) { return callback(error); } var httpRequest = new webClient.WebRequest(); httpRequest.method = 'GET'; httpRequest.headers = this.client.setCustomHeaders(options); httpRequest.uri = this.client.getRequestUri('//subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/{resourceType}/{resourceName}/extensions', { '{resourceGroupName}': resourceGroupName, '{resourceType}': getComputeResourceTypeString(resourceType), '{resourceName}': resourceName } ); var result = []; this.client.beginRequest(httpRequest).then(async (response: webClient.WebResponse) => { if (response.statusCode == 200) { if (response.body.value) { result = result.concat(response.body.value); } if (response.body.nextLink) { var nextResult = await this.client.accumulateResultFromPagedResult(response.body.nextLink); if (nextResult.error) { return new azureServiceClient.ApiResult(nextResult.error); } result = result.concat(nextResult.result); } return new azureServiceClient.ApiResult(null, result); } else { return new azureServiceClient.ApiResult(azureServiceClient.ToError(response), result); } }).then((apiResult: azureServiceClient.ApiResult) => callback(apiResult.error, apiResult.result), (error) => callback(error)); } public get(resourceGroupName: string, resourceName: string, resourceType: Model.ComputeResourceType, vmExtensionName: string, options, callback: azureServiceClient.ApiCallback) { var client = this.client; if (!callback && typeof options === 'function') { callback = options; options = null; } if (!callback) { throw new Error(tl.loc("CallbackCannotBeNull")); } var expand = (options && options.expand !== undefined) ? options.expand : undefined; // Validate try { this.client.isValidResourceGroupName(resourceGroupName); if (resourceName === null || resourceName === undefined || typeof resourceName.valueOf() !== 'string') { throw new Error(tl.loc("ResourceNameCannotBeNull")); } if (vmExtensionName === null || vmExtensionName === undefined || typeof vmExtensionName.valueOf() !== 'string') { throw new Error(tl.loc("VmExtensionNameCannotBeNull")); } if (expand !== null && expand !== undefined && typeof expand.valueOf() !== 'string') { throw new Error(tl.loc("ExpandShouldBeOfTypeString")); } } catch (error) { return callback(error); } // Create HTTP transport objects var httpRequest = new webClient.WebRequest(); httpRequest.method = 'GET'; httpRequest.headers = this.client.setCustomHeaders(options); httpRequest.uri = this.client.getRequestUri('//subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/{resourceType}/{resourceName}/extensions/{vmExtensionName}', { '{resourceGroupName}': resourceGroupName, '{resourceType}': getComputeResourceTypeString(resourceType), '{resourceName}': resourceName, '{vmExtensionName}': vmExtensionName } ); httpRequest.body = null; this.client.beginRequest(httpRequest).then((response: webClient.WebResponse) => { var deferred = Q.defer<azureServiceClient.ApiResult>(); if (response.statusCode == 200) { var result = response.body; deferred.resolve(new azureServiceClient.ApiResult(null, result)); } else { deferred.resolve(new azureServiceClient.ApiResult(azureServiceClient.ToError(response))); } return deferred.promise; }).then((apiResult: azureServiceClient.ApiResult) => callback(apiResult.error, apiResult.result), (error) => callback(error)); } public createOrUpdate(resourceGroupName: string, resourceName: string, resourceType: Model.ComputeResourceType, vmExtensionName: string, extensionParameters, callback: azureServiceClient.ApiCallback): void { var client = this.client; if (!callback) { throw new Error(tl.loc("CallbackCannotBeNull")); } // Validate try { this.client.isValidResourceGroupName(resourceGroupName); if (resourceName === null || resourceName === undefined || typeof resourceName.valueOf() !== 'string') { throw new Error(tl.loc("ResourceNameCannotBeNull")); } if (vmExtensionName === null || vmExtensionName === undefined || typeof vmExtensionName.valueOf() !== 'string') { throw new Error(tl.loc("VmExtensionNameCannotBeNull")); } if (extensionParameters === null || extensionParameters === undefined) { throw new Error(tl.loc("ExtensionParametersCannotBeNull")); } } catch (error) { return callback(error); } // Create HTTP transport objects var httpRequest = new webClient.WebRequest(); httpRequest.method = 'PUT'; httpRequest.headers = this.client.setCustomHeaders(null); httpRequest.uri = this.client.getRequestUri('//subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/{resourceType}/{resourceName}/extensions/{vmExtensionName}', { '{resourceGroupName}': resourceGroupName, '{resourceType}': getComputeResourceTypeString(resourceType), '{resourceName}': resourceName, '{vmExtensionName}': vmExtensionName } ); // Serialize Request var requestContent = null; var requestModel = null; if (extensionParameters !== null && extensionParameters !== undefined) { httpRequest.body = JSON.stringify(extensionParameters); } // Send request this.client.beginRequest(httpRequest).then((response: webClient.WebResponse) => { var deferred = Q.defer<azureServiceClient.ApiResult>(); if (response.statusCode != 200 && response.statusCode != 201) { deferred.resolve(new azureServiceClient.ApiResult(azureServiceClient.ToError(response))); } else { this.client.getLongRunningOperationResult(response).then((operationResponse: webClient.WebResponse) => { if (operationResponse.body.status === "Succeeded") { var result = { properties: { "provisioningState": operationResponse.body.status } }; deferred.resolve(new azureServiceClient.ApiResult(null, result)); } else { deferred.resolve(new azureServiceClient.ApiResult(azureServiceClient.ToError(operationResponse))); } }, (error) => deferred.reject(error)); } return deferred.promise; }).then((apiResult: azureServiceClient.ApiResult) => callback(apiResult.error, apiResult.result), (error) => callback(error)); } public deleteMethod(resourceGroupName: string, resourceName: string, resourceType: Model.ComputeResourceType, vmExtensionName: string, callback: azureServiceClient.ApiCallback) { if (!callback) { throw new Error(tl.loc("CallbackCannotBeNull")); } // Validate try { this.client.isValidResourceGroupName(resourceGroupName); if (resourceName === null || resourceName === undefined || typeof resourceName.valueOf() !== 'string') { throw new Error(tl.loc("ResourceNameCannotBeNull")); } if (vmExtensionName === null || vmExtensionName === undefined || typeof vmExtensionName.valueOf() !== 'string') { throw new Error(tl.loc("VmExtensionNameCannotBeNull")); } } catch (error) { return callback(error); } // Create HTTP transport objects var httpRequest = new webClient.WebRequest(); httpRequest.method = 'DELETE'; httpRequest.uri = this.client.getRequestUri('//subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/{resourceType}/{resourceName}/extensions/{vmExtensionName}', { '{resourceGroupName}': resourceGroupName, '{resourceType}': getComputeResourceTypeString(resourceType), '{resourceName}': resourceName, '{vmExtensionName}': vmExtensionName } ); // Send request this.client.beginRequest(httpRequest).then((response: webClient.WebResponse) => { var deferred = Q.defer<azureServiceClient.ApiResult>(); if (response.statusCode !== 202 && response.statusCode !== 204) { deferred.resolve(new azureServiceClient.ApiResult(azureServiceClient.ToError(response))); } else { this.client.getLongRunningOperationResult(response).then((operationResponse: webClient.WebResponse) => { if (operationResponse.statusCode === 200) { deferred.resolve(new azureServiceClient.ApiResult(null)); } else { deferred.resolve(new azureServiceClient.ApiResult(azureServiceClient.ToError(operationResponse))); } }, (error) => deferred.reject(error)); } return deferred.promise; }).then((apiResult: azureServiceClient.ApiResult) => callback(apiResult.error, apiResult.result), (error) => callback(error)); } } export class VirtualMachineScaleSets { private client: ComputeManagementClient; constructor(client) { this.client = client; } public list(options, callback: azureServiceClient.ApiCallback) { if (!callback && typeof options === 'function') { callback = options; options = null; } if (!callback) { throw new Error(tl.loc("CallbackCannotBeNull")); } var httpRequest = new webClient.WebRequest(); httpRequest.method = 'GET'; httpRequest.headers = this.client.setCustomHeaders(options); httpRequest.uri = this.client.getRequestUri('//subscriptions/{subscriptionId}/providers/Microsoft.Compute/virtualMachineScaleSets', {}); var result = []; this.client.beginRequest(httpRequest).then(async (response: webClient.WebResponse) => { if (response.statusCode == 200) { if (response.body.value) { result = result.concat(response.body.value); } if (response.body.nextLink) { var nextResult = await this.client.accumulateResultFromPagedResult(response.body.nextLink); if (nextResult.error) { return new azureServiceClient.ApiResult(nextResult.error); } result = result.concat(nextResult.result); } return new azureServiceClient.ApiResult(null, result); } else { return new azureServiceClient.ApiResult(azureServiceClient.ToError(response), result); } }).then((apiResult: azureServiceClient.ApiResult) => callback(apiResult.error, apiResult.result), (error) => callback(error)); } public get(resourceGroupName: string, vmssName: string, options, callback: azureServiceClient.ApiCallback) { var client = this.client; if (!callback && typeof options === 'function') { callback = options; options = null; } if (!callback) { throw new Error(tl.loc("CallbackCannotBeNull")); } var expand = (options && options.expand !== undefined) ? options.expand : undefined; // Validate try { this.client.isValidResourceGroupName(resourceGroupName); if (vmssName === null || vmssName === undefined || typeof vmssName.valueOf() !== 'string') { throw new Error(tl.loc("VMSSNameCannotBeNull")); } if (expand) { var allowedValues = ['instanceView']; if (!allowedValues.some(function (item) { return item === expand; })) { throw new Error(tl.loc("InvalidValue", expand, allowedValues)); } } } catch (error) { return callback(error); } var httpRequest = new webClient.WebRequest(); httpRequest.method = 'GET'; httpRequest.uri = this.client.getRequestUri('//subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmssName}', { '{resourceGroupName}': resourceGroupName, '{vmssName}': vmssName }, ['$expand=' + encodeURIComponent(expand)] ); // Set Headers httpRequest.headers = this.client.setCustomHeaders(options); this.client.beginRequest(httpRequest).then((response: webClient.WebResponse) => { var deferred = Q.defer<azureServiceClient.ApiResult>(); if (response.statusCode == 200) { var result = response.body; deferred.resolve(new azureServiceClient.ApiResult(null, result)); } else { deferred.resolve(new azureServiceClient.ApiResult(azureServiceClient.ToError(response))); } return deferred.promise; }).then((apiResult: azureServiceClient.ApiResult) => callback(apiResult.error, apiResult.result), (error) => callback(error)); } public updateImage(resourceGroupName: string, vmssName: string, imageUrl: string, options, callback: azureServiceClient.ApiCallback) { var client = this.client; if (!callback && typeof options === 'function') { callback = options; options = null; } if (!callback) { throw new Error(tl.loc("CallbackCannotBeNull")); } if (imageUrl === null || imageUrl === undefined || typeof imageUrl.valueOf() !== 'string') { throw new Error(tl.loc("VMSSImageUrlCannotBeNull")); } var expand = (options && options.expand !== undefined) ? options.expand : undefined; // Validate try { this.client.isValidResourceGroupName(resourceGroupName); if (vmssName === null || vmssName === undefined || typeof vmssName.valueOf() !== 'string') { throw new Error(tl.loc("VMSSNameCannotBeNull")); } } catch (error) { return callback(error); } // get VMSS this.get(resourceGroupName, vmssName, null, (error, result, request, response) => { if (error) { tl.warning(tl.loc("GetVMSSFailed", resourceGroupName, vmssName, error)); return callback(error, null); } var vmss: Model.VMSS = result; var osDisk = vmss.properties.virtualMachineProfile.storageProfile.osDisk; if (!(osDisk && osDisk.image && osDisk.image.uri)) { return callback(tl.loc("VMSSDoesNotHaveCustomImage", vmssName)); } if (imageUrl === osDisk.image.uri) { console.log(tl.loc("VMSSImageAlreadyUptoDate", vmssName)); return callback(null, null); } // update image uri osDisk.image.uri = imageUrl; var storageProfile: Model.StorageProfile = { "osDisk": osDisk }; // update VM extension var oldExtensionProfile: Model.ExtensionProfile = vmss.properties.virtualMachineProfile.extensionProfile; var virtualMachineProfile: Model.VirtualMachineProfile = { "storageProfile": storageProfile }; var properties: Model.VMSSProperties = { "virtualMachineProfile": virtualMachineProfile }; var patchBody: Model.VMSS = { "id": vmss["id"], "name": vmss["name"], "properties": properties }; var httpRequest = new webClient.WebRequest(); httpRequest.method = 'PATCH'; httpRequest.uri = this.client.getRequestUri('//subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachineScaleSets/{vmssName}', { '{resourceGroupName}': resourceGroupName, '{vmssName}': vmssName } ); // Set Headers httpRequest.headers = this.client.setCustomHeaders(options); httpRequest.body = JSON.stringify(patchBody); // patch VMSS image console.log(tl.loc("NewVMSSImageUrl", imageUrl)); console.log(tl.loc("VMSSUpdateImage", vmssName)); this.client.beginRequest(httpRequest).then((response: webClient.WebResponse) => { var deferred = Q.defer<azureServiceClient.ApiResult>(); var statusCode = response.statusCode; if (response.statusCode == 200) { // wait for image update to complete this.client.getLongRunningOperationResult(response).then((operationResponse: webClient.WebResponse) => { if (operationResponse.body.status === "Succeeded") { deferred.resolve(new azureServiceClient.ApiResult(null, operationResponse.body)); } else { deferred.resolve(new azureServiceClient.ApiResult(azureServiceClient.ToError(operationResponse))); } }, (error) => deferred.reject(error)); } else { deferred.resolve(new azureServiceClient.ApiResult(azureServiceClient.ToError(response))); } return deferred.promise; }).then((apiResult: azureServiceClient.ApiResult) => callback(apiResult.error, apiResult.result), (error) => callback(error)); }); } } export function getComputeResourceTypeString(resourceType: Model.ComputeResourceType): string { switch (resourceType) { case Model.ComputeResourceType.VirtualMachine: return "virtualMachines" case Model.ComputeResourceType.VirtualMachineScaleSet: return "virtualMachineScaleSets" } }
the_stack
import { Abstract } from "./Abstract" import { TeamSpeak } from "../TeamSpeak" import { ClientEntry } from "../types/ResponseTypes" import { ClientDBEdit, ClientEdit } from "../types/PropertyTypes" import { ClientType } from "../types/enum" import { TeamSpeakChannel } from "./Channel" import { TeamSpeakServerGroup } from "./ServerGroup" import { Permission } from "../util/Permission" export class TeamSpeakClient extends Abstract<ClientEntry> { constructor(parent: TeamSpeak, list: ClientEntry) { super(parent, list, "client") } get clid() { return super.getPropertyByName("clid") } get cid() { return super.getPropertyByName("cid") } get databaseId() { return super.getPropertyByName("clientDatabaseId") } get nickname() { return super.getPropertyByName("clientNickname") } get type() { return super.getPropertyByName("clientType") } get uniqueIdentifier() { return super.getPropertyByName("clientUniqueIdentifier") } get away() { return super.getPropertyByName("clientAway") } get awayMessage() { return super.getPropertyByName("clientAwayMessage") } get flagTalking() { return super.getPropertyByName("clientFlagTalking") } get inputMuted() { return super.getPropertyByName("clientInputMuted") } get outputMuted() { return super.getPropertyByName("clientOutputMuted") } get inputHardware() { return super.getPropertyByName("clientInputHardware") } get outputHardware() { return super.getPropertyByName("clientOutputHardware") } get talkPower() { return super.getPropertyByName("clientTalkPower") } get isTalker() { return super.getPropertyByName("clientIsTalker") } get isPrioritySpeaker() { return super.getPropertyByName("clientIsPrioritySpeaker") } get isRecording() { return super.getPropertyByName("clientIsRecording") } get isChannelCommander() { return super.getPropertyByName("clientIsChannelCommander") } get servergroups() { return super.getPropertyByName("clientServergroups") } get channelGroupId() { return super.getPropertyByName("clientChannelGroupId") } get channelGroupInheritedChannelId() { return super.getPropertyByName("clientChannelGroupInheritedChannelId") } get version() { return super.getPropertyByName("clientVersion") } get platform() { return super.getPropertyByName("clientPlatform") } get idleTime() { return super.getPropertyByName("clientIdleTime") } get created() { return super.getPropertyByName("clientCreated") } get lastconnected() { return super.getPropertyByName("clientLastconnected") } get country() { return super.getPropertyByName("clientCountry") } get estimatedLocation() { return super.getPropertyByName("clientEstimatedLocation") } get connectionClientIp() { return super.getPropertyByName("connectionClientIp") } get badges() { return super.getPropertyByName("clientBadges") } /** evaluates if the client is a query client or a normal client */ isQuery() { return this.type === ClientType.ServerQuery } /** * Retrieves a displayable Client Link for the TeamSpeak Chat */ getUrl() { return `[URL=client://${this.clid}/${this.uniqueIdentifier}~${encodeURIComponent(this.nickname)}]${this.nickname}[/URL]` } /** returns general info of the client, requires the client to be online */ getInfo() { return super.getParent().clientInfo(this).then(data => data[0]) } /** returns the clients database info */ getDBInfo() { return super.getParent().clientDbInfo(this).then(data => data[0]) } /** returns a list of custom properties for the client */ customInfo() { return super.getParent().customInfo(this) } /** * removes a custom property from the client * @param ident the key which should be deleted */ customDelete(ident: string) { return super.getParent().customDelete(this, ident) } /** * creates or updates a custom property for the client * ident and value can be any value, and are the key value pair of the custom property * @param ident the key which should be set * @param value the value which should be set */ customSet(ident: string, value: string) { return super.getParent().customSet(this, ident, value) } /** * kicks the client from the server * @param msg the message the client should receive when getting kicked */ kickFromServer(msg: string) { return super.getParent().clientKick(this, 5, msg) } /** * kicks the client from their currently joined channel * @param msg the message the client should receive when getting kicked (max 40 Chars) */ kickFromChannel(msg: string) { return super.getParent().clientKick(this, 4, msg) } /** * bans the chosen client with its uid * @param banreason ban reason * @param time bantime in seconds, if left empty it will result in a permaban */ ban(banreason: string, time?: number) { return super.getParent().ban({ uid: this.uniqueIdentifier, time, banreason }) } /** * moves the client to a different channel * @param cid channel id in which the client should get moved * @param cpw the channel password */ move(cid: string|TeamSpeakChannel, cpw?: string) { return super.getParent().clientMove(this, cid, cpw) } /** * adds the client to one or more groups * @param sgid one or more servergroup ids which the client should be added to */ addGroups(sgid: string|string[]|TeamSpeakServerGroup|TeamSpeakServerGroup[]) { return super.getParent().clientAddServerGroup(this, sgid) } /** * Removes the client from one or more groups * @param sgid one or more servergroup ids which the client should be added to */ delGroups(sgid: string|string[]|TeamSpeakServerGroup|TeamSpeakServerGroup[]) { return super.getParent().clientDelServerGroup(this, sgid) } /** * edits the client * @param properties the properties to change */ edit(properties: ClientEdit) { return this.getParent().clientEdit(this, properties) } /** * Changes a clients settings using given properties. * @param properties the properties which should be modified */ dbEdit(properties: ClientDBEdit) { return this.getParent().clientDbEdit(this, properties) } /** * pokes the client with a certain message * @param msg the message the client should receive */ poke(msg: string) { return super.getParent().clientPoke(this, msg) } /** * sends a textmessage to the client * @param msg the message the client should receive */ message(msg: string) { return super.getParent().sendTextMessage(this, 1, msg) } /** * returns a list of permissions defined for the client * @param permsid if the permsid option is set to true the output will contain the permission names */ permList(permsid?: boolean) { return super.getParent().clientPermList(this, permsid) } /** * Adds a set of specified permissions to a client. * Multiple permissions can be added by providing the three parameters of each permission. * A permission can be specified by permid or permsid. * @param perm the permission object to set */ addPerm(perm: Permission.PermType) { return super.getParent().clientAddPerm(this, perm) } /** * Adds a set of specified permissions to a client. * Multiple permissions can be added by providing the three parameters of each permission. * A permission can be specified by permid or permsid. */ createPerm() { return super.getParent().clientAddPerm(this, undefined) } /** * Removes a set of specified permissions from a client. * Multiple permissions can be removed at once. * A permission can be specified by permid or permsid * @param perm the permid or permsid */ delPerm(perm: string|number) { return super.getParent().clientDelPerm(this, perm) } /** returns a Buffer with the avatar of the user */ getAvatar() { return this.getAvatarName().then(name => super.getParent().downloadFile(`/${name}`)) } /** returns a Buffer with the icon of the client */ getIcon() { return this.getIconId().then(id => super.getParent().downloadIcon(id)) } /** returns the avatar name of the client */ getAvatarName() { return this.getDBInfo().then(data => `avatar_${data.clientBase64HashClientUID}`) } /** gets the icon name of the client */ getIconId() { return super.getParent().getIconId(this.permList(true)) } /** retrieves the client id from a string or teamspeak client */ static getId<T extends TeamSpeakClient.ClientType>(client?: T): T extends undefined ? undefined : string static getId(client?: TeamSpeakClient.ClientType): string|undefined { return client instanceof TeamSpeakClient ? client.clid : client } /** retrieves the client dbid from a string or teamspeak client */ static getDbid<T extends TeamSpeakClient.ClientType>(client?: T): T extends undefined ? undefined : string static getDbid(client?: TeamSpeakClient.ClientType): string|undefined { return client instanceof TeamSpeakClient ? client.databaseId : client } /** retrieves the client dbid from a string or teamspeak client */ static getUid<T extends TeamSpeakClient.ClientType>(client?: T): T extends undefined ? undefined : string static getUid(client?: TeamSpeakClient.ClientType): string|undefined { return client instanceof TeamSpeakClient ? client.uniqueIdentifier : client } /** retrieves the clients from an array */ static getMultipleIds(client: TeamSpeakClient.MultiClientType): string[] { const list = Array.isArray(client) ? client : [client] return list.map(c => TeamSpeakClient.getId(c)) as string[] } /** retrieves the clients from an array */ static getMultipleDbids(client: TeamSpeakClient.MultiClientType): string[] { const list = Array.isArray(client) ? client : [client] return list.map(c => TeamSpeakClient.getDbid(c)) as string[] } /** retrieves the clients from an array */ static getMultipleUids(client: TeamSpeakClient.MultiClientType): string[] { const list = Array.isArray(client) ? client : [client] return list.map(c => TeamSpeakClient.getUid(c)) as string[] } } export namespace TeamSpeakClient { export type ClientType = string|TeamSpeakClient export type MultiClientType = string[]|TeamSpeakClient[]|ClientType }
the_stack
const promiseExists = typeof Promise === 'function'; const globalObject = ((Obj) => { if (typeof globalThis === 'object') { return globalThis; // eslint-disable-line } Object.defineProperty(Obj, 'typeDetectGlobalObject', { get() { return this; }, configurable: true, }); // @ts-ignore const global = typeDetectGlobalObject; // eslint-disable-line // @ts-ignore delete Obj.typeDetectGlobalObject; return global; })(Object.prototype); const symbolExists = typeof Symbol !== 'undefined'; const mapExists = typeof Map !== 'undefined'; const setExists = typeof Set !== 'undefined'; const weakMapExists = typeof WeakMap !== 'undefined'; const weakSetExists = typeof WeakSet !== 'undefined'; const dataViewExists = typeof DataView !== 'undefined'; const symbolIteratorExists = symbolExists && typeof Symbol.iterator !== 'undefined'; const symbolToStringTagExists = symbolExists && typeof Symbol.toStringTag !== 'undefined'; const setEntriesExists = setExists && typeof Set.prototype.entries === 'function'; const mapEntriesExists = mapExists && typeof Map.prototype.entries === 'function'; const setIteratorPrototype = setEntriesExists && Object.getPrototypeOf(new Set().entries()); const mapIteratorPrototype = mapEntriesExists && Object.getPrototypeOf(new Map().entries()); const arrayIteratorExists = symbolIteratorExists && typeof Array.prototype[Symbol.iterator] === 'function'; const arrayIteratorPrototype = arrayIteratorExists && Object.getPrototypeOf([][Symbol.iterator]()); const stringIteratorExists = symbolIteratorExists && typeof String.prototype[Symbol.iterator] === 'function'; const stringIteratorPrototype = stringIteratorExists && Object.getPrototypeOf(''[Symbol.iterator]()); const toStringLeftSliceLength = 8; const toStringRightSliceLength = -1; /** * ### typeOf (obj) * * Uses `Object.prototype.toString` to determine the type of an object, * normalising behaviour across engine versions & well optimised. * * @param {Mixed} object * @return {String} object type * @api public */ export default function typeDetect(obj: unknown): string { /* ! Speed optimisation * Pre: * string literal x 3,039,035 ops/sec ±1.62% (78 runs sampled) * boolean literal x 1,424,138 ops/sec ±4.54% (75 runs sampled) * number literal x 1,653,153 ops/sec ±1.91% (82 runs sampled) * undefined x 9,978,660 ops/sec ±1.92% (75 runs sampled) * function x 2,556,769 ops/sec ±1.73% (77 runs sampled) * Post: * string literal x 38,564,796 ops/sec ±1.15% (79 runs sampled) * boolean literal x 31,148,940 ops/sec ±1.10% (79 runs sampled) * number literal x 32,679,330 ops/sec ±1.90% (78 runs sampled) * undefined x 32,363,368 ops/sec ±1.07% (82 runs sampled) * function x 31,296,870 ops/sec ±0.96% (83 runs sampled) */ const typeofObj = typeof obj; if (typeofObj !== 'object') { return typeofObj; } /* ! Speed optimisation * Pre: * null x 28,645,765 ops/sec ±1.17% (82 runs sampled) * Post: * null x 36,428,962 ops/sec ±1.37% (84 runs sampled) */ if (obj === null) { return 'null'; } /* ! Spec Conformance * Test: `Object.prototype.toString.call(window)`` * - Node === "[object global]" * - Chrome === "[object global]" * - Firefox === "[object Window]" * - PhantomJS === "[object Window]" * - Safari === "[object Window]" * - IE 11 === "[object Window]" * - IE Edge === "[object Window]" * Test: `Object.prototype.toString.call(this)`` * - Chrome Worker === "[object global]" * - Firefox Worker === "[object DedicatedWorkerGlobalScope]" * - Safari Worker === "[object DedicatedWorkerGlobalScope]" * - IE 11 Worker === "[object WorkerGlobalScope]" * - IE Edge Worker === "[object WorkerGlobalScope]" */ if (obj === globalObject) { return 'global'; } /* ! Speed optimisation * Pre: * array literal x 2,888,352 ops/sec ±0.67% (82 runs sampled) * Post: * array literal x 22,479,650 ops/sec ±0.96% (81 runs sampled) */ if ( Array.isArray(obj) && (symbolToStringTagExists === false || !(Symbol.toStringTag in obj)) ) { return 'Array'; } // Not caching existence of `window` and related properties due to potential // for `window` to be unset before tests in quasi-browser environments. if (typeof window === 'object' && window !== null) { /* ! Spec Conformance * (https://html.spec.whatwg.org/multipage/browsers.html#location) * WhatWG HTML$7.7.3 - The `Location` interface * Test: `Object.prototype.toString.call(window.location)`` * - IE <=11 === "[object Object]" * - IE Edge <=13 === "[object Object]" */ if (typeof (window as any).location === 'object' && obj === (window as any).location) { return 'Location'; } /* ! Spec Conformance * (https://html.spec.whatwg.org/#document) * WhatWG HTML$3.1.1 - The `Document` object * Note: Most browsers currently adher to the W3C DOM Level 2 spec * (https://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-26809268) * which suggests that browsers should use HTMLTableCellElement for * both TD and TH elements. WhatWG separates these. * WhatWG HTML states: * > For historical reasons, Window objects must also have a * > writable, configurable, non-enumerable property named * > HTMLDocument whose value is the Document interface object. * Test: `Object.prototype.toString.call(document)`` * - Chrome === "[object HTMLDocument]" * - Firefox === "[object HTMLDocument]" * - Safari === "[object HTMLDocument]" * - IE <=10 === "[object Document]" * - IE 11 === "[object HTMLDocument]" * - IE Edge <=13 === "[object HTMLDocument]" */ if (typeof (window as any).document === 'object' && obj === (window as any).document) { return 'Document'; } if (typeof (window as any).navigator === 'object') { /* ! Spec Conformance * (https://html.spec.whatwg.org/multipage/webappapis.html#mimetypearray) * WhatWG HTML$8.6.1.5 - Plugins - Interface MimeTypeArray * Test: `Object.prototype.toString.call(navigator.mimeTypes)`` * - IE <=10 === "[object MSMimeTypesCollection]" */ if (typeof (window as any).navigator.mimeTypes === 'object' && obj === (window as any).navigator.mimeTypes) { return 'MimeTypeArray'; } /* ! Spec Conformance * (https://html.spec.whatwg.org/multipage/webappapis.html#pluginarray) * WhatWG HTML$8.6.1.5 - Plugins - Interface PluginArray * Test: `Object.prototype.toString.call(navigator.plugins)`` * - IE <=10 === "[object MSPluginsCollection]" */ if (typeof (window as any).navigator.plugins === 'object' && obj === (window as any).navigator.plugins) { return 'PluginArray'; } } if ((typeof (window as any).HTMLElement === 'function' || typeof (window as any).HTMLElement === 'object') && obj instanceof (window as any).HTMLElement) { /* ! Spec Conformance * (https://html.spec.whatwg.org/multipage/webappapis.html#pluginarray) * WhatWG HTML$4.4.4 - The `blockquote` element - Interface `HTMLQuoteElement` * Test: `Object.prototype.toString.call(document.createElement('blockquote'))`` * - IE <=10 === "[object HTMLBlockElement]" */ if ((obj as any).tagName === 'BLOCKQUOTE') { return 'HTMLQuoteElement'; } /* ! Spec Conformance * (https://html.spec.whatwg.org/#htmltabledatacellelement) * WhatWG HTML$4.9.9 - The `td` element - Interface `HTMLTableDataCellElement` * Note: Most browsers currently adher to the W3C DOM Level 2 spec * (https://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-82915075) * which suggests that browsers should use HTMLTableCellElement for * both TD and TH elements. WhatWG separates these. * Test: Object.prototype.toString.call(document.createElement('td')) * - Chrome === "[object HTMLTableCellElement]" * - Firefox === "[object HTMLTableCellElement]" * - Safari === "[object HTMLTableCellElement]" */ if ((obj as any).tagName === 'TD') { return 'HTMLTableDataCellElement'; } /* ! Spec Conformance * (https://html.spec.whatwg.org/#htmltableheadercellelement) * WhatWG HTML$4.9.9 - The `td` element - Interface `HTMLTableHeaderCellElement` * Note: Most browsers currently adher to the W3C DOM Level 2 spec * (https://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-82915075) * which suggests that browsers should use HTMLTableCellElement for * both TD and TH elements. WhatWG separates these. * Test: Object.prototype.toString.call(document.createElement('th')) * - Chrome === "[object HTMLTableCellElement]" * - Firefox === "[object HTMLTableCellElement]" * - Safari === "[object HTMLTableCellElement]" */ if ((obj as any).tagName === 'TH') { return 'HTMLTableHeaderCellElement'; } } } /* ! Speed optimisation * Pre: * Float64Array x 625,644 ops/sec ±1.58% (80 runs sampled) * Float32Array x 1,279,852 ops/sec ±2.91% (77 runs sampled) * Uint32Array x 1,178,185 ops/sec ±1.95% (83 runs sampled) * Uint16Array x 1,008,380 ops/sec ±2.25% (80 runs sampled) * Uint8Array x 1,128,040 ops/sec ±2.11% (81 runs sampled) * Int32Array x 1,170,119 ops/sec ±2.88% (80 runs sampled) * Int16Array x 1,176,348 ops/sec ±5.79% (86 runs sampled) * Int8Array x 1,058,707 ops/sec ±4.94% (77 runs sampled) * Uint8ClampedArray x 1,110,633 ops/sec ±4.20% (80 runs sampled) * Post: * Float64Array x 7,105,671 ops/sec ±13.47% (64 runs sampled) * Float32Array x 5,887,912 ops/sec ±1.46% (82 runs sampled) * Uint32Array x 6,491,661 ops/sec ±1.76% (79 runs sampled) * Uint16Array x 6,559,795 ops/sec ±1.67% (82 runs sampled) * Uint8Array x 6,463,966 ops/sec ±1.43% (85 runs sampled) * Int32Array x 5,641,841 ops/sec ±3.49% (81 runs sampled) * Int16Array x 6,583,511 ops/sec ±1.98% (80 runs sampled) * Int8Array x 6,606,078 ops/sec ±1.74% (81 runs sampled) * Uint8ClampedArray x 6,602,224 ops/sec ±1.77% (83 runs sampled) */ const stringTag = (symbolToStringTagExists && (obj as any)[Symbol.toStringTag]); if (typeof stringTag === 'string') { return stringTag; } const objPrototype = Object.getPrototypeOf(obj); /* ! Speed optimisation * Pre: * regex literal x 1,772,385 ops/sec ±1.85% (77 runs sampled) * regex constructor x 2,143,634 ops/sec ±2.46% (78 runs sampled) * Post: * regex literal x 3,928,009 ops/sec ±0.65% (78 runs sampled) * regex constructor x 3,931,108 ops/sec ±0.58% (84 runs sampled) */ if (objPrototype === RegExp.prototype) { return 'RegExp'; } /* ! Speed optimisation * Pre: * date x 2,130,074 ops/sec ±4.42% (68 runs sampled) * Post: * date x 3,953,779 ops/sec ±1.35% (77 runs sampled) */ if (objPrototype === Date.prototype) { return 'Date'; } /* ! Spec Conformance * (http://www.ecma-international.org/ecma-262/6.0/index.html#sec-promise.prototype-@@tostringtag) * ES6$25.4.5.4 - Promise.prototype[@@toStringTag] should be "Promise": * Test: `Object.prototype.toString.call(Promise.resolve())`` * - Chrome <=47 === "[object Object]" * - Edge <=20 === "[object Object]" * - Firefox 29-Latest === "[object Promise]" * - Safari 7.1-Latest === "[object Promise]" */ if (promiseExists && objPrototype === Promise.prototype) { return 'Promise'; } /* ! Speed optimisation * Pre: * set x 2,222,186 ops/sec ±1.31% (82 runs sampled) * Post: * set x 4,545,879 ops/sec ±1.13% (83 runs sampled) */ if (setExists && objPrototype === Set.prototype) { return 'Set'; } /* ! Speed optimisation * Pre: * map x 2,396,842 ops/sec ±1.59% (81 runs sampled) * Post: * map x 4,183,945 ops/sec ±6.59% (82 runs sampled) */ if (mapExists && objPrototype === Map.prototype) { return 'Map'; } /* ! Speed optimisation * Pre: * weakset x 1,323,220 ops/sec ±2.17% (76 runs sampled) * Post: * weakset x 4,237,510 ops/sec ±2.01% (77 runs sampled) */ if (weakSetExists && objPrototype === WeakSet.prototype) { return 'WeakSet'; } /* ! Speed optimisation * Pre: * weakmap x 1,500,260 ops/sec ±2.02% (78 runs sampled) * Post: * weakmap x 3,881,384 ops/sec ±1.45% (82 runs sampled) */ if (weakMapExists && objPrototype === WeakMap.prototype) { return 'WeakMap'; } /* ! Spec Conformance * (http://www.ecma-international.org/ecma-262/6.0/index.html#sec-dataview.prototype-@@tostringtag) * ES6$24.2.4.21 - DataView.prototype[@@toStringTag] should be "DataView": * Test: `Object.prototype.toString.call(new DataView(new ArrayBuffer(1)))`` * - Edge <=13 === "[object Object]" */ if (dataViewExists && objPrototype === DataView.prototype) { return 'DataView'; } /* ! Spec Conformance * (http://www.ecma-international.org/ecma-262/6.0/index.html#sec-%mapiteratorprototype%-@@tostringtag) * ES6$23.1.5.2.2 - %MapIteratorPrototype%[@@toStringTag] should be "Map Iterator": * Test: `Object.prototype.toString.call(new Map().entries())`` * - Edge <=13 === "[object Object]" */ if (mapExists && objPrototype === mapIteratorPrototype) { return 'Map Iterator'; } /* ! Spec Conformance * (http://www.ecma-international.org/ecma-262/6.0/index.html#sec-%setiteratorprototype%-@@tostringtag) * ES6$23.2.5.2.2 - %SetIteratorPrototype%[@@toStringTag] should be "Set Iterator": * Test: `Object.prototype.toString.call(new Set().entries())`` * - Edge <=13 === "[object Object]" */ if (setExists && objPrototype === setIteratorPrototype) { return 'Set Iterator'; } /* ! Spec Conformance * (http://www.ecma-international.org/ecma-262/6.0/index.html#sec-%arrayiteratorprototype%-@@tostringtag) * ES6$22.1.5.2.2 - %ArrayIteratorPrototype%[@@toStringTag] should be "Array Iterator": * Test: `Object.prototype.toString.call([][Symbol.iterator]())`` * - Edge <=13 === "[object Object]" */ if (arrayIteratorExists && objPrototype === arrayIteratorPrototype) { return 'Array Iterator'; } /* ! Spec Conformance * (http://www.ecma-international.org/ecma-262/6.0/index.html#sec-%stringiteratorprototype%-@@tostringtag) * ES6$21.1.5.2.2 - %StringIteratorPrototype%[@@toStringTag] should be "String Iterator": * Test: `Object.prototype.toString.call(''[Symbol.iterator]())`` * - Edge <=13 === "[object Object]" */ if (stringIteratorExists && objPrototype === stringIteratorPrototype) { return 'String Iterator'; } /* ! Speed optimisation * Pre: * object from null x 2,424,320 ops/sec ±1.67% (76 runs sampled) * Post: * object from null x 5,838,000 ops/sec ±0.99% (84 runs sampled) */ if (objPrototype === null) { return 'Object'; } return Object .prototype .toString .call(obj) .slice(toStringLeftSliceLength, toStringRightSliceLength); }
the_stack
// If a UI module has been loaded, we can rely on the publically-published 'name' property // having been set as a way to short-out a UI reload. Its parent object always exists by // this point in the build process. if(!window['keyman']['ui']['name']) { /********************************/ /* */ /* Floating User Interface */ /* */ /********************************/ /** * Do not enclose in an anonymous function, as the compiler may create * global scope variables to replace true, false, null, which can collide * with other variables. * Instead, use the --output-wrapper command during optimization, which will * add the anonymous function to enclose all code, including those optimized * variables which would otherwise have global scope. **/ try { // Declare KeymanWeb, OnScreen keyboard and Util objects var keymanweb=window['keyman']; var util=keymanweb['util']; var dbg=keymanweb['debug']; // Disable UI for touch devices if(util['isTouchDevice']()) throw ''; // User interface global and local variables keymanweb['ui'] = {}; var ui=keymanweb['ui']; ui['name'] = 'float'; ui.KeyboardSelector = null; ui.outerDiv = null; // replaces DivKeymanWeb ui.innerDiv = null; // replaces Lkdiv ui.oskButton = null; // toggles OSK on or off ui.kbdIcon = null; // keyboard icon within OSK button ui.selecting = false; // control focus behaviour during selection ui.updateList = true; // control keyboard list updating ui.updateTimer = null; // prevent unnecessary list refreshing ui.floatRight = false; // align left by default ui.initialized = false; // initialization flag /** * Display or hide the OSK from the OSK icon link */ ui.toggleOSK = function() { let osk = keymanweb.osk; keymanweb['focusLastActiveElement'](); if(osk && osk['show']) { if(osk['isEnabled']()) osk['hide'](); else osk['show'](true); } if(window.event) window.event.returnValue=false; return false; } /** * Function Initialize * Scope Private * Description UI Initialization **/ ui['initialize'] = ui.Initialize = function() { // Must always initialize after keymanWeb itself, otherwise options are undefined if(!keymanweb['initialized']) { window.setTimeout(ui.Initialize,50); return; } if(ui.initialized || util['isTouchDevice']()) return; var imgPath=util['getOption']('resources')+"ui/float/"; ui.outerDiv = util['createElement']('DIV'); // Container for UI (visible when KeymanWeb is active) ui.innerDiv = util['createElement']('DIV'); // inner div for UI ui.kbdIcon = util['createElement']('IMG'); ui.outerDiv.innerHTML = "<a href='http://keyman.com/web/' target='KeymanWebHelp'>" + "<img src='"+imgPath+"kmicon.gif' border='0' style='padding: 0px 2px 0 1px; margin:0px;' title='KeymanWeb' alt='KeymanWeb' /></a>"; /* I2081 */ var s=ui.outerDiv.style; s.backgroundColor='white'; s.border='solid 1px black'; s.position='absolute'; s.height='18px'; s.font='bold 8pt sans-serif'; s.display='none'; s.textAlign='left';s.overflow='hidden'; util['attachDOMEvent'](ui.outerDiv,'mousedown',ui._SelectorMouseDown); util['attachDOMEvent'](ui.outerDiv,'mouseover',ui._SelectorMouseOver); util['attachDOMEvent'](ui.outerDiv,'mouseout',ui._SelectorMouseOut); // Register keymanweb events ui.registerEvents(); ui.kbdIcon.src = imgPath+'kbdicon.gif'; ui.kbdIcon.title = 'Display visual keyboard'; // Set initial OSK button style (off by default) ui.oskButtonState(false); var Lhdiv = util['createElement']('DIV'); ui.oskButton = Lhdiv; Lhdiv.onclick = ui.toggleOSK; Lhdiv.appendChild(ui.kbdIcon); ui.innerDiv.appendChild(Lhdiv); ui.outerDiv.appendChild(ui.innerDiv); document.body.appendChild(ui.outerDiv); ui.KeyboardSelector = util['createElement']('SELECT'); // ControlSelector - KeymanWeb keyboard selector s=ui.KeyboardSelector.style; s.font='8pt sans-serif'; s.backgroundColor='#f3e5de'; s.border='solid 1px #7B9EBD'; s.height='16px';s.margin='1px 2px 0px 2px'; s.left='20px'; s.top='0px'; s.position='absolute'; s.maxWidth='150px'; util['attachDOMEvent'](ui.KeyboardSelector,'change',ui.SelectKeyboardChange); util['attachDOMEvent'](ui.KeyboardSelector,'blur',ui.SelectBlur); ui.innerDiv.appendChild(ui.KeyboardSelector); //this may need to be moved up.... // Check required interface alignment and default keyboard var opt=util['getOption']('ui'),dfltKeyboard='(System keyboard)'; if(opt && typeof(opt) == 'object') { if(typeof(opt['position']) == 'string' && opt['position'] == 'right') ui.floatRight = true; if(typeof(opt['default']) == 'string') dfltKeyboard = opt['default']; } var Lopt = util['createElement']('OPTION'); Lopt.value = '-'; Lopt.innerHTML = dfltKeyboard; ui.KeyboardSelector.appendChild(Lopt); Lopt = null; // This must be set before updating the keyboard list to prevent recursion! ui.initialized = true; // Update the keyboard list if required ui.updateKeyboardList(); //may also want to initialize style sheet here ?? } ui._UnloadUserInterface = function() { ui.KeyboardSelector = ui.innerDiv = ui.outerDiv = ui.kbdIcon = null; }; /** * UI removal - resource cleanup */ keymanweb['addEventListener']('unloaduserinterface', ui._UnloadUserInterface); ui.shutdown = function() { var root = ui.outerDiv; if(root) { root.parentNode.removeChild(root); } ui._UnloadUserInterface(); if(window.removeEventListener) { window.removeEventListener('resize', ui._Resize, false); } } /** * Update list of keyboards shown by UI */ ui.updateKeyboardList = function() { // Do nothing unless list requires updating if(ui.updateList) { if(!ui.initialized) ui.Initialize(); // Remove current list (except for default element) var i,opts=ui.KeyboardSelector.getElementsByTagName('OPTION'); for(i=opts.length; i>1; i--) { ui.KeyboardSelector.removeChild(opts[i-1]); } // Loop over installed keyboards and add to selection list var Ln,Lopt,Lkbds=keymanweb['getKeyboards'](); for(Ln=0; Ln<Lkbds.length; Ln++) { Lopt = util['createElement']('OPTION'); Lopt.value = Lkbds[Ln]['InternalName']+':'+Lkbds[Ln]['LanguageCode'];; Lopt.innerHTML = Lkbds[Ln]['Name'].replace(/\s?keyboard/i,''); if(Lkbds[Ln]['LanguageName']) { var lg=Lkbds[Ln]['LanguageName']; // Only show the main language name if variants indicated (this is tentative) // e.g. Chinese rather than Chinese, Mandarin, which is in the keyboard name lg = lg.split(',')[0]; if(Lkbds[Ln]['Name'].search(lg) == -1) Lopt.innerHTML = lg+' ('+Lopt.innerHTML+')'; // I1300 - Language support } ui.KeyboardSelector.appendChild(Lopt); Lopt = null; } } ui.updateList = false; // Set the menu selector to the currently saved keyboard var sk = keymanweb['getSavedKeyboard']().split(':'); if(sk.length < 2) sk[1] = ''; ui.updateMenu(sk[0],sk[1]); // Redisplay the UI to correct width for any new language entries if(keymanweb['getLastActiveElement']()) { ui.HideInterface(); ui.ShowInterface(); } } /** * Function updateMenu * Scope Private * @param {string} kbd * @param {string} lg * Description Update the UI menu selection * Separate arguments passed to allow better control of selection when a keyboard * is listed more than once for different language codes */ ui.updateMenu = function(kbd,lg) { var i=0; // This can be called during startup before fully initialized - ignore if so if(!ui.initialized) return; var match = kbd; if(lg != '') match += ':' + lg; if(kbd == '') ui.KeyboardSelector.selectedIndex=0; else { var opt=ui.KeyboardSelector.getElementsByTagName('OPTION'); for(i=0; i<opt.length; i++) { var t=opt[i].value; if(lg == '') t = t.split(':')[0]; if(t == match) { ui.KeyboardSelector.selectedIndex=i; break; } } } } /** * Function oskButtonState * Scope Private * @param {boolean} oskEnabled * Description Update kbd icon border style to indicate whether OSK is enabled for display or not **/ ui.oskButtonState = function(oskEnabled) { var s = ui.kbdIcon.style; s.width='24px'; s.height='13px'; s.top='1px'; s.verticalAlign='bottom'; s.padding='2px 2px 1px 2px'; s.position='absolute'; s.border=oskEnabled ? 'inset 1px #808080' : 'none'; s.background=oskEnabled ? '#f7e7de' : 'white'; s.display = 'block'; if(ui.initialized) ui.oskButton.style.display = 'block'; } /** * Register all keymanweb and OSK events only after keymanweb is fully initialized * **/ ui.registerEvents = function() { /** * Keyboard registration event handler * * Set a timer to update the UI keyboard list on timeout after each keyboard is registered, * thus updating only once when only if multiple keyboards are registered together */ keymanweb['addEventListener']('keyboardregistered', function(p) { ui.updateList = true; if(ui.updateTimer) clearTimeout(ui.updateTimer); ui.updateTimer = setTimeout(ui.updateKeyboardList,200); }); /** * Keyboard load event handler * * Set the menu selector to the currently saved keyboard when a keyboard is loaded * * Note: Cannot simply set it to the loaded keyboard, * as more than one language may be supported by that keyboard. */ keymanweb['addEventListener']('keyboardloaded', function(p) { var sk = keymanweb['getSavedKeyboard']().split(':'); if(sk.length > 1) ui.updateMenu(sk[0],sk[1]); }); /** * Keyboard change event handler * * Update menu selection and control OSK display appropriately */ keymanweb['addEventListener']('keyboardchange', function(p) { // Update the keyboard selector whenever a keyboard is loaded ui.updateMenu(p['internalName'],p['languageCode']); // (Conditionally) display the OSK button, and set the style ui.addButtonOSK(); }); let osk = keymanweb.osk; if(!osk) { return; } /** * Show OSK event handler: show or hide the OSK button (never display if a CJK keyboard) */ osk['addEventListener']('show', function(oskPosition) { ui.addButtonOSK(); return oskPosition; }); /** * Hide OSK event handler */ osk['addEventListener']('hide', function(hiddenByUser) { if(ui.initialized) ui.oskButtonState(false); }); } /** * Function _SelectorMouseDown * Scope Private * @param {Object} e event * Description Set KMW UI activation state on mouse click */ ui._SelectorMouseDown = function(e) { if(keymanweb['activatingUI']) keymanweb['activatingUI'](1); } /** * Function _SelectorMouseOver * Scope Private * @param {Object} e event * Description Set KMW UI activation state on mouse over */ ui._SelectorMouseOver = function(e) { if(keymanweb['activatingUI']) keymanweb['activatingUI'](1); } /** * Function _SelectorMouseOut * Scope Private * @param {Object} e event * Description Clear KMW UI activation state on mouse out */ ui._SelectorMouseOut = function(e) { if(keymanweb['activatingUI']) keymanweb['activatingUI'](0); } /** * Function _SelectKeyboardChange * Scope Private * @param {Object} e event * Description Change active keyboard in response to user selection event */ ui.SelectKeyboardChange = function(e) { if(ui.KeyboardSelector.value != '-') { var i=ui.KeyboardSelector.selectedIndex; var t=ui.KeyboardSelector.options[i].value.split(':'); keymanweb['setActiveKeyboard'](t[0],t[1]); } else keymanweb['setActiveKeyboard'](''); //if(osk['show']) osk['show'](osk['isEnabled']()); handled by keyboard change event??? keymanweb['focusLastActiveElement'](); ui.selecting = true; } /** * Function _SelectBlur * Scope Private * @param {Object} e event * Description Ensure OSK is hidden when moving focus after reselecting a keyboard */ ui.SelectBlur = function(e) { if(!ui.selecting) keymanweb['focusLastActiveElement'](); ui.selecting = false; } /** * Function ShowInterface * Scope Private * @param {number=} Px x-position for KMW window * @param {number=} Py y-position for KMW window * Description Display KMW window at specified position */ ui.ShowInterface = function(Px, Py) { if(!ui.initialized) return; var Ls = ui.outerDiv.style; if(Px && Py) { Ls.left = Px + 'px'; Ls.top = Py + 'px'; } Ls.display = 'block'; ui.kbdIcon.style.left = ui.KeyboardSelector.offsetWidth + 24 + 'px'; // (Conditionally) display the OSK button ui.addButtonOSK(); // Set the language selection to the currently active keyboard, if listed ui.updateMenu(keymanweb['getActiveKeyboard'](),keymanweb['getActiveLanguage']()); } /** * Function HideInterface * Scope Private * Description Completely hide KMW window */ ui.HideInterface = function() { if(!ui.initialized) return; ui.outerDiv.style.display = 'none'; } /** * Function addButtonOSK * Scope Private * Description Display the OSK button unless a CJK keyboard (or English) */ ui.addButtonOSK = function() { if(ui.oskButton != null) { if(keymanweb['isCJK']() || (ui.KeyboardSelector.selectedIndex==0)) { ui.oskButton.style.display = 'none'; ui.outerDiv.style.width = ui.KeyboardSelector.offsetWidth+30+'px'; } else { ui.oskButton.style.display = 'block'; if(keymanweb.osk) { ui.oskButtonState(keymanweb.osk['isEnabled']()); } else { ui.oskButtonState(false); } ui.outerDiv.style.width = ui.KeyboardSelector.offsetWidth+56+'px'; } } } //TODO: had to expose properties of params - what does that do? (focus event doesn't normally include these properties?) keymanweb['addEventListener']('controlfocused', function(params) { if(params['activeControl'] == null || params['activeControl']['_kmwAttachment']) { /*if(keymanweb._IsIEEditableIframe(Ltarg)) Ltarg = Ltarg.ownerDocument.parentWindow.frameElement; else if(keymanweb.domManager._IsMozillaEditableIframe(Ltarg)) Ltarg = Ltarg.defaultView.frameElement;*/ if(ui.floatRight) // I1296 ui.ShowInterface(util['getAbsoluteX'](params.target) + params.target.offsetWidth + 1, util['getAbsoluteY'](params.target) + 1); else ui.ShowInterface(util['getAbsoluteX'](params.target), util['getAbsoluteY'](params.target) - parseInt(util['getStyleValue'](ui.outerDiv,'height'),10) - 2); } return true; }); keymanweb['addEventListener']('controlblurred', function(params) { if(!params['event']) return true; // I2404 - Manage IE events in IFRAMEs if(!params['isActivating']) ui.HideInterface(); return true; }); /** * Function _Resize * Scope Private * @param {Object} e event object * @return {boolean} * Description Display KMW OSK at specified position (returns nothing) */ ui._Resize = function(e) { if(ui.outerDiv.style.display =='block') { var elem = keymanweb['getLastActiveElement'](); if(ui.floatRight) // I1296 ui.ShowInterface(util['getAbsoluteX'](elem) + elem.offsetWidth + 1, util['getAbsoluteY'](elem) + 1); else ui.ShowInterface(util['getAbsoluteX'](elem) + 1, util['getAbsoluteY'](elem) + elem.offsetHeight + 1); } return true; } if(window.addEventListener) window.addEventListener('resize', ui._Resize, false); // Initialize after KMW is fully initialized, if UI already loaded keymanweb['addEventListener']('loaduserinterface',ui.Initialize); // but also call initialization when script loaded, which is after KMW initialization for asynchronous script loading ui.Initialize(); } catch(err){} // Do not wrap in an anonymous function - let the closure compiler do that, but // use try...catch to avoid script errors and only execute if a desktop browser }
the_stack
import { UAProperty } from "node-opcua-address-space-base" import { DataType } from "node-opcua-variant" import { UInt32 } from "node-opcua-basic-types" import { UAInitialState } from "node-opcua-nodeset-ua/source/ua_initial_state" import { UAState } from "node-opcua-nodeset-ua/source/ua_state" import { UAFiniteStateMachine, UAFiniteStateMachine_Base } from "node-opcua-nodeset-ua/source/ua_finite_state_machine" import { UATransition } from "node-opcua-nodeset-ua/source/ua_transition" export interface UAAnalyserChannel_OperatingModeExecuteSubStateMachine_selectExecutionCycle extends Omit<UAInitialState, "stateNumber"> { // Object stateNumber: UAProperty<UInt32, /*z*/DataType.UInt32>; } export interface UAAnalyserChannel_OperatingModeExecuteSubStateMachine_waitForCalibrationTrigger extends Omit<UAState, "stateNumber"> { // Object stateNumber: UAProperty<UInt32, /*z*/DataType.UInt32>; } export interface UAAnalyserChannel_OperatingModeExecuteSubStateMachine_extractCalibrationSample extends Omit<UAState, "stateNumber"> { // Object stateNumber: UAProperty<UInt32, /*z*/DataType.UInt32>; } export interface UAAnalyserChannel_OperatingModeExecuteSubStateMachine_prepareCalibrationSample extends Omit<UAState, "stateNumber"> { // Object stateNumber: UAProperty<UInt32, /*z*/DataType.UInt32>; } export interface UAAnalyserChannel_OperatingModeExecuteSubStateMachine_analyseCalibrationSample extends Omit<UAState, "stateNumber"> { // Object stateNumber: UAProperty<UInt32, /*z*/DataType.UInt32>; } export interface UAAnalyserChannel_OperatingModeExecuteSubStateMachine_waitForValidationTrigger extends Omit<UAState, "stateNumber"> { // Object stateNumber: UAProperty<UInt32, /*z*/DataType.UInt32>; } export interface UAAnalyserChannel_OperatingModeExecuteSubStateMachine_extractValidationSample extends Omit<UAState, "stateNumber"> { // Object stateNumber: UAProperty<UInt32, /*z*/DataType.UInt32>; } export interface UAAnalyserChannel_OperatingModeExecuteSubStateMachine_prepareValidationSample extends Omit<UAState, "stateNumber"> { // Object stateNumber: UAProperty<UInt32, /*z*/DataType.UInt32>; } export interface UAAnalyserChannel_OperatingModeExecuteSubStateMachine_analyseValidationSample extends Omit<UAState, "stateNumber"> { // Object stateNumber: UAProperty<UInt32, /*z*/DataType.UInt32>; } export interface UAAnalyserChannel_OperatingModeExecuteSubStateMachine_waitForSampleTrigger extends Omit<UAState, "stateNumber"> { // Object stateNumber: UAProperty<UInt32, /*z*/DataType.UInt32>; } export interface UAAnalyserChannel_OperatingModeExecuteSubStateMachine_extractSample extends Omit<UAState, "stateNumber"> { // Object stateNumber: UAProperty<UInt32, /*z*/DataType.UInt32>; } export interface UAAnalyserChannel_OperatingModeExecuteSubStateMachine_prepareSample extends Omit<UAState, "stateNumber"> { // Object stateNumber: UAProperty<UInt32, /*z*/DataType.UInt32>; } export interface UAAnalyserChannel_OperatingModeExecuteSubStateMachine_analyseSample extends Omit<UAState, "stateNumber"> { // Object stateNumber: UAProperty<UInt32, /*z*/DataType.UInt32>; } export interface UAAnalyserChannel_OperatingModeExecuteSubStateMachine_waitForDiagnosticTrigger extends Omit<UAState, "stateNumber"> { // Object stateNumber: UAProperty<UInt32, /*z*/DataType.UInt32>; } export interface UAAnalyserChannel_OperatingModeExecuteSubStateMachine_diagnostic extends Omit<UAState, "stateNumber"> { // Object stateNumber: UAProperty<UInt32, /*z*/DataType.UInt32>; } export interface UAAnalyserChannel_OperatingModeExecuteSubStateMachine_waitForCleaningTrigger extends Omit<UAState, "stateNumber"> { // Object stateNumber: UAProperty<UInt32, /*z*/DataType.UInt32>; } export interface UAAnalyserChannel_OperatingModeExecuteSubStateMachine_cleaning extends Omit<UAState, "stateNumber"> { // Object stateNumber: UAProperty<UInt32, /*z*/DataType.UInt32>; } export interface UAAnalyserChannel_OperatingModeExecuteSubStateMachine_publishResults extends Omit<UAState, "stateNumber"> { // Object stateNumber: UAProperty<UInt32, /*z*/DataType.UInt32>; } export interface UAAnalyserChannel_OperatingModeExecuteSubStateMachine_ejectGrabSample extends Omit<UAState, "stateNumber"> { // Object stateNumber: UAProperty<UInt32, /*z*/DataType.UInt32>; } export interface UAAnalyserChannel_OperatingModeExecuteSubStateMachine_cleanupSamplingSystem extends Omit<UAState, "stateNumber"> { // Object stateNumber: UAProperty<UInt32, /*z*/DataType.UInt32>; } /** * | | | * |----------------|--------------------------------------------------| * |namespace |http://opcfoundation.org/UA/ADI/ | * |nodeClass |ObjectType | * |typedDefinition |2:AnalyserChannel_OperatingModeExecuteSubStateMachineType ns=2;i=1009| * |isAbstract |false | */ export interface UAAnalyserChannel_OperatingModeExecuteSubStateMachine_Base extends UAFiniteStateMachine_Base { /** * selectExecutionCycle * This pseudo-state is used to decide which * execution path shall be taken. */ selectExecutionCycle: UAAnalyserChannel_OperatingModeExecuteSubStateMachine_selectExecutionCycle; /** * waitForCalibrationTrigger * Wait until the analyser channel is ready to * perform the Calibration acquisition cycle */ waitForCalibrationTrigger: UAAnalyserChannel_OperatingModeExecuteSubStateMachine_waitForCalibrationTrigger; /** * extractCalibrationSample * Collect / setup the sampling system to perform * the acquisition cycle of a Calibration cycle */ extractCalibrationSample: UAAnalyserChannel_OperatingModeExecuteSubStateMachine_extractCalibrationSample; /** * prepareCalibrationSample * Prepare the Calibration sample for the * AnalyseCalibrationSample state */ prepareCalibrationSample: UAAnalyserChannel_OperatingModeExecuteSubStateMachine_prepareCalibrationSample; /** * analyseCalibrationSample * Perform the analysis of the Calibration Sample */ analyseCalibrationSample: UAAnalyserChannel_OperatingModeExecuteSubStateMachine_analyseCalibrationSample; /** * waitForValidationTrigger * Wait until the analyser channel is ready to * perform the Validation acquisition cycle */ waitForValidationTrigger: UAAnalyserChannel_OperatingModeExecuteSubStateMachine_waitForValidationTrigger; /** * extractValidationSample * Collect / setup the sampling system to perform * the acquisition cycle of a Validation cycle */ extractValidationSample: UAAnalyserChannel_OperatingModeExecuteSubStateMachine_extractValidationSample; /** * prepareValidationSample * Prepare the Validation sample for the * AnalyseValidationSample state */ prepareValidationSample: UAAnalyserChannel_OperatingModeExecuteSubStateMachine_prepareValidationSample; /** * analyseValidationSample * Perform the analysis of the Validation Sample */ analyseValidationSample: UAAnalyserChannel_OperatingModeExecuteSubStateMachine_analyseValidationSample; /** * waitForSampleTrigger * Wait until the analyser channel is ready to * perform the Sample acquisition cycle */ waitForSampleTrigger: UAAnalyserChannel_OperatingModeExecuteSubStateMachine_waitForSampleTrigger; /** * extractSample * Collect the Sample from the process */ extractSample: UAAnalyserChannel_OperatingModeExecuteSubStateMachine_extractSample; /** * prepareSample * Prepare the Sample for the AnalyseSample state */ prepareSample: UAAnalyserChannel_OperatingModeExecuteSubStateMachine_prepareSample; /** * analyseSample * Perform the analysis of the Sample */ analyseSample: UAAnalyserChannel_OperatingModeExecuteSubStateMachine_analyseSample; /** * waitForDiagnosticTrigger * Wait until the analyser channel is ready to * perform the diagnostic cycle, */ waitForDiagnosticTrigger: UAAnalyserChannel_OperatingModeExecuteSubStateMachine_waitForDiagnosticTrigger; /** * diagnostic * Perform the diagnostic cycle. */ diagnostic: UAAnalyserChannel_OperatingModeExecuteSubStateMachine_diagnostic; /** * waitForCleaningTrigger * Wait until the analyser channel is ready to * perform the cleaning cycle, */ waitForCleaningTrigger: UAAnalyserChannel_OperatingModeExecuteSubStateMachine_waitForCleaningTrigger; /** * cleaning * Perform the cleaning cycle. */ cleaning: UAAnalyserChannel_OperatingModeExecuteSubStateMachine_cleaning; /** * publishResults * Publish the results of the previous acquisition * cycle */ publishResults: UAAnalyserChannel_OperatingModeExecuteSubStateMachine_publishResults; /** * ejectGrabSample * The Sample that was just analysed is ejected from * the system to allow the operator or another * system to grab it */ ejectGrabSample: UAAnalyserChannel_OperatingModeExecuteSubStateMachine_ejectGrabSample; /** * cleanupSamplingSystem * Cleanup the sampling sub-system to be ready for * the next acquisition */ cleanupSamplingSystem: UAAnalyserChannel_OperatingModeExecuteSubStateMachine_cleanupSamplingSystem; selectExecutionCycleToWaitForCalibrationTriggerTransition: UATransition; waitForCalibrationTriggerToExtractCalibrationSampleTransition: UATransition; extractCalibrationSampleTransition: UATransition; extractCalibrationSampleToPrepareCalibrationSampleTransition: UATransition; prepareCalibrationSampleTransition: UATransition; prepareCalibrationSampleToAnalyseCalibrationSampleTransition: UATransition; analyseCalibrationSampleTransition: UATransition; analyseCalibrationSampleToPublishResultsTransition: UATransition; selectExecutionCycleToWaitForValidationTriggerTransition: UATransition; waitForValidationTriggerToExtractValidationSampleTransition: UATransition; extractValidationSampleTransition: UATransition; extractValidationSampleToPrepareValidationSampleTransition: UATransition; prepareValidationSampleTransition: UATransition; prepareValidationSampleToAnalyseValidationSampleTransition: UATransition; analyseValidationSampleTransition: UATransition; analyseValidationSampleToPublishResultsTransition: UATransition; selectExecutionCycleToWaitForSampleTriggerTransition: UATransition; waitForSampleTriggerToExtractSampleTransition: UATransition; extractSampleTransition: UATransition; extractSampleToPrepareSampleTransition: UATransition; prepareSampleTransition: UATransition; prepareSampleToAnalyseSampleTransition: UATransition; analyseSampleTransition: UATransition; analyseSampleToPublishResultsTransition: UATransition; selectExecutionCycleToWaitForDiagnosticTriggerTransition: UATransition; waitForDiagnosticTriggerToDiagnosticTransition: UATransition; diagnosticTransition: UATransition; diagnosticToPublishResultsTransition: UATransition; selectExecutionCycleToWaitForCleaningTriggerTransition: UATransition; waitForCleaningTriggerToCleaningTransition: UATransition; cleaningTransition: UATransition; cleaningToPublishResultsTransition: UATransition; publishResultsToCleanupSamplingSystemTransition: UATransition; publishResultsToEjectGrabSampleTransition: UATransition; ejectGrabSampleTransition: UATransition; ejectGrabSampleToCleanupSamplingSystemTransition: UATransition; cleanupSamplingSystemTransition: UATransition; cleanupSamplingSystemToSelectExecutionCycleTransition: UATransition; } export interface UAAnalyserChannel_OperatingModeExecuteSubStateMachine extends UAFiniteStateMachine, UAAnalyserChannel_OperatingModeExecuteSubStateMachine_Base { }
the_stack
const models = require('../../../../../db/mysqldb/index') import moment from 'moment' const { resClientJson } = require('../../../utils/resData') const Op = require('sequelize').Op const trimHtml = require('trim-html') const xss = require('xss') const clientWhere = require('../../../utils/clientWhere') const config = require('../../../../../config') const { TimeNow, TimeDistance } = require('../../../utils/time') const shortid = require('shortid') const lowdb = require('../../../../../db/lowdb/index') import { statusList, userMessageAction, modelAction, modelName } from '../../../utils/constant' import userVirtual from '../../../common/userVirtual' /* 动态专题模块模块 */ // 获取动态专题详情 class articleBlog { /** * 获取所有文章专题get * @param {object} ctx 上下文对象 */ static async getUserArticleBlogAll(req: any, res: any, next: any) { /* 获取所有文章专题 */ let { uid } = req.query try { let allUserArticleBlog = await models.article_blog.findAll({ where: { uid } }) resClientJson(res, { state: 'success', message: '获取当前用户个人专题成功', data: { list: allUserArticleBlog } }) } catch (err) { resClientJson(res, { state: 'error', message: '错误信息:' + err.message }) return false } } /** * 创建用户专题 * @param {object} ctx 上下文对象 */ static async createUserArticleBlog(req: any, res: any, next: any) { /* 创建用户专题 */ let { blog_name, en_name, description, icon, enable, tag_ids } = req.body let { user = '' } = req try { if (blog_name.length === 0) { throw new Error('请输入文章专题名字') } let oneUserArticleBlog = await models.article_blog.findOne({ where: { uid: user.uid, name: blog_name } }) let userArticleBlogCount = await models.article_blog.count({ where: { uid: user.uid } }) if (userArticleBlogCount > 50) { throw new Error('当前只开放,用户创建的个人专栏上限为50个') } if (en_name) { let enNameArticleBlog = await models.article_blog.findOne({ where: { en_name } }) if (enNameArticleBlog) { throw new Error('英文名字已存在') } if (en_name.length > 60) { throw new Error('英文名字小于60个字符') } } // 虚拟币判断是否可以进行继续的操作 const isVirtual = await userVirtual.isVirtual({ uid: user.uid, type: modelName.article_blog, action: modelAction.create }) if (!isVirtual) { throw new Error('贝壳余额不足!') } let oneArticleTag = await models.article_tag.findOne({ where: { tag_id: config.ARTICLE_TAG.dfOfficialExclusive } }) const website = lowdb .read() .get('website') .value() if (tag_ids) { if (~tag_ids.indexOf(config.ARTICLE_TAG.dfOfficialExclusive)) { if (!~user.user_role_ids.indexOf(config.USER_ROLE.dfManagementTeam)) { throw new Error( `${oneArticleTag.name}只有${website.website_name}管理团队才能使用` ) } } } let userRoleALL = await models.user_role.findAll({ where: { user_role_id: { [Op.or]: user.user_role_ids.split(',') }, user_role_type: 1 // 用户角色类型1是默认角色 } }) let userAuthorityIds = '' userRoleALL.map((roleItem: any) => { userAuthorityIds += roleItem.user_authority_ids + ',' }) let status = ~userAuthorityIds.indexOf( config.ARTICLE_BLOG.dfNoReviewArticleBlogId ) ? statusList.freeReview : statusList.pendingReview if (oneUserArticleBlog) { throw new Error('不能创建自己已有的专题') } const createArticleBlog = await models.article_blog.create({ name: blog_name, en_name: en_name || shortid.generate(), icon: icon || config.DF_ICON, description: description || '', uid: user.uid, enable: enable || false, tag_ids: tag_ids || '', status }) await userVirtual.setVirtual({ uid: user.uid, associate: createArticleBlog.blog_id, type: modelName.article_blog, action: modelAction.create }) resClientJson(res, { state: 'success', message: '文章个人专栏创建成功' }) } catch (err) { resClientJson(res, { state: 'error', message: '错误信息:' + err.message }) return false } } /** * 更新用户专题 * @param {object} ctx 上下文对象 */ static async updateUserArticleBlog(req: any, res: any, next: any) { const resData = req.body let { user = '' } = req try { let oneUserArticleBlog = await models.article_blog.findOne({ where: { name: resData.blog_name, blog_id: { [Op.ne]: resData.blog_id } } }) if (oneUserArticleBlog) { throw new Error('标题已存在') } if (resData.en_name) { let enNameArticleBlog = await models.article_blog.findOne({ where: { en_name: resData.en_name, blog_id: { [Op.ne]: resData.blog_id } } }) if (enNameArticleBlog) { throw new Error('英文标题已存在') } if (resData.en_name.length > 60) { throw new Error('英文标题小于60个字符') } } let oneArticleTag = await models.article_tag.findOne({ where: { tag_id: config.ARTICLE_TAG.dfOfficialExclusive } }) const website = lowdb .read() .get('website') .value() if (~resData.tag_ids.indexOf(config.ARTICLE_TAG.dfOfficialExclusive)) { if (!~user.user_role_ids.indexOf(config.USER_ROLE.dfManagementTeam)) { throw new Error( `${oneArticleTag.name}只有${website.website_name}管理团队才能使用` ) } } if (oneUserArticleBlog) { throw new Error('不能修改自己已有的专题') } let userRoleALL = await models.user_role.findAll({ where: { user_role_id: { [Op.or]: user.user_role_ids.split(',') }, user_role_type: 1 // 用户角色类型1是默认角色 } }) let userAuthorityIds = '' userRoleALL.map((roleItem: any) => { userAuthorityIds += roleItem.user_authority_ids + ',' }) let status = ~userAuthorityIds.indexOf( config.ARTICLE_BLOG.dfNoReviewArticleBlogId ) ? statusList.freeReview // 免审核 : statusList.pendingReview // 待审核 await models.article_blog.update( { name: resData.blog_name, en_name: resData.en_name || shortid.generate(), icon: resData.icon || config.DF_ICON, description: resData.description || '', enable: resData.enable || false, tag_ids: resData.tag_ids || '', status }, { where: { blog_id: resData.blog_id, // 查询条件 uid: user.uid } } ) resClientJson(res, { state: 'success', message: '更新成功' }) } catch (err) { resClientJson(res, { state: 'error', message: '错误信息:' + err.message }) return false } } /** * 删除用户文章专题 * @param {object} ctx 上下文对象 */ static async deleteUserArticleBlog(req: any, res: any, next: any) { const resData = req.body let { user = '' } = req try { await models.article_blog.destroy({ where: { blog_id: resData.blog_id, // 查询条件 uid: user.uid } }) resClientJson(res, { state: 'success', message: '删除用户个人专栏成功' }) } catch (err) { resClientJson(res, { state: 'error', message: '错误信息:' + err.message }) return false } } // 获取个人专栏详细信息信息 static async getArticleBlogView(req: any, res: any, next: any) { let blogId = req.query.blogId try { let oneArticleBlog = await models.article_blog.findOne({ where: { blog_id: blogId // 查询条件 } }) await models.article_blog.update( { read_count: Number(oneArticleBlog.read_count) + 1 }, { where: { blog_id: blogId } } // 为空,获取全部,也可以自己添加条件 ) oneArticleBlog.setDataValue( 'create_dt', await TimeDistance(oneArticleBlog.create_date) ) oneArticleBlog.setDataValue( 'update_dt', await TimeDistance(oneArticleBlog.update_date) ) oneArticleBlog.setDataValue( 'articleCount', await models.article.count({ where: { blog_ids: oneArticleBlog.blog_id } }) ) oneArticleBlog.setDataValue( 'likeCount', await models.collect.count({ where: { associate_id: oneArticleBlog.blog_id, is_associate: true, type: modelName.article_blog } }) ) oneArticleBlog.setDataValue( 'likeUserIds', await models.collect.findAll({ where: { associate_id: oneArticleBlog.blog_id, is_associate: true, type: modelName.article_blog } }) ) if (oneArticleBlog.tag_ids) { oneArticleBlog.setDataValue( 'tag', await models.article_tag.findAll({ where: { tag_id: { [Op.or]: oneArticleBlog.tag_ids.split(',') } } }) ) } oneArticleBlog.setDataValue( 'user', await models.user.findOne({ where: { uid: oneArticleBlog.uid }, attributes: ['uid', 'avatar', 'nickname', 'sex', 'introduction'] }) ) if (oneArticleBlog) { await resClientJson(res, { state: 'success', message: 'success', data: { articleBlog: oneArticleBlog } }) } else { await resClientJson(res, { state: 'success', message: '文章个人专栏不存在', data: { articleBlog: {} } }) } } catch (err) { resClientJson(res, { state: 'error', message: '错误信息:' + err.message }) return false } } // 获取个人专栏所含有的文章 static async getArticleBlogArticleList(req: any, res: any, next: any) { let page = req.query.page || 1 let pageSize = req.query.pageSize || 24 let sort = req.query.sort let blogId = req.query.blogId let whereParams = { blog_ids: blogId, is_public: true, // 公开的文章 status: { [Op.or]: [statusList.reviewSuccess, statusList.freeReview] // 审核成功、免审核 } } let orderParams: any[] = [] try { let { count, rows } = await models.article.findAndCountAll({ where: whereParams, // 为空,获取全部,也可以自己添加条件 offset: (page - 1) * pageSize, // 开始的数据索引,比如当page=2 时offset=10 ,而pagesize我们定义为10,则现在为索引为10,也就是从第11条开始返回数据条目 limit: pageSize, // 每页限制返回的数据条数 order: orderParams }) for (let i in rows) { rows[i].setDataValue( 'create_dt', await TimeDistance(rows[i].create_date) ) rows[i].setDataValue( 'update_dt', await TimeDistance(rows[i].update_date) ) if (rows[i].tag_ids) { rows[i].setDataValue( 'tag', await models.article_tag.findAll({ where: { tag_id: { [Op.or]: rows[i].tag_ids.split(',') } } }) ) } rows[i].setDataValue( 'user', await models.user.findOne({ where: { uid: rows[i].uid }, attributes: ['uid', 'avatar', 'nickname', 'sex', 'introduction'] }) ) } await resClientJson(res, { state: 'success', message: 'success', data: { page, count, pageSize, list: rows } }) } catch (err) { resClientJson(res, { state: 'error', message: '错误信息:' + err.message }) return false } } } export default articleBlog
the_stack
"use strict"; import { TxtNode } from "@textlint/ast-node-types"; import { parse, Syntax } from "../src/index"; import assert from "assert"; import traverse from "traverse"; const inspect = (obj: Record<string, unknown>) => JSON.stringify(obj, null, 4); function findFirstTypedNode(node: TxtNode, type: string, value?: string): TxtNode { let result: TxtNode | null = null; traverse(node).forEach(function (x) { // eslint-disable-next-line no-invalid-this if (this.notLeaf) { if (x.type === type) { if (value == null) { result = x; } else if (x.raw === value) { result = x; } } } }); if (result == null) { /* eslint-disable no-console */ console.log(inspect(node)); throw new Error(`Not Found type:${type}`); /* eslint-enable no-console */ } return result; } function shouldHaveImplementTxtNode(node: TxtNode, rawValue: string) { const lines = rawValue.split("\n"); const lastLine = lines[lines.length - 1]; assert.strictEqual(node.raw, rawValue); assert.deepStrictEqual(node.loc, { start: { line: 1, column: 0 }, end: { line: lines.length, column: lastLine.length } }); assert.deepStrictEqual(node.range, [0, rawValue.length]); } function shouldHaveImplementInlineTxtNode(node: TxtNode, text: string, allText: string) { assert.strictEqual(node.raw, text); const startColumn = allText.indexOf(text); assert.deepStrictEqual(node.loc, { start: { line: 1, column: startColumn }, end: { line: 1, column: startColumn + text.length } }); assert.deepStrictEqual(node.range, [startColumn, startColumn + text.length]); } /* NOTE: `line` start with 1 `column` start with 0 */ describe("markdown-parser", function () { context("Node type is Document", function () { it("should has implemented TxtNode", function () { const RootDocument = parse(""); assert.strictEqual(RootDocument.type, Syntax.Document); assert.strictEqual(RootDocument.raw, ""); assert.deepStrictEqual(RootDocument.loc, { start: { line: 1, column: 0 }, end: { line: 1, column: 0 } }); assert.deepStrictEqual(RootDocument.range, [0, 0]); }); it("should has range and loc on whole text", function () { const text = "# Header\n\n" + "- list\n\n" + "text Str."; const lines = text.split("\n"); const RootDocument = parse(text); assert.strictEqual(RootDocument.type, Syntax.Document); assert.strictEqual(RootDocument.raw, text); assert.deepStrictEqual(RootDocument.loc, { start: { line: 1, column: 0 }, end: { line: lines.length, column: lines[lines.length - 1].length } }); assert.deepStrictEqual(RootDocument.range, [0, text.length]); }); it("should has range and loc on whole text", function () { const text = "# Header\n" + "\n" + "text"; const lines = text.split("\n"); const RootDocument = parse(text); assert.strictEqual(RootDocument.type, Syntax.Document); assert.strictEqual(RootDocument.raw, text); assert.deepStrictEqual(RootDocument.loc, { start: { line: 1, column: 0 }, end: { line: lines.length, column: lines[lines.length - 1].length } }); const slicedText = text.slice(RootDocument.range[0], RootDocument.range[1]); assert.deepStrictEqual(slicedText, text); }); }); /* Paragraph > Str */ context("Node type is Paragraph", function () { let AST: TxtNode, rawValue: string; beforeEach(function () { rawValue = "string"; AST = parse(rawValue); }); context("Paragraph", function () { it("should has implemented TxtNode", function () { const node = findFirstTypedNode(AST, Syntax.Paragraph, rawValue); shouldHaveImplementTxtNode(node, rawValue); }); }); context("Text", function () { it("should has implemented TxtNode", function () { const node = findFirstTypedNode(AST, Syntax.Str, rawValue); shouldHaveImplementTxtNode(node, rawValue); }); }); }); /* H1 > Str */ context("Node type is Header", function () { /** * text * ===== **/ context("SetextHeader", function () { let AST: TxtNode, text: string, header: string; beforeEach(function () { text = "string"; header = `${text}\n======`; AST = parse(header); }); context("Header", function () { it("should has implemented TxtNode", function () { const node = findFirstTypedNode(AST, Syntax.Header); shouldHaveImplementTxtNode(node, header); }); }); context("Str", function () { it("should has implemented TxtNode", function () { const node = findFirstTypedNode(AST, Syntax.Str); shouldHaveImplementTxtNode(node, text); }); }); }); /** * # text * */ context("ATXHeader", function () { let AST: TxtNode, text: string, header: string; beforeEach(function () { text = "string"; header = `# ${text}`; AST = parse(header); }); context("Header", function () { it("should has implemented TxtNode", function () { const node = findFirstTypedNode(AST, Syntax.Header); shouldHaveImplementTxtNode(node, header); }); }); context("Str", function () { it("should have correct range", function () { const node = findFirstTypedNode(AST, Syntax.Str); shouldHaveImplementInlineTxtNode(node, text, header); }); }); }); }); context("Node type is Link", function () { let AST: TxtNode, rawValue: string, labelText: string; beforeEach(function () { labelText = "text"; rawValue = `[${labelText}](http://example.com)`; AST = parse(rawValue); }); it("should has implemented TxtNode", function () { const node = findFirstTypedNode(AST, Syntax.Link); shouldHaveImplementTxtNode(node, rawValue); }); context("Str", function () { it("should have correct range", function () { const node = findFirstTypedNode(AST, Syntax.Str); shouldHaveImplementInlineTxtNode(node, labelText, rawValue); }); }); }); context("Node type is List", function () { it("should has implemented TxtNode", function () { const rawValue = "- list1\n- list2", AST = parse(rawValue); const node = findFirstTypedNode(AST, Syntax.List); shouldHaveImplementTxtNode(node, rawValue); }); }); context("Node type is ListItem", function () { it("should same the bullet_char", function () { let node: TxtNode, AST: TxtNode; AST = parse("- item"); node = findFirstTypedNode(AST, Syntax.ListItem); assert(/^-/.test(node.raw)); AST = parse("* item"); node = findFirstTypedNode(AST, Syntax.ListItem); assert(/^\*/.test(node.raw)); }); it("should have marker_offser of each items", function () { const AST = parse("- item\n" + " - item2"); // second line should has offset const node = findFirstTypedNode(AST, Syntax.ListItem, "- item2"); assert(node); assert.strictEqual(node.raw, "- item2"); }); it("should has implemented TxtNode", function () { const text = "text", rawValue = `- ${text}`, AST = parse(rawValue); const node = findFirstTypedNode(AST, Syntax.ListItem); shouldHaveImplementTxtNode(node, rawValue); }); context("Str", function () { it("should have correct range", function () { const text = "text", rawValue = `- ${text}`, AST = parse(rawValue); const node = findFirstTypedNode(AST, Syntax.Str); shouldHaveImplementInlineTxtNode(node, text, rawValue); }); }); }); /* > BlockQuote */ context("Node type is BlockQuote", function () { let AST: TxtNode, rawValue: string, text: string; beforeEach(function () { text = "text"; rawValue = `> ${text}`; AST = parse(rawValue); }); it("should has implemented TxtNode", function () { const node = findFirstTypedNode(AST, Syntax.BlockQuote); assert.deepStrictEqual(node.range, [0, rawValue.length]); }); }); /* ``` CodeBlock ``` */ context("Node type is CodeBlock", function () { context("IndentCodeBlock", function () { let AST: TxtNode, rawValue: string, code: string; beforeEach(function () { code = "var code;"; rawValue = `${" \n" + " "}${code}\n\n`; AST = parse(rawValue); }); it("should has implemented TxtNode", function () { const node = findFirstTypedNode(AST, Syntax.CodeBlock); assert(node.raw.indexOf(code) !== -1); const slicedCode = rawValue.slice(node.range[0], node.range[1]); assert.strictEqual(slicedCode.trim(), code); }); }); context("FencedCode", function () { let AST: TxtNode, rawValue: string, code: string; beforeEach(function () { code = "var code;"; rawValue = `\`\`\`\n${code}\n\`\`\``; AST = parse(rawValue); }); it("should has implemented TxtNode", function () { const node = findFirstTypedNode(AST, Syntax.CodeBlock); const codeBlockRaw = rawValue; assert.strictEqual(node.raw, codeBlockRaw); const slicedCode = rawValue.slice(node.range[0], node.range[1]); assert.strictEqual(slicedCode, codeBlockRaw); }); }); }); /* `code` */ context("Node type is Code", function () { let AST: TxtNode, rawValue: string; beforeEach(function () { rawValue = "`code`"; AST = parse(rawValue); }); it("should has implemented TxtNode", function () { const node = findFirstTypedNode(AST, Syntax.Code); shouldHaveImplementTxtNode(node, rawValue); }); }); /* __Strong__ */ context("Node type is Strong", function () { let AST: TxtNode, rawValue: string, text: string; beforeEach(function () { text = "text"; rawValue = `__${text}__`; AST = parse(rawValue); }); it("should has implemented TxtNode", function () { const node = findFirstTypedNode(AST, Syntax.Strong); shouldHaveImplementTxtNode(node, rawValue); }); context("Str", function () { it("should have correct range", function () { const node = findFirstTypedNode(AST, Syntax.Str); shouldHaveImplementInlineTxtNode(node, text, rawValue); }); }); }); /* ![text](http://example.com/a.png) */ context("Node type is Image", function () { let AST: TxtNode, rawValue: string, labelText: string; beforeEach(function () { labelText = "text"; rawValue = `![${labelText}](http://example.com/a.png)`; AST = parse(rawValue); }); it("should has implemented TxtNode", function () { const node = findFirstTypedNode(AST, Syntax.Image); shouldHaveImplementTxtNode(node, rawValue); }); }); /* *text* */ context("Node type is Emphasis", function () { let AST: TxtNode, rawValue: string, text: string; beforeEach(function () { text = "text"; rawValue = `*${text}*`; AST = parse(rawValue); }); it("should has implemented TxtNode", function () { const node = findFirstTypedNode(AST, Syntax.Emphasis); shouldHaveImplementTxtNode(node, rawValue); }); context("Str", function () { it("should have correct range", function () { const node = findFirstTypedNode(AST, Syntax.Str); shouldHaveImplementInlineTxtNode(node, text, rawValue); }); }); }); /* ---- */ context("Node type is HorizontalRule", function () { let AST: TxtNode, rawValue: string; beforeEach(function () { rawValue = "----"; AST = parse(rawValue); }); it("should has implemented TxtNode", function () { const node = findFirstTypedNode(AST, Syntax.HorizontalRule); shouldHaveImplementTxtNode(node, rawValue); }); }); /* <html> */ context("Node type is Html", function () { let AST: TxtNode, rawValue: string; beforeEach(function () { rawValue = "<p>text</p>"; AST = parse(rawValue); }); it("should has implemented TxtNode", function () { const node = findFirstTypedNode(AST, Syntax.Html); shouldHaveImplementTxtNode(node, rawValue); }); }); });
the_stack
import { async, TestBed, inject } from "@angular/core/testing"; import { NO_ERRORS_SCHEMA } from "@angular/core"; import { IdprestapiService } from "./idprestapi.service"; import { MockBackend, MockConnection } from "@angular/http/testing"; import { HttpModule, XHRBackend, ResponseOptions, Response, RequestMethod} from "@angular/http"; import "rxjs/add/operator/toPromise"; import { IdpdataService } from "./idpdata.service"; import { CookieService } from "ngx-cookie"; import { Router, NavigationExtras } from "@angular/router"; import { environment } from "../environments/environment"; import { Adal4Service } from "adal-angular4"; import { StartupService } from "./startup.service"; import { KeycloakService } from "./keycloak/keycloak.service"; import { platformBrowserDynamic } from "@angular/platform-browser-dynamic"; import { HttpClientTestingModule, HttpTestingController } from "@angular/common/http/testing"; import { HttpClient, HttpResponse, HttpErrorResponse } from "@angular/common/http"; import {Observable} from "rxjs/Observable"; describe("IdprestapiService", () => { let httpTestingController: HttpTestingController; let idprestapiService: IdprestapiService; class IdpdataServiceStub { constructor() {} template: any = { "grantAccess": { "applicationName": "", "developers": [], "pipelineAdmins": [], "releaseManager": [], "environmentOwnerDetails": [{ "environmentName": "", "environmentOwners": [], "dbOwners": [] }], "slaveDetails": [ { "slaveName": "", "buildServerOS": "", "workspacePath": "", "createNewSlave": "", "labels": "", "sshKeyPath": "", "slaveUsage": "both" } ] }, "basicInfo": { "additionalMailRecipients": { "applicationTeam": "", "emailIds": "" }, "applicationName": "", "buildInterval": { "buildInterval": "", "buildIntervalValue": 0, "pollSCM": "off" }, "buildServerOS": "", "engine": "", "pipelineName": "" }, "code": { "category": "", "technology": "", "scm": [], "buildScript": [{"tool": ""}, {"tool": ""}, {}] }, "buildInfo": { "buildtool": "", "castAnalysis": {}, "artifactToStage": {}, "modules": [], "postBuildScript": {} }, "deployInfo": { "deployEnv": [] }, "testInfo": { "testEnv": [] }, "formStatus": { "basicInfo": { "appNameStatus": "0", "formStatus": "0" }, "codeInfo": "", "buildInfo": { "buildToolStatus": "0", "formStatus": "0", "ibmsiTypeStatus": "0" }, "deployInfo": "", "testInfo": "", "operation": "" }, "checkboxStatus": { "basicInfo": {}, "codeInfo": {}, "buildInfo": {}, "deployInfo": {}, "testInfo": {}, "others": {} }, "backUp": { "deployInfo": {}, "testInfo": {} }, "masterJson": {} }; data: any = JSON.parse(JSON.stringify(this.template)); language = "english"; idpUserName = ""; roles = []; access_token: any; permissions = []; createAppflag = false; createPipelineflag = false; copyPipelineflag = false; editPipelineflag = false; deletePipelineflag = false; test = false; devServerURL: any= ""; IDPDashboardURL = ""; IDPLink = ""; geUrl = ""; role = ""; IDPDropdownProperties: any = {}; showConfig: any; pa= true; continuecontrol: any; geFlag: any; p: any= false; ejbVal: any; warVal: any; jarVal: any; pipelineData: any; triggerJobData: any; application: any; freezeNavBars= false; osFlag: any; op: any; operation: any; initMain: any= false; RestApiDetails: any= false; buildInfoReset= false; compMove: any; unit: any; code: any; refreshBuild= false; } class RouterStub { navigate(commands: any[], extras?: NavigationExtras) { } } class StartUpServiceStub { authmode = "ldap"; keycloakUrl = "abc"; keycloakRealm = "aa"; keycloakClientId = ""; clouddeployurl = ""; getData() { return "data"; } } const idpdataserviceStub: IdpdataServiceStub = new IdpdataServiceStub(); const routerStub: RouterStub = new RouterStub(); const startupStub: StartUpServiceStub = new StartUpServiceStub(); beforeEach(async(() => { const cookieServiceSpy = jasmine.createSpyObj(["get"]); const stubValue = true; const stub = { id: 1, name: "A" }; const adalServiceSpy = jasmine.createSpyObj(["get"]); const keycloakServiceSpy = jasmine.createSpyObj(["get"]); cookieServiceSpy.get.and.returnValue(stubValue); console.log(Observable.of(stub)); adalServiceSpy.get.and.returnValue(stubValue); keycloakServiceSpy.get.and.returnValue(stubValue); TestBed.configureTestingModule({ imports: [HttpClientTestingModule, HttpModule], providers: [{provide: StartupService, useValue: startupStub}, {provide: CookieService, useValue: cookieServiceSpy}, {provide: IdpdataService, useValue: idpdataserviceStub}, {provide: Router, useValue: routerStub}, {provide: Adal4Service, useValue: adalServiceSpy}, {provide: KeycloakService, useValue: keycloakServiceSpy}, IdprestapiService ], schemas: [NO_ERRORS_SCHEMA] }); httpTestingController = TestBed.get(HttpTestingController); idprestapiService = TestBed.get(IdprestapiService); })); beforeEach(() => { }); it("#getValue should return stubbed value from a spy", () => { // create `getValue` spy on an object representing the ValueService /* const { idprestService, stubValue, stub, cookieServiceSpy, httpServiceSpy, adalServiceSpy, startupStub, keycloakServiceSpy } = setup(); */ let response; idprestapiService.getNotification().then(res => {response = res; }); /* expect(response) .toBe(stub, "service returned stub value"); expect(httpServiceSpy.getValue.calls.count()) .toBe(1, "spy method was called once"); expect(httpServiceSpy.getValue.calls.mostRecent().returnValue) .toBe(stubPromiseValue); */ }); /* it("#getValue should return stubbed value from a spy", () => { idprestService.getUserName(); idprestService.updatePlan("data1", "data2", "data3", "envData"); idprestService.getReleaseNumber("data1"); idprestService.getEnvNames("data1", "d2"); idprestService.obtainAccessToken("data1"); idprestService.getData(); idprestService.logout(); idprestService.checkApplicationNames("data1"); idprestService.getOrganizationWiseApplicationNames(); idprestService.getAvailableSlot("d1", "d2", "d3"); idprestService.getPipelineDetails("data"); idprestService.checkForApplicationType("data"); idprestService.getEnvSlots("d1","d2"); idprestService.getExistingSlot("d1","d2", "d3"); idprestService.emailToEnvOwner("d1"); idprestService.getPipelineEnv("d1","d2"); idprestService.getEnvironmentPairs("d1","d2"); }); */ it("should run #getNotification()", async(() => { const result = idprestapiService.getNotification(); })); it("should run #getUserName()", async(() => { const result = idprestapiService.getUserName(); })); it("should run #updatePlan()", async(() => { let data1, data2, data3, envData; const result = idprestapiService.updatePlan(data1, data2, data3, envData); })); it("should run #getReleaseNumber()", async(() => { let data; const result = idprestapiService.getReleaseNumber(data); })); it("should run #getEnvNames()", async(() => { let data; let data1; const result = idprestapiService.getEnvNames(data, data1); })); it("should run #obtainAccessToken()", async(() => { let params; const result = idprestapiService.obtainAccessToken(params); })); it("should run #getData()", async(() => { const result = idprestapiService.getData(); })); it("should run #logout()", async(() => { const result = idprestapiService.logout(); })); it("should run #checkApplicationNames()", async(() => { const result = idprestapiService.checkApplicationNames({}); })); it("should run #getOrganizationWiseApplicationNames()", async(() => { const result = idprestapiService.getOrganizationWiseApplicationNames(); })); it("should run #getTimeZone()", async(() => { const result = idprestapiService.getTimeZone(); })); it("should run #getAvailableSlot()", async(() => { let data1; let data2; let data3; const result = idprestapiService.getAvailableSlot(data1, data2, data3); })); it("should run #getPipelineDetails()", async(() => { let data; const result = idprestapiService.getPipelineDetails(data); })); it("should run #checkForApplicationType()", async(() => { let data; const result = idprestapiService.checkForApplicationType(data); })); it("should run #getEnvSlots()", async(() => { const result = idprestapiService.getEnvSlots("application_name", "env"); })); it("should run #getExistingSlot()", async(() => { let application_name; let release_number; let env; const result = idprestapiService.getExistingSlot(application_name, release_number, env); })); it("should run #emailToEnvOwner()", async(() => { let envOwner; const result = idprestapiService.emailToEnvOwner(envOwner); })); it("should run #getPipelineEnv()", async(() => { let data; let data1; const result = idprestapiService.getPipelineEnv(data, data1); })); it("should run #getEnvironmentPairs()", async(() => { let data; const result = idprestapiService.getEnvironmentPairs(data); })); it("should run #getEnvironmentNames()", async(() => { let data; const result = idprestapiService.getEnvironmentNames(data); })); it("should run #getIDPDropdownProperties()", async(() => { const result = idprestapiService.getIDPDropdownProperties(); })); it("should run #checkAvailableJobs()", async(() => { const result = idprestapiService.checkAvailableJobs(); })); it("should run #triggerJob()", async(() => { let request; const result = idprestapiService.triggerJob(request); })); it("should run #createCloudApplication()", async(() => { let requestData; const result = idprestapiService.createCloudApplication(requestData); })); it("should run #createLoadBalancer()", async(() => { let requestData; const result = idprestapiService.createLoadBalancer(requestData); })); it("should run #createCloudPipeline()", async(() => { let requestData; const result = idprestapiService.createCloudPipeline(requestData); })); it("should run #copyeditCloudPipeline()", async(() => { let appName; let pipName; const result = idprestapiService.copyeditCloudPipeline(appName, pipName); })); it("should run #submit()", async(() => { const result = idprestapiService.submit({}); })); it("should run #triggerJobs()", async(() => { let requestData; const result = idprestapiService.triggerJobs({}); })); it("should run #getApplicationDetails()", async(() => { const requestData = {}; const result = idprestapiService.getApplicationDetails(requestData); })); it("should run #deletePipeline()", async(() => { const requestData = {}; const result = idprestapiService.deletePipeline(requestData); })); it("should run #getExistingApps()", async(() => { const result = idprestapiService.getExistingApps(); })); it("should run #getApplicationInfo()", async(() => { const requestData = {}; const result = idprestapiService.getApplicationInfo(requestData); })); it("should run #getFilteredApplicationNames()", async(() => { const filterString = ""; const result = idprestapiService.getFilteredApplicationNames(filterString); })); it("should run #editApplicationDetails()", async(() => { const requestData = {}; const result = idprestapiService.editApplicationDetails(requestData); })); it("should run #createApplication()", async(() => { const requestData = {}; const result = idprestapiService.createApplication(requestData); })); it("should run #getJobs()", async(() => { const requestData = {}; const result = idprestapiService.getJobs(requestData); })); it("should run #getStageViewUrl()", async(() => { const result = idprestapiService.getStageViewUrl(); })); it("should run #getPipelineList()", async(() => { const responseData = {}; const result = idprestapiService.getPipelineList(responseData); })); it("should run #sendAppMail()", async(() => { const responseData = {}; const result = idprestapiService.sendAppMail(responseData); })); it("should run #sendOrgMail()", async(() => { const responseData = {}; const result = idprestapiService.sendOrgMail(responseData); })); it("should run #sendLicenseMail()", async(() => { const responseData = {}; const result = idprestapiService.sendLicenseMail(responseData); })); it("should run #sendPipeMail()", async(() => { const responseData = {}; const result = idprestapiService.sendPipeMail(responseData); })); it("should run #getPipelineNames()", async(() => { const requestData = {}; const result = idprestapiService.getPipelineNames(requestData); })); it("should run #getPipelineListforWorkflow()", async(() => { const requestData = {}; const result = idprestapiService.getPipelineListforWorkflow(requestData); })); it("should run #getExistingAppNames()", async(() => { const result = idprestapiService.getExistingAppNames(); })); it("should run #checkSubApplication()", async(() => { const data = {}; const result = idprestapiService.checkSubApplication(data); })); it("should run #getActiveReleases()", async(() => { const requestData = {}; const result = idprestapiService.getActiveReleases(requestData); })); it("should run #getHistoryReleases()", async(() => { const requestData = {}; const result = idprestapiService.getHistoryReleases(requestData); })); it("should run #getApplicationNameForReleaseManager()", async(() => { const responseData = {}; const result = idprestapiService.getApplicationNameForReleaseManager(responseData); })); it("should run #postReleaseData()", async(() => { const responseData = {}; const result = idprestapiService.postReleaseData(responseData); })); it("should run #updateReleases()", async(() => { const responseData = {}; const result = idprestapiService.updateReleases(responseData); })); it("should run #checkReleaseNo()", async(() => { const result = idprestapiService.checkReleaseNo(); })); it("should run #getArtifactsRm()", async(() => { const data = {}; const result = idprestapiService.getArtifactsRm(data); })); it("should run #getReleasesApprovePortal()", async(() => { const result = idprestapiService.getReleasesApprovePortal(); })); it("should run #updateArtifacts()", async(() => { const data = {}; const result = idprestapiService.updateArtifacts(data); })); it("should run #fetchTriggerSteps()", async(() => { const data = {}; const result = idprestapiService.fetchTriggerSteps(data); })); it("should run #getJobParamList()", async(() => { const result = idprestapiService.getJobParamList(); })); it("should run #getTestPlanList()", async(() => { const result = idprestapiService.getTestPlanList("appName", "pipeName"); })); it("should run #getTestSuitList()", async(() => { const result = idprestapiService.getTestSuitList("id", "appName", "pipeName"); })); it("should run #base64EncodeDecode()", async(() => { const result = idprestapiService.base64EncodeDecode("uname", "pass"); })); it("should run #buildIntervalTriggerJobs()", async(() => { const data = {}; const result = idprestapiService.buildIntervalTriggerJobs(data); })); it("should run #getSlaveStatus()", async(() => { const data = {}; const result = idprestapiService.getSlaveStatus(data); })); it("should run #getArtifactLatestDetails()", async(() => { const data = {}; const result = idprestapiService.getArtifactLatestDetails(data); })); it("should run #getPipelineAdmins()", async(() => { const appName = "appName"; const result = idprestapiService.getPipelineAdmins(appName); })); it("should run #getPipelinePermission()", async(() => { const data = {}; const result = idprestapiService.getPipelinePermission(data); })); it("should run #approveJobs()", async(() => { const requestData = {}; const result = idprestapiService.approveJobs(requestData); })); it("should run #getSubscriptionPermission()", async(() => { const result = idprestapiService.getSubscriptionPermission(); })); it("should run #getValidatedLicense()", async(() => { const result = idprestapiService.getValidatedLicense(); })); it("should run #createLicense()", async(() => { const data = {}; const result = idprestapiService.createLicense(data); })); it("should run #createOrganization()", async(() => { const requestData = {}; const result = idprestapiService.createOrganization(requestData); })); it("should run #getExistingOrgNames()", async(() => { const result = idprestapiService.getExistingOrgNames(); })); it("should run #editOrganizationDetails()", async(() => { const result = idprestapiService.editOrganizationDetails({}); })); });
the_stack
import { BaseResource, CloudError, AzureServiceClientOptions } from "@azure/ms-rest-azure-js"; import * as msRest from "@azure/ms-rest-js"; export { BaseResource, CloudError }; /** * @interface * An interface representing ErrorMesssage. * Error response containing message and code. * */ export interface ErrorMesssage { /** * @member {string} [code] standard error code */ code?: string; /** * @member {string} [message] standard error description */ message?: string; /** * @member {string} [details] detailed summary of error */ details?: string; } /** * @interface * An interface representing AsyncOperationResult. * Result of a long running operation. * */ export interface AsyncOperationResult { /** * @member {string} [status] current status of a long running operation. */ status?: string; /** * @member {ErrorMesssage} [error] Error message containing code, description * and details */ error?: ErrorMesssage; } /** * @interface * An interface representing CertificateProperties. * The description of an X509 CA Certificate. * */ export interface CertificateProperties { /** * @member {string} [subject] The certificate's subject name. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly subject?: string; /** * @member {Date} [expiry] The certificate's expiration date and time. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly expiry?: Date; /** * @member {string} [thumbprint] The certificate's thumbprint. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly thumbprint?: string; /** * @member {boolean} [isVerified] Determines whether certificate has been * verified. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly isVerified?: boolean; /** * @member {Date} [created] The certificate's creation date and time. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly created?: Date; /** * @member {Date} [updated] The certificate's last update date and time. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly updated?: Date; } /** * @interface * An interface representing CertificateResponse. * The X509 Certificate. * * @extends BaseResource */ export interface CertificateResponse extends BaseResource { /** * @member {CertificateProperties} [properties] properties of a certificate */ properties?: CertificateProperties; /** * @member {string} [id] The resource identifier. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly id?: string; /** * @member {string} [name] The name of the certificate. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly name?: string; /** * @member {string} [etag] The entity tag. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly etag?: string; /** * @member {string} [type] The resource type. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly type?: string; } /** * @interface * An interface representing CertificateListDescription. * The JSON-serialized array of Certificate objects. * */ export interface CertificateListDescription { /** * @member {CertificateResponse[]} [value] The array of Certificate objects. */ value?: CertificateResponse[]; } /** * @interface * An interface representing CertificateBodyDescription. * The JSON-serialized X509 Certificate. * */ export interface CertificateBodyDescription { /** * @member {string} [certificate] Base-64 representation of the X509 leaf * certificate .cer file or just .pem file content. */ certificate?: string; } /** * @interface * An interface representing IotDpsSkuInfo. * List of possible provisoning service SKUs. * */ export interface IotDpsSkuInfo { /** * @member {IotDpsSku} [name] Sku name. Possible values include: 'S1' */ name?: IotDpsSku; /** * @member {string} [tier] Pricing tier name of the provisioning service. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly tier?: string; /** * @member {number} [capacity] The number of units to provision */ capacity?: number; } /** * @interface * An interface representing IotHubDefinitionDescription. * Description of the IoT hub. * */ export interface IotHubDefinitionDescription { /** * @member {boolean} [applyAllocationPolicy] flag for applying * allocationPolicy or not for a given iot hub. */ applyAllocationPolicy?: boolean; /** * @member {number} [allocationWeight] weight to apply for a given iot h. */ allocationWeight?: number; /** * @member {string} [name] Host name of the IoT hub. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly name?: string; /** * @member {string} connectionString Connection string og the IoT hub. */ connectionString: string; /** * @member {string} location ARM region of the IoT hub. */ location: string; } /** * @interface * An interface representing SharedAccessSignatureAuthorizationRuleAccessRightsDescription. * Description of the shared access key. * */ export interface SharedAccessSignatureAuthorizationRuleAccessRightsDescription { /** * @member {string} keyName Name of the key. */ keyName: string; /** * @member {string} [primaryKey] Primary SAS key value. */ primaryKey?: string; /** * @member {string} [secondaryKey] Secondary SAS key value. */ secondaryKey?: string; /** * @member {AccessRightsDescription} rights Rights that this key has. * Possible values include: 'ServiceConfig', 'EnrollmentRead', * 'EnrollmentWrite', 'DeviceConnect', 'RegistrationStatusRead', * 'RegistrationStatusWrite' */ rights: AccessRightsDescription; } /** * @interface * An interface representing IotDpsPropertiesDescription. * the service specific properties of a provisoning service, including keys, * linked iot hubs, current state, and system generated properties such as * hostname and idScope * */ export interface IotDpsPropertiesDescription { /** * @member {State} [state] Current state of the provisioning service. * Possible values include: 'Activating', 'Active', 'Deleting', 'Deleted', * 'ActivationFailed', 'DeletionFailed', 'Transitioning', 'Suspending', * 'Suspended', 'Resuming', 'FailingOver', 'FailoverFailed' */ state?: State; /** * @member {string} [provisioningState] The ARM provisioning state of the * provisioning service. */ provisioningState?: string; /** * @member {IotHubDefinitionDescription[]} [iotHubs] List of IoT hubs * assosciated with this provisioning service. */ iotHubs?: IotHubDefinitionDescription[]; /** * @member {AllocationPolicy} [allocationPolicy] Allocation policy to be used * by this provisioning service. Possible values include: 'Hashed', * 'GeoLatency', 'Static' */ allocationPolicy?: AllocationPolicy; /** * @member {string} [serviceOperationsHostName] Service endpoint for * provisioning service. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly serviceOperationsHostName?: string; /** * @member {string} [deviceProvisioningHostName] Device endpoint for this * provisioning service. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly deviceProvisioningHostName?: string; /** * @member {string} [idScope] Unique identifier of this provisioning service. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly idScope?: string; /** * @member {SharedAccessSignatureAuthorizationRuleAccessRightsDescription[]} * [authorizationPolicies] List of authorization keys for a provisioning * service. */ authorizationPolicies?: SharedAccessSignatureAuthorizationRuleAccessRightsDescription[]; } /** * @interface * An interface representing Resource. * The common properties of an Azure resource. * * @extends BaseResource */ export interface Resource extends BaseResource { /** * @member {string} [id] The resource identifier. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly id?: string; /** * @member {string} [name] The resource name. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly name?: string; /** * @member {string} [type] The resource type. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly type?: string; /** * @member {string} location The resource location. */ location: string; /** * @member {{ [propertyName: string]: string }} [tags] The resource tags. */ tags?: { [propertyName: string]: string }; } /** * @interface * An interface representing ProvisioningServiceDescription. * The description of the provisioning service. * * @extends Resource */ export interface ProvisioningServiceDescription extends Resource { /** * @member {string} [etag] The Etag field is *not* required. If it is * provided in the response body, it must also be provided as a header per * the normal ETag convention. */ etag?: string; /** * @member {IotDpsPropertiesDescription} properties Service specific * properties for a provisioning service */ properties: IotDpsPropertiesDescription; /** * @member {IotDpsSkuInfo} sku Sku info for a provisioning Service. */ sku: IotDpsSkuInfo; } /** * @interface * An interface representing OperationDisplay. * The object that represents the operation. * */ export interface OperationDisplay { /** * @member {string} [provider] Service provider: Microsoft Devices. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly provider?: string; /** * @member {string} [resource] Resource Type: ProvisioningServices. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly resource?: string; /** * @member {string} [operation] Name of the operation. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly operation?: string; } /** * @interface * An interface representing Operation. * IoT Hub REST API operation. * */ export interface Operation { /** * @member {string} [name] Operation name: {provider}/{resource}/{read | * write | action | delete} * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly name?: string; /** * @member {OperationDisplay} [display] The object that represents the * operation. */ display?: OperationDisplay; } /** * @interface * An interface representing ErrorDetails. * Error details. * */ export interface ErrorDetails { /** * @member {string} [code] The error code. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly code?: string; /** * @member {string} [httpStatusCode] The HTTP status code. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly httpStatusCode?: string; /** * @member {string} [message] The error message. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly message?: string; /** * @member {string} [details] The error details. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly details?: string; } /** * @interface * An interface representing IotDpsSkuDefinition. * Available Sku's of tier and units. * */ export interface IotDpsSkuDefinition { /** * @member {IotDpsSku} [name] Sku name. Possible values include: 'S1' */ name?: IotDpsSku; } /** * @interface * An interface representing OperationInputs. * Input values for operation results call. * */ export interface OperationInputs { /** * @member {string} name The name of the Provisioning Service to check. */ name: string; } /** * @interface * An interface representing NameAvailabilityInfo. * Description of name availability. * */ export interface NameAvailabilityInfo { /** * @member {boolean} [nameAvailable] specifies if a name is available or not */ nameAvailable?: boolean; /** * @member {NameUnavailabilityReason} [reason] specifies the reason a name is * unavailable. Possible values include: 'Invalid', 'AlreadyExists' */ reason?: NameUnavailabilityReason; /** * @member {string} [message] message containing a etailed reason name is * unavailable */ message?: string; } /** * @interface * An interface representing TagsResource. * A container holding only the Tags for a resource, allowing the user to * update the tags on a Provisioning Service instance. * */ export interface TagsResource { /** * @member {{ [propertyName: string]: string }} [tags] Resource tags */ tags?: { [propertyName: string]: string }; } /** * @interface * An interface representing VerificationCodeResponseProperties. */ export interface VerificationCodeResponseProperties { /** * @member {string} [verificationCode] Verification code. */ verificationCode?: string; /** * @member {string} [subject] Certificate subject. */ subject?: string; /** * @member {string} [expiry] Code expiry. */ expiry?: string; /** * @member {string} [thumbprint] Certificate thumbprint. */ thumbprint?: string; /** * @member {boolean} [isVerified] Indicate if the certificate is verified by * owner of private key. */ isVerified?: boolean; /** * @member {string} [created] Certificate created time. */ created?: string; /** * @member {string} [updated] Certificate updated time. */ updated?: string; } /** * @interface * An interface representing VerificationCodeResponse. * Description of the response of the verification code. * * @extends BaseResource */ export interface VerificationCodeResponse extends BaseResource { /** * @member {string} [name] Name of certificate. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly name?: string; /** * @member {string} [etag] Request etag. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly etag?: string; /** * @member {string} [id] The resource identifier. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly id?: string; /** * @member {string} [type] The resource type. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly type?: string; /** * @member {VerificationCodeResponseProperties} [properties] */ properties?: VerificationCodeResponseProperties; } /** * @interface * An interface representing VerificationCodeRequest. * The JSON-serialized leaf certificate * */ export interface VerificationCodeRequest { /** * @member {string} [certificate] base-64 representation of X509 certificate * .cer file or just .pem file content. */ certificate?: string; } /** * @interface * An interface representing DpsCertificateGetOptionalParams. * Optional Parameters. * * @extends RequestOptionsBase */ export interface DpsCertificateGetOptionalParams extends msRest.RequestOptionsBase { /** * @member {string} [ifMatch] ETag of the certificate. */ ifMatch?: string; } /** * @interface * An interface representing DpsCertificateCreateOrUpdateOptionalParams. * Optional Parameters. * * @extends RequestOptionsBase */ export interface DpsCertificateCreateOrUpdateOptionalParams extends msRest.RequestOptionsBase { /** * @member {string} [ifMatch] ETag of the certificate. This is required to * update an existing certificate, and ignored while creating a brand new * certificate. */ ifMatch?: string; } /** * @interface * An interface representing DpsCertificateDeleteMethodOptionalParams. * Optional Parameters. * * @extends RequestOptionsBase */ export interface DpsCertificateDeleteMethodOptionalParams extends msRest.RequestOptionsBase { /** * @member {string} [certificatename] This is optional, and it is the Common * Name of the certificate. */ certificatename?: string; /** * @member {Uint8Array} [certificaterawBytes] Raw data within the * certificate. */ certificaterawBytes?: Uint8Array; /** * @member {boolean} [certificateisVerified] Indicates if certificate has * been verified by owner of the private key. */ certificateisVerified?: boolean; /** * @member {CertificatePurpose} [certificatepurpose] A description that * mentions the purpose of the certificate. Possible values include: * 'clientAuthentication', 'serverAuthentication' */ certificatepurpose?: CertificatePurpose; /** * @member {Date} [certificatecreated] Time the certificate is created. */ certificatecreated?: Date; /** * @member {Date} [certificatelastUpdated] Time the certificate is last * updated. */ certificatelastUpdated?: Date; /** * @member {boolean} [certificatehasPrivateKey] Indicates if the certificate * contains a private key. */ certificatehasPrivateKey?: boolean; /** * @member {string} [certificatenonce] Random number generated to indicate * Proof of Possession. */ certificatenonce?: string; } /** * @interface * An interface representing DpsCertificateGenerateVerificationCodeOptionalParams. * Optional Parameters. * * @extends RequestOptionsBase */ export interface DpsCertificateGenerateVerificationCodeOptionalParams extends msRest.RequestOptionsBase { /** * @member {string} [certificatename] Common Name for the certificate. */ certificatename?: string; /** * @member {Uint8Array} [certificaterawBytes] Raw data of certificate. */ certificaterawBytes?: Uint8Array; /** * @member {boolean} [certificateisVerified] Indicates if the certificate has * been verified by owner of the private key. */ certificateisVerified?: boolean; /** * @member {CertificatePurpose} [certificatepurpose] Description mentioning * the purpose of the certificate. Possible values include: * 'clientAuthentication', 'serverAuthentication' */ certificatepurpose?: CertificatePurpose; /** * @member {Date} [certificatecreated] Certificate creation time. */ certificatecreated?: Date; /** * @member {Date} [certificatelastUpdated] Certificate last updated time. */ certificatelastUpdated?: Date; /** * @member {boolean} [certificatehasPrivateKey] Indicates if the certificate * contains private key. */ certificatehasPrivateKey?: boolean; /** * @member {string} [certificatenonce] Random number generated to indicate * Proof of Possession. */ certificatenonce?: string; } /** * @interface * An interface representing DpsCertificateVerifyCertificateOptionalParams. * Optional Parameters. * * @extends RequestOptionsBase */ export interface DpsCertificateVerifyCertificateOptionalParams extends msRest.RequestOptionsBase { /** * @member {string} [certificatename] Common Name for the certificate. */ certificatename?: string; /** * @member {Uint8Array} [certificaterawBytes] Raw data of certificate. */ certificaterawBytes?: Uint8Array; /** * @member {boolean} [certificateisVerified] Indicates if the certificate has * been verified by owner of the private key. */ certificateisVerified?: boolean; /** * @member {CertificatePurpose} [certificatepurpose] Describe the purpose of * the certificate. Possible values include: 'clientAuthentication', * 'serverAuthentication' */ certificatepurpose?: CertificatePurpose; /** * @member {Date} [certificatecreated] Certificate creation time. */ certificatecreated?: Date; /** * @member {Date} [certificatelastUpdated] Certificate last updated time. */ certificatelastUpdated?: Date; /** * @member {boolean} [certificatehasPrivateKey] Indicates if the certificate * contains private key. */ certificatehasPrivateKey?: boolean; /** * @member {string} [certificatenonce] Random number generated to indicate * Proof of Possession. */ certificatenonce?: string; } /** * @interface * An interface representing IotDpsClientOptions. * @extends AzureServiceClientOptions */ export interface IotDpsClientOptions extends AzureServiceClientOptions { /** * @member {string} [baseUri] */ baseUri?: string; } /** * @interface * An interface representing the OperationListResult. * Result of the request to list IoT Hub operations. It contains a list of * operations and a URL link to get the next set of results. * * @extends Array<Operation> */ export interface OperationListResult extends Array<Operation> { /** * @member {string} [nextLink] URL to get the next set of operation list * results if there are any. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly nextLink?: string; } /** * @interface * An interface representing the ProvisioningServiceDescriptionListResult. * List of provisioning service descriptions. * * @extends Array<ProvisioningServiceDescription> */ export interface ProvisioningServiceDescriptionListResult extends Array<ProvisioningServiceDescription> { /** * @member {string} [nextLink] the next link * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly nextLink?: string; } /** * @interface * An interface representing the IotDpsSkuDefinitionListResult. * List of available SKUs. * * @extends Array<IotDpsSkuDefinition> */ export interface IotDpsSkuDefinitionListResult extends Array<IotDpsSkuDefinition> { /** * @member {string} [nextLink] The next link. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly nextLink?: string; } /** * @interface * An interface representing the SharedAccessSignatureAuthorizationRuleListResult. * List of shared access keys. * * @extends Array<SharedAccessSignatureAuthorizationRuleAccessRightsDescription> */ export interface SharedAccessSignatureAuthorizationRuleListResult extends Array<SharedAccessSignatureAuthorizationRuleAccessRightsDescription> { /** * @member {string} [nextLink] The next link. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly nextLink?: string; } /** * Defines values for IotDpsSku. * Possible values include: 'S1' * @readonly * @enum {string} */ export type IotDpsSku = 'S1'; /** * Defines values for State. * Possible values include: 'Activating', 'Active', 'Deleting', 'Deleted', 'ActivationFailed', * 'DeletionFailed', 'Transitioning', 'Suspending', 'Suspended', 'Resuming', 'FailingOver', * 'FailoverFailed' * @readonly * @enum {string} */ export type State = 'Activating' | 'Active' | 'Deleting' | 'Deleted' | 'ActivationFailed' | 'DeletionFailed' | 'Transitioning' | 'Suspending' | 'Suspended' | 'Resuming' | 'FailingOver' | 'FailoverFailed'; /** * Defines values for AllocationPolicy. * Possible values include: 'Hashed', 'GeoLatency', 'Static' * @readonly * @enum {string} */ export type AllocationPolicy = 'Hashed' | 'GeoLatency' | 'Static'; /** * Defines values for AccessRightsDescription. * Possible values include: 'ServiceConfig', 'EnrollmentRead', 'EnrollmentWrite', 'DeviceConnect', * 'RegistrationStatusRead', 'RegistrationStatusWrite' * @readonly * @enum {string} */ export type AccessRightsDescription = 'ServiceConfig' | 'EnrollmentRead' | 'EnrollmentWrite' | 'DeviceConnect' | 'RegistrationStatusRead' | 'RegistrationStatusWrite'; /** * Defines values for NameUnavailabilityReason. * Possible values include: 'Invalid', 'AlreadyExists' * @readonly * @enum {string} */ export type NameUnavailabilityReason = 'Invalid' | 'AlreadyExists'; /** * Defines values for CertificatePurpose. * Possible values include: 'clientAuthentication', 'serverAuthentication' * @readonly * @enum {string} */ export type CertificatePurpose = 'clientAuthentication' | 'serverAuthentication'; /** * Contains response data for the list operation. */ export type OperationsListResponse = OperationListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: OperationListResult; }; }; /** * Contains response data for the listNext operation. */ export type OperationsListNextResponse = OperationListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: OperationListResult; }; }; /** * Contains response data for the get operation. */ export type DpsCertificateGetResponse = CertificateResponse & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: CertificateResponse; }; }; /** * Contains response data for the createOrUpdate operation. */ export type DpsCertificateCreateOrUpdateResponse = CertificateResponse & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: CertificateResponse; }; }; /** * Contains response data for the list operation. */ export type DpsCertificateListResponse = CertificateListDescription & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: CertificateListDescription; }; }; /** * Contains response data for the generateVerificationCode operation. */ export type DpsCertificateGenerateVerificationCodeResponse = VerificationCodeResponse & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: VerificationCodeResponse; }; }; /** * Contains response data for the verifyCertificate operation. */ export type DpsCertificateVerifyCertificateResponse = CertificateResponse & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: CertificateResponse; }; }; /** * Contains response data for the get operation. */ export type IotDpsResourceGetResponse = ProvisioningServiceDescription & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: ProvisioningServiceDescription; }; }; /** * Contains response data for the createOrUpdate operation. */ export type IotDpsResourceCreateOrUpdateResponse = ProvisioningServiceDescription & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: ProvisioningServiceDescription; }; }; /** * Contains response data for the update operation. */ export type IotDpsResourceUpdateResponse = ProvisioningServiceDescription & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: ProvisioningServiceDescription; }; }; /** * Contains response data for the listBySubscription operation. */ export type IotDpsResourceListBySubscriptionResponse = ProvisioningServiceDescriptionListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: ProvisioningServiceDescriptionListResult; }; }; /** * Contains response data for the listByResourceGroup operation. */ export type IotDpsResourceListByResourceGroupResponse = ProvisioningServiceDescriptionListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: ProvisioningServiceDescriptionListResult; }; }; /** * Contains response data for the getOperationResult operation. */ export type IotDpsResourceGetOperationResultResponse = AsyncOperationResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: AsyncOperationResult; }; }; /** * Contains response data for the listValidSkus operation. */ export type IotDpsResourceListValidSkusResponse = IotDpsSkuDefinitionListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: IotDpsSkuDefinitionListResult; }; }; /** * Contains response data for the checkProvisioningServiceNameAvailability operation. */ export type IotDpsResourceCheckProvisioningServiceNameAvailabilityResponse = NameAvailabilityInfo & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: NameAvailabilityInfo; }; }; /** * Contains response data for the listKeys operation. */ export type IotDpsResourceListKeysResponse = SharedAccessSignatureAuthorizationRuleListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: SharedAccessSignatureAuthorizationRuleListResult; }; }; /** * Contains response data for the listKeysForKeyName operation. */ export type IotDpsResourceListKeysForKeyNameResponse = SharedAccessSignatureAuthorizationRuleAccessRightsDescription & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: SharedAccessSignatureAuthorizationRuleAccessRightsDescription; }; }; /** * Contains response data for the beginCreateOrUpdate operation. */ export type IotDpsResourceBeginCreateOrUpdateResponse = ProvisioningServiceDescription & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: ProvisioningServiceDescription; }; }; /** * Contains response data for the beginUpdate operation. */ export type IotDpsResourceBeginUpdateResponse = ProvisioningServiceDescription & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: ProvisioningServiceDescription; }; }; /** * Contains response data for the listBySubscriptionNext operation. */ export type IotDpsResourceListBySubscriptionNextResponse = ProvisioningServiceDescriptionListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: ProvisioningServiceDescriptionListResult; }; }; /** * Contains response data for the listByResourceGroupNext operation. */ export type IotDpsResourceListByResourceGroupNextResponse = ProvisioningServiceDescriptionListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: ProvisioningServiceDescriptionListResult; }; }; /** * Contains response data for the listValidSkusNext operation. */ export type IotDpsResourceListValidSkusNextResponse = IotDpsSkuDefinitionListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: IotDpsSkuDefinitionListResult; }; }; /** * Contains response data for the listKeysNext operation. */ export type IotDpsResourceListKeysNextResponse = SharedAccessSignatureAuthorizationRuleListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: SharedAccessSignatureAuthorizationRuleListResult; }; };
the_stack
import * as assert from "assert"; import * as moment from "moment"; import { testContext, disposeTestDocumentStore } from "../Utils/TestUtil"; import { IDocumentStore, } from "../../src"; import { DateUtil } from "../../src/Utility/DateUtil"; import { GetDocumentsCommand } from "../../src/Documents/Commands/GetDocumentsCommand"; import { StringUtil } from "../../src/Utility/StringUtil"; // getTimezoneOffset() returns reversed offset, hence the "-" const LOCAL_TIMEZONE_OFFSET = -(new Date(2018, 7, 1).getTimezoneOffset()); const LOCAL_TIMEZONE_OFFSET_HOURS = LOCAL_TIMEZONE_OFFSET / 60; const LOCAL_TIMEZONE_STRING = // tslint:disable-next-line:max-line-length `${LOCAL_TIMEZONE_OFFSET >= 0 ? "+" : "-"}${StringUtil.leftPad(LOCAL_TIMEZONE_OFFSET_HOURS.toString(), 2, "0")}:00`; describe("DateUtil", function () { describe("without timezones", function () { it("should properly parse & format date (without UTC dates)", async function () { const dateUtil = new DateUtil({ withTimezone: false }); const date = moment("2018-10-15T09:46:28.306").toDate(); const stringified = dateUtil.stringify(date); assert.strictEqual(stringified, "2018-10-15T09:46:28.3060000"); const parsed = dateUtil.parse(stringified); assert.strictEqual(parsed.getHours(), date.getHours()); assert.strictEqual(parsed.toISOString(), date.toISOString()); }); it("should properly format regular date using UTC dates", async function () { const dateUtil = new DateUtil({ withTimezone: false, useUtcDates: true }); const date = moment("2018-10-15T12:00:00.000").toDate(); const stringified = dateUtil.stringify(date); const expected = new Date(2018, 9, 15, date.getHours() - LOCAL_TIMEZONE_OFFSET_HOURS, 0, 0, 0); const expectedStringified = moment(expected).format(DateUtil.DEFAULT_DATE_FORMAT) + "Z"; assert.strictEqual(stringified, expectedStringified); const parsed = dateUtil.parse(stringified); assert.strictEqual(parsed.getHours(), date.getHours()); assert.strictEqual(parsed.toISOString(), date.toISOString()); }); }); describe("with timezones", function () { it("should properly parse & format date (without UTC dates)", async function () { const dateUtil = new DateUtil({ withTimezone: true }); const hour6 = 12; const timezoneOffsetHours = 6; const date = moment.parseZone(`2018-10-15T${hour6}:00:00.0000000+06:00`).toDate(); // preconditions check assert.strictEqual( date.getHours(), hour6 - timezoneOffsetHours + LOCAL_TIMEZONE_OFFSET_HOURS); const expectedHours = date.getHours(); const expected = new Date(2018, 9, 15, expectedHours, 0, 0, 0); const expectedStringified = moment(expected).format(DateUtil.DEFAULT_DATE_FORMAT) + LOCAL_TIMEZONE_STRING; const stringified = dateUtil.stringify(date); assert.strictEqual(stringified, expectedStringified); const parsed = dateUtil.parse(stringified); assert.strictEqual(parsed.getHours(), date.getHours()); assert.strictEqual(parsed.toISOString(), date.toISOString()); }); it("should properly format regular date using UTC dates", async function () { const dateUtil = new DateUtil({ withTimezone: true, useUtcDates: true }); const hour6 = 12; const timezoneOffsetHours = 6; const date = moment.parseZone(`2018-10-15T${hour6}:00:00.0000000+06:00`).toDate(); // preconditions check assert.strictEqual( date.getHours(), hour6 - timezoneOffsetHours + LOCAL_TIMEZONE_OFFSET_HOURS); const expectedHours = date.getHours() - LOCAL_TIMEZONE_OFFSET_HOURS; const utcTimezoneString = "+00:00"; const expected = new Date(2018, 9, 15, expectedHours, 0, 0, 0); const expectedStringified = moment(expected).format(DateUtil.DEFAULT_DATE_FORMAT) + utcTimezoneString; const stringified = dateUtil.stringify(date); assert.strictEqual(stringified, expectedStringified); const parsed = dateUtil.parse(stringified); assert.strictEqual(parsed.getHours(), date.getHours()); assert.strictEqual(parsed.toISOString(), date.toISOString()); }); }); }); describe("[RDBC-236] Dates storage", function () { let store: IDocumentStore; describe("storing timezone info", function () { beforeEach(async function () { testContext.customizeStore = async store => { store.conventions.storeDatesWithTimezoneInfo = true; store.conventions.findCollectionNameForObjectLiteral = () => "tests"; }; store = await testContext.getDocumentStore(); }); afterEach(function () { testContext.customizeStore = null; }); afterEach(async () => await disposeTestDocumentStore(store)); it("can store & load date", async () => { const hoursLocal = 13; const date = new Date(2018, 9, 12, hoursLocal, 10, 10, 0); { const session = store.openSession(); await session.store({ start: date }, "date/1"); await session.saveChanges(); } { const cmd = new GetDocumentsCommand({ ids: [ "date/1" ], start: 0, pageSize: 1, conventions: store.conventions }); await store.getRequestExecutor().execute(cmd); assert.strictEqual( cmd.result.results[0]["start"], "2018-10-12T13:10:10.0000000" + LOCAL_TIMEZONE_STRING); } { const session = store.openSession(); const loaded = await session.load("date/1"); const { start } = loaded as any; assert.strictEqual(start.getHours(), date.getHours()); assert.strictEqual(start.toString(), date.toString()); } }); }); describe("store dates as UTC", function () { beforeEach(async function () { testContext.customizeStore = async store => { store.conventions.storeDatesInUtc = true; store.conventions.findCollectionNameForObjectLiteral = () => "tests"; }; store = await testContext.getDocumentStore(); }); afterEach(function () { testContext.customizeStore = null; }); afterEach(async () => await disposeTestDocumentStore(store)); it("can properly store & load date", async () => { const hoursLocal = 13; const date = new Date(2018, 9, 12, hoursLocal, 10, 10, 0); { const session = store.openSession(); await session.store({ start: date }, "date/1"); await session.saveChanges(); } { const cmd = new GetDocumentsCommand({ ids: [ "date/1" ], start: 0, pageSize: 1, conventions: store.conventions }); await store.getRequestExecutor().execute(cmd); const hoursUtcString = StringUtil.leftPad( (hoursLocal - LOCAL_TIMEZONE_OFFSET_HOURS).toString(), 2, "0"); assert.strictEqual( cmd.result.results[0]["start"], `2018-10-12T${hoursUtcString}:10:10.0000000Z`); } { const session = store.openSession(); const loaded = await session.load("date/1"); const { start } = loaded as any; assert.strictEqual(start.getHours(), date.getHours()); assert.strictEqual(start.toString(), date.toString()); } }); }); describe("store dates as UTC with timezone info", function () { beforeEach(async function () { testContext.customizeStore = async store => { store.conventions.storeDatesWithTimezoneInfo = true; store.conventions.storeDatesInUtc = true; store.conventions.findCollectionNameForObjectLiteral = () => "tests"; }; store = await testContext.getDocumentStore(); }); afterEach(function () { testContext.customizeStore = null; }); afterEach(async () => await disposeTestDocumentStore(store)); it("can store & load date", async () => { const hoursLocal = 13; const date = new Date(2018, 9, 12, hoursLocal, 10, 10, 0); { const session = store.openSession(); await session.store({ start: date }, "date/1"); await session.saveChanges(); } { const cmd = new GetDocumentsCommand({ ids: [ "date/1" ], start: 0, pageSize: 1, conventions: store.conventions }); await store.getRequestExecutor().execute(cmd); const hoursUtcString = StringUtil.leftPad( (hoursLocal - LOCAL_TIMEZONE_OFFSET_HOURS).toString(), 2, "0"); assert.strictEqual( cmd.result.results[0]["start"], `2018-10-12T${hoursUtcString}:10:10.0000000+00:00`); } { const session = store.openSession(); const loaded = await session.load("date/1"); const { start } = loaded as any; assert.strictEqual(start.getHours(), date.getHours()); assert.strictEqual(start.toString(), date.toString()); } }); }); });
the_stack
import * as vscode from "vscode"; import { Context, edit, Positions, Selections } from ".."; import { TrackedSelection } from "../../utils/tracked-selection"; const enum Constants { PositionMask = 0b00_11_1, BehaviorMask = 0b11_00_1, } function mapResults( insertFlags: insert.Flags, document: vscode.TextDocument, selections: readonly vscode.Selection[], replacements: readonly replace.Result[], ) { let flags = TrackedSelection.Flags.Inclusive | TrackedSelection.Flags.EmptyExtendsForward, where = undefined as "start" | "end" | "active" | "anchor" | undefined; switch (insertFlags & Constants.PositionMask) { case insert.Flags.Active: where = "active"; break; case insert.Flags.Anchor: where = "anchor"; break; case insert.Flags.Start: where = "start"; break; case insert.Flags.End: where = "end"; break; } if (where !== undefined && (insertFlags & Constants.BehaviorMask) === insert.Flags.Keep) { flags = (insertFlags & Constants.PositionMask) === insert.Flags.Start ? TrackedSelection.Flags.StrictStart : TrackedSelection.Flags.StrictEnd; } const savedSelections = TrackedSelection.fromArray(selections, document), discardedSelections = new Uint8Array(selections.length); const promise = edit((editBuilder) => { for (let i = 0, len = replacements.length; i < len; i++) { const result = replacements[i], selection = selections[i]; if (result === undefined) { editBuilder.delete(selection); discardedSelections[i] = 1; } else if (where === undefined) { editBuilder.replace(selection, result); if (TrackedSelection.length(savedSelections, i) !== result.length) { const documentChangedEvent: vscode.TextDocumentContentChangeEvent[] = [{ range: selection, rangeOffset: TrackedSelection.startOffset(savedSelections, i), rangeLength: TrackedSelection.length(savedSelections, i), text: result, }]; TrackedSelection.updateAfterDocumentChanged(savedSelections, documentChangedEvent, flags); } } else { const position = selection[where]; editBuilder.replace(position, result); const selectionOffset = TrackedSelection.startOffset(savedSelections, i), selectionLength = TrackedSelection.length(savedSelections, i); const documentChangedEvent: vscode.TextDocumentContentChangeEvent[] = [{ range: new vscode.Range(position, position), rangeOffset: position === selection.start ? selectionOffset : selectionOffset + selectionLength, rangeLength: 0, text: result, }]; TrackedSelection.updateAfterDocumentChanged(savedSelections, documentChangedEvent, flags); } } }).then(() => { const results: vscode.Selection[] = []; for (let i = 0, len = discardedSelections.length; i < len; i++) { if (discardedSelections[i]) { continue; } let restoredSelection = TrackedSelection.restore(savedSelections, i, document); if (where !== undefined && (insertFlags & Constants.BehaviorMask) === insert.Flags.Select) { // Selections were extended; we now unselect the previously selected // text. const totalLength = TrackedSelection.length(savedSelections, i), insertedLength = replacements[i]!.length, previousLength = totalLength - insertedLength; if (restoredSelection[where] === restoredSelection.start) { restoredSelection = Selections.fromStartEnd( restoredSelection.start, Positions.offset(restoredSelection.end, -previousLength, document)!, restoredSelection.isReversed, ); } else { restoredSelection = Selections.fromStartEnd( Positions.offset(restoredSelection.start, previousLength, document)!, restoredSelection.end, restoredSelection.isReversed, ); } } results.push(restoredSelection); } return results; }); return Context.wrap(promise); } /** * Inserts text next to the given selections according to the given function. * * @param f A mapping function called for each selection; given the text content * and the index of the selection, it should return the new text content of * the selection, or `undefined` if it is to be removed. Also works for * `async` (i.e. `Promise`-returning) functions, in which case **all** results * must be promises. * @param selections If `undefined`, the selections of the active editor will be * used. Otherwise, must be a `vscode.Selection` array which will be mapped * in the active editor. * * ### Example * ```js * Selections.set(await insert(insert.Replace, (x) => `${+x * 2}`)); * ``` * * Before: * ``` * 1 2 3 * ^ 0 * ^ 1 * ^ 2 * ``` * * After: * ``` * 2 4 6 * ^ 0 * ^ 1 * ^ 2 * ``` */ export function insert( flags: insert.Flags, f: insert.Callback<insert.Result> | insert.Callback<insert.AsyncResult>, selections?: readonly vscode.Selection[], ): Thenable<vscode.Selection[]> { return insert.byIndex( flags, (i, selection, document) => f(document.getText(selection), selection, i, document) as any, selections, ); } export namespace insert { /** * Insertion flags for `insert`. */ export const enum Flags { /** * Replace text and select replacement text. */ Replace = 0, /** * Insert at active position of selection. */ Active = 0b00_00_1, /** * Insert at start of selection. */ Start = 0b00_01_1, /** * Insert at end of selection. */ End = 0b00_10_1, /** * Insert at anchor of selection. */ Anchor = 0b00_11_1, /** * Keep current selections. */ Keep = 0b00_00_1, /** * Select inserted text only. */ Select = 0b01_00_1, /** * Extend to inserted text. */ Extend = 0b10_00_1, } export const Replace = Flags.Replace, Start = Flags.Start, End = Flags.End, Active = Flags.Active, Anchor = Flags.Anchor, Keep = Flags.Keep, Select = Flags.Select, Extend = Flags.Extend; export function flagsAtEdge(edge?: "active" | "anchor" | "start" | "end") { switch (edge) { case undefined: return Flags.Replace; case "active": return Flags.Active; case "anchor": return Flags.Anchor; case "start": return Flags.Start; case "end": return Flags.End; } } /** * The result of a callback passed to `insert` or `insert.byIndex`. */ export type Result = string | undefined; /** * The result of an async callback passed to `insert` or `insert.byIndex`. */ export type AsyncResult = Thenable<Result>; /** * A callback passed to `insert`. */ export interface Callback<T> { (text: string, selection: vscode.Selection, index: number, document: vscode.TextDocument): T; } /** * A callback passed to `insert.byIndex`. */ export interface ByIndexCallback<T> { (index: number, selection: vscode.Selection, document: vscode.TextDocument): T; } /** * Inserts text next to the given selections according to the given function. * * @param f A mapping function called for each selection; given the index, * range and editor of each selection, it should return the new text content * of the selection, or `undefined` if it is to be removed. Also works for * `async` (i.e. `Promise`-returning) functions, in which case **all** * results must be promises. * @param selections If `undefined`, the selections of the active editor will * be used. Otherwise, must be a `vscode.Selection` array which will be * mapped in the active editor. * * ### Example * ```js * Selections.set(await insert.byIndex(insert.Start, (i) => `${i + 1}`)); * ``` * * Before: * ``` * a b c * ^ 0 * ^ 1 * ^ 2 * ``` * * After: * ``` * 1a 2b 3c * ^ 0 * ^ 1 * ^ 2 * ``` * * ### Example * ```js * Selections.set(await insert.byIndex(insert.Start | insert.Select, (i) => `${i + 1}`)); * ``` * * Before: * ``` * a b c * ^ 0 * ^ 1 * ^ 2 * ``` * * After: * ``` * 1a 2b 3c * ^ 0 * ^ 1 * ^ 2 * ``` * * ### Example * ```js * Selections.set(await insert.byIndex(insert.Start | insert.Extend, (i) => `${i + 1}`)); * ``` * * Before: * ``` * a b c * ^ 0 * ^ 1 * ^ 2 * ``` * * After: * ``` * 1a 2b 3c * ^^ 0 * ^^ 1 * ^^ 2 * ``` * * ### Example * ```js * Selections.set(await insert.byIndex(insert.End, (i) => `${i + 1}`)); * ``` * * Before: * ``` * a b c * ^ 0 * ^ 1 * ^ 2 * ``` * * After: * ``` * a1 b2 c3 * ^ 0 * ^ 1 * ^ 2 * ``` * * ### Example * ```js * Selections.set(await insert.byIndex(insert.End | insert.Select, (i) => `${i + 1}`)); * ``` * * Before: * ``` * a b c * ^ 0 * ^ 1 * ^ 2 * ``` * * After: * ``` * a1 b2 c3 * ^ 0 * ^ 1 * ^ 2 * ``` * * ### Example * ```js * Selections.set(await insert.byIndex(insert.End | insert.Extend, (i) => `${i + 1}`)); * ``` * * Before: * ``` * a b c * ^ 0 * ^ 1 * ^ 2 * ``` * * After: * ``` * a1 b2 c3 * ^^ 0 * ^^ 1 * ^^ 2 * ``` */ export function byIndex( flags: Flags, f: ByIndexCallback<Result> | ByIndexCallback<AsyncResult>, selections: readonly vscode.Selection[] = Context.current.selections, ): Thenable<vscode.Selection[]> { if (selections.length === 0) { return Context.wrap(Promise.resolve([])); } const document = Context.current.document, firstResult = f(0, selections[0], document); if (typeof firstResult === "object") { // `f` returns promises. const promises = [firstResult]; for (let i = 1, len = selections.length; i < len; i++) { promises.push(f(i, selections[i], document) as AsyncResult); } return Context.wrap( Promise .all(promises) .then((results) => mapResults(flags, document, selections, results)), ); } // `f` returns regular values. const allResults: Result[] = [firstResult]; for (let i = 1, len = selections.length; i < len; i++) { allResults.push(f(i, selections[i], document) as Result); } return mapResults(flags, document, selections, allResults); } export namespace byIndex { /** * Same as `insert.byIndex`, but also inserts strings that end with a * newline character on the next or previous line. */ export async function withFullLines( flags: Flags, f: ByIndexCallback<Result> | ByIndexCallback<AsyncResult>, selections: readonly vscode.Selection[] = Context.current.selections, ) { const document = Context.current.document, allResults = await Promise.all(selections.map((sel, i) => f(i, sel, document))); // Separate full-line results from all results. const results: Result[] = [], resultsSelections: vscode.Selection[] = [], fullLineResults: Result[] = [], fullLineResultsSelections: vscode.Selection[] = [], isFullLines: boolean[] = []; for (let i = 0; i < allResults.length; i++) { const result = allResults[i]; if (result === undefined) { continue; } if (result.endsWith("\n")) { fullLineResults.push(result); fullLineResultsSelections.push(selections[i]); isFullLines.push(true); } else { results.push(result); resultsSelections.push(selections[i]); isFullLines.push(false); } } if (fullLineResults.length === 0) { return await mapResults(flags, document, resultsSelections, results); } let savedSelections = new TrackedSelection.Set( TrackedSelection.fromArray(fullLineResultsSelections, document), document, ); // Insert non-full lines. const normalSelections = await mapResults(flags, document, resultsSelections, results); // Insert full lines. const fullLineSelections = savedSelections.restore(); savedSelections.dispose(); const nextFullLineSelections: vscode.Selection[] = [], insertionPositions: vscode.Position[] = []; if ((flags & Constants.PositionMask) === Flags.Start) { for (const selection of fullLineSelections) { const insertionPosition = Positions.lineStart(selection.start.line); insertionPositions.push(insertionPosition); if ((flags & Constants.BehaviorMask) === Flags.Extend) { nextFullLineSelections.push( Selections.fromStartEnd( insertionPosition, selection.end, selection.isReversed, document), ); } else if ((flags & Constants.BehaviorMask) === Flags.Select) { nextFullLineSelections.push(Selections.empty(insertionPosition)); } else { // Keep selection as is. nextFullLineSelections.push(selection); } } } else { for (const selection of fullLineSelections) { const insertionPosition = Positions.lineStart(Selections.endLine(selection) + 1); insertionPositions.push(insertionPosition); if ((flags & Constants.BehaviorMask) === Flags.Extend) { nextFullLineSelections.push( Selections.fromStartEnd( selection.start, insertionPosition, selection.isReversed, document), ); } else if ((flags & Constants.BehaviorMask) === Flags.Select) { nextFullLineSelections.push(Selections.empty(insertionPosition)); } else { // Keep selection as is. nextFullLineSelections.push(selection); } } } savedSelections = new TrackedSelection.Set( TrackedSelection.fromArray(nextFullLineSelections, document), document, (flags & Constants.BehaviorMask) === Flags.Keep ? TrackedSelection.Flags.Strict : TrackedSelection.Flags.Inclusive, ); await edit((editBuilder) => { for (let i = 0; i < insertionPositions.length; i++) { editBuilder.replace(insertionPositions[i], fullLineResults[i]!); } }); const finalFullLineSelections = savedSelections.restore(); savedSelections.dispose(); // Merge back selections. const allSelections: vscode.Selection[] = []; for (let i = 0, normalIdx = 0, fullLineIdx = 0; i < isFullLines.length; i++) { if (isFullLines[i]) { allSelections.push(finalFullLineSelections[fullLineIdx++]); } else { allSelections.push(normalSelections[normalIdx++]); } } return allSelections; } } } /** * Replaces the given selections according to the given function. * * @param f A mapping function called for each selection; given the text content * and the index of the selection, it should return the new text content of * the selection, or `undefined` if it is to be removed. Also works for * `async` (i.e. `Promise`-returning) functions, in which case **all** results * must be promises. * @param selections If `undefined`, the selections of the active editor will be * used. Otherwise, must be a `vscode.Selection` array which will be mapped * in the active editor. * * ### Example * ```js * await replace((x) => `${+x * 2}`); * ``` * * Before: * ``` * 1 2 3 * ^ 0 * ^ 1 * ^ 2 * ``` * * After: * ``` * 2 4 6 * ^ 0 * ^ 1 * ^ 2 * ``` */ export function replace( f: replace.Callback<replace.Result> | replace.Callback<replace.AsyncResult>, selections?: readonly vscode.Selection[], ): Thenable<vscode.Selection[]> { return insert(insert.Flags.Replace, f, selections); } export namespace replace { /** * The result of a callback passed to `replace` or `replace.byIndex`. */ export type Result = string | undefined; /** * The result of an async callback passed to `replace` or `replace.byIndex`. */ export type AsyncResult = Thenable<Result>; /** * A callback passed to `replace`. */ export interface Callback<T> { (text: string, selection: vscode.Selection, index: number, document: vscode.TextDocument): T; } /** * A callback passed to `replace.byIndex`. */ export interface ByIndexCallback<T> { (index: number, selection: vscode.Selection, document: vscode.TextDocument): T; } /** * Replaces the given selections according to the given function. * * @param f A mapping function called for each selection; given the index, * range and editor of each selection, it should return the new text content * of the selection, or `undefined` if it is to be removed. Also works for * `async` (i.e. `Promise`-returning) functions, in which case **all** * results must be promises. * @param selections If `undefined`, the selections of the active editor will * be used. Otherwise, must be a `vscode.Selection` array which will be * mapped in the active editor. * * ### Example * ```js * await replace.byIndex((i) => `${i + 1}`); * ``` * * Before: * ``` * a b c * ^ 0 * ^ 1 * ^ 2 * ``` * * After: * ``` * 1 2 3 * ^ 0 * ^ 1 * ^ 2 * ``` */ export function byIndex( f: ByIndexCallback<Result> | ByIndexCallback<AsyncResult>, selections?: readonly vscode.Selection[], ): Thenable<vscode.Selection[]> { return insert.byIndex(insert.Flags.Replace, f, selections); } } /** * Rotates the given selections and their contents by the given offset. * * @param selections If `undefined`, the selections of the active editor will be * used. Otherwise, must be a `vscode.Selection` array which will be mapped * in the active editor. * * ### Example * ```js * await rotate(1); * ``` * * Before: * ``` * a b c * ^ 0 * ^ 1 * ^ 2 * ``` * * After: * ``` * b c a * ^ 1 * ^ 2 * ^ 0 * ``` */ export function rotate(by: number, selections?: readonly vscode.Selection[]) { return rotate .contentsOnly(by, selections) .then((selections) => rotate.selectionsOnly(by, selections)); } export namespace rotate { /** * Rotates the contents of the given selections by the given offset. * * @see rotate * * ### Example * ```js * await rotate.contentsOnly(1); * ``` * * Before: * ``` * a b c * ^ 0 * ^ 1 * ^ 2 * ``` * * After: * ``` * b c a * ^ 0 * ^ 1 * ^ 2 * ``` */ export function contentsOnly( by: number, selections: readonly vscode.Selection[] = Context.current.selections, ) { const len = selections.length; // Handle negative values for `by`: by = (by % len) + len; if (by === len) { return Context.wrap(Promise.resolve(selections.slice())); } return replace.byIndex( (i, _, document) => document.getText(selections[(i + by) % len]), selections, ); } /** * Rotates the given selections (but not their contents) by the given offset. * * @see rotate * * ### Example * ```js * rotate.selectionsOnly(1); * ``` * * Before: * ``` * a b c * ^ 0 * ^ 1 * ^ 2 * ``` * * After: * ``` * a b c * ^ 1 * ^ 2 * ^ 0 * ``` */ export function selectionsOnly(by: number, selections?: readonly vscode.Selection[]) { Selections.set(Selections.rotate(by, selections)); } }
the_stack
namespace Textor { export class TextModel { private _textBuffer: TextBuffer; private _undoService: UndoService; private _textRange: TextRange = new TextRange(new TextPosition(0, 0), new TextPosition(0, 0)); private _selectionChangedHandlers: SelectionChangeHandler[] = []; private _tabSize: number; private _tabText: string; constructor(undoService: UndoService, textBuffer: TextBuffer) { this._textBuffer = textBuffer; this._undoService = undoService; } public addEventListener(type: string, callback: (e) => void) { switch (type) { case "selectionchanged": this._selectionChangedHandlers.push(callback); break; } } public removeEventListener(type: string, callback: (e) => void) { switch (type) { case "selectionchanged": this._selectionChangedHandlers = this._selectionChangedHandlers.filter((item) => item !== callback); break; } } public get textRange(): TextRange { return this._textRange; } public get tabText(): string { return this._tabText; } public select(textPosition: TextPosition) { if (!textPosition.equals(this._textRange.start) || !textPosition.equals(this._textRange.end)) { const oldRange: TextRange = this._textRange; this._textRange = new TextRange(new TextPosition(textPosition.line, textPosition.column), new TextPosition(textPosition.line, textPosition.column)); this.onSelectionChanged(new SelectionChangeEvent(oldRange, this._textRange)); } } public selectRange(textRange: TextRange) { if (!textRange.start.equals(this._textRange.start) || !textRange.end.equals(this._textRange.end)) { const oldRange = this._textRange; this._textRange = textRange; this.onSelectionChanged(new SelectionChangeEvent(oldRange, this._textRange)); } } public moveCursor(dimension: string, distance: string, direction: string, select: boolean) { let position: TextPosition = this._textRange.end; if (!select) { position = (direction === "previous") ? this.getTextRange().start : this.getTextRange().end; if (dimension === "line") { position.column = (direction === "previous") ? this._textRange.start.column : this._textRange.end.column; } } // switch to text buffer units position = this.toBufferPosition(position); if (dimension === "column") { if (select || this.isCursor()) { if (distance === "boundary") { if (direction !== "previous") { position.column = this._textBuffer.getColumns(position.line); } else { // search first non-whitespace character const text: string = this._textBuffer.getLine(position.line); for (let i = 0; i < text.length; i++) { if ((text[i] !== " ") && (text[i] !== "\t")) { position.column = (i === position.column) ? 0 : i; break; } } } } else if (distance === "word") { const text: string = this._textBuffer.getLine(position.line); if ((direction !== "previous") && (position.column >= text.length)) { position.column++; } else if ((direction === "previous") && (position.column === 0)) { position.column--; } else { position.column = this.findWordBreak(text, position.column, (direction === "previous") ? -1 : +1); } } else { position.column += (direction === "previous") ? -Number(distance) : +Number(distance); } if (position.column < 0) { position.line--; if (position.line < 0) { position.line = 0; position.column = 0; } else { position.column = this._textBuffer.getColumns(position.line); } } if (position.column > this._textBuffer.getColumns(position.line)) { position.line++; position.column = 0; if (position.line >= this._textBuffer.getLines()) { position.line = this._textBuffer.getLines() - 1; position.column = this._textBuffer.getColumns(position.line); } } } } if (dimension === "line") { if (distance !== "boundrary") { position.line += (direction === "previous") ? -Number(distance) : +Number(distance); } if (position.line < 0) { position.line = 0; position.column = 0; } else if (position.line > this._textBuffer.getLines() - 1) { position.line = this._textBuffer.getLines() - 1; position.column = this._textBuffer.getColumns(position.line); } } // switch back to selection units with tabs expanded position = this.toScreenPosition(position); const textRange = (select) ? new TextRange(new TextPosition(this._textRange.start.line, this._textRange.start.column), position) : new TextRange(position, position); this._undoService.begin(); this._undoService.add(new SelectionUndoUnit(this, textRange)); this._undoService.commit(); } public insertText(text: string) { this._undoService.begin(); this._undoService.add(new TextUndoUnit( this, this._textBuffer, this.toBufferRange(this.getTextRange()), text)); this._undoService.commit(); } public deleteSelection(position: string) { if (!this.isCursor() || (position === null)) { this.insertText(""); } else { const textRange = this.toBufferRange(this.getTextRange()); if (position === "previous") { textRange.start.column--; if (textRange.start.column < 0) { textRange.start.line--; if (textRange.start.line < 0) { textRange.start.line = 0; textRange.start.column = 0; } else { textRange.start.column = this._textBuffer.getColumns(textRange.start.line); } } } else if (position === "next") { textRange.end.column++; if (textRange.end.column > this._textBuffer.getColumns(textRange.end.line)) { textRange.end.line++; if (textRange.end.line > this._textBuffer.getLines() - 1) { textRange.end.line = this._textBuffer.getLines() - 1; textRange.end.column = this._textBuffer.getColumns(textRange.end.line); } else { textRange.end.column = 0; } } } this._undoService.begin(); this._undoService.add(new TextUndoUnit(this, this._textBuffer, textRange, "")); this._undoService.commit(); } } public getTextRange(): TextRange { // return valid range with tabs expanded if (this.isCursor()) { let line: number = this._textRange.start.line; let column: number = this._textRange.start.column; if (line >= this._textBuffer.getLines()) { line = this._textBuffer.getLines() - 1; column = this.getColumns(line); } else if (column > this.getColumns(line)) { column = this.getColumns(line); } return new TextRange(new TextPosition(line, column), new TextPosition(line, column)); } const textRange: TextRange = this._textRange.clone(); if (textRange.start.line >= this._textBuffer.getLines()) { textRange.start.line = this._textBuffer.getLines() - 1; textRange.start.column = this.getColumns(textRange.start.line); } if (textRange.end.line >= this._textBuffer.getLines()) { textRange.end.line = this._textBuffer.getLines() - 1; textRange.end.column = this.getColumns(textRange.end.line); } if (textRange.start.column > this.getColumns(textRange.start.line)) { textRange.start = new TextPosition(textRange.start.line, this.getColumns(textRange.start.line)); } if (textRange.end.column > this.getColumns(textRange.end.line)) { textRange.end = new TextPosition(textRange.end.line, this.getColumns(textRange.end.line)); } return textRange.normalize(); } public isCursor(): boolean { return this._textRange.isEmpty; } public set tabSize(value: number) { this._tabSize = value; this._tabText = ""; for (let i = 0; i < this._tabSize; i++) { this._tabText += " "; } } public get tabSize(): number { return this._tabSize; } public getColumns(line: number): number { return this.getTabLength(this._textBuffer.getLine(line)); } public getTabLength(text: string): number { let tabLength = 0; const bufferLength = text.length; for (let i = 0; i < bufferLength; i++) { tabLength += (text[i] === "\t") ? this._tabSize : 1; } return tabLength; } public toScreenPosition(textPosition: TextPosition) { // transform from text buffer position to selection position. const text = this._textBuffer.getLine(textPosition.line).substring(0, textPosition.column); const length = this.getTabLength(text) - text.length; return new TextPosition(textPosition.line, textPosition.column + length); } public toBufferPosition(textPosition: TextPosition) { // transform from selection position to text buffer position. const text = this._textBuffer.getLine(textPosition.line); let column = 0; for (let i = 0; i < text.length; i++) { column += (text[i] === "\t") ? this._tabSize : 1; if (column > textPosition.column) { return new TextPosition(textPosition.line, i); } } return new TextPosition(textPosition.line, text.length); } public toScreenRange(textRange: TextRange): TextRange { return new TextRange(this.toScreenPosition(textRange.start), this.toScreenPosition(textRange.end)); } public toBufferRange(textRange: TextRange): TextRange { return new TextRange(this.toBufferPosition(textRange.start), this.toBufferPosition(textRange.end)); } public getIndent(): string { const textRange: TextRange = this.getTextRange(); if (textRange.isEmpty) { let text: string = this._textBuffer.getLine(textRange.end.line); let index: number = 0; while ((index < text.length) && (text[index] === "\t" || text[index] === " ")) { index++; } text = text.substring(0, index); if (textRange.end.column >= this.getTabLength(text)) { return text; } } return ""; } public findWordBreak(text: string, startIndex: number, increment: number): number { if (increment < 0) { startIndex += increment; } const startState: boolean = this.isWordSeparator(text[startIndex]); for (let i = startIndex; (i >= 0) && (i < text.length); i += increment) { if (this.isWordSeparator(text[i]) !== startState) { return (increment < 0) ? (i -= increment) : i; } } return (increment < 0) ? 0 : text.length; } private isWordSeparator(character: string): boolean { return ' \t\'",;.!~@#$%^&*?=<>()[]:\\+-'.indexOf(character) !== -1; } private onSelectionChanged(e: SelectionChangeEvent) { for (const handler of this._selectionChangedHandlers) { handler(e); } } } }
the_stack
namespace LiteMol.Example.Channels.UI { import React = LiteMol.Plugin.React export interface UIState { app: State.AppState, /** * This represents the JSON data returned by MOLE. * * In a production environment (when using TypeScript), * it would be a good idea to write type interfaces for the * data to avoid bugs. */ data: any } export function render(app: State.AppState, target: Element) { LiteMol.Plugin.ReactDOM.render(<App {...app} />, target); } export class App extends React.Component<State.AppState, { isLoading?: boolean, error?: string, data?: any }> { state = { isLoading: false, data: void 0, error: void 0 }; componentDidMount() { this.load(); } load() { this.setState({ isLoading: true, error: void 0 }); State.loadData(this.props.plugin, '1tqn', 'data.json') .then(data => this.setState({ isLoading: false, data })) .catch(e => this.setState({ isLoading: false, error: '' + e })); } render() { if (this.state.data) { return <Data data={this.state.data} app={this.props} /> } else { let controls: any[] = []; if (this.state.isLoading) { controls.push(<h1>Loading...</h1>); } else { controls.push(<button onClick={() => this.load()}>Load Data</button>); if (this.state.error) { controls.push(<div style={{ color: 'red', fontSize: '18px' }}>Error: {this.state.error}</div>); } } return <div>{controls}</div>; } } } export class Data extends React.Component<UIState, {}> { render() { return <div> <Selection {...this.props} /> <h2>Channels</h2> <Channels channels={this.props.data.Channels.Tunnels} {...this.props} header='Tunnels' /> <Channels channels={this.props.data.Channels.MergedPores} {...this.props} header='Merged Pores' /> <Channels channels={this.props.data.Channels.Pores} {...this.props} header='Pores' /> <Channels channels={this.props.data.Channels.Paths} {...this.props} header='Paths' /> <h2>Empty Space</h2> <Cavities cavities={[this.props.data.Cavities.Surface]} {...this.props} header='Surface' /> <Cavities cavities={this.props.data.Cavities.Cavities} {...this.props} header='Cavities' /> <Cavities cavities={this.props.data.Cavities.Voids} {...this.props} header='Voids' /> <h2>Origins</h2> <Origins origins={this.props.data.Origins.User} {...this.props} label='User Specifed (optimized)' /> <Origins origins={this.props.data.Origins.InputOrigins} {...this.props} label='User Specifed' /> <Origins origins={this.props.data.Origins.Computed} {...this.props} label='Computed' /> <Origins origins={this.props.data.Origins.Database} {...this.props} label='Database' /> </div>; } } export class Selection extends React.Component<UIState, { label?: string }> { state = { label: void 0 } private observer: Bootstrap.Rx.IDisposable | undefined = void 0; componentWillMount() { this.observer = this.props.app.events.select.subscribe(e => { if (e.kind === 'nothing') { this.setState({ label: void 0}) } else if (e.kind === 'molecule') { let r = e.data.residues[0]; this.setState({ label: `${r.name} ${r.authSeqNumber} ${r.chain.authAsymId}` }); } else if (e.kind === 'point') { this.setState({ label: Behaviour.vec3str(e.data) }); } }); } componentWillUnmount() { if (this.observer) { this.observer.dispose(); this.observer = void 0; } } render() { return <div> <h3>Last Selection</h3> { !this.state.label ? <div><i>Click on atom or residue, or Ctrl+click on cavity boundary</i></div> : <div>{this.state.label}</div> } </div> } } export class Section extends React.Component<{ header: string, count: number }, { isExpanded: boolean }> { state = { isExpanded: false } private toggle(e: React.MouseEvent<HTMLElement>) { e.preventDefault(); this.setState({ isExpanded: !this.state.isExpanded }); } render() { return <div style={{ position: 'relative' }}> <h3><a href='#' onClick={e => this.toggle(e)} className='section-header'><div style={{ width: '15px', display: 'inline-block', textAlign: 'center' }}>{this.state.isExpanded ? '-' : '+'}</div> {this.props.header} ({this.props.count})</a></h3> <div style={{ display: this.state.isExpanded ? 'block' : 'none' }}>{this.props.children}</div> </div> } } export class Renderable extends React.Component<{ label: string | JSX.Element, element: any, toggle: (plugin: Plugin.Controller, elements: any[], visible: boolean) => Promise<any> } & UIState, { }> { private toggle() { this.props.element.__isBusy = true; this.forceUpdate(() => this.props.toggle(this.props.app.plugin, [this.props.element], !this.props.element.__isVisible) .then(() => this.forceUpdate()).catch(() => this.forceUpdate())); } private highlight(isOn: boolean) { this.props.app.plugin.command(Bootstrap.Command.Entity.Highlight, { entities: this.props.app.plugin.context.select(this.props.element.__id), isOn }); } render() { return <div> <label onMouseEnter={() => this.highlight(true)} onMouseLeave={() => this.highlight(false)} > <input type='checkbox' checked={!!this.props.element.__isVisible} onChange={() => this.toggle()} disabled={!!this.props.element.__isBusy} /> {this.props.label} </label> </div> } } export class Channels extends React.Component<UIState & { channels: any[], header: string }, { isBusy: boolean }> { state = { isBusy: false } private show(visible: boolean) { for (let element of this.props.channels) { element.__isBusy = true; } this.setState({ isBusy: true }, () => State.showChannelVisuals(this.props.app.plugin, this.props.channels, visible) .then(() => this.setState({ isBusy: false })).catch(() => this.setState({ isBusy: false }))); } render() { return <Section header={this.props.header} count={(this.props.channels || '').length}> <div className='show-all'><button onClick={() => this.show(true)} disabled={this.state.isBusy}>All</button><button onClick={() => this.show(false)} disabled={this.state.isBusy}>None</button></div> { this.props.channels && this.props.channels.length > 0 ? this.props.channels.map((c, i) => <Channel key={i} channel={c} {...this.props as any} />) : 'None'} </Section> } } export class Channel extends React.Component<UIState & { channel: any }, { isVisible: boolean }> { state = { isVisible: false }; render() { let c = this.props.channel; let len = c.Profile[c.Profile.length - 1].Distance; let bneck = c.Profile.reduce((b: number, n: any) => Math.min(b, n.Radius), Number.POSITIVE_INFINITY); return <Renderable label={<span><b>{c.Id}</b>, {`Length: ${len} Å, Bottleneck: ${bneck} Å`}</span>} element={c} toggle={State.showChannelVisuals} {...this.props as any} /> } } export class Cavities extends React.Component<UIState & { cavities: any[], header: string }, { isBusy: boolean }> { state = { isBusy: false } private show(visible: boolean) { for (let element of this.props.cavities) { element.__isBusy = true; } this.setState({ isBusy: true }, () => State.showCavityVisuals(this.props.app.plugin, this.props.cavities, visible) .then(() => this.setState({ isBusy: false })).catch(() => this.setState({ isBusy: false }))); } render() { return <Section header={this.props.header} count={(this.props.cavities || '').length}> <div className='show-all'><button onClick={() => this.show(true)} disabled={this.state.isBusy}>All</button><button onClick={() => this.show(false)} disabled={this.state.isBusy}>None</button></div> { this.props.cavities && this.props.cavities.length > 0 ? this.props.cavities.map((c, i) => <Cavity key={i} cavity={c} {...this.props as any} />) : 'None'} </Section> } } export class Cavity extends React.Component<UIState & { cavity: any }, { isVisible: boolean }> { state = { isVisible: false }; render() { let c = this.props.cavity; return <div> <Renderable label={<span><b>{c.Id}</b>, {`Volume: ${c.Volume | 0} Å`}<sup>3</sup></span>} element={c} toggle={State.showCavityVisuals} {...this.props as any} /> </div> } } export class Origins extends React.Component<{ label: string | JSX.Element, origins: any } & UIState, { }> { private toggle() { this.props.origins.__isBusy = true; this.forceUpdate(() => State.showOriginsSurface(this.props.app.plugin, this.props.origins, !this.props.origins.__isVisible) .then(() => this.forceUpdate()).catch(() => this.forceUpdate())); } private highlight(isOn: boolean) { this.props.app.plugin.command(Bootstrap.Command.Entity.Highlight, { entities: this.props.app.plugin.context.select(this.props.origins.__id), isOn }); } render() { if (!this.props.origins.Points.length) { return <div style={{ display: 'none' }} /> } return <div> <label onMouseEnter={() => this.highlight(true)} onMouseLeave={() => this.highlight(false)} > <input type='checkbox' checked={!!this.props.origins.__isVisible} onChange={() => this.toggle()} disabled={!!this.props.origins.__isBusy} /> {this.props.label} </label> </div> } } }
the_stack
import argparse = require('argparse'); import mkdirp = require('mkdirp') import sprintf = require('sprintf'); import pathLib = require('path'); import underscore = require('underscore'); import agile_keychain = require('../lib/agile_keychain'); import asyncutil = require('../lib/base/asyncutil'); import cli_common = require('./cli_common'); import clipboard = require('./clipboard'); import collectionutil = require('../lib/base/collectionutil'); import consoleio = require('./console'); import edit_cmd = require('./edit_cmd'); import item_repair = require('../lib/item_repair'); import item_search = require('../lib/item_search'); import item_store = require('../lib/item_store'); import key_agent = require('../lib/key_agent'); import nodefs = require('../lib/vfs/node'); import password_gen = require('../lib/password_gen'); import vfs = require('../lib/vfs/vfs'); import { defer } from '../lib/base/promise_util'; interface HandlerMap { [index: string]: (args: any) => Promise<any>; } interface NewPass { pass: string; hint: string; } enum ShowItemFormat { ShowOverview, ShowJSON, ShowFull } // reasons for a command to fail var NO_SUCH_ITEM_ERR = 'No items matched the pattern'; var NO_SUCH_FIELD_ERR = 'No fields matched the pattern'; var ACTION_CANCELED_ERR = 'Action canceled'; function sortByTitle(items: item_store.Item[]) { return items.concat().sort((a, b) => { return a.title.localeCompare(b.title); }); } export class CLI { private configDir: string; private io: consoleio.TermIO; private keyAgent: key_agent.KeyAgent; private clipboard: clipboard.Clipboard; private editCommand: cli_common.CommandHandler; private passwordGenerator: () => string; constructor(io?: consoleio.TermIO, agent?: key_agent.KeyAgent, clipboardImpl?: clipboard.Clipboard) { this.configDir = process.env.HOME + "/.config/agile_keychain-web"; this.io = io || new consoleio.ConsoleIO(); this.keyAgent = agent || new key_agent.SimpleKeyAgent(); this.clipboard = clipboardImpl || clipboard.createPlatformClipboard(); this.passwordGenerator = () => { return password_gen.generatePassword(12); }; } private printf(format: string, ...args: any[]) { consoleio.printf.apply(null, [this.io, format].concat(args)); } private createParser(): argparse.ArgumentParser { var parser = new argparse.ArgumentParser({ description: '1Password command-line client' }); parser.addArgument(['-v', '--vault'], { action: 'store', nargs: 1, dest: 'vault', help: 'Specify the path of the vault to open' }); parser.addArgument(['-d', '--debug'], { action: 'storeTrue', nargs: 1, dest: 'debug', help: 'Enable debug output' }); var subcommands = parser.addSubparsers({ dest: 'command' }); var listCommand = subcommands.addParser('list', { description: 'List items in the vault' }); listCommand.addArgument(['-p', '--pattern'], { action: 'store', dest: 'pattern', nargs: 1, type: 'string', help: 'List only items matching PATTERN' }) var itemPatternArg = () => { return { action: 'store', help: 'Pattern specifying the items' }; }; var showCommand = subcommands.addParser('show', { description: 'Show the contents of an item' }); showCommand.addArgument(['pattern'], itemPatternArg()); showCommand.addArgument(['--format'], { action: 'store', nargs: 1, dest: 'format', help: 'Output format for item contents', defaultValue: ['full'], type: 'string', choices: ['overview', 'full', 'json'] }); subcommands.addParser('lock', { description: 'Lock the vault so that the master password will be required ' + 'for any further commands' }); var copyCommand = subcommands.addParser('copy', { description: 'Copy the value of a field from an item to the clipboard' }); copyCommand.addArgument(['item'], itemPatternArg()); copyCommand.addArgument(['field'], { action: 'store', nargs: '?', defaultValue: 'password', help: 'Pattern specifying the name of the field to copy (eg. "username"). ' + 'Defaults to copying the password' }); var addCommand = subcommands.addParser('add', { description: 'Add a new item to the vault' }); addCommand.addArgument(['type'], { action: 'store', help: 'Type of item to add. The only supported value is currently "login"' }); addCommand.addArgument(['title'], { action: 'store', help: 'The title of the new item' }); this.editCommand = new edit_cmd.EditCommand(this.io, subcommands, this.passwordGenerator); var trashCommand = subcommands.addParser('trash', { description: 'Move items in the vault to the trash' }); trashCommand.addArgument(['item'], itemPatternArg()); var restoreCommand = subcommands.addParser('restore', { description: 'Restore items in the vault that were previously trashed' }); restoreCommand.addArgument(['item'], itemPatternArg()); var setPassCommand = subcommands.addParser('set-password', { description: 'Change the master password for the vault' }); setPassCommand.addArgument(['--iterations'], { action: 'store', dest: 'iterations', type: 'int' }); var removeCommand = subcommands.addParser('remove', { description: 'Remove items from the vault. This action is permanent and cannot be undone.' }); removeCommand.addArgument(['pattern'], itemPatternArg()); subcommands.addParser('gen-password', { description: 'Generate a new random password' }); var newVaultCommand = subcommands.addParser('new-vault'); newVaultCommand.addArgument(['path'], { action: 'store' }); newVaultCommand.addArgument(['--iterations'], { action: 'store', dest: 'iterations', type: 'int' }); subcommands.addParser('repair', { description: 'Check and repair items in a vault' }); return parser; } private findExistingVaultInDropbox(storage: vfs.VFS, dropboxRoot: string): Promise<string> { var path = defer<string>(); var settingsFilePath = pathLib.join(dropboxRoot, '.ws.agile.1Password.settings'); var rootFile = storage.read(settingsFilePath); rootFile.then((content) => { path.resolve(pathLib.join(dropboxRoot, content)); }, (err) => { this.printf('Unable to find keychain path in %s, using default path', settingsFilePath); path.resolve(pathLib.join(dropboxRoot, '1Password/1Password.agilekeychain')); }); return path.promise; } private unlockVault(vault: agile_keychain.Vault): Promise<void> { return vault.isLocked().then((isLocked) => { if (!isLocked) { return Promise.resolve<void>(null); } var password = this.io.readPassword('Master password: '); return password.then((password) => { return vault.unlock(password); }); }); } private printOverview(item: item_store.Item) { this.printf('%s (%s)', item.title, item.typeDescription()); this.printf('\nInfo:'); this.printf(' ID: %s', item.uuid); this.printf(' Updated: %s', item.updatedAt); item.locations.forEach((location) => { this.printf(' Location: %s', location); }); if (item.trashed) { this.printf(' In Trash: Yes'); } if (item.openContents && item.openContents.tags) { this.printf(' Tags: %s', item.openContents.tags.join(', ')); } } private printDetails(content: item_store.ItemContent) { if (content.sections.length > 0) { this.printf('\nSections:'); content.sections.forEach((section) => { if (section.title) { this.printf(' %s', section.title); } section.fields.forEach((field) => { this.printf(' %s: %s', field.title, item_store.fieldValueString(field)); }); }); } if (content.urls.length > 0) { this.printf('\nWebsites:'); content.urls.forEach((url) => { this.printf(' %s: %s', url.label, url.url); }); } if (content.formFields.length > 0) { this.printf('\nForm Fields:'); content.formFields.forEach((field) => { this.printf(' %s (%s): %s', field.name, field.type, field.value); }); } if (content.htmlAction) { this.printf('\nForm Destination: %s %s', content.htmlMethod.toUpperCase(), content.htmlAction); } } private initVault(customVaultPath: string): Promise<agile_keychain.Vault> { var storage: vfs.VFS = new nodefs.FileVFS('/'); var dropboxRoot: string; storage = new nodefs.FileVFS('/'); dropboxRoot = process.env.HOME + '/Dropbox'; if (customVaultPath) { customVaultPath = pathLib.resolve(customVaultPath); } var authenticated = Promise.resolve<void>(null); return authenticated.then(() => { if (customVaultPath) { return customVaultPath; } else { return this.findExistingVaultInDropbox(storage, dropboxRoot); } }).then(path => new agile_keychain.Vault(storage, path, this.keyAgent)); } private passwordFieldPrompt(): Promise<string> { return consoleio.passwordFieldPrompt(this.io, this.passwordGenerator); } /** Returns the item from @p vault matching a given @p pattern. * If there are multiple matching items the user is prompted to select one. */ private selectItem(vault: agile_keychain.Vault, pattern: string): Promise<item_store.Item> { return item_search.lookupItems(vault, pattern).then((items) => { return this.select(sortByTitle(items), 'items', 'Item', pattern, (item) => { return item.title; }); }); } // prompt the user for a selection from a list of items private select<T>(items: T[], plural: string, singular: string, pattern: string, captionFunc: (item: T) => string): Promise<T> { if (items.length < 1) { this.printf('No %s matching pattern "%s"', plural, pattern); return Promise.reject<T>(NO_SUCH_ITEM_ERR); } else if (items.length == 1) { return Promise.resolve(items[0]); } this.printf('Multiple %s match "%s":\n', plural, pattern); items.forEach((item, index) => { this.printf(' [%d] %s', index + 1, captionFunc(item)); }); this.printf(''); return this.io.readLine(sprintf('Select %s: ', singular)).then((indexStr) => { var index = parseInt(indexStr) - 1 || 0; if (index < 0) { index = 0; } else if (index >= items.length) { index = items.length - 1; } return items[index]; }); } private addLoginFields(content: item_store.ItemContent): Promise<item_store.ItemContent> { return this.io.readLine('Website: ').then((website) => { content.urls.push({ label: 'website', url: website }); return this.io.readLine('Username: '); }) .then((username) => { content.formFields.push({ id: '', name: 'username', designation: 'username', type: item_store.FormFieldType.Text, value: username }); return this.passwordFieldPrompt(); }) .then((password) => { content.formFields.push({ id: '', name: 'password', designation: 'password', type: item_store.FormFieldType.Password, value: password }); return content; }); } private addItemCommand(vault: agile_keychain.Vault, type: string, title: string): Promise<void> { var types = item_search.matchType(type); return this.select(types, 'item types', 'item type', type, (typeCode) => { return item_store.ITEM_TYPES[<string>typeCode].name; }).then((type) => { var item = new item_store.Item(vault); item.title = title; item.typeName = type; let content = item_store.ContentUtil.empty(); let contentReady: Promise<item_store.ItemContent>; if (type == item_store.ItemTypes.LOGIN) { contentReady = this.addLoginFields(content); } else { // add a default section with a blank title content.sections.push({ name: '', title: '', fields: [] }); contentReady = Promise.resolve(content); } return contentReady.then(() => { item.setContent(content); return item.save(); }).then(() => { this.printf("Added new item '%s'", item.title); return Promise.resolve<void>(null); }); }); } private trashItemCommand(vault: agile_keychain.Vault, pattern: string, trash: boolean): Promise<void[]> { return item_search.lookupItems(vault, pattern).then(items => { var trashOps: Promise<void>[] = []; items.forEach((item) => { item.trashed = trash; trashOps.push(item.save()); }); return Promise.all(trashOps); }); } private readNewPassword(): Promise<NewPass> { return this.io.readPassword('New password: ').then((pass) => { return this.io.readPassword('Re-enter new password: ').then((pass2) => { if (pass != pass2) { throw ('Passwords do not match'); } return this.io.readLine('Hint for new password: ').then((hint) => { return { pass: pass, hint: hint }; }); }); }); } private setPasswordCommand(vault: agile_keychain.Vault, iterations?: number): Promise<number> { var result = defer<number>(); var currentPass: string; var newPass: string; var newPass2: string; this.io.readPassword('Re-enter existing password: ').then((pass) => { currentPass = pass; return this.io.readPassword('New password: '); }).then((newPass_) => { newPass = newPass_; return this.io.readPassword('Re-enter new password: '); }).then((newPass2_) => { newPass2 = newPass2_; if (newPass != newPass2) { this.printf('Passwords do not match'); result.resolve(1); return undefined; } return this.io.readLine('Hint for new password: '); }).then((hint) => { return vault.changePassword(currentPass, newPass, hint, iterations); }).then(() => { this.printf('The master password for this vault has been changed.\n\n' + 'If you are using other 1Password apps, please note that they may still ' + 'require the previous password when they are next unlocked'); result.resolve(0); }).catch((err) => { this.printf('Unable to update the vault password: %s', err); }); return result.promise; } private removeCommand(vault: agile_keychain.Vault, pattern: string): Promise<void> { var items: item_store.Item[]; return item_search.lookupItems(vault, pattern).then((items_) => { items = sortByTitle(items_); if (items.length == 0) { this.printf('No matching items'); throw NO_SUCH_ITEM_ERR; } items.forEach((item) => { this.printOverview(item); }); this.printf(''); return this.io.readLine(sprintf('Do you really want to remove these %d item(s) permanently?', items.length)); }).then((response) => { if (response.match(/[yY]/)) { var removeOps: Promise<void>[] = []; items.forEach((item) => { removeOps.push(item.remove()); }); return Promise.all(removeOps).then(() => { this.printf(sprintf('%d items were removed', items.length)); }); } else { throw ACTION_CANCELED_ERR; } }); } private genPasswordCommand(): Promise<void> { this.printf(password_gen.generatePassword(12)); return Promise.resolve<void>(null); } private listCommand(vault: agile_keychain.Vault, pattern: string): Promise<void> { return vault.listItems().then((items) => { items.sort((a, b) => { return a.title.toLowerCase().localeCompare(b.title.toLowerCase()); }); var matchCount = 0; items.forEach((item) => { if (!pattern || item_search.matchItem(item, pattern)) { ++matchCount; this.printf('%s (%s, %s)', item.title, item.typeDescription(), item.shortID()); } }); this.printf('\n%d matching item(s) in vault', matchCount); }); } private showItemCommand(vault: agile_keychain.Vault, pattern: string, format: ShowItemFormat): Promise<void> { var item: item_store.Item; return this.selectItem(vault, pattern).then((_item) => { item = _item; return item.getContent(); }).then((content) => { if (format == ShowItemFormat.ShowOverview || format == ShowItemFormat.ShowFull) { this.printOverview(item); } if (format == ShowItemFormat.ShowFull) { this.printDetails(content); } if (format == ShowItemFormat.ShowJSON) { return item.getRawDecryptedData().then((json) => { var data = JSON.parse(json); this.printf('%s', collectionutil.prettyJSON(data)); }); } return undefined; }); } private copyItemCommand(vault: agile_keychain.Vault, pattern: string, field: string): Promise<void> { return this.selectItem(vault, pattern).then((item) => { return item.getContent().then((content) => { var matches = item_search.matchField(content, field); if (matches.length > 0) { var label: string; var match = matches[0]; var copied: Promise<void>; if (match.url) { label = match.url.label; copied = this.clipboard.setData(match.url.url); } else if (match.formField) { label = match.formField.designation || match.formField.name; copied = this.clipboard.setData(match.formField.value); } else if (match.field) { label = match.field.title; copied = this.clipboard.setData(match.field.value); } return copied.then(() => { this.printf('Copied "%s" from "%s" to clipboard', label, item.title); }); } else { this.printf('No fields matching "%s"', field); throw NO_SUCH_FIELD_ERR; } }); }); } private newVaultCommand(fs: vfs.VFS, path: string, iterations?: number): Promise<void> { return this.readNewPassword().then((newPass) => { var absPath = pathLib.resolve(path); return agile_keychain.Vault.createVault(fs, absPath, newPass.pass, newPass.hint, iterations).then((vault) => { this.printf('New vault created in %s', vault.vaultPath()); }); }); } private repairCommand(vault: agile_keychain.Vault): Promise<{}> { return vault.listItems().then((items) => { var sortedItems = underscore.sortBy(items, (item) => { return item.title.toLowerCase(); }); var repairTasks: Array<() => Promise<void>> = []; this.printf('Checking %d items...', sortedItems.length); sortedItems.forEach((item) => { var repairTask = () => { return item_repair.repairItem(item, (err) => { this.printf('%s', err) }, () => { return this.io.readLine('Correct item? Y/N').then((result) => { return result.match(/y/i) != null; }); }); }; repairTasks.push(repairTask); }); return asyncutil.series(repairTasks); }); } /** Starts the command-line interface and returns * a promise for the exit code. */ exec(argv: string[]): Promise<number> { var args = this.createParser().parseArgs(argv); mkdirp.sync(this.configDir) var currentVault: agile_keychain.Vault; var vaultReady: Promise<void>; var requiresUnlockedVault = ['new-vault', 'gen-password'].indexOf(args.command) == -1; if (requiresUnlockedVault) { var vault = this.initVault(args.vault ? args.vault[0] : null); vaultReady = vault.then((vault) => { currentVault = vault; return this.unlockVault(vault); }); } else { vaultReady = Promise.resolve<void>(null); } var handlers: HandlerMap = {}; handlers['list'] = (args) => { return this.listCommand(currentVault, args.pattern ? args.pattern[0] : null); }; handlers['show'] = (args) => { var format: ShowItemFormat; switch (args.format[0]) { case 'full': format = ShowItemFormat.ShowFull; break; case 'overview': format = ShowItemFormat.ShowOverview; break; case 'json': format = ShowItemFormat.ShowJSON; break; default: return Promise.reject<void>(new Error('Unsupported output format: ' + args.format[0])); } return this.showItemCommand(currentVault, args.pattern, format); }; handlers['lock'] = (args) => { return currentVault.lock(); }; handlers['copy'] = (args) => { return this.copyItemCommand(currentVault, args.item, args.field); }; handlers['add'] = (args) => { return this.addItemCommand(currentVault, args.type, args.title); }; handlers['edit'] = (args) => { return this.selectItem(currentVault, args.item).then((item) => { return this.editCommand.handle(args, item); }); }; handlers['trash'] = (args) => { return this.trashItemCommand(currentVault, args.item, true); }; handlers['restore'] = (args) => { return this.trashItemCommand(currentVault, args.item, false); }; handlers['set-password'] = (args) => { return this.setPasswordCommand(currentVault, args.iterations); }; handlers['remove'] = (args) => { return this.removeCommand(currentVault, args.pattern); }; handlers['gen-password'] = (args) => { return this.genPasswordCommand(); }; handlers['new-vault'] = (args) => { return this.newVaultCommand(new nodefs.FileVFS('/'), args.path, args.iterations); } handlers['repair'] = (args) => { return this.repairCommand(currentVault); }; // process commands return vaultReady.then(() => { var handler = handlers[args.command]; if (handler) { return handler(args).then((result) => { if (typeof result == 'number') { // if the handler returns an exit status, use that return <number>result; } else { // otherwise assume success return 0; } }).catch((err) => { this.printf('%s', err); if (args.debug) { this.printf('%s', err.stack); } return 1; }); } else { this.printf('Unknown command: %s', args.command); return 1; } }).catch(err => { this.printf('Unlocking failed: %s', err.message); return 2; }); } }
the_stack
import { createLocalVue, mount, shallowMount, Wrapper } from '@vue/test-utils'; import Vuex, { Store } from 'vuex'; import AutocompleteWidget from '@/components/stepforms/widgets/Autocomplete.vue'; import FilterSimpleConditionWidget from '@/components/stepforms/widgets/FilterSimpleCondition.vue'; import InputTextWidget from '@/components/stepforms/widgets/InputText.vue'; import MultiInputTextWidget from '@/components/stepforms/widgets/MultiInputText.vue'; import { RootState, setupMockStore } from './utils'; const localVue = createLocalVue(); localVue.use(Vuex); describe('Widget FilterSimpleCondition', () => { let emptyStore: Store<RootState>; beforeEach(() => { emptyStore = setupMockStore({}); }); it('should instantiate', () => { const wrapper = shallowMount(FilterSimpleConditionWidget, { store: emptyStore, localVue }); expect(wrapper.exists()).toBeTruthy(); }); it('should have exactly 3 input components', () => { const wrapper = shallowMount(FilterSimpleConditionWidget, { store: emptyStore, localVue }); const autocompleteWrappers = wrapper.findAll('autocompletewidget-stub'); expect(autocompleteWrappers.length).toEqual(2); const inputtextWrappers = wrapper.findAll('inputtextwidget-stub'); expect(inputtextWrappers.length).toEqual(1); }); it('should have exactly have a MultiInputTextWidget if operator is "in" or "nin"', async () => { const wrapper = shallowMount(FilterSimpleConditionWidget, { store: emptyStore, localVue, propsData: { value: { column: 'foo', value: [], operator: 'in' }, }, sync: false, }); const autocompleteWrappers = wrapper.findAll('multiinputtextwidget-stub'); expect(autocompleteWrappers.length).toEqual(1); }); it('should not have any input component if operator is "isnull" or "not null"', async () => { const wrapper = shallowMount(FilterSimpleConditionWidget, { store: emptyStore, localVue, propsData: { value: { column: 'foo', value: [], operator: 'isnull' }, }, sync: false, }); const inputTextWrappers = wrapper.find('inputtextwidget-stub'); const multinnputtextWrappers = wrapper.find('multiinputtextwidget-stub'); expect(inputTextWrappers.exists()).toBeFalsy(); expect(multinnputtextWrappers.exists()).toBeFalsy(); }); it('should instantiate a widgetAutocomplete widget with column names from the store', () => { const store = setupMockStore({ dataset: { headers: [{ name: 'columnA' }, { name: 'columnB' }, { name: 'columnC' }], data: [], }, }); const wrapper = shallowMount(FilterSimpleConditionWidget, { store, localVue }); const widgetWrappers = wrapper.findAll('autocompletewidget-stub'); expect(widgetWrappers.at(0).attributes('options')).toEqual('columnA,columnB,columnC'); }); it('should instantiate a widgetAutocomplete widget with column names from the prop', () => { const wrapper = shallowMount(FilterSimpleConditionWidget, { store: emptyStore, localVue, propsData: { columnNamesProp: ['columnA', 'columnB', 'columnC'], }, }); const widgetWrappers = wrapper.findAll('autocompletewidget-stub'); expect(widgetWrappers.at(0).attributes('options')).toEqual('columnA,columnB,columnC'); }); it('should instantiate a widgetAutocomplete widget with nothing', () => { const wrapper = shallowMount(FilterSimpleConditionWidget, { store: emptyStore, localVue, }); const widgetWrappers = wrapper.findAll('autocompletewidget-stub'); expect(widgetWrappers.at(0).attributes('options')).toEqual(''); }); it('should pass down the "column" prop to the first AutocompleteWidget value prop', async () => { const wrapper = shallowMount(FilterSimpleConditionWidget, { store: emptyStore, localVue, propsData: { value: { column: 'foo', value: '', operator: 'eq' }, }, sync: false, }); const widgetWrappers = wrapper.findAll('autocompletewidget-stub'); expect(widgetWrappers.at(0).props().value).toEqual('foo'); }); it('should pass down the "operator" prop to the second AutocompleteWidget value prop', async () => { const wrapper = shallowMount(FilterSimpleConditionWidget, { store: emptyStore, localVue, propsData: { value: { column: 'foo', value: [], operator: 'nin' }, }, sync: false, }); const widgetWrappers = wrapper.findAll('autocompletewidget-stub'); expect(widgetWrappers.at(1).props().value).toEqual({ operator: 'nin', label: 'is not one of', inputWidget: MultiInputTextWidget, }); }); it('should emit a new condition with the correct type of value when changing the operator', () => { const wrapper = shallowMount(FilterSimpleConditionWidget, { store: emptyStore, localVue, propsData: { dataPath: '.condition' }, sync: false, }); // default emitted value expect(wrapper.emitted().input[0]).toEqual([{ column: '', value: '', operator: 'eq' }]); const operatorWrapper = wrapper.findAll('autocompletewidget-stub').at(1); // in operator operatorWrapper.vm.$emit('input', { operator: 'in' }); expect(wrapper.emitted().input[1]).toEqual([{ column: '', value: [], operator: 'in' }]); // isnull operator operatorWrapper.vm.$emit('input', { operator: 'isnull' }); expect(wrapper.emitted().input[2]).toEqual([{ column: '', value: null, operator: 'isnull' }]); // matches operator operatorWrapper.vm.$emit('input', { operator: 'matches' }); expect(wrapper.emitted().input[3]).toEqual([{ column: '', value: '', operator: 'matches' }]); }); it('should the widget accordingly when changing the operator', async () => { const wrapper = shallowMount(FilterSimpleConditionWidget, { store: emptyStore, localVue, propsData: { dataPath: '.condition' }, sync: false, }); expect(wrapper.emitted().input[0]).toEqual([{ column: '', value: '', operator: 'eq' }]); // in operator wrapper.setProps({ value: { column: '', value: [], operator: 'in' }, }); await wrapper.vm.$nextTick(); let valueInputWrapper = wrapper.find('.filterValue'); expect(valueInputWrapper.is(MultiInputTextWidget)).toBe(true); expect(valueInputWrapper.attributes('placeholder')).toEqual('Enter a value'); // isnull operator wrapper.setProps({ value: { column: '', value: null, operator: 'isnull' }, }); await wrapper.vm.$nextTick(); valueInputWrapper = wrapper.find('.filterValue'); expect(valueInputWrapper.exists()).toBeFalsy(); // matches operator wrapper.setProps({ value: { column: '', value: '', operator: 'matches' }, }); await wrapper.vm.$nextTick(); valueInputWrapper = wrapper.find('.filterValue'); expect(valueInputWrapper.is(InputTextWidget)).toBe(true); expect(valueInputWrapper.attributes('placeholder')).toEqual('Enter a regex, e.g. "[Ss]ales"'); }); it('should emit input when changing the column', async () => { const wrapper = shallowMount(FilterSimpleConditionWidget, { store: emptyStore, localVue, propsData: { dataPath: '.condition' }, sync: false, }); expect(wrapper.emitted().input[0]).toEqual([{ column: '', value: '', operator: 'eq' }]); const columnInputWrapper = wrapper.findAll('autocompletewidget-stub').at(0); columnInputWrapper.vm.$emit('input', 'foo'); await wrapper.vm.$nextTick(); expect(wrapper.emitted().input[1]).toEqual([{ column: 'foo', value: '', operator: 'eq' }]); }); it('should emit input when changing the value', async () => { const wrapper = shallowMount(FilterSimpleConditionWidget, { store: emptyStore, localVue, propsData: { dataPath: '.condition' }, sync: false, }); expect(wrapper.emitted().input[0]).toEqual([{ column: '', value: '', operator: 'eq' }]); const valueInputWrapper = wrapper.find('.filterValue'); valueInputWrapper.vm.$emit('input', 'toto'); await wrapper.vm.$nextTick(); expect(wrapper.emitted().input[1]).toEqual([{ column: '', value: 'toto', operator: 'eq' }]); }); it('should update selectedColumn when column is changed', async () => { const store = setupMockStore({ dataset: { headers: [{ name: 'columnA' }, { name: 'columnB' }, { name: 'columnC' }], data: [], }, selectedColumns: ['columnA'], }); const wrapper = mount(FilterSimpleConditionWidget, { propsData: { value: { column: 'columnA', value: 'bar', operator: 'eq' }, }, store, localVue, sync: false, }); wrapper.find(AutocompleteWidget).vm.$emit('input', 'columnB'); await wrapper.vm.$nextTick(); expect(store.state.vqb.selectedColumns).toEqual(['columnB']); }); it('should keep value when operator is changed and types match', async () => { const store = setupMockStore({ dataset: { headers: [{ name: 'columnA' }, { name: 'columnB' }, { name: 'columnC' }], data: [], }, selectedColumns: ['columnA'], }); const wrapper = mount(FilterSimpleConditionWidget, { propsData: { value: { column: 'columnA', value: 'bar', operator: 'eq' }, }, store, localVue, sync: false, }); wrapper.find('.filterOperator').vm.$emit('input', { operator: 'ne' }); await wrapper.vm.$nextTick(); expect(wrapper.emitted().input[0]).toEqual([ { column: 'columnA', value: 'bar', operator: 'ne' }, ]); }); it("should replace value with default when operator is changed and types don't match", async () => { const store = setupMockStore({ dataset: { headers: [{ name: 'columnA' }, { name: 'columnB' }, { name: 'columnC' }], data: [], }, selectedColumns: ['columnA'], }); const wrapper = mount(FilterSimpleConditionWidget, { propsData: { value: { column: 'columnA', value: 'bar', operator: 'eq' }, }, store, localVue, sync: false, }); wrapper.find('.filterOperator').vm.$emit('input', { operator: 'in' }); await wrapper.vm.$nextTick(); expect(wrapper.emitted().input[0]).toEqual([{ column: 'columnA', value: [], operator: 'in' }]); }); describe('date column and date', () => { let wrapper: Wrapper<FilterSimpleConditionWidget>; const createWrapper = (mountType: Function, customProps: any = {}) => { const store = setupMockStore({ dataset: { headers: [{ name: 'columnA' }, { name: 'columnB' }, { name: 'columnC' }], data: [], }, selectedColumns: ['columnA'], }); wrapper = mountType(FilterSimpleConditionWidget, { propsData: { value: { column: 'columnA', value: new Date('2021-01-01'), operator: 'eq' }, columnTypes: { columnA: 'date' }, ...customProps, }, store, localVue, sync: false, }); }; it('should use the date input', () => { createWrapper(mount); const widgetWrappers = wrapper.findAll('.filterValue'); expect(widgetWrappers.at(0).classes()).toContain('widget-input-date__container'); }); it('should emit a new condition with the correct type of value when changing the operator', () => { createWrapper(shallowMount); const operatorWrapper = wrapper.findAll('autocompletewidget-stub').at(1); // ne operator operatorWrapper.vm.$emit('input', { operator: 'ne' }); expect(wrapper.emitted().input[0]).toEqual([ { column: 'columnA', value: new Date('2021-01-01'), operator: 'ne' }, ]); // eq operator operatorWrapper.vm.$emit('input', { operator: 'eq' }); expect(wrapper.emitted().input[1]).toEqual([ { column: 'columnA', value: new Date('2021-01-01'), operator: 'eq' }, ]); // in operator operatorWrapper.vm.$emit('input', { operator: 'in' }); expect(wrapper.emitted().input[2]).toEqual([ { column: 'columnA', value: [], operator: 'in' }, ]); // isnull operator operatorWrapper.vm.$emit('input', { operator: 'isnull' }); expect(wrapper.emitted().input[3]).toEqual([ { column: 'columnA', value: null, operator: 'isnull' }, ]); }); it('should transform invalid dates to valid date when changing the operator', () => { createWrapper(shallowMount, { value: { column: 'columnA', value: 1, operator: 'matches' }, }); const operatorWrapper = wrapper.findAll('autocompletewidget-stub').at(1); // eq operator operatorWrapper.vm.$emit('input', { operator: 'eq' }); expect(wrapper.emitted().input[0]).toEqual([ { column: 'columnA', value: null, operator: 'eq' }, ]); }); it('should transform invalid dates to valid date when changing the column type', async () => { createWrapper(shallowMount, { value: { column: 'columnA', value: new Date('2021-01-01'), operator: 'eq' }, }); wrapper.setProps({ columnTypes: { columnA: 'string' } }); await wrapper.vm.$nextTick(); // relaunch operator validation automatically when changing the column type expect(wrapper.emitted().input[0]).toEqual([ { column: 'columnA', value: '', operator: 'eq' }, ]); }); it('should not pass the variables props if hideColumnVariables is true', () => { const customProps = { availableVariables: ['test'], variableDelimiters: ['test'], hideColumnVariables: true, }; createWrapper(mount, customProps); const widgetWrappers = wrapper.findAll('.columnInput'); const props = widgetWrappers.at(0).props(); expect(props.availableVariables).toBe(undefined); expect(props.variableDelimiters).toBe(undefined); }); }); });
the_stack
import { IEntityAnnotationObject } from "./IEntityAnnotationObject"; import { ITextIntentSequenceLabelObjectByPosition} from "./ITextIntentSequenceLabelObjectByPosition"; import { Data } from "./Data"; import { Utility } from "../utility/Utility"; export class EntityAnnotatedCorpusData extends Data { public static createEntityAnnotatedCorpusDataFromSamplingExistingEntityAnnotatedCorpusDataUtterances( existingEntityAnnotatedCorpusData: EntityAnnotatedCorpusData, linesToSkip: number, samplingIndexArray: number[]): EntityAnnotatedCorpusData { // ------------------------------------------------------------------- const entityAnnotatedCorpusData: EntityAnnotatedCorpusData = EntityAnnotatedCorpusData.createEntityAnnotatedCorpusData( existingEntityAnnotatedCorpusData.getContent(), linesToSkip); // ------------------------------------------------------------------- const luUtterances: ITextIntentSequenceLabelObjectByPosition[] = entityAnnotatedCorpusData.luUtterances; const lengthUtterancesArray: number = luUtterances.length; entityAnnotatedCorpusData.luUtterances = []; for (const index of samplingIndexArray) { if ((index < 0) || (index > lengthUtterancesArray)) { Utility.debuggingThrow(`(index|${index}|<0)||(index|${index}|>lengthUtterancesArray|${lengthUtterancesArray}|)`); } entityAnnotatedCorpusData.luUtterances.push(luUtterances[index]); } // ------------------------------------------------------------------- entityAnnotatedCorpusData.intentInstanceIndexMapArray = entityAnnotatedCorpusData.collectIntents(entityAnnotatedCorpusData.luUtterances); entityAnnotatedCorpusData.entityTypeInstanceIndexMapArray = entityAnnotatedCorpusData.collectEntityTypes(entityAnnotatedCorpusData.luUtterances); entityAnnotatedCorpusData.intentsUtterancesWeights.intents = entityAnnotatedCorpusData.luUtterances.map( (entry: ITextIntentSequenceLabelObjectByPosition) => entry.intent); entityAnnotatedCorpusData.intentsUtterancesWeights.utterances = entityAnnotatedCorpusData.luUtterances.map( (entry: ITextIntentSequenceLabelObjectByPosition) => entry.text); entityAnnotatedCorpusData.intentsUtterancesWeights.weights = entityAnnotatedCorpusData.luUtterances.map( (entry: ITextIntentSequenceLabelObjectByPosition) => entry.weight); // ------------------------------------------------------------------- return entityAnnotatedCorpusData; } public static createEntityAnnotatedCorpusDataFromFilteringExistingEntityAnnotatedCorpusDataUtterances( existingEntityAnnotatedCorpusData: EntityAnnotatedCorpusData, linesToSkip: number, filteringIndexSet: Set<number>): EntityAnnotatedCorpusData { // ------------------------------------------------------------------- const entityAnnotatedCorpusData: EntityAnnotatedCorpusData = EntityAnnotatedCorpusData.createEntityAnnotatedCorpusData( existingEntityAnnotatedCorpusData.getContent(), linesToSkip); // ------------------------------------------------------------------- const luUtterances: ITextIntentSequenceLabelObjectByPosition[] = entityAnnotatedCorpusData.luUtterances; entityAnnotatedCorpusData.luUtterances = luUtterances.filter( (value: ITextIntentSequenceLabelObjectByPosition, index: number, array: ITextIntentSequenceLabelObjectByPosition[]) => { return (filteringIndexSet.has(index)); }); // ------------------------------------------------------------------- entityAnnotatedCorpusData.intentInstanceIndexMapArray = entityAnnotatedCorpusData.collectIntents(entityAnnotatedCorpusData.luUtterances); entityAnnotatedCorpusData.entityTypeInstanceIndexMapArray = entityAnnotatedCorpusData.collectEntityTypes(entityAnnotatedCorpusData.luUtterances); entityAnnotatedCorpusData.intentsUtterancesWeights.intents = entityAnnotatedCorpusData.luUtterances.map( (entry: ITextIntentSequenceLabelObjectByPosition) => entry.intent); entityAnnotatedCorpusData.intentsUtterancesWeights.utterances = entityAnnotatedCorpusData.luUtterances.map( (entry: ITextIntentSequenceLabelObjectByPosition) => entry.text); entityAnnotatedCorpusData.intentsUtterancesWeights.weights = entityAnnotatedCorpusData.luUtterances.map( (entry: ITextIntentSequenceLabelObjectByPosition) => entry.weight); // ------------------------------------------------------------------- return entityAnnotatedCorpusData; } public static createEntityAnnotatedCorpusData( content: string, linesToSkip: number): EntityAnnotatedCorpusData { // ------------------------------------------------------------------- const entityAnnotatedCorpusData: EntityAnnotatedCorpusData = new EntityAnnotatedCorpusData( linesToSkip); entityAnnotatedCorpusData.content = content; // ------------------------------------------------------------------- entityAnnotatedCorpusData.luUtterances = entityAnnotatedCorpusData.retrieveEntityAnnotatedCorpusUtterances( content); // ------------------------------------------------------------------- entityAnnotatedCorpusData.intentInstanceIndexMapArray = entityAnnotatedCorpusData.collectIntents(entityAnnotatedCorpusData.luUtterances); entityAnnotatedCorpusData.entityTypeInstanceIndexMapArray = entityAnnotatedCorpusData.collectEntityTypes(entityAnnotatedCorpusData.luUtterances); entityAnnotatedCorpusData.intentsUtterancesWeights.intents = entityAnnotatedCorpusData.luUtterances.map( (entry: ITextIntentSequenceLabelObjectByPosition) => entry.intent); entityAnnotatedCorpusData.intentsUtterancesWeights.utterances = entityAnnotatedCorpusData.luUtterances.map( (entry: ITextIntentSequenceLabelObjectByPosition) => entry.text); entityAnnotatedCorpusData.intentsUtterancesWeights.weights = entityAnnotatedCorpusData.luUtterances.map( (entry: ITextIntentSequenceLabelObjectByPosition) => entry.weight); // ------------------------------------------------------------------- return entityAnnotatedCorpusData; } protected linesToSkip: number = 0; protected constructor( linesToSkip: number = 0) { super(); this.linesToSkip = linesToSkip; } public async createDataFromSamplingExistingDataUtterances( existingData: Data, labelColumnIndex: number, textColumnIndex: number, weightColumnIndex: number, linesToSkip: number, samplingIndexArray: number[], toResetFeaturizerLabelFeatureMaps: boolean): Promise<Data> { if (!(existingData instanceof EntityAnnotatedCorpusData)) { Utility.debuggingThrow("logic error: the input Data object should be a EntityAnnotatedCorpusData object."); } // tslint:disable-next-line: max-line-length return EntityAnnotatedCorpusData.createEntityAnnotatedCorpusDataFromSamplingExistingEntityAnnotatedCorpusDataUtterances( existingData as EntityAnnotatedCorpusData, linesToSkip, samplingIndexArray); } public async createDataFromFilteringExistingDataUtterances( existingData: Data, labelColumnIndex: number, textColumnIndex: number, weightColumnIndex: number, linesToSkip: number, filteringIndexSet: Set<number>, toResetFeaturizerLabelFeatureMaps: boolean): Promise<Data> { if (!(existingData instanceof EntityAnnotatedCorpusData)) { Utility.debuggingThrow("logic error: the input Data object should be a EntityAnnotatedCorpusData object."); } // tslint:disable-next-line: max-line-length return EntityAnnotatedCorpusData.createEntityAnnotatedCorpusDataFromFilteringExistingEntityAnnotatedCorpusDataUtterances( existingData as EntityAnnotatedCorpusData, linesToSkip, filteringIndexSet); } public retrieveEntityAnnotatedCorpusUtterances( // ---- NOTE ---- the return is newly allocated, unlike the one in LuData content: string, includePartOfSpeechTagTagAsEntities: boolean = true, utteranceReconstructionDelimiter: string = " ", defaultEntityTag: string = "O", useIdForIntent: boolean = true): ITextIntentSequenceLabelObjectByPosition[] { const entityAnnotatedCorpusTypes: IEntityAnnotationObject = Utility.loadEntityAnnotatedCorpusContent( content, // ---- filename: string, this.getLinesToSkip(), // ---- lineIndexToStart: number = 0, ",", // ---- columnDelimiter: string = ",", "\n", // ---- rowDelimiter: string = "\n", -1, // ---- lineIndexToEnd: number = -1 ); const entityAnnotatedCorpusUtterances: ITextIntentSequenceLabelObjectByPosition[] = Utility.entityAnnotatedCorpusTypesToEntityAnnotatedCorpusUtterances( entityAnnotatedCorpusTypes, includePartOfSpeechTagTagAsEntities, utteranceReconstructionDelimiter, defaultEntityTag, useIdForIntent); return entityAnnotatedCorpusUtterances; } public getLuObject(): any { // ---- NOTE: can be overriden by a child class. throw new Error("Logical error as it's not implemented for a " + "EntityAnnotatedCorpusData object to generate a LU object."); } public getLuLuisJsonStructure(): any { // ---- NOTE: can be overriden by a child class. throw new Error("Logical error as it's not implemented for a " + "EntityAnnotatedCorpusData object to generate a LUIS JSON object."); } public getLuQnaJsonStructure(): any { // ---- NOTE: can be overriden by a child class. throw new Error("Logical error as it's not implemented for a " + "EntityAnnotatedCorpusData object to generate a QnA JSON object."); } public getLuQnaAlterationsJsonStructure(): any { // ---- NOTE: can be overriden by a child class. throw new Error("Logical error as it's not implemented for a " + "EntityAnnotatedCorpusData to generate a QnA Alterations JSON object."); } public getLinesToSkip(): number { return this.linesToSkip; } }
the_stack
import { expect } from "chai"; import { TestConfig } from "./TestConfig"; import RandomGenerator from "./mocks/RandomGenerator"; import { SkuType, DeveloperNotification, NotificationType } from "../../src/play-billing"; const testConfig = TestConfig.getInstance(); const playBilling = testConfig.playBilling; const apiClientMock = testConfig.playApiClientMock; const packageName = 'somePackageName'; const sku = 'someSubsSku' describe('Register a purchase with an user account, then waits for it to auto-renew', () => { let randomUserId: string; let randomPurchaseToken: string; let expiryTimeOfRenewedPurchase: number; let now: number; beforeEach(async () => { // Assume a brand new purchase, avoid conflict by using random orderId and purchaseToken now = Date.now(); const startTimeOfOriginalPurchase = now - 100000; const expiryTimeOfOriginalPurchase = now + 100000; const newPurchasePlayApiResponse: any = { kind: "androidpublisher#subscriptionPurchase", startTimeMillis: startTimeOfOriginalPurchase, expiryTimeMillis: expiryTimeOfOriginalPurchase, autoRenewing: true, priceCurrencyCode: "JPY", priceAmountMicros: "99000000", countryCode: "JP", developerPayload: "", orderId: RandomGenerator.generateRandomOrderId() }; apiClientMock.mockResponse(newPurchasePlayApiResponse); randomUserId = 'userId' + RandomGenerator.generateUniqueIdFromTimestamp(); randomPurchaseToken = "token" + RandomGenerator.generateUniqueIdFromTimestamp(); // Register the purchase to the user await playBilling.purchases().registerToUserAccount( packageName, sku, randomPurchaseToken, SkuType.SUBS, randomUserId ); // Fast forward to after the original purchase has expired testConfig.dateMock.mockCurrentTimestamp(expiryTimeOfOriginalPurchase + 100000); const renewedPurchasePlayApiResponse = Object.assign({}, newPurchasePlayApiResponse); expiryTimeOfRenewedPurchase = expiryTimeOfOriginalPurchase + 200000; renewedPurchasePlayApiResponse.orderId = newPurchasePlayApiResponse.orderId + '..1'; renewedPurchasePlayApiResponse.expiryTimeMillis = expiryTimeOfRenewedPurchase; apiClientMock.mockResponse(renewedPurchasePlayApiResponse); }); const expectPurchaseRecordHasBeenUpdated = async () => { // Query subscriptions that has been registered to the user const purchaseList = await playBilling.users().queryCurrentSubscriptions(randomUserId, sku, packageName); expect(purchaseList.length, 'the user has only one subscription registered to himself').to.equal(1); expect(purchaseList[0].purchaseToken, 'the purchase match the one we registered earlier').to.equal(randomPurchaseToken); expect(purchaseList[0].isEntitlementActive(), 'the subscription is active').to.equal(true); expect(purchaseList[0].expiryTimeMillis, 'the subscription is renewed').to.equal(expiryTimeOfRenewedPurchase); }; it('then our library should properly handle subscription renewal notification and update the purchase record', async () => { /// Mock receiving a Realtime Developer notification const renewalNotification: DeveloperNotification = { version: '1.0', packageName: 'string', eventTimeMillis: now, subscriptionNotification: { version: '1.0', notificationType: NotificationType.SUBSCRIPTION_RENEWED, purchaseToken: randomPurchaseToken, subscriptionId: sku } } await playBilling.purchases().processDeveloperNotification(packageName, renewalNotification); // Test if our purchase record has been properly updated await expectPurchaseRecordHasBeenUpdated(); }); it('and our library should still find out and update purchase records without the renewal notification', async () => { // Test if our purchase record has been properly updated await expectPurchaseRecordHasBeenUpdated(); }); afterEach(() => testConfig.dateMock.reset()); }); describe('Register a purchase with an user account, then waits for it to expire', () => { let randomUserId: string; let randomPurchaseToken: string; let now: number; beforeEach(async () => { // Assume a brand new purchase, avoid conflict by using random orderId and purchaseToken now = Date.now(); const startTimeOfOriginalPurchase = now - 100000; const expiryTimeOfOriginalPurchase = now + 100000; const newPurchasePlayApiResponse: any = { kind: "androidpublisher#subscriptionPurchase", startTimeMillis: startTimeOfOriginalPurchase, expiryTimeMillis: expiryTimeOfOriginalPurchase, autoRenewing: true, priceCurrencyCode: "JPY", priceAmountMicros: "99000000", countryCode: "JP", developerPayload: "", orderId: RandomGenerator.generateRandomOrderId() }; apiClientMock.mockResponse(newPurchasePlayApiResponse); randomUserId = 'userId' + RandomGenerator.generateUniqueIdFromTimestamp(); randomPurchaseToken = "token" + RandomGenerator.generateUniqueIdFromTimestamp(); // Register the purchase to the user await playBilling.purchases().registerToUserAccount( packageName, sku, randomPurchaseToken, SkuType.SUBS, randomUserId ); // Fast forward to after the original purchase has expired testConfig.dateMock.mockCurrentTimestamp(expiryTimeOfOriginalPurchase + 100000); const expiredPurchasePlayApiResponse = Object.assign({}, newPurchasePlayApiResponse); expiredPurchasePlayApiResponse.autoRenewing = false; expiredPurchasePlayApiResponse.cancelReason = '0'; expiredPurchasePlayApiResponse.userCancellationTimeMillis = now; apiClientMock.mockResponse(expiredPurchasePlayApiResponse); }); const expectPurchaseRecordHasExpired = async () => { // Query subscriptions that has been registered to the user const purchaseList = await playBilling.users().queryCurrentSubscriptions(randomUserId, sku, packageName); expect(purchaseList.length, 'the user no longer has any active subscription registered to himself').to.equal(0); }; it('then our library should properly handle subscription cancel notification and update the purchase record', async () => { /// Mock receiving a Realtime Developer notification const cancelNotification: DeveloperNotification = { version: '1.0', packageName: 'string', eventTimeMillis: now, subscriptionNotification: { version: '1.0', notificationType: NotificationType.SUBSCRIPTION_CANCELED, purchaseToken: randomPurchaseToken, subscriptionId: sku } } await playBilling.purchases().processDeveloperNotification(packageName, cancelNotification); // Test if our purchase record has been properly updated await expectPurchaseRecordHasExpired(); }); it('and our library should still find out and update purchase records without the cancel notification', async () => { // Test if our purchase record has been properly updated await expectPurchaseRecordHasExpired(); }); afterEach(() => testConfig.dateMock.reset()); }); describe('Register a purchase with an user account, then cancel it and then restore', () => { let randomUserId: string; let randomPurchaseToken: string; let expiryTimeOfRenewedPurchase: number; let expiryTimeOfOriginalPurchase: number; let startTimeOfOriginalPurchase: number; let newPurchasePlayApiResponse: any; let now: number; beforeEach(async () => { // Assume a brand new purchase, avoid conflict by using random orderId and purchaseToken now = Date.now(); startTimeOfOriginalPurchase = now - 100000; expiryTimeOfOriginalPurchase = now + 100000; newPurchasePlayApiResponse = { kind: "androidpublisher#subscriptionPurchase", startTimeMillis: startTimeOfOriginalPurchase, expiryTimeMillis: expiryTimeOfOriginalPurchase, autoRenewing: true, priceCurrencyCode: "JPY", priceAmountMicros: "99000000", countryCode: "JP", developerPayload: "", orderId: RandomGenerator.generateRandomOrderId() }; apiClientMock.mockResponse(newPurchasePlayApiResponse); randomUserId = 'userId' + RandomGenerator.generateUniqueIdFromTimestamp(); randomPurchaseToken = "token" + RandomGenerator.generateUniqueIdFromTimestamp(); // Register the purchase to the user await playBilling.purchases().registerToUserAccount( packageName, sku, randomPurchaseToken, SkuType.SUBS, randomUserId ); }); const simulatePurchaseCancellation = () => { const cancelledPurchasePlayApiResponse = Object.assign({}, newPurchasePlayApiResponse); cancelledPurchasePlayApiResponse.autoRenewing = false; cancelledPurchasePlayApiResponse.cancelReason = '0'; cancelledPurchasePlayApiResponse.userCancellationTimeMillis = now + 1000; apiClientMock.mockResponse(cancelledPurchasePlayApiResponse); } const simulatePurchaseRestoration = () => { const restoredPurchasePlayApiResponse = Object.assign({}, newPurchasePlayApiResponse); apiClientMock.mockResponse(restoredPurchasePlayApiResponse); } const fastForwardToAfterPurchaseRenewal = () => { // Fast forward to after the original purchase has expired testConfig.dateMock.mockCurrentTimestamp(expiryTimeOfOriginalPurchase + 100000); const renewedPurchasePlayApiResponse = Object.assign({}, newPurchasePlayApiResponse); expiryTimeOfRenewedPurchase = expiryTimeOfOriginalPurchase + 200000; renewedPurchasePlayApiResponse.orderId = newPurchasePlayApiResponse.orderId + '..1'; renewedPurchasePlayApiResponse.expiryTimeMillis = expiryTimeOfRenewedPurchase; apiClientMock.mockResponse(renewedPurchasePlayApiResponse); } const expectSubscriptionIsStillActive = async () => { // Query subscriptions that has been registered to the user const purchaseList = await playBilling.users().queryCurrentSubscriptions(randomUserId, sku, packageName); expect(purchaseList.length, 'the user has only one subscription registered to himself').to.equal(1); expect(purchaseList[0].purchaseToken, 'the purchase match the one we registered earlier').to.equal(randomPurchaseToken); expect(purchaseList[0].isEntitlementActive(), 'the subscription is active').to.equal(true); expect(purchaseList[0].expiryTimeMillis, 'the subscription is renewed').to.equal(expiryTimeOfRenewedPurchase); }; it('then our library should handle cancel notification and renewal notification, then update the purchase record', async () => { simulatePurchaseCancellation(); /// Mock receiving a Realtime Developer notification - cancel notification const cancelNotification: DeveloperNotification = { version: '1.0', packageName: 'string', eventTimeMillis: now + 1000, subscriptionNotification: { version: '1.0', notificationType: NotificationType.SUBSCRIPTION_CANCELED, purchaseToken: randomPurchaseToken, subscriptionId: sku } } await playBilling.purchases().processDeveloperNotification(packageName, cancelNotification); simulatePurchaseRestoration(); /// Mock receiving a Realtime Developer notification - cancel notification const restoreNotification: DeveloperNotification = { version: '1.0', packageName: 'string', eventTimeMillis: now + 1000, subscriptionNotification: { version: '1.0', notificationType: NotificationType.SUBSCRIPTION_RESTARTED, purchaseToken: randomPurchaseToken, subscriptionId: sku } } await playBilling.purchases().processDeveloperNotification(packageName, restoreNotification); fastForwardToAfterPurchaseRenewal(); /// Mock receiving a Realtime Developer notification const renewalNotification: DeveloperNotification = { version: '1.0', packageName: 'string', eventTimeMillis: expiryTimeOfOriginalPurchase, subscriptionNotification: { version: '1.0', notificationType: NotificationType.SUBSCRIPTION_RENEWED, purchaseToken: randomPurchaseToken, subscriptionId: sku } } await playBilling.purchases().processDeveloperNotification(packageName, renewalNotification); // Test if our purchase record has been properly updated await expectSubscriptionIsStillActive(); }); it('and our library should still find out that the subscription is renewed without all the notifications', async () => { simulatePurchaseCancellation(); simulatePurchaseRestoration(); fastForwardToAfterPurchaseRenewal(); // Test if our purchase record has been properly updated await expectSubscriptionIsStillActive(); }); afterEach(() => testConfig.dateMock.reset()); });
the_stack
import { ComponentFixture, TestBed } from '@angular/core/testing'; import { DebugElement } from '@angular/core'; import { ComponentBase } from '../src/component-base'; import { ControlComponents } from './control.component'; import { AppComponent } from './app.module'; import { pipeComponents } from './pipe.component'; import { check } from './app.pipe'; /** * Complex Spec */ jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; describe('=> Complex Component => ', () => { let comp: AppComponent; let fixture: ComponentFixture<AppComponent>; let de: DebugElement; let el: HTMLElement; let directives: any[] = ControlComponents; directives.push(AppComponent); beforeEach((done) => { TestBed.configureTestingModule({ declarations: directives, providers: [ComponentBase] }); /* tslint:disable */ TestBed.overrideComponent(AppComponent, { set: { template: `<ej2-control> <e-childs> <e-child [text]='child1.text' [header]='child1.header' ></e-child> <e-child [text]='child2.text' [header]='child2.header' ></e-child> <e-child [text]='child3.text' [header]='child3.header' ></e-child> </e-childs> </ej2-control>` } }); /* tslint:enable */ TestBed.compileComponents().then(() => { fixture = TestBed.createComponent(AppComponent); comp = fixture.componentInstance; de = fixture.debugElement; el = de.nativeElement; fixture.detectChanges(); setTimeout(() => { done(); }, 100); }); }); it('complex data processing', () => { let instance: any = (el.querySelector('.e-control') as any).ej2_instances[0]; expect(JSON.stringify(instance.childs[0].properties)).toEqual('{"header":true,"text":"Child1","subChilds":[]}'); expect(JSON.stringify(instance.childs[1].properties)).toEqual('{"header":false,"text":"Child2","subChilds":[]}'); }); it('complex data binding', (done: Function) => { comp.child2 = { text: 'ChangedChild', header: true }; fixture.detectChanges(); setTimeout(() => { let instance: any = (el.querySelector('.e-control') as any).ej2_instances[0]; expect(JSON.stringify(instance.childs[0].properties)).toEqual('{"header":true,"text":"Child1","subChilds":[]}'); expect(JSON.stringify(instance.childs[1].properties)).toEqual('{"header":true,"text":"ChangedChild","subChilds":[]}'); done(); }, 100); }); afterAll(() => { el.remove(); }); }); describe('=> Complex Component for pipe => ', () => { let comp: AppComponent; let fixture: ComponentFixture<AppComponent>; let de: DebugElement; let el: HTMLElement; let directives: any[] = pipeComponents; directives.push(AppComponent); beforeEach((done) => { TestBed.configureTestingModule({ declarations: [directives, check], providers: [ComponentBase] }); /* tslint:disable */ TestBed.overrideComponent(AppComponent, { set: { template: `<ej2-control> <e-childs> <e-child [text]='child1.text' header='{{ child1.header | check }}' ></e-child> <e-child [text]='child2.text' [header]='child2.header' ></e-child> <e-child [text]='child3.text' [header]='child3.header' ></e-child> </e-childs> </ej2-control>` } }); /* tslint:enable */ TestBed.compileComponents().then(() => { fixture = TestBed.createComponent(AppComponent); comp = fixture.componentInstance; de = fixture.debugElement; el = de.nativeElement; fixture.detectChanges(); setTimeout(() => { done(); }, 100); }); }); it('complex data binding with pipe', (done: Function) => { fixture.detectChanges(); setTimeout(() => { let instance: any = (el.querySelector('.e-control') as any).ej2_instances[0]; expect(JSON.stringify(instance.childs[0].properties.header)).toEqual('"false"'); done(); }, 100); }); afterAll(() => { el.remove(); }); }); describe('=> Complex Component => ', () => { let comp: AppComponent; let fixture: ComponentFixture<AppComponent>; let de: DebugElement; let el: HTMLElement; let directives: any[] = ControlComponents; directives.push(AppComponent); beforeEach((done) => { TestBed.configureTestingModule({ declarations: directives, providers: [ComponentBase] }); /* tslint:disable */ TestBed.overrideComponent(AppComponent, { set: { template: `<ej2-control> <e-childs> <e-child [text]='child1.text' [header]=true > <e-sub-childs> <e-sub-child text='SubChild1' [header]=true ></e-sub-child> <e-sub-child text='SubChild2' [header]=true ></e-sub-child> <e-sub-child text='SubChild3' [header]=true ></e-sub-child> </e-sub-childs> </e-child> <e-child [text]='child2.text' [header]=false ></e-child> <e-child [text]='child3.text' [header]=true ></e-child> </e-childs> </ej2-control>` } }); /* tslint:enable */ TestBed.compileComponents().then(() => { fixture = TestBed.createComponent(AppComponent); comp = fixture.componentInstance; de = fixture.debugElement; el = de.nativeElement; fixture.detectChanges(); setTimeout(() => { done(); }, 1000); }); }); it('complex data 2 level processing', () => { let instance: any = (el.querySelector('.e-control') as any).ej2_instances[0]; expect(JSON.stringify(instance.childs[0], (key: string, value: Object) => { return instance.getActualProperties(value); })).toEqual( '{"header":true,"text":"Child1","subChilds":[{"header":true,"text":"SubChild1"},' + '{"header":true,"text":"SubChild2"},{"header":true,"text":"SubChild3"}]}' ); }); afterAll(() => { el.remove(); }); }); describe('=> Complex Component => ', () => { let comp: AppComponent; let fixture: ComponentFixture<AppComponent>; let de: DebugElement; let el: HTMLElement; let directives: any[] = ControlComponents; directives.push(AppComponent); beforeEach((done) => { TestBed.configureTestingModule({ declarations: directives, providers: [ComponentBase] }); /* tslint:disable */ TestBed.overrideComponent(AppComponent, { set: { template: `<ej2-control> <e-childs> <e-child> <e-sub-childs> <e-sub-child text='SubChild1' [header]=true ></e-sub-child> <e-sub-child text='SubChild2' [header]=true ></e-sub-child> <e-sub-child text='SubChild3' [header]=true ></e-sub-child> </e-sub-childs> </e-child> </e-childs> </ej2-control>` } }); /* tslint:enable */ TestBed.compileComponents().then(() => { fixture = TestBed.createComponent(AppComponent); comp = fixture.componentInstance; de = fixture.debugElement; el = de.nativeElement; fixture.detectChanges(); setTimeout(() => { done(); }, 1000); }); }); it('complex data 2 level with out parent property changed', () => { let instance: any = (el.querySelector('.e-control') as any).ej2_instances[0]; expect(JSON.stringify(instance.childs[0], (key: string, value: Object) => { return instance.getActualProperties(value); })).toEqual( '{"subChilds":[{"header":true,"text":"SubChild1"},{"header":true,"text":"SubChild2"},' + '{"header":true,"text":"SubChild3"}],"text":"Child","header":true}' ); }); afterAll(() => { el.remove(); }); }); describe('=> Complex Component => ', () => { let comp: AppComponent; let fixture: ComponentFixture<AppComponent>; let de: DebugElement; let el: HTMLElement; let directives: any[] = ControlComponents; directives.push(AppComponent); beforeEach((done) => { TestBed.configureTestingModule({ declarations: directives, providers: [ComponentBase] }); /* tslint:disable */ TestBed.overrideComponent(AppComponent, { set: { template: `<ej2-control> <e-childs> <e-child *ngFor="let item of new; [text]='item.text' [header]='item.header'> </e-childs> </ej2-control>` } }); /* tslint:enable */ TestBed.compileComponents().then(() => { fixture = TestBed.createComponent(AppComponent); comp = fixture.componentInstance; de = fixture.debugElement; el = de.nativeElement; fixture.detectChanges(); setTimeout(() => { done(); }, 100); }); }); it('complex data processing hasnew', () => { expect(JSON.stringify(comp.new[0])).toEqual('{"text":"Child1","header":true}'); expect(JSON.stringify(comp.new[1])).toEqual('{"text":"Child2","header":false}'); expect(JSON.stringify(comp.new[2])).toEqual('{"text":"Child3","header":true}'); }); it('complex data binding has-new', (done: Function) => { comp.new = [{ text: 'ChangedChild', header: true }]; fixture.detectChanges(); setTimeout(() => { let instance: any = (el.querySelector('.e-control') as any).ej2_instances[0]; expect(JSON.stringify(comp.new[0])).toEqual('{"text":"ChangedChild","header":true}'); done(); }, 100); }); afterAll(() => { el.remove(); }); });
the_stack
 cornerstoneWADOImageLoader.configure({ beforeSend: function(xhr) { // Add custom headers here (e.g. auth tokens) //xhr.setRequestHeader('x-auth-token', 'my auth token'); if (DICOMwebJS.ServerConfiguration.IncludeAuthorizationHeader) { xhr.setRequestHeader("Authorization", DICOMwebJS.ServerConfiguration.SecurityToken); } } }); interface Stack { currentImageIdIndex: number ; imageIds: Array<string>; instanceParams: Array<CommonDicomInstanceParams> ; }; class WadoViewer { private _loaded: Boolean = false; private _uriProxy: WadoUriProxy; private _stack: Stack; private _transferSyntax: string; private _$parentView: JQuery; private _viewerElement: HTMLElement; private _copyImageView: copyImageUrlView; private _mouseActionsButtons: ViewerMouseButtons = new ViewerMouseButtons(); private WADO_IMAGE_LOADER_PREFIX = "wadouri:"; private _seriesNavigator: SeriesNavigator; private _instanceSlider: InstanceSlider; constructor($parentView:JQuery, uriProxy: WadoUriProxy) { this._$parentView = $parentView; this._viewerElement = $parentView.find('#dicomImage').get(0); this._uriProxy = uriProxy; this._copyImageView = new copyImageUrlView($parentView, uriProxy); this._seriesNavigator = new SeriesNavigator(this); this._instanceSlider = new InstanceSlider(this); const options = { renderer: 'webgl' }; cornerstone.enable(this._viewerElement, options); cornerstoneWADOImageLoader.external.cornerstone = cornerstone; this.configureWebWorker(); this._viewerElement.addEventListener('cornerstonenewimage', (e) => { this.onNewImage(e); }); $(this._$parentView).find("input[name=defaultButtonTool]").change((eventObj:JQueryEventObject) =>{ var element: any = eventObj.target; if (element.value == "WL") { this._mouseActionsButtons.DefaultButton = this._mouseActionsButtons.MouseActions.WL; } else { this._mouseActionsButtons.DefaultButton = this._mouseActionsButtons.MouseActions.Sroll; } if (this._loaded) { this._mouseActionsButtons.applyMouseAction(this._viewerElement); } }); $(window).resize(() => { cornerstone.resize(this._viewerElement, true); }) } configureWebWorker() { var config = { webWorkerPath: location.protocol + "//" + location.host + '/scripts/cornerstone/cornerstoneWADOImageLoaderWebWorker.min.js', taskConfiguration: { 'decodeTask': { codecsPath: location.protocol + "//" + location.host + '/scripts/cornerstone/cornerstoneWADOImageLoaderCodecs.min.js', usePDFJS: false } } }; cornerstoneWADOImageLoader.webWorkerManager.initialize(config); } public refresh() { cornerstone.resize(this._viewerElement, true); } public parentView() { return this._$parentView; } public getViewerElement() { return this._viewerElement; } public loadStudy(studyParam: StudyParams, transferSyntax: string = null) { this._seriesNavigator.reset(); $.getJSON(DICOMwebJS.ServerConfiguration.getOhifJsonEndpoint(studyParam.StudyInstanceUid)).then((data: any) => { $.each(data.studies, (studyIndex: number, study: any) => { $.each(study.seriesList, (seriesIndex: number, series) => { this.loadSeriesJson(study, series, transferSyntax).then(() => { this._seriesNavigator.setStudy(study, seriesIndex, transferSyntax); }); return false; }); return false; }); }); } public loadSeriesJson(study: any, series: any, transferSyntax: string = null): JQueryPromise<{}> { var imageIds: Array<any> = []; var instanceParams: Array<CommonDicomInstanceParams> = []; var stack: Stack = { currentImageIdIndex: 0, imageIds: imageIds, instanceParams: instanceParams }; $.each(series.instances, (instsanceIndex: number, instance: any) => { let imageParam: WadoImageParams = { frameNumber: null, transferSyntax: transferSyntax }; let dicomInstance = { studyUID: study.studyInstanceUid, seriesUID: series.seriesInstanceUid, instanceUID: instance.sopInstanceUid }; var wadoImageLoaderUrl = this.getWadoImageLoaderUrl(dicomInstance, imageParam); instanceParams.push(dicomInstance); imageIds.push(wadoImageLoaderUrl); }); this._stack = stack; return this.loadAndViewImage(stack); } public loadInstance(dicomInstance: CommonDicomInstanceParams, transferSyntax: string = null) { let imageParam: WadoImageParams = { frameNumber: null, transferSyntax:transferSyntax }; var wadoImageLoaderUrl = this.getWadoImageLoaderUrl(dicomInstance, imageParam); var stack: Stack = { currentImageIdIndex: 0, imageIds: [], instanceParams: [] }; stack.imageIds.push(wadoImageLoaderUrl); stack.instanceParams.push(dicomInstance); this._stack = stack; this._seriesNavigator.reset(); this.loadAndViewImage(stack); } public loadedInstance(): CommonDicomInstanceParams { if (this._stack) { return this._stack.instanceParams[this._stack.currentImageIdIndex]; } return null; } private loadAndViewImage(stack: Stack): JQueryPromise<{}>{ var element = this._viewerElement; var promise; this._instanceSlider.reset(); if (stack.imageIds.length == 0) { return; } var start = new Date().getTime(); cornerstoneTools.clearToolState(element, "stack"); this._instanceSlider.setStack(stack); try { promise = cornerstone.loadAndCacheImage(stack.imageIds[0]); promise.then((image: any) => { this._loaded = true; var viewport = cornerstone.getDefaultViewportForImage(element, image); //$('#toggleModalityLUT').attr("checked",viewport.modalityLUT !== undefined); //$('#toggleVOILUT').attr("checked",viewport.voiLUT !== undefined); cornerstone.displayImage(element, image, viewport); cornerstoneTools.mouseInput.enable(element); cornerstoneTools.mouseWheelInput.enable(element); cornerstoneTools.wwwcTouchDrag.activate(element); cornerstoneTools.addStackStateManager(element, ['stack', 'playClip']); cornerstoneTools.addToolState(element, 'stack', stack); if (stack.imageIds.length > 1) { this._mouseActionsButtons.WheelButton = this._mouseActionsButtons.MouseActions.Sroll; } else { this._mouseActionsButtons.WheelButton = this._mouseActionsButtons.MouseActions.Zoom; } this._mouseActionsButtons.applyMouseAction(element); cornerstone.resize(this._viewerElement, true); function getTransferSyntax() { var value = image.data.string('x00020010'); return value + ' [' + uids[value] + ']'; } function getSopClass() { var value = image.data.string('x00080016'); return value + ' [' + uids[value] + ']'; } function getPixelRepresentation() { var value = image.data.uint16('x00280103'); if (value === undefined) { return; } return value + (value === 0 ? ' (unsigned)' : ' (signed)'); } function getPlanarConfiguration() { var value = image.data.uint16('x00280006'); if (value === undefined) { return; } return value + (value === 0 ? ' (pixel)' : ' (plane)'); } $('#transferSyntax').text(getTransferSyntax()); $('#sopClass').text(getSopClass()); $('#samplesPerPixel').text(image.data.uint16('x00280002')); $('#photometricInterpretation').text(image.data.string('x00280004')); $('#numberOfFrames').text(image.data.string('x00280008')); $('#planarConfiguration').text(getPlanarConfiguration()); $('#rows').text(image.data.uint16('x00280010')); $('#columns').text(image.data.uint16('x00280011')); $('#pixelSpacing').text(image.data.string('x00280030')); $('#bitsAllocated').text(image.data.uint16('x00280100')); $('#bitsStored').text(image.data.uint16('x00280101')); $('#highBit').text(image.data.uint16('x00280102')); $('#pixelRepresentation').text(getPixelRepresentation()); $('#windowCenter').text(image.data.string('x00281050')); $('#windowWidth').text(image.data.string('x00281051')); $('#rescaleIntercept').text(image.data.string('x00281052')); $('#rescaleSlope').text(image.data.string('x00281053')); $('#basicOffsetTable').text(image.data.elements.x7fe00010.basicOffsetTable ? image.data.elements.x7fe00010.basicOffsetTable.length : ''); $('#fragments').text(image.data.elements.x7fe00010.fragments ? image.data.elements.x7fe00010.fragments.length : ''); $('#minStoredPixelValue').text(image.minPixelValue); $('#maxStoredPixelValue').text(image.maxPixelValue); var end = new Date().getTime(); var time = end - start; $('#loadTime').text(time + "ms"); }); promise.catch((xhr: XMLHttpRequest) => { var errorText = "Image failed to load"; try { if ('TextDecoder' in window && xhr.response) { var enc = new TextDecoder(); errorText = enc.decode(xhr.response); } } catch (error) { } new ModalDialog().showError("Error - " + xhr.status, errorText); }); } catch(err) { new ModalDialog().showError("Error", err); } return promise; } private getWadoImageLoaderUrl(dicomInstance: CommonDicomInstanceParams, imageParam: WadoImageParams) { var instanceUrl = this._uriProxy.createUrl(dicomInstance, MimeTypes.DICOM, imageParam); //add this "wadouri:" so it loads the wado uri loader, //the loader trims this prefix from the url return this.WADO_IMAGE_LOADER_PREFIX + instanceUrl; } private onNewImage(e) { var newImageIdIndex = this._stack.currentImageIdIndex; this._copyImageView.setUrl(this._stack.imageIds[this._stack.currentImageIdIndex].replace(this.WADO_IMAGE_LOADER_PREFIX,"")); } } class ViewerMouseButtons { public MouseActions = { WL: "WL", Zoom: "Zoom", Pan: "Pan", Sroll: "Scroll" }; public DefaultButton = this.MouseActions.WL; public RightButton = this.MouseActions.Zoom; public MiddleButton = this.MouseActions.Pan; public WheelButton = this.MouseActions.Sroll; public applyMouseAction(element: HTMLElement) { cornerstoneTools.wwwc.activate(element, 0); cornerstoneTools.pan.activate(element, 0); cornerstoneTools.zoom.activate(element, 0); cornerstoneTools.stackScroll.activate(element, 0); this.apply(element, cornerstoneTools.wwwc, this.MouseActions.WL); this.apply(element, cornerstoneTools.pan, this.MouseActions.Pan); this.apply(element, cornerstoneTools.zoom, this.MouseActions.Zoom); this.apply(element, cornerstoneTools.stackScroll, this.MouseActions.Sroll); if (this.WheelButton == this.MouseActions.Zoom) { cornerstoneTools.zoomWheel.activate(element); cornerstoneTools.stackScrollWheel.deactivate(element); cornerstoneTools.scrollIndicator.disable(element); } else { // Enable all tools we want to use with this element //cornerstoneTools.stackScroll.activate(element, 1); cornerstoneTools.stackScrollWheel.activate(element); cornerstoneTools.scrollIndicator.enable(element); cornerstoneTools.zoomWheel.deactivate(element); } } private apply(element: HTMLElement, action: any, mouseAction: string) { if (this.DefaultButton == mouseAction) { action.activate(element, 1); } else if (this.RightButton == mouseAction) { action.activate(element, 4); } else if (this.MiddleButton == mouseAction) { action.activate(element, 2); } } } class SeriesNavigator { private _wadoViewer: WadoViewer; private _study: any = null; private _loadedSeriesIndex: number = -1; private _transferSyntax: string = null; private _$prevEl: JQuery; private _$nextEl: JQuery; private _$serInput: JQuery; private _seriesCount: number = 0; constructor(viewer: WadoViewer) { this._wadoViewer = viewer; this._$prevEl = this._wadoViewer.parentView().find(".prevtSer"); this._$nextEl = this._wadoViewer.parentView().find(".nextSer"); this._$serInput = this._wadoViewer.parentView().find(".seriesCount"); this._$nextEl.click(() => { this.next(); }); this._$prevEl.click(() => { this.prev(); }); this.reset(); } public setStudy(study: any, loadedSeriesIndex: number, transferSyntax:string=null) { this._study = study; this._loadedSeriesIndex = loadedSeriesIndex; this._transferSyntax = transferSyntax; this._seriesCount = study.seriesList.length; this.render(); } public reset() { this._$serInput.text(""); this._$prevEl.attr("disabled", "true"); this._$nextEl.attr("disabled", "true"); this._loadedSeriesIndex = -1; this._seriesCount = 0; this._study = null; } private render() { this._$serInput.text("Series " + (this._loadedSeriesIndex + 1) + "/" + this._seriesCount); if (this._loadedSeriesIndex == 0) { this._$prevEl.attr("disabled", "true"); } else { this._$prevEl.removeAttr("disabled"); } if (this._loadedSeriesIndex == this._seriesCount-1) { this._$nextEl.attr("disabled", "true"); } else { this._$nextEl.removeAttr("disabled"); } } private next() { if (this._loadedSeriesIndex == -1 || this._loadedSeriesIndex >= this._seriesCount-1 ) return; this._wadoViewer.loadSeriesJson(this._study, this._study.seriesList[++this._loadedSeriesIndex], this._transferSyntax); this.render(); } private prev() { if (this._loadedSeriesIndex <= 0) return; this._wadoViewer.loadSeriesJson(this._study, this._study.seriesList[--this._loadedSeriesIndex], this._transferSyntax); this.render(); } } class InstanceSlider { private _viewer: WadoViewer; private _stack: Stack; private _$slider: JQuery; private _$instanceCount: JQuery; constructor(viewer: WadoViewer) { this._viewer = viewer; this._$slider = viewer.parentView().find(".instance-slider"); this._$instanceCount = viewer.parentView().find(".instance-count"); this._viewer.getViewerElement().addEventListener('cornerstonenewimage', (e) => { this._$slider.val(this._stack.currentImageIdIndex + 1); this.render(); }); this._$slider.on('input', () => { var slideIndex = this._$slider.val()-1; if (slideIndex >= 0 && slideIndex < this._stack.imageIds.length) { var targetElement = this._viewer.getViewerElement(); var stackToolDataSource = cornerstoneTools.getToolState(targetElement, 'stack'); if (stackToolDataSource === undefined) { return; } var stackData = stackToolDataSource.data[0]; // Switch images, if necessary if (slideIndex !== stackData.currentImageIdIndex && stackData.imageIds[slideIndex] !== undefined) { cornerstone.loadAndCacheImage(stackData.imageIds[slideIndex]).then(function (image) { var viewport = cornerstone.getViewport(targetElement); stackData.currentImageIdIndex = slideIndex; cornerstone.displayImage(targetElement, image, viewport); }); } } }) } public setStack(stack: Stack) { this._stack = stack; this._$slider.val(stack.currentImageIdIndex + 1); this._$slider.attr("min", 1); this._$slider.attr("max", this._stack.imageIds.length); this.render(); } public reset() { this._stack = null; this._$instanceCount.text(""); } private render() { this._$instanceCount.text("Count " + (this._stack.currentImageIdIndex+1) + "/" + this._stack.imageIds.length); } }
the_stack
import { PagedAsyncIterableIterator } from "@azure/core-paging"; import { ScalingPlans } from "../operationsInterfaces"; import * as coreClient from "@azure/core-client"; import * as Mappers from "../models/mappers"; import * as Parameters from "../models/parameters"; import { DesktopVirtualizationAPIClient } from "../desktopVirtualizationAPIClient"; import { ScalingPlan, ScalingPlansListByResourceGroupNextOptionalParams, ScalingPlansListByResourceGroupOptionalParams, ScalingPlansListBySubscriptionNextOptionalParams, ScalingPlansListBySubscriptionOptionalParams, ScalingPlansListByHostPoolNextOptionalParams, ScalingPlansListByHostPoolOptionalParams, ScalingPlansGetOptionalParams, ScalingPlansGetResponse, ScalingPlansCreateOptionalParams, ScalingPlansCreateResponse, ScalingPlansDeleteOptionalParams, ScalingPlansUpdateOptionalParams, ScalingPlansUpdateResponse, ScalingPlansListByResourceGroupResponse, ScalingPlansListBySubscriptionResponse, ScalingPlansListByHostPoolResponse, ScalingPlansListByResourceGroupNextResponse, ScalingPlansListBySubscriptionNextResponse, ScalingPlansListByHostPoolNextResponse } from "../models"; /// <reference lib="esnext.asynciterable" /> /** Class containing ScalingPlans operations. */ export class ScalingPlansImpl implements ScalingPlans { private readonly client: DesktopVirtualizationAPIClient; /** * Initialize a new instance of the class ScalingPlans class. * @param client Reference to the service client */ constructor(client: DesktopVirtualizationAPIClient) { this.client = client; } /** * List scaling plans. * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param options The options parameters. */ public listByResourceGroup( resourceGroupName: string, options?: ScalingPlansListByResourceGroupOptionalParams ): PagedAsyncIterableIterator<ScalingPlan> { const iter = this.listByResourceGroupPagingAll(resourceGroupName, options); return { next() { return iter.next(); }, [Symbol.asyncIterator]() { return this; }, byPage: () => { return this.listByResourceGroupPagingPage(resourceGroupName, options); } }; } private async *listByResourceGroupPagingPage( resourceGroupName: string, options?: ScalingPlansListByResourceGroupOptionalParams ): AsyncIterableIterator<ScalingPlan[]> { let result = await this._listByResourceGroup(resourceGroupName, options); yield result.value || []; let continuationToken = result.nextLink; while (continuationToken) { result = await this._listByResourceGroupNext( resourceGroupName, continuationToken, options ); continuationToken = result.nextLink; yield result.value || []; } } private async *listByResourceGroupPagingAll( resourceGroupName: string, options?: ScalingPlansListByResourceGroupOptionalParams ): AsyncIterableIterator<ScalingPlan> { for await (const page of this.listByResourceGroupPagingPage( resourceGroupName, options )) { yield* page; } } /** * List scaling plans in subscription. * @param options The options parameters. */ public listBySubscription( options?: ScalingPlansListBySubscriptionOptionalParams ): PagedAsyncIterableIterator<ScalingPlan> { const iter = this.listBySubscriptionPagingAll(options); return { next() { return iter.next(); }, [Symbol.asyncIterator]() { return this; }, byPage: () => { return this.listBySubscriptionPagingPage(options); } }; } private async *listBySubscriptionPagingPage( options?: ScalingPlansListBySubscriptionOptionalParams ): AsyncIterableIterator<ScalingPlan[]> { let result = await this._listBySubscription(options); yield result.value || []; let continuationToken = result.nextLink; while (continuationToken) { result = await this._listBySubscriptionNext(continuationToken, options); continuationToken = result.nextLink; yield result.value || []; } } private async *listBySubscriptionPagingAll( options?: ScalingPlansListBySubscriptionOptionalParams ): AsyncIterableIterator<ScalingPlan> { for await (const page of this.listBySubscriptionPagingPage(options)) { yield* page; } } /** * List scaling plan associated with hostpool. * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param hostPoolName The name of the host pool within the specified resource group * @param options The options parameters. */ public listByHostPool( resourceGroupName: string, hostPoolName: string, options?: ScalingPlansListByHostPoolOptionalParams ): PagedAsyncIterableIterator<ScalingPlan> { const iter = this.listByHostPoolPagingAll( resourceGroupName, hostPoolName, options ); return { next() { return iter.next(); }, [Symbol.asyncIterator]() { return this; }, byPage: () => { return this.listByHostPoolPagingPage( resourceGroupName, hostPoolName, options ); } }; } private async *listByHostPoolPagingPage( resourceGroupName: string, hostPoolName: string, options?: ScalingPlansListByHostPoolOptionalParams ): AsyncIterableIterator<ScalingPlan[]> { let result = await this._listByHostPool( resourceGroupName, hostPoolName, options ); yield result.value || []; let continuationToken = result.nextLink; while (continuationToken) { result = await this._listByHostPoolNext( resourceGroupName, hostPoolName, continuationToken, options ); continuationToken = result.nextLink; yield result.value || []; } } private async *listByHostPoolPagingAll( resourceGroupName: string, hostPoolName: string, options?: ScalingPlansListByHostPoolOptionalParams ): AsyncIterableIterator<ScalingPlan> { for await (const page of this.listByHostPoolPagingPage( resourceGroupName, hostPoolName, options )) { yield* page; } } /** * Get a scaling plan. * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param scalingPlanName The name of the scaling plan. * @param options The options parameters. */ get( resourceGroupName: string, scalingPlanName: string, options?: ScalingPlansGetOptionalParams ): Promise<ScalingPlansGetResponse> { return this.client.sendOperationRequest( { resourceGroupName, scalingPlanName, options }, getOperationSpec ); } /** * Create or update a scaling plan. * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param scalingPlanName The name of the scaling plan. * @param scalingPlan Object containing scaling plan definitions. * @param options The options parameters. */ create( resourceGroupName: string, scalingPlanName: string, scalingPlan: ScalingPlan, options?: ScalingPlansCreateOptionalParams ): Promise<ScalingPlansCreateResponse> { return this.client.sendOperationRequest( { resourceGroupName, scalingPlanName, scalingPlan, options }, createOperationSpec ); } /** * Remove a scaling plan. * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param scalingPlanName The name of the scaling plan. * @param options The options parameters. */ delete( resourceGroupName: string, scalingPlanName: string, options?: ScalingPlansDeleteOptionalParams ): Promise<void> { return this.client.sendOperationRequest( { resourceGroupName, scalingPlanName, options }, deleteOperationSpec ); } /** * Update a scaling plan. * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param scalingPlanName The name of the scaling plan. * @param options The options parameters. */ update( resourceGroupName: string, scalingPlanName: string, options?: ScalingPlansUpdateOptionalParams ): Promise<ScalingPlansUpdateResponse> { return this.client.sendOperationRequest( { resourceGroupName, scalingPlanName, options }, updateOperationSpec ); } /** * List scaling plans. * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param options The options parameters. */ private _listByResourceGroup( resourceGroupName: string, options?: ScalingPlansListByResourceGroupOptionalParams ): Promise<ScalingPlansListByResourceGroupResponse> { return this.client.sendOperationRequest( { resourceGroupName, options }, listByResourceGroupOperationSpec ); } /** * List scaling plans in subscription. * @param options The options parameters. */ private _listBySubscription( options?: ScalingPlansListBySubscriptionOptionalParams ): Promise<ScalingPlansListBySubscriptionResponse> { return this.client.sendOperationRequest( { options }, listBySubscriptionOperationSpec ); } /** * List scaling plan associated with hostpool. * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param hostPoolName The name of the host pool within the specified resource group * @param options The options parameters. */ private _listByHostPool( resourceGroupName: string, hostPoolName: string, options?: ScalingPlansListByHostPoolOptionalParams ): Promise<ScalingPlansListByHostPoolResponse> { return this.client.sendOperationRequest( { resourceGroupName, hostPoolName, options }, listByHostPoolOperationSpec ); } /** * ListByResourceGroupNext * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param nextLink The nextLink from the previous successful call to the ListByResourceGroup method. * @param options The options parameters. */ private _listByResourceGroupNext( resourceGroupName: string, nextLink: string, options?: ScalingPlansListByResourceGroupNextOptionalParams ): Promise<ScalingPlansListByResourceGroupNextResponse> { return this.client.sendOperationRequest( { resourceGroupName, nextLink, options }, listByResourceGroupNextOperationSpec ); } /** * ListBySubscriptionNext * @param nextLink The nextLink from the previous successful call to the ListBySubscription method. * @param options The options parameters. */ private _listBySubscriptionNext( nextLink: string, options?: ScalingPlansListBySubscriptionNextOptionalParams ): Promise<ScalingPlansListBySubscriptionNextResponse> { return this.client.sendOperationRequest( { nextLink, options }, listBySubscriptionNextOperationSpec ); } /** * ListByHostPoolNext * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param hostPoolName The name of the host pool within the specified resource group * @param nextLink The nextLink from the previous successful call to the ListByHostPool method. * @param options The options parameters. */ private _listByHostPoolNext( resourceGroupName: string, hostPoolName: string, nextLink: string, options?: ScalingPlansListByHostPoolNextOptionalParams ): Promise<ScalingPlansListByHostPoolNextResponse> { return this.client.sendOperationRequest( { resourceGroupName, hostPoolName, nextLink, options }, listByHostPoolNextOperationSpec ); } } // Operation Specifications const serializer = coreClient.createSerializer(Mappers, /* isXml */ false); const getOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DesktopVirtualization/scalingPlans/{scalingPlanName}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.ScalingPlan }, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.scalingPlanName ], headerParameters: [Parameters.accept], serializer }; const createOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DesktopVirtualization/scalingPlans/{scalingPlanName}", httpMethod: "PUT", responses: { 200: { bodyMapper: Mappers.ScalingPlan }, 201: { bodyMapper: Mappers.ScalingPlan }, default: { bodyMapper: Mappers.CloudError } }, requestBody: Parameters.scalingPlan, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.scalingPlanName ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const deleteOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DesktopVirtualization/scalingPlans/{scalingPlanName}", httpMethod: "DELETE", responses: { 200: {}, 204: {}, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.scalingPlanName ], headerParameters: [Parameters.accept], serializer }; const updateOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DesktopVirtualization/scalingPlans/{scalingPlanName}", httpMethod: "PATCH", responses: { 200: { bodyMapper: Mappers.ScalingPlan }, default: { bodyMapper: Mappers.CloudError } }, requestBody: Parameters.scalingPlan1, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.scalingPlanName ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const listByResourceGroupOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DesktopVirtualization/scalingPlans", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.ScalingPlanList }, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName ], headerParameters: [Parameters.accept], serializer }; const listBySubscriptionOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/providers/Microsoft.DesktopVirtualization/scalingPlans", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.ScalingPlanList }, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion], urlParameters: [Parameters.$host, Parameters.subscriptionId], headerParameters: [Parameters.accept], serializer }; const listByHostPoolOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DesktopVirtualization/hostPools/{hostPoolName}/scalingPlans", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.ScalingPlanList }, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.hostPoolName ], headerParameters: [Parameters.accept], serializer }; const listByResourceGroupNextOperationSpec: coreClient.OperationSpec = { path: "{nextLink}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.ScalingPlanList }, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.nextLink, Parameters.subscriptionId, Parameters.resourceGroupName ], headerParameters: [Parameters.accept], serializer }; const listBySubscriptionNextOperationSpec: coreClient.OperationSpec = { path: "{nextLink}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.ScalingPlanList }, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.nextLink, Parameters.subscriptionId ], headerParameters: [Parameters.accept], serializer }; const listByHostPoolNextOperationSpec: coreClient.OperationSpec = { path: "{nextLink}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.ScalingPlanList }, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.nextLink, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.hostPoolName ], headerParameters: [Parameters.accept], serializer };
the_stack
import { Contract, ContractFactory } from '@ethersproject/contracts' import { Resolvable, Resolver } from 'did-resolver' import { getResolver } from '../resolver' import { EthrDidController } from '../controller' import DidRegistryContract from 'ethr-did-registry' import { interpretIdentifier, stringToBytes32 } from '../helpers' import { createProvider, sleep, startMining, stopMining } from './testUtils' import { nullAddress } from '../helpers' jest.setTimeout(30000) describe('ethrResolver', () => { // let registry, accounts, did, identity, controller, delegate1, delegate2, ethr, didResolver let registryContract: Contract, accounts, did: string, identity: string, controller: string, delegate1: string, delegate2: string, keyAgreementController: string, didResolver: Resolvable const web3Provider = createProvider() beforeAll(async () => { const factory = ContractFactory.fromSolidity(DidRegistryContract).connect(web3Provider.getSigner(0)) registryContract = await factory.deploy() registryContract = await registryContract.deployed() await registryContract.deployTransaction.wait() const registry = registryContract.address accounts = await web3Provider.listAccounts() identity = accounts[1] controller = accounts[2] delegate1 = accounts[3] delegate2 = accounts[4] keyAgreementController = accounts[5] did = `did:ethr:dev:${identity}` didResolver = new Resolver(getResolver({ name: 'dev', provider: web3Provider, registry })) }) describe('unregistered', () => { it('resolves document', async () => { expect.assertions(1) await expect(didResolver.resolve(did)).resolves.toEqual({ didDocumentMetadata: {}, didResolutionMetadata: { contentType: 'application/did+ld+json' }, didDocument: { '@context': [ 'https://www.w3.org/ns/did/v1', 'https://identity.foundation/EcdsaSecp256k1RecoverySignature2020/lds-ecdsa-secp256k1-recovery2020-0.0.jsonld', ], id: did, verificationMethod: [ { id: `${did}#controller`, type: 'EcdsaSecp256k1RecoveryMethod2020', controller: did, blockchainAccountId: `${identity}@eip155:1337`, }, ], authentication: [`${did}#controller`], assertionMethod: [`${did}#controller`], }, }) }) it('resolves document with publicKey identifier', async () => { expect.assertions(1) const pubKey = '0x0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798' const pubdid = `did:ethr:dev:${pubKey}` await expect(didResolver.resolve(pubdid)).resolves.toEqual({ didDocumentMetadata: {}, didResolutionMetadata: { contentType: 'application/did+ld+json' }, didDocument: { '@context': [ 'https://www.w3.org/ns/did/v1', 'https://identity.foundation/EcdsaSecp256k1RecoverySignature2020/lds-ecdsa-secp256k1-recovery2020-0.0.jsonld', ], id: pubdid, verificationMethod: [ { id: `${pubdid}#controller`, type: 'EcdsaSecp256k1RecoveryMethod2020', controller: pubdid, blockchainAccountId: `${identity}@eip155:1337`, }, { id: `${pubdid}#controllerKey`, type: 'EcdsaSecp256k1VerificationKey2019', controller: pubdid, publicKeyHex: pubKey, }, ], authentication: [`${pubdid}#controller`, `${pubdid}#controllerKey`], assertionMethod: [`${pubdid}#controller`, `${pubdid}#controllerKey`], }, }) }) }) describe('controller changed', () => { it('resolves document', async () => { expect.assertions(1) await new EthrDidController(identity, registryContract).changeOwner(controller, { from: identity }) const result = await didResolver.resolve(did) delete result.didDocumentMetadata.updated expect(result).toEqual({ didDocumentMetadata: { versionId: '2' }, didResolutionMetadata: { contentType: 'application/did+ld+json' }, didDocument: { '@context': [ 'https://www.w3.org/ns/did/v1', 'https://identity.foundation/EcdsaSecp256k1RecoverySignature2020/lds-ecdsa-secp256k1-recovery2020-0.0.jsonld', ], id: did, verificationMethod: [ { id: `${did}#controller`, type: 'EcdsaSecp256k1RecoveryMethod2020', controller: did, blockchainAccountId: `${controller}@eip155:1337`, }, ], authentication: [`${did}#controller`], assertionMethod: [`${did}#controller`], }, }) }) it('changing controller invalidates the publicKey as identifier', async () => { expect.assertions(3) const pubKey = '0x0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798' const pubdid = `did:ethr:dev:${pubKey}` const { didDocument } = await didResolver.resolve(pubdid) expect(didDocument).toEqual({ '@context': [ 'https://www.w3.org/ns/did/v1', 'https://identity.foundation/EcdsaSecp256k1RecoverySignature2020/lds-ecdsa-secp256k1-recovery2020-0.0.jsonld', ], id: pubdid, verificationMethod: [ { id: `${pubdid}#controller`, type: 'EcdsaSecp256k1RecoveryMethod2020', controller: pubdid, blockchainAccountId: `${controller}@eip155:1337`, }, ], authentication: [`${pubdid}#controller`], assertionMethod: [`${pubdid}#controller`], }) expect(didDocument?.verificationMethod?.length).toBe(1) expect(didDocument?.authentication?.length).toBe(1) }) }) describe('delegates', () => { describe('add signing delegate', () => { it('resolves document', async () => { expect.assertions(1) await new EthrDidController(identity, registryContract).addDelegate('veriKey', delegate1, 86401, { from: controller, }) const result = await didResolver.resolve(did) delete result.didDocumentMetadata.updated await expect(result).toEqual({ didDocumentMetadata: { versionId: '3' }, didResolutionMetadata: { contentType: 'application/did+ld+json' }, didDocument: { '@context': [ 'https://www.w3.org/ns/did/v1', 'https://identity.foundation/EcdsaSecp256k1RecoverySignature2020/lds-ecdsa-secp256k1-recovery2020-0.0.jsonld', ], id: did, verificationMethod: [ { id: `${did}#controller`, type: 'EcdsaSecp256k1RecoveryMethod2020', controller: did, blockchainAccountId: `${controller}@eip155:1337`, }, { id: `${did}#delegate-1`, type: 'EcdsaSecp256k1RecoveryMethod2020', controller: did, blockchainAccountId: `${delegate1}@eip155:1337`, }, ], authentication: [`${did}#controller`], assertionMethod: [`${did}#controller`, `${did}#delegate-1`], }, }) }) }) describe('add auth delegate', () => { it('resolves document', async () => { expect.assertions(1) await new EthrDidController(identity, registryContract).addDelegate('sigAuth', delegate2, 1, { from: controller, }) const result = await didResolver.resolve(did) //don't compare against hardcoded timestamps delete result.didDocumentMetadata.updated expect(result).toEqual({ didDocumentMetadata: { versionId: '4' }, didResolutionMetadata: { contentType: 'application/did+ld+json' }, didDocument: { '@context': [ 'https://www.w3.org/ns/did/v1', 'https://identity.foundation/EcdsaSecp256k1RecoverySignature2020/lds-ecdsa-secp256k1-recovery2020-0.0.jsonld', ], id: did, verificationMethod: [ { id: `${did}#controller`, type: 'EcdsaSecp256k1RecoveryMethod2020', controller: did, blockchainAccountId: `${controller}@eip155:1337`, }, { id: `${did}#delegate-1`, type: 'EcdsaSecp256k1RecoveryMethod2020', controller: did, blockchainAccountId: `${delegate1}@eip155:1337`, }, { id: `${did}#delegate-2`, type: 'EcdsaSecp256k1RecoveryMethod2020', controller: did, blockchainAccountId: `${delegate2}@eip155:1337`, }, ], authentication: [`${did}#controller`, `${did}#delegate-2`], assertionMethod: [`${did}#controller`, `${did}#delegate-1`, `${did}#delegate-2`], }, }) }) }) describe('expire automatically', () => { it('resolves document', async () => { expect.assertions(1) //key validity was set to less than 2 seconds await sleep(4) const result = await didResolver.resolve(did) //don't compare against hardcoded timestamps delete result.didDocumentMetadata.updated expect(result).toEqual({ didDocumentMetadata: { versionId: '4' }, didResolutionMetadata: { contentType: 'application/did+ld+json' }, didDocument: { '@context': [ 'https://www.w3.org/ns/did/v1', 'https://identity.foundation/EcdsaSecp256k1RecoverySignature2020/lds-ecdsa-secp256k1-recovery2020-0.0.jsonld', ], id: did, verificationMethod: [ { id: `${did}#controller`, type: 'EcdsaSecp256k1RecoveryMethod2020', controller: did, blockchainAccountId: `${controller}@eip155:1337`, }, { id: `${did}#delegate-1`, type: 'EcdsaSecp256k1RecoveryMethod2020', controller: did, blockchainAccountId: `${delegate1}@eip155:1337`, }, ], authentication: [`${did}#controller`], assertionMethod: [`${did}#controller`, `${did}#delegate-1`], }, }) }) }) describe('revokes delegate', () => { it('resolves document', async () => { expect.assertions(1) await new EthrDidController(identity, registryContract).revokeDelegate('veriKey', delegate1, { from: controller, }) await sleep(1) const result = await didResolver.resolve(did) //don't compare against hardcoded timestamps delete result.didDocumentMetadata.updated expect(result).toEqual({ didDocumentMetadata: { versionId: '5' }, didResolutionMetadata: { contentType: 'application/did+ld+json' }, didDocument: { '@context': [ 'https://www.w3.org/ns/did/v1', 'https://identity.foundation/EcdsaSecp256k1RecoverySignature2020/lds-ecdsa-secp256k1-recovery2020-0.0.jsonld', ], id: did, verificationMethod: [ { id: `${did}#controller`, type: 'EcdsaSecp256k1RecoveryMethod2020', controller: did, blockchainAccountId: `${controller}@eip155:1337`, }, ], authentication: [`${did}#controller`], assertionMethod: [`${did}#controller`], }, }) }) }) describe('re-add auth delegate', () => { it('resolves document', async () => { expect.assertions(1) await new EthrDidController(identity, registryContract).addDelegate('sigAuth', delegate2, 86402, { from: controller, }) const result = await didResolver.resolve(did) //don't compare against hardcoded timestamps delete result.didDocumentMetadata.updated expect(result).toEqual({ didDocumentMetadata: { versionId: '6' }, didResolutionMetadata: { contentType: 'application/did+ld+json' }, didDocument: { '@context': [ 'https://www.w3.org/ns/did/v1', 'https://identity.foundation/EcdsaSecp256k1RecoverySignature2020/lds-ecdsa-secp256k1-recovery2020-0.0.jsonld', ], id: did, verificationMethod: [ { id: `${did}#controller`, type: 'EcdsaSecp256k1RecoveryMethod2020', controller: did, blockchainAccountId: `${controller}@eip155:1337`, }, { id: `${did}#delegate-4`, type: 'EcdsaSecp256k1RecoveryMethod2020', controller: did, blockchainAccountId: `${delegate2}@eip155:1337`, }, ], authentication: [`${did}#controller`, `${did}#delegate-4`], assertionMethod: [`${did}#controller`, `${did}#delegate-4`], }, }) }) }) }) describe('attributes', () => { describe('add publicKey', () => { it('resolves with EcdsaSecp256k1VerificationKey2019', async () => { expect.assertions(1) await new EthrDidController(identity, registryContract).setAttribute( 'did/pub/Secp256k1/veriKey', '0x02b97c30de767f084ce3080168ee293053ba33b235d7116a3263d29f1450936b71', 86401, { from: controller } ) const { didDocument } = await didResolver.resolve(did) expect(didDocument).toEqual({ '@context': [ 'https://www.w3.org/ns/did/v1', 'https://identity.foundation/EcdsaSecp256k1RecoverySignature2020/lds-ecdsa-secp256k1-recovery2020-0.0.jsonld', ], id: did, verificationMethod: [ { id: `${did}#controller`, type: 'EcdsaSecp256k1RecoveryMethod2020', controller: did, blockchainAccountId: `${controller}@eip155:1337`, }, { id: `${did}#delegate-4`, type: 'EcdsaSecp256k1RecoveryMethod2020', controller: did, blockchainAccountId: `${delegate2}@eip155:1337`, }, { id: `${did}#delegate-5`, type: 'EcdsaSecp256k1VerificationKey2019', controller: did, publicKeyHex: '02b97c30de767f084ce3080168ee293053ba33b235d7116a3263d29f1450936b71', }, ], authentication: [`${did}#controller`, `${did}#delegate-4`], assertionMethod: [`${did}#controller`, `${did}#delegate-4`, `${did}#delegate-5`], }) }) it('resolves with Ed25519VerificationKey2018', async () => { expect.assertions(1) await new EthrDidController(identity, registryContract).setAttribute( 'did/pub/Ed25519/veriKey/base64', '0x02b97c30de767f084ce3080168ee293053ba33b235d7116a3263d29f1450936b71', 86402, { from: controller } ) const { didDocument } = await didResolver.resolve(did) expect(didDocument).toEqual({ '@context': [ 'https://www.w3.org/ns/did/v1', 'https://identity.foundation/EcdsaSecp256k1RecoverySignature2020/lds-ecdsa-secp256k1-recovery2020-0.0.jsonld', ], id: did, verificationMethod: [ { id: `${did}#controller`, type: 'EcdsaSecp256k1RecoveryMethod2020', controller: did, blockchainAccountId: `${controller}@eip155:1337`, }, { id: `${did}#delegate-4`, type: 'EcdsaSecp256k1RecoveryMethod2020', controller: did, blockchainAccountId: `${delegate2}@eip155:1337`, }, { id: `${did}#delegate-5`, type: 'EcdsaSecp256k1VerificationKey2019', controller: did, publicKeyHex: '02b97c30de767f084ce3080168ee293053ba33b235d7116a3263d29f1450936b71', }, { id: `${did}#delegate-6`, type: 'Ed25519VerificationKey2018', controller: did, publicKeyBase64: Buffer.from( '02b97c30de767f084ce3080168ee293053ba33b235d7116a3263d29f1450936b71', 'hex' ).toString('base64'), }, ], authentication: [`${did}#controller`, `${did}#delegate-4`], assertionMethod: [`${did}#controller`, `${did}#delegate-4`, `${did}#delegate-5`, `${did}#delegate-6`], }) }) it('resolves with RSAVerificationKey2018', async () => { expect.assertions(1) await new EthrDidController(identity, registryContract).setAttribute( 'did/pub/RSA/veriKey/pem', '-----BEGIN PUBLIC KEY...END PUBLIC KEY-----\r\n', 86403, { from: controller } ) const { didDocument } = await didResolver.resolve(did) expect(didDocument).toEqual({ '@context': [ 'https://www.w3.org/ns/did/v1', 'https://identity.foundation/EcdsaSecp256k1RecoverySignature2020/lds-ecdsa-secp256k1-recovery2020-0.0.jsonld', ], id: did, verificationMethod: [ { id: `${did}#controller`, type: 'EcdsaSecp256k1RecoveryMethod2020', controller: did, blockchainAccountId: `${controller}@eip155:1337`, }, { id: `${did}#delegate-4`, type: 'EcdsaSecp256k1RecoveryMethod2020', controller: did, blockchainAccountId: `${delegate2}@eip155:1337`, }, { id: `${did}#delegate-5`, type: 'EcdsaSecp256k1VerificationKey2019', controller: did, publicKeyHex: '02b97c30de767f084ce3080168ee293053ba33b235d7116a3263d29f1450936b71', }, { id: `${did}#delegate-6`, type: 'Ed25519VerificationKey2018', controller: did, publicKeyBase64: Buffer.from( '02b97c30de767f084ce3080168ee293053ba33b235d7116a3263d29f1450936b71', 'hex' ).toString('base64'), }, { id: `${did}#delegate-7`, type: 'RSAVerificationKey2018', controller: did, publicKeyPem: '-----BEGIN PUBLIC KEY...END PUBLIC KEY-----\r\n', }, ], authentication: [`${did}#controller`, `${did}#delegate-4`], assertionMethod: [ `${did}#controller`, `${did}#delegate-4`, `${did}#delegate-5`, `${did}#delegate-6`, `${did}#delegate-7`, ], }) }) it('resolves with X25519KeyAgreementKey2019', async () => { expect.assertions(1) const keyAgrDid = `did:ethr:dev:${keyAgreementController}` await new EthrDidController(keyAgreementController, registryContract).setAttribute( 'did/pub/X25519/enc/base64', `0x${Buffer.from('MCowBQYDK2VuAyEAEYVXd3/7B4d0NxpSsA/tdVYdz5deYcR1U+ZkphdmEFI=', 'base64').toString('hex')}`, 86404, { from: keyAgreementController } ) const { didDocument } = await didResolver.resolve(keyAgrDid) expect(didDocument).toEqual({ '@context': [ 'https://www.w3.org/ns/did/v1', 'https://identity.foundation/EcdsaSecp256k1RecoverySignature2020/lds-ecdsa-secp256k1-recovery2020-0.0.jsonld', ], id: keyAgrDid, verificationMethod: [ { id: `${keyAgrDid}#controller`, type: 'EcdsaSecp256k1RecoveryMethod2020', controller: keyAgrDid, blockchainAccountId: `${keyAgreementController}@eip155:1337`, }, { id: `${keyAgrDid}#delegate-1`, type: 'X25519KeyAgreementKey2019', controller: keyAgrDid, publicKeyBase64: 'MCowBQYDK2VuAyEAEYVXd3/7B4d0NxpSsA/tdVYdz5deYcR1U+ZkphdmEFI=', }, ], authentication: [`${keyAgrDid}#controller`], assertionMethod: [`${keyAgrDid}#controller`, `${keyAgrDid}#delegate-1`], }) }) }) describe('add service endpoints', () => { it('resolves document', async () => { expect.assertions(1) await new EthrDidController(identity, registryContract).setAttribute( stringToBytes32('did/svc/HubService'), 'https://hubs.uport.me', 86405, { from: controller } ) const { didDocument } = await didResolver.resolve(did) expect(didDocument).toEqual({ '@context': [ 'https://www.w3.org/ns/did/v1', 'https://identity.foundation/EcdsaSecp256k1RecoverySignature2020/lds-ecdsa-secp256k1-recovery2020-0.0.jsonld', ], id: did, verificationMethod: [ { id: `${did}#controller`, type: 'EcdsaSecp256k1RecoveryMethod2020', controller: did, blockchainAccountId: `${controller}@eip155:1337`, }, { id: `${did}#delegate-4`, type: 'EcdsaSecp256k1RecoveryMethod2020', controller: did, blockchainAccountId: `${delegate2}@eip155:1337`, }, { id: `${did}#delegate-5`, type: 'EcdsaSecp256k1VerificationKey2019', controller: did, publicKeyHex: '02b97c30de767f084ce3080168ee293053ba33b235d7116a3263d29f1450936b71', }, { id: `${did}#delegate-6`, type: 'Ed25519VerificationKey2018', controller: did, publicKeyBase64: Buffer.from( '02b97c30de767f084ce3080168ee293053ba33b235d7116a3263d29f1450936b71', 'hex' ).toString('base64'), }, { id: `${did}#delegate-7`, type: 'RSAVerificationKey2018', controller: did, publicKeyPem: '-----BEGIN PUBLIC KEY...END PUBLIC KEY-----\r\n', }, ], authentication: [`${did}#controller`, `${did}#delegate-4`], assertionMethod: [ `${did}#controller`, `${did}#delegate-4`, `${did}#delegate-5`, `${did}#delegate-6`, `${did}#delegate-7`, ], service: [ { id: `${did}#service-1`, type: 'HubService', serviceEndpoint: 'https://hubs.uport.me', }, ], }) }) }) }) describe('revoke publicKey', () => { it('resolves without EcdsaSecp256k1VerificationKey2019', async () => { expect.assertions(1) await new EthrDidController(identity, registryContract).revokeAttribute( 'did/pub/Secp256k1/veriKey', '0x02b97c30de767f084ce3080168ee293053ba33b235d7116a3263d29f1450936b71', { from: controller } ) const { didDocument } = await didResolver.resolve(did) expect(didDocument).toEqual({ '@context': [ 'https://www.w3.org/ns/did/v1', 'https://identity.foundation/EcdsaSecp256k1RecoverySignature2020/lds-ecdsa-secp256k1-recovery2020-0.0.jsonld', ], id: did, verificationMethod: [ { id: `${did}#controller`, type: 'EcdsaSecp256k1RecoveryMethod2020', controller: did, blockchainAccountId: `${controller}@eip155:1337`, }, { id: `${did}#delegate-4`, type: 'EcdsaSecp256k1RecoveryMethod2020', controller: did, blockchainAccountId: `${delegate2}@eip155:1337`, }, { id: `${did}#delegate-6`, type: 'Ed25519VerificationKey2018', controller: did, publicKeyBase64: Buffer.from( '02b97c30de767f084ce3080168ee293053ba33b235d7116a3263d29f1450936b71', 'hex' ).toString('base64'), }, { id: `${did}#delegate-7`, type: 'RSAVerificationKey2018', controller: did, publicKeyPem: '-----BEGIN PUBLIC KEY...END PUBLIC KEY-----\r\n', }, ], authentication: [`${did}#controller`, `${did}#delegate-4`], assertionMethod: [`${did}#controller`, `${did}#delegate-4`, `${did}#delegate-6`, `${did}#delegate-7`], service: [ { id: `${did}#service-1`, type: 'HubService', serviceEndpoint: 'https://hubs.uport.me', }, ], }) }) it('resolves without Ed25519VerificationKey2018', async () => { expect.assertions(1) await new EthrDidController(identity, registryContract).revokeAttribute( 'did/pub/Ed25519/veriKey/base64', '0x02b97c30de767f084ce3080168ee293053ba33b235d7116a3263d29f1450936b71', { from: controller } ) const { didDocument } = await didResolver.resolve(did) expect(didDocument).toEqual({ '@context': [ 'https://www.w3.org/ns/did/v1', 'https://identity.foundation/EcdsaSecp256k1RecoverySignature2020/lds-ecdsa-secp256k1-recovery2020-0.0.jsonld', ], id: did, verificationMethod: [ { id: `${did}#controller`, type: 'EcdsaSecp256k1RecoveryMethod2020', controller: did, blockchainAccountId: `${controller}@eip155:1337`, }, { id: `${did}#delegate-4`, type: 'EcdsaSecp256k1RecoveryMethod2020', controller: did, blockchainAccountId: `${delegate2}@eip155:1337`, }, { id: `${did}#delegate-7`, type: 'RSAVerificationKey2018', controller: did, publicKeyPem: '-----BEGIN PUBLIC KEY...END PUBLIC KEY-----\r\n', }, ], authentication: [`${did}#controller`, `${did}#delegate-4`], assertionMethod: [`${did}#controller`, `${did}#delegate-4`, `${did}#delegate-7`], service: [ { id: `${did}#service-1`, type: 'HubService', serviceEndpoint: 'https://hubs.uport.me', }, ], }) }) it('resolves without RSAVerificationKey2018', async () => { expect.assertions(1) await new EthrDidController(identity, registryContract).revokeAttribute( stringToBytes32('did/pub/RSA/veriKey/pem'), '-----BEGIN PUBLIC KEY...END PUBLIC KEY-----\r\n', { from: controller } ) const { didDocument } = await didResolver.resolve(did) expect(didDocument).toEqual({ '@context': [ 'https://www.w3.org/ns/did/v1', 'https://identity.foundation/EcdsaSecp256k1RecoverySignature2020/lds-ecdsa-secp256k1-recovery2020-0.0.jsonld', ], id: did, verificationMethod: [ { id: `${did}#controller`, type: 'EcdsaSecp256k1RecoveryMethod2020', controller: did, blockchainAccountId: `${controller}@eip155:1337`, }, { id: `${did}#delegate-4`, type: 'EcdsaSecp256k1RecoveryMethod2020', controller: did, blockchainAccountId: `${delegate2}@eip155:1337`, }, ], authentication: [`${did}#controller`, `${did}#delegate-4`], assertionMethod: [`${did}#controller`, `${did}#delegate-4`], service: [ { id: `${did}#service-1`, type: 'HubService', serviceEndpoint: 'https://hubs.uport.me', }, ], }) }) describe('revoke service endpoints', () => { it('resolves without HubService', async () => { expect.assertions(1) await new EthrDidController(identity, registryContract).revokeAttribute( stringToBytes32('did/svc/HubService'), 'https://hubs.uport.me', { from: controller } ) const { didDocument } = await didResolver.resolve(did) expect(didDocument).toEqual({ '@context': [ 'https://www.w3.org/ns/did/v1', 'https://identity.foundation/EcdsaSecp256k1RecoverySignature2020/lds-ecdsa-secp256k1-recovery2020-0.0.jsonld', ], id: did, verificationMethod: [ { id: `${did}#controller`, type: 'EcdsaSecp256k1RecoveryMethod2020', controller: did, blockchainAccountId: `${controller}@eip155:1337`, }, { id: `${did}#delegate-4`, type: 'EcdsaSecp256k1RecoveryMethod2020', controller: did, blockchainAccountId: `${delegate2}@eip155:1337`, }, ], authentication: [`${did}#controller`, `${did}#delegate-4`], assertionMethod: [`${did}#controller`, `${did}#delegate-4`], }) }) }) }) describe('multiple events in one block', () => { beforeAll(async () => { const ethrDid = new EthrDidController(identity, registryContract) await stopMining(web3Provider) await Promise.all([ ethrDid.setAttribute(stringToBytes32('did/svc/TestService'), 'https://test.uport.me', 86406, { from: controller, }), ethrDid.setAttribute(stringToBytes32('did/svc/TestService'), 'https://test.uport.me', 86407, { from: controller, }), sleep(1).then(() => startMining(web3Provider)), ]) }) it('resolves document', async () => { expect.assertions(1) const result = await didResolver.resolve(did) //don't compare against hardcoded timestamps delete result.didDocumentMetadata.updated expect(result).toEqual({ didDocumentMetadata: { versionId: '16' }, didResolutionMetadata: { contentType: 'application/did+ld+json', }, didDocument: { '@context': [ 'https://www.w3.org/ns/did/v1', 'https://identity.foundation/EcdsaSecp256k1RecoverySignature2020/lds-ecdsa-secp256k1-recovery2020-0.0.jsonld', ], id: did, verificationMethod: [ { id: `${did}#controller`, type: 'EcdsaSecp256k1RecoveryMethod2020', controller: did, blockchainAccountId: `${controller}@eip155:1337`, }, { id: `${did}#delegate-4`, type: 'EcdsaSecp256k1RecoveryMethod2020', controller: did, blockchainAccountId: `${delegate2}@eip155:1337`, }, ], authentication: [`${did}#controller`, `${did}#delegate-4`], assertionMethod: [`${did}#controller`, `${did}#delegate-4`], service: [ { id: `${did}#service-4`, type: 'TestService', serviceEndpoint: 'https://test.uport.me', }, ], }, }) }) }) describe('attribute revocation event in same block(-batch) as attribute creation', () => { beforeAll(async () => { const ethrDid = new EthrDidController(identity, registryContract) await stopMining(web3Provider) await Promise.all([ ethrDid.setAttribute(stringToBytes32('did/svc/TestService2'), 'https://test2.uport.me', 86408, { from: controller, }), sleep(1).then(() => ethrDid.revokeAttribute(stringToBytes32('did/svc/TestService2'), 'https://test2.uport.me', { from: controller, }) ), sleep(1).then(() => startMining(web3Provider)), ]) }) it('resolves document', async () => { expect.assertions(1) const result = await didResolver.resolve(did) //don't compare against hardcoded timestamps delete result.didDocumentMetadata.updated expect(result).toEqual({ didDocumentMetadata: { versionId: '18' }, didResolutionMetadata: { contentType: 'application/did+ld+json', }, didDocument: { '@context': [ 'https://www.w3.org/ns/did/v1', 'https://identity.foundation/EcdsaSecp256k1RecoverySignature2020/lds-ecdsa-secp256k1-recovery2020-0.0.jsonld', ], id: did, verificationMethod: [ { id: `${did}#controller`, type: 'EcdsaSecp256k1RecoveryMethod2020', controller: did, blockchainAccountId: `${controller}@eip155:1337`, }, { id: `${did}#delegate-4`, type: 'EcdsaSecp256k1RecoveryMethod2020', controller: did, blockchainAccountId: `${delegate2}@eip155:1337`, }, ], authentication: [`${did}#controller`, `${did}#delegate-4`], assertionMethod: [`${did}#controller`, `${did}#delegate-4`], service: [ { id: `${did}#service-4`, type: 'TestService', serviceEndpoint: 'https://test.uport.me', }, ], }, }) }) }) describe('regression', () => { it('resolves same document with case sensitive eth address (https://github.com/decentralized-identity/ethr-did-resolver/issues/105)', async () => { expect.assertions(3) const lowAddress = accounts[5].toLowerCase() const checksumAddress = interpretIdentifier(lowAddress).address const lowDid = `did:ethr:dev:${lowAddress}` const checksumDid = `did:ethr:dev:${checksumAddress}` await new EthrDidController(lowAddress, registryContract).setAttribute( 'did/pub/Secp256k1/veriKey/hex', '0x02b97c30de767f084ce3080168ee293053ba33b235d7116a3263d29f1450936b71', 86409, { from: lowAddress } ) const didDocumentLow = (await didResolver.resolve(lowDid)).didDocument const didDocumentChecksum = (await didResolver.resolve(checksumDid)).didDocument expect(lowDid).not.toEqual(checksumDid) expect(didDocumentLow).toBeDefined() //we don't care about the actual keys, only about their sameness expect(JSON.stringify(didDocumentLow).toLowerCase()).toEqual(JSON.stringify(didDocumentChecksum).toLowerCase()) }) it('adds sigAuth to authentication section (https://github.com/decentralized-identity/ethr-did-resolver/issues/95)', async () => { expect.assertions(1) const identity = accounts[4] const did = `did:ethr:dev:${identity}` const authPubKey = `31303866356238393330623164633235386162353765386630646362363932353963363162316166` await new EthrDidController(identity, registryContract).setAttribute( 'did/pub/Ed25519/sigAuth/hex', `0x${authPubKey}`, 86410, { from: identity } ) const { didDocument } = await didResolver.resolve(did) expect(didDocument).toEqual({ '@context': [ 'https://www.w3.org/ns/did/v1', 'https://identity.foundation/EcdsaSecp256k1RecoverySignature2020/lds-ecdsa-secp256k1-recovery2020-0.0.jsonld', ], id: did, verificationMethod: [ { id: `${did}#controller`, controller: did, type: 'EcdsaSecp256k1RecoveryMethod2020', blockchainAccountId: `${delegate2}@eip155:1337`, }, { id: `${did}#delegate-1`, controller: did, type: `Ed25519VerificationKey2018`, publicKeyHex: authPubKey, }, ], authentication: [`${did}#controller`, `${did}#delegate-1`], assertionMethod: [`${did}#controller`, `${did}#delegate-1`], }) }) describe('Ed25519VerificationKey2018 in base58 (https://github.com/decentralized-identity/ethr-did-resolver/pull/106)', () => { it('resolves document', async () => { expect.assertions(1) const identity = accounts[3] const did = `did:ethr:dev:${identity}` const publicKeyHex = `b97c30de767f084ce3080168ee293053ba33b235d7116a3263d29f1450936b71` const expectedPublicKeyBase58 = 'DV4G2kpBKjE6zxKor7Cj21iL9x9qyXb6emqjszBXcuhz' await new EthrDidController(identity, registryContract).setAttribute( 'did/pub/Ed25519/veriKey/base58', `0x${publicKeyHex}`, 86411, { from: identity } ) const result = await didResolver.resolve(did) //don't compare against hardcoded timestamps delete result.didDocumentMetadata.updated expect(result).toEqual({ didDocumentMetadata: { versionId: '21' }, didResolutionMetadata: { contentType: 'application/did+ld+json', }, didDocument: { '@context': [ 'https://www.w3.org/ns/did/v1', 'https://identity.foundation/EcdsaSecp256k1RecoverySignature2020/lds-ecdsa-secp256k1-recovery2020-0.0.jsonld', ], id: did, verificationMethod: [ { id: `${did}#controller`, type: 'EcdsaSecp256k1RecoveryMethod2020', controller: did, blockchainAccountId: `${identity}@eip155:1337`, }, { id: `${did}#delegate-1`, type: 'Ed25519VerificationKey2018', controller: did, publicKeyBase58: expectedPublicKeyBase58, }, ], authentication: [`${did}#controller`], assertionMethod: [`${did}#controller`, `${did}#delegate-1`], }, }) }) }) describe('can deactivate a DID (https://github.com/decentralized-identity/ethr-did-resolver/issues/83)', () => { it('resolves deactivated document', async () => { expect.assertions(2) const identity = accounts[6] const did = `did:ethr:dev:${identity}` await new EthrDidController(identity, registryContract).changeOwner(nullAddress, { from: identity }) const result = await didResolver.resolve(did) expect(result.didDocumentMetadata.updated).toBeDefined() delete result.didDocumentMetadata.updated expect(result).toEqual({ didDocumentMetadata: { deactivated: true, versionId: '22', }, didResolutionMetadata: { contentType: 'application/did+ld+json', }, didDocument: { '@context': 'https://www.w3.org/ns/did/v1', id: did, verificationMethod: [], authentication: [], assertionMethod: [], }, }) }) }) describe('versioning', () => { it('can resolve virgin DID with versionId=latest', async () => { expect.assertions(1) const virginAddress = '0xce3080168EE293053bA33b235D7116a3263D29f1' const virginDID = `did:ethr:dev:${virginAddress}` const result = await didResolver.resolve(`${virginDID}?versionId=latest`) expect(result).toEqual({ didDocumentMetadata: {}, didResolutionMetadata: { contentType: 'application/did+ld+json', }, didDocument: { '@context': [ 'https://www.w3.org/ns/did/v1', 'https://identity.foundation/EcdsaSecp256k1RecoverySignature2020/lds-ecdsa-secp256k1-recovery2020-0.0.jsonld', ], id: virginDID, verificationMethod: [ { id: `${virginDID}#controller`, type: 'EcdsaSecp256k1RecoveryMethod2020', controller: virginDID, blockchainAccountId: `${virginAddress}@eip155:1337`, }, ], authentication: [`${virginDID}#controller`], assertionMethod: [`${virginDID}#controller`], }, }) }) it('can resolve modified did with versionId=latest', async () => { expect.assertions(2) const identity = accounts[3] const modifiedDid = `did:ethr:dev:${identity}` const result = await didResolver.resolve(`${modifiedDid}?versionId=latest`) expect(result.didDocumentMetadata.updated).toBeDefined() delete result.didDocumentMetadata.updated expect(result).toEqual({ didDocumentMetadata: { versionId: '21' }, didResolutionMetadata: { contentType: 'application/did+ld+json', }, didDocument: { '@context': [ 'https://www.w3.org/ns/did/v1', 'https://identity.foundation/EcdsaSecp256k1RecoverySignature2020/lds-ecdsa-secp256k1-recovery2020-0.0.jsonld', ], id: modifiedDid, verificationMethod: [ { id: `${modifiedDid}#controller`, type: 'EcdsaSecp256k1RecoveryMethod2020', controller: modifiedDid, blockchainAccountId: `${identity}@eip155:1337`, }, { id: `${modifiedDid}#delegate-1`, type: 'Ed25519VerificationKey2018', controller: modifiedDid, publicKeyBase58: 'DV4G2kpBKjE6zxKor7Cj21iL9x9qyXb6emqjszBXcuhz', }, ], authentication: [`${modifiedDid}#controller`], assertionMethod: [`${modifiedDid}#controller`, `${modifiedDid}#delegate-1`], }, }) }) it('can resolve did with versionId before an attribute change', async () => { expect.assertions(3) const result = await didResolver.resolve(`${did}?versionId=6`) expect(result.didDocumentMetadata.updated).toBeDefined() delete result.didDocumentMetadata.updated expect(result.didDocumentMetadata.nextUpdate).toBeDefined() delete result.didDocumentMetadata.nextUpdate expect(result).toEqual({ didDocumentMetadata: { versionId: '6', nextVersionId: '7' }, didResolutionMetadata: { contentType: 'application/did+ld+json' }, didDocument: { '@context': [ 'https://www.w3.org/ns/did/v1', 'https://identity.foundation/EcdsaSecp256k1RecoverySignature2020/lds-ecdsa-secp256k1-recovery2020-0.0.jsonld', ], id: did, verificationMethod: [ { id: `${did}#controller`, type: 'EcdsaSecp256k1RecoveryMethod2020', controller: did, blockchainAccountId: `${controller}@eip155:1337`, }, { id: `${did}#delegate-4`, type: 'EcdsaSecp256k1RecoveryMethod2020', controller: did, blockchainAccountId: `${delegate2}@eip155:1337`, }, ], authentication: [`${did}#controller`, `${did}#delegate-4`], assertionMethod: [`${did}#controller`, `${did}#delegate-4`], }, }) }) it('can resolve did with versionId before a delegate change', async () => { expect.assertions(3) const result = await didResolver.resolve(`${did}?versionId=2`) expect(result.didDocumentMetadata.updated).toBeDefined() delete result.didDocumentMetadata.updated expect(result.didDocumentMetadata.nextUpdate).toBeDefined() delete result.didDocumentMetadata.nextUpdate expect(result).toEqual({ didDocumentMetadata: { versionId: '2', nextVersionId: '3' }, didResolutionMetadata: { contentType: 'application/did+ld+json' }, didDocument: { '@context': [ 'https://www.w3.org/ns/did/v1', 'https://identity.foundation/EcdsaSecp256k1RecoverySignature2020/lds-ecdsa-secp256k1-recovery2020-0.0.jsonld', ], id: did, verificationMethod: [ { id: `${did}#controller`, type: 'EcdsaSecp256k1RecoveryMethod2020', controller: did, blockchainAccountId: `${controller}@eip155:1337`, }, ], authentication: [`${did}#controller`], assertionMethod: [`${did}#controller`], }, }) }) it('can resolve did with versionId before an owner change', async () => { expect.assertions(2) const result = await didResolver.resolve(`${did}?versionId=1`) expect(result.didDocumentMetadata.nextUpdate).toBeDefined() delete result.didDocumentMetadata.nextUpdate expect(result).toEqual({ didDocumentMetadata: { nextVersionId: '2', }, didResolutionMetadata: { contentType: 'application/did+ld+json' }, didDocument: { '@context': [ 'https://www.w3.org/ns/did/v1', 'https://identity.foundation/EcdsaSecp256k1RecoverySignature2020/lds-ecdsa-secp256k1-recovery2020-0.0.jsonld', ], id: did, verificationMethod: [ { id: `${did}#controller`, type: 'EcdsaSecp256k1RecoveryMethod2020', controller: did, blockchainAccountId: `${identity}@eip155:1337`, }, ], authentication: [`${did}#controller`], assertionMethod: [`${did}#controller`], }, }) }) it('can resolve did with versionId before deactivation', async () => { expect.assertions(2) const deactivatedDid = `did:ethr:dev:${accounts[6]}` const result = await didResolver.resolve(`${deactivatedDid}?versionId=21`) expect(result.didDocumentMetadata.nextUpdate).toBeDefined() delete result.didDocumentMetadata.nextUpdate expect(result).toEqual({ didDocumentMetadata: { nextVersionId: '22', }, didResolutionMetadata: { contentType: 'application/did+ld+json' }, didDocument: { '@context': [ 'https://www.w3.org/ns/did/v1', 'https://identity.foundation/EcdsaSecp256k1RecoverySignature2020/lds-ecdsa-secp256k1-recovery2020-0.0.jsonld', ], id: deactivatedDid, verificationMethod: [ { id: `${deactivatedDid}#controller`, type: 'EcdsaSecp256k1RecoveryMethod2020', controller: deactivatedDid, blockchainAccountId: `${accounts[6]}@eip155:1337`, }, ], authentication: [`${deactivatedDid}#controller`], assertionMethod: [`${deactivatedDid}#controller`], }, }) }) it('can resolve did with versionId before an attribute expiration', async () => { expect.assertions(1) const result = await didResolver.resolve(`${did}?versionId=4`) //don't compare against hardcoded timestamps delete result.didDocumentMetadata.updated delete result.didDocumentMetadata.nextUpdate expect(result).toEqual({ didDocumentMetadata: { versionId: '4', nextVersionId: '5' }, didResolutionMetadata: { contentType: 'application/did+ld+json' }, didDocument: { '@context': [ 'https://www.w3.org/ns/did/v1', 'https://identity.foundation/EcdsaSecp256k1RecoverySignature2020/lds-ecdsa-secp256k1-recovery2020-0.0.jsonld', ], id: did, verificationMethod: [ { id: `${did}#controller`, type: 'EcdsaSecp256k1RecoveryMethod2020', controller: did, blockchainAccountId: `${controller}@eip155:1337`, }, { id: `${did}#delegate-1`, type: 'EcdsaSecp256k1RecoveryMethod2020', controller: did, blockchainAccountId: `${delegate1}@eip155:1337`, }, { id: `${did}#delegate-2`, type: 'EcdsaSecp256k1RecoveryMethod2020', controller: did, blockchainAccountId: `${delegate2}@eip155:1337`, }, ], authentication: [`${did}#controller`, `${did}#delegate-2`], assertionMethod: [`${did}#controller`, `${did}#delegate-1`, `${did}#delegate-2`], }, }) }) }) }) })
the_stack
import * as React from 'react'; import type { PageProps } from 'gatsby'; import { graphql, navigate } from 'gatsby'; import { styled } from 'gatsby-theme-stitches/src/config'; import { GatsbySeo } from 'gatsby-plugin-next-seo'; import { rem } from 'polished'; import { required } from '@cometjs/core'; import type { PropOf, RefOf } from '@cometjs/react-utils'; import { mapAbstractType } from '@cometjs/graphql-utils'; import _PageTitle from '../components/PageTitle'; import _FormField from '../components/FormField'; import FileAttachmentField from '../components/formField/FileAttachmentField'; import ShortTextField from '../components/formField/ShortTextField'; import LongTextField from '../components/formField/LongTextField'; import SingleSelectField from '../components/formField/SingleSelectField'; import MultiSelectField from '../components/formField/MultiSelectField'; import YesNoField from '../components/formField/YesNoField'; import TermsField from '../components/formField/TermsField'; import Button from '../components/Button'; import _Spinner from '../components/Spinner'; import messages from './jobApplicationPage/messages'; type JobApplicationPageProps = PageProps<GatsbyTypes.TeamWebsite_JobApplicationPageQuery, GatsbyTypes.SitePageContext>; export const query = graphql` query TeamWebsite_JobApplicationPage( $id: String! $locale: String! $navigationId: String! ) { ...TeamWebsite_DefaultLayout_query ...TeamWebsite_JobPostLayout_query jobPost(id: { eq: $id }) { ghId title boardToken parentJob { questions { __typename name label required description ...on GreenhouseJobBoardJobQuestionForYesNo { options { label value } } ...on GreenhouseJobBoardJobQuestionForSingleSelect { options { label value } } ...on GreenhouseJobBoardJobQuestionForMultiSelect { options { label value } } } } } privacyPolicy: prismicTermsAndConditions( uid: { eq: "job-application-privacy" } lang: { eq: $locale } ) { id data { content { html } } } sensitiveInfoPolicy: prismicTermsAndConditions( uid: { eq: "job-application-sensitive" } lang: { eq: $locale } ) { id data { content { html } } } } `; type State = ( | 'initial' | 'invalid' | 'fetching' | 'completed' ); type Action = ( | 'INVALID' | 'FETCH_START' | 'FETCH_COMPLETE' ); const initialState: State = 'initial'; const reducer: React.Reducer<State, Action> = (state, action) => { switch (action) { case 'INVALID': { switch (state) { case 'initial': case 'fetching': case 'invalid': { return 'invalid'; } } break; } case 'FETCH_START': { switch (state) { case 'initial': case 'invalid': { return 'fetching'; } } break; } case 'FETCH_COMPLETE': { if (state === 'fetching') { return 'completed'; } break; } } return state; }; const Form = styled('form', { }); const FormField = styled(_FormField, { marginBottom: rem(32), }); const Spinner = styled(_Spinner, { height: '50%', }); const greenhouseAcceptedMimeTypes = [ 'text/plain', 'application/rtf', 'application/pdf', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', ]; const makeEndpoint = (boardToken: string, jobId: string): string => { const host = process.env.GATSBY_JOB_APPLICATION_FORM_HOST || 'http://localhost:8787'; return `${host.replace(/\/$/, '')}/boards/${boardToken}/jobs/${jobId}/application/proxy`; }; const JobApplicationPage: React.FC<JobApplicationPageProps> = ({ data, }) => { required(data.jobPost); const [state, dispatch] = React.useReducer(reducer, initialState); const jobApplicationFormEndpoint = makeEndpoint(data.jobPost.boardToken, data.jobPost.ghId); type FormRef = RefOf<typeof Form>; const formRef = React.useRef<FormRef>(null); // Note: Progressive Enhancement // 사실 이거 없어도 기본 폼으로 100% 동작함 type SubmitHandler = NonNullable<PropOf<typeof Form, 'onSubmit'>>; const handleSubmit: SubmitHandler = e => { e.preventDefault(); if (!formRef.current) { return; } const formData = new FormData(formRef.current); (async () => { required(data.jobPost); dispatch('FETCH_START'); try { const response = await fetch(jobApplicationFormEndpoint, { method: 'POST', body: formData, }); if (response.ok) { dispatch('FETCH_COMPLETE'); window.alert(messages.alert_completed); } else { dispatch('INVALID'); const message = await response.text(); window.alert(message); } } catch (e) { console.error(e); window.alert(messages.alert_failed); dispatch('INVALID'); } })(); }; React.useEffect(() => { required(data.jobPost); if (state === 'completed') { navigate('/completed/'); } }, [state]); const portfolioField = data.jobPost.parentJob.questions.find(question => question.name === 'cover_letter'); return ( <Form ref={formRef} method="post" encType="multipart/form-data" action={jobApplicationFormEndpoint} onSubmit={handleSubmit} > <GatsbySeo noindex /> <FormField as={ShortTextField} name="first_name" label={messages.field_name_label} placeholder={messages.field_name_placeholder} required /> {/* Treat the first_name as fullname */} <input type="hidden" name="last_name" value={"\u200b"} /> <FormField as={ShortTextField} type="tel" name="phone" label={messages.field_phone_label} placeholder={messages.field_phone_placeholder} required /> <FormField as={ShortTextField} type="email" name="email" label={messages.field_email_label} placeholder={messages.field_email_placeholder} required /> <FormField as={FileAttachmentField} name="resume" accepts={greenhouseAcceptedMimeTypes} label={messages.field_resume_label} description={messages.field_resume_description} placeholder={messages.field_resume_placeholder} required /> {portfolioField && ( <FormField as={FileAttachmentField} accepts={greenhouseAcceptedMimeTypes} name={portfolioField.name} label={messages.field_portfolio_label} description={messages.field_portfolio_description} placeholder={messages.field_portfolio_placeholder} required={portfolioField.required} /> )} {data.jobPost.parentJob.questions // Note: Custom Question 만 따로 렌더링 .filter(question => question.name.startsWith('question')) .map(question => mapAbstractType(question, { GreenhouseJobBoardJobQuestionForShortText: question => ( <FormField as={ShortTextField} key={question.name} name={question.name} label={question.label} required={question.required} /> ), GreenhouseJobBoardJobQuestionForLongText: question => ( <FormField as={LongTextField} key={question.name} name={question.name} label={question.label} required={question.required} /> ), GreenhouseJobBoardJobQuestionForAttachment: question => ( <FormField as={FileAttachmentField} key={question.name} accepts={greenhouseAcceptedMimeTypes} placeholder={messages.custom_field_file_placeholder} name={question.name} label={question.label} required={question.required} /> ), GreenhouseJobBoardJobQuestionForYesNo: question => ( <FormField as={YesNoField} key={question.name} name={question.name} label={question.label} required={question.required} /> ), GreenhouseJobBoardJobQuestionForSingleSelect: question => ( <FormField as={SingleSelectField} key={question.name} name={question.name} label={question.label} required={question.required} options={[...question.options]} /> ), GreenhouseJobBoardJobQuestionForMultiSelect: question => ( <FormField as={MultiSelectField} key={question.name} name={question.name} label={question.label} required={question.required} options={[...question.options]} /> ), }))} {data.privacyPolicy?.data?.content?.html && ( <FormField as={TermsField} terms={data.privacyPolicy.data.content.html} label={messages.terms_privacy_info} /> )} {data.sensitiveInfoPolicy?.data?.content?.html && ( <FormField as={TermsField} terms={data.sensitiveInfoPolicy.data.content.html} label={messages.terms_sensitive_info} /> )} <Button as="button" type="primary" fullWidth disabled={state === 'fetching'} > {state === 'fetching' ? ( <Spinner /> ) : ( messages.button_submit )} </Button> </Form> ); }; export default JobApplicationPage;
the_stack
import { defineConfig } from '@agile-ts/utils'; import type { Logger } from '@agile-ts/logger'; // The Log Code Manager keeps track // and manages all important Logs of AgileTs. // // How does the identification of Log Messages work? // Let's take a look at this example: // 00:00:00 // // |00|:00:00 first digits are based on the Agile Class // 00 = General // 10 = Agile // 11 = Storage // ... // // --- // 00:|00|:00 second digits are based on the Log Type export const logCodeTypes = { '00': 'success', '01': 'info', '02': 'warn', '03': 'error', }; // // --- // 00:00:|00| third digits are based on the Log Message (ascending counted) const logCodeMessages = { // Agile '10:00:00': 'Created new AgileInstance.', '10:02:00': 'Be careful when binding multiple Agile Instances globally in one application!', // Storages '11:02:00': "The 'Local Storage' is not available in your current environment. " + "To use the '.persist()' functionality, please provide a custom Storage!", '11:02:01': 'The first allocated Storage for AgileTs must be set as the default Storage!', '11:03:00': "Storage with the key/name '${0}' already exists!", '11:03:01': "Couldn't find Storage '${0}'. " + "The Storage with the key/name '${0}' doesn't exists!", '11:03:02': "Storage with the key/name '${0}' isn't ready yet!", '11:03:03': 'No Storage found to get a value from! Please specify at least one Storage.', '11:03:04': 'No Storage found to store a value in! Please specify at least one Storage.', '11:03:05': 'No Storage found to remove a value from! Please specify at least one Storage.', // Persistent '12:03:00': 'No valid persist Key found! Provide a valid key or assign one to the parent instance.', '12:03:01': 'No valid persist Storage Key found! Please specify at least one Storage Key to use the persist functionality.', '12:03:02': "Couldn't validate Persistent '${0}'." + "The Storage with the key/name '${1}' doesn't exists!`", // Storage '13:00:00': "Registered new Storage '${0}'.", '13:01:00': "GET value at key '${1}' from Storage '${0}'.", '13:01:01': "SET value at key '${1}' in Storage '${0}'.", '13:01:02': "REMOVE value at key '${1}' from Storage '${0}'.", '13:02:00': 'Using normalGet() in a async-based Storage might result in an unexpected return value. ' + 'Instead of a resolved value a Promise is returned!', '13:03:00': "Invalid Storage '${0}()' method provided!", // State '14:03:01': "'${1}' is a not supported type! Supported types are: String, Boolean, Array, Object, Number.", '14:03:02': "The 'patch()' method works only in object based States!", '14:03:03': 'Only one Interval can be active at once!', '14:03:04': "Failed to invert value of the type '${0}'!", // SubController '15:01:00': "Unregistered 'Callback' based Subscription.", '15:01:01': "Unregistered 'Component' based Subscription.", '15:01:02': "Registered 'Component' based Subscription.", '15:01:03': "Registered 'Callback' based Subscription.", // Runtime '16:01:00': "Created Job '${0}'", '16:01:01': "Completed Job '${0}'", '16:01:02': 'Updated/Rerendered Subscriptions', '16:02:00': "SubscriptionContainer/Component '${0}' isn't ready to rerender!", '16:02:01': 'Job with not ready SubscriptionContainer/Component was removed from the runtime ' + 'after ${0} tries to avoid a Job overflow.', // Observer '17:03:00': "The 'perform()' method isn't set in Observer but need to be set! Observer is no stand alone class.", // Integrations '18:00:00': "Integrated '${0}' into AgileTs '${1}'", '18:02:00': "Can't call the 'update()' method on a not ready Integration '${0}'!", '18:03:00': "Failed to integrate Framework '${0}' into AgileTs '${1}'!", // Computed // Collection Persistent '1A:02:00': 'Failed to build unique Item StorageKey!', '1A:02:01': 'Failed to build unique Group StorageKey!', // Collection '1B:02:00': "We recommend using 'createGroup()' " + "instead of 'Group()' outside the Collection configuration object.", '1B:02:01': "We recommend using 'createSelector()' " + "instead of 'Selector()' outside the Collection configuration object.", '1B:02:02': 'By overwriting the whole Item ' + "you have to pass the correct itemKey into the 'changes object!'", '1B:02:03': "We recommend using 'Group()' instead of 'createGroup()' " + 'inside the Collection configuration object.', '1B:02:04': "We recommend using 'Selector()' instead of 'createSelector()' " + 'inside the Collection configuration object.', '1B:02:05': "Collection '${0}' Item Data has to contain a primaryKey property called '${1}'!", '1B:03:00': "Couldn't update Item with the key/name '${0}' " + "because it doesn't exist in Collection '${1}'", '1B:03:01': "Valid object required to update Item value '${0}' in Collection '${1}'!", '1B:03:02': "Group with the key/name '${0}' already exists!", '1B:03:03': "Selector with the key/name '${0}' already exists!", '1B:03:04': "Couldn't update ItemKey from '${0}' to '${1}' " + "because an Item with the key/name '${1}' already exists in the Collection '${2}'!", '1B:03:05': "Item Data of Collection '${0}' has to be a valid object!", '1B:03:06': "Item tried to add to the Collection '${0}' belongs to another Collection '${1}'!", // Group '1C:02:00': "Couldn't find some Items in the Collection '${0}' " + "during the rebuild of the Group '${1}' output.", '1C:03:00': "The 'output' property of the Group '${0}' is a automatically generated readonly property " + 'that can only be mutated by the Group itself!', '1C:03:01': "The 'item' property of the Group '${0}' is a automatically generated readonly property " + 'that can only be mutated by the Group itself!', // Utils '20:03:00': 'Failed to get Agile Instance from', '20:03:01': "Failed to create global Instance at '${0}'", '20:03:02': "Required module '${0}' couldn't be retrieved!", // General '00:03:00': "The '${0}()' method isn't set in ${1} but need to be set!" + ' ${1} is no stand alone class.', '00:03:01': "'${0}' has to be of the type ${1}!", }; export class LogCodeManager<LogCodeMessagesType extends Object = Object> { // Keymap of messages that the LogCodeManager can log public logCodeMessages: LogCodeMessagesType; // Optional '@agile-ts/logger' package for more advanced logging public _loggerPackage: any; // Whether the LogCodeManager is allowed to log public allowLogging = true; /** * Manages logging for AgileTs based on log codes. * * @param logCodeMessages - Keymap of messages that the LogCodeManager can log. * @param loggerPackage - Optional '@agile-ts/logger' package for more advanced logging. */ constructor(logCodeMessages: LogCodeMessagesType, loggerPackage?: any) { this.logCodeMessages = logCodeMessages; this._loggerPackage = loggerPackage; } /** * Retrieves the shared Logger from the specified 'loggerPackage'. * * @public */ public get logger(): Logger | null { return this._loggerPackage?.sharedLogger || null; } /** * Returns the log message according to the specified log code. * * @internal * @param logCode - Log code of the message to be returned. * @param replacers - Instances that replace these '${x}' placeholders based on the index * For example: 'replacers[0]' replaces '${0}', 'replacers[1]' replaces '${1}', .. */ public getLog<T extends LogCodePaths<LogCodeMessagesType>>( logCode: T, replacers: any[] = [] ): string { let result = this.logCodeMessages[logCode] as any; if (result == null) return logCode; // Replace '${x}' with the specified replacer instances for (let i = 0; i < replacers.length; i++) { result = result.replace('${' + i + '}', replacers[i]); } return result; } /** * Logs the log message according to the specified log code * with the Agile Logger if installed or the normal console. * * @internal * @param logCode - Log code of the message to be logged. * @param config - Configuration object * @param data - Data to be attached to the end of the log message. */ public log<T extends LogCodePaths<LogCodeMessagesType>>( logCode: T, config: LogConfigInterface = {}, ...data: any[] ): void { if ((this.logger != null && !this.logger.isActive) || !this.allowLogging) return; config = defineConfig(config, { replacers: [], tags: [], }); const logType = logCodeTypes[logCode.substr(3, 2)]; if (typeof logType !== 'string') return; // Handle logging without Logger package if (this.logger == null) { if (logType === 'error' || logType === 'warn') console[logType](`Agile: ${this.getLog(logCode, config.replacers)}`); return; } // Handle logging with Logger package const log = this.getLog(logCode, config.replacers); if (config.tags?.length === 0) this.logger[logType](log, ...data); else this.logger.if.tag(config.tags as any)[logType](log, ...data); } } /** * Creates an extension of the specified LogCodeManager * and assigns the provided additional log messages to it. * * @param logCodeManager - LogCodeManager to create an extension from. * @param additionalLogs - Log messages to be added to the created LogCodeManager extensions. */ export function assignAdditionalLogs<NewLogCodeMessages, OldLogCodeMessages>( logCodeManager: LogCodeManager<OldLogCodeMessages>, additionalLogs: { [key: string]: string } ): LogCodeManager<NewLogCodeMessages> { const copiedLogCodeManager = new LogCodeManager( { ...logCodeManager.logCodeMessages, ...additionalLogs, }, logCodeManager._loggerPackage ); return copiedLogCodeManager as any; } // Instantiate LogCodeManager based on the current environment type LogCodeMessagesType = typeof logCodeMessages; let tempLogCodeManager: LogCodeManager<LogCodeMessagesType>; if (process.env.NODE_ENV !== 'production') { let loggerPackage: any = null; try { loggerPackage = require('@agile-ts/logger'); } catch (e) { // empty catch block } tempLogCodeManager = new LogCodeManager(logCodeMessages, loggerPackage); } else { tempLogCodeManager = new LogCodeManager({} as any, null); } /** * The Log Code Manager keeps track * and manages all important Logs for the '@agile-ts/core' package. * * @internal */ export const logCodeManager = tempLogCodeManager; interface LogConfigInterface { /** * Instances that replace these '${x}' placeholders based on the index * For example: 'replacers[0]' replaces '${0}', 'replacers[1]' replaces '${1}', .. * @default [] */ replacers?: any[]; /** * Tags that need to be active in order to log the specified logCode. * @default [] */ tags?: string[]; } export type LogCodePaths<T> = { [K in keyof T]: T[K] extends string ? K : never; }[keyof T] & string;
the_stack
import { fillValue, findInput, findLabel, getValue, iff, LOG, NGX, setValue, open, close, getByLabel, getByPlaceholder } from './functions'; // -------------- Helpers -------------- // Workaround for https://github.com/cypress-io/cypress/issues/18879 function Cypress_Commands_add_Subject<T extends keyof Cypress.Chainable>(name: T, options: any, fn: any): void { Cypress.Commands.add(name, options, fn); } // -------------- Utils -------------- /** * Find element by name attribute. */ Cypress.Commands.add( 'getByName', ( name: string, options: Partial<Cypress.Loggable & Cypress.Timeoutable & Cypress.Withinable & Cypress.Shadow> = {} ) => { return cy.get(`*[name="${name}"]`, options); } ); /** * Find element by label attribute. */ Cypress.Commands.add('getByLabel', (label: string, options: Partial<Cypress.Loggable & Cypress.Withinable>) => { options = { log: true, withinSubject: cy['state']('withinSubject'), ...options }; const $el = getByLabel(label, options) as JQuery<any>; if (options.log) { Cypress.log({ name: 'getByLabel', message: label, $el, consoleProps: () => { return { Yielded: $el, Elements: $el?.length, Label: label }; } }); } return cy.wrap($el, LOG); }); /** * Find element by placeholder text. */ Cypress.Commands.add('getByPlaceholder', (text: string, options: Partial<Cypress.Loggable & Cypress.Withinable>) => { options = { log: true, withinSubject: cy['state']('withinSubject'), ...options }; const $el = getByPlaceholder(text, options) as JQuery<any>; if (options.log) { Cypress.log({ name: 'getByPlaceholder', message: text, $el, consoleProps: () => { return { Yielded: $el, Elements: $el?.length, Placeholder: text }; } }); } return cy.wrap($el, LOG); }); // TODO: getByRole? /** * Like `cy.within`, but for each element. */ Cypress_Commands_add_Subject( 'withinEach', { prevSubject: 'element' }, ( subject: JQuery<any>, fn: (el: JQuery<any>) => void, options: Partial<Cypress.Loggable> ): Cypress.Chainable<JQuery<Element>> => { options = { log: true, ...options }; if (options.log) { Cypress.log({ name: 'withinEach', $el: subject, consoleProps: () => { return { 'Applied To': subject, Elements: subject?.length }; } }); } // TODO: support `.withinEach(options, callbackFn)` subject.each((_: number, element: Element) => { cy.wrap(element, LOG).within(LOG, fn); }); return cy.wrap(subject, LOG); } ); Cypress_Commands_add_Subject( 'ngxHover', { prevSubject: 'element' }, (subject: JQuery<any>, options: Partial<Cypress.Loggable>): Cypress.Chainable<JQuery<Element>> => { options = { log: true, ...options }; if (options.log) { Cypress.log({ name: 'hover', $el: subject, consoleProps: () => { return { 'Applied To': subject, Elements: subject?.length }; } }); } return cy .wrap(subject, LOG) .trigger('mouseover', LOG) .trigger('mouseenter', LOG) .invoke(LOG, 'addClass', 'cy-hover'); } ); Cypress_Commands_add_Subject( 'ngxUnhover', { prevSubject: 'element' }, (subject: JQuery<any>, options: Partial<Cypress.Loggable>): Cypress.Chainable<JQuery<Element>> => { options = { log: true, ...options }; if (options.log) { Cypress.log({ name: 'unhover', $el: subject, consoleProps: () => { return { 'Applied To': subject, Elements: subject?.length }; } }); } return cy .wrap(subject, LOG) .invoke(LOG, 'removeClass', 'cy-hover') .trigger('mouseleave', LOG) .trigger('mouseout', LOG); } ); /** * Like `cy.within` but also forces the element into a hover state. */ Cypress_Commands_add_Subject( 'whileHovering', { prevSubject: 'element' }, ( subject: JQuery<any>, fn: (currentSubject: JQuery<any>) => void, options: Partial<Cypress.Loggable> ): Cypress.Chainable<JQuery<Element>> => { options = { log: true, ...options }; if (options.log) { Cypress.log({ name: 'whileHovering', $el: subject, consoleProps: () => { return { 'Applied To': subject, Elements: subject?.length }; } }); } // TODO: support `.whileHovering(options, callbackFn)` cy.wrap(subject, LOG) .ngxHover(LOG) .within(LOG, fn) .iff( undefined, $el => { return cy.wrap($el, LOG).ngxUnhover(LOG); }, LOG ); return cy.wrap(subject, LOG); } ); /** * Like `cy.within` but only if the element exists in the DOM. */ Cypress_Commands_add_Subject( 'iff', { prevSubject: true }, ( subject: JQuery<any>, selector: string, fn, options: Partial<Cypress.Loggable> ): Cypress.Chainable<JQuery<Element>> => { options = { log: true, ...options }; if (options.log) { Cypress.log({ name: 'iff', $el: subject, message: selector, consoleProps: () => { return { 'Applied To': subject, Elements: subject?.length, Selector: selector }; } }); } // TODO: support `.iff(selector, options, callbackFn)` iff(subject, selector, fn); return cy.wrap(subject, LOG); } ); // -------------- Commands -------------- /** * Set ngx-ui-testing debug mode. */ Cypress.Commands.add('ngxDebug', (value: boolean): any => { LOG.log = value; }); /** * Given an ngx-ui element, returns the child native input element. */ Cypress_Commands_add_Subject( 'ngxFindNativeInput', { prevSubject: 'element' }, (subject: JQuery<any>, options: Partial<Cypress.Loggable> = {}): Cypress.Chainable<JQuery<Element>> => { options = { log: true, ...options }; const $el = findInput(subject); if (options.log) { Cypress.log({ name: 'ngxFindNativeInput', $el: subject, consoleProps: () => { return { 'Applied To': subject, Elements: subject?.length, Yielded: $el }; } }); } return cy.wrap($el, LOG); } ); /** * Given an element, returns the label element. */ Cypress_Commands_add_Subject( 'ngxFindLabel', { prevSubject: 'element' }, (subject: JQuery<any>, options: Partial<Cypress.Loggable> = {}): Cypress.Chainable<JQuery<Element>> => { options = { log: true, ...options }; const $el = findLabel(subject); if (options.log) { Cypress.log({ name: 'ngxFindLabel', $el: subject, consoleProps: () => { return { 'Applied To': subject, Elements: subject?.length, Yielded: $el }; } }); } return cy.wrap($el); } ); /** * Close all ngx-ui notifications, if any. */ Cypress.Commands.add('ngxCloseNotifications', () => { return cy.get('ngx-notification-container').iff('.ngx-notification-close', $el => $el.trigger('click')); }); Cypress_Commands_add_Subject( 'ngxOpen', { prevSubject: 'element' }, (subject: JQuery<any>, options: Partial<Cypress.Loggable> = {}): Cypress.Chainable<JQuery<Element>> => { options = { log: true, ...options }; if (options.log) { Cypress.log({ name: 'ngxOpen', $el: subject, consoleProps: () => { return { 'Applied To': subject, Elements: subject?.length }; } }); } switch (subject.prop('tagName').toLowerCase()) { case NGX.SELECT: case NGX.SECTION: case NGX.DROPDOWN: case NGX.PLUS_MENU: case NGX.NAG: return cy.wrap(subject, LOG).withinEach(open, LOG); } return; // THROW ERROR } ); Cypress_Commands_add_Subject( 'ngxClose', { prevSubject: 'element' }, (subject: JQuery<any>, options: Partial<Cypress.Loggable> = {}): Cypress.Chainable<JQuery<Element>> => { options = { log: true, ...options }; if (options.log) { Cypress.log({ name: 'ngxClose', $el: subject, consoleProps: () => { return { 'Applied To': subject, Elements: subject?.length }; } }); } switch (subject.prop('tagName').toLowerCase()) { case NGX.SELECT: case NGX.SECTION: case NGX.DROPDOWN: case NGX.PLUS_MENU: case NGX.LFD: case NGX.NOTIFICATION: case NGX.NAG: case NGX.ALERT: case NGX.DRAWER: return cy.wrap(subject, LOG).withinEach(close, LOG); } return; // THROW ERROR } ); /** * Like `cy.type` but clears existing text before and works with ngx-ui elements. */ Cypress_Commands_add_Subject( 'ngxFill', { prevSubject: 'element' }, ( subject: JQuery<any>, text?: string, options: Partial<Cypress.Loggable> = {} ): Cypress.Chainable<JQuery<Element>> => { options = { log: true, ...options }; if (options.log) { Cypress.log({ name: 'ngxFill', $el: subject, consoleProps: () => { return { 'Applied To': subject, Elements: subject?.length, text }; } }); } return cy.wrap(subject, LOG).each(el => fillValue(el, text, options)); } ); /** * Given an element, returns the element's value. */ Cypress_Commands_add_Subject( 'ngxGetValue', { prevSubject: 'element' }, ( subject: JQuery<any>, options: Partial<Cypress.Loggable> = {} ): Cypress.Chainable<string | number | string[] | undefined | boolean> => { options = { log: true, ...options }; const value = getValue(subject); if (options.log) { Cypress.log({ name: 'ngxGetValue', $el: subject, consoleProps: () => { return { 'Applied To': subject, Elements: subject?.length, Returned: value }; } }); } return cy.wrap(value); } ); /** * Set an elements value directly */ Cypress_Commands_add_Subject( 'ngxSetValue', { prevSubject: 'element' }, ( subject: JQuery<any>, text?: string, options: Partial<Cypress.Loggable> = {} ): Cypress.Chainable<JQuery<Element>> => { options = { log: true, ...options }; if (options.log) { Cypress.log({ name: 'ngxSetValue', $el: subject, consoleProps: () => { return { 'Applied To': subject, Elements: subject?.length, Value: text }; } }); } return cy.wrap(subject, LOG).each(el => setValue(el, text)); } ); Cypress_Commands_add_Subject( 'ngxSelectTab', { prevSubject: 'element' }, ( subject: JQuery<any>, textOrIndex: string | number, options: Partial<Cypress.Loggable> = {} ): Cypress.Chainable<JQuery<Element>> => { options = { log: true, ...options }; if (options.log) { Cypress.log({ name: 'ngxSelectTab', $el: subject, consoleProps: () => { return { 'Applied To': subject, Elements: subject?.length }; } }); } switch (subject.prop('tagName').toLowerCase()) { case NGX.TABS: return cy.wrap(subject, LOG).withinEach(() => { if (typeof textOrIndex === 'number') { cy.get('.ngx-tabs-list button.ngx-tab').eq(textOrIndex).click(); } else { cy.get('.ngx-tabs-list button.ngx-tab').contains(textOrIndex).click(); } }, LOG); } return; // THROW ERROR } );
the_stack
import { ISvgJsonElement, ISvgJsonRoot } from "./svgjson"; import { TagBuilder } from "./tag-builder"; enum ENodeKind { root, element } interface ENode { parent?: ENode; is_group?: boolean; tag?: string; element?: ISvgJsonElement; repeats?: number; chilren: Array<ENode>; textContent?: string; attributes: any; attribute_defaults?: Array<string>; } interface IMatchInfo { index: number; texts: Array<string>; endIndex: number; } // 参考标准: // https://docs.emmet.io/abbreviations/syntax/ const FULL_EXP = /([\.#]?[a-z0-9_\$@-]+)|[>\^\+\*\(\)\[\]=]|("[^"]*")|('[^']*')|(\{[^\}]*\})|((?<=\[[^\]]*)\s+)/gi; const NAME_EXP = /^[a-z0-9_-]+$/i; const STR_EXP = /^"[^"]*"$/; const STR_EXP2 = /^'[^']*'$/; const NUM_EXP = /^[0-9]+$/; const WS_EXP = /^\s+$/; const NO_EMMET_TAGS = ['script']; function is_name(name: string) { return NAME_EXP.test(name); } function is_number(num: string) { return NUM_EXP.test(num); } function replace_number(str: string, current: number, count: number) { return str.replace(/(\$+)(\@(\-|(\d+))?)?/g, (_1, s, _2, flag, start)=>{ let nostr = current.toString(); if(start) { nostr = (current + parseInt(start) - 1).toString(); } else if(flag) { nostr = (count - current + 1).toString(); } if(nostr.length >= s.length) { return nostr; } return '0'.repeat(s.length - nostr.length) + nostr; }); } export function execAll(input: string) : Array<IMatchInfo> { const matches: Array<IMatchInfo> = []; let matchInfo : IMatchInfo | null = null; let matched: RegExpExecArray | null = null; let matchIndex = -1; while(matched = FULL_EXP.exec(input)) { if(matchIndex == matched.index) { break; } matchIndex = matched.index; if(!matchInfo || matchInfo.endIndex < matched.index) { matchInfo = { index: matched.index, texts: [], endIndex: matched.index}; matches.push(matchInfo); } let matchPart = matched[0]; matchInfo.texts.push(matchPart); matchInfo.endIndex += matchPart.length; } return matches; } export class ENodeBuilder { /** 调试模式 */ debug = false; /** * 默认顶层标签 */ defaultTagName = "svg"; /** 使用标签树关系过滤下层可用标签 */ defaultTagUseTree = false; /** * 是否生成 Snippet 变量参数 */ useSnippet = true; root!: ENode; current!: ENode; elementNames: Array<string>; constructor(public svginfo: ISvgJsonRoot) { this.elementNames = Object.keys(svginfo.elements); // console.debug('this.elementNames', this.elementNames); this.root = { attributes: {}, chilren: [] }; } _plusNode() { if(this.current == this.root) { this.root = { is_group: true, attributes: {}, chilren: [this.current] }; this.current.parent = this.root; } const nextcurrent = { parent : this.current.parent, attributes: {}, chilren: [] }; this.current.parent!.chilren.push(nextcurrent); this.current = nextcurrent; } partStartIndex: number = 0; partStartOffset: number = 0; parse(parts: Array<string>) { this.current = this.root; this.partStartIndex = 0; const len = parts.length; let offset = 0; const groupInfo : Array<ENode> = []; let idx = 0; let next = function() { idx++; let p = parts[idx]; offset += p.length; return p; }; while(idx < len) { let part = parts[idx]; offset+=part.length; switch(part) { case '(': // 分组开始 { this.current.is_group = true; groupInfo.push(this.current); let newcurrent : ENode = { chilren:[], attributes:{}, parent:this.current }; this.current.chilren.push(newcurrent); this.current = newcurrent; } break; case ')': // 分组结束 { let newcurrent = groupInfo.pop(); if(newcurrent) { this.current = newcurrent; } } break; case '[': // 属性定义开始 { while(true){ part = next(); if (!is_name(part)) { if(this.debug) { console.debug('属性名检查失败', part, idx); } return false; } let attrname = part; offset += attrname.length; part = next(); if (part == ']') { // 无值属性名 this.current.attributes[attrname] = ''; break; } else if (part !== '=') { if(this.debug) { console.debug('属性名之后期待 =', part); } return false; } part = next(); if (part == ']') { // 无值属性名 this.current.attributes[attrname] = ''; break; } else if (STR_EXP.test(part) || STR_EXP2.test(part)) { this.current.attributes[attrname] = part.substring(1, part.length - 1); } else if (is_name(part)) { this.current.attributes[attrname] = part; } else { if(this.debug) { console.debug('= 号之后没有属性值', part); } return false; } part = parts[idx+1]; if(WS_EXP.test(part)) { // 属性间空间,直接忽略 next(); part = parts[idx+1]; } if (part == ']') { // 属性声明正常结束 next(); break; } else if(is_name(part)) { // 新的属性声明开始 continue; } else { if(this.debug) { console.debug('期待 ] 或属性名', part); } return false; } } } break; case '^': if(this.current.parent) { this.current = this.current.parent; this._plusNode(); } break; case '=': if(this.debug) { console.debug('未知位置出现 ='); } return false; case '>': this.current = { parent : this.current, attributes: {}, chilren: [] }; this.current.parent!.chilren.push(this.current); break; case '+': this._plusNode(); break; case '*': { // NUMBER MODE let numpart = part = parts[idx+1]; if(is_number(numpart)) { this.current.repeats = parseInt(numpart); offset += part.length; idx++; } else { if(this.debug) { console.debug('* 号后面不是数字', numpart, typeof(numpart)); } return false; } } break; default: if(part.startsWith('{')){ this.current.chilren.push({ textContent: part.substring(1, part.length-1), attributes: {}, chilren: [] }); } else if(part.startsWith('#')){ this.current.attributes.id = part.substring(1); } else if(part.startsWith('.')) { if(this.current.attributes.class) { this.current.attributes.class += ' ' + part.substring(1); } else { this.current.attributes.class = part.substring(1); } } else { // console.debug('part', part); this.current.tag = part; // 全名匹配 this.current.element = this.svginfo.elements[this.current.tag.toLowerCase()]; if(!this.current.element) { // 缩写匹配 if(part in this.svginfo.elementNameMap) { part = this.svginfo.elementNameMap[part]; } // 开头匹配 this.current.tag = this.elementNames.find(n=>n.startsWith(part) && !NO_EMMET_TAGS.includes(n)); // 包含匹配 if(!this.current.tag) { this.current.tag = this.elementNames.find(n=>n.includes(part) && !NO_EMMET_TAGS.includes(n)); } if(this.current.tag) { this.current.element = this.svginfo.elements[this.current.tag]; break; } // 无效的数据,重设可区域开始到下一个位置 if(this.debug) { console.warn('RSET PART START', part); } this.partStartIndex = idx + 1; this.partStartOffset = offset; this.current = this.root = { chilren: [], attributes: {} }; } } } idx++; } if(this.debug && this.partStartIndex >= parts.length) { console.debug('partStartIndex', this.partStartIndex); } return this.partStartIndex < parts.length; } private indent: string = ' '; public get indentSize() : number { return this.indent.length; } public set indentSize(value: number) { if(value <= 0) { throw new Error('indentSize can not be negative.'); } this.indent = ' '.repeat(value); } getDefaultTagForParent(parentTag: string | null) { if(parentTag) { let pt = this.svginfo.elements[parentTag]; if(pt && pt.subElements && pt.subElements.length) { return pt.subElements[0]; } } return null; } private snippetIndex = 0; private snippetOutputIndex = 0; private lastSnippetValued = false; newSnippetAttribute(builder: TagBuilder, value?: string) { this.snippetIndex++; this.snippetOutputIndex = builder.output.length; if(value) { this.lastSnippetValued = true; return `$\{${this.snippetIndex}:${value}\}`; } this.lastSnippetValued = false; return `$${this.snippetIndex}`; } buildNode(outputs: TagBuilder, node: ENode, indentLevel: number = 0, contextNumber: number = 1, contextCount: number = 1, inline = false) { let startNumber = 1; let endNumber = 1; let countNumber = contextCount; if(node.repeats) { endNumber = node.repeats; countNumber = node.repeats; } let nodeInline = inline || !!(node.element && node.element.inline); let nodeSimple = !!(node.element && node.element.simple && !node.element.subElements); // 处理默认元素名 if(!node.tag && (node.attributes.class || node.attributes.id || Object.keys(node.attributes).length)) { let parentTag = outputs.getOpenTagName(); node.tag = this.defaultTagUseTree && parentTag && this.getDefaultTagForParent(parentTag && parentTag.name) || this.defaultTagName; if(this.debug) { console.debug('New CHILD for', parentTag, node.tag); } node.element = this.svginfo.elements[node.tag.toLowerCase()]; } for(let i = startNumber; i <= endNumber; i++) { let currentNumber = node.repeats ? i : contextNumber; // 输出文本内容 if(node.textContent) { outputs.addText(replace_number(node.textContent, currentNumber, countNumber)); return; } const currentTagStart = !node.is_group && node.tag; // 输出开始标签属性 if(currentTagStart) { // 开始标签 outputs.startTag(node.tag!, nodeInline, nodeSimple); // 开始属性 if(node.element && node.element.defaultAttributes) { // 如果需要默认属性 for(var attrname in node.element.defaultAttributes) { if(node.attributes && attrname in node.attributes) { continue; } // outputs.addAttribute(attrname, node.element.defaultAttributes[attrname]); if(this.useSnippet) { outputs.addAttribute(attrname, this.newSnippetAttribute(outputs, node.element.defaultAttributes[attrname])); } else { outputs.addAttribute(attrname, ''); } } } if(node.attributes) { for(var attrname in node.attributes) { outputs.addAttribute(attrname, replace_number(node.attributes[attrname], currentNumber, countNumber)); } } } // 填充子元素 if(node.chilren && node.chilren.length) { let childrenlevel = indentLevel + 1; if(node.is_group || nodeInline) { childrenlevel = indentLevel; } for(var child of node.chilren) { this.buildNode(outputs, child, childrenlevel, currentNumber, 1, nodeInline); } } else { if(this.useSnippet && !node.is_group && !inline) { outputs.addText(this.newSnippetAttribute(outputs)); } } if(currentTagStart) { outputs.endTag(); } } } private replace_index = 0; toCode(): string { this.snippetIndex = 0; this.snippetOutputIndex = 0; this.lastSnippetValued = false; const builder = new TagBuilder(); builder.indent = this.indent; this.replace_index = 0; this.buildNode(builder, this.root); if(this.useSnippet) { if(this.snippetIndex > 0) { if(this.lastSnippetValued) { return builder.toString() + '$0'; } for(var i=this.snippetOutputIndex;i<builder.output.length;i++) { if(builder.output[i].includes('$' + this.snippetIndex)){ builder.output[i] = builder.output[i].replace('$' + this.snippetIndex, '$0'); break; } } } } return builder.toString(); } }
the_stack
import _ from 'lodash' import {ActionGroupSpec, ActionContextType, ActionOutputStyle, ActionOutput, ActionContextOrder, SelectionType} from '../actions/actionSpec' import K8sFunctions from '../k8s/k8sFunctions' import IstioFunctions from '../k8s/istioFunctions' import ChoiceManager, {ItemSelection} from '../actions/choiceManager' import { MtlsUtil, ClientMtlsMode } from '../k8s/mtlsUtil'; const plugin : ActionGroupSpec = { context: ActionContextType.Istio, title: "Analysis Recipes", order: ActionContextOrder.Analysis, actions: [ { name: "Analyze Service mTLS Status", order: 2, selectionType: SelectionType.Service, loadingMessage: "Loading Services...", choose: ChoiceManager.chooseService.bind(ChoiceManager, 1, 5), async act(actionContext) { const selections = await ChoiceManager.getServiceSelections(actionContext) this.directAct && this.directAct(selections) }, async directAct(selections) { this.showTitle(selections) this.showOutputLoading && this.showOutputLoading(true) const globalMtlsStatuses = {} const clusterServiceMtlsStatuses = {} const clusters = this.actionContext.getClusters() for(const cluster of clusters) { globalMtlsStatuses[cluster.name] = await MtlsUtil.getGlobalMtlsStatus(cluster.k8sClient) const clusterServices = selections.filter(s => s.cluster === cluster.name).map(s => s.item) clusterServiceMtlsStatuses[cluster.name] = await MtlsUtil.getServiceMtlsStatuses(cluster.k8sClient, clusterServices) } for(const selection of selections) { const cluster = this.actionContext.getClusters().filter(c => c.name === selection.cluster)[0] const service = selection.item const output: ActionOutput = [] output.push([">" + service.name+"."+service.namespace+" @ "+cluster.name, ""]) if(!cluster.hasIstio) { output.push([">>Istio not installed", ""]) this.onStreamOutput && this.onStreamOutput(output) continue } const globalMtlsStatus = globalMtlsStatuses[cluster.name] const serviceMtlsStatuses = clusterServiceMtlsStatuses[cluster.name] const namespaceMtlsStatus = serviceMtlsStatuses[service.namespace] const serviceMtlsStatus = namespaceMtlsStatus[service.name] output.push(["Cluster mTLS", globalMtlsStatus.globalMtlsMode || "Disabled"]) output.push(["Namespace Default mTLS", namespaceMtlsStatus.namespaceDefaultMtlsMode || "N/A"]) output.push(["Envoy Sidecar Status", serviceMtlsStatus.hasSidecar ? "Sidecar Proxy Present" : "Sidecar Proxy Not Deployed"]) this.outputServicePolicies(serviceMtlsStatus, output) this.outputServiceDestinationRules(serviceMtlsStatus, output) const portNumbers: any[] = ["##Port"] const portMtls: any[] = ["mTLS"] const clientAccess: any[] = ["Client Access"] const policyConflicts: any[] = ["Policy Conflicts"] const drConflicts: any[] = ["DR Conflicts"] const impactedClients: any[] = ["Impacted Clients"] const portsAnalysis: any[] = [] this.generatePortTable(service, serviceMtlsStatus, namespaceMtlsStatus, globalMtlsStatus, portNumbers, portMtls, clientAccess, policyConflicts, drConflicts, impactedClients) const portTable: any[] = [] portNumbers.forEach((p,i) => { portTable.push([portNumbers[i], portMtls[i], clientAccess[i], policyConflicts[i], drConflicts[i], impactedClients[i]]) }) output.push([]) output.push([">>>Service Ports"]) output.push(portTable) output.push([]) output.push(...portsAnalysis) this.onStreamOutput && this.onStreamOutput(output) } this.showOutputLoading && this.showOutputLoading(false) }, showTitle(selections) { if(selections && selections.length > 0){ const servicesTitle = selections.map(s => "["+s.name+"."+s.namespace+"@"+s.cluster+"]").join(", ") this.onOutput && this.onOutput([["mTLS Analysis for Service " + servicesTitle, ""]], ActionOutputStyle.Table) } else { this.onOutput && this.onOutput([["Service mTLS Analysis", ""]], ActionOutputStyle.Table) } }, refresh(actionContext) { this.act(actionContext) }, filterSelections(selections) { return selections && selections.length > 0 ? selections.slice(0, 5) : [] }, outputServicePolicies(serviceMtlsStatus, output) { output.push([]) output.push([">>>Relevant Service mTLS Policies", ""]) serviceMtlsStatus.mtlsPolicies.length === 0 && output.push(["", "No Policies"]) serviceMtlsStatus.mtlsPolicies.forEach(sp => { delete sp.labels delete sp.annotations output.push([sp.name, sp]) }) }, outputServiceDestinationRules(serviceMtlsStatus, output) { output.push([]) output.push([">>>Relevant mTLS DestinationRules", ""]) serviceMtlsStatus.mtlsDestinationRules.length === 0 && output.push(["","No DestinationRules"]) serviceMtlsStatus.mtlsDestinationRules.forEach(dr => { delete dr.labels delete dr.annotations output.push([dr.name, dr]) }) }, generatePortTable(service, serviceMtlsStatus, namespaceMtlsStatus, globalMtlsStatus, portNumbers, portMtls, clientAccess, policyConflicts, drConflicts, impactedClients) { service.ports.forEach(sp => { portNumbers.push(sp.port) const portStatus = serviceMtlsStatus.servicePortAccess[sp.port] const portDefaultMtlsDestinationRuleStatus = serviceMtlsStatus.servicePortDefaultMtlsDestinationRuleStatus[sp.port] const servicePortClientMtlsModes = serviceMtlsStatus.effectiveServicePortClientMtlsModes[sp.port] const portMtlsModes = serviceMtlsStatus.effectiveServicePortMtlsModes[sp.port] const portMtlsMode = portStatus.service.conflict ? "[CONFLICT] " + portMtlsModes.join(", ") : !portStatus.service.mtls ? ClientMtlsMode.DISABLE : portStatus.service.servicePortMtlsMode ? portStatus.service.servicePortMtlsMode : namespaceMtlsStatus.namespaceDefaultMtlsMode ? namespaceMtlsStatus.namespaceDefaultMtlsMode : globalMtlsStatus.globalMtlsMode || "N/A" portMtls.push(portMtlsMode) policyConflicts.push(portStatus.service.conflict ? "[Found Policy Conflicts]" : "[No]") const clientNamespacesWithDRPolicyConflicts = Object.keys(portStatus.client.clientNamespacesInConflictWithMtlsPolicy) const clientNamespacesWithConflicts = portStatus.client.clientNamespacesWithMtlsConflicts .concat(clientNamespacesWithDRPolicyConflicts) const impactedClientItems: any[] = [] impactedClientItems.push(clientNamespacesWithConflicts.length === 0 ? "" : clientNamespacesWithConflicts.map(n => n.length > 0 ? n : "[All Sidecar Clients]")) clientNamespacesWithConflicts.length === 1 && clientNamespacesWithConflicts[0] === "" && portStatus.client.sidecarAccessNamespaces.length > 0 && impactedClientItems.push(" (Except: " + portStatus.client.sidecarAccessNamespaces.map(ns => ns.namespace).join(", ") + ")") if(impactedClientItems.length > 0) { impactedClients.push(...impactedClientItems) } let drConflictsItems: any[] = [] if(portStatus.client.conflict) { if(portStatus.client.clientNamespacesWithMtlsConflicts.length > 0) { portStatus.client.clientNamespacesWithMtlsConflicts.forEach(ns => { const rules = _.uniqBy(servicePortClientMtlsModes[ns].map(info => info.dr.name+"."+info.dr.namespace)) drConflictsItems.push(rules.join(", ")) }) } if(clientNamespacesWithDRPolicyConflicts.length > 0) { clientNamespacesWithDRPolicyConflicts.forEach(ns => { const destRules = portStatus.client.clientNamespacesInConflictWithMtlsPolicy[ns] const ruleNames = _.uniqBy(destRules.map(dr => dr.name+"."+dr.namespace)) drConflictsItems.push(ruleNames.join(", ")) }) } } if(drConflictsItems.length > 0) { drConflictsItems = _.uniqBy(drConflictsItems) drConflicts.push(drConflictsItems) } else {//if(!portStatus.client.conflict && clientNamespacesWithConflicts.length === 0) { drConflicts.push("[No]") } let clientAccessConflictMessage = portStatus.client.noAccess ? "[Blocked for all clients]" : portStatus.client.allAccess ? drConflictsItems.length === 0 ? "[Open to all clients]" : "[Open to all clients]<br/>[Found DR conflicts]" : portStatus.client.nonSidecarOnly ? "[Non-Sidecar Clients Only]" : portStatus.client.sidecarOnly ? drConflictsItems.length > 0 ? "[All sidecar clients except DR conflicts]" : portDefaultMtlsDestinationRuleStatus.onlyDefaultMtlsDestinationRuleDefined ? "[All sidecar clients]" : "[Select sidecar clients (see DR)]" : portStatus.client.conflict ? "[Some namespaces have conflicts]" : "" clientAccessConflictMessage.length > 0 && clientAccess.push(clientAccessConflictMessage) }) }, performPortAnalysis(service, serviceMtlsStatus, namespaceMtlsStatus, globalMtlsStatus, portNumbers, portMtls, policyConflicts, drConflicts, impactedClients, portsAnalysis) { service.ports.forEach(sp => { portsAnalysis.push([">>>Service Port " + sp.port + " Analysis"]) portNumbers.push(sp.port) const portStatus = serviceMtlsStatus.servicePortAccess[sp.port] const portMtlsModes = serviceMtlsStatus.effectiveServicePortMtlsModes[sp.port] const servicePortClientMtlsModes = serviceMtlsStatus.effectiveServicePortClientMtlsModes[sp.port] const portMtlsMode = portStatus.service.conflict ? "[CONFLICT] " + portMtlsModes.join(",") : !portStatus.service.mtls ? "N/A" : portStatus.service.servicePortMtlsMode ? portStatus.service.servicePortMtlsMode : namespaceMtlsStatus.namespaceDefaultMtlsMode ? namespaceMtlsStatus.namespaceDefaultMtlsMode : globalMtlsStatus.globalMtlsMode || "N/A" portMtls.push(portMtlsMode) policyConflicts.push(portStatus.service.conflict ? "[Found Policy Conflicts]" : "[No]") const clientNamespacesWithDRPolicyConflicts = Object.keys(portStatus.client.clientNamespacesInConflictWithMtlsPolicy) const clientNamespacesWithConflicts = portStatus.client.clientNamespacesWithMtlsConflicts .concat(clientNamespacesWithDRPolicyConflicts) const clientConflictInfo: any[] = [] impactedClients.push(clientNamespacesWithConflicts.length === 0 ? "" : clientNamespacesWithConflicts.map(n => n.length > 0 ? n : "[All Sidecar Clients]").join(", ") + (clientNamespacesWithConflicts.length === 1 && clientNamespacesWithConflicts[0] === "" && portStatus.client.sidecarAccessNamespaces.length > 0 ? " (Except: " + portStatus.client.sidecarAccessNamespaces.map(ns => ns.namespace).join(", ") + ")" : "") ) if(portStatus.client.conflict) { if(portStatus.client.clientNamespacesWithMtlsConflicts.length > 0) { portStatus.client.clientNamespacesWithMtlsConflicts.forEach(ns => { const rules = _.uniqBy(servicePortClientMtlsModes[ns].map(info => info.dr.name+"."+info.dr.namespace)).join(", ") drConflicts.push(rules) servicePortClientMtlsModes[ns].map(data => { const rule = data.dr.name + "." + data.dr.namespace clientConflictInfo.push(["Rule [" + rule + "] for " + (ns.length > 0 ? " namespace ["+ns+"]" : "all sidecar clients") + " uses mTLS mode [" + data.mode + "]"]) }) }) } if(clientNamespacesWithDRPolicyConflicts.length > 0) { clientNamespacesWithDRPolicyConflicts.forEach(ns => { const destRules = portStatus.client.clientNamespacesInConflictWithMtlsPolicy[ns] const ruleNames = _.uniqBy(destRules.map(dr => dr.name+"."+dr.namespace)).join(", ") drConflicts.push(ruleNames) servicePortClientMtlsModes[ns].map(data => { const rule = data.dr.name + "." + data.dr.namespace clientConflictInfo.push([ "Rule [" + rule + "] uses mTLS mode [" + data.mode + "] for " + (ns.length > 0 ? " namespace ["+ns+"]" : "all sidecar clients") + (serviceMtlsStatus.hasSidecar ? " whereas service port mTLS mode is [" + portMtlsMode + "]" : " whereas service runs without sidecar and does not support mTLS") ]) }) }) } } if(!portStatus.client.conflict && clientNamespacesWithConflicts.length === 0) { drConflicts.push("No Conflicts") } clientConflictInfo.length > 0 && portsAnalysis.push(["DR Conflicts", clientConflictInfo]) const clientAccess: any[] = [] let clientAccessConflictMessage = portStatus.client.noAccess ? "Blocked for all clients" : portStatus.client.allAccess ? "Open to all clients" : portStatus.client.nonSidecarOnly ? "Non-Sidecar Clients Only" : portStatus.client.sidecarOnly ? "Sidecar Clients Only" : portStatus.client.conflict ? "One or more client namespaces have conflicts" : "" clientAccessConflictMessage.length > 0 && clientAccess.push([clientAccessConflictMessage]) const accessAnalysis: any[] = [] if(namespaceMtlsStatus.namespaceDefaultMtlsMode) { if(portStatus.service.servicePortMtlsMode && namespaceMtlsStatus.namespaceDefaultMtlsMode !== portStatus.service.servicePortMtlsMode) { accessAnalysis.push("Service policy has overridden mTLS mode from namespace default of [" + namespaceMtlsStatus.namespaceDefaultMtlsMode + "] to [" + portStatus.service.servicePortMtlsMode + "]") } } else { if(portStatus.service.servicePortMtlsMode && globalMtlsStatus.globalMtlsMode !== portStatus.service.servicePortMtlsMode) { accessAnalysis.push("Service policy has overridden mTLS mode from global default of [" + globalMtlsStatus.globalMtlsMode + "] to [" + portStatus.service.servicePortMtlsMode + "]") } } if(portStatus.service.conflict) { accessAnalysis.push("Service policies have conflicting mTLS configuration") accessAnalysis.push("Port mTLS Modes: " + serviceMtlsStatus.effectiveServicePortMtlsModes[sp.port]) } else { portStatus.service.mtls && portStatus.service.permissive && accessAnalysis.push("Service has given PERMISSIVE mTLS access to allow access without a sidecar") portStatus.service.mtls && !portStatus.service.permissive && accessAnalysis.push("Service requires STRICT mTLS access, and cannot be accessed without a sidecar") portStatus.client.noDestinationRules && portStatus.service.permissive && accessAnalysis.push("No DestinationRule is defined to configure mTLS, so sidecar clients will also access without mTLS") portStatus.service.mtls && !portStatus.service.permissive && portStatus.client.noDestinationRules && accessAnalysis.push("Sidecar mTLS access requires a DestinationRule, but none are defined for this port") if(clientNamespacesWithConflicts.length > 0) { portStatus.client.clientNamespacesWithMtlsConflicts.forEach(ns => { accessAnalysis.push((ns.length > 0 ? "Sidecar clients in Namespace [" + ns + "]" : "All sidecar clients") + " are blocked due to DestinationRule [" + (ns.dr ? ns.dr.name : "") + "]") }) clientNamespacesWithDRPolicyConflicts.forEach(ns => { const destRules = portStatus.client.clientNamespacesInConflictWithMtlsPolicy[ns] const ruleNames = _.uniqBy(destRules.map(dr => dr.name+"."+dr.namespace)).join(", ") accessAnalysis.push((ns.length > 0 ? "Sidecar clients in Namespace [" + ns + "]" : "All sidecar clients") + " are blocked due to DestinationRules [" + ruleNames + "]") }) } portStatus.client.sidecarAccessNamespaces.forEach(s => { if(s.dr) { accessAnalysis.push((s.namespace.length > 0 ? "Clients in Namespace [" + s.namespace + "]" : portStatus.client.conflict ? "All other client namespaces" : "All client namespaces") + " can access via sidecar using DestinationRule [" + s.dr.name+"."+s.dr.namespace + "]" ) } else { accessAnalysis.push((s.namespace.length > 0 ? "Clients in Namespace [" + s.namespace + "]" : portStatus.client.conflict ? "All other client namespaces" : "All client namespaces") + " can access via sidecar without any DestinationRule as mTLS is not required by the service" ) } }) } clientAccess.push(accessAnalysis) portsAnalysis.push(["Client Access", clientAccess]) if(portStatus.client.sidecarAccessNamespaces.length > 0) { const exceptions: string[] = [] clientNamespacesWithDRPolicyConflicts.forEach(ns => ns.length > 0 && exceptions.push(ns)) portStatus.client.clientNamespacesWithMtlsConflicts.forEach(ns => ns.length > 0 && exceptions.push(ns)) portsAnalysis.push(["Client Namespaces with Sidecar access", portStatus.client.sidecarAccessNamespaces.map(ns => ns.namespace.length > 0 ? ns.namespace : "All") + (exceptions.length > 0 ? " (Except: " + exceptions.join(", ") + ")" : "") ]) } }) } } ], } export default plugin
the_stack
import * as React from "react"; import { Route } from "react-router-dom"; import service from "./../services/service"; import Spinner from "./../components/Spinner"; import MoreVertIcon from "material-ui/svg-icons/navigation/more-vert"; import { Chip, Divider, Dialog, FlatButton, IconButton, IconMenu, List, ListItem, MenuItem, Paper, RaisedButton, TextField } from "material-ui"; import { Debounce } from "./../utils/debounce"; import { WorkspaceConfig } from "../../global-types"; const Fragment = React.Fragment; const MAX_RECORDS = 200; type DeleteItemKeyDialogProps = { busy: boolean; itemLabel: string; handleClose: () => void; handleConfirm: (key: string) => void; }; type DeleteItemKeyDialogState = { value: string; valid?: boolean; }; class DeleteItemKeyDialog extends React.Component<DeleteItemKeyDialogProps, DeleteItemKeyDialogState> { constructor(props: DeleteItemKeyDialogProps) { super(props); this.state = { value: "" }; } handleClose() { if (this.props.handleClose && !this.props.busy) this.props.handleClose(); } handleConfirm() { if (this.props.handleConfirm) this.props.handleConfirm(this.state.value); } render() { let { busy, itemLabel } = this.props; return ( <Dialog title={"Delete Item"} modal={true} open={true} onRequestClose={this.handleClose} actions={[ <FlatButton disabled={busy} primary={true} label="Cancel" onClick={this.handleClose.bind(this)} />, <FlatButton disabled={busy} primary={true} label="Delete" onClick={this.handleConfirm.bind(this)} /> ]} > {this.state.valid ? ( undefined ) : ( <p> Do you really want to delete the item <b>"{itemLabel}"</b>? </p> )} {busy ? <Spinner /> : undefined} </Dialog> ); } } type EditItemKeyDialogProps = { busy: boolean; value?: string; title?: string; confirmLabel: string; handleClose: () => void; handleConfirm: (value: string, initialValue: string) => void; }; type EditItemKeyDialogState = { value: string; initialValue: string; valid?: boolean; }; class EditItemKeyDialog extends React.Component<EditItemKeyDialogProps, EditItemKeyDialogState> { constructor(props: EditItemKeyDialogProps) { super(props); this.state = { value: props.value || "", initialValue: props.value || "" }; } handleClose() { if (this.props.handleClose && !this.props.busy) this.props.handleClose(); } handleConfirm() { if (this.validate() && this.props.handleConfirm) this.props.handleConfirm(this.state.value, this.state.initialValue); } validate() { let value = this.state.value || ""; return /^[a-zA-Z0-9_-]+([/][a-zA-Z0-9_-]+)*$/.test(value) && value.length > 0; } handleChange = (e: any) => { this.setState({ value: e.target.value }); }; render() { let { busy, confirmLabel } = this.props; let valid = this.validate(); return ( <Dialog title={this.props.title} contentStyle={{ maxWidth: "600px" }} modal={true} open={true} onRequestClose={this.handleClose} actions={[ <FlatButton disabled={busy} primary={true} label="Cancel" onClick={this.handleClose.bind(this)} />, <FlatButton disabled={busy || !valid} primary={true} label={confirmLabel} onClick={this.handleConfirm.bind(this)} /> ]} > <TextField floatingLabelText="Item Name" value={this.state.value} disabled={busy} onChange={this.handleChange} floatingLabelFixed={true} underlineShow={true} fullWidth={true} /> {this.state.valid ? undefined : <p>Allowed characters: alphanumeric, dash, underline and slash.</p>} {busy ? <Spinner /> : undefined} </Dialog> ); } } type CollectionProps = { siteKey: string; workspaceKey: string; collectionKey: string; }; type CollectionState = { selectedWorkspaceDetails: WorkspaceConfig | null; filter: string; items?: Array<{ key: string; label: string }>; filteredItems: Array<{ key: string; label: string }>; trunked: boolean; view?: { key?: string; item: any }; modalBusy: boolean; dirs: Array<string>; }; class CollectionListItems extends React.PureComponent<{ filteredItems: Array<any>; onItemClick: (item: any) => void; onRenameItemClick: (item: any) => void; onDeleteItemClick: (item: any) => void; }> { render() { let { filteredItems, onItemClick, onRenameItemClick, onDeleteItemClick } = this.props; return ( <React.Fragment> {filteredItems.map((item, index) => { let iconButtonElement = ( <IconButton touch={true}> <MoreVertIcon /> </IconButton> ); let rightIconMenu = ( <IconMenu iconButtonElement={iconButtonElement}> <MenuItem onClick={() => onRenameItemClick(item)}>Rename</MenuItem> <MenuItem onClick={() => onDeleteItemClick(item)}>Delete</MenuItem> </IconMenu> ); return ( <Fragment key={item.key}> {index !== 0 ? <Divider /> : undefined} <ListItem primaryText={item.label || item.key} onClick={() => { onItemClick(item); }} rightIconButton={rightIconMenu} /> </Fragment> ); })} </React.Fragment> ); } } class Collection extends React.Component<CollectionProps, CollectionState> { filterDebounce = new Debounce(200); history: any; constructor(props: CollectionProps) { super(props); this.state = { selectedWorkspaceDetails: null, filter: "", filteredItems: [], trunked: false, modalBusy: false, dirs: [] }; } setCreateItemView() { this.setState({ view: { key: "createItem", item: null }, modalBusy: false }); } setRenameItemView(item: any) { this.setState({ view: { key: "renameItem", item }, modalBusy: false }); } setDeleteItemView(item: any) { this.setState({ view: { key: "deleteItem", item }, modalBusy: false }); } setRootView() { this.setState({ view: undefined, modalBusy: false }); } componentWillMount() { service.registerListener(this); } componentDidMount() { this.refreshItems(); } refreshItems() { let stateUpdate: any = {}; const { siteKey, workspaceKey, collectionKey } = this.props; if (siteKey && workspaceKey && collectionKey) { Promise.all([ service.api.listCollectionItems(siteKey, workspaceKey, collectionKey).then(items => { stateUpdate.items = items; stateUpdate = { ...stateUpdate, ...this.resolveFilteredItems(items) }; }), service.api.getWorkspaceDetails(siteKey, workspaceKey).then(workspaceDetails => { stateUpdate.selectedWorkspaceDetails = workspaceDetails; }) ]) .then(() => { this.setState(stateUpdate); }) .catch(e => {}); } } componentWillUnmount() { service.unregisterListener(this); } deleteCollectionItem() { let { siteKey, workspaceKey, collectionKey } = this.props; const view = this.state.view; if (view == null) return; service.api.deleteCollectionItem(siteKey, workspaceKey, collectionKey, view.item.key).then( () => { let itemsCopy: Array<any> = (this.state.items || []).slice(0); let itemIndex = itemsCopy.findIndex(x => x.key === view.item.key); itemsCopy.splice(itemIndex, 1); this.setState({ items: itemsCopy, modalBusy: false, view: undefined, ...this.resolveFilteredItems(itemsCopy) }); }, () => { this.setState({ modalBusy: false, view: undefined }); } ); } renameCollectionItem(itemKey: string, itemOldKey: string) { let { siteKey, workspaceKey, collectionKey } = this.props; if (this.state.view == null) return; service.api.renameCollectionItem(siteKey, workspaceKey, collectionKey, itemOldKey, itemKey).then( result => { if (result.renamed) { let itemsCopy: Array<any> = (this.state.items || []).slice(0); let itemIndex = itemsCopy.findIndex(x => x.label === itemOldKey); itemsCopy[itemIndex] = result.item; this.setState({ items: itemsCopy, modalBusy: false, view: undefined, ...this.resolveFilteredItems(itemsCopy) }); } else { //TODO: warn someone! this.setState({ modalBusy: false, view: undefined }); } }, () => { //TODO: warn someone! this.setState({ modalBusy: false, view: undefined }); } ); } createCollectionItemKey(itemKey: string) { this.setState({ modalBusy: true }); let { siteKey, workspaceKey, collectionKey } = this.props; service.api .createCollectionItemKey(siteKey, workspaceKey, collectionKey, itemKey) .then( ({ unavailableReason, key }) => { if (unavailableReason) { //TODO: display some warning this.setState({ modalBusy: false }); } else { //refresh this.refreshItems(); } }, e => { this.setState({ modalBusy: false }); } ) .then(() => { this.setRootView(); }); } resolveFilteredItems = (items: Array<any>) => { let trunked = false; let dirs: { [key: string]: boolean } = { "": true }; let filteredItems: Array<any> = (items || []).filter(item => { let parts = item.label.split("/"); let c = ""; for (let i = 0; i < parts.length - 1; i++) { c = c + parts[i] + "/"; dirs[c] = true; } return item.key.startsWith(this.state.filter); }); if (filteredItems.length > MAX_RECORDS) { filteredItems = filteredItems.slice(0, MAX_RECORDS); trunked = true; } let dirsArr: Array<string> = Object.keys(dirs); return { filteredItems, trunked, dirs: dirsArr }; }; handleFilterChange = (e: any, value: string) => { this.setState({ filter: value }); this.filterDebounce.run(() => { this.setState(this.resolveFilteredItems(this.state.items || [])); }); }; handleItemClick = (item: any) => { let { siteKey, workspaceKey, collectionKey } = this.props; let path = `/sites/${encodeURIComponent(siteKey)}/workspaces/${encodeURIComponent( workspaceKey )}/collections/${encodeURIComponent(collectionKey)}/${encodeURIComponent(item.key)}`; this.history.push(path); }; handleDeleteItemClick = (item: any) => { this.setDeleteItemView(item); }; handleRenameItemClick = (item: any) => { this.setRenameItemView(item); }; handleDirClick = (e: any) => { this.setState({ filter: e.currentTarget.dataset.dir }); this.filterDebounce.run(() => { this.setState(this.resolveFilteredItems(this.state.items || [])); }); }; render() { let { collectionKey } = this.props; let { filteredItems, trunked } = this.state; let dialog: any; if (this.state.view) { let view = this.state.view; if (view.key === "createItem") { dialog = ( <EditItemKeyDialog value="" title="New Item" busy={this.state.modalBusy} handleClose={this.setRootView.bind(this)} handleConfirm={this.createCollectionItemKey.bind(this)} confirmLabel="Create" /> ); } else if (view.key === "renameItem") { dialog = ( <EditItemKeyDialog title="Rename Item" value={this.state.view.item.label} busy={this.state.modalBusy} handleClose={this.setRootView.bind(this)} handleConfirm={this.renameCollectionItem.bind(this)} confirmLabel="Rename" /> ); } else if (view.key === "deleteItem") { dialog = ( <DeleteItemKeyDialog busy={this.state.modalBusy} handleClose={this.setRootView.bind(this)} handleConfirm={this.deleteCollectionItem.bind(this)} itemLabel={view.item.label} /> ); } } const selectedWorkspaceDetails = this.state.selectedWorkspaceDetails; if (selectedWorkspaceDetails == null) { return <Spinner />; } const collection = selectedWorkspaceDetails.collections.find(x => x.key == collectionKey); if (collection == null) return null; return ( <Route render={({ history }) => { this.history = history; return ( <div style={{ padding: "20px" }}> <h2>{collection.title}</h2> <div> <RaisedButton label="New Item" onClick={ this.setCreateItemView.bind( this ) /* function(){ history.push('/collections/'+encodeURIComponent(collectionKey)+'/new') */ } /> {/* <span> </span> <RaisedButton label='New Section' onClick={ this.setCreateSectionView.bind(this) } /> */} </div> <br /> <TextField floatingLabelText="Filter" onChange={this.handleFilterChange} fullWidth={true} value={this.state.filter} hintText="Item name" /> <div style={{ display: "flex", flexWrap: "wrap", padding: "10px 0" }}> {this.state.dirs.map(dir => { return ( <Chip key={dir} style={{ marginRight: "5px" }} onClick={this.handleDirClick} data-dir={dir}> /{dir} </Chip> ); })} </div> <Paper> <List> <CollectionListItems filteredItems={filteredItems} onItemClick={this.handleItemClick} onRenameItemClick={this.handleRenameItemClick} onDeleteItemClick={this.handleDeleteItemClick} /> {trunked ? ( <React.Fragment> <Divider /> <ListItem disabled primaryText={`Max records limit reached (${MAX_RECORDS})`} style={{ color: "rgba(0,0,0,.3)" }} /> </React.Fragment> ) : null} </List> </Paper> {dialog} </div> ); }} /> ); } } export default Collection;
the_stack
import { Device, TextureProps, Sampler, SamplerProps, SamplerParameters, isObjectEmpty } from '@luma.gl/api'; import {Texture, cast, log, assert, isPowerOfTwo, loadImage} from '@luma.gl/api'; import GL from '@luma.gl/constants'; import type {WebGLSamplerParameters} from '../../types/webgl'; import {withParameters} from '../../context/state-tracker/with-parameters'; import { getWebGLTextureFormat, getWebGLTextureParameters, getTextureFormatBytesPerPixel } from '../converters/texture-formats'; import { convertSamplerParametersToWebGL, updateSamplerParametersForNPOT } from '../converters/sampler-parameters'; import WebGLDevice from '../webgl-device'; import WEBGLBuffer from './webgl-buffer'; import WEBGLSampler from './webgl-sampler'; export type {TextureProps}; type SetImageDataOptions = { target?: number; level?: number; dataFormat?: any; width: number; height: number; depth?: number; format: any; type?: any; offset?: number; data: any; compressed?: boolean; parameters?: Record<GL, any>; /** @deprecated */ pixels?: any; }; /** * @param {*} pixels, data - * null - create empty texture of specified format * Typed array - init from image data in typed array * Buffer|WebGLBuffer - (WEBGL2) init from image data in WebGLBuffer * HTMLImageElement|Image - Inits with content of image. Auto width/height * HTMLCanvasElement - Inits with contents of canvas. Auto width/height * HTMLVideoElement - Creates video texture. Auto width/height * * @param x - xOffset from where texture to be updated * @param y - yOffset from where texture to be updated * @param width - width of the sub image to be updated * @param height - height of the sub image to be updated * @param level - mip level to be updated * @param {GLenum} format - internal format of image data. * @param {GLenum} type * - format of array (autodetect from type) or * - (WEBGL2) format of buffer or ArrayBufferView * @param {GLenum} dataFormat - format of image data. * @param {Number} offset - (WEBGL2) offset from start of buffer * @parameters - temporary settings to be applied, can be used to supply pixel store settings. */ type SetSubImageDataOptions = { target?: number; level?: number; dataFormat?: any; width?: number; height?: number; depth?: number; format?: any; type?: any; offset?: number; data: any; parameters?: Record<GL, any>; compressed?: boolean; x?: number; y?: number; /** @deprecated */ pixels?: any; }; type SetImageData3DOptions = { level?: number; dataFormat?: any; width: number; height: number; depth?: number; format: any; type?: any; offset?: number; data: any; parameters?: Record<GL, any>; }; // Polyfill export default class WEBGLTexture extends Texture { // TODO - remove? static FACES: number[] = [ GL.TEXTURE_CUBE_MAP_POSITIVE_X, GL.TEXTURE_CUBE_MAP_NEGATIVE_X, GL.TEXTURE_CUBE_MAP_POSITIVE_Y, GL.TEXTURE_CUBE_MAP_NEGATIVE_Y, GL.TEXTURE_CUBE_MAP_POSITIVE_Z, GL.TEXTURE_CUBE_MAP_NEGATIVE_Z ]; readonly MAX_ATTRIBUTES: number; readonly device: WebGLDevice; readonly gl: WebGLRenderingContext; readonly gl2: WebGL2RenderingContext | null; readonly handle: WebGLTexture; data; width: number = undefined; height: number = undefined; depth: number = undefined; format: GL = undefined; type: GL = undefined; dataFormat: GL = undefined; mipmaps: boolean = undefined; /** * @note `target` cannot be modified by bind: * textures are special because when you first bind them to a target, * they get special information. When you first bind a texture as a * GL_TEXTURE_2D, you are saying that this texture is a 2D texture. * And it will always be a 2D texture; this state cannot be changed ever. * A texture that was first bound as a GL_TEXTURE_2D, must always be bound as a GL_TEXTURE_2D; * attempting to bind it as GL_TEXTURE_3D will give rise to a run-time error * */ target: GL; textureUnit: number = undefined; /** Sampler object (currently unused) */ sampler: WEBGLSampler = undefined; /** * Program.draw() checks the loaded flag of all textures to avoid * Textures that are still loading from promises * Set to true as soon as texture has been initialized with valid data */ loaded: boolean = false; _video: { video: HTMLVideoElement; parameters: any; lastTime: number; }; constructor(device: Device, props: TextureProps) { super(device, {format: GL.RGBA, ...props}); this.device = cast<WebGLDevice>(device); this.gl = this.device.gl; this.gl2 = this.device.gl2; this.handle = this.props.handle || this.gl.createTexture(); // @ts-expect-error Per SPECTOR docs this.handle.__SPECTOR_Metadata = {...this.props, data: typeof this.props.data}; // {name: this.props.id}; this.target = getWebGLTextureTarget(this.props); // Program.draw() checks the loaded flag of all textures this.loaded = false; // Signature: new Texture2D(gl, {data: url}) if (typeof this.props?.data === 'string') { Object.assign(this.props, {data: loadImage(this.props.data)}); } this.initialize(this.props); Object.seal(this); } destroy(): void { if (this.handle) { this.gl.deleteTexture(this.handle); this.removeStats(); this.trackDeallocatedMemory('Texture'); // @ts-expect-error this.handle = null; } } toString(): string { return `Texture(${this.id},${this.width}x${this.height})`; } // eslint-disable-next-line max-statements initialize(props: TextureProps = {}): this { // Cube textures if (this.props.dimension === 'cube') { return this.initializeCube(props); } let data = props.data; if (data instanceof Promise) { data.then((resolvedImageData) => this.initialize( Object.assign({}, props, { pixels: resolvedImageData, data: resolvedImageData }) ) ); return this; } const isVideo = typeof HTMLVideoElement !== 'undefined' && data instanceof HTMLVideoElement; // @ts-expect-error if (isVideo && data.readyState < HTMLVideoElement.HAVE_METADATA) { this._video = null; // Declare member before the object is sealed // @ts-expect-error data.addEventListener('loadeddata', () => this.initialize(props)); return this; } let {parameters = {} as Record<GL, any>} = props; const { pixels = null, recreate = false, pixelStore = {}, textureUnit = undefined} = props; // pixels variable is for API compatibility purpose if (!data) { // TODO - This looks backwards? Commenting out for now until we decide // which prop to use // log.deprecated('data', 'pixels')(); data = pixels; } let {width, height, dataFormat, type, compressed = false, mipmaps = true} = props; const {depth = 0} = props; // Deduce width and height ({width, height, compressed, dataFormat, type} = this._deduceParameters({ format: props.format, type, dataFormat, compressed, data, width, height })); const format = getWebGLTextureFormat(this.gl, props.format); // Store opts for accessors this.width = width; this.height = height; this.depth = depth; this.format = format; this.type = type; this.dataFormat = dataFormat; this.textureUnit = textureUnit; if (Number.isFinite(this.textureUnit)) { this.gl.activeTexture(GL.TEXTURE0 + this.textureUnit); this.gl.bindTexture(this.target, this.handle); } if (mipmaps && this.device.isWebGL1 && isNPOT(this.width, this.height)) { log.warn(`texture: ${this} is Non-Power-Of-Two, disabling mipmaps`)(); mipmaps = false; } this.mipmaps = mipmaps; this.setImageData({ data, width, height, depth, format, type, dataFormat, // @ts-expect-error parameters: pixelStore, compressed }); // Set texture sampler parameters this.setSampler(props.sampler); this._setSamplerParameters(parameters); if (mipmaps) { this.generateMipmap(); } // TODO - Store data to enable auto recreate on context loss if (recreate) { this.data = data; } if (isVideo) { this._video = { video: data as HTMLVideoElement, parameters, // @ts-expect-error lastTime: data.readyState >= HTMLVideoElement.HAVE_CURRENT_DATA ? data.currentTime : -1 }; } return this; } initializeCube(props?: TextureProps): this { const {mipmaps = true, parameters = {} as Record<GL, any>} = props; // Store props for accessors // this.props = props; // @ts-expect-error this.setCubeMapImageData(props).then(() => { this.loaded = true; // TODO - should genMipmap() be called on the cubemap or on the faces? // TODO - without generateMipmap() cube textures do not work at all!!! Why? if (mipmaps) { this.generateMipmap(props); } this.setSampler(props.sampler); this._setSamplerParameters(parameters); }); return this; } setSampler(sampler: Sampler | SamplerProps = {}): this { let samplerProps: SamplerParameters; if (sampler instanceof WEBGLSampler) { this.sampler = sampler; samplerProps = sampler.props; } else { this.sampler = new WEBGLSampler(this.device, sampler); samplerProps = sampler as SamplerProps; } // TODO - technically, this is only needed in WebGL1. In WebGL2 we could always use the sampler. const parameters = convertSamplerParametersToWebGL(samplerProps); this._setSamplerParameters(parameters); return this; } /** * If size has changed, reinitializes with current format * @note note clears image and mipmaps */ resize({height, width, mipmaps = false}): this { if (width !== this.width || height !== this.height) { return this.initialize({ width, height, format: this.format, type: this.type, dataFormat: this.dataFormat, mipmaps }); } return this; } /** Update external texture (video frame) */ update(): this { if (this._video) { const {video, parameters, lastTime} = this._video; // @ts-expect-error if (lastTime === video.currentTime || video.readyState < HTMLVideoElement.HAVE_CURRENT_DATA) { return; } this.setSubImageData({ data: video, parameters }); if (this.mipmaps) { this.generateMipmap(); } this._video.lastTime = video.currentTime; } } // Call to regenerate mipmaps after modifying texture(s) generateMipmap(params = {}): this { if (this.device.isWebGL1 && isNPOT(this.width, this.height)) { log.warn(`texture: ${this} is Non-Power-Of-Two, disabling mipmaping`)(); return this; } this.mipmaps = true; this.gl.bindTexture(this.target, this.handle); withParameters(this.gl, params, () => { this.gl.generateMipmap(this.target); }); this.gl.bindTexture(this.target, null); return this; } /* * Allocates storage * @param {*} pixels - * null - create empty texture of specified format * Typed array - init from image data in typed array * Buffer|WebGLBuffer - (WEBGL2) init from image data in WebGLBuffer * HTMLImageElement|Image - Inits with content of image. Auto width/height * HTMLCanvasElement - Inits with contents of canvas. Auto width/height * HTMLVideoElement - Creates video texture. Auto width/height * * @param width - * @param height - * @param mipMapLevel - * @param {GLenum} format - format of image data. * @param {GLenum} type * - format of array (autodetect from type) or * - (WEBGL2) format of buffer * @param {Number} offset - (WEBGL2) offset from start of buffer * @parameters - temporary settings to be applied, can be used to supply pixel store settings. */ // eslint-disable-next-line max-statements, complexity setImageData(options: SetImageDataOptions) { if (this.props.dimension === '3d') { return this.setImageData3D(options); } this.trackDeallocatedMemory('Texture'); const { target = this.target, pixels = null, level = 0, format = this.format, offset = 0, parameters = {} as Record<GL, any> } = options; let { data = null, type = this.type, width = this.width, height = this.height, dataFormat = this.dataFormat, compressed = false } = options; // pixels variable is for API compatibility purpose if (!data) { data = pixels; } ({type, dataFormat, compressed, width, height} = this._deduceParameters({ format: this.props.format, type, dataFormat, compressed, data, width, height })); const {gl} = this; gl.bindTexture(this.target, this.handle); let dataType = null; ({data, dataType} = this._getDataType({data, compressed})); let gl2; withParameters(this.gl, parameters, () => { switch (dataType) { case 'null': gl.texImage2D(target, level, format, width, height, 0 /*border*/, dataFormat, type, data); break; case 'typed-array': // Looks like this assert is not necessary, as offset is ignored under WebGL1 // assert((offset === 0 || this.device.isWebGL2), 'offset supported in WebGL2 only'); gl.texImage2D( target, level, format, width, height, 0, // border (must be 0) dataFormat, type, data, // @ts-expect-error offset ); break; case 'buffer': // WebGL2 enables creating textures directly from a WebGL buffer gl2 = this.device.assertWebGL2(); gl2.bindBuffer(GL.PIXEL_UNPACK_BUFFER, data.handle || data); gl2.texImage2D( target, level, format, width, height, 0 /*border*/, dataFormat, type, offset ); gl2.bindBuffer(GL.PIXEL_UNPACK_BUFFER, null); break; case 'browser-object': if (this.device.isWebGL2) { gl.texImage2D( target, level, format, width, height, 0 /*border*/, dataFormat, type, data ); } else { gl.texImage2D(target, level, format, dataFormat, type, data); } break; case 'compressed': for (const [levelIndex, levelData] of data.entries()) { gl.compressedTexImage2D( target, levelIndex, levelData.format, levelData.width, levelData.height, 0 /* border, must be 0 */, levelData.data ); } break; default: assert(false, 'Unknown image data type'); } }); if (data && data.byteLength) { this.trackAllocatedMemory(data.byteLength, 'Texture'); } else { const bytesPerPixel = getTextureFormatBytesPerPixel(this.gl, this.props.format); this.trackAllocatedMemory(this.width * this.height * bytesPerPixel, 'Texture'); } this.loaded = true; return this; } /** * Redefines an area of an existing texture * Note: does not allocate storage * Redefines an area of an existing texture */ setSubImageData({ target = this.target, pixels = null, data = null, x = 0, y = 0, width = this.width, height = this.height, level = 0, format = this.format, type = this.type, dataFormat = this.dataFormat, compressed = false, offset = 0, parameters = {} as Record<GL, any> }: SetSubImageDataOptions) { ({type, dataFormat, compressed, width, height} = this._deduceParameters({ format: this.props.format, type, dataFormat, compressed, data, width, height })); assert(this.depth === 1, 'texSubImage not supported for 3D textures'); // pixels variable is for API compatibility purpose if (!data) { data = pixels; } // Support ndarrays if (data && data.data) { const ndarray = data; data = ndarray.data; width = ndarray.shape[0]; height = ndarray.shape[1]; } // Support buffers if (data instanceof WEBGLBuffer) { data = data.handle; } this.gl.bindTexture(this.target, this.handle); withParameters(this.gl, parameters, () => { // TODO - x,y parameters if (compressed) { this.gl.compressedTexSubImage2D(target, level, x, y, width, height, format, data); } else if (data === null) { this.gl.texSubImage2D(target, level, x, y, width, height, dataFormat, type, null); } else if (ArrayBuffer.isView(data)) { // const gl2 = this.device.assertWebGL2(); // @ts-expect-error last offset parameter is ignored under WebGL1 this.gl.texSubImage2D(target, level, x, y, width, height, dataFormat, type, data, offset); } else if (typeof WebGLBuffer !== 'undefined' && data instanceof WebGLBuffer) { // WebGL2 allows us to create texture directly from a WebGL buffer const gl2 = this.device.assertWebGL2(); // This texImage2D signature uses currently bound GL.PIXEL_UNPACK_BUFFER gl2.bindBuffer(GL.PIXEL_UNPACK_BUFFER, data); gl2.texSubImage2D(target, level, x, y, width, height, dataFormat, type, offset); gl2.bindBuffer(GL.PIXEL_UNPACK_BUFFER, null); } else if (this.device.isWebGL2) { // Assume data is a browser supported object (ImageData, Canvas, ...) const gl2 = this.device.assertWebGL2(); gl2.texSubImage2D(target, level, x, y, width, height, dataFormat, type, data); } else { this.gl.texSubImage2D(target, level, x, y, dataFormat, type, data); } }); this.gl.bindTexture(this.target, null); } /** * Defines a two-dimensional texture image or cube-map texture image with * pixels from the current framebuffer (rather than from client memory). * (gl.copyTexImage2D wrapper) * * Note that binding a texture into a Framebuffer's color buffer and * rendering can be faster. */ copyFramebuffer(opts = {}) { log.error( 'Texture.copyFramebuffer({...}) is no logner supported, use copyToTexture(source, target, opts})' )(); return null; } getActiveUnit(): number { return this.gl.getParameter(GL.ACTIVE_TEXTURE) - GL.TEXTURE0; } bind(textureUnit = this.textureUnit) { const {gl} = this; if (textureUnit !== undefined) { this.textureUnit = textureUnit; gl.activeTexture(gl.TEXTURE0 + textureUnit); } gl.bindTexture(this.target, this.handle); return textureUnit; } unbind(textureUnit = this.textureUnit) { const {gl} = this; if (textureUnit !== undefined) { this.textureUnit = textureUnit; gl.activeTexture(gl.TEXTURE0 + textureUnit); } gl.bindTexture(this.target, null); return textureUnit; } // PRIVATE METHODS _getDataType({data, compressed = false}) { if (compressed) { return {data, dataType: 'compressed'}; } if (data === null) { return {data, dataType: 'null'}; } if (ArrayBuffer.isView(data)) { return {data, dataType: 'typed-array'}; } if (data instanceof WEBGLBuffer) { return {data: data.handle, dataType: 'buffer'}; } // Raw WebGL handle (not a luma wrapper) if (typeof WebGLBuffer !== 'undefined' && data instanceof WebGLBuffer) { return {data, dataType: 'buffer'}; } // Assume data is a browser supported object (ImageData, Canvas, ...) return {data, dataType: 'browser-object'}; } // HELPER METHODS _deduceParameters(opts) { const {format, data} = opts; let {width, height, dataFormat, type, compressed} = opts; // Deduce format and type from format const parameters = getWebGLTextureParameters(this.gl, format); dataFormat = dataFormat || parameters.dataFormat; type = type || parameters.type; compressed = compressed || parameters.compressed; ({width, height} = this._deduceImageSize(data, width, height)); return {dataFormat, type, compressed, width, height, format, data}; } // eslint-disable-next-line complexity _deduceImageSize(data, width, height): {width: number; height: number} { let size; if (typeof ImageData !== 'undefined' && data instanceof ImageData) { size = {width: data.width, height: data.height}; } else if (typeof HTMLImageElement !== 'undefined' && data instanceof HTMLImageElement) { size = {width: data.naturalWidth, height: data.naturalHeight}; } else if (typeof HTMLCanvasElement !== 'undefined' && data instanceof HTMLCanvasElement) { size = {width: data.width, height: data.height}; } else if (typeof ImageBitmap !== 'undefined' && data instanceof ImageBitmap) { size = {width: data.width, height: data.height}; } else if (typeof HTMLVideoElement !== 'undefined' && data instanceof HTMLVideoElement) { size = {width: data.videoWidth, height: data.videoHeight}; } else if (!data) { size = {width: width >= 0 ? width : 1, height: height >= 0 ? height : 1}; } else { size = {width, height}; } assert(size, 'Could not deduced texture size'); assert( width === undefined || size.width === width, 'Deduced texture width does not match supplied width' ); assert( height === undefined || size.height === height, 'Deduced texture height does not match supplied height' ); return size; } // CUBE MAP METHODS /* eslint-disable max-statements, max-len */ async setCubeMapImageData(options: { width: any; height: any; pixels: any; data: any; format?: any; type?: any; }): Promise<void> { const {gl} = this; const {width, height, pixels, data, format = GL.RGBA, type = GL.UNSIGNED_BYTE} = options; const imageDataMap = pixels || data; // pixel data (imageDataMap) is an Object from Face to Image or Promise. // For example: // { // GL.TEXTURE_CUBE_MAP_POSITIVE_X : Image-or-Promise, // GL.TEXTURE_CUBE_MAP_NEGATIVE_X : Image-or-Promise, // ... } // To provide multiple level-of-details (LODs) this can be Face to Array // of Image or Promise, like this // { // GL.TEXTURE_CUBE_MAP_POSITIVE_X : [Image-or-Promise-LOD-0, Image-or-Promise-LOD-1], // GL.TEXTURE_CUBE_MAP_NEGATIVE_X : [Image-or-Promise-LOD-0, Image-or-Promise-LOD-1], // ... } const resolvedFaces = await Promise.all( WEBGLTexture.FACES.map((face) => { const facePixels = imageDataMap[face]; return Promise.all(Array.isArray(facePixels) ? facePixels : [facePixels]); }) ); this.bind(); WEBGLTexture.FACES.forEach((face, index) => { if (resolvedFaces[index].length > 1 && this.props.mipmaps !== false) { // If the user provides multiple LODs, then automatic mipmap // generation generateMipmap() should be disabled to avoid overwritting them. log.warn(`${this.id} has mipmap and multiple LODs.`)(); } resolvedFaces[index].forEach((image, lodLevel) => { // TODO: adjust width & height for LOD! if (width && height) { gl.texImage2D(face, lodLevel, format, width, height, 0 /*border*/, format, type, image); } else { gl.texImage2D(face, lodLevel, format, format, type, image); } }); }); this.unbind(); } /** @todo update this method to accept LODs */ setImageDataForFace(options) { const { face, width, height, pixels, data, format = GL.RGBA, type = GL.UNSIGNED_BYTE // generateMipmap = false // TODO } = options; const {gl} = this; const imageData = pixels || data; this.bind(); if (imageData instanceof Promise) { imageData.then((resolvedImageData) => this.setImageDataForFace( Object.assign({}, options, { face, data: resolvedImageData, pixels: resolvedImageData }) ) ); } else if (this.width || this.height) { gl.texImage2D(face, 0, format, width, height, 0 /*border*/, format, type, imageData); } else { gl.texImage2D(face, 0, format, format, type, imageData); } return this; } /** Image 3D copies from Typed Array or WebGLBuffer */ setImageData3D({ level = 0, dataFormat, format, type, // = GL.UNSIGNED_BYTE, width, height, depth = 1, offset = 0, data, parameters = {} as Record<GL, any> as Record<GL, any> }: SetImageData3DOptions) { this.trackDeallocatedMemory('Texture'); this.gl.bindTexture(this.target, this.handle); const webglTextureFormat = getWebGLTextureParameters(this.gl, format); withParameters(this.gl, parameters, () => { if (ArrayBuffer.isView(data)) { // @ts-expect-error this.gl.texImage3D( this.target, level, webglTextureFormat.format, width, height, depth, 0 /* border, must be 0 */, webglTextureFormat.dataFormat, webglTextureFormat.type, // dataType: getWebGL, data ); } if (data instanceof WEBGLBuffer) { this.gl.bindBuffer(GL.PIXEL_UNPACK_BUFFER, data.handle); // @ts-expect-error this.gl.texImage3D( this.target, level, dataFormat, width, height, depth, 0 /* border, must be 0 */, format, type, offset ); } }); if (data && data.byteLength) { this.trackAllocatedMemory(data.byteLength, 'Texture'); } else { const bytesPerPixel = getTextureFormatBytesPerPixel(this.gl, this.props.format); this.trackAllocatedMemory(this.width * this.height * this.depth * bytesPerPixel, 'Texture'); } this.loaded = true; return this; } // RESOURCE METHODS /** * Sets sampler parameters on texture * @note: Applies NPOT workaround if appropriate */ _setSamplerParameters(parameters: WebGLSamplerParameters) { // Work around WebGL1 sampling restrictions on NPOT textures if (this.device.isWebGL1 && isNPOT(this.width, this.height)) { parameters = updateSamplerParametersForNPOT(parameters); } // NPOT parameters may populate an empty object if (isObjectEmpty(parameters)) { return; } logParameters(parameters); this.gl.bindTexture(this.target, this.handle); for (const [pname, pvalue] of Object.entries(parameters)) { const param = Number(pname); let value = pvalue; // Apparently there are integer/float conversion issues requires two parameter setting functions in JavaScript. // For now, pick the float version for parameters specified as GLfloat. switch (param) { case GL.TEXTURE_MIN_LOD: case GL.TEXTURE_MAX_LOD: this.gl.texParameterf(this.target, param, value); break; default: this.gl.texParameteri(this.target, param, value); break; } } this.gl.bindTexture(this.target, null); return this; } /** @deprecated For LegacyTexture subclass */ protected _getWebGL1NPOTParameterOverride(pname: number, value: number): number { // NOTE: Apply NPOT workaround const npot = this.device.isWebGL1 && isNPOT(this.width, this.height); if (npot) { switch (pname) { case GL.TEXTURE_MIN_FILTER: if (value !== GL.LINEAR && value !== GL.NEAREST) { // log.warn(`texture: ${this} is Non-Power-Of-Two, forcing TEXTURE_MIN_FILTER to LINEAR`)(); return GL.LINEAR; } break; case GL.TEXTURE_WRAP_S: case GL.TEXTURE_WRAP_T: // if (value !== GL.CLAMP_TO_EDGE) { log.warn(`texture: ${this} is Non-Power-Of-Two, ${getKey(this.gl, pname)} to CLAMP_TO_EDGE`)(); } return GL.CLAMP_TO_EDGE; default: break; } } return value; } } // HELPERS function getWebGLTextureTarget(props: TextureProps) { switch (props.dimension) { // supported in WebGL case '2d': return GL.TEXTURE_2D; case 'cube': return GL.TEXTURE_CUBE_MAP; // supported in WebGL2 case '2d-array': return GL.TEXTURE_2D_ARRAY; case '3d': return GL.TEXTURE_3D; // not supported in any WebGL version case '1d': case 'cube-array': default: throw new Error(props.dimension); } } function isNPOT(width: number, height: number): boolean { // Width and height not available, avoid classifying as NPOT texture if (!width || !height) { return false; } return !isPowerOfTwo(width) || !isPowerOfTwo(height); } function logParameters(parameters: Record<number, GL | number>) { log.log(1, 'texture sampler parameters', parameters)(); for (const [pname, pvalue] of Object.entries(parameters)) { } }
the_stack
import Vue from 'vue' import { PropValidator } from 'vue/types/options' import WPicker from '../WPicker' // Mixins import Picker from '@/mixins/picker' // Utils import mixins, { ExtractVue } from '@/utils/mixins' type StartBoundary = { startYear: number startMonth: number startDate: number startHour: number startMinute: number } type EndBoundary = { endYear: number endMonth: number endDate: number endHour: number endMinute: number } type ValueRange = { year?: [number, number] month?: [number, number] date?: [number, number] hour?: [number, number] minute?: [number, number] } type PickerInstance = InstanceType<typeof WPicker> interface options extends Vue { $refs: { picker: PickerInstance } } const currentYear = new Date().getFullYear() const isValidDate = (date: any) => Object.prototype.toString.call(date) === '[object Date]' && !isNaN(date.getTime()) export default mixins<options & ExtractVue<[typeof Picker]> >( Picker ).extend({ name: 'w-datetime-picker', components: { WPicker, }, props: { type: { type: String, default: 'datetime', }, startDate: { type: Date, default: () => new Date(currentYear - 10, 0, 1), validator: isValidDate, } as PropValidator<Date>, endDate: { type: Date, default: () => new Date(currentYear + 10, 11, 31), validator: isValidDate, } as PropValidator<Date>, startHour: { type: Number, default: 0, }, endHour: { type: Number, default: 23, }, yearFormat: { type: String, default: '{value}', }, monthFormat: { type: String, default: '{value}', }, dateFormat: { type: String, default: '{value}', }, hourFormat: { type: String, default: '{value}', }, minuteFormat: { type: String, default: '{value}', }, visibleItemCount: { type: Number, default: 7, }, value: {} as PropValidator<Date | string>, }, data () { return { internalValue: this.value, } }, computed: { ranges (): ValueRange { if (this.type === 'time') { return { hour: [this.startHour, this.endHour], minute: [0, 59], } } const { startYear, startMonth, startDate, startHour, startMinute, } = this.getBoundary('start', this.internalValue as Date) as StartBoundary const { endYear, endMonth, endDate, endHour, endMinute, } = this.getBoundary('end', this.internalValue as Date) as EndBoundary if (this.type === 'datetime') { return { year: [startYear, endYear], month: [startMonth, endMonth], date: [startDate, endDate], hour: [startHour, endHour], minute: [startMinute, endMinute], } } else { return { year: [startYear, endYear], month: [startMonth, endMonth], date: [startDate, endDate], } } }, columns (): any[] { const result = [] for (const rangeKey in this.ranges) { result.push({ options: this.fillColumnOptions( rangeKey, (this.ranges as any)[rangeKey][0], (this.ranges as any)[rangeKey][1] ), }) } return result }, }, watch: { value (val) { val = this.correctValue(val) const isEqual = this.type === 'time' ? val === this.internalValue : val.valueOf() === this.internalValue.valueOf() if (!isEqual) { this.internalValue = val } }, internalValue (val) { this.updateColumnValue(val) }, }, created () { this.internalValue = this.correctValue(this.value) }, mounted () { if (!this.value) { this.internalValue = this.type.includes('date') ? this.startDate : `${('0' + this.startHour).slice(-2)}:00` } else { this.internalValue = this.correctValue(this.value) } this.updateColumnValue(this.internalValue) }, methods: { getMonthEndDay (year: number, month: number): number { // Date() 第三参数为 0,实际返回上一个月最后一天,注意 Date 对象中 month 实际从 0 开始,而形参 month 表示实际月份 return new Date(year, month, 0).getDate() }, getTrueValue (formattedValue: string): number { while (isNaN(parseInt(formattedValue, 10))) { formattedValue = formattedValue.slice(1) } return parseInt(formattedValue, 10) }, correctValue (value: Date | string | number): Date | string { // validate value const isDateType = this.type.includes('date') if (isDateType && !isValidDate(value)) { value = this.startDate } else if (!value) { const { startHour } = this value = `${startHour > 10 ? startHour : '0' + startHour}:00` } // time type if (!isDateType) { const [hour, minute] = (value as string).split(':') let correctedHour = Math.max(parseInt(hour), this.startHour) correctedHour = Math.min(correctedHour, this.endHour) return `${correctedHour}:${minute}` } // date type const { endYear, endMonth, endDate, endHour, endMinute, } = this.getBoundary('end', value as Date) as EndBoundary const { startYear, startMonth, startDate, startHour, startMinute, } = this.getBoundary('start', value as Date) as StartBoundary const startDay = new Date( startYear, startMonth - 1, startDate, startHour, startMinute ) const endDay = new Date( endYear, endMonth - 1, endDate, endHour, endMinute ) value = Math.min(Math.max((value as Date).getTime(), startDay.getTime()), endDay.getTime()) return new Date(value) }, onChange (picker: PickerInstance): void { const values = picker.getValues() let value if (this.type === 'time') { value = values.join(':') } else { const year = this.getTrueValue(values[0]) const month = this.getTrueValue(values[1]) let date = this.getTrueValue(values[2]) const endDate = this.getMonthEndDay(year, month) date = date > endDate ? endDate : date let hour = 0 let minute = 0 if (this.type === 'datetime') { hour = this.getTrueValue(values[3]) minute = this.getTrueValue(values[4]) } value = new Date(year, month - 1, date, hour, minute) } value = this.correctValue(value) this.internalValue = value this.$emit('change', picker) }, fillColumnOptions (type: string, start: number, end: number): any[] { const options = [] for (let i = start; i <= end; i++) { if (i < 10) { options.push( (this as any)[`${type}Format`].replace('{value}', ('0' + i).slice(-2)) ) } else { options.push((this as any)[`${type}Format`].replace('{value}', i)) } } return options }, getBoundary (type: 'start' | 'end', value: Date): StartBoundary | EndBoundary { const boundary = type === 'start' ? this.startDate : this.endDate const year = boundary.getFullYear() let month = 1 let date = 1 let hour = 0 let minute = 0 if (type === 'end') { month = 12 date = this.getMonthEndDay(value.getFullYear(), value.getMonth() + 1) hour = 23 minute = 59 } if (value.getFullYear() === year) { month = boundary.getMonth() + 1 if (value.getMonth() + 1 === month) { date = boundary.getDate() if (value.getDate() === date) { hour = boundary.getHours() if (value.getHours() === hour) { minute = boundary.getMinutes() } } } } return type === 'start' ? { startYear: year, startMonth: month, startDate: date, startHour: hour, startMinute: minute, } : { endYear: year, endMonth: month, endDate: date, endHour: hour, endMinute: minute, } }, updateColumnValue (value: string | Date) { let values: string[] = [] if (this.type === 'time') { const internalValue = (value as string).split(':') values = [ this.hourFormat.replace('{value}', `0${internalValue[0]}`.slice(-2)), this.minuteFormat.replace('{value}', `0${internalValue[1]}`.slice(-2)), ] } else { values = [ this.yearFormat.replace('{value}', `${(value as Date).getFullYear()}`), this.monthFormat.replace( '{value}', `0${(value as Date).getMonth() + 1}`.slice(-2) ), this.dateFormat.replace('{value}', `0${(value as Date).getDate()}`.slice(-2)), ] if (this.type === 'datetime') { values.push( this.hourFormat.replace( '{value}', `0${(value as Date).getHours()}`.slice(-2) ), this.minuteFormat.replace( '{value}', `0${(value as Date).getMinutes()}`.slice(-2) ) ) } } this.$nextTick(() => { this.setColumnByValues(values) }) }, setColumnByValues (values: string[]) { this.$refs.picker.setValues(values) }, onCancel () { this.isActive = false this.$emit('cancel') }, onConfirm () { this.isActive = false this.$emit('input', this.internalValue) this.$emit('confirm', this.internalValue) }, }, render () { return ( <WPicker ref="picker" visible={this.isActive} columns={this.columns} onChange={() => { this.onChange(this.$refs.picker) }} onCancel={this.onCancel} onConfirm={this.onConfirm} confirm-text={this.confirmText} cancel-text={this.cancelText} close-on-click-mask={this.closeOnClickMask} visible-item-count={this.visibleItemCount} /> ) }, })
the_stack
import { Codicon } from 'vs/base/common/codicons'; import { localize } from 'vs/nls'; import { foreground, registerColor } from 'vs/platform/theme/common/colorRegistry'; import { IColorTheme, ICssStyleCollector, registerThemingParticipant } from 'vs/platform/theme/common/themeService'; export const SYMBOL_ICON_ARRAY_FOREGROUND = registerColor('symbolIcon.arrayForeground', { dark: foreground, light: foreground, hc: foreground }, localize('symbolIcon.arrayForeground', 'The foreground color for array symbols. These symbols appear in the outline, breadcrumb, and suggest widget.')); export const SYMBOL_ICON_BOOLEAN_FOREGROUND = registerColor('symbolIcon.booleanForeground', { dark: foreground, light: foreground, hc: foreground }, localize('symbolIcon.booleanForeground', 'The foreground color for boolean symbols. These symbols appear in the outline, breadcrumb, and suggest widget.')); export const SYMBOL_ICON_CLASS_FOREGROUND = registerColor('symbolIcon.classForeground', { dark: '#EE9D28', light: '#D67E00', hc: '#EE9D28' }, localize('symbolIcon.classForeground', 'The foreground color for class symbols. These symbols appear in the outline, breadcrumb, and suggest widget.')); export const SYMBOL_ICON_COLOR_FOREGROUND = registerColor('symbolIcon.colorForeground', { dark: foreground, light: foreground, hc: foreground }, localize('symbolIcon.colorForeground', 'The foreground color for color symbols. These symbols appear in the outline, breadcrumb, and suggest widget.')); export const SYMBOL_ICON_CONSTANT_FOREGROUND = registerColor('symbolIcon.constantForeground', { dark: foreground, light: foreground, hc: foreground }, localize('symbolIcon.constantForeground', 'The foreground color for constant symbols. These symbols appear in the outline, breadcrumb, and suggest widget.')); export const SYMBOL_ICON_CONSTRUCTOR_FOREGROUND = registerColor('symbolIcon.constructorForeground', { dark: '#B180D7', light: '#652D90', hc: '#B180D7' }, localize('symbolIcon.constructorForeground', 'The foreground color for constructor symbols. These symbols appear in the outline, breadcrumb, and suggest widget.')); export const SYMBOL_ICON_ENUMERATOR_FOREGROUND = registerColor('symbolIcon.enumeratorForeground', { dark: '#EE9D28', light: '#D67E00', hc: '#EE9D28' }, localize('symbolIcon.enumeratorForeground', 'The foreground color for enumerator symbols. These symbols appear in the outline, breadcrumb, and suggest widget.')); export const SYMBOL_ICON_ENUMERATOR_MEMBER_FOREGROUND = registerColor('symbolIcon.enumeratorMemberForeground', { dark: '#75BEFF', light: '#007ACC', hc: '#75BEFF' }, localize('symbolIcon.enumeratorMemberForeground', 'The foreground color for enumerator member symbols. These symbols appear in the outline, breadcrumb, and suggest widget.')); export const SYMBOL_ICON_EVENT_FOREGROUND = registerColor('symbolIcon.eventForeground', { dark: '#EE9D28', light: '#D67E00', hc: '#EE9D28' }, localize('symbolIcon.eventForeground', 'The foreground color for event symbols. These symbols appear in the outline, breadcrumb, and suggest widget.')); export const SYMBOL_ICON_FIELD_FOREGROUND = registerColor('symbolIcon.fieldForeground', { dark: '#75BEFF', light: '#007ACC', hc: '#75BEFF' }, localize('symbolIcon.fieldForeground', 'The foreground color for field symbols. These symbols appear in the outline, breadcrumb, and suggest widget.')); export const SYMBOL_ICON_FILE_FOREGROUND = registerColor('symbolIcon.fileForeground', { dark: foreground, light: foreground, hc: foreground }, localize('symbolIcon.fileForeground', 'The foreground color for file symbols. These symbols appear in the outline, breadcrumb, and suggest widget.')); export const SYMBOL_ICON_FOLDER_FOREGROUND = registerColor('symbolIcon.folderForeground', { dark: foreground, light: foreground, hc: foreground }, localize('symbolIcon.folderForeground', 'The foreground color for folder symbols. These symbols appear in the outline, breadcrumb, and suggest widget.')); export const SYMBOL_ICON_FUNCTION_FOREGROUND = registerColor('symbolIcon.functionForeground', { dark: '#B180D7', light: '#652D90', hc: '#B180D7' }, localize('symbolIcon.functionForeground', 'The foreground color for function symbols. These symbols appear in the outline, breadcrumb, and suggest widget.')); export const SYMBOL_ICON_INTERFACE_FOREGROUND = registerColor('symbolIcon.interfaceForeground', { dark: '#75BEFF', light: '#007ACC', hc: '#75BEFF' }, localize('symbolIcon.interfaceForeground', 'The foreground color for interface symbols. These symbols appear in the outline, breadcrumb, and suggest widget.')); export const SYMBOL_ICON_KEY_FOREGROUND = registerColor('symbolIcon.keyForeground', { dark: foreground, light: foreground, hc: foreground }, localize('symbolIcon.keyForeground', 'The foreground color for key symbols. These symbols appear in the outline, breadcrumb, and suggest widget.')); export const SYMBOL_ICON_KEYWORD_FOREGROUND = registerColor('symbolIcon.keywordForeground', { dark: foreground, light: foreground, hc: foreground }, localize('symbolIcon.keywordForeground', 'The foreground color for keyword symbols. These symbols appear in the outline, breadcrumb, and suggest widget.')); export const SYMBOL_ICON_METHOD_FOREGROUND = registerColor('symbolIcon.methodForeground', { dark: '#B180D7', light: '#652D90', hc: '#B180D7' }, localize('symbolIcon.methodForeground', 'The foreground color for method symbols. These symbols appear in the outline, breadcrumb, and suggest widget.')); export const SYMBOL_ICON_MODULE_FOREGROUND = registerColor('symbolIcon.moduleForeground', { dark: foreground, light: foreground, hc: foreground }, localize('symbolIcon.moduleForeground', 'The foreground color for module symbols. These symbols appear in the outline, breadcrumb, and suggest widget.')); export const SYMBOL_ICON_NAMESPACE_FOREGROUND = registerColor('symbolIcon.namespaceForeground', { dark: foreground, light: foreground, hc: foreground }, localize('symbolIcon.namespaceForeground', 'The foreground color for namespace symbols. These symbols appear in the outline, breadcrumb, and suggest widget.')); export const SYMBOL_ICON_NULL_FOREGROUND = registerColor('symbolIcon.nullForeground', { dark: foreground, light: foreground, hc: foreground }, localize('symbolIcon.nullForeground', 'The foreground color for null symbols. These symbols appear in the outline, breadcrumb, and suggest widget.')); export const SYMBOL_ICON_NUMBER_FOREGROUND = registerColor('symbolIcon.numberForeground', { dark: foreground, light: foreground, hc: foreground }, localize('symbolIcon.numberForeground', 'The foreground color for number symbols. These symbols appear in the outline, breadcrumb, and suggest widget.')); export const SYMBOL_ICON_OBJECT_FOREGROUND = registerColor('symbolIcon.objectForeground', { dark: foreground, light: foreground, hc: foreground }, localize('symbolIcon.objectForeground', 'The foreground color for object symbols. These symbols appear in the outline, breadcrumb, and suggest widget.')); export const SYMBOL_ICON_OPERATOR_FOREGROUND = registerColor('symbolIcon.operatorForeground', { dark: foreground, light: foreground, hc: foreground }, localize('symbolIcon.operatorForeground', 'The foreground color for operator symbols. These symbols appear in the outline, breadcrumb, and suggest widget.')); export const SYMBOL_ICON_PACKAGE_FOREGROUND = registerColor('symbolIcon.packageForeground', { dark: foreground, light: foreground, hc: foreground }, localize('symbolIcon.packageForeground', 'The foreground color for package symbols. These symbols appear in the outline, breadcrumb, and suggest widget.')); export const SYMBOL_ICON_PROPERTY_FOREGROUND = registerColor('symbolIcon.propertyForeground', { dark: foreground, light: foreground, hc: foreground }, localize('symbolIcon.propertyForeground', 'The foreground color for property symbols. These symbols appear in the outline, breadcrumb, and suggest widget.')); export const SYMBOL_ICON_REFERENCE_FOREGROUND = registerColor('symbolIcon.referenceForeground', { dark: foreground, light: foreground, hc: foreground }, localize('symbolIcon.referenceForeground', 'The foreground color for reference symbols. These symbols appear in the outline, breadcrumb, and suggest widget.')); export const SYMBOL_ICON_SNIPPET_FOREGROUND = registerColor('symbolIcon.snippetForeground', { dark: foreground, light: foreground, hc: foreground }, localize('symbolIcon.snippetForeground', 'The foreground color for snippet symbols. These symbols appear in the outline, breadcrumb, and suggest widget.')); export const SYMBOL_ICON_STRING_FOREGROUND = registerColor('symbolIcon.stringForeground', { dark: foreground, light: foreground, hc: foreground }, localize('symbolIcon.stringForeground', 'The foreground color for string symbols. These symbols appear in the outline, breadcrumb, and suggest widget.')); export const SYMBOL_ICON_STRUCT_FOREGROUND = registerColor('symbolIcon.structForeground', { dark: foreground, light: foreground, hc: foreground }, localize('symbolIcon.structForeground', 'The foreground color for struct symbols. These symbols appear in the outline, breadcrumb, and suggest widget.')); export const SYMBOL_ICON_TEXT_FOREGROUND = registerColor('symbolIcon.textForeground', { dark: foreground, light: foreground, hc: foreground }, localize('symbolIcon.textForeground', 'The foreground color for text symbols. These symbols appear in the outline, breadcrumb, and suggest widget.')); export const SYMBOL_ICON_TYPEPARAMETER_FOREGROUND = registerColor('symbolIcon.typeParameterForeground', { dark: foreground, light: foreground, hc: foreground }, localize('symbolIcon.typeParameterForeground', 'The foreground color for type parameter symbols. These symbols appear in the outline, breadcrumb, and suggest widget.')); export const SYMBOL_ICON_UNIT_FOREGROUND = registerColor('symbolIcon.unitForeground', { dark: foreground, light: foreground, hc: foreground }, localize('symbolIcon.unitForeground', 'The foreground color for unit symbols. These symbols appear in the outline, breadcrumb, and suggest widget.')); export const SYMBOL_ICON_VARIABLE_FOREGROUND = registerColor('symbolIcon.variableForeground', { dark: '#75BEFF', light: '#007ACC', hc: '#75BEFF' }, localize('symbolIcon.variableForeground', 'The foreground color for variable symbols. These symbols appear in the outline, breadcrumb, and suggest widget.')); registerThemingParticipant((theme: IColorTheme, collector: ICssStyleCollector) => { const symbolIconArrayColor = theme.getColor(SYMBOL_ICON_ARRAY_FOREGROUND); if (symbolIconArrayColor) { collector.addRule(`${Codicon.symbolArray.cssSelector} { color: ${symbolIconArrayColor}; }`); } const symbolIconBooleanColor = theme.getColor(SYMBOL_ICON_BOOLEAN_FOREGROUND); if (symbolIconBooleanColor) { collector.addRule(`${Codicon.symbolBoolean.cssSelector} { color: ${symbolIconBooleanColor}; }`); } const symbolIconClassColor = theme.getColor(SYMBOL_ICON_CLASS_FOREGROUND); if (symbolIconClassColor) { collector.addRule(`${Codicon.symbolClass.cssSelector} { color: ${symbolIconClassColor}; }`); } const symbolIconMethodColor = theme.getColor(SYMBOL_ICON_METHOD_FOREGROUND); if (symbolIconMethodColor) { collector.addRule(`${Codicon.symbolMethod.cssSelector} { color: ${symbolIconMethodColor}; }`); } const symbolIconColorColor = theme.getColor(SYMBOL_ICON_COLOR_FOREGROUND); if (symbolIconColorColor) { collector.addRule(`${Codicon.symbolColor.cssSelector} { color: ${symbolIconColorColor}; }`); } const symbolIconConstantColor = theme.getColor(SYMBOL_ICON_CONSTANT_FOREGROUND); if (symbolIconConstantColor) { collector.addRule(`${Codicon.symbolConstant.cssSelector} { color: ${symbolIconConstantColor}; }`); } const symbolIconConstructorColor = theme.getColor(SYMBOL_ICON_CONSTRUCTOR_FOREGROUND); if (symbolIconConstructorColor) { collector.addRule(`${Codicon.symbolConstructor.cssSelector} { color: ${symbolIconConstructorColor}; }`); } const symbolIconEnumeratorColor = theme.getColor(SYMBOL_ICON_ENUMERATOR_FOREGROUND); if (symbolIconEnumeratorColor) { collector.addRule(` ${Codicon.symbolValue.cssSelector},${Codicon.symbolEnum.cssSelector} { color: ${symbolIconEnumeratorColor}; }`); } const symbolIconEnumeratorMemberColor = theme.getColor(SYMBOL_ICON_ENUMERATOR_MEMBER_FOREGROUND); if (symbolIconEnumeratorMemberColor) { collector.addRule(`${Codicon.symbolEnumMember.cssSelector} { color: ${symbolIconEnumeratorMemberColor}; }`); } const symbolIconEventColor = theme.getColor(SYMBOL_ICON_EVENT_FOREGROUND); if (symbolIconEventColor) { collector.addRule(`${Codicon.symbolEvent.cssSelector} { color: ${symbolIconEventColor}; }`); } const symbolIconFieldColor = theme.getColor(SYMBOL_ICON_FIELD_FOREGROUND); if (symbolIconFieldColor) { collector.addRule(`${Codicon.symbolField.cssSelector} { color: ${symbolIconFieldColor}; }`); } const symbolIconFileColor = theme.getColor(SYMBOL_ICON_FILE_FOREGROUND); if (symbolIconFileColor) { collector.addRule(`${Codicon.symbolFile.cssSelector} { color: ${symbolIconFileColor}; }`); } const symbolIconFolderColor = theme.getColor(SYMBOL_ICON_FOLDER_FOREGROUND); if (symbolIconFolderColor) { collector.addRule(`${Codicon.symbolFolder.cssSelector} { color: ${symbolIconFolderColor}; }`); } const symbolIconFunctionColor = theme.getColor(SYMBOL_ICON_FUNCTION_FOREGROUND); if (symbolIconFunctionColor) { collector.addRule(`${Codicon.symbolFunction.cssSelector} { color: ${symbolIconFunctionColor}; }`); } const symbolIconInterfaceColor = theme.getColor(SYMBOL_ICON_INTERFACE_FOREGROUND); if (symbolIconInterfaceColor) { collector.addRule(`${Codicon.symbolInterface.cssSelector} { color: ${symbolIconInterfaceColor}; }`); } const symbolIconKeyColor = theme.getColor(SYMBOL_ICON_KEY_FOREGROUND); if (symbolIconKeyColor) { collector.addRule(`${Codicon.symbolKey.cssSelector} { color: ${symbolIconKeyColor}; }`); } const symbolIconKeywordColor = theme.getColor(SYMBOL_ICON_KEYWORD_FOREGROUND); if (symbolIconKeywordColor) { collector.addRule(`${Codicon.symbolKeyword.cssSelector} { color: ${symbolIconKeywordColor}; }`); } const symbolIconModuleColor = theme.getColor(SYMBOL_ICON_MODULE_FOREGROUND); if (symbolIconModuleColor) { collector.addRule(`${Codicon.symbolModule.cssSelector} { color: ${symbolIconModuleColor}; }`); } const outlineNamespaceColor = theme.getColor(SYMBOL_ICON_NAMESPACE_FOREGROUND); if (outlineNamespaceColor) { collector.addRule(`${Codicon.symbolNamespace.cssSelector} { color: ${outlineNamespaceColor}; }`); } const symbolIconNullColor = theme.getColor(SYMBOL_ICON_NULL_FOREGROUND); if (symbolIconNullColor) { collector.addRule(`${Codicon.symbolNull.cssSelector} { color: ${symbolIconNullColor}; }`); } const symbolIconNumberColor = theme.getColor(SYMBOL_ICON_NUMBER_FOREGROUND); if (symbolIconNumberColor) { collector.addRule(`${Codicon.symbolNumber.cssSelector} { color: ${symbolIconNumberColor}; }`); } const symbolIconObjectColor = theme.getColor(SYMBOL_ICON_OBJECT_FOREGROUND); if (symbolIconObjectColor) { collector.addRule(`${Codicon.symbolObject.cssSelector} { color: ${symbolIconObjectColor}; }`); } const symbolIconOperatorColor = theme.getColor(SYMBOL_ICON_OPERATOR_FOREGROUND); if (symbolIconOperatorColor) { collector.addRule(`${Codicon.symbolOperator.cssSelector} { color: ${symbolIconOperatorColor}; }`); } const symbolIconPackageColor = theme.getColor(SYMBOL_ICON_PACKAGE_FOREGROUND); if (symbolIconPackageColor) { collector.addRule(`${Codicon.symbolPackage.cssSelector} { color: ${symbolIconPackageColor}; }`); } const symbolIconPropertyColor = theme.getColor(SYMBOL_ICON_PROPERTY_FOREGROUND); if (symbolIconPropertyColor) { collector.addRule(`${Codicon.symbolProperty.cssSelector} { color: ${symbolIconPropertyColor}; }`); } const symbolIconReferenceColor = theme.getColor(SYMBOL_ICON_REFERENCE_FOREGROUND); if (symbolIconReferenceColor) { collector.addRule(`${Codicon.symbolReference.cssSelector} { color: ${symbolIconReferenceColor}; }`); } const symbolIconSnippetColor = theme.getColor(SYMBOL_ICON_SNIPPET_FOREGROUND); if (symbolIconSnippetColor) { collector.addRule(`${Codicon.symbolSnippet.cssSelector} { color: ${symbolIconSnippetColor}; }`); } const symbolIconStringColor = theme.getColor(SYMBOL_ICON_STRING_FOREGROUND); if (symbolIconStringColor) { collector.addRule(`${Codicon.symbolString.cssSelector} { color: ${symbolIconStringColor}; }`); } const symbolIconStructColor = theme.getColor(SYMBOL_ICON_STRUCT_FOREGROUND); if (symbolIconStructColor) { collector.addRule(`${Codicon.symbolStruct.cssSelector} { color: ${symbolIconStructColor}; }`); } const symbolIconTextColor = theme.getColor(SYMBOL_ICON_TEXT_FOREGROUND); if (symbolIconTextColor) { collector.addRule(`${Codicon.symbolText.cssSelector} { color: ${symbolIconTextColor}; }`); } const symbolIconTypeParameterColor = theme.getColor(SYMBOL_ICON_TYPEPARAMETER_FOREGROUND); if (symbolIconTypeParameterColor) { collector.addRule(`${Codicon.symbolTypeParameter.cssSelector} { color: ${symbolIconTypeParameterColor}; }`); } const symbolIconUnitColor = theme.getColor(SYMBOL_ICON_UNIT_FOREGROUND); if (symbolIconUnitColor) { collector.addRule(`${Codicon.symbolUnit.cssSelector} { color: ${symbolIconUnitColor}; }`); } const symbolIconVariableColor = theme.getColor(SYMBOL_ICON_VARIABLE_FOREGROUND); if (symbolIconVariableColor) { collector.addRule(`${Codicon.symbolVariable.cssSelector} { color: ${symbolIconVariableColor}; }`); } });
the_stack
import { AnnotationEvent, CoreApp, DataQueryError, DataQueryRequest, DataQueryResponse, DataSourceApi, DataSourceInstanceSettings, dateMath, DateTime, LoadingState, rangeUtil, ScopedVars, TimeRange, } from '@grafana/data'; import { BackendSrvRequest, FetchError, getBackendSrv } from '@grafana/runtime'; import { safeStringifyValue } from 'app/core/utils/explore'; import { getTimeSrv, TimeSrv } from 'app/features/dashboard/services/TimeSrv'; import { getTemplateSrv, TemplateSrv } from 'app/features/templating/template_srv'; import cloneDeep from 'lodash/cloneDeep'; import defaults from 'lodash/defaults'; import LRU from 'lru-cache'; import { forkJoin, merge, Observable, of, pipe, throwError } from 'rxjs'; import { catchError, filter, map, tap } from 'rxjs/operators'; import addLabelToQuery from './add_label_to_query'; import PrometheusLanguageProvider from './language_provider'; import { expandRecordingRules } from './language_utils'; import PrometheusMetricFindQuery from './metric_find_query'; import { getQueryHints } from './query_hints'; import { getOriginalMetricName, renderTemplate, transform } from './result_transformer'; import { isFetchErrorResponse, PromDataErrorResponse, PromDataSuccessResponse, PromMatrixData, PromOptions, PromQuery, PromQueryRequest, PromScalarData, PromVectorData, } from './types'; export const ANNOTATION_QUERY_STEP_DEFAULT = '60s'; export class PrometheusDatasource extends DataSourceApi<PromQuery, PromOptions> { type: string; editorSrc: string; ruleMappings: { [index: string]: string }; url: string; directUrl: string; basicAuth: any; withCredentials: any; metricsNameCache = new LRU<string, string[]>(10); interval: string; queryTimeout: string; httpMethod: string; languageProvider: PrometheusLanguageProvider; lookupsDisabled: boolean; customQueryParameters: any; constructor( instanceSettings: DataSourceInstanceSettings<PromOptions>, private readonly templateSrv: TemplateSrv = getTemplateSrv(), private readonly timeSrv: TimeSrv = getTimeSrv() ) { super(instanceSettings); this.type = 'prometheus'; this.editorSrc = 'app/features/prometheus/partials/query.editor.html'; this.url = instanceSettings.url!; this.basicAuth = instanceSettings.basicAuth; this.withCredentials = instanceSettings.withCredentials; this.interval = instanceSettings.jsonData.timeInterval || '15s'; this.queryTimeout = instanceSettings.jsonData.queryTimeout; this.httpMethod = instanceSettings.jsonData.httpMethod || 'GET'; this.directUrl = instanceSettings.jsonData.directUrl; this.ruleMappings = {}; this.languageProvider = new PrometheusLanguageProvider(this); this.lookupsDisabled = instanceSettings.jsonData.disableMetricsLookup ?? false; this.customQueryParameters = new URLSearchParams(instanceSettings.jsonData.customQueryParameters); } init = () => { this.loadRules(); }; getQueryDisplayText(query: PromQuery) { return query.expr; } _addTracingHeaders(httpOptions: PromQueryRequest, options: DataQueryRequest<PromQuery>) { httpOptions.headers = {}; const proxyMode = !this.url.match(/^http/); if (proxyMode) { httpOptions.headers['X-Dashboard-Id'] = options.dashboardId; httpOptions.headers['X-Panel-Id'] = options.panelId; } } _request<T = any>(url: string, data: Record<string, string> | null, overrides: Partial<BackendSrvRequest> = {}) { const options: BackendSrvRequest = defaults(overrides, { url: this.url + url, method: this.httpMethod, headers: {}, }); if (options.method === 'GET') { if (data && Object.keys(data).length) { options.url = options.url + '?' + Object.entries(data) .map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`) .join('&'); } } else { options.headers!['Content-Type'] = 'application/x-www-form-urlencoded'; options.data = data; } if (this.basicAuth || this.withCredentials) { options.withCredentials = true; } if (this.basicAuth) { options.headers!.Authorization = this.basicAuth; } return getBackendSrv().fetch<T>(options); } // Use this for tab completion features, wont publish response to other components metadataRequest<T = any>(url: string) { return this._request<T>(url, null, { method: 'GET', hideFromInspector: true }).toPromise(); // toPromise until we change getTagValues, getTagKeys to Observable } interpolateQueryExpr(value: string | string[] = [], variable: any) { // if no multi or include all do not regexEscape if (!variable.multi && !variable.includeAll) { return prometheusRegularEscape(value); } if (typeof value === 'string') { return prometheusSpecialRegexEscape(value); } const escapedValues = value.map(val => prometheusSpecialRegexEscape(val)); if (escapedValues.length === 1) { return escapedValues[0]; } return '(' + escapedValues.join('|') + ')'; } targetContainsTemplate(target: PromQuery) { return this.templateSrv.variableExists(target.expr); } prepareTargets = (options: DataQueryRequest<PromQuery>, start: number, end: number) => { const queries: PromQueryRequest[] = []; const activeTargets: PromQuery[] = []; for (const target of options.targets) { if (!target.expr || target.hide) { continue; } target.requestId = options.panelId + target.refId; if (target.range && target.instant) { // If running both (only available in Explore) - instant and range query, prepare both targets // Create instant target const instantTarget: any = cloneDeep(target); instantTarget.format = 'table'; instantTarget.instant = true; instantTarget.range = false; instantTarget.valueWithRefId = true; delete instantTarget.maxDataPoints; instantTarget.requestId += '_instant'; // Create range target const rangeTarget: any = cloneDeep(target); rangeTarget.format = 'time_series'; rangeTarget.instant = false; instantTarget.range = true; // Add both targets to activeTargets and queries arrays activeTargets.push(instantTarget, rangeTarget); queries.push( this.createQuery(instantTarget, options, start, end), this.createQuery(rangeTarget, options, start, end) ); } else if (target.instant && options.app === CoreApp.Explore) { // If running only instant query in Explore, format as table const instantTarget: any = cloneDeep(target); instantTarget.format = 'table'; queries.push(this.createQuery(instantTarget, options, start, end)); activeTargets.push(instantTarget); } else { queries.push(this.createQuery(target, options, start, end)); activeTargets.push(target); } } return { queries, activeTargets, }; }; query(options: DataQueryRequest<PromQuery>): Observable<DataQueryResponse> { const start = this.getPrometheusTime(options.range.from, false); const end = this.getPrometheusTime(options.range.to, true); const { queries, activeTargets } = this.prepareTargets(options, start, end); // No valid targets, return the empty result to save a round trip. if (!queries || !queries.length) { return of({ data: [], state: LoadingState.Done, }); } if (options.app === CoreApp.Explore) { return this.exploreQuery(queries, activeTargets, end); } return this.panelsQuery(queries, activeTargets, end, options.requestId, options.scopedVars); } private exploreQuery(queries: PromQueryRequest[], activeTargets: PromQuery[], end: number) { let runningQueriesCount = queries.length; const mixedQueries = activeTargets.some(t => t.range) && activeTargets.some(t => t.instant); const subQueries = queries.map((query, index) => { const target = activeTargets[index]; const filterAndMapResponse = pipe( // Decrease the counter here. We assume that each request returns only single value and then completes // (should hold until there is some streaming requests involved). tap(() => runningQueriesCount--), filter((response: any) => (response.cancelled ? false : true)), map((response: any) => { const data = transform(response, { query, target, responseListLength: queries.length, mixedQueries }); return { data, key: query.requestId, state: runningQueriesCount === 0 ? LoadingState.Done : LoadingState.Loading, } as DataQueryResponse; }) ); if (query.instant) { return this.performInstantQuery(query, end).pipe(filterAndMapResponse); } return this.performTimeSeriesQuery(query, query.start, query.end).pipe(filterAndMapResponse); }); return merge(...subQueries); } private panelsQuery( queries: PromQueryRequest[], activeTargets: PromQuery[], end: number, requestId: string, scopedVars: ScopedVars ) { const observables = queries.map((query, index) => { const target = activeTargets[index]; const filterAndMapResponse = pipe( filter((response: any) => (response.cancelled ? false : true)), map((response: any) => { const data = transform(response, { query, target, responseListLength: queries.length, scopedVars }); return data; }) ); if (query.instant) { return this.performInstantQuery(query, end).pipe(filterAndMapResponse); } return this.performTimeSeriesQuery(query, query.start, query.end).pipe(filterAndMapResponse); }); return forkJoin(observables).pipe( map(results => { const data = results.reduce((result, current) => { return [...result, ...current]; }, []); return { data, key: requestId, state: LoadingState.Done, }; }) ); } createQuery(target: PromQuery, options: DataQueryRequest<PromQuery>, start: number, end: number) { const query: PromQueryRequest = { hinting: target.hinting, instant: target.instant, step: 0, expr: '', requestId: target.requestId, refId: target.refId, start: 0, end: 0, }; const range = Math.ceil(end - start); // options.interval is the dynamically calculated interval let interval: number = rangeUtil.intervalToSeconds(options.interval); // Minimum interval ("Min step"), if specified for the query, or same as interval otherwise. const minInterval = rangeUtil.intervalToSeconds( this.templateSrv.replace(target.interval || options.interval, options.scopedVars) ); // Scrape interval as specified for the query ("Min step") or otherwise taken from the datasource. // Min step field can have template variables in it, make sure to replace it. const scrapeInterval = target.interval ? rangeUtil.intervalToSeconds(this.templateSrv.replace(target.interval, options.scopedVars)) : rangeUtil.intervalToSeconds(this.interval); const intervalFactor = target.intervalFactor || 1; // Adjust the interval to take into account any specified minimum and interval factor plus Prometheus limits const adjustedInterval = this.adjustInterval(interval, minInterval, range, intervalFactor); let scopedVars = { ...options.scopedVars, ...this.getRangeScopedVars(options.range), ...this.getRateIntervalScopedVariable(adjustedInterval, scrapeInterval), }; // If the interval was adjusted, make a shallow copy of scopedVars with updated interval vars if (interval !== adjustedInterval) { interval = adjustedInterval; scopedVars = Object.assign({}, options.scopedVars, { __interval: { text: interval + 's', value: interval + 's' }, __interval_ms: { text: interval * 1000, value: interval * 1000 }, ...this.getRateIntervalScopedVariable(interval, scrapeInterval), ...this.getRangeScopedVars(options.range), }); } query.step = interval; let expr = target.expr; // Apply adhoc filters const adhocFilters = this.templateSrv.getAdhocFilters(this.name); expr = adhocFilters.reduce((acc: string, filter: { key?: any; operator?: any; value?: any }) => { const { key, operator } = filter; let { value } = filter; if (operator === '=~' || operator === '!~') { value = prometheusRegularEscape(value); } return addLabelToQuery(acc, key, value, operator); }, expr); // Only replace vars in expression after having (possibly) updated interval vars query.expr = this.templateSrv.replace(expr, scopedVars, this.interpolateQueryExpr); // Align query interval with step to allow query caching and to ensure // that about-same-time query results look the same. const adjusted = alignRange(start, end, query.step, this.timeSrv.timeRange().to.utcOffset() * 60); query.start = adjusted.start; query.end = adjusted.end; this._addTracingHeaders(query, options); return query; } getRateIntervalScopedVariable(interval: number, scrapeInterval: number) { // Fall back to the default scrape interval of 15s if scrapeInterval is 0 for some reason. if (scrapeInterval === 0) { scrapeInterval = 15; } const rateInterval = Math.max(interval + scrapeInterval, 4 * scrapeInterval); return { __rate_interval: { text: rateInterval + 's', value: rateInterval + 's' } }; } adjustInterval(interval: number, minInterval: number, range: number, intervalFactor: number) { // Prometheus will drop queries that might return more than 11000 data points. // Calculate a safe interval as an additional minimum to take into account. // Fractional safeIntervals are allowed, however serve little purpose if the interval is greater than 1 // If this is the case take the ceil of the value. let safeInterval = range / 11000; if (safeInterval > 1) { safeInterval = Math.ceil(safeInterval); } return Math.max(interval * intervalFactor, minInterval, safeInterval); } performTimeSeriesQuery(query: PromQueryRequest, start: number, end: number) { if (start > end) { throw { message: 'Invalid time range' }; } const url = '/api/v1/query_range'; const data: any = { query: query.expr, start, end, step: query.step, }; if (this.queryTimeout) { data['timeout'] = this.queryTimeout; } for (const [key, value] of this.customQueryParameters) { if (data[key] == null) { data[key] = value; } } return this._request<PromDataSuccessResponse<PromMatrixData>>(url, data, { requestId: query.requestId, headers: query.headers, }).pipe( catchError((err: FetchError<PromDataErrorResponse<PromMatrixData>>) => { if (err.cancelled) { return of(err); } return throwError(this.handleErrors(err, query)); }) ); } performInstantQuery(query: PromQueryRequest, time: number) { const url = '/api/v1/query'; const data: any = { query: query.expr, time, }; if (this.queryTimeout) { data['timeout'] = this.queryTimeout; } for (const [key, value] of this.customQueryParameters) { if (data[key] == null) { data[key] = value; } } return this._request<PromDataSuccessResponse<PromVectorData | PromScalarData>>(url, data, { requestId: query.requestId, headers: query.headers, }).pipe( catchError((err: FetchError<PromDataErrorResponse<PromVectorData | PromScalarData>>) => { if (err.cancelled) { return of(err); } return throwError(this.handleErrors(err, query)); }) ); } handleErrors = (err: any, target: PromQuery) => { const error: DataQueryError = { message: (err && err.statusText) || 'Unknown error during query transaction. Please check JS console logs.', refId: target.refId, }; if (err.data) { if (typeof err.data === 'string') { error.message = err.data; } else if (err.data.error) { error.message = safeStringifyValue(err.data.error); } } else if (err.message) { error.message = err.message; } else if (typeof err === 'string') { error.message = err; } error.status = err.status; error.statusText = err.statusText; return error; }; metricFindQuery(query: string) { if (!query) { return Promise.resolve([]); } const scopedVars = { __interval: { text: this.interval, value: this.interval }, __interval_ms: { text: rangeUtil.intervalToMs(this.interval), value: rangeUtil.intervalToMs(this.interval) }, ...this.getRangeScopedVars(this.timeSrv.timeRange()), }; const interpolated = this.templateSrv.replace(query, scopedVars, this.interpolateQueryExpr); const metricFindQuery = new PrometheusMetricFindQuery(this, interpolated); return metricFindQuery.process(); } getRangeScopedVars(range: TimeRange = this.timeSrv.timeRange()) { const msRange = range.to.diff(range.from); const sRange = Math.round(msRange / 1000); return { __range_ms: { text: msRange, value: msRange }, __range_s: { text: sRange, value: sRange }, __range: { text: sRange + 's', value: sRange + 's' }, }; } createAnnotationQueryOptions = (options: any): DataQueryRequest<PromQuery> => { const annotation = options.annotation; const interval = annotation && annotation.step && typeof annotation.step === 'string' ? annotation.step : ANNOTATION_QUERY_STEP_DEFAULT; return { ...options, interval, }; }; async annotationQuery(options: any): Promise<AnnotationEvent[]> { const annotation = options.annotation; const { expr = '', tagKeys = '', titleFormat = '', textFormat = '' } = annotation; if (!expr) { return Promise.resolve([]); } const start = this.getPrometheusTime(options.range.from, false); const end = this.getPrometheusTime(options.range.to, true); const queryOptions = this.createAnnotationQueryOptions(options); // Unsetting min interval for accurate event resolution const minStep = '1s'; const queryModel = { expr, interval: minStep, refId: 'X', requestId: `prom-query-${annotation.name}`, }; const query = this.createQuery(queryModel, queryOptions, start, end); const response = await this.performTimeSeriesQuery(query, query.start, query.end).toPromise(); const eventList: AnnotationEvent[] = []; const splitKeys = tagKeys.split(','); if (isFetchErrorResponse(response) && response.cancelled) { return []; } const step = Math.floor(query.step ?? 15) * 1000; response?.data?.data?.result?.forEach(series => { const tags = Object.entries(series.metric) .filter(([k]) => splitKeys.includes(k)) .map(([_k, v]: [string, string]) => v); series.values.forEach((value: any[]) => { let timestampValue; // rewrite timeseries to a common format if (annotation.useValueForTime) { timestampValue = Math.floor(parseFloat(value[1])); value[1] = 1; } else { timestampValue = Math.floor(parseFloat(value[0])) * 1000; } value[0] = timestampValue; }); const activeValues = series.values.filter(value => parseFloat(value[1]) >= 1); const activeValuesTimestamps = activeValues.map(value => value[0]); // Instead of creating singular annotation for each active event we group events into region if they are less // then `step` apart. let latestEvent: AnnotationEvent | null = null; for (const timestamp of activeValuesTimestamps) { // We already have event `open` and we have new event that is inside the `step` so we just update the end. if (latestEvent && (latestEvent.timeEnd ?? 0) + step >= timestamp) { latestEvent.timeEnd = timestamp; continue; } // Event exists but new one is outside of the `step` so we "finish" the current region. if (latestEvent) { eventList.push(latestEvent); } // We start a new region. latestEvent = { time: timestamp, timeEnd: timestamp, annotation, title: renderTemplate(titleFormat, series.metric), tags, text: renderTemplate(textFormat, series.metric), }; } if (latestEvent) { // finish up last point if we have one latestEvent.timeEnd = activeValuesTimestamps[activeValuesTimestamps.length - 1]; eventList.push(latestEvent); } }); return eventList; } async getTagKeys() { const result = await this.metadataRequest('/api/v1/labels'); return result?.data?.data?.map((value: any) => ({ text: value })) ?? []; } async getTagValues(options: any = {}) { const result = await this.metadataRequest(`/api/v1/label/${options.key}/values`); return result?.data?.data?.map((value: any) => ({ text: value })) ?? []; } async testDatasource() { const now = new Date().getTime(); const query = { expr: '1+1' } as PromQueryRequest; const response = await this.performInstantQuery(query, now / 1000).toPromise(); return response.data.status === 'success' ? { status: 'success', message: 'Data source is working' } : { status: 'error', message: response.data.error }; } interpolateVariablesInQueries(queries: PromQuery[], scopedVars: ScopedVars): PromQuery[] { let expandedQueries = queries; if (queries && queries.length) { expandedQueries = queries.map(query => { const expandedQuery = { ...query, datasource: this.name, expr: this.templateSrv.replace(query.expr, scopedVars, this.interpolateQueryExpr), }; return expandedQuery; }); } return expandedQueries; } getQueryHints(query: PromQuery, result: any[]) { return getQueryHints(query.expr ?? '', result, this); } async loadRules() { try { const res = await this.metadataRequest('/api/v1/rules'); const groups = res.data?.data?.groups; if (groups) { this.ruleMappings = extractRuleMappingFromGroups(groups); } } catch (e) { console.log('Rules API is experimental. Ignore next error.'); console.error(e); } } modifyQuery(query: PromQuery, action: any): PromQuery { let expression = query.expr ?? ''; switch (action.type) { case 'ADD_FILTER': { expression = addLabelToQuery(expression, action.key, action.value); break; } case 'ADD_FILTER_OUT': { expression = addLabelToQuery(expression, action.key, action.value, '!='); break; } case 'ADD_HISTOGRAM_QUANTILE': { expression = `histogram_quantile(0.95, sum(rate(${expression}[5m])) by (le))`; break; } case 'ADD_RATE': { expression = `rate(${expression}[5m])`; break; } case 'ADD_SUM': { expression = `sum(${expression.trim()}) by ($1)`; break; } case 'EXPAND_RULES': { if (action.mapping) { expression = expandRecordingRules(expression, action.mapping); } break; } default: break; } return { ...query, expr: expression }; } getPrometheusTime(date: string | DateTime, roundUp: boolean) { if (typeof date === 'string') { date = dateMath.parse(date, roundUp)!; } return Math.ceil(date.valueOf() / 1000); } getTimeRange(): { start: number; end: number } { const range = this.timeSrv.timeRange(); return { start: this.getPrometheusTime(range.from, false), end: this.getPrometheusTime(range.to, true), }; } getOriginalMetricName(labelData: { [key: string]: string }) { return getOriginalMetricName(labelData); } } /** * Align query range to step. * Rounds start and end down to a multiple of step. * @param start Timestamp marking the beginning of the range. * @param end Timestamp marking the end of the range. * @param step Interval to align start and end with. * @param utcOffsetSec Number of seconds current timezone is offset from UTC */ export function alignRange( start: number, end: number, step: number, utcOffsetSec: number ): { end: number; start: number } { const alignedEnd = Math.floor((end + utcOffsetSec) / step) * step - utcOffsetSec; const alignedStart = Math.floor((start + utcOffsetSec) / step) * step - utcOffsetSec; return { end: alignedEnd, start: alignedStart, }; } export function extractRuleMappingFromGroups(groups: any[]) { return groups.reduce( (mapping, group) => group.rules .filter((rule: any) => rule.type === 'recording') .reduce( (acc: { [key: string]: string }, rule: any) => ({ ...acc, [rule.name]: rule.query, }), mapping ), {} ); } export function prometheusRegularEscape(value: any) { return typeof value === 'string' ? value.replace(/\\/g, '\\\\').replace(/'/g, "\\\\'") : value; } export function prometheusSpecialRegexEscape(value: any) { return typeof value === 'string' ? value.replace(/\\/g, '\\\\\\\\').replace(/[$^*{}\[\]\'+?.()|]/g, '\\\\$&') : value; }
the_stack
'use strict'; require('dnscache')({enable: true}); import fs from 'fs'; // `inspect` is used instead of `JSON.stringify` because it can handle circular structures, such as `AxiosResponse` objects. import {inspect} from 'util'; import axios from 'axios'; import {errors, Browser} from 'puppeteer'; const {TimeoutError} = errors; const prompt = require('prompt'); import logger from "./logger"; import utils from './utils'; interface Stream { url: string, broadcaster_id: string } export class Client { readonly #clientId: string; readonly #oauthToken: string; readonly #channelLogin: string; readonly #defaultHeaders; constructor(clientId: string, oauthToken: string, channelLogin: string) { this.#clientId = clientId; this.#oauthToken = oauthToken; this.#channelLogin = channelLogin; this.#defaultHeaders = { 'Content-Type': 'text/plain;charset=UTF-8', 'Client-Id': this.#clientId, 'Authorization': `OAuth ${this.#oauthToken}` } } /** * Get a list of drop campaigns. This can include expired, active, and future campaigns. * @returns {Promise<*>} */ async getDropCampaigns() { const response = await axios.post('https://gql.twitch.tv/gql', { 'operationName': 'ViewerDropsDashboard', 'extensions': { 'persistedQuery': { "version": 1, "sha256Hash": "e8b98b52bbd7ccd37d0b671ad0d47be5238caa5bea637d2a65776175b4a23a64" } } }, { headers: this.#defaultHeaders } ); try { const campaigns = response['data']['data']['currentUser']['dropCampaigns']; if (!Array.isArray(campaigns)) { throw new TypeError('Drop campaigns is not an array!'); } return campaigns; } catch (error) { logger.debug('Error in function getDropCampaigns! Response: ' + inspect(response, {depth: null})); throw error; } } async getDropCampaignDetails(dropId: string) { const response = await axios.post('https://gql.twitch.tv/gql', { 'operationName': 'DropCampaignDetails', 'extensions': { 'persistedQuery': { "version": 1, "sha256Hash": "14b5e8a50777165cfc3971e1d93b4758613fe1c817d5542c398dce70b7a45c05" } }, 'variables': { 'dropID': dropId, 'channelLogin': this.#channelLogin } }, { headers: this.#defaultHeaders } ); try { return response['data']['data']['user']['dropCampaign']; } catch (error) { logger.debug('Error in function getDropCampaignDetails! Response: ' + inspect(response, {depth: null})); throw error; } } async getInventory() { const response = await axios.post('https://gql.twitch.tv/gql', { 'operationName': 'Inventory', 'extensions': { "persistedQuery": { "version": 1, "sha256Hash": "9cdfc5ebf8ee497e49c5b922829d67e5bce039f3c713f0706d234944195d56ad" } } }, { headers: this.#defaultHeaders } ); try { return response['data']['data']['currentUser']['inventory']; } catch (error) { logger.debug('Error in function getInventory! Response: ' + inspect(response, {depth: null})); throw error; } } async getDropEnabledStreams(gameName: string): Promise<Stream[]> { const response = await axios.post('https://gql.twitch.tv/gql', { "operationName": "DirectoryPage_Game", "variables": { "name": gameName.toLowerCase(), "options": { "includeRestricted": [ "SUB_ONLY_LIVE" ], "sort": "VIEWER_COUNT", "recommendationsContext": { "platform": "web" }, "requestID": "JIRA-VXP-2397", // TODO: what is this for??? "tags": [ "c2542d6d-cd10-4532-919b-3d19f30a768b" // "Drops enabled" ] }, "sortTypeIsRecency": false, "limit": 30 }, "extensions": { "persistedQuery": { "version": 1, "sha256Hash": "d5c5df7ab9ae65c3ea0f225738c08a36a4a76e4c6c31db7f8c4b8dc064227f9e" } } }, { headers: this.#defaultHeaders } ); const streams = response['data']['data']['game']['streams']; if (streams === null) { return []; } const result = []; for (const stream of streams['edges']) { result.push({ 'url': 'https://www.twitch.tv/' + stream['node']['broadcaster']['login'], 'broadcaster_id': stream['node']['broadcaster']['id'] }); } return result; } async claimDropReward(dropId: string) { const response = await axios.post('https://gql.twitch.tv/gql', { "operationName": "DropsPage_ClaimDropRewards", "variables": { "input": { "dropInstanceID": dropId } }, "extensions": { "persistedQuery": { "version": 1, "sha256Hash": "2f884fa187b8fadb2a49db0adc033e636f7b6aaee6e76de1e2bba9a7baf0daf6" } } }, { headers: this.#defaultHeaders } ); if ('errors' in response.data) { throw new Error(JSON.stringify(response.data['errors'])); } } /*async claimCommunityPoints(channelId: string, claimId: string) { const response = await axios.post('https://gql.twitch.tv/gql', { "operationName": "ClaimCommunityPoints", "variables": { "input": { "channelID": channelId, "claimID": claimId } }, "extensions": { "persistedQuery": { "version": 1, "sha256Hash": "46aaeebe02c99afdf4fc97c7c0cba964124bf6b0af229395f1f6d1feed05b3d0" } } }, { headers: this.#defaultHeaders } ); if ('errors' in response.data) { throw new Error(JSON.stringify(response.data['errors'])); } }*/ async getDropCampaignsInProgress() { const inventory = await this.getInventory(); const campaigns = inventory['dropCampaignsInProgress']; if (campaigns === null) { return []; } return campaigns; } async getInventoryDrop(dropId: string, campaignId?: string) { const campaigns = await this.getDropCampaignsInProgress(); for (const campaign of campaigns) { if (!campaignId || campaign['id'] === campaignId) { const drops = campaign['timeBasedDrops']; for (const drop of drops) { if (drop['id'] === dropId) { return drop; } } } } return null; } } export async function login(browser: Browser, username?: string, password?: string, headless: boolean = false) { const page = await browser.newPage(); // Throw an error if the page is closed for any reason const onPageClosed = () => { throw new Error('Page closed!'); } page.on('close', onPageClosed); // Go to login page await page.goto('https://www.twitch.tv/login'); // Enter username if (username !== undefined) { await page.focus('#login-username'); await page.keyboard.type(username); } // Enter password if (password !== undefined) { await page.focus('#password-input'); await page.keyboard.type(password); } // Click login button if (username !== undefined && password !== undefined) { await page.click('[data-a-target="passport-login-button"]'); } if (headless) { while (true) { // TODO: This loop and try/catch statements could be replaced with Promise.any(), but it seems that Node.js 14 does not support it. // Check for email verification code try { logger.info('Checking for email verification...'); await page.waitForXPath('//*[contains(text(), "please enter the 6-digit code we sent")]'); logger.info('Email verification found.'); // Prompt user for code prompt.start(); const result: any = await utils.asyncPrompt(['code']); const code = result['code']; prompt.stop(); // Enter code const first_input = await page.waitForXPath('(//input)[1]'); if (first_input == null) { logger.error('first_input was null!'); break } await first_input.click(); await page.keyboard.type(code); break; } catch (error) { if (error instanceof TimeoutError) { logger.info('Email verification not found.'); } else { logger.error(error); } } // Check for 2FA code try { logger.info('Checking for 2FA verification...'); await page.waitForXPath('//*[contains(text(), "Enter the code found in your authenticator app")]'); logger.info('2FA verification found.'); // Prompt user for code prompt.start(); const result: any = await utils.asyncPrompt(['code']); const code = result['code']; prompt.stop(); // Enter code const first_input = await page.waitForXPath('(//input[@type="text"])'); if (first_input == null) { logger.error('first_input was null!'); break } await first_input.click(); await page.keyboard.type(code); // Click submit const button = await page.waitForXPath('//button[@target="submit_button"]'); if (button == null) { logger.error('button was null!'); break } await button.click(); break; } catch (error) { if (error instanceof TimeoutError) { logger.info('2FA verification not found.'); } else { logger.error(error); } } logger.info('No extra verification found!'); break; } // Wait for redirect to main Twitch page. If this times out then there is probably a different type of verification that we haven't checked for. try { await page.waitForNavigation(); } catch (error) { if (error instanceof TimeoutError) { const time = new Date().getTime(); const screenshotPath = 'failed-login-screenshot-' + time + '.png'; const htmlPath = 'failed-login-html-' + time + '.html'; logger.error('Failed to login. There was probably an extra verification step that this app didn\'t check for. ' + 'A screenshot of the page will be saved to ' + screenshotPath + ' and the page content will be saved to ' + htmlPath + '. Please create an issue on GitHub with both of these files.'); await page.screenshot({ fullPage: true, path: screenshotPath }); fs.writeFileSync(htmlPath, await page.content()); } throw error; } } else { // Wait for redirect to main Twitch page. The timeout is unlimited here because we may be prompted for additional authentication. await page.waitForNavigation({timeout: 0}); } const cookies = await page.cookies(); page.off('close', onPageClosed); await page.close(); return cookies; } export default { Client, login }
the_stack
import { callbackify } from "util"; import { AddressSpace, SessionContext, UAMethod, UATrustList, UAObject, UAVariable, UAServerConfiguration, ISessionContext } from "node-opcua-address-space"; import { checkDebugFlag, make_debugLog, make_warningLog } from "node-opcua-debug"; import { NodeId, resolveNodeId } from "node-opcua-nodeid"; import { StatusCodes } from "node-opcua-status-code"; import { CallMethodResultOptions } from "node-opcua-types"; import { DataType, Variant, VariantArrayType } from "node-opcua-variant"; import { AccessRestrictionsFlag, NodeClass } from "node-opcua-data-model"; import { ByteString, UAString } from "node-opcua-basic-types"; import { ObjectTypeIds } from "node-opcua-constants"; import { CreateSigningRequestResult, PushCertificateManager } from "../push_certificate_manager"; import { installCertificateExpirationAlarm } from "./install_CertificateAlarm"; import { PushCertificateManagerServerImpl, PushCertificateManagerServerOptions } from "./push_certificate_manager_server_impl"; import { installAccessRestrictionOnTrustList, promoteTrustList } from "./promote_trust_list"; import { hasEncryptedChannel, hasExpectedUserAccess } from "./tools"; import { rolePermissionAdminOnly, rolePermissionRestricted } from "./roles_and_permissions"; const debugLog = make_debugLog("ServerConfiguration"); const doDebug = checkDebugFlag("ServerConfiguration"); const warningLog = make_warningLog("ServerConfiguration"); const errorLog = debugLog; function expected( variant: Variant | undefined, dataType: DataType, variantArrayType: VariantArrayType ): boolean { if (!variant) { return false; } if (variant.dataType !== dataType) { return false; } if (variant.arrayType !== variantArrayType) { return false; } return true; } function getPushCertificateManager(method: UAMethod): PushCertificateManager | null { const serverConfiguration = method.addressSpace.rootFolder.objects.server.getChildByName("ServerConfiguration"); const serverConfigurationPriv = serverConfiguration as any; if (serverConfigurationPriv.$pushCertificateManager) { return serverConfigurationPriv.$pushCertificateManager; } // throw new Error("Cannot find pushCertificateManager object"); return null; } async function _createSigningRequest( this: UAMethod, inputArguments: Variant[], context: ISessionContext ): Promise<CallMethodResultOptions> { const certificateGroupIdVariant = inputArguments[0]; const certificateTypeIdVariant = inputArguments[1]; const subjectNameVariant = inputArguments[2]; const regeneratePrivateKeyVariant = inputArguments[3]; const nonceVariant = inputArguments[4]; if (!expected(certificateGroupIdVariant, DataType.NodeId, VariantArrayType.Scalar)) { warningLog("expecting an NodeId for certificateGroupId - 0"); return { statusCode: StatusCodes.BadInvalidArgument }; } if (!expected(certificateTypeIdVariant, DataType.NodeId, VariantArrayType.Scalar)) { warningLog("expecting an NodeId for certificateTypeId - 1"); return { statusCode: StatusCodes.BadInvalidArgument }; } if (!expected(subjectNameVariant, DataType.String, VariantArrayType.Scalar)) { warningLog("expecting an String for subjectName - 2"); return { statusCode: StatusCodes.BadInvalidArgument }; } if (!expected(regeneratePrivateKeyVariant, DataType.Boolean, VariantArrayType.Scalar)) { warningLog("expecting an Boolean for regeneratePrivateKey - 3"); return { statusCode: StatusCodes.BadInvalidArgument }; } if (!expected(nonceVariant, DataType.ByteString, VariantArrayType.Scalar)) { warningLog("expecting an ByteString for nonceVariant - 4"); return { statusCode: StatusCodes.BadInvalidArgument }; } if (!hasEncryptedChannel(context)) { return { statusCode: StatusCodes.BadSecurityModeInsufficient }; } if (!hasExpectedUserAccess(context)) { return { statusCode: StatusCodes.BadUserAccessDenied }; } const certificateGroupId = certificateGroupIdVariant.value as NodeId; const certificateTypeId = certificateTypeIdVariant.value as NodeId; const subjectName = subjectNameVariant.value as string; const regeneratePrivateKey = regeneratePrivateKeyVariant.value as boolean; const nonce = nonceVariant.value as Buffer; const pushCertificateManager = getPushCertificateManager(this); if (!pushCertificateManager) { return { statusCode: StatusCodes.BadNotImplemented }; } const result: CreateSigningRequestResult = await pushCertificateManager.createSigningRequest( certificateGroupId, certificateTypeId, subjectName, regeneratePrivateKey, nonce ); if (result.statusCode !== StatusCodes.Good) { return { statusCode: result.statusCode }; } const callMethodResult = { outputArguments: [ { dataType: DataType.ByteString, value: result.certificateSigningRequest } ], statusCode: result.statusCode }; return callMethodResult; } async function _updateCertificate( this: UAMethod, inputArguments: Variant[], context: ISessionContext ): Promise<CallMethodResultOptions> { const certificateGroupId: NodeId = inputArguments[0].value as NodeId; const certificateTypeId: NodeId = inputArguments[1].value as NodeId; const certificate: Buffer = inputArguments[2].value as Buffer; const issuerCertificates: Buffer[] = inputArguments[3].value as Buffer[]; const privateKeyFormat: UAString = inputArguments[4].value as UAString; const privateKey: Buffer = inputArguments[5].value as ByteString; // This Method requires an encrypted channel and that the Client provides credentials with // administrative rights on the Server if (!hasEncryptedChannel(context)) { return { statusCode: StatusCodes.BadSecurityModeInsufficient }; } if (!hasExpectedUserAccess(context)) { return { statusCode: StatusCodes.BadUserAccessDenied }; } if (privateKeyFormat && privateKeyFormat !== "" && privateKeyFormat.toLowerCase() !== "pem") { errorLog("_updateCertificate: Invalid PEM format requested " + privateKeyFormat); return { statusCode: StatusCodes.BadInvalidArgument }; } const pushCertificateManager = getPushCertificateManager(this); if (!pushCertificateManager) { return { statusCode: StatusCodes.BadNotImplemented }; } const result = await pushCertificateManager.updateCertificate( certificateGroupId, certificateTypeId, certificate, issuerCertificates, privateKeyFormat, privateKey, ); // todo raise a CertificateUpdatedAuditEventType if (result.statusCode !== StatusCodes.Good) { return { statusCode: result.statusCode }; } const callMethodResult = { outputArguments: [ { dataType: DataType.Boolean, value: !!result.applyChangesRequired! } ], statusCode: result.statusCode }; return callMethodResult; } async function _getRejectedList( this: UAMethod, inputArguments: Variant[], context: ISessionContext ): Promise<CallMethodResultOptions> { if (!hasEncryptedChannel(context)) { return { statusCode: StatusCodes.BadSecurityModeInsufficient }; } if (!hasExpectedUserAccess(context)) { return { statusCode: StatusCodes.BadUserAccessDenied }; } const pushCertificateManager = getPushCertificateManager(this); if (!pushCertificateManager) { return { statusCode: StatusCodes.BadNotImplemented }; } const result = await pushCertificateManager.getRejectedList(); if (result.statusCode !== StatusCodes.Good) { return { statusCode: result.statusCode }; } return { outputArguments: [ { arrayType: VariantArrayType.Array, dataType: DataType.ByteString, value: result.certificates } ], statusCode: StatusCodes.Good }; } async function _applyChanges( this: UAMethod, inputArguments: Variant[], context: ISessionContext ): Promise<CallMethodResultOptions> { // This Method requires an encrypted channel and that the Client provide credentials with // administrative rights on the Server. if (!hasEncryptedChannel(context)) { return { statusCode: StatusCodes.BadSecurityModeInsufficient }; } if (!hasExpectedUserAccess(context)) { return { statusCode: StatusCodes.BadUserAccessDenied }; } const pushCertificateManager = getPushCertificateManager(this); if (!pushCertificateManager) { return { statusCode: StatusCodes.BadNotImplemented }; } const statusCode = await pushCertificateManager.applyChanges(); return { statusCode }; } function bindCertificateManager( addressSpace: AddressSpace, options: PushCertificateManagerServerOptions ) { const serverConfiguration = addressSpace.rootFolder.objects.server.getChildByName("ServerConfiguration")! as UAServerConfiguration; const defaultApplicationGroup = serverConfiguration.certificateGroups.getComponentByName("DefaultApplicationGroup"); if (defaultApplicationGroup) { const trustList = defaultApplicationGroup.getComponentByName("TrustList"); if (trustList) { (trustList as any).$$certificateManager = options.applicationGroup; } } const defaultTokenGroup = serverConfiguration.certificateGroups.getComponentByName("DefaultUserTokenGroup"); if (defaultTokenGroup) { const trustList = defaultTokenGroup.getComponentByName("TrustList"); if (trustList) { (trustList as any).$$certificateManager = options.userTokenGroup; } } } export async function promoteCertificateGroup(certificateGroup: UAObject) { const trustList = certificateGroup.getChildByName("TrustList") as UATrustList; if (trustList) { promoteTrustList(trustList); } } export async function installPushCertificateManagement( addressSpace: AddressSpace, options: PushCertificateManagerServerOptions ): Promise<void> { const serverConfiguration = addressSpace.rootFolder.objects.server.getChildByName("ServerConfiguration")! as UAServerConfiguration; const serverConfigurationPriv = serverConfiguration as any; if (serverConfigurationPriv.$pushCertificateManager) { warningLog("PushCertificateManagement has already been installed"); return; } const accessRestrictionFlag = AccessRestrictionsFlag.SigningRequired | AccessRestrictionsFlag.EncryptionRequired; function installAccessRestrictions(serverConfiguration: UAObject) { serverConfiguration.setRolePermissions(rolePermissionRestricted); serverConfiguration.setAccessRestrictions(AccessRestrictionsFlag.None); const applyName = serverConfiguration.getMethodByName("ApplyChanges"); applyName?.setRolePermissions(rolePermissionAdminOnly); applyName?.setAccessRestrictions(AccessRestrictionsFlag.SigningRequired | AccessRestrictionsFlag.EncryptionRequired); const createSigningRequest = serverConfiguration.getMethodByName("CreateSigningRequest"); createSigningRequest?.setRolePermissions(rolePermissionAdminOnly); createSigningRequest?.setAccessRestrictions(accessRestrictionFlag); const getRejectedList = serverConfiguration.getMethodByName("GetRejectedList"); getRejectedList?.setRolePermissions(rolePermissionAdminOnly); getRejectedList?.setAccessRestrictions(accessRestrictionFlag); const updateCertificate = serverConfiguration.getMethodByName("UpdateCertificate"); updateCertificate?.setRolePermissions(rolePermissionAdminOnly); updateCertificate?.setAccessRestrictions(accessRestrictionFlag); const certificateGroups = serverConfiguration.getComponentByName("CertificateGroups")!; certificateGroups.setRolePermissions(rolePermissionRestricted); certificateGroups.setAccessRestrictions(AccessRestrictionsFlag.None); function installAccessRestrictionOnGroup(group: UAObject) { const trustList = group.getComponentByName("TrustList")!; if (trustList) { installAccessRestrictionOnTrustList(trustList); } } for (const group of certificateGroups.getComponents()) { group?.setRolePermissions(rolePermissionAdminOnly); group?.setAccessRestrictions(AccessRestrictionsFlag.SigningRequired | AccessRestrictionsFlag.EncryptionRequired); if (group.nodeClass === NodeClass.Object) { installAccessRestrictionOnGroup(group as UAObject); } } } installAccessRestrictions(serverConfiguration) serverConfigurationPriv.$pushCertificateManager = new PushCertificateManagerServerImpl(options); serverConfiguration.supportedPrivateKeyFormats.setValueFromSource({ arrayType: VariantArrayType.Array, dataType: DataType.String, value: ["PEM"] }); function install_method_handle_on_type(addressSpace: AddressSpace): void { const serverConfigurationType = addressSpace.findObjectType("ServerConfigurationType")! as any; if (serverConfigurationType.createSigningRequest.isBound()) { return; } serverConfigurationType.createSigningRequest.bindMethod(callbackify(_createSigningRequest)); serverConfigurationType.getRejectedList.bindMethod(callbackify(_getRejectedList)); serverConfigurationType.updateCertificate.bindMethod(callbackify(_updateCertificate)); serverConfigurationType.applyChanges.bindMethod(callbackify(_applyChanges)); } install_method_handle_on_type(addressSpace); serverConfiguration.createSigningRequest.bindMethod(callbackify(_createSigningRequest)); serverConfiguration.updateCertificate.bindMethod(callbackify(_updateCertificate)); serverConfiguration.getRejectedList.bindMethod(callbackify(_getRejectedList)); if (serverConfiguration.applyChanges) { serverConfiguration.applyChanges!.bindMethod(callbackify(_applyChanges)); } installCertificateExpirationAlarm(addressSpace); const cg = serverConfiguration.certificateGroups.getComponents(); const defaultApplicationGroup = serverConfiguration.certificateGroups.getComponentByName("DefaultApplicationGroup")!; const certificateTypes = defaultApplicationGroup.getPropertyByName("CertificateTypes") as UAVariable; certificateTypes.setValueFromSource({ dataType: DataType.NodeId, arrayType: VariantArrayType.Array, value: [ resolveNodeId(ObjectTypeIds.RsaSha256ApplicationCertificateType) ] }); for (const certificateGroup of cg) { if (certificateGroup.nodeClass !== NodeClass.Object) { continue; } await promoteCertificateGroup(certificateGroup as UAObject); } await bindCertificateManager(addressSpace, options); }
the_stack
import {AnimationFrame} from '@material/animation/animationframe'; import {MDCFoundation} from '@material/base/foundation'; import {SpecificEventListener, SpecificWindowEventListener} from '@material/base/types'; import {MDCDialogAdapter} from './adapter'; import {cssClasses, numbers, strings} from './constants'; import {DialogConfigOptions} from './types'; enum AnimationKeys { POLL_SCROLL_POS = 'poll_scroll_position', POLL_LAYOUT_CHANGE = 'poll_layout_change' } export class MDCDialogFoundation extends MDCFoundation<MDCDialogAdapter> { static override get cssClasses() { return cssClasses; } static override get strings() { return strings; } static override get numbers() { return numbers; } static override get defaultAdapter(): MDCDialogAdapter { return { addBodyClass: () => undefined, addClass: () => undefined, areButtonsStacked: () => false, clickDefaultButton: () => undefined, eventTargetMatches: () => false, getActionFromEvent: () => '', getInitialFocusEl: () => null, hasClass: () => false, isContentScrollable: () => false, notifyClosed: () => undefined, notifyClosing: () => undefined, notifyOpened: () => undefined, notifyOpening: () => undefined, releaseFocus: () => undefined, removeBodyClass: () => undefined, removeClass: () => undefined, reverseButtons: () => undefined, trapFocus: () => undefined, registerContentEventHandler: () => undefined, deregisterContentEventHandler: () => undefined, isScrollableContentAtTop: () => false, isScrollableContentAtBottom: () => false, registerWindowEventHandler: () => undefined, deregisterWindowEventHandler: () => undefined, }; } private dialogOpen = false; private isFullscreen = false; private animationFrame = 0; private animationTimer = 0; private escapeKeyAction = strings.CLOSE_ACTION; private scrimClickAction = strings.CLOSE_ACTION; private autoStackButtons = true; private areButtonsStacked = false; private suppressDefaultPressSelector = strings.SUPPRESS_DEFAULT_PRESS_SELECTOR; private readonly contentScrollHandler: SpecificEventListener<'scroll'>; private readonly animFrame: AnimationFrame; private readonly windowResizeHandler: SpecificWindowEventListener<'resize'>; private readonly windowOrientationChangeHandler: SpecificWindowEventListener<'orientationchange'>; constructor(adapter?: Partial<MDCDialogAdapter>) { super({...MDCDialogFoundation.defaultAdapter, ...adapter}); this.animFrame = new AnimationFrame(); this.contentScrollHandler = () => { this.handleScrollEvent(); }; this.windowResizeHandler = () => { this.layout(); }; this.windowOrientationChangeHandler = () => { this.layout(); }; } override init() { if (this.adapter.hasClass(cssClasses.STACKED)) { this.setAutoStackButtons(false); } this.isFullscreen = this.adapter.hasClass(cssClasses.FULLSCREEN); } override destroy() { if (this.animationTimer) { clearTimeout(this.animationTimer); this.handleAnimationTimerEnd(); } if (this.isFullscreen) { this.adapter.deregisterContentEventHandler( 'scroll', this.contentScrollHandler); } this.animFrame.cancelAll(); this.adapter.deregisterWindowEventHandler( 'resize', this.windowResizeHandler); this.adapter.deregisterWindowEventHandler( 'orientationchange', this.windowOrientationChangeHandler); } open(dialogOptions?: DialogConfigOptions) { this.dialogOpen = true; this.adapter.notifyOpening(); this.adapter.addClass(cssClasses.OPENING); if (this.isFullscreen) { // A scroll event listener is registered even if the dialog is not // scrollable on open, since the window resize event, or orientation // change may make the dialog scrollable after it is opened. this.adapter.registerContentEventHandler( 'scroll', this.contentScrollHandler); } if (dialogOptions && dialogOptions.isAboveFullscreenDialog) { this.adapter.addClass(cssClasses.SCRIM_HIDDEN); } this.adapter.registerWindowEventHandler('resize', this.windowResizeHandler); this.adapter.registerWindowEventHandler( 'orientationchange', this.windowOrientationChangeHandler); // Wait a frame once display is no longer "none", to establish basis for // animation this.runNextAnimationFrame(() => { this.adapter.addClass(cssClasses.OPEN); this.adapter.addBodyClass(cssClasses.SCROLL_LOCK); this.layout(); this.animationTimer = setTimeout(() => { this.handleAnimationTimerEnd(); this.adapter.trapFocus(this.adapter.getInitialFocusEl()); this.adapter.notifyOpened(); }, numbers.DIALOG_ANIMATION_OPEN_TIME_MS); }); } close(action = '') { if (!this.dialogOpen) { // Avoid redundant close calls (and events), e.g. from keydown on elements // that inherently emit click return; } this.dialogOpen = false; this.adapter.notifyClosing(action); this.adapter.addClass(cssClasses.CLOSING); this.adapter.removeClass(cssClasses.OPEN); this.adapter.removeBodyClass(cssClasses.SCROLL_LOCK); if (this.isFullscreen) { this.adapter.deregisterContentEventHandler( 'scroll', this.contentScrollHandler); } this.adapter.deregisterWindowEventHandler( 'resize', this.windowResizeHandler); this.adapter.deregisterWindowEventHandler( 'orientationchange', this.windowOrientationChangeHandler); cancelAnimationFrame(this.animationFrame); this.animationFrame = 0; clearTimeout(this.animationTimer); this.animationTimer = setTimeout(() => { this.adapter.releaseFocus(); this.handleAnimationTimerEnd(); this.adapter.notifyClosed(action); }, numbers.DIALOG_ANIMATION_CLOSE_TIME_MS); } /** * Used only in instances of showing a secondary dialog over a full-screen * dialog. Shows the "surface scrim" displayed over the full-screen dialog. */ showSurfaceScrim() { this.adapter.addClass(cssClasses.SURFACE_SCRIM_SHOWING); this.runNextAnimationFrame(() => { this.adapter.addClass(cssClasses.SURFACE_SCRIM_SHOWN); }); } /** * Used only in instances of showing a secondary dialog over a full-screen * dialog. Hides the "surface scrim" displayed over the full-screen dialog. */ hideSurfaceScrim() { this.adapter.removeClass(cssClasses.SURFACE_SCRIM_SHOWN); this.adapter.addClass(cssClasses.SURFACE_SCRIM_HIDING); } /** * Handles `transitionend` event triggered when surface scrim animation is * finished. */ handleSurfaceScrimTransitionEnd() { this.adapter.removeClass(cssClasses.SURFACE_SCRIM_HIDING); this.adapter.removeClass(cssClasses.SURFACE_SCRIM_SHOWING); } isOpen() { return this.dialogOpen; } getEscapeKeyAction(): string { return this.escapeKeyAction; } setEscapeKeyAction(action: string) { this.escapeKeyAction = action; } getScrimClickAction(): string { return this.scrimClickAction; } setScrimClickAction(action: string) { this.scrimClickAction = action; } getAutoStackButtons(): boolean { return this.autoStackButtons; } setAutoStackButtons(autoStack: boolean) { this.autoStackButtons = autoStack; } getSuppressDefaultPressSelector(): string { return this.suppressDefaultPressSelector; } setSuppressDefaultPressSelector(selector: string) { this.suppressDefaultPressSelector = selector; } layout() { this.animFrame.request(AnimationKeys.POLL_LAYOUT_CHANGE, () => { this.layoutInternal(); }); } /** Handles click on the dialog root element. */ handleClick(evt: MouseEvent) { const isScrim = this.adapter.eventTargetMatches(evt.target, strings.SCRIM_SELECTOR); // Check for scrim click first since it doesn't require querying ancestors. if (isScrim && this.scrimClickAction !== '') { this.close(this.scrimClickAction); } else { const action = this.adapter.getActionFromEvent(evt); if (action) { this.close(action); } } } /** Handles keydown on the dialog root element. */ handleKeydown(evt: KeyboardEvent) { const isEnter = evt.key === 'Enter' || evt.keyCode === 13; if (!isEnter) { return; } const action = this.adapter.getActionFromEvent(evt); if (action) { // Action button callback is handled in `handleClick`, // since space/enter keydowns on buttons trigger click events. return; } // `composedPath` is used here, when available, to account for use cases // where a target meant to suppress the default press behaviour // may exist in a shadow root. // For example, a textarea inside a web component: // <mwc-dialog> // <horizontal-layout> // #shadow-root (open) // <mwc-textarea> // #shadow-root (open) // <textarea></textarea> // </mwc-textarea> // </horizontal-layout> // </mwc-dialog> const target = evt.composedPath ? evt.composedPath()[0] : evt.target; const isDefault = this.suppressDefaultPressSelector ? !this.adapter.eventTargetMatches( target, this.suppressDefaultPressSelector) : true; if (isEnter && isDefault) { this.adapter.clickDefaultButton(); } } /** Handles keydown on the document. */ handleDocumentKeydown(evt: KeyboardEvent) { const isEscape = evt.key === 'Escape' || evt.keyCode === 27; if (isEscape && this.escapeKeyAction !== '') { this.close(this.escapeKeyAction); } } /** * Handles scroll event on the dialog's content element -- showing a scroll * divider on the header or footer based on the scroll position. This handler * should only be registered on full-screen dialogs with scrollable content. */ private handleScrollEvent() { // Since scroll events can fire at a high rate, we throttle these events by // using requestAnimationFrame. this.animFrame.request(AnimationKeys.POLL_SCROLL_POS, () => { this.toggleScrollDividerHeader(); this.toggleScrollDividerFooter(); }); } private layoutInternal() { if (this.autoStackButtons) { this.detectStackedButtons(); } this.toggleScrollableClasses(); } private handleAnimationTimerEnd() { this.animationTimer = 0; this.adapter.removeClass(cssClasses.OPENING); this.adapter.removeClass(cssClasses.CLOSING); } /** * Runs the given logic on the next animation frame, using setTimeout to * factor in Firefox reflow behavior. */ private runNextAnimationFrame(callback: () => void) { cancelAnimationFrame(this.animationFrame); this.animationFrame = requestAnimationFrame(() => { this.animationFrame = 0; clearTimeout(this.animationTimer); this.animationTimer = setTimeout(callback, 0); }); } private detectStackedButtons() { // Remove the class first to let us measure the buttons' natural positions. this.adapter.removeClass(cssClasses.STACKED); const areButtonsStacked = this.adapter.areButtonsStacked(); if (areButtonsStacked) { this.adapter.addClass(cssClasses.STACKED); } if (areButtonsStacked !== this.areButtonsStacked) { this.adapter.reverseButtons(); this.areButtonsStacked = areButtonsStacked; } } private toggleScrollableClasses() { // Remove the class first to let us measure the natural height of the // content. this.adapter.removeClass(cssClasses.SCROLLABLE); if (this.adapter.isContentScrollable()) { this.adapter.addClass(cssClasses.SCROLLABLE); if (this.isFullscreen) { // If dialog is full-screen and scrollable, check if a scroll divider // should be shown. this.toggleScrollDividerHeader(); this.toggleScrollDividerFooter(); } } } private toggleScrollDividerHeader() { if (!this.adapter.isScrollableContentAtTop()) { this.adapter.addClass(cssClasses.SCROLL_DIVIDER_HEADER); } else if (this.adapter.hasClass(cssClasses.SCROLL_DIVIDER_HEADER)) { this.adapter.removeClass(cssClasses.SCROLL_DIVIDER_HEADER); } } private toggleScrollDividerFooter() { if (!this.adapter.isScrollableContentAtBottom()) { this.adapter.addClass(cssClasses.SCROLL_DIVIDER_FOOTER); } else if (this.adapter.hasClass(cssClasses.SCROLL_DIVIDER_FOOTER)) { this.adapter.removeClass(cssClasses.SCROLL_DIVIDER_FOOTER); } } } // tslint:disable-next-line:no-default-export Needed for backward compatibility with MDC Web v0.44.0 and earlier. export default MDCDialogFoundation;
the_stack
import { createElement, isNullOrUndefined, isObject, remove } from '@syncfusion/ej2-base'; import { Gantt } from '../base/gantt'; import * as cls from '../base/css-constants'; import { IGanttData, ITaskData, IConnectorLineObject, IPredecessor } from '../base/interface'; import { isScheduledTask } from '../base/utils'; /** * To render the connector line in Gantt */ export class ConnectorLine { private parent: Gantt; public dependencyViewContainer: HTMLElement; private lineColor: string; private lineStroke: number; public tooltipTable: HTMLElement; /** * @hidden */ public expandedRecords: IGanttData[]; constructor(ganttObj?: Gantt) { this.expandedRecords = []; this.parent = ganttObj; this.dependencyViewContainer = createElement('div', { className: cls.dependencyViewContainer }); this.initPublicProp(); } /** * To get connector line gap. * * @param {IConnectorLineObject} data . * @returns {number} . * @private */ private getconnectorLineGap(data: IConnectorLineObject): number { let width: number = 0; width = (data.milestoneChild ? ((this.parent.chartRowsModule.milestoneMarginTop / 2) + (this.parent.chartRowsModule.milestoneHeight / 2)) : ((this.parent.chartRowsModule.taskBarMarginTop / 2) + (this.parent.chartRowsModule.taskBarHeight / 2))); return width; } /** * To initialize the public property. * * @returns {void} * @private */ public initPublicProp(): void { this.lineColor = this.parent.connectorLineBackground; this.lineStroke = (this.parent.connectorLineWidth) > 4 ? 4 : this.parent.connectorLineWidth; this.createConnectorLineTooltipTable(); } private getTaskbarMidpoint(isMilestone: boolean): number { return Math.floor(isMilestone ? (this.parent.chartRowsModule.milestoneMarginTop + (this.parent.chartRowsModule.milestoneHeight / 2)) : (this.parent.chartRowsModule.taskBarMarginTop + (this.parent.chartRowsModule.taskBarHeight / 2))) + 1; } /** * To connector line object collection. * * @param {IGanttData} parentGanttData . * @param {IGanttData} childGanttData . * @param {IPredecessor} predecessor . * @returns {void} * @private */ public createConnectorLineObject(parentGanttData: IGanttData, childGanttData: IGanttData, predecessor: IPredecessor): IConnectorLineObject { const connectorObj: IConnectorLineObject = {} as IConnectorLineObject; const updatedRecords: IGanttData[] = this.parent.pdfExportModule && this.parent.pdfExportModule.isPdfExport ? this.parent.flatData : this.expandedRecords; const parentIndex: number = updatedRecords.indexOf(parentGanttData); const childIndex: number = updatedRecords.indexOf(childGanttData); const parentGanttRecord: ITaskData = parentGanttData.ganttProperties; const childGanttRecord: ITaskData = childGanttData.ganttProperties; const currentData: IGanttData[] = this.parent.virtualScrollModule && this.parent.enableVirtualization ? this.parent.currentViewData : this.parent.getExpandedRecords(this.parent.currentViewData); connectorObj.parentIndexInCurrentView = currentData.indexOf(parentGanttData); connectorObj.childIndexInCurrentView = currentData.indexOf(childGanttData); const isVirtualScroll: boolean = this.parent.virtualScrollModule && this.parent.enableVirtualization; if ((!isVirtualScroll && (connectorObj.parentIndexInCurrentView === -1 || connectorObj.childIndexInCurrentView === -1)) || connectorObj.parentIndexInCurrentView === -1 && connectorObj.childIndexInCurrentView === -1) { return null; } else { connectorObj.parentLeft = parentGanttRecord.isMilestone ? parentGanttRecord.left - (this.parent.chartRowsModule.milestoneHeight / 2) : parentGanttRecord.left; connectorObj.childLeft = childGanttRecord.isMilestone ? childGanttRecord.left - (this.parent.chartRowsModule.milestoneHeight / 2) : childGanttRecord.left; connectorObj.parentWidth = parentGanttRecord.width === 0 || parentGanttRecord.isMilestone ? (Math.floor(this.parent.chartRowsModule.milestoneHeight)) : parentGanttRecord.width; connectorObj.childWidth = childGanttRecord.width === 0 || childGanttRecord.isMilestone ? (Math.floor(this.parent.chartRowsModule.milestoneHeight)) : childGanttRecord.width; connectorObj.parentIndex = parentIndex; connectorObj.childIndex = childIndex; const rowHeight: number = this.parent.ganttChartModule.getChartRows()[0] && this.parent.ganttChartModule.getChartRows()[0].getBoundingClientRect().height; connectorObj.rowHeight = rowHeight && !isNaN(rowHeight) ? rowHeight : this.parent.rowHeight; connectorObj.type = predecessor.type; const parentId: string = this.parent.viewType === 'ResourceView' ? parentGanttRecord.taskId : parentGanttRecord.rowUniqueID; const childId: string = this.parent.viewType === 'ResourceView' ? childGanttRecord.taskId : childGanttRecord.rowUniqueID; connectorObj.connectorLineId = 'parent' + parentId + 'child' + childId; connectorObj.milestoneParent = parentGanttRecord.isMilestone ? true : false; connectorObj.milestoneChild = childGanttRecord.isMilestone ? true : false; if (isNullOrUndefined(isScheduledTask(parentGanttRecord)) || isNullOrUndefined(isScheduledTask(childGanttRecord))) { return null; } else { return connectorObj; } } } /** * To render connector line. * * @param {IConnectorLineObject} connectorLinesCollection . * @returns {void} * @private */ public renderConnectorLines(connectorLinesCollection: IConnectorLineObject[]): void { let connectorLine: string = ''; const ariaConnector : IConnectorLineObject[] = []; for (let index: number = 0; index < connectorLinesCollection.length; index++) { connectorLine = connectorLine + this.getConnectorLineTemplate(connectorLinesCollection[index]); ariaConnector.push(connectorLinesCollection[index]); } this.dependencyViewContainer.innerHTML = connectorLine; const childNodes: NodeList = this.parent.connectorLineModule.dependencyViewContainer.childNodes; for (let i: number = 0; i < childNodes.length; i++) { const innerChild: NodeList = childNodes[i].childNodes; for (let j: number = 0; j < innerChild.length; j++) { const ariaString: string = this.parent.connectorLineModule.generateAriaLabel(ariaConnector[i]); (<HTMLElement>innerChild[j]).setAttribute('aria-label', ariaString); } } this.parent.ganttChartModule.chartBodyContent.appendChild(this.dependencyViewContainer); } /** * To get parent position. * * @param {IConnectorLineObject} data . * @returns {void} * @private */ private getParentPosition(data: IConnectorLineObject): string { if (data.parentIndex < data.childIndex) { if (data.type === 'FF') { if ((data.childLeft + data.childWidth) >= (data.parentLeft + data.parentWidth)) { return 'FFType2'; } else { return 'FFType1'; } } else if ((data.parentLeft < data.childLeft) && (data.childLeft > (data.parentLeft + data.parentWidth + 25))) { if (data.type === 'FS') { return 'FSType1'; } if (data.type === 'SF') { return 'SFType1'; } else if (data.type === 'SS') { return 'SSType2'; } else if (data.type === 'FF') { return 'FFType2'; } } else if ((data.parentLeft < data.childLeft && (data.childLeft < (data.parentLeft + data.parentWidth))) || (data.parentLeft === data.childLeft || data.parentLeft > data.childLeft)) { if (data.parentLeft > (data.childLeft + data.childWidth + 25)) { if (data.type === 'SF') { return 'SFType2'; } } if (data.parentLeft > data.childLeft) { if (data.type === 'SS') { return 'SSType1'; } if (data.type === 'SF') { return 'SFType1'; } if (data.type === 'FF') { return 'FFType1'; } } else if ((data.childLeft + data.childWidth) > (data.parentLeft + data.parentWidth)) { if (data.type === 'FF') { return 'FFType2'; } } if (data.type === 'FS') { return 'FSType2'; } else if (data.type === 'SS') { return 'SSType2'; } else if (data.type === 'FF') { return 'FFType1'; } else if (data.type === 'SF') { return 'SFType1'; } } else if ((data.parentLeft) < data.childLeft) { if (data.type === 'FS') { return 'FSType2'; } else if (data.type === 'FF') { return 'FFType2'; } else if (data.type === 'SS') { return 'SSType2'; } else if (data.type === 'SF') { return 'SFType1'; } } } else if (data.parentIndex > data.childIndex) { if ((data.parentLeft < data.childLeft) && (data.childLeft > (data.parentLeft + data.parentWidth))) { if (data.type === 'FS') { if (30 >= (data.childLeft - (data.milestoneParent ? (data.parentLeft + data.parentWidth + 4) : (data.parentLeft + data.parentWidth)))) { return 'FSType3'; } else { return 'FSType4'; } } if (data.parentLeft < data.childLeft || ((data.childLeft + data.childWidth) > (data.parentLeft + data.parentWidth))) { if (data.type === 'SS') { return 'SSType4'; } if (data.type === 'FF') { return 'FFType4'; } if (data.type === 'SF') { return 'SFType4'; } // eslint-disable-next-line } else if ((data.childLeft + data.childWidth) > (data.parentLeft + data.parentWidth)) { if (data.type === 'FF') { return 'FFType4'; } } } else if ((data.parentLeft < data.childLeft && (data.childLeft < (data.parentLeft + data.parentWidth))) || (data.parentLeft === data.childLeft || data.parentLeft > data.childLeft)) { if ((data.childLeft + data.childWidth) <= (data.parentLeft + data.parentWidth)) { if (data.type === 'FF') { return 'FFType3'; } if (data.type === 'SF') { if ((data.childLeft + data.childWidth + 25) < (data.parentLeft)) { return 'SFType3'; } else { return 'SFType4'; } } if (data.type === 'SS') { if (data.childLeft <= data.parentLeft) { return 'SSType3'; } else { return 'SSType4'; } } } else if ((data.childLeft + data.childWidth) > (data.parentLeft + data.parentWidth)) { if (data.type === 'FF') { return 'FFType4'; } if (data.type === 'SF') { return 'SFType4'; } if (data.type === 'SS') { if (data.childLeft <= data.parentLeft) { return 'SSType3'; } else { return 'SSType4'; } } } if (data.type === 'FS') { return 'FSType3'; } } else if (data.parentLeft < data.childLeft) { if (data.type === 'FS') { return 'FSType3'; } if (data.type === 'SS') { return 'SSType4'; } if (data.type === 'FF') { return 'FFType4'; } if (data.type === 'SF') { return 'SFType4'; } } } return null; } /** * To get line height. * * @param {IConnectorLineObject} data . * @returns {void} * @private */ private getHeightValue(data: IConnectorLineObject): number { return (data.parentIndex * data.rowHeight) > (data.childIndex * data.rowHeight) ? ((data.parentIndex * data.rowHeight) - (data.childIndex * data.rowHeight)) : ((data.childIndex * data.rowHeight) - (data.parentIndex * data.rowHeight)); } /** * To get sstype2 inner element width. * * @param {IConnectorLineObject} data . * @returns {void} * @private */ private getInnerElementWidthSSType2(data: IConnectorLineObject): number { if (data.parentLeft === data.childLeft) { return 10; } return (data.childLeft - data.parentLeft); } /** * To get sstype2 inner element left. * * @param {IConnectorLineObject} data . * @returns {void} * @private */ private getInnerElementLeftSSType2(data: IConnectorLineObject): number { if (data.parentLeft === data.childLeft) { return (data.parentLeft - 20); } return (data.parentLeft - 10); } /** * To get sstype2 inner child element width. * * @param {IConnectorLineObject} data . * @returns {void} * @private */ private getInnerChildWidthSSType2(data: IConnectorLineObject): number { if ((data.parentLeft + data.parentWidth) < data.childLeft) { return 10; } if (data.parentLeft === data.childLeft) { return 20; } if ((data.parentLeft + data.parentWidth) >= data.childLeft) { return 10; } return (data.childLeft - data.parentLeft); } private getBorderStyles(cssType: string, unit: number): string { const borderWidth: string = 'border-' + cssType + '-width:' + unit + 'px;'; const borderStyle: string = 'border-' + cssType + '-style:solid;'; const borderColor: string = !isNullOrUndefined(this.lineColor) ? 'border-' + cssType + '-color:' + this.lineColor + ';' : ''; return (borderWidth + borderStyle + borderColor); } /** * To get connector line template. * * @param {IConnectorLineObject} data . * @returns {void} * @private */ public getConnectorLineTemplate(data: IConnectorLineObject): string { const setInnerChildWidthSSType2: number = this.getInnerChildWidthSSType2(data); const setInnerElementWidthSSType2: number = this.getInnerElementWidthSSType2(data); const setInnerElementLeftSSType2: number = this.getInnerElementLeftSSType2(data); const height: number = this.getHeightValue(data); const isMilestoneParent: boolean = data.milestoneParent ? true : false; const isMilestone: boolean = data.milestoneChild ? true : false; let connectorContainer: string = ''; const isVirtual: boolean = this.parent.virtualScrollModule && this.parent.enableVirtualization; const connectorLine: { top: number, height: number } = this.getPosition(data, this.getParentPosition(data), height); const heightValue: number = isVirtual ? connectorLine.height : height; if (this.getParentPosition(data)) { connectorContainer = '<div id="ConnectorLine' + data.connectorLineId + '" style="background-color:black">'; let div: string = '<div class="' + cls.connectorLineContainer + '" tabindex="-1" style="'; const eLine: string = '<div class="' + cls.connectorLine + '" style="' + (!isNullOrUndefined(this.lineColor) ? 'outline-color:' + this.lineColor + ';' : ''); const rightArrow: string = '<div class="' + cls.connectorLineRightArrow + '" style="' + (!isNullOrUndefined(this.lineColor) ? 'outline-color:' + this.lineColor + ';' : ''); const leftArrow: string = '<div class="' + cls.connectorLineLeftArrow + '" style="' + (!isNullOrUndefined(this.lineColor) ? 'outline-color:' + this.lineColor + ';' : ''); const duplicateStingOne: string = leftArrow + (isMilestone ? 'left:0px;' : '') + this.getBorderStyles('right', 10) + 'top:' + (-5 - this.lineStroke + (this.lineStroke - 1)) + 'px;border-bottom-width:' + (5 + this.lineStroke) + 'px;' + 'border-top-width:' + (5 + this.lineStroke) + 'px;width:0;height:0;position:relative;"></div>'; const duplicateStingTwo: string = this.getBorderStyles('left', 10) + 'top:' + (-6) + 'px;border-bottom-width:' + (5 + this.lineStroke) + 'px;' + 'border-top-width:' + (5 + this.lineStroke) + 'px;width:0;height:0;position:relative;"></div>'; const duplicateStingThree: string = this.getBorderStyles('top', this.lineStroke) + 'position:relative;"></div>' + eLine + 'top:' + (- (13 + ((this.lineStroke - 1) * 2))) + 'px;width:0px;' + this.getBorderStyles('left', this.lineStroke) + this.getBorderStyles('top', (heightValue - (this.lineStroke - 1))) + 'position:relative;"></div>'; const duplicateStingFour: string = leftArrow + 'left:' + (((data.childLeft + data.childWidth) - (data.parentLeft)) + 10) + 'px;' + this.getBorderStyles('right', 10); const duplicateStingFive: string = 'top:' + (-(6 + (5 + this.lineStroke) + (this.lineStroke / 2))) + 'px;' + this.getBorderStyles('top', this.lineStroke) + 'position:relative;"></div>'; if (this.getParentPosition(data) === 'FSType1') { div = div + 'left:' + (data.parentLeft + data.parentWidth) + 'px;top:' + (isVirtual ? connectorLine.top : ((data.parentIndex * data.rowHeight) + this.getTaskbarMidpoint(isMilestone) - (this.lineStroke - 1))) + 'px;' + 'width:1px;height:' + heightValue + 'px;position:absolute" data-connectortype="FSType1">'; div = div + eLine; div = div + 'left:' + (isMilestoneParent ? -1 : 0) + 'px;width:' + (isMilestoneParent ? ((((data.childLeft - (data.parentLeft + data.parentWidth + 10)) + this.lineStroke) - 10) + 1) : (((data.childLeft - (data.parentLeft + data.parentWidth + 10)) + this.lineStroke) - 10)) + 'px;' + this.getBorderStyles('top', this.lineStroke) + 'position:relative;"></div>'; div = div + eLine; div = div + 'left:' + ((data.childLeft - (data.parentLeft + data.parentWidth + 10)) - 10) + 'px;' + 'width:0px;' + this.getBorderStyles('right', this.lineStroke) + this.getBorderStyles('top', (heightValue - this.lineStroke)) + 'position:relative;"></div>'; div = div + eLine; div = div + 'left:' + ((data.childLeft - (data.parentLeft + data.parentWidth + 10)) - 10) + 'px;width:10px;' + this.getBorderStyles('top', this.lineStroke) + 'position:relative;"></div>'; div = div + rightArrow; div = div + 'left:' + (data.childLeft - (data.parentLeft + data.parentWidth + 10)) + 'px;' + this.getBorderStyles('left', 10) + 'top:' + (-6 - this.lineStroke) + 'px;border-bottom-width:' + (5 + this.lineStroke) + 'px;border-top-width:' + (5 + this.lineStroke) + 'px;width:0;height:0;position:relative;"></div></div>'; } if (this.getParentPosition(data) === 'FSType2') { div = div + 'left:' + data.parentLeft + 'px;top:' + (isVirtual ? connectorLine.top : ((data.parentIndex * data.rowHeight) + this.getTaskbarMidpoint(isMilestone) - (this.lineStroke - 1))) + 'px;' + 'width:1px;height:' + heightValue + 'px;position:absolute" data-connectortype="FSType2">'; div = div + eLine; div = div + 'left:' + (isMilestoneParent ? data.parentWidth - 1 : data.parentWidth) + 'px;width:' + (isMilestoneParent ? 11 : 10) + 'px;' + this.getBorderStyles('top', this.lineStroke) + 'position:relative;"></div>'; div = div + eLine; div = div + 'left:' + (data.parentWidth + 10 - this.lineStroke) + 'px;' + this.getBorderStyles('left', this.lineStroke) + 'width:0px;' + this.getBorderStyles( 'top', (heightValue - this.getconnectorLineGap(data) - this.lineStroke)) + 'position:relative;"></div>'; div = div + eLine; div = div + 'left:' + (data.parentWidth - (((data.parentLeft + data.parentWidth) - data.childLeft) + 20)) + 'px;' + 'width:' + (((data.parentLeft + data.parentWidth) - data.childLeft) + 30) + 'px;' + this.getBorderStyles('top', this.lineStroke) + 'position:relative;"></div>'; div = div + eLine; div = div + 'left:' + (data.parentWidth - (((data.parentLeft + data.parentWidth) - data.childLeft) + 20)) + 'px;width:0px;' + this.getBorderStyles('top', (this.getconnectorLineGap(data) - this.lineStroke)) + this.getBorderStyles('left', this.lineStroke) + 'position:relative;"></div>'; div = div + eLine; div = div + 'left:' + (data.parentWidth - (((data.parentLeft + data.parentWidth) - data.childLeft) + 20)) + 'px;width:10px;' + this.getBorderStyles('top', this.lineStroke) + 'position:relative;"></div>'; div = div + rightArrow; div = div + 'left:' + (data.parentWidth - (((data.parentLeft + data.parentWidth) - data.childLeft) + 10)) + 'px;' + this.getBorderStyles('left', 10) + 'border-bottom-width:' + (5 + this.lineStroke) + 'px;' + 'border-top-width:' + (5 + this.lineStroke) + 'px;top:' + (-6 - this.lineStroke) + 'px;width:0;height:0;position:relative;"></div></div>'; } if (this.getParentPosition(data) === 'FSType3') { div = div + 'left:' + (data.childLeft - 20) + 'px;top:' + (isVirtual ? connectorLine.top : ((data.childIndex * data.rowHeight) + this.getTaskbarMidpoint(isMilestoneParent) - (this.lineStroke - 1))) + 'px;' + 'width:1px;height:' + heightValue + 'px;position:absolute" data-connectortype="FSType3">'; div = div + rightArrow; div = div + 'left:10px;' + this.getBorderStyles('left', 10) + 'border-bottom-width:' + (5 + this.lineStroke) + 'px;border-top-width:' + (5 + this.lineStroke) + 'px;' + 'top:' + (-6) + 'px;width:0;height:0;position:relative;"></div>'; div = div + eLine; div = div + 'width:10px;' + this.getBorderStyles('top', this.lineStroke) + 'position:relative;top:' + (-(6 + (5 + this.lineStroke) + Math.round(this.lineStroke / 2))) + 'px;"></div>'; div = div + eLine; div = div + 'width:' + this.lineStroke + 'px;' + this.getBorderStyles( 'top', (heightValue - this.getconnectorLineGap(data) - this.lineStroke + 1)) + 'position:relative;top:' + (- (13 + ((this.lineStroke - 1) * 2))) + 'px;"></div>'; div = div + eLine; div = div + 'width:' + (((data.parentLeft + data.parentWidth) - data.childLeft) + 30) + 'px;' + this.getBorderStyles('top', this.lineStroke) + 'position:relative;top:' + (- (13 + ((this.lineStroke - 1) * 2))) + 'px;"></div>'; div = div + eLine; div = div + 'left:' + (((data.parentLeft + data.parentWidth) - data.childLeft) + (30 - this.lineStroke)) + 'px;width:0px;' + 'height:' + (this.getconnectorLineGap(data) - this.lineStroke) + 'px;' + this.getBorderStyles('left', this.lineStroke) + 'position:relative;' + 'top:' + (- (13 + ((this.lineStroke - 1) * 2))) + 'px;"></div>'; div = div + eLine; div = div + (isMilestoneParent ? 'left:' + (((data.parentLeft + data.parentWidth) - data.childLeft) + (18 - this.lineStroke)) + 'px;width:' + (12 + this.lineStroke) + 'px;' : 'left:' + (((data.parentLeft + data.parentWidth) - data.childLeft) + 20) + 'px;width:10px;') + this.getBorderStyles('top', this.lineStroke) + 'position:relative;top:' + (- (13 + ((this.lineStroke - 1) * 2))) + 'px;"></div></div>'; } if (this.getParentPosition(data) === 'FSType4') { div = div + 'left:' + (data.parentLeft + data.parentWidth) + 'px;top:' + (isVirtual ? connectorLine.top : ((data.childIndex * data.rowHeight) + this.getTaskbarMidpoint(isMilestone) - (this.lineStroke - 1))) + 'px;' + 'width:1px;height:' + heightValue + 'px;position:absolute" data-connectortype="FSType4">'; div = div + rightArrow; div = div + 'left:' + (data.childLeft - (data.parentLeft + data.parentWidth + 10)) + 'px;' + this.getBorderStyles('left', 10) + 'top:' + (-6) + 'px;' + 'border-bottom-width:' + (5 + this.lineStroke) + 'px;border-top-width:' + (5 + this.lineStroke) + 'px;width:0;height:0;position:relative;"></div>'; div = div + eLine; div = div + 'left:' + (data.childLeft - (data.parentLeft + data.parentWidth) - 20) + 'px;top:' + (-(6 + (5 + this.lineStroke) + Math.round(this.lineStroke / 2))) + 'px;width:10px;' + this.getBorderStyles('top', this.lineStroke) + 'position:relative;"></div>'; div = div + eLine; div = div + 'top:' + (- (13 + ((this.lineStroke - 1) * 2))) + 'px;left:' + (data.childLeft - (data.parentLeft + data.parentWidth) - 20) + 'px;width:0px;' + this.getBorderStyles('left', this.lineStroke) + this.getBorderStyles('top', (heightValue - this.lineStroke + 1)) + 'position:relative;"></div>'; div = div + eLine; div = div + (isMilestoneParent ? 'left:-1px;' : '') + 'top:' + (- (13 + ((this.lineStroke - 1) * 2))) + 'px;width:' + (isMilestoneParent ? ((data.childLeft - (data.parentLeft + data.parentWidth + 20) + 1) + this.lineStroke) : ((data.childLeft - (data.parentLeft + data.parentWidth + 20)) + this.lineStroke)) + 'px;' + this.getBorderStyles('top', this.lineStroke) + 'position:relative;"></div></div>'; } if (this.getParentPosition(data) === 'SSType4') { div = div + 'left:' + (data.parentLeft - 10) + 'px;top:' + (isVirtual ? connectorLine.top : ((data.childIndex * data.rowHeight) + this.getTaskbarMidpoint(isMilestone) - (this.lineStroke - 1))) + 'px;' + 'width:1px;height:' + heightValue + 'px;position:absolute" data-connectortype="SSType4">'; div = div + rightArrow; div = div + 'left:' + (data.childLeft - data.parentLeft) + 'px;' + duplicateStingTwo; div = div + eLine; div = div + 'top:' + (-(6 + (5 + this.lineStroke) + (this.lineStroke / 2))) + 'px;width:' + (data.childLeft - data.parentLeft) + 'px;' + duplicateStingThree; div = div + eLine; div = div + 'top:' + (- (13 + ((this.lineStroke - 1) * 2))) + 'px;width:10px;' + this.getBorderStyles('top', this.lineStroke) + 'position:relative;"></div></div>'; } if (this.getParentPosition(data) === 'SSType3') { div = div + 'left:' + (data.childLeft - 20) + 'px;top:' + (isVirtual ? connectorLine.top : ((data.childIndex * data.rowHeight) + this.getTaskbarMidpoint(isMilestone) - (this.lineStroke - 1))) + 'px;' + 'width:1px;height:' + heightValue + 'px;position:absolute" data-connectortype="SSType3">'; div = div + rightArrow; div = div + 'left:10px;' + duplicateStingTwo; div = div + eLine; div = div + 'top:' + (-(6 + (5 + this.lineStroke) + (this.lineStroke / 2))) + 'px;width:10px;' + duplicateStingThree; div = div + eLine; div = div + 'top:' + (- (13 + ((this.lineStroke - 1) * 2))) + 'px;width:' + (data.parentLeft - data.childLeft + 21) + 'px;' + this.getBorderStyles('top', this.lineStroke) + 'position:relative;"></div></div>'; } if (this.getParentPosition(data) === 'SSType2') { div = div + 'left:' + setInnerElementLeftSSType2 + 'px;top:' + (isVirtual ? connectorLine.top : ((data.parentIndex * data.rowHeight) + this.getTaskbarMidpoint(isMilestoneParent) - (this.lineStroke - 1))) + 'px;' + 'width:1px;height:' + heightValue + 'px;position:absolute" data-connectortype="SSType2">'; div = div + eLine; div = div + 'width:' + (setInnerChildWidthSSType2 + 1) + 'px;' + this.getBorderStyles('top', this.lineStroke) + 'position:relative;"></div>'; div = div + eLine; div = div + 'width:0px;' + this.getBorderStyles('left', this.lineStroke) + this.getBorderStyles('top', (heightValue - this.lineStroke)) + 'position:relative;"></div>'; div = div + eLine; div = div + 'width:' + setInnerElementWidthSSType2 + 'px;' + this.getBorderStyles('top', this.lineStroke) + 'position:relative;"></div>'; div = div + rightArrow; div = div + 'left:' + setInnerElementWidthSSType2 + 'px;' + this.getBorderStyles('left', 10) + 'top:' + (-6 - this.lineStroke) + 'px;' + 'border-bottom-width:' + (5 + this.lineStroke) + 'px;border-top-width:' + (5 + this.lineStroke) + 'px;width:0;' + 'height:0;position:relative;"></div></div>'; } if (this.getParentPosition(data) === 'SSType1') { div = div + 'left:' + (data.childLeft - 20) + 'px;top:' + (isVirtual ? connectorLine.top : ((data.parentIndex * data.rowHeight) + this.getTaskbarMidpoint(isMilestoneParent) - (this.lineStroke - 1))) + 'px;' + 'width:1px;height:' + heightValue + 'px;position:absolute" data-connectortype="SSType1">'; div = div + eLine; div = div + 'width:' + (data.parentLeft - data.childLeft + 21) + 'px;' + this.getBorderStyles('top', this.lineStroke) + 'position:relative;"></div>'; div = div + eLine; div = div + 'width:0px;' + this.getBorderStyles('left', this.lineStroke) + this.getBorderStyles('top', (heightValue - this.lineStroke)) + 'position:relative;"></div>'; div = div + eLine; div = div + 'width:10px;' + this.getBorderStyles('top', this.lineStroke) + 'position:relative;"></div>'; div = div + rightArrow; div = div + 'left:10px;' + this.getBorderStyles('left', 10) + 'top:' + (-6 - this.lineStroke) + 'px;border-bottom-width:' + (5 + this.lineStroke) + 'px;' + 'border-top-width:' + (5 + this.lineStroke) + 'px;width:0;height:0;position:relative;"></div></div>'; } if (this.getParentPosition(data) === 'FFType1') { div = div + 'left:' + (data.childLeft + data.childWidth) + 'px;top:' + (isVirtual ? connectorLine.top : ((data.parentIndex * data.rowHeight) + this.getTaskbarMidpoint(isMilestoneParent) - (this.lineStroke - 1))) + 'px;' + 'width:1px;height:' + heightValue + 'px;position:absolute" data-connectortype="FFType1">'; div = div + eLine; div = div + 'left:' + (isMilestoneParent ? (((data.parentLeft + data.parentWidth) - (data.childLeft + data.childWidth)) - 1) : ((data.parentLeft + data.parentWidth) - (data.childLeft + data.childWidth))) + 'px;' + 'width:' + (isMilestoneParent ? (21 + this.lineStroke) : (20 + this.lineStroke)) + 'px;' + this.getBorderStyles('top', this.lineStroke) + 'position:relative;"></div>'; div = div + eLine; div = div + 'left:' + (((data.parentLeft + data.parentWidth) - (data.childLeft + data.childWidth)) + 20) + 'px;width:0px;' + this.getBorderStyles('left', this.lineStroke) + this.getBorderStyles('top', (heightValue - this.lineStroke)) + 'position:relative;"></div>'; div = div + eLine; div = div + 'left:' + (isMilestone ? 4 : 10) + 'px;width:' + (isMilestone ? (((data.parentLeft + data.parentWidth) - (data.childLeft + data.childWidth)) + (16 + this.lineStroke)) : (((data.parentLeft + data.parentWidth) - (data.childLeft + data.childWidth)) + (10 + this.lineStroke))) + 'px;' + this.getBorderStyles('top', this.lineStroke) + 'position:relative;"></div>'; div = div + leftArrow; div = div + (isMilestone ? 'left:0px;' : '') + this.getBorderStyles('right', 10) + 'top:' + (-6 - this.lineStroke) + 'px;border-bottom-width:' + (5 + this.lineStroke) + 'px;' + 'border-top-width:' + (5 + this.lineStroke) + 'px;width:0;height:0;position:relative;"></div></div>'; } if (this.getParentPosition(data) === 'FFType2') { div = div + 'left:' + (data.parentLeft + data.parentWidth) + 'px;top:' + (isVirtual ? connectorLine.top : ((data.parentIndex * data.rowHeight) + this.getTaskbarMidpoint(isMilestoneParent) - (this.lineStroke - 1))) + 'px;' + 'width:1px;height:' + heightValue + 'px;position:absolute" data-connectortype="FFType2">'; div = div + eLine; div = div + (isMilestoneParent ? 'left:-1px;' : '') + 'width:' + (isMilestoneParent ? (((data.childLeft + data.childWidth) - (data.parentLeft + data.parentWidth)) + (21 + this.lineStroke)) : (((data.childLeft + data.childWidth) - (data.parentLeft + data.parentWidth)) + (20 + this.lineStroke))) + 'px;' + this.getBorderStyles('top', this.lineStroke) + 'position:relative;"></div>'; div = div + eLine; div = div + 'left:' + (((data.childLeft + data.childWidth) - (data.parentLeft + data.parentWidth)) + 20) + 'px;width:0px;' + this.getBorderStyles('left', this.lineStroke) + this.getBorderStyles('top', (heightValue - this.lineStroke)) + 'position:relative;"></div>'; div = div + eLine; div = div + 'left:' + (isMilestone ? (((data.childLeft + data.childWidth) - (data.parentLeft + data.parentWidth)) + 4) : (((data.childLeft + data.childWidth) - (data.parentLeft + data.parentWidth)) + 10)) + 'px;' + 'width:' + (isMilestone ? (16 + this.lineStroke) : (10 + this.lineStroke)) + 'px;' + this.getBorderStyles('top', this.lineStroke) + 'position:relative;"></div>'; div = div + leftArrow; div = div + 'left:' + ((data.childLeft + data.childWidth) - (data.parentLeft + data.parentWidth)) + 'px;' + this.getBorderStyles('right', 10) + 'top:' + (-6 - this.lineStroke) + 'px;' + 'border-bottom-width:' + (5 + this.lineStroke) + 'px;border-top-width:' + (5 + this.lineStroke) + 'px;width:0;height:0;position:relative;"></div></div>'; } if (this.getParentPosition(data) === 'FFType3') { div = div + 'left:' + (data.childLeft + data.childWidth) + 'px;top:' + (isVirtual ? connectorLine.top : ((data.childIndex * data.rowHeight) + this.getTaskbarMidpoint(isMilestone) - (this.lineStroke - 1))) + 'px;' + 'width:1px;height:' + heightValue + 'px;position:absolute" data-connectortype="FFType3">'; div = div + duplicateStingOne; div = div + eLine; div = div + (isMilestone ? ('left:4px;width:' + (((data.parentLeft + data.parentWidth) - (data.childLeft + data.childWidth)) + 16)) : ('left:10px;width:' + (((data.parentLeft + data.parentWidth) - (data.childLeft + data.childWidth)) + 10))) + 'px;top:' + (-(6 + (5 + this.lineStroke) + (this.lineStroke / 2))) + 'px;' + this.getBorderStyles('top', this.lineStroke) + 'position:relative;"></div>'; div = div + eLine; div = div + 'left:' + (((data.parentLeft + data.parentWidth) - (data.childLeft + data.childWidth)) + 20) + 'px;top:' + (- (13 + ((this.lineStroke - 1) * 2))) + 'px;' + 'width:0px;' + this.getBorderStyles('left', this.lineStroke) + this.getBorderStyles('top', (heightValue - this.lineStroke + 1)) + 'position:relative;"></div>'; div = div + eLine; div = div + (isMilestoneParent ? ('left:' + (((data.parentLeft + data.parentWidth) - (data.childLeft + data.childWidth)) - 1) + 'px;width:21') : ('left:' + ((data.parentLeft + data.parentWidth) - (data.childLeft + data.childWidth)) + 'px;width:20')) + 'px;top:' + (- (13 + ((this.lineStroke - 1) * 2))) + 'px;' + this.getBorderStyles('top', this.lineStroke) + 'position:relative;"></div></div>'; } if (this.getParentPosition(data) === 'FFType4') { div = div + 'left:' + (data.parentLeft + data.parentWidth) + 'px;top:' + (isVirtual ? connectorLine.top : ((data.childIndex * data.rowHeight) + this.getTaskbarMidpoint(isMilestone) - (this.lineStroke - 1))) + 'px;' + 'width:1px;height:' + heightValue + 'px;position:absolute" data-connectortype="FFType4">'; div = div + leftArrow; div = div + ('left:' + ((data.childLeft + data.childWidth) - (data.parentLeft + data.parentWidth))) + 'px;' + this.getBorderStyles('right', 10) + 'top:' + (-5 - this.lineStroke + (this.lineStroke - 1)) + 'px;' + 'border-bottom-width:' + (5 + this.lineStroke) + 'px;border-top-width:' + (5 + this.lineStroke) + 'px;width:0;height:0;' + 'position:relative;"></div>'; div = div + eLine; div = div + (isMilestone ? ('left:' + (((data.childLeft + data.childWidth) - (data.parentLeft + data.parentWidth)) + 4) + 'px;width:' + (16 + this.lineStroke)) : ('left:' + (((data.childLeft + data.childWidth) - (data.parentLeft + data.parentWidth)) + 10) + 'px;width:' + (10 + this.lineStroke))) + 'px;' + duplicateStingFive; div = div + eLine; div = div + 'left:' + (((data.childLeft + data.childWidth) - (data.parentLeft + data.parentWidth)) + 20) + 'px;top:' + (- (13 + ((this.lineStroke - 1) * 2))) + 'px;width:0px;' + this.getBorderStyles('left', this.lineStroke) + this.getBorderStyles('top', (heightValue - this.lineStroke + 1)) + 'position:relative;"></div>'; div = div + eLine; div = div + (isMilestoneParent ? ('left:-1px;width:' + (((data.childLeft + data.childWidth) - (data.parentLeft + data.parentWidth)) + (21 + this.lineStroke))) : ('width:' + (((data.childLeft + data.childWidth) - (data.parentLeft + data.parentWidth)) + (20 + this.lineStroke)))) + 'px;top:' + (- (13 + ((this.lineStroke - 1) * 2))) + 'px;' + this.getBorderStyles('top', this.lineStroke) + 'position:relative;"></div></div>'; } if (this.getParentPosition(data) === 'SFType4') { div = div + 'left:' + (data.parentLeft - 10) + 'px;top:' + (isVirtual ? connectorLine.top : ((data.childIndex * data.rowHeight) + this.getTaskbarMidpoint(isMilestone) - (this.lineStroke - 1))) + 'px;width:1px;' + 'height:' + heightValue + 'px;position:absolute" data-connectortype="SFType4">'; div = div + duplicateStingFour + 'top:' + (-5 - this.lineStroke + (this.lineStroke - 1)) + 'px;' + 'border-bottom-width:' + (5 + this.lineStroke) + 'px;border-top-width:' + (5 + this.lineStroke) + 'px;width:0;height:0;' + 'position:relative;"></div>'; div = div + eLine; div = div + 'left:' + (isMilestone ? ((((data.childLeft + data.childWidth) - (data.parentLeft)) + (14 + this.lineStroke)) + 'px;width:16') : ((((data.childLeft + data.childWidth) - (data.parentLeft)) + 20) + 'px;width:' + (10 + this.lineStroke))) + 'px;' + duplicateStingFive; div = div + eLine; div = div + 'left:' + (((data.childLeft + data.childWidth) - (data.parentLeft)) + 30) + 'px;top:' + (- (13 + ((this.lineStroke - 1) * 2))) + 'px;width:0px;' + this.getBorderStyles('left', this.lineStroke) + this.getBorderStyles( 'top', (heightValue - this.getconnectorLineGap(data) - (this.lineStroke - 1))) + 'position:relative;"></div>'; div = div + eLine; div = div + 'top:' + (- (13 + ((this.lineStroke - 1) * 2))) + 'px;width:' + (((data.childLeft + data.childWidth) - (data.parentLeft)) + (30 + this.lineStroke)) + 'px;' + this.getBorderStyles('top', this.lineStroke) + 'position:relative;"></div>'; div = div + eLine; div = div + 'top:' + (- (13 + ((this.lineStroke - 1) * 2))) + 'px;width:0px;' + this.getBorderStyles('left', this.lineStroke) + this.getBorderStyles('top', (this.getconnectorLineGap(data) - this.lineStroke)) + 'position:relative;"></div>'; div = div + eLine; div = div + 'top:' + (- (13 + ((this.lineStroke - 1) * 2))) + 'px;width:11px;' + this.getBorderStyles('top', this.lineStroke) + 'position:relative;"></div></div>'; } if (this.getParentPosition(data) === 'SFType3') { div = div + 'left:' + (data.childLeft + data.childWidth) + 'px;top:' + (isVirtual ? connectorLine.top : ((data.childIndex * data.rowHeight) + this.getTaskbarMidpoint(isMilestone) - (this.lineStroke - 1))) + 'px;' + 'width:1px;height:' + heightValue + 'px;position:absolute" data-connectortype="SFType3">'; div = div + duplicateStingOne; div = div + eLine; div = div + (isMilestone ? 'left:4px;width:' + (16 + this.lineStroke) : 'left:10px;width:' + (10 + this.lineStroke)) + 'px;top:' + (-(13 + ((this.lineStroke - 1) * 2) - 1)) + 'px;' + this.getBorderStyles('top', this.lineStroke) + 'position:relative;"></div>'; div = div + eLine; div = div + 'left:20px;top:' + (-(13 + ((this.lineStroke - 1) * 2))) + 'px;width:0px;' + this.getBorderStyles('left', this.lineStroke) + this.getBorderStyles('top', (heightValue - (this.lineStroke - 1))) + 'position:relative;"></div>'; div = div + eLine; div = div + 'left:20px;top:' + (-(13 + ((this.lineStroke - 1) * 2))) + 'px;width:' + ((data.parentLeft - (data.childLeft + data.childWidth + 20)) + this.lineStroke) + 'px;' + this.getBorderStyles('top', this.lineStroke) + 'position:relative;"></div></div>'; } if (this.getParentPosition(data) === 'SFType1') { div = div + 'left:' + (data.parentLeft - 10) + 'px;top:' + (isVirtual ? connectorLine.top : ((data.parentIndex * data.rowHeight) + this.getTaskbarMidpoint(isMilestone) - (this.lineStroke - 1))) + 'px;' + 'width:1px;height:' + heightValue + 'px;position:absolute" data-connectortype="SFType1">'; div = div + eLine; div = div + 'width:11px;' + this.getBorderStyles('top', this.lineStroke) + 'position:relative;"></div>'; div = div + eLine; div = div + 'width:0px;' + this.getBorderStyles('left', this.lineStroke) + this.getBorderStyles( 'top', (heightValue - this.getconnectorLineGap(data) - this.lineStroke)) + 'position:relative;"></div>'; div = div + eLine; div = div + 'width:' + (((data.childLeft + data.childWidth) - (data.parentLeft)) + (30 + this.lineStroke)) + 'px;' + this.getBorderStyles('top', this.lineStroke) + 'position:relative;"></div>'; div = div + eLine; div = div + 'left:' + (((data.childLeft + data.childWidth) - (data.parentLeft)) + 30) + 'px;width:0px;' + this.getBorderStyles('left', this.lineStroke) + this.getBorderStyles('top', (this.getconnectorLineGap(data) - this.lineStroke)) + 'position:relative;"></div>'; div = div + eLine; div = div + (isMilestone ? ('left:' + (((data.childLeft + data.childWidth) - (data.parentLeft)) + 15) + 'px;width:' + (15 + this.lineStroke)) : ('left:' + (((data.childLeft + data.childWidth) - (data.parentLeft)) + 20) + 'px;width:' + (10 + this.lineStroke))) + 'px;' + this.getBorderStyles('top', this.lineStroke) + 'position:relative;"></div>'; div = div + duplicateStingFour + 'top:' + (-6 - this.lineStroke) + 'px;' + 'border-bottom-width:' + (5 + this.lineStroke) + 'px;border-top-width:' + (5 + this.lineStroke) + 'px;position:relative;"></div></div>'; } if (this.getParentPosition(data) === 'SFType2') { div = div + 'left:' + (data.childLeft + data.childWidth) + 'px;top:' + (isVirtual ? connectorLine.top : ((data.parentIndex * data.rowHeight) + this.getTaskbarMidpoint(isMilestoneParent) - (this.lineStroke - 1))) + 'px;' + 'width:1px;height:' + heightValue + 'px;position:absolute" data-connectortype="SFType2">'; div = div + eLine; div = div + 'left:' + (((data.parentLeft) - (data.childLeft + data.childWidth)) - 10) + 'px;width:11px;' + this.getBorderStyles('top', this.lineStroke) + 'position:relative;"></div>'; div = div + eLine; div = div + 'left:' + (((data.parentLeft) - (data.childLeft + data.childWidth)) - 10) + 'px;width:0px;' + this.getBorderStyles('left', this.lineStroke) + this.getBorderStyles('top', (heightValue - this.lineStroke)) + 'position:relative;"></div>'; div = div + eLine; div = div + (isMilestone ? ('left:4px;width:' + (((data.parentLeft) - (data.childLeft + data.childWidth)) - (14 - this.lineStroke))) : ('left:10px;width:' + (((data.parentLeft) - (data.childLeft + data.childWidth)) - (20 - this.lineStroke)))) + 'px;' + this.getBorderStyles('top', this.lineStroke) + 'position:relative;"></div>'; div = div + leftArrow; div = div + 'left:0px;' + this.getBorderStyles('right', 10) + 'top:' + (-6 - this.lineStroke) + 'px;border-bottom-width:' + (5 + this.lineStroke) + 'px;border-top-width:' + (5 + this.lineStroke) + 'px;width:0;height:0;position:relative;"></div></div>'; } connectorContainer += div; connectorContainer += '</div>'; } return connectorContainer; } /** * @param {IConnectorLineObject} data . * @param {string} type . * @param {number} heightValue . * @returns {number} . * @private */ private getPosition(data: IConnectorLineObject, type: string, heightValue: number): { top: number, height: number } { let topPosition: number = 0; let lineHeight: number = 0; if (this.parent.virtualScrollModule && this.parent.enableVirtualization) { const isMilestoneParent: boolean = data.milestoneParent ? true : false; const isMilestone: boolean = data.milestoneChild ? true : false; const midPointParent: number = this.getTaskbarMidpoint(isMilestoneParent) - (this.lineStroke - 1); const midPoint: number = this.getTaskbarMidpoint(isMilestone) - (this.lineStroke - 1); const isParentIndex: boolean = data.parentIndexInCurrentView !== -1; const isChildIndex: boolean = data.childIndexInCurrentView !== -1; const lastRowIndex: number = this.parent.currentViewData.length - 1; if (type === 'SSType1' || type === 'SSType2' || type === 'FFType1' || type === 'FFType2' || type === 'SFType2') { topPosition = isParentIndex ? (data.parentIndexInCurrentView * data.rowHeight) + midPointParent : 0; lineHeight = (isParentIndex && isChildIndex) ? heightValue : isChildIndex ? (data.childIndexInCurrentView * data.rowHeight) + midPointParent : (lastRowIndex * data.rowHeight) + midPointParent; } else if (type === 'SSType3' || type === 'SSType4' || type === 'FSType4' || type === 'FFType3' || type === 'FFType4' || type === 'SFType4' || type === 'SFType3') { topPosition = isChildIndex ? (data.childIndexInCurrentView * data.rowHeight) + midPoint : 0; lineHeight = (isParentIndex && isChildIndex) ? heightValue : isParentIndex ? (data.parentIndexInCurrentView * data.rowHeight) + midPoint : (lastRowIndex * data.rowHeight) + midPoint; } else if (type === 'FSType3') { topPosition = isChildIndex ? (data.childIndexInCurrentView * data.rowHeight) + midPointParent : 0; lineHeight = (isParentIndex && isChildIndex) ? heightValue : isParentIndex ? (data.parentIndexInCurrentView * data.rowHeight) + midPoint : (lastRowIndex * data.rowHeight) + midPointParent; } else if (type === 'SFType1' || type === 'FSType1' || type === 'FSType2') { topPosition = isParentIndex ? (data.parentIndexInCurrentView * data.rowHeight) + midPoint : 0; lineHeight = (isParentIndex && isChildIndex) ? heightValue : isChildIndex ? (data.childIndexInCurrentView * data.rowHeight) + midPoint : (lastRowIndex * data.rowHeight) + midPoint; } } return { top: topPosition, height: lineHeight }; } /** * @returns {void} . * @private */ public createConnectorLineTooltipTable(): void { this.tooltipTable = createElement( 'table', { className: '.e-tooltiptable', styles: 'margin-top:0px', attrs: { 'cellspacing': '2px', 'cellpadding': '2px' } }); const tooltipBody: HTMLElement = createElement('tbody'); tooltipBody.innerHTML = ''; this.tooltipTable.appendChild(tooltipBody); } /** * @param {string} fromTaskName . * @param {string} fromPredecessorText . * @param {string} toTaskName . * @param {string} toPredecessorText . * @returns {string} . * @private */ public getConnectorLineTooltipInnerTd( fromTaskName: string, fromPredecessorText: string, toTaskName?: string, toPredecessorText?: string): string { let innerTd: string = '<tr id="fromPredecessor"><td >' + this.parent.localeObj.getConstant('from') + '</td><td> '; innerTd = innerTd + fromTaskName + ' </td><td> ' + this.parent.localeObj.getConstant(fromPredecessorText) + ' </td> </tr>'; innerTd = innerTd + '<tr id="toPredecessor"><td>' + this.parent.localeObj.getConstant('to') + '</td><td> ' + toTaskName; innerTd = innerTd + ' </td><td> ' + this.parent.localeObj.getConstant(toPredecessorText) + ' </td></tr></tbody><table>'; return innerTd; } /** * Generate aria-label for connectorline * * @param {IConnectorLineObject} data . * @returns {string} . * @private */ public generateAriaLabel(data: IConnectorLineObject): string { const type: string = data.type; const updatedRecords: IGanttData[] = this.expandedRecords; const fromName: string = updatedRecords[data.parentIndex].ganttProperties.taskName; const toName: string = updatedRecords[data.childIndex].ganttProperties.taskName; const start: string = this.parent.localeObj.getConstant('start'); const finish: string = this.parent.localeObj.getConstant('finish'); let value: string = ''; if (type === 'FS') { value = fromName + ' ' + finish + ' to ' + toName + ' ' + start; } else if (type === 'FF') { value = fromName + ' ' + finish + ' to ' + toName + ' ' + finish; } else if (type === 'SS') { value = fromName + ' ' + start + ' to ' + toName + ' ' + start; } else { value = fromName + ' ' + start + ' to ' + toName + ' ' + finish; } return value; } /** * To get the record based on the predecessor value * * @param {string} id . * @returns {IGanttData} . * @private */ public getRecordByID(id: string): IGanttData { if (isNullOrUndefined(id)) { return null; } return this.parent.viewType === 'ResourceView' ? this.parent.flatData[this.parent.getTaskIds().indexOf('T' + id.toString())] : this.parent.flatData[this.parent.ids.indexOf(id.toString())]; } /** * Method to remove connector line from DOM * * @param {IGanttData[] | object} records . * @returns {void} . * @private */ public removePreviousConnectorLines(records: IGanttData[] | object): void { let isObjectType: boolean; if (isObject(records) === true) { isObjectType = true; } else { isObjectType = false; } const length: number = isObjectType ? Object.keys(records).length : (records as IGanttData[]).length; const keys: string[] = Object.keys(records); for (let i: number = 0; i < length; i++) { let data: IGanttData; if (isObjectType) { const uniqueId: string = keys[i]; data = records[uniqueId] as IGanttData; } else { data = records[i]; } const predecessors: IPredecessor[] = data.ganttProperties && data.ganttProperties.predecessor; if (predecessors && predecessors.length > 0) { for (let pre: number = 0; pre < predecessors.length; pre++) { const lineId: string = 'parent' + predecessors[pre].from + 'child' + predecessors[pre].to; this.removeConnectorLineById(lineId); } } } } /** * @param {string} id . * @returns {void} . * @private */ public removeConnectorLineById(id: string): void { const element: Element = this.parent.connectorLineModule.dependencyViewContainer.querySelector('#ConnectorLine' + id); if (!isNullOrUndefined(element)) { remove(element); } } }
the_stack
import { unitTest, assert, assertEquals, assertNotEquals, assertThrows, } from "./test_util.ts"; function delay(seconds: number): Promise<void> { return new Promise<void>((resolve) => { setTimeout(() => { resolve(); }, seconds); }); } function readableStreamToArray<R>( readable: { getReader(): ReadableStreamDefaultReader<R> }, reader?: ReadableStreamDefaultReader<R> ): Promise<R[]> { if (reader === undefined) { reader = readable.getReader(); } const chunks: R[] = []; return pump(); function pump(): Promise<R[]> { return reader!.read().then((result) => { if (result.done) { return chunks; } chunks.push(result.value); return pump(); }); } } unitTest(function transformStreamConstructedWithTransformFunction() { new TransformStream({ transform(): void {} }); }); unitTest(function transformStreamConstructedNoTransform() { new TransformStream(); new TransformStream({}); }); unitTest(function transformStreamIntstancesHaveProperProperties() { const ts = new TransformStream({ transform(): void {} }); const proto = Object.getPrototypeOf(ts); const writableStream = Object.getOwnPropertyDescriptor(proto, "writable"); assert(writableStream !== undefined, "it has a writable property"); assert(!writableStream.enumerable, "writable should be non-enumerable"); assertEquals( typeof writableStream.get, "function", "writable should have a getter" ); assertEquals( writableStream.set, undefined, "writable should not have a setter" ); assert(writableStream.configurable, "writable should be configurable"); assert( ts.writable instanceof WritableStream, "writable is an instance of WritableStream" ); assert( WritableStream.prototype.getWriter.call(ts.writable), "writable should pass WritableStream brand check" ); const readableStream = Object.getOwnPropertyDescriptor(proto, "readable"); assert(readableStream !== undefined, "it has a readable property"); assert(!readableStream.enumerable, "readable should be non-enumerable"); assertEquals( typeof readableStream.get, "function", "readable should have a getter" ); assertEquals( readableStream.set, undefined, "readable should not have a setter" ); assert(readableStream.configurable, "readable should be configurable"); assert( ts.readable instanceof ReadableStream, "readable is an instance of ReadableStream" ); assertNotEquals( ReadableStream.prototype.getReader.call(ts.readable), undefined, "readable should pass ReadableStream brand check" ); }); unitTest(function transformStreamWritableStartsAsWritable() { const ts = new TransformStream({ transform(): void {} }); const writer = ts.writable.getWriter(); assertEquals(writer.desiredSize, 1, "writer.desiredSize should be 1"); }); unitTest(async function transformStreamReadableCanReadOutOfWritable() { const ts = new TransformStream(); const writer = ts.writable.getWriter(); writer.write("a"); assertEquals( writer.desiredSize, 0, "writer.desiredSize should be 0 after write()" ); const result = await ts.readable.getReader().read(); assertEquals( result.value, "a", "result from reading the readable is the same as was written to writable" ); assert(!result.done, "stream should not be done"); await delay(0); assert(writer.desiredSize === 1, "desiredSize should be 1 again"); }); unitTest(async function transformStreamCanReadWhatIsWritten() { let c: TransformStreamDefaultController; const ts = new TransformStream({ start(controller: TransformStreamDefaultController): void { c = controller; }, transform(chunk: string): void { c.enqueue(chunk.toUpperCase()); }, }); const writer = ts.writable.getWriter(); writer.write("a"); const result = await ts.readable.getReader().read(); assertEquals( result.value, "A", "result from reading the readable is the transformation of what was written to writable" ); assert(!result.done, "stream should not be done"); }); unitTest(async function transformStreamCanReadBothChunks() { let c: TransformStreamDefaultController; const ts = new TransformStream({ start(controller: TransformStreamDefaultController): void { c = controller; }, transform(chunk: string): void { c.enqueue(chunk.toUpperCase()); c.enqueue(chunk.toUpperCase()); }, }); const writer = ts.writable.getWriter(); writer.write("a"); const reader = ts.readable.getReader(); const result1 = await reader.read(); assertEquals( result1.value, "A", "the first chunk read is the transformation of the single chunk written" ); assert(!result1.done, "stream should not be done"); const result2 = await reader.read(); assertEquals( result2.value, "A", "the second chunk read is also the transformation of the single chunk written" ); assert(!result2.done, "stream should not be done"); }); unitTest(async function transformStreamCanReadWhatIsWritten() { let c: TransformStreamDefaultController; const ts = new TransformStream({ start(controller: TransformStreamDefaultController): void { c = controller; }, transform(chunk: string): Promise<void> { return delay(0).then(() => c.enqueue(chunk.toUpperCase())); }, }); const writer = ts.writable.getWriter(); writer.write("a"); const result = await ts.readable.getReader().read(); assertEquals( result.value, "A", "result from reading the readable is the transformation of what was written to writable" ); assert(!result.done, "stream should not be done"); }); unitTest(async function transformStreamAsyncReadMultipleChunks() { let doSecondEnqueue: () => void; let returnFromTransform: () => void; const ts = new TransformStream({ transform( chunk: string, controller: TransformStreamDefaultController ): Promise<void> { delay(0).then(() => controller.enqueue(chunk.toUpperCase())); doSecondEnqueue = (): void => controller.enqueue(chunk.toUpperCase()); return new Promise((resolve) => { returnFromTransform = resolve; }); }, }); const reader = ts.readable.getReader(); const writer = ts.writable.getWriter(); writer.write("a"); const result1 = await reader.read(); assertEquals( result1.value, "A", "the first chunk read is the transformation of the single chunk written" ); assert(!result1.done, "stream should not be done"); doSecondEnqueue!(); const result2 = await reader.read(); assertEquals( result2.value, "A", "the second chunk read is also the transformation of the single chunk written" ); assert(!result2.done, "stream should not be done"); returnFromTransform!(); }); unitTest(function transformStreamClosingWriteClosesRead() { const ts = new TransformStream({ transform(): void {} }); const writer = ts.writable.getWriter(); writer.close(); return Promise.all([writer.closed, ts.readable.getReader().closed]).then( undefined ); }); unitTest(async function transformStreamCloseWaitAwaitsTransforms() { let transformResolve: () => void; const transformPromise = new Promise<void>((resolve) => { transformResolve = resolve; }); const ts = new TransformStream( { transform(): Promise<void> { return transformPromise; }, }, undefined, { highWaterMark: 1 } ); const writer = ts.writable.getWriter(); writer.write("a"); writer.close(); let rsClosed = false; ts.readable.getReader().closed.then(() => { rsClosed = true; }); await delay(0); assertEquals(rsClosed, false, "readable is not closed after a tick"); transformResolve!(); await writer.closed; // TODO: Is this expectation correct? assertEquals(rsClosed, true, "readable is closed at that point"); }); unitTest(async function transformStreamCloseWriteAfterSyncEnqueues() { let c: TransformStreamDefaultController<string>; const ts = new TransformStream<string, string>({ start(controller: TransformStreamDefaultController): void { c = controller; }, transform(): Promise<void> { c.enqueue("x"); c.enqueue("y"); return delay(0); }, }); const writer = ts.writable.getWriter(); writer.write("a"); writer.close(); const readableChunks = readableStreamToArray(ts.readable); await writer.closed; const chunks = await readableChunks; assertEquals( chunks, ["x", "y"], "both enqueued chunks can be read from the readable" ); }); unitTest(async function transformStreamWritableCloseAsyncAfterAsyncEnqueues() { let c: TransformStreamDefaultController<string>; const ts = new TransformStream<string, string>({ start(controller: TransformStreamDefaultController<string>): void { c = controller; }, transform(): Promise<void> { return delay(0) .then(() => c.enqueue("x")) .then(() => c.enqueue("y")) .then(() => delay(0)); }, }); const writer = ts.writable.getWriter(); writer.write("a"); writer.close(); const readableChunks = readableStreamToArray(ts.readable); await writer.closed; const chunks = await readableChunks; assertEquals( chunks, ["x", "y"], "both enqueued chunks can be read from the readable" ); }); unitTest(async function transformStreamTransformerMethodsCalledAsMethods() { let c: TransformStreamDefaultController<string>; const transformer = { suffix: "-suffix", start(controller: TransformStreamDefaultController<string>): void { c = controller; c.enqueue("start" + this.suffix); }, transform(chunk: string): void { c.enqueue(chunk + this.suffix); }, flush(): void { c.enqueue("flushed" + this.suffix); }, }; const ts = new TransformStream(transformer); const writer = ts.writable.getWriter(); writer.write("a"); writer.close(); const readableChunks = readableStreamToArray(ts.readable); await writer.closed; const chunks = await readableChunks; assertEquals( chunks, ["start-suffix", "a-suffix", "flushed-suffix"], "all enqueued chunks have suffixes" ); }); unitTest(async function transformStreamMethodsShouldNotBeAppliedOrCalled() { function functionWithOverloads(): void {} functionWithOverloads.apply = (): void => { throw new Error("apply() should not be called"); }; functionWithOverloads.call = (): void => { throw new Error("call() should not be called"); }; const ts = new TransformStream({ start: functionWithOverloads, transform: functionWithOverloads, flush: functionWithOverloads, }); const writer = ts.writable.getWriter(); writer.write("a"); writer.close(); await readableStreamToArray(ts.readable); }); unitTest(async function transformStreamCallTransformSync() { let transformCalled = false; const ts = new TransformStream( { transform(): void { transformCalled = true; }, }, undefined, { highWaterMark: Infinity } ); // transform() is only called synchronously when there is no backpressure and // all microtasks have run. await delay(0); const writePromise = ts.writable.getWriter().write(undefined); assert(transformCalled, "transform() should have been called"); await writePromise; }); unitTest(function transformStreamCloseWriteCloesesReadWithNoChunks() { const ts = new TransformStream({}, undefined, { highWaterMark: 0 }); const writer = ts.writable.getWriter(); writer.close(); return Promise.all([writer.closed, ts.readable.getReader().closed]).then( undefined ); }); unitTest(function transformStreamEnqueueThrowsAfterTerminate() { new TransformStream({ start(controller: TransformStreamDefaultController): void { controller.terminate(); assertThrows(() => { controller.enqueue(undefined); }, TypeError); }, }); }); unitTest(function transformStreamEnqueueThrowsAfterReadableCancel() { let controller: TransformStreamDefaultController; const ts = new TransformStream({ start(c: TransformStreamDefaultController): void { controller = c; }, }); const cancelPromise = ts.readable.cancel(); assertThrows( () => controller.enqueue(undefined), TypeError, undefined, "enqueue should throw" ); return cancelPromise; }); unitTest(function transformStreamSecondTerminateNoOp() { new TransformStream({ start(controller: TransformStreamDefaultController): void { controller.terminate(); controller.terminate(); }, }); }); unitTest(async function transformStreamTerminateAfterReadableCancelIsNoop() { let controller: TransformStreamDefaultController; const ts = new TransformStream({ start(c: TransformStreamDefaultController): void { controller = c; }, }); const cancelReason = { name: "cancelReason" }; const cancelPromise = ts.readable.cancel(cancelReason); controller!.terminate(); await cancelPromise; try { await ts.writable.getWriter().closed; } catch (e) { assert(e === cancelReason); return; } throw new Error("closed should have rejected"); }); unitTest(async function transformStreamStartCalledOnce() { let calls = 0; new TransformStream({ start(): void { ++calls; }, }); await delay(0); assertEquals(calls, 1, "start() should have been called exactly once"); }); unitTest(function transformStreamReadableTypeThrows() { assertThrows( // eslint-disable-next-line @typescript-eslint/no-explicit-any () => new TransformStream({ readableType: "bytes" as any }), RangeError, undefined, "constructor should throw" ); }); unitTest(function transformStreamWirtableTypeThrows() { assertThrows( // eslint-disable-next-line @typescript-eslint/no-explicit-any () => new TransformStream({ writableType: "bytes" as any }), RangeError, undefined, "constructor should throw" ); }); unitTest(function transformStreamSubclassable() { class Subclass extends TransformStream { extraFunction(): boolean { return true; } } assert( Object.getPrototypeOf(Subclass.prototype) === TransformStream.prototype, "Subclass.prototype's prototype should be TransformStream.prototype" ); assert( Object.getPrototypeOf(Subclass) === TransformStream, "Subclass's prototype should be TransformStream" ); const sub = new Subclass(); assert( sub instanceof TransformStream, "Subclass object should be an instance of TransformStream" ); assert( sub instanceof Subclass, "Subclass object should be an instance of Subclass" ); const readableGetter = Object.getOwnPropertyDescriptor( TransformStream.prototype, "readable" )!.get; assert( readableGetter!.call(sub) === sub.readable, "Subclass object should pass brand check" ); assert( sub.extraFunction(), "extraFunction() should be present on Subclass object" ); });
the_stack
import { IMemoryTable, Schema, QueryError, TableEvent, PermissionDeniedError, NotSupported, IndexDef, ColumnNotFound, ISubscription, nil, DataType } from './interfaces'; import { _ISelection, IValue, _ITable, setId, getId, CreateIndexDef, CreateIndexColDef, _IDb, _Transaction, _ISchema, _Column, _IType, SchemaField, _IIndex, _Explainer, _SelectExplanation, ChangeHandler, Stats, OnConflictHandler, DropHandler, IndexHandler, asIndex, RegClass, RegType, Reg, ChangeOpts } from './interfaces-private'; import { buildValue } from './expression-builder'; import { BIndex } from './btree-index'; import { columnEvaluator } from './transforms/selection'; import { nullIsh, deepCloneSimple, Optional, indexHash, findTemplate, colByName } from './utils'; import { Map as ImMap } from 'immutable'; import { CreateColumnDef, TableConstraintForeignKey, TableConstraint, Expr, Name, ExprRef } from 'pgsql-ast-parser'; import { ColRef } from './column'; import { buildAlias, Alias } from './transforms/alias'; import { DataSourceBase } from './transforms/transform-base'; import { parseSql } from './parse-cache'; import { ForeignKey } from './constraints/foreign-key'; import { Types } from './datatypes'; type Raw<T> = ImMap<string, T>; interface ChangeSub<T> { before: Set<ChangeHandler<T>>; after: Set<ChangeHandler<T>>; } interface ChangePlan<T> { before(): void after(): void; } class ColumnManager { private _columns?: readonly IValue[]; readonly map = new Map<string, ColRef>(); get columns(): readonly IValue[] { if (!this._columns) { this._columns = Object.freeze(Array.from(this.map.values(), c => c.expression)); } return this._columns!; } invalidateColumns() { this._columns = undefined; } // Pass-through methods get = this.map.get.bind(this.map); has = this.map.has.bind(this.map) values = this.map.values.bind(this.map); set(name: string, colDef: ColRef) { this.invalidateColumns(); return this.map.set(name, colDef); } delete(name: string) { this.invalidateColumns(); return this.map.delete(name); } } export class MemoryTable<T = any> extends DataSourceBase<T> implements IMemoryTable, _ITable<T> { private handlers = new Map<TableEvent, Set<() => void>>(); readonly selection: Alias<T>; private _reg?: Reg; get reg(): Reg { if (!this._reg) { throw new QueryError(`relation "${this.name}" does not exist`); } return this._reg; } get columns() { return this.columnMgr.columns; } private it = 0; private cstGen = 0; hasPrimary = false; private readonly = false; hidden = false; private dataId = Symbol(); private serialsId: symbol = Symbol(); private indexByHash = new Map<string, { index: BIndex<T>; expressions: IValue[]; }>(); readonly columnMgr = new ColumnManager(); name: string; private changeHandlers = new Map<_Column | null, ChangeSub<T>>(); private truncateHandlers = new Set<DropHandler>(); private drophandlers = new Set<DropHandler>(); private indexHandlers = new Set<IndexHandler>(); get type() { return 'table' as const; } get debugId() { return this.name; } entropy(t: _Transaction) { return this.bin(t).size; } isOriginOf(a: IValue<any>): boolean { return a.origin === this.selection; } constructor(schema: _ISchema, t: _Transaction, _schema: Schema) { super(schema); this.name = _schema.name; this.selection = buildAlias(this, this.name) as Alias<T>; // fields for (const s of _schema.fields) { this.addColumn(s, t); } // other table constraints for (const c of _schema.constraints ?? []) { this.addConstraint(c, t); } } register() { // once fields registered, // then register the table // (column registrations need it not to be registered yet) this._reg = this.ownerSchema._reg_register(this); return this; } stats(t: _Transaction): Stats | null { return { count: this.bin(t).size, }; } rename(name: string) { const on = this.name; if (on === name) { return this; } this.name = name; this.ownerSchema._reg_rename(this, on, name); (this.selection as Alias<T>).name = this.name; this.db.onSchemaChange(); return this; } getColumn(column: string | ExprRef): IValue; getColumn(column: string | ExprRef, nullIfNotFound?: boolean): IValue | nil; getColumn(column: string | ExprRef, nullIfNotFound?: boolean): IValue<any> | nil { return colByName(this.columnMgr.map, column, nullIfNotFound) ?.expression; } explain(e: _Explainer): _SelectExplanation { return { _: 'table', table: this.name, }; } addColumn(column: SchemaField | CreateColumnDef, t: _Transaction): _Column { if ('dataType' in column) { const tp: SchemaField = { ...column, name: column.name.name, type: this.ownerSchema.getType(column.dataType), }; delete (tp as any as Optional<CreateColumnDef>).dataType; return this.addColumn(tp, t); } if (this.columnMgr.has(column.name)) { throw new QueryError(`Column "${column.name}" already exists`); } const type = typeof column.type === 'string' ? this.ownerSchema.getType(column.type) : column.type; const cref = new ColRef(this, columnEvaluator(this.selection, column.name, type as _IType), column, column.name); // auto increments if (column.serial) { t.set(this.serialsId, t.getMap(this.serialsId).set(column.name, 0)); } this.columnMgr.set(column.name, cref); try { if (column.constraints?.length) { cref.addConstraints(column.constraints, t); } const hasDefault = column.constraints?.some(x => x.type === 'default'); if (!hasDefault) { this.remapData(t, x => (x as any)[column.name] = (x as any)[column.name] ?? null); } } catch (e) { this.columnMgr.delete(column.name); throw e; } // once constraints created, reference them. (constraint creation might have thrown)m this.db.onSchemaChange(); this.selection.rebuild(); return cref; } getColumnRef(column: string): ColRef; getColumnRef(column: string, nullIfNotFound?: boolean): ColRef | nil; getColumnRef(column: string, nullIfNotFound?: boolean): ColRef | nil { const got = this.columnMgr.get(column); if (!got) { if (nullIfNotFound) { return null; } throw new QueryError(`Column "${column}" not found`); } return got; } bin(t: _Transaction) { return t.getMap<Raw<T>>(this.dataId); } setBin(t: _Transaction, val: Raw<T>) { return t.set(this.dataId, val); } on(event: TableEvent, handler: () => any): ISubscription { let lst = this.handlers.get(event); if (!lst) { this.handlers.set(event, lst = new Set()); } lst.add(handler); return { unsubscribe: () => lst!.delete(handler), }; } raise(event: TableEvent) { const got = this.handlers.get(event); for (const h of got ?? []) { h(); } this.db.raiseTable(this.name, event); } setReadonly() { this.readonly = true; return this; } setHidden() { this.hidden = true; return this; } *enumerate(t: _Transaction): Iterable<T> { this.raise('seq-scan'); for (const v of this.bin(t).values()) { yield deepCloneSimple(v); // copy the original data to prevent it from being mutated. } } find(template?: T, columns?: (keyof T)[]): Iterable<T> { return findTemplate(this.selection, this.db.data, template, columns); } remapData(t: _Transaction, modify: (newCopy: T) => any) { // convert raw data (⚠ must copy the whole thing, // because it can throw in the middle of this process !) // => this would result in partially converted tables. const converted = this.bin(t).map(x => { const copy = { ...x }; modify(copy); return copy; }); this.setBin(t, converted); } insert(toInsert: T): T { const ret = this.doInsert(this.db.data, deepCloneSimple(toInsert)); return deepCloneSimple(ret); } doInsert(t: _Transaction, toInsert: T, opts?: ChangeOpts): T { if (this.readonly) { throw new PermissionDeniedError(this.name); } // get ID of this item const newId = this.name + '_' + (this.it++); setId(toInsert, newId); // serial (auto increments) columns let serials = t.getMap(this.serialsId); for (const [k, v] of serials.entries()) { if (!nullIsh((toInsert as any)[k])) { continue; } (toInsert as any)[k] = v + 1; serials = serials.set(k, v + 1); } t.set(this.serialsId, serials); // set default values for (const c of this.columnMgr.values()) { c.setDefaults(toInsert, t); } // check change handlers (foreign keys) const changePlan = this.changePlan(t, null, toInsert, opts); changePlan.before(); // check "on conflict" const onConflict = opts?.onConflict; if (onConflict) { if ('ignore' in onConflict) { if (onConflict.ignore === 'all') { for (const k of this.indexByHash.values()) { const key = k.index.buildKey(toInsert, t); const found = k.index.eqFirst(key, t); if (found) { return found; // ignore. } } } else { const index = onConflict.ignore as BIndex; const key = index.buildKey(toInsert, t); const found = index.eqFirst(key, t); if (found) { return found; // ignore. } } } else { const index = onConflict.onIndex as BIndex; const key = index.buildKey(toInsert, t); const got = index.eqFirst(key, t); if (got) { // update ! onConflict.update(got, toInsert); return this.update(t, got); } } } // check constraints for (const c of this.columnMgr.values()) { c.checkConstraints(toInsert, t); } // check change handlers (foreign keys) changePlan.after(); // index & check indx contrainsts this.indexElt(t, toInsert); this.setBin(t, this.bin(t).set(newId, toInsert)); return toInsert; } private changePlan(t: _Transaction, old: T | null, neu: T | null, _opts: ChangeOpts | nil): ChangePlan<T> { const opts = _opts ?? {}; let iter: () => IterableIterator<ChangeSub<T>>; if (!old || !neu) { iter = () => this.changeHandlers.values(); } else { const ret: ChangeSub<T>[] = []; const global = this.changeHandlers.get(null); if (global) { ret.push(global); } for (const def of this.columnMgr.values()) { const h = this.changeHandlers.get(def); if (!h) { continue; } const oldVal = (old as any)[def.expression.id!]; const neuVal = (neu as any)[def.expression.id!]; if (def.expression.type.equals(oldVal, neuVal)) { continue; } ret.push(h); } iter = ret[Symbol.iterator].bind(ret); } return { before: () => { const ran = new Set(); for (const { before } of iter()) { for (const b of before) { if (!b || ran.has(b)) { continue; } b(old, neu, t, opts); ran.add(b); } } }, after: () => { const ran = new Set(); for (const { after } of iter()) { for (const a of after) { if (!a || ran.has(a)) { continue; } a(old, neu, t, opts); ran.add(a); } } }, } } update(t: _Transaction, toUpdate: T): T { if (this.readonly) { throw new PermissionDeniedError(this.name); } const bin = this.bin(t); const id = getId(toUpdate); const exists = bin.get(id) ?? null; // set default values for (const c of this.columnMgr.values()) { c.setDefaults(toUpdate, t); } // check change handlers (foreign keys) const changePlan = this.changePlan(t, exists, toUpdate, null); changePlan.before(); changePlan.after(); // check constraints for (const c of this.columnMgr.values()) { c.checkConstraints(toUpdate, t); } // remove old version from index if (exists) { for (const k of this.indexByHash.values()) { k.index.delete(exists, t); } } // add new version to index this.indexElt(t, toUpdate); // store raw this.setBin(t, bin.delete(id).set(id, toUpdate)); return toUpdate; } delete(t: _Transaction, toDelete: T) { const id = getId(toDelete); const bin = this.bin(t); const got = bin.get(id); if (!id || !got) { throw new Error('Unexpected error: an operation has been asked on an item which does not belong to this table'); } // check change handlers (foreign keys) const changePlan = this.changePlan(t, toDelete, null, null); changePlan.before(); changePlan.after(); // remove from indices for (const k of this.indexByHash.values()) { k.index.delete(got, t); } this.setBin(t, bin.delete(id)); return got; } truncate(t: _Transaction): void { // call truncate handlers for (const h of this.truncateHandlers) { h(t); } // truncate indices for (const k of this.indexByHash.values()) { k.index.truncate(t); } this.setBin(t, ImMap()); } private indexElt(t: _Transaction, toInsert: T) { for (const k of this.indexByHash.values()) { k.index.add(toInsert, t); } } hasItem(item: T, t: _Transaction) { const id = getId(item); return this.bin(t).has(id); } getIndex(...forValues: IValue[]): _IIndex | nil { if (!forValues.length || forValues.some(x => !x || !this.isOriginOf(x))) { return null; } const ihash = indexHash(forValues); const got = this.indexByHash.get(ihash); return got?.index ?? null; } constraintNameGen(constraintName?: string) { return constraintName ?? (this.name + '_constraint_' + (++this.cstGen)); } addCheck(_t: _Transaction, check: Expr, constraintName?: string) { constraintName = this.constraintNameGen(constraintName); const getter = buildValue(this.selection, check).cast(Types.bool); const checkVal = (t: _Transaction, v: any) => { const value = getter.get(v, t); if (value === false) { throw new QueryError(`check constraint "${constraintName}" is violated by some row`) } } // check that everything matches (before adding check) for (const v of this.enumerate(_t)) { checkVal(_t, v); } // add a check for future updates this.onBeforeChange([], (old, neu, ct) => { if (!neu) { return; } checkVal(ct, neu); }); } createIndex(t: _Transaction, expressions: CreateIndexDef): this; createIndex(t: _Transaction, expressions: Name[], type: 'primary' | 'unique', indexName?: string): this; createIndex(t: _Transaction, expressions: Name[] | CreateIndexDef, _type?: 'primary' | 'unique', _indexName?: string): this { if (this.readonly) { throw new PermissionDeniedError(this.name); } if (Array.isArray(expressions)) { const keys: CreateIndexColDef[] = []; for (const e of expressions) { const getter = this.selection.getColumn(e.name); keys.push({ value: getter, }); } return this.createIndex(t, { columns: keys, primary: _type === 'primary', notNull: _type === 'primary', unique: !!_type, indexName: _indexName, }); } if (!expressions?.columns?.length) { throw new QueryError('Empty index'); } if (expressions.primary && this.hasPrimary) { throw new QueryError('Table ' + this.name + ' already has a primary key'); } if (expressions.primary) { expressions.notNull = true; expressions.unique = true; } const ihash = indexHash(expressions.columns.map(x => x.value)); const indexName = this.determineIndexRelName(expressions.indexName, ihash, expressions.ifNotExists, 'idx'); if (!indexName) { return this; } const index = new BIndex(t , indexName , expressions.columns , this , ihash , !!expressions.unique , !!expressions.notNull , expressions.predicate); // fill index (might throw if constraint not respected) const bin = this.bin(t); for (const e of bin.values()) { index.add(e, t); } // =========== reference index ============ this.indexHandlers.forEach(h => h('create', index)); // ⚠⚠ This must be done LAST, to avoid throwing an execption if index population failed for (const col of index.expressions) { for (const used of col.usedColumns) { this.getColumnRef(used.id!).usedInIndexes.add(index); } } this.indexByHash.set(ihash, { index, expressions: index.expressions }); if (expressions.primary) { this.hasPrimary = true; } return this; } private determineIndexRelName(indexName: string | nil, ihash: string, ifNotExists: boolean | nil, sufix: string): string | nil { if (indexName) { if (this.ownerSchema.getOwnObject(indexName)) { if (ifNotExists) { return null; } throw new QueryError(`relation "${indexName}" already exists`); } return indexName; } else { const baseName = indexName = `${this.name}_${ihash}_${sufix}`; let i = 1; while (this.ownerSchema.getOwnObject(indexName)) { indexName = baseName + (i++); } return indexName!; } } dropIndex(t: _Transaction, uName: string) { const u = asIndex(this.ownerSchema.getOwnObject(uName)) as BIndex; if (!u || !this.indexByHash.has(u.hash)) { throw new QueryError('Cannot drop index that does not belong to this table: ' + uName); } this.indexHandlers.forEach(h => h('drop', u)); this.indexByHash.delete(u.hash); u.dropFromData(t); this.ownerSchema._reg_unregister(u); } onIndex(sub: IndexHandler): ISubscription { this.indexHandlers.add(sub); return { unsubscribe: () => this.indexHandlers.delete(sub), }; } listIndices(): IndexDef[] { return [...this.indexByHash.values()] .map<IndexDef>(x => ({ name: x.index.name!, expressions: x.expressions.map(x => x.id!), })); } addForeignKey(cst: TableConstraintForeignKey, t: _Transaction) { const ihash = indexHash(cst.localColumns.map(x => x.name)); const constraintName = this.determineIndexRelName(cst.constraintName?.name, ihash, false, 'fk'); if (!constraintName) { return this; } const got = new ForeignKey(constraintName) .install(t, cst, this); // todo; return this; } addConstraint(cst: TableConstraint, t: _Transaction) { // todo add constraint name switch (cst.type) { case 'foreign key': return this.addForeignKey(cst, t); case 'primary key': return this.createIndex(t, cst.columns, 'primary', cst.constraintName?.name); case 'unique': return this.createIndex(t, cst.columns, 'unique', cst.constraintName?.name); case 'check': return this.addCheck(t, cst.expr, cst.constraintName?.name); default: throw NotSupported.never(cst, 'constraint type'); } } onBeforeChange(columns: (string | _Column)[], check: ChangeHandler<T>): ISubscription { return this._subChange('before', columns, check); } onCheckChange(columns: string[], check: ChangeHandler<T>): ISubscription { return this._subChange('before', columns, check); } private _subChange(key: keyof ChangeSub<T>, columns: (string | _Column)[], check: ChangeHandler<T>): ISubscription { const unsubs: (() => void)[] = []; for (const c of columns) { const ref = typeof c === 'string' ? this.getColumnRef(c) : c; let ch = this.changeHandlers.get(ref); if (!ch) { this.changeHandlers.set(ref, ch = { after: new Set(), before: new Set(), }); } ch[key].add(check); unsubs.push(() => ch![key].delete(check)); } return { unsubscribe: () => { for (const u of unsubs) { u(); } } } } drop(t: _Transaction) { this.drophandlers.forEach(d => d(t)); t.delete(this.dataId); for (const i of this.indexByHash.values()) { i.index.dropFromData(t); } // todo should also check foreign keys, cascade, ... return this.ownerSchema._reg_unregister(this); } onDrop(sub: DropHandler): ISubscription { this.drophandlers.add(sub); return { unsubscribe: () => { this.drophandlers.delete(sub); } } } onTruncate(sub: DropHandler): ISubscription { this.truncateHandlers.add(sub); return { unsubscribe: () => { this.truncateHandlers.delete(sub); } } } }
the_stack
import { Section, Chapter, C, R } from 'core/components' import { PageType } from 'core/types' import FadeIn from 'core/components/ui/fadein' import { SyntaxHighlighter, prism, styles, FooterNav } from '..' import { BulletedList } from 'core/components/widgets' export const Page: PageType = () => { return ( <Chapter filename="styling"> <Section> <h1>Layout, styling, and animation</h1> <p> Windrift stories are primarily composed of text, so attention to detail regarding the presentation of text—both visually and for screenreaders—is encouraged. Where possible, defer to general web and accessibility guidelines on good user experience. This section highlights some affordances available as part of Windrift, as well as some best practices that are unique to digital narrative. </p> <h2>Terminology</h2> <ol> <li> Windrift provides components called <strong>layouts</strong>, found in{' '} <code>core/components/ui/layouts</code>. These are designed to be{' '} <strong>reusable across many stories</strong> and control the structure of the HTML page. </li> <li> Each individual story has a <strong>story template</strong>. This is the{' '} <code>index.tsx</code> page created for you when you run the story generator. By default this will use the default <strong>layout</strong>. Every chapter in your story will be rendered inside this page. </li> <li> Finally, within each story, chapter, or section you can control the{' '} <strong>styling</strong> of the text and other media. </li> </ol> <h2> Layout using the <kbd>Grid</kbd> component </h2> <p> Your story template calls a layout component provided in{' '} <code>core/components/ui/layouts</code>. </p> <p> The default layout is <code>core/components/ui/layouts/grid.tsx</code>, which implements the HTML <code>&lt;head&gt;</code>, a top <code>&lt;header&gt;</code> , and a <code>&lt;main&gt;</code> block. </p> <p> The main block is composed of a three-column layout with the following HTML structure: </p> <div style={{ textAlign: 'center' }}> <img src="/stories/manual/images/page-template.svg" alt="Diagram of default page layout" /> </div> <br /> <br /> <p> To understand what's happening here, look at the Grid component in the Windrift source (check the source code itself for the most current version). It accepts the following parameters: </p> <SyntaxHighlighter language="tsx" style={prism}> {`export type GridProps = { /** * Content to be included inside the NextJS {@link Head} * (@see {@link https://nextjs.org/docs/api-reference/next/head}). * Defaults to the HTML title and viewport specification. */ head?: React.ReactNode /** Optional content for the top nav header; defaults to a top-level * nav with the story title and {@link ResetButton}. */ header?: React.ReactNode /** Optional content for the left-hand body column. @default "" */ left?: React.ReactNode /** Optional content for the right-hand body column. @default "" */ right?: React.ReactNode /** A style object as imported from a CSS or SCSS file * * @example * import styles from 'public/stories/manual/styles/Index.module.scss' */ styles?: Record<string, string> }`} </SyntaxHighlighter> <p> All parameters are optional, which means that without making any changes, you'll get a reasonable presentation of story title and content. Most stories will work well with this layout and there is usually not a reason to change this. </p> <h3>Your story template</h3> <p> When you run <code>npm run start &lt;your-story-id&gt;</code>, Windrift generates a file <code>stories/&lt;your-story-id&gt;/index.tsx</code>. By default it looks like this: </p> <SyntaxHighlighter language="tsx" style={prism}> {`import * as React from 'react' import Grid from 'core/components/ui/layouts/grid' import styles from 'public/stories/<your-story-id>/styles/Index.module.scss' const Index: React.FC = ({ children }) => { return ( <Grid styles={styles} head={<link></link>}> {children} // This will always contain the current chapter's content </Grid> ) } export default Index`} </SyntaxHighlighter> <p> As you can see, it passes along your story's styles and an empty placeholder for content in the HTML <code>&lt;head&gt;</code>—these are the two areas you're likely to customize. </p> <div className={styles.twoUp}> <div> <p> The top header provides the story title and a reset button:{' '} <code>core/components/ui/reset-button.tsx</code>. You are strongly encouraged to provide a reset button for all stories, but you can customize the text and design as much as needed. </p> <p> The left and right <code>&lt;nav&gt;</code> elements end up empty and are used as gutters (because no <code>left</code> or <code>right</code>{' '} props are passed), and your story content is in the middle pane. </p> </div> <img src="/stories/manual/images/rendered-template.svg" alt="Diagram of layout populated with page contents" /> <div> <p> If you wanted to put something in the left pane—for example, other kinds of navigation—you'd modify <code>index.tsx</code> to call the Grid like so:{' '} </p> <SyntaxHighlighter language="tsx" style={prism}> {`<Grid styles={styles} left={<div> <ul> <li>About</li> <li>Help</li> </ul> </div>}> {children} </Grid>`} </SyntaxHighlighter> </div> <img src="/stories/manual/images/left.svg" alt="Diagram of layout with left nav" /> </div> <p> Similarly, to put a common element in the center pane of any story, add it before or after <code>{`{children}`}</code>. For example, the table of contents at the top of this manual is implemented as a custom component which is prepended before all the chapter content: <SyntaxHighlighter language="tsx" style={prism}> {`// stories/manual/index.tsx import TableOfContents from './table-of-contents' const Index: React.FC = ({ children }) => ( <Grid ...> <TableOfContents /> {children} </Grid>)`} </SyntaxHighlighter> </p> <aside className={styles.advanced}> <p> You don't need to use <code>Grid</code> at all. A minimal layout{' '} <code>core/components/ui/layouts/minimal.tsx</code> is provided if you want to completely customize the whole page or write your own layout using that as an example. See <code>stories/minimal/index.tsx</code> for an example of using the Minimal layout. If you use <code>Minimal</code> or your own layout you'll need to write all of your CSS from the ground up, as the default CSS is designed to match <code>Grid</code>. </p> </aside> <h2>Fonts</h2> <p> NextJS provides a good foundation for{' '} <a href="https://nextjs.org/docs/basic-features/font-optimization"> font management </a> , and most authors can follow the defaults provided in the Windrift sample stories. You're encouraged to use{' '} <a href="https://fonts.google.com/">Google Fonts</a>, which load quickly and reliably, offer a huge range of character sets, and are optimized for screen (rather than print) usage. </p> <p>You'll need to do the following steps to add a new font to a story:</p> <ol> <li>Import the font in the story template</li> <li>Assign the new font to the desired style</li> </ol> <h3>Step 1: Import the font in your story template</h3> <p> The story template wraps every page in your story, so put the font import in the header. There should already be a placeholder from the story generator: </p> <SyntaxHighlighter language="tsx" style={prism}> {`// stories/manual/index.tsx <Grid styles={styles} head={ <link href="https://fonts.googleapis.com/css2?family=EB+Garamond&display=block" rel="stylesheet" /> }> {children} </Grid>`} </SyntaxHighlighter> <p> Note the use of <code>display=block</code>. This instructs the browser to{' '} <em>block</em> (wait) for the font to be completely loaded before rendering the text content. This is <em>not</em> the usual web recommendation, where it's typically better to put some content in front of users as fast as possible and then switch in the correct font later. Hypertext stories are generally loaded all at once up-front, so using the <code>block</code> loading instruction provides a better user experience than a font that shifts midway into the introduction. (See{' '} <a href="https://font-display.glitch.me/">font-display tutorial</a> by Monica Dinculescu for an excellent summary of CSS font rendering options.) </p> <p> Don't use the shorter <code>@import</code> form of font loading that Google Fonts might suggest—NextJS will perform useful optimizations on the{' '} <code>&lt;link&gt;</code> syntax listed above only. </p> <h3>Step 2: Assign the new font as the default, or to a specific element</h3> <p> The story generator will give you some basic CSS to work with. This will be discussed in more detail in the next section, but to use your new font as the default for all text, add the following: </p> <SyntaxHighlighter language="css" style={prism}>{`/* public/stories/<your-story-id>/Index.module.scss */ @use '/public/styles/fonts' with ( $body: 'EB Garamond', ); /* This next rule will be inserted by the story generator */ .main { /* Customizations can go here */ }`}</SyntaxHighlighter> <p> This combination of <a href="https://sass-lang.com/">Sass/CSS</a> and{' '} <a href="https://css-tricks.com/css-modules-part-1-need/">CSS Modules</a> may be unfamiliar to you, but will be discussed more in the next section. </p> <p> To limit your new font to only specific elements, such as{' '} <code>&lt;h1&gt;</code>, you can use a more familiar syntax: </p> <SyntaxHighlighter language="css" style={prism}>{`/* public/stories/<your-story-id>y/Index.module.scss */ .main { h1 { font-family: 'EB Garamond'; } }`}</SyntaxHighlighter> <h2>Styling</h2> <p> Windrift ships with <a href="https://sass-lang.com/">Sass</a> (SCSS), an extension to CSS that allows a richer expression of styles, reusable rules, and variables. All plain CSS is valid SCSS, so you don't have to use SCSS if you don't want to. However, there are a few Windrift-specific features to get oriented on before customizing your story's styles. </p> <h3>Customizing CSS in the most simple way</h3> <p> You can add a CSS or SCSS file to the head of your story template in the way you would for any HTML document. An example is provided in the head of the manual's{' '} <code>stories/manual/index.tsx</code>: </p> <SyntaxHighlighter language="tsx" style={prism}> {`<Grid styles={styles} head={ <> <link href="https://fonts.googleapis.com/..." rel="stylesheet" /> <link rel="stylesheet" href="/stories/manual/styles/traditional.css" /> <!-- Contents of traditional.css: .traditional { color: white; background: purple; } --> </> }>...</Grid>`} </SyntaxHighlighter> <aside> This text is styled with a normal CSS class:{' '} <span className="traditional">this should be purple</span>. (Note that in React, you must use <code>className</code> rather than "class".) </aside> <p> While this method is simple and effective, the CSS Modules approach described next has many advantages, and will provide a lot of benefit for any significantly complex story or stories. </p> <h3> Using the per-story <kbd>Index.module.scss</kbd> file </h3> <p> The story generator will give you an SCSS file where you can put per-story CSS that will be pre-configured to make use of the included Grid layout and styling. The file will be in{' '} <code>public/stories/&lt;your-story-id&gt;/styles/Index.module.scss</code>: </p> <SyntaxHighlighter language="css" style={prism}>{`/* public/stories/<your-story-id>/Index.module.scss */ @use '/public/styles/grid'; @use '/public/styles/colors'; .main { /* Customizations can go here */ } `}</SyntaxHighlighter> <p> The first two lines import the default Windrift SCSS that matches the{' '} <code>Grid</code> layout. This will give you a mobile-friendly, modern presentation using (surprise!){' '} <a href="https://css-tricks.com/snippets/css/complete-guide-grid/">CSS Grid</a>. A number of useful variables related to fonts, colors, and margins are exported that can be used to override default values without having to rigorously specify new rules. Check out the Stone Harbor CSS for examples that use these variable overrides. </p> <p> The word "module" in the file indicates that this is a CSS Module, which means its use is limited to a specific React component. In this case it will be scoped to your specific story, since it's associated with the <code>index.tsx</code>{' '} story template. </p> <p> CSS Modules should mostly work like any CSS file, with one surprising "gotcha"—to use any class identifier you'll need to import the selector name as a variable in your source code. It's easiest to explain by example. </p> <p> Since this manual is a Windrift story, it has a <code>Index.module.scss</code>{' '} to go with it. That file describes all the styles used in the manual, including the following SCSS: </p> <SyntaxHighlighter language="css" style={prism}>{`/* public/stories/manual/Index.module.scss */ @use '/public/styles/grid'; @use '/public/styles/colors'; .main { /* ... */ .styleExample { color: green; } address { color: blue; } } `}</SyntaxHighlighter> <p> The first rule here uses a class selector: <code>.styleExample</code>. To actually use this rule in the current chapter, it must be imported and referenced as a variable: </p> <SyntaxHighlighter language="tsx" style={ prism }>{`import styles from 'public/stories/manual/styles/Index.module.scss' export const Page: PageType = () => { return ( <Chapter filename="styling"> [...] <span className={styles.styleExample}>should be green</span>. <address>should be blue</address> </Chapter>)} `}</SyntaxHighlighter> <aside> This text will be wrapped in a <code>styleExample</code> class:{' '} <span className={styles.styleExample}>should be green</span>. </aside> <p> Typically, multiword CSS class names are hyphen-separated, but because CSS Modules will refer to them as JavaScript variables, camelCase is recommended here. Also note that in React, you must use <code>className</code> rather than "class". </p> <p> However, if a CSS rule uses an element selector, you can just use it normally without a special import: </p> <aside> This text will be wrapped in an <code>address</code> element:{' '} <address>should be blue</address> </aside> <p> You're not confined to putting all styles in your single{' '} <code>Index.module.scss</code> file; for large stylesheets you can break up the files and import them using SCSS syntax, and if your story includes styles that only apply to specific chapters or components, use and import CSS modules just for those components. </p> <p> Though the technique may be unfamiliar at first, using CSS Modules prevents a style from one story from bleeding over into another and has become a recommended best practice in the React community. You will also get the benefit of hot reloading (changes to styles will immediately update in your story while you develop) and compatibility with any future improvements from Windrift core. </p> <aside className={styles.advanced}> NextJS (and therefore Windrift) support other mechanisms of importing CSS, including the "CSS in JS" approach. See the{' '} <a href="https://nextjs.org/docs/basic-features/built-in-css-support"> NextJS documentation on CSS support </a>{' '} for a full reference. </aside> <h2>Animation</h2> <p> Windrift comes bundled with two methods for animating or transitioning elements:{' '} <a href="https://reactcommunity.org/react-transition-group/"> react-transition-group </a>{' '} and <a href="https://react-spring.io/">react-spring</a>. React Transition Group applies and removes CSS classes when React elements enter or leave the DOM and is good for animations that don't require complex timings or dependency chains. React Spring is a powerful library that uses spring physics to animate value changes and apply them to any value, including position, opacity, or scale. </p> <p> React Transition Group is used in the core library for the default fade-in animation for new Sections. </p> <p> The timings for the section fade-in are controlled in{' '} <code>public/styles/_transitions.scss</code>. You can override these transition classes with different values in your story's CSS, but note that you'll need to use "traditional" CSS (not CSS Modules), as those classes are defined outside the scope of your specific story. </p> <h3> Using <kbd>FadeIn</kbd> </h3> <p> By default, new sections fade in but <code>Response</code>s simply appear. A{' '} <code>FadeIn</code> UI component is provided if you want to change this behavior: </p> <SyntaxHighlighter language="tsx" style={prism}>{`// import FadeIn from 'core/components/ui/fadein' <R tag="animation" options={{ fade: <FadeIn>I will fade in.</FadeIn>, appear: <p>I will just appear.</p> }} />`}</SyntaxHighlighter> <aside> <p> Select how you want the response to be displayed:{' '} <C tag="animation" options={[['fade', 'appear']]} persist={true} widget={BulletedList} /> </p> <p> <R tag="animation" options={{ fade: <FadeIn>I will fade in.</FadeIn>, appear: <p>I will just appear.</p> }} /> </p> </aside> <p> In text-heavy stories, use animation sparingly. It's recommended that you make the durations quick and use short delays. Animations that are novel at first tend to fatigue readers over time. </p> <p> The <code>FadeIn</code> component takes only one option, which is the element that wraps the faded component and defaults to <code>span</code>.{' '} <code>FadeIn</code> is just a convenient pass-through to React Spring, so customize it by creating your own version. </p> <p> Animating in React and tying the animation events to Windrift choice/inventory responses is beyond the scope of this document, but there are several examples of such animations in the{' '} <a href="https://playground.windrift.app">Windrift Playground</a> ( <a href="https://github.com/lizadaly/windrift-playground">source</a>). </p> <FooterNav text="Learn about automated browser testing and continuous integration..." next="testing" /> </Section> </Chapter> ) }
the_stack
import {spawn, ChildProcess} from "child_process" import {Socket} from "net" import {argv} from "yargs" import {join, delimiter, basename, extname, dirname} from "path" import os from "os" import assert from "assert" import chalk from "chalk" import which from "which" import {task, task2, success, passthrough, BuildError} from "../task" import {Linker} from "@compiler/linker" import * as preludes from "@compiler/prelude" import {compile_typescript} from "@compiler/compiler" import * as paths from "../paths" async function is_available(port: number): Promise<boolean> { const host = "0.0.0.0" const timeout = 10000 return new Promise((resolve, reject) => { const socket = new Socket() let available = false let failure = false socket.on("connect", () => { socket.destroy() }) socket.setTimeout(timeout) socket.on("timeout", () => { failure = true socket.destroy() }) socket.on("error", (error: NodeJS.ErrnoException) => { if (error.code === "ECONNREFUSED") available = true }) socket.on("close", () => { if (!failure) resolve(available) else reject(new BuildError("net", "timeout when searching for unused port")) }) socket.connect(port, host) }) } async function find_port(port: number): Promise<number> { while (!await is_available(port)) { port++ } return port } function terminate(proc: ChildProcess): void { process.once("exit", () => proc.kill()) process.once("SIGINT", () => proc.kill("SIGINT")) process.once("SIGTERM", () => proc.kill("SIGTERM")) } function node(files: string[]): Promise<void> { const env = { ...process.env, NODE_PATH: paths.build_dir.lib, } const proc = spawn(process.execPath, files, {stdio: "inherit", env}) terminate(proc) return new Promise((resolve, reject) => { proc.on("error", reject) proc.on("exit", (code, signal) => { if (code === 0) resolve() else { const comment = signal === "SIGINT" || code === 130 ? "interrupted" : "failed" reject(new BuildError("node", `tests ${comment}`)) } }) }) } task("test:codebase:compile", async () => { compile_typescript("./test/codebase/tsconfig.json") }) task("test:codebase", ["test:codebase:compile"], async () => { await node(["./build/test/codebase/index.js"]) }) function sys_path(): string { const path = [process.env.PATH] switch (os.type()) { case "Linux": path.push("/opt/google/chrome/") break case "Darwin": path.push("/Applications/Google\ Chrome.app/Contents/MacOS/") break case "Windows_NT": path.push("c:\\Program Files\\Google\\Chrome\\Application\\") path.push("c:\\Program Files (x86)\\Google\\Chrome\\Application\\") break } return path.join(delimiter) } function chrome(): string { const names = ["chromium", "chromium-browser", "chrome", "google-chrome", "Google Chrome"] const path = sys_path() for (const name of names) { const executable = which.sync(name, {nothrow: true, path}) if (executable != null) return executable } throw new BuildError("headless", `can't find any of ${names.join(", ")} on PATH="${path}"`) } async function headless(port: number): Promise<ChildProcess> { const args = [ "--headless", `--remote-debugging-address=${argv.host ?? "127.0.0.1"}`, `--remote-debugging-port=${port}`, "--font-render-hinting=none", // fixes measureText() on Linux with external fonts "--disable-font-subpixel-positioning", // makes images look similar on all platform "--force-color-profile=srgb", // ^^^ "--force-device-scale-factor=1", // ^^^ ] const executable = chrome() const proc = spawn(executable, args, {stdio: "pipe"}) return new Promise((resolve, reject) => { const timer = setTimeout(() => { reject(new BuildError("headless", `timeout starting ${executable}`)) }, 30000) proc.on("error", reject) let buffer = "" proc.stderr.on("data", (chunk) => { buffer += `${chunk}` const result = buffer.match(/DevTools listening [^\n]*\n/) if (result != null) { proc.stderr.removeAllListeners() clearTimeout(timer) const [line] = result console.log(line.trim()) resolve(proc) } else if (buffer.match(/bind\(\)/)) { proc.stderr.removeAllListeners() clearTimeout(timer) reject(new BuildError("headless", `can't start headless browser on port ${port}`)) } }) }) } async function server(port: number): Promise<ChildProcess> { const args = ["--no-warnings", "./test/devtools", "server", `--port=${port}`] if (argv.debug) { if (argv.debug === true) args.unshift("--inspect-brk") else args.unshift(`--inspect-brk=${argv.debug}`) } const proc = spawn(process.execPath, args, {stdio: ["inherit", "inherit", "inherit", "ipc"]}) terminate(proc) return new Promise((resolve, reject) => { proc.on("error", reject) proc.on("message", (msg) => { if (msg == "ready") resolve(proc) else reject(new BuildError("devtools-server", "failed to start")) }) proc.on("exit", (code, _signal) => { if (code !== 0) { reject(new BuildError("devtools-server", "failed to start")) } }) }) } async function retry(fn: () => Promise<void>, attempts: number): Promise<void> { assert(attempts > 0) while (true) { if (--attempts == 0) { await fn() break } else { try { await fn() break } catch {} } } } function opt(name: string, value: unknown): string { return value != null ? `--${name}=${value}` : "" } function devtools(devtools_port: number, server_port: number, name: string, baselines_root?: string): Promise<void> { const args = [ `http://localhost:${server_port}/${name}`, opt("k", argv.k), opt("grep", argv.grep), opt("ref", argv.ref), opt("baselines-root", baselines_root), `--screenshot=${argv.screenshot ?? "test"}`, ] return _devtools(devtools_port, args) } function devtools_info(devtools_port: number): Promise<void> { return _devtools(devtools_port, ["--info"]) } function _devtools(devtools_port: number, user_args: string[]): Promise<void> { const args = [ "--no-warnings", "./test/devtools", `--port=${devtools_port}`, ...user_args, ] if (argv.debug) { if (argv.debug === true) args.unshift("--inspect-brk") else args.unshift(`--inspect-brk=${argv.debug}`) } const proc = spawn(process.execPath, args, {stdio: "inherit"}) terminate(proc) return new Promise((resolve, reject) => { proc.on("error", reject) proc.on("exit", (code, signal) => { if (code === 0) resolve() else { const comment = signal === "SIGINT" || code === 130 ? "interrupted" : "failed" reject(new BuildError("devtools", `tests ${comment}`)) } }) }) } async function keep_alive(): Promise<void> { await new Promise((resolve) => { process.on("SIGINT", () => resolve(undefined)) }) } task("test:run:headless", async () => { const proc = await headless(9222) await devtools_info(9222) terminate(proc) await keep_alive() }) task("test:spawn:headless", async () => { const proc = await headless(9222) await devtools_info(9222) console.log(`Exec '${chalk.gray("kill")} ${chalk.magenta(`${proc.pid}`)}' to terminate the browser process`) }) const start_headless = task("test:start:headless", async () => { let port = 9222 await retry(async () => { port = await find_port(port) const proc = await headless(port) terminate(proc) }, 3) return success(port) }) const start_server = task("test:start:server", async () => { let port = 5777 await retry(async () => { port = await find_port(port) await server(port) }, 3) return success(port) }) const start = task2("test:start", [start_headless, start_server], async (devtools_port, server_port) => { return success([devtools_port, server_port] as [number, number]) }) function compile(name: string, options?: {auto_index?: boolean}) { // `files` is in TS canonical form, i.e. `/` is the separator on all platforms const base_dir = `test/${name}` compile_typescript(`./${base_dir}/tsconfig.json`, !options?.auto_index ? {} : { inputs(files) { const imports = ['export * from "../framework"'] for (const file of files) { if (file.startsWith(base_dir) && (file.endsWith(".ts") || file.endsWith(".tsx"))) { const ext = extname(file) const name = basename(file, ext) if (!name.startsWith("_") && !name.endsWith(".d")) { const dir = dirname(file).replace(base_dir, "").replace(/^\//, "") const module = dir == "" ? `./${name}` : [".", ...dir.split("/"), name].join("/") imports.push(`import "${module}"`) } } } const index = `${base_dir}/index.ts` const source = imports.join("\n") return new Map([[index, source]]) }, }) } async function bundle(name: string): Promise<void> { const linker = new Linker({ entries: [join(paths.build_dir.test, name, "index.js")], bases: [paths.build_dir.test, "./node_modules"], cache: join(paths.build_dir.test, `${name}.json`), target: "ES2020", minify: false, externals: [/^@bokehjs\//], shims: ["fs", "module"], }) if (!argv.rebuild) linker.load_cache() const {bundles: [bundle], status} = await linker.link() linker.store_cache() const prelude = { main: preludes.default_prelude({global: "Tests"}), plugin: preludes.plugin_prelude(), } const postlude = { main: preludes.postlude(), plugin: preludes.plugin_postlude(), } bundle.assemble({prelude, postlude}).write(join(paths.build_dir.test, `${name}.js`)) if (!status) throw new BuildError(`${name}:bundle`, "unable to bundle modules") } task("test:compile:unit", async () => compile("unit", {auto_index: true})) const build_unit = task("test:build:unit", [passthrough("test:compile:unit")], async () => await bundle("unit")) task2("test:unit", [start, build_unit], async ([devtools_port, server_port]) => { await devtools(devtools_port, server_port, "unit") return success(undefined) }) task("test:compile:integration", async () => compile("integration", {auto_index: true})) const build_integration = task("test:build:integration", [passthrough("test:compile:integration")], async () => await bundle("integration")) task2("test:integration", [start, build_integration], async ([devtools_port, server_port]) => { await devtools(devtools_port, server_port, "integration", "test/baselines") return success(undefined) }) task("test:defaults:compile", ["defaults:generate"], async () => compile("defaults")) const build_defaults = task("test:build:defaults", [passthrough("test:defaults:compile")], async () => await bundle("defaults")) task2("test:defaults", [start, build_defaults], async ([devtools_port, server_port]) => { await devtools(devtools_port, server_port, "defaults") return success(undefined) }) task("test:build", ["test:build:defaults", "test:build:unit", "test:build:integration"]) task("test:lib", ["test:unit", "test:integration"]) task("test", ["test:codebase", "test:defaults", "test:lib"])
the_stack
declare module fng { export interface IFng extends angular.IModule { beforeProcess? : (scope: IFormScope, cb: (err?: Error) => void) => void; } var formsAngular: IFng; /* Type definitions for types that are used on both the client and the server */ type formStyle = 'inline' | 'vertical' | 'horizontal' | 'horizontalCompact' | 'stacked'; export interface IBaseArrayLookupReference { property: string; value: string; } /* IInternalLookupreference makes it possible to look up from a list (of key / value pairs) in the current record. For example var ShelfSchema = new Schema({ location: {type: String, required: true} }); // Note that this schema needs an _id as it is an internal lookup var ESchema = new Schema({ warehouse_name: {type: String, list: {}}, shelves: {type: [ShelfSchema]}, favouriteShelf: {type: Schema.Types.ObjectId, internalRef: {property: 'shelves', value:'location'}; }); */ export interface IFngInternalLookupReference extends IBaseArrayLookupReference { noConvert? : boolean; // can be used by a tricksy hack to get around nesting limitations } /* ILookupListReference makes it possible to look up from a list (of key / value pairs) in a document in another collection for example: const LSchemaDef : IFngSchemaDefinition = { descriptin: {type: String, required: true, list: {}}, warehouse: {type: Schema.Types.ObjectId, ref:'k_referencing_self_collection', form: {directive: 'fng-ui-select', fngUiSelect: {fngAjax: true}}}, shelf: {type: Schema.Types.ObjectId, lookupListRef: {collection:'k_referencing_self_collection', id:'$warehouse', property: 'shelves', value:'location'}}, }; */ export interface IFngLookupListReference extends IBaseArrayLookupReference { collection: string; // collection that contains the list /* Some means of calculating _id in collection. If it starts with $ then it is property in record */ id: string; } /* showWhen allows conditional display of fields based on values elsewhere. For example having prompted whether someone is a smoker you may want a field asking how many they smoke a day: smoker: {type: Boolean}, howManyPerDay: {type: Number, form:{showWhen:{lhs:"$smoker", comp:"eq", rhs:true}}} As you can see from the example there are three parts to the showIf object: lhs (left hand side) a value to be compared. To use the current value of another field in the document preceed it with $. comp supported comparators are 'eq' for equality, 'ne' for not equals, 'gt' (greater than), 'gte' (greater than or equal to), 'lt' (less than) and 'lte' (less than or equal to) rhs (right hand side) the other value to be compared. Details as for lhs. */ export interface IFngShowWhen { lhs: any; comp: 'eq' | 'ne' | 'gt' | 'gte' | 'lt' | 'lte'; rhs: any; } /* link allows the setting up of hyperlinks for lookup reference fields */ export interface IFngLinkSetup { linkOnly?: boolean; // if true then the input element is not generated (this overrides label) label?: boolean; // Make a link out of the label (causes text to be overridden) (this overrides text) form?: string; // can be used to generate a link to a custom schema linktab?: string; // can be used to generate a link to a tab on a form text?: string; // the literal value used for the link. If this property is omitted then text is generated from the field values of the document referred to by the link. } export type FieldSizeString = 'mini' | 'small' | 'medium' | 'large' | 'xlarge' | 'xxlarge' | 'block-level'; // sets control width. Default is 'medium'' export interface IFngSchemaTypeFormOpts { /* The input type to be generated - which must be compatible with the Mongoose type. Common examples are email, url. In addition to the standard HTML5 types there are some 'special' types: textarea: a textarea control radio: a radio button control select: a select control Note that if the field type is String and the name (or label) contains the string 'password' then type="password" will be used unless type="text". If the Mongoose schema has an enum array you can specify a radio button group (instead of a select) by using a type of radio */ type?: string; hidden?: boolean; // inhibits this schema key from appearing on the generated form. label?: string | null; // overrides the default input label. label:null suppresses the label altogether. ref?: string; // reference to another collection internalRef? : IFngInternalLookupReference; lookupListRef?: IFngLookupListReference; id?: string; // specifies the id of the input field (which defaults to f_name) placeHolder?: string // adds placeholder text to the input (depending on data type). help?: string; // adds help text under the input. helpInline?: string; // adds help to the right of the input. popup?: string; // adds title (popup help) as specified. ariaLabel?: string; // adds aria-label as specified. order?: number; // allows user to specify the order / tab order of this field in the form. This overrides the position in the Mongoose schema. size?: FieldSizeString; readonly?: boolean | string; // adds the readonly or ng-readonly attribute to the generated input (currently doesn't work with date - and perhaps other types). rows?: number | 'auto'; // sets the number of rows in inputs (such as textarea) that support this. Setting rows to "auto" makes the textarea expand to fit the content, rather than create a scrollbar. tab?: string; // Used to divide a large form up into a tabset with multiple tabs showWhen?: IFngShowWhen | string; // allows conditional display of fields based on values elsewhere. string must be an abular expression. /* add: 'class="myClass"' allows custom styling of a specific input Angular model options can be used - for example add: 'ng-model-options="{updateOn: \'default blur\', debounce: { \'default\': 500, \'blur\': 0 }}" ' custom validation directives, such as the timezone validation in this schema */ add?: string; // allows arbitrary attributes to be added to the input tag. class?: string; // allows arbitrary classes to be added to the input tag. inlineRadio?: boolean; // (only valid when type is radio) should be set to true to present all radio button options in a single line link?: IFngLinkSetup; // handles displaying links for ref lookups /* With a select / radio type you can specify the options. You can either do this by putting the option values in an array and passing it directly, or by putting them in an array on the scope and passing the name of the array (which allows run-time modification */ options?: Array<string> | string; /* Directive allows you to specify custom behaviour. Gets passed attributes from form-input (with schema replaced with the current element - so add can be used to pass data into directives). */ directive?: string; /* Inhibits the forms-angular client from looking up the possible values for a IFngLookupReference or IFngInternalLookupReference field (when a directive has a an alternative way of handling things) */ noLookup?: boolean; /* The next few options relate to the handling and display of arrays (including arrays of subdocuments) */ noAdd?: boolean | string; // inhibits an Add button being generated for arrays. noneIndicator?: boolean; // show "None" where there's no add button and no array items unshift?: boolean; // (for arrays of sub documents) puts an add button in the sub schema header which allows insertion of new sub documents at the beginning of the array. noRemove?: boolean | string; // inhibits a Remove button being generated for array elements. formstyle?: formStyle; // (only valid on a sub schema) sets style of sub form. sortable? : boolean | string; // Allows drag and drop sorting of arrays - requires angular-ui-sortable ngClass?: string; // Allows for conditional per-item styling through the addition of an ng-class expression to the class list of li elements created for each item in the array /* The next section relates to the display of sub documents */ customSubDoc?: string; // Allows you to specify custom HTML (which may include directives) for the sub doc customHeader?: string; // Allows you to specify custom HTML (which may include directives) for the header of a group of sub docs customFooter?: string; // Allows you to specify custom HTML (which may include directives) for the footer of a group of sub docs /* Suppresses warnings about attenpting deep nesting which would be logged to console in some circumstances when a directive fakes deep nesting */ suppressNestingWarning? : boolean; } // Schema passed from server - derived from Mongoose schema export interface IFieldViewInfo extends IFngSchemaTypeFormOpts { name: string; schema?: Array<IFieldViewInfo>; array?: boolean; showIf? : any; required?: boolean; step? : number; } export type fieldType = 'string' | 'text' | 'textarea' | 'number' | 'select' | 'link' | 'date' | 'checkbox' | 'password' | 'radio'; // Schema used internally on client - often derived from IFieldViewInfo passed from server export interface IFormInstruction extends IFieldViewInfo { id? : string; // id of generated DOM element type?: fieldType; defaultValue? : any; rows? : number; label?: string; options?: any; ids?: any; hidden?: boolean; tab?: string; add? : string; ref? : any; link? : any; linktext?: string; linklabel?: boolean; form?: string; // the form that is linked to select2? : any; // deprecated schema?: IFormInstruction[]; // If the field is an array of fields intType? : 'date'; [ directiveOptions: string] : any; } export interface IContainer { /* Type of container, which determines markup. This is currently only available when the schema is generated by the client for use independent of the BaseController In the case of a string which does not match one of the predefined options the generated container div is given the class of the name */ containerType: 'fieldset' | 'well' | 'tabset' | 'tab' | 'well-large' | 'well-small' | string; title?: string; /* h1...h6 will use a header style anything else will be used as a paragraph stype */ titleTagOrClass? : string; content: IFormInstruction[]; } export type IFormSchemaElement = IFormInstruction | IContainer; export type IFormSchema = IFormSchemaElement[]; export type IControlledFormSchema = IFormInstruction[]; export interface IEnumInstruction { repeat: string; value: string; label? : string; } export interface IFngCtrlState { master: any; allowLocationChange: boolean; // Do we allow location change or prompt for permission } export interface IRecordHandler { convertToMongoModel(schema: IControlledFormSchema, anObject: any, prefixLength: number, scope: IFormScope): any; createNew(dataToSave: any, options: any, scope: IFormScope, ctrlState: IFngCtrlState): void; deleteRecord(id: string, scope: IFormScope, ctrlState: IFngCtrlState): void; updateDocument(dataToSave : any, options: any, scope: IFormScope, ctrlState: IFngCtrlState) : void; readRecord($scope: IFormScope, ctrlState); scrollTheList($scope: IFormScope); getListData(record, fieldName, listSchema?, $scope?: IFormScope); suffixCleanId(inst, suffix); setData(object, fieldname, element, value); setUpLookupOptions(lookupCollection, schemaElement, $scope: IFormScope, ctrlState, handleSchema); setUpLookupListOptions: (ref: IFngLookupListReference, formInstructions: IFormInstruction, $scope: IFormScope, ctrlState: IFngCtrlState) => void; handleInternalLookup($scope: IFormScope, formInstructions, ref): void; preservePristine(element, fn): void; convertIdToListValue(id, idsArray, valuesArray, fname); decorateScope($scope:IFormScope, $uibModal, recordHandlerInstance : IRecordHandler, ctrlState); fillFormFromBackendCustomSchema(schema, $scope:IFormScope, formGeneratorInstance, recordHandlerInstance, ctrlState); fillFormWithBackendSchema($scope: IFormScope, formGeneratorInstance, recordHandlerInstance, ctrlState); handleError($scope: IFormScope); } export interface IFormGenerator { generateEditUrl(obj, $scope:IFormScope): string; generateViewUrl(obj, $scope:IFormScope): string; generateNewUrl($scope: IFormScope): string; handleFieldType(formInstructions, mongooseType, mongooseOptions, $scope: IFormScope, ctrlState); handleSchema(description: string, source, destForm, destList, prefix, doRecursion: boolean, $scope: IFormScope, ctrlState); updateDataDependentDisplay(curValue, oldValue, force, $scope: IFormScope); add(fieldName: string, $event, $scope: IFormScope, modelOverride?: any); unshift(fieldName: string, $event, $scope: IFormScope, modelOverride?: any); remove(fieldName: string, value, $event, $scope: IFormScope, modelOverride?: any); hasError(formName, name, index, $scope: IFormScope); decorateScope($scope: IFormScope, formGeneratorInstance, recordHandlerInstance: IRecordHandler, sharedStuff); } export interface IFngSingleLookupHandler { formInstructions: IFormInstruction; lastPart: string; possibleArray: string; } export interface IFngLookupHandler { lookupOptions: string[]; lookupIds: string[]; handlers: IFngSingleLookupHandler[] } export interface IFngInternalLookupHandlerInfo extends IFngLookupHandler { ref: IFngInternalLookupReference; } export interface IFngLookupListHandlerInfo extends IFngLookupHandler { ref: IFngLookupListReference; } /* The scope which contains form data */ export interface IFormScope extends angular.IScope { sharedData: any; modelNameDisplay : string; modelName: string; formName: string; alertTitle: any; errorVisible: boolean; errorMessage: any; errorHideTimer: number; save: any; newRecord: boolean; initialiseNewRecord?: any; id: any; newClick: any; deleteClick: any; isDeleteDisabled: any; isCancelDisabled: any; isNewDisabled: any; isSaveDisabled: any; whyDisabled: string; unconfirmedDelete: boolean; getVal: any; sortableOptions: any; tabs?: Array<any>; // In the case of forms that contain a tab set tab?: string; // title of the active tab - from the route activeTabNo?: number; topLevelFormName: string; // The name of the form record: any; originalData: any; // the unconverted data read from the server phase: any; disableFunctions: any; dataEventFunctions: any; listSchema: any; recordList: any; dataDependencies: any; internalLookups: IFngInternalLookupHandlerInfo[]; listLookups: IFngLookupListHandlerInfo[]; conversions: any; pageSize: any; pagesLoaded: any; cancel: () => any; showError: (error: any, alertTitle? : string) => void; prepareForSave: (cb: (error: string, dataToSave?: any) => void) => void; setDefaults: (formSchema: IFormSchema, base?: string) => any; formSchema: IControlledFormSchema; baseSchema: () => Array<any>; setFormDirty: any; add: any; hasError: any; unshift: any; remove: any; openSelect2: any; toJSON: any; skipCols: any; setPristine: any; generateEditUrl: any; generateViewUrl: any; generateNewUrl: any; scrollTheList: any; getListData: any; phaseWatcher: any; dismissError: () => void; stickError: () => void; clearTimeout: () => void; handleHttpError: (response: any) => void; dropConversionWatcher: () => void; readingRecord?: Promise<any>; onSchemaFetch?: (description: string, source: IFieldViewInfo[]) => void; onSchemaProcessed?: (description: string, formSchema: IFormInstruction[]) => void; updateQueryForTab?: (tab: string) => void; tabDeselect?: ($event: any, $selectedIndex: number) => void; setUpCustomLookupOptions?: (schemaElement: IFormInstruction, ids: string[], options: string[], baseScope: any) => void; } export interface IContextMenuDivider { divider: boolean; } export interface IContextMenuOption { // For it to make any sense, a menu option needs one of the next three properties url?: string; fn?: () => void; urlFunc?: () => string; text: string; isDisabled?: () => boolean; isHidden?: () => boolean; // Does the option appear in the following contexts? listing: boolean; creating: boolean; editing: boolean; } export interface IModelController extends IFormScope { onBaseCtrlReady? : (baseScope: IFormScope) => void; // Optional callback after form is instantiated onAllReady? : (baseScope: IFormScope) => void; // Optional callback after form is instantiated and populated contextMenu? : Array<IContextMenuOption | IContextMenuDivider>; contextMenuPromise? : Promise<Array<IContextMenuOption | IContextMenuDivider>>; } export interface IBaseFormOptions { /** * The style of the form layout. Supported values are horizontalcompact, horizontal, vertical, inline */ //TODO supported values should be in an enum formstyle?: formStyle; /** * Model on form scope (defaults to record). * <li><strong>model</strong> the object in the scope to be bound to the model controller. Specifying * the model inhibits the generation of the <strong>form</strong> tag unless the <strong>forceform</strong> attribute is set to true</li> */ model? : string; /** * The name to be given to the form - defaults to myForm */ name?: string; /** * Normally first field in a form gets autofocus set. Use this to prevent this */ noautofocus?: string; /* Suppress the generation of element ids (sometimes required when using nested form-inputs in a directive) */ noid? : boolean; } export interface IFormAttrs extends IFormOptions, angular.IAttributes { /** * Schema used by the form */ schema : string; forceform?: string; // Must be true or omitted. Forces generation of the <strong>form</strong> tag when model is specified noid? : boolean; } export interface IFormOptions extends IBaseFormOptions { schema? : string; subkey?: string; subkeyno?: number; subschema? : string; subschemaroot? : string; viewform? : boolean; suppressNestingWarning? : boolean; } export interface IBuiltInRoute { route: string; state: string; templateUrl: string; options? : any; } export interface IRoutingConfig { hashPrefix: string; html5Mode: boolean; routing: string; // What sort of routing do we want? ngroute or uirouter. // TODO Should be enum prefix: string; // How do we want to prefix out routes? If not empty string then first character must be slash (which is added if not) // for example '/db' that gets prepended to all the generated routes. This can be used to // prevent generated routes (which have a lot of parameters) from clashing with other routes in // the web app that have nothing to do with CRUD forms fixedRoutes?: Array<IBuiltInRoute>; templateFolder?: string; // The folder where the templates for base-list, base-edit and base-analysis live. Internal templates used by default. For pre 0.7.0 behaviour use 'partials/' add2fngRoutes?: any; // An object to add to the generated routes. One use case would be to add {authenticate: true} // so that the client authenticates for certain routes variantsForDemoWebsite? : any; // Just for demo website variants?: any; // Just for demo website onDelete?: string; // Supports literal (such as '/') or 'new' (which will go to a /new of the model) default is to go to the list view } export interface IFngRoute { newRecord?: boolean; analyse?: boolean; modelName?: string; reportSchemaName? : string; id? : string; formName? : string; tab? : string; variant? : string; // TODO should be enum of supported frameworks } } declare var formsAngular: fng.IFng;
the_stack
import { Component, OnInit, OnDestroy } from '@angular/core'; import { IonRefresher } from '@ionic/angular'; import { CoreApp } from '@services/app'; import { CoreEventObserver, CoreEvents } from '@singletons/events'; import { CoreLocalNotifications } from '@services/local-notifications'; import { CoreSites } from '@services/sites'; import { CoreDomUtils } from '@services/utils/dom'; import { CoreTimeUtils } from '@services/utils/time'; import { AddonCalendarProvider, AddonCalendar, AddonCalendarEventToDisplay, AddonCalendarCalendarDay, AddonCalendarEventType, } from '../../services/calendar'; import { AddonCalendarOffline } from '../../services/calendar-offline'; import { AddonCalendarFilter, AddonCalendarHelper } from '../../services/calendar-helper'; import { AddonCalendarSync, AddonCalendarSyncProvider } from '../../services/calendar-sync'; import { CoreCategoryData, CoreCourses, CoreEnrolledCourseData } from '@features/courses/services/courses'; import { CoreCoursesHelper } from '@features/courses/services/courses-helper'; import { AddonCalendarFilterPopoverComponent } from '../../components/filter/filter'; import moment from 'moment'; import { Network, NgZone } from '@singletons'; import { CoreNavigator } from '@services/navigator'; import { Params } from '@angular/router'; import { Subscription } from 'rxjs'; import { CoreUtils } from '@services/utils/utils'; import { CoreConstants } from '@/core/constants'; /** * Page that displays the calendar events for a certain day. */ @Component({ selector: 'page-addon-calendar-day', templateUrl: 'day.html', styleUrls: ['../../calendar-common.scss', 'day.scss'], }) export class AddonCalendarDayPage implements OnInit, OnDestroy { protected currentSiteId: string; protected year!: number; protected month!: number; protected day!: number; protected categories: { [id: number]: CoreCategoryData } = {}; protected events: AddonCalendarEventToDisplay[] = []; // Events (both online and offline). protected onlineEvents: AddonCalendarEventToDisplay[] = []; protected offlineEvents: { [monthId: string]: { [day: number]: AddonCalendarEventToDisplay[] } } = {}; // Offline events classified in month & day. protected offlineEditedEventsIds: number[] = []; // IDs of events edited in offline. protected deletedEvents: number[] = []; // Events deleted in offline. protected timeFormat?: string; protected currentTime!: number; // Observers. protected newEventObserver: CoreEventObserver; protected discardedObserver: CoreEventObserver; protected editEventObserver: CoreEventObserver; protected deleteEventObserver: CoreEventObserver; protected undeleteEventObserver: CoreEventObserver; protected syncObserver: CoreEventObserver; protected manualSyncObserver: CoreEventObserver; protected onlineObserver: Subscription; protected obsDefaultTimeChange?: CoreEventObserver; protected filterChangedObserver: CoreEventObserver; periodName?: string; filteredEvents: AddonCalendarEventToDisplay [] = []; canCreate = false; courses: Partial<CoreEnrolledCourseData>[] = []; loaded = false; hasOffline = false; isOnline = false; syncIcon = CoreConstants.ICON_LOADING; isCurrentDay = false; isPastDay = false; currentMoment!: moment.Moment; filter: AddonCalendarFilter = { filtered: false, courseId: undefined, categoryId: undefined, course: true, group: true, site: true, user: true, category: true, }; constructor() { this.currentSiteId = CoreSites.getCurrentSiteId(); if (CoreLocalNotifications.isAvailable()) { // Re-schedule events if default time changes. this.obsDefaultTimeChange = CoreEvents.on(AddonCalendarProvider.DEFAULT_NOTIFICATION_TIME_CHANGED, () => { AddonCalendar.scheduleEventsNotifications(this.onlineEvents); }, this.currentSiteId); } // Listen for events added. When an event is added, reload the data. this.newEventObserver = CoreEvents.on( AddonCalendarProvider.NEW_EVENT_EVENT, (data) => { if (data && data.eventId) { this.loaded = false; this.refreshData(true, true); } }, this.currentSiteId, ); // Listen for new event discarded event. When it does, reload the data. this.discardedObserver = CoreEvents.on(AddonCalendarProvider.NEW_EVENT_DISCARDED_EVENT, () => { this.loaded = false; this.refreshData(true, true); }, this.currentSiteId); // Listen for events edited. When an event is edited, reload the data. this.editEventObserver = CoreEvents.on( AddonCalendarProvider.EDIT_EVENT_EVENT, (data) => { if (data && data.eventId) { this.loaded = false; this.refreshData(true, true); } }, this.currentSiteId, ); // Refresh data if calendar events are synchronized automatically. this.syncObserver = CoreEvents.on(AddonCalendarSyncProvider.AUTO_SYNCED, () => { this.loaded = false; this.refreshData(false, true); }, this.currentSiteId); // Refresh data if calendar events are synchronized manually but not by this page. this.manualSyncObserver = CoreEvents.on(AddonCalendarSyncProvider.MANUAL_SYNCED, (data) => { if (data && (data.source != 'day' || data.year != this.year || data.month != this.month || data.day != this.day)) { this.loaded = false; this.refreshData(false, true); } }, this.currentSiteId); // Update the events when an event is deleted. this.deleteEventObserver = CoreEvents.on( AddonCalendarProvider.DELETED_EVENT_EVENT, (data) => { if (data && !data.sent) { // Event was deleted in offline. Just mark it as deleted, no need to refresh. this.hasOffline = this.markAsDeleted(data.eventId, true) || this.hasOffline; this.deletedEvents.push(data.eventId); } else { this.loaded = false; this.refreshData(false, true); } }, this.currentSiteId, ); // Listen for events "undeleted" (offline). this.undeleteEventObserver = CoreEvents.on( AddonCalendarProvider.UNDELETED_EVENT_EVENT, (data) => { if (!data || !data.eventId) { return; } // Mark it as undeleted, no need to refresh. const found = this.markAsDeleted(data.eventId, false); // Remove it from the list of deleted events if it's there. const index = this.deletedEvents.indexOf(data.eventId); if (index != -1) { this.deletedEvents.splice(index, 1); } if (found) { // The deleted event belongs to current list. Re-calculate "hasOffline". this.hasOffline = false; if (this.events.length != this.onlineEvents.length) { this.hasOffline = true; } else { const event = this.events.find((event) => event.deleted || event.offline); this.hasOffline = !!event; } } }, this.currentSiteId, ); this.filterChangedObserver = CoreEvents.on( AddonCalendarProvider.FILTER_CHANGED_EVENT, async (data) => { this.filter = data; // Course viewed has changed, check if the user can create events for this course calendar. this.canCreate = await AddonCalendarHelper.canEditEvents(this.filter.courseId); this.filterEvents(); }, ); // Refresh online status when changes. this.onlineObserver = Network.onChange().subscribe(() => { // Execute the callback in the Angular zone, so change detection doesn't stop working. NgZone.run(() => { this.isOnline = CoreApp.isOnline(); }); }); } /** * View loaded. */ ngOnInit(): void { const types: string[] = []; CoreUtils.enumKeys(AddonCalendarEventType).forEach((name) => { const value = AddonCalendarEventType[name]; this.filter[name] = CoreNavigator.getRouteBooleanParam(name) ?? true; types.push(value); }); this.filter.courseId = CoreNavigator.getRouteNumberParam('courseId'); this.filter.categoryId = CoreNavigator.getRouteNumberParam('categoryId'); this.filter.filtered = typeof this.filter.courseId != 'undefined' || types.some((name) => !this.filter[name]); const now = new Date(); this.year = CoreNavigator.getRouteNumberParam('year') || now.getFullYear(); this.month = CoreNavigator.getRouteNumberParam('month') || (now.getMonth() + 1); this.day = CoreNavigator.getRouteNumberParam('day') || now.getDate(); this.calculateCurrentMoment(); this.calculateIsCurrentDay(); this.fetchData(true); } /** * Fetch all the data required for the view. * * @param sync Whether it should try to synchronize offline events. * @param showErrors Whether to show sync errors to the user. * @return Promise resolved when done. */ async fetchData(sync?: boolean): Promise<void> { this.syncIcon = CoreConstants.ICON_LOADING; this.isOnline = CoreApp.isOnline(); if (sync) { await this.sync(); } try { const promises: Promise<void>[] = []; // Load courses for the popover. promises.push(CoreCoursesHelper.getCoursesForPopover(this.filter.courseId).then((data) => { this.courses = data.courses; return; })); // Get categories. promises.push(this.loadCategories()); // Get offline events. promises.push(AddonCalendarOffline.getAllEditedEvents().then((offlineEvents) => { // Classify them by month & day. this.offlineEvents = AddonCalendarHelper.classifyIntoMonths(offlineEvents); // Get the IDs of events edited in offline. this.offlineEditedEventsIds = offlineEvents.filter((event) => event.id! > 0).map((event) => event.id!); return; })); // Get events deleted in offline. promises.push(AddonCalendarOffline.getAllDeletedEventsIds().then((ids) => { this.deletedEvents = ids; return; })); // Check if user can create events. promises.push(AddonCalendarHelper.canEditEvents(this.filter.courseId).then((canEdit) => { this.canCreate = canEdit; return; })); // Get user preferences. promises.push(AddonCalendar.getCalendarTimeFormat().then((value) => { this.timeFormat = value; return; })); await Promise.all(promises); await this.fetchEvents(); } catch (error) { CoreDomUtils.showErrorModalDefault(error, 'addon.calendar.errorloadevents', true); } this.loaded = true; this.syncIcon = CoreConstants.ICON_SYNC; } /** * Fetch the events for current day. * * @return Promise resolved when done. */ async fetchEvents(): Promise<void> { let result: AddonCalendarCalendarDay; try { // Don't pass courseId and categoryId, we'll filter them locally. result = await AddonCalendar.getDayEvents(this.year, this.month, this.day); this.onlineEvents = result.events.map((event) => AddonCalendarHelper.formatEventData(event)); } catch (error) { if (CoreApp.isOnline()) { throw error; } // Allow navigating to non-cached days in offline (behave as if using emergency cache). this.onlineEvents = []; } // Calculate the period name. We don't use the one in result because it's in server's language. this.periodName = CoreTimeUtils.userDate( new Date(this.year, this.month - 1, this.day).getTime(), 'core.strftimedaydate', ); // Schedule notifications for the events retrieved (only future events will be scheduled). AddonCalendar.scheduleEventsNotifications(this.onlineEvents); // Merge the online events with offline data. this.events = this.mergeEvents(); // Filter events by course. this.filterEvents(); this.calculateIsCurrentDay(); // Re-calculate the formatted time so it uses the device date. const dayTime = this.currentMoment.unix() * 1000; const promises = this.events.map((event) => { event.ispast = this.isPastDay || (this.isCurrentDay && this.isEventPast(event)); return AddonCalendar.formatEventTime(event, this.timeFormat!, true, dayTime).then((time) => { event.formattedtime = time; return; }); }); await Promise.all(promises); } /** * Merge online events with the offline events of that period. * * @return Merged events. */ protected mergeEvents(): AddonCalendarEventToDisplay[] { this.hasOffline = false; if (!Object.keys(this.offlineEvents).length && !this.deletedEvents.length) { // No offline events, nothing to merge. return this.onlineEvents; } const monthOfflineEvents = this.offlineEvents[AddonCalendarHelper.getMonthId(this.year, this.month)]; const dayOfflineEvents = monthOfflineEvents && monthOfflineEvents[this.day]; let result = this.onlineEvents; if (this.deletedEvents.length) { // Mark as deleted the events that were deleted in offline. result.forEach((event) => { event.deleted = this.deletedEvents.indexOf(event.id) != -1; if (event.deleted) { this.hasOffline = true; } }); } if (this.offlineEditedEventsIds.length) { // Remove the online events that were modified in offline. result = result.filter((event) => this.offlineEditedEventsIds.indexOf(event.id) == -1); if (result.length != this.onlineEvents.length) { this.hasOffline = true; } } if (dayOfflineEvents && dayOfflineEvents.length) { // Add the offline events (either new or edited). this.hasOffline = true; result = AddonCalendarHelper.sortEvents(result.concat(dayOfflineEvents)); } return result; } /** * Filter events based on the filter popover. */ protected filterEvents(): void { this.filteredEvents = AddonCalendarHelper.getFilteredEvents(this.events, this.filter, this.categories); } /** * Refresh the data. * * @param refresher Refresher. * @param done Function to call when done. * @return Promise resolved when done. */ async doRefresh(refresher?: IonRefresher, done?: () => void): Promise<void> { if (!this.loaded) { return; } await this.refreshData(true).finally(() => { refresher?.complete(); done && done(); }); } /** * Refresh the data. * * @param sync Whether it should try to synchronize offline events. * @param afterChange Whether the refresh is done after an event has changed or has been synced. * @return Promise resolved when done. */ async refreshData(sync?: boolean, afterChange?: boolean): Promise<void> { this.syncIcon = CoreConstants.ICON_LOADING; const promises: Promise<void>[] = []; // Don't invalidate day events after a change, it has already been handled. if (!afterChange) { promises.push(AddonCalendar.invalidateDayEvents(this.year, this.month, this.day)); } promises.push(AddonCalendar.invalidateAllowedEventTypes()); promises.push(CoreCourses.invalidateCategories(0, true)); promises.push(AddonCalendar.invalidateTimeFormat()); await Promise.all(promises).finally(() => this.fetchData(sync)); } /** * Load categories to be able to filter events. * * @return Promise resolved when done. */ protected async loadCategories(): Promise<void> { try { const cats = await CoreCourses.getCategories(0, true); this.categories = {}; // Index categories by ID. cats.forEach((category) => { this.categories[category.id] = category; }); } catch { // Ignore errors. } } /** * Try to synchronize offline events. * * @param showErrors Whether to show sync errors to the user. * @return Promise resolved when done. */ protected async sync(showErrors?: boolean): Promise<void> { try { const result = await AddonCalendarSync.syncEvents(); if (result.warnings && result.warnings.length) { CoreDomUtils.showErrorModal(result.warnings[0]); } if (result.updated) { // Trigger a manual sync event. result.source = 'day'; result.day = this.day; result.month = this.month; result.year = this.year; CoreEvents.trigger(AddonCalendarSyncProvider.MANUAL_SYNCED, result, this.currentSiteId); } } catch (error) { if (showErrors) { CoreDomUtils.showErrorModalDefault(error, 'core.errorsync', true); } } } /** * Navigate to a particular event. * * @param eventId Event to load. */ gotoEvent(eventId: number): void { if (eventId < 0) { // It's an offline event, go to the edit page. this.openEdit(eventId); } else { CoreNavigator.navigateToSitePath(`/calendar/event/${eventId}`); } } /** * Show the context menu. * * @param event Event. */ async openFilter(event: MouseEvent): Promise<void> { await CoreDomUtils.openPopover({ component: AddonCalendarFilterPopoverComponent, componentProps: { courses: this.courses, filter: this.filter, }, event, }); } /** * Open page to create/edit an event. * * @param eventId Event ID to edit. */ openEdit(eventId?: number): void { const params: Params = {}; if (!eventId) { // It's a new event, set the time. eventId = 0; params.timestamp = moment().year(this.year).month(this.month - 1).date(this.day).unix() * 1000; } if (this.filter.courseId) { params.courseId = this.filter.courseId; } CoreNavigator.navigateToSitePath(`/calendar/edit/${eventId}`, { params }); } /** * Calculate current moment. */ calculateCurrentMoment(): void { this.currentMoment = moment().year(this.year).month(this.month - 1).date(this.day); } /** * Check if user is viewing the current day. */ calculateIsCurrentDay(): void { const now = new Date(); this.currentTime = CoreTimeUtils.timestamp(); this.isCurrentDay = this.year == now.getFullYear() && this.month == now.getMonth() + 1 && this.day == now.getDate(); this.isPastDay = this.year < now.getFullYear() || (this.year == now.getFullYear() && this.month < now.getMonth()) || (this.year == now.getFullYear() && this.month == now.getMonth() + 1 && this.day < now.getDate()); } /** * Go to current day. */ async goToCurrentDay(): Promise<void> { const now = new Date(); const initialDay = this.day; const initialMonth = this.month; const initialYear = this.year; this.day = now.getDate(); this.month = now.getMonth() + 1; this.year = now.getFullYear(); this.calculateCurrentMoment(); this.loaded = false; try { await this.fetchEvents(); this.isCurrentDay = true; } catch (error) { CoreDomUtils.showErrorModalDefault(error, 'addon.calendar.errorloadevents', true); this.year = initialYear; this.month = initialMonth; this.day = initialDay; this.calculateCurrentMoment(); } this.loaded = true; } /** * Load next day. */ async loadNext(): Promise<void> { this.increaseDay(); this.loaded = false; try { await this.fetchEvents(); } catch (error) { CoreDomUtils.showErrorModalDefault(error, 'addon.calendar.errorloadevents', true); this.decreaseDay(); } this.loaded = true; } /** * Load previous day. */ async loadPrevious(): Promise<void> { this.decreaseDay(); this.loaded = false; try { await this.fetchEvents(); } catch (error) { CoreDomUtils.showErrorModalDefault(error, 'addon.calendar.errorloadevents', true); this.increaseDay(); } this.loaded = true; } /** * Decrease the current day. */ protected decreaseDay(): void { this.currentMoment.subtract(1, 'day'); this.year = this.currentMoment.year(); this.month = this.currentMoment.month() + 1; this.day = this.currentMoment.date(); } /** * Increase the current day. */ protected increaseDay(): void { this.currentMoment.add(1, 'day'); this.year = this.currentMoment.year(); this.month = this.currentMoment.month() + 1; this.day = this.currentMoment.date(); } /** * Find an event and mark it as deleted. * * @param eventId Event ID. * @param deleted Whether to mark it as deleted or not. * @return Whether the event was found. */ protected markAsDeleted(eventId: number, deleted: boolean): boolean { const event = this.onlineEvents.find((event) => event.id == eventId); if (event) { event.deleted = deleted; return true; } return false; } /** * Returns if the event is in the past or not. * * @param event Event object. * @return True if it's in the past. */ isEventPast(event: AddonCalendarEventToDisplay): boolean { return (event.timestart + event.timeduration) < this.currentTime; } /** * Page destroyed. */ ngOnDestroy(): void { this.newEventObserver?.off(); this.discardedObserver?.off(); this.editEventObserver?.off(); this.deleteEventObserver?.off(); this.undeleteEventObserver?.off(); this.syncObserver?.off(); this.manualSyncObserver?.off(); this.onlineObserver?.unsubscribe(); this.filterChangedObserver?.off(); this.obsDefaultTimeChange?.off(); } }
the_stack
import genFn from "generate-function"; import { ArgumentNode, ASTNode, DirectiveNode, FieldNode, FragmentDefinitionNode, getLocation, GraphQLArgument, GraphQLDirective, GraphQLError, GraphQLField, GraphQLIncludeDirective, GraphQLInputType, GraphQLObjectType, GraphQLSkipDirective, InlineFragmentNode, isEnumType, isInputObjectType, isListType, isNonNullType, isScalarType, print, SelectionSetNode, SourceLocation, typeFromAST, valueFromASTUntyped, ValueNode, VariableNode, versionInfo } from "graphql"; import { getFieldDef } from "graphql/execution/execute"; import { Kind, SelectionNode, TypeNode } from "graphql/language"; import { isAbstractType } from "graphql/type"; import { CompilationContext, GLOBAL_VARIABLES_NAME } from "./execution"; import createInspect from "./inspect"; import { Maybe } from "./types"; export interface JitFieldNode extends FieldNode { __internalShouldInclude?: string; } export interface FieldsAndNodes { [key: string]: JitFieldNode[]; } const inspect = createInspect(); /** * Given a selectionSet, adds all of the fields in that selection to * the passed in map of fields, and returns it at the end. * * CollectFields requires the "runtime type" of an object. For a field which * returns an Interface or Union type, the "runtime type" will be the actual * Object type returned by that field. */ export function collectFields( compilationContext: CompilationContext, runtimeType: GraphQLObjectType, selectionSet: SelectionSetNode, fields: FieldsAndNodes, visitedFragmentNames: { [key: string]: boolean } ): FieldsAndNodes { return collectFieldsImpl( compilationContext, runtimeType, selectionSet, fields, visitedFragmentNames ); } /** * Implementation of collectFields defined above with extra parameters * used for recursion and need not be exposed publically */ function collectFieldsImpl( compilationContext: CompilationContext, runtimeType: GraphQLObjectType, selectionSet: SelectionSetNode, fields: FieldsAndNodes, visitedFragmentNames: { [key: string]: boolean }, previousShouldInclude = "" ): FieldsAndNodes { for (const selection of selectionSet.selections) { switch (selection.kind) { case Kind.FIELD: { const name = getFieldEntryKey(selection); if (!fields[name]) { fields[name] = []; } const fieldNode: JitFieldNode = selection; /** * Carry over fragment's skip and include code * * fieldNode.__internalShouldInclude * --------------------------------- * When the parent field has a skip or include, the current one * should be skipped if the parent is skipped in the path. * * previousShouldInclude * --------------------- * `should include`s from fragment spread and inline fragments * * compileSkipInclude(selection) * ----------------------------- * `should include`s generated for the current fieldNode */ fieldNode.__internalShouldInclude = joinShouldIncludeCompilations( fieldNode.__internalShouldInclude ?? "", previousShouldInclude, compileSkipInclude(compilationContext, selection) ); /** * We augment the entire subtree as the parent object's skip/include * directives influence the child even if the child doesn't have * skip/include on it's own. * * Refer the function definition for example. */ augmentFieldNodeTree(compilationContext, fieldNode); fields[name].push(fieldNode); break; } case Kind.INLINE_FRAGMENT: if ( !doesFragmentConditionMatch( compilationContext, selection, runtimeType ) ) { continue; } collectFieldsImpl( compilationContext, runtimeType, selection.selectionSet, fields, visitedFragmentNames, joinShouldIncludeCompilations( // `should include`s from previous fragments previousShouldInclude, // current fragment's shouldInclude compileSkipInclude(compilationContext, selection) ) ); break; case Kind.FRAGMENT_SPREAD: { const fragName = selection.name.value; if (visitedFragmentNames[fragName]) { continue; } visitedFragmentNames[fragName] = true; const fragment = compilationContext.fragments[fragName]; if ( !fragment || !doesFragmentConditionMatch(compilationContext, fragment, runtimeType) ) { continue; } collectFieldsImpl( compilationContext, runtimeType, fragment.selectionSet, fields, visitedFragmentNames, joinShouldIncludeCompilations( // `should include`s from previous fragments previousShouldInclude, // current fragment's shouldInclude compileSkipInclude(compilationContext, selection) ) ); break; } } } return fields; } /** * Augment __internalShouldInclude code for all sub-fields in the * tree with @param rootfieldNode as the root. * * This is required to handle cases where there are multiple paths to * the same node. And each of those paths contain different skip/include * values. * * For example, * * ``` * { * foo @skip(if: $c1) { * bar @skip(if: $c2) * } * ... { * foo @skip(if: $c3) { * bar * } * } * } * ``` * * We decide shouldInclude at runtime per fieldNode. When we handle the * field `foo`, the logic is straight forward - it requires one of $c1 or $c3 * to be false. * * But, when we handle the field `bar`, and we are in the context of the fieldNode, * not enough information is available. This is because, if we only included $c2 * to decide if bar is included, consider the case - * * $c1: true, $c2: true, $c3: false * * If we considered only $c2, we would have skipped bar. But the correct implementation * is to include bar, because foo($c3) { bar } is not skipped. The entire sub-tree's * logic is required to handle bar. * * So, to handle this case, we augment the tree at each point to consider the * skip/include logic from the parent as well. * * @param compilationContext {CompilationContext} Required for getFragment by * name to handle fragment spread operation. * * @param rootFieldNode {JitFieldNode} The root field to traverse from for * adding __internalShouldInclude to all sub field nodes. */ function augmentFieldNodeTree( compilationContext: CompilationContext, rootFieldNode: JitFieldNode ) { for (const selection of rootFieldNode.selectionSet?.selections ?? []) { handle(rootFieldNode, selection); } /** * Recursively traverse through sub-selection and combine `shouldInclude`s * from parent and current ones. */ function handle( parentFieldNode: JitFieldNode, selection: SelectionNode, comesFromFragmentSpread = false ) { switch (selection.kind) { case Kind.FIELD: { const jitFieldNode: JitFieldNode = selection; if (!comesFromFragmentSpread) { jitFieldNode.__internalShouldInclude = joinShouldIncludeCompilations( parentFieldNode.__internalShouldInclude ?? "", jitFieldNode.__internalShouldInclude ?? "" ); } // go further down the query tree for (const selection of jitFieldNode.selectionSet?.selections ?? []) { handle(jitFieldNode, selection); } break; } case Kind.INLINE_FRAGMENT: { for (const subSelection of selection.selectionSet.selections) { handle(parentFieldNode, subSelection, true); } break; } case Kind.FRAGMENT_SPREAD: { const fragment = compilationContext.fragments[selection.name.value]; for (const subSelection of fragment.selectionSet.selections) { handle(parentFieldNode, subSelection, true); } } } } } /** * Joins a list of shouldInclude compiled code into a single logical * statement. * * The operation is `&&` because, it is used to join parent->child * relations in the query tree. Note: parent can be either parent field * or fragment. * * For example, * { * foo @skip(if: $c1) { * ... @skip(if: $c2) { * bar @skip(if: $c3) * } * } * } * * Only when a parent is included, the child is included. So, we use `&&`. * * compilationFor($c1) && compilationFor($c2) && compilationFor($c3) * * @param compilations */ function joinShouldIncludeCompilations(...compilations: string[]) { // remove "true" since we are joining with '&&' as `true && X` = `X` // This prevents an explosion of `&& true` which could break // V8's internal size limit for string. // // Note: the `true` appears if a field does not have a skip/include directive // So, the more nested the query is, the more of unnecessary `&& true` // we get. // // Failing to do this results in [RangeError: invalid array length] // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Invalid_array_length // remove empty strings let filteredCompilations = compilations.filter((it) => it); // Split conditions by && and flatten it filteredCompilations = ([] as string[]).concat( ...filteredCompilations.map((e) => e.split(" && ").map((it) => it.trim())) ); // Deduplicate items filteredCompilations = Array.from(new Set(filteredCompilations)); return filteredCompilations.join(" && "); } /** * Compiles directives `skip` and `include` and generates the compilation * code based on GraphQL specification. * * @param node {SelectionNode} The selection node (field/fragment/inline-fragment) * for which we generate the compiled skipInclude. */ function compileSkipInclude( compilationContext: CompilationContext, node: SelectionNode ): string { const gen = genFn(); const { skipValue, includeValue } = compileSkipIncludeDirectiveValues( compilationContext, node ); /** * Spec: https://spec.graphql.org/June2018/#sec--include * * Neither @skip nor @include has precedence over the other. * In the case that both the @skip and @include directives * are provided in on the same the field or fragment, it must * be queried only if the @skip condition is false and the * @include condition is true. Stated conversely, the field * or fragment must not be queried if either the @skip * condition is true or the @include condition is false. */ if (skipValue != null && includeValue != null) { gen(`${skipValue} === false && ${includeValue} === true`); } else if (skipValue != null) { gen(`(${skipValue} === false)`); } else if (includeValue != null) { gen(`(${includeValue} === true)`); } else { gen(`true`); } return gen.toString(); } /** * Compile skip or include directive values into JIT compatible * runtime code. * * @param node {SelectionNode} */ function compileSkipIncludeDirectiveValues( compilationContext: CompilationContext, node: SelectionNode ) { const skipDirective = node.directives?.find( (it) => it.name.value === GraphQLSkipDirective.name ); const includeDirective = node.directives?.find( (it) => it.name.value === GraphQLIncludeDirective.name ); const skipValue = skipDirective ? compileSkipIncludeDirective(compilationContext, skipDirective) : // The null here indicates the absense of the directive // which is later used to determine if both skip and include // are present null; const includeValue = includeDirective ? compileSkipIncludeDirective(compilationContext, includeDirective) : // The null here indicates the absense of the directive // which is later used to determine if both skip and include // are present null; return { skipValue, includeValue }; } /** * Compile the skip/include directive node. Resolve variables to it's * path from context, resolve scalars to their respective values. * * @param directive {DirectiveNode} */ function compileSkipIncludeDirective( compilationContext: CompilationContext, directive: DirectiveNode ) { const ifNode = directive.arguments?.find((it) => it.name.value === "if"); if (ifNode == null) { throw new GraphQLError( `Directive '${directive.name.value}' is missing required arguments: 'if'`, [directive] ); } switch (ifNode.value.kind) { case Kind.VARIABLE: validateSkipIncludeVariableType(compilationContext, ifNode.value); return `${GLOBAL_VARIABLES_NAME}["${ifNode.value.name.value}"]`; case Kind.BOOLEAN: return `${ifNode.value.value.toString()}`; default: throw new GraphQLError( `Argument 'if' on Directive '${ directive.name.value }' has an invalid value (${valueFromASTUntyped( ifNode.value )}). Expected type 'Boolean!'`, [ifNode] ); } } /** * Validate the skip and include directive's argument values at compile time. * * This validation step is required as these directives are part of an * implicit schema in GraphQL. * * @param compilationContext {CompilationContext} * @param variable {VariableNode} the variable used in 'if' argument of the skip/include directive */ function validateSkipIncludeVariableType( compilationContext: CompilationContext, variable: VariableNode ) { const variableDefinition = compilationContext.operation.variableDefinitions?.find( (it) => it.variable.name.value === variable.name.value ); if (variableDefinition == null) { throw new GraphQLError(`Variable '${variable.name.value}' is not defined`, [ variable ]); } if ( !( variableDefinition.type.kind === Kind.NON_NULL_TYPE && variableDefinition.type.type.kind === Kind.NAMED_TYPE && variableDefinition.type.type.name.value === "Boolean" ) ) { throw new GraphQLError( `Variable '${variable.name.value}' of type '${typeNodeToString( variableDefinition.type )}' used in position expecting type 'Boolean!'`, [variableDefinition] ); } } /** * Print the string representation of the TypeNode for error messages * * @param type {TypeNode} type node to be converted to string representation */ function typeNodeToString(type: TypeNode): string { switch (type.kind) { case Kind.NAMED_TYPE: return type.name.value; case Kind.NON_NULL_TYPE: return `${typeNodeToString(type.type)}!`; case Kind.LIST_TYPE: return `[${typeNodeToString(type.type)}]`; } } /** * Determines if a fragment is applicable to the given type. */ function doesFragmentConditionMatch( compilationContext: CompilationContext, fragment: FragmentDefinitionNode | InlineFragmentNode, type: GraphQLObjectType ): boolean { const typeConditionNode = fragment.typeCondition; if (!typeConditionNode) { return true; } const conditionalType = typeFromAST( compilationContext.schema, typeConditionNode ); if (conditionalType === type) { return true; } if (!conditionalType) { return false; } if (isAbstractType(conditionalType)) { return compilationContext.schema.isSubType(conditionalType, type); } return false; } /** * Implements the logic to compute the key of a given field's entry */ function getFieldEntryKey(node: FieldNode): string { return node.alias ? node.alias.value : node.name.value; } /** * Resolves the field on the given source object. In particular, this * figures out the value that the field returns by calling its resolve function, * then calls completeValue to complete promises, serialize scalars, or execute * the sub-selection-set for objects. */ export function resolveFieldDef( compilationContext: CompilationContext, parentType: GraphQLObjectType, fieldNodes: FieldNode[] ): Maybe<GraphQLField<any, any>> { const fieldNode = fieldNodes[0]; if (versionInfo.major < 16) { const fieldName = fieldNode.name.value; return getFieldDef(compilationContext.schema, parentType, fieldName as any); } return getFieldDef(compilationContext.schema, parentType, fieldNode as any); } /** * A memoized collection of relevant subfields in the context of the return * type. Memoizing ensures the subfields are not repeatedly calculated, which * saves overhead when resolving lists of values. */ export const collectSubfields = memoize3(_collectSubfields); function _collectSubfields( compilationContext: CompilationContext, returnType: GraphQLObjectType, fieldNodes: FieldNode[] ): { [key: string]: FieldNode[] } { let subFieldNodes = Object.create(null); const visitedFragmentNames = Object.create(null); for (const fieldNode of fieldNodes) { const selectionSet = fieldNode.selectionSet; if (selectionSet) { subFieldNodes = collectFields( compilationContext, returnType, selectionSet, subFieldNodes, visitedFragmentNames ); } } return subFieldNodes; } function memoize3( fn: ( compilationContext: CompilationContext, returnType: GraphQLObjectType, fieldNodes: FieldNode[] ) => { [key: string]: FieldNode[] } ): ( compilationContext: CompilationContext, returnType: GraphQLObjectType, fieldNodes: FieldNode[] ) => { [key: string]: FieldNode[] } { let cache0: WeakMap<any, any>; function memoized(a1: any, a2: any, a3: any) { if (!cache0) { cache0 = new WeakMap(); } let cache1 = cache0.get(a1); let cache2; if (cache1) { cache2 = cache1.get(a2); if (cache2) { const cachedValue = cache2.get(a3); if (cachedValue !== undefined) { return cachedValue; } } } else { cache1 = new WeakMap(); cache0.set(a1, cache1); } if (!cache2) { cache2 = new WeakMap(); cache1.set(a2, cache2); } // eslint-disable-next-line prefer-rest-params const newValue = (fn as any)(...arguments); cache2.set(a3, newValue); return newValue; } return memoized; } // response path is used for identifying // the info resolver function as well as the path in errros, // the meta type is used for elements that are only to be used for // the function name type ResponsePathType = "variable" | "literal" | "meta"; export interface ObjectPath { prev: ObjectPath | undefined; key: string; type: ResponsePathType; } interface MissingVariablePath { valueNode: VariableNode; path?: ObjectPath; argument?: { definition: GraphQLArgument; node: ArgumentNode }; } export interface Arguments { values: { [argument: string]: any }; missing: MissingVariablePath[]; } /** * Prepares an object map of argument values given a list of argument * definitions and list of argument AST nodes. * * Note: The returned value is a plain Object with a prototype, since it is * exposed to user code. Care should be taken to not pull values from the * Object prototype. */ export function getArgumentDefs( def: GraphQLField<any, any> | GraphQLDirective, node: FieldNode | DirectiveNode ): Arguments { const values: { [key: string]: any } = {}; const missing: MissingVariablePath[] = []; const argDefs = def.args; const argNodes = node.arguments || []; const argNodeMap = keyMap(argNodes, (arg) => arg.name.value); for (const argDef of argDefs) { const name = argDef.name; if (argDef.defaultValue !== undefined) { // Set the coerced value to the default values[name] = argDef.defaultValue; } const argType = argDef.type; const argumentNode = argNodeMap[name]; let hasVariables = false; if (argumentNode && argumentNode.value.kind === Kind.VARIABLE) { hasVariables = true; missing.push({ valueNode: argumentNode.value, path: addPath(undefined, name, "literal"), argument: { definition: argDef, node: argumentNode } }); } else if (argumentNode) { const coercedValue = valueFromAST(argumentNode.value, argType); if (coercedValue === undefined) { // Note: ValuesOfCorrectType validation should catch this before // execution. This is a runtime check to ensure execution does not // continue with an invalid argument value. throw new GraphQLError( `Argument "${name}" of type "${argType}" has invalid value ${print( argumentNode.value )}.`, argumentNode.value ); } if (isASTValueWithVariables(coercedValue)) { missing.push( ...coercedValue.variables.map(({ valueNode, path }) => ({ valueNode, path: addPath(path, name, "literal") })) ); } values[name] = coercedValue.value; } if (isNonNullType(argType) && values[name] === undefined && !hasVariables) { // If no value or a nullish value was provided to a variable with a // non-null type (required), produce an error. throw new GraphQLError( argumentNode ? `Argument "${name}" of non-null type ` + `"${argType}" must not be null.` : `Argument "${name}" of required type ` + `"${argType}" was not provided.`, node ); } } return { values, missing }; } interface ASTValueWithVariables { value: object | string | boolean | symbol | number | null | any[]; variables: MissingVariablePath[]; } function isASTValueWithVariables(x: any): x is ASTValueWithVariables { return !!x.variables; } interface ASTValue { value: object | string | boolean | symbol | number | null | any[]; } export function valueFromAST( valueNode: ValueNode, type: GraphQLInputType ): undefined | ASTValue | ASTValueWithVariables { if (isNonNullType(type)) { if (valueNode.kind === Kind.NULL) { return; // Invalid: intentionally return no value. } return valueFromAST(valueNode, type.ofType); } if (valueNode.kind === Kind.NULL) { // This is explicitly returning the value null. return { value: null }; } if (valueNode.kind === Kind.VARIABLE) { return { value: null, variables: [{ valueNode, path: undefined }] }; } if (isListType(type)) { const itemType = type.ofType; if (valueNode.kind === Kind.LIST) { const coercedValues = []; const variables: MissingVariablePath[] = []; const itemNodes = valueNode.values; for (let i = 0; i < itemNodes.length; i++) { const itemNode = itemNodes[i]; if (itemNode.kind === Kind.VARIABLE) { coercedValues.push(null); variables.push({ valueNode: itemNode, path: addPath(undefined, i.toString(), "literal") }); } else { const itemValue = valueFromAST(itemNode, itemType); if (!itemValue) { return; // Invalid: intentionally return no value. } coercedValues.push(itemValue.value); if (isASTValueWithVariables(itemValue)) { variables.push( ...itemValue.variables.map(({ valueNode, path }) => ({ valueNode, path: addPath(path, i.toString(), "literal") })) ); } } } return { value: coercedValues, variables }; } // Single item which will be coerced to a list const coercedValue = valueFromAST(valueNode, itemType); if (coercedValue === undefined) { return; // Invalid: intentionally return no value. } if (isASTValueWithVariables(coercedValue)) { return { value: [coercedValue.value], variables: coercedValue.variables.map(({ valueNode, path }) => ({ valueNode, path: addPath(path, "0", "literal") })) }; } return { value: [coercedValue.value] }; } if (isInputObjectType(type)) { if (valueNode.kind !== Kind.OBJECT) { return; // Invalid: intentionally return no value. } const coercedObj = Object.create(null); const variables: MissingVariablePath[] = []; const fieldNodes = keyMap(valueNode.fields, (field) => field.name.value); const fields = Object.values(type.getFields()); for (const field of fields) { if (field.defaultValue !== undefined) { coercedObj[field.name] = field.defaultValue; } const fieldNode = fieldNodes[field.name]; if (!fieldNode) { continue; } const fieldValue = valueFromAST(fieldNode.value, field.type); if (!fieldValue) { return; // Invalid: intentionally return no value. } if (isASTValueWithVariables(fieldValue)) { variables.push( ...fieldValue.variables.map(({ valueNode, path }) => ({ valueNode, path: addPath(path, field.name, "literal") })) ); } coercedObj[field.name] = fieldValue.value; } return { value: coercedObj, variables }; } if (isEnumType(type)) { if (valueNode.kind !== Kind.ENUM) { return; // Invalid: intentionally return no value. } const enumValue = type.getValue(valueNode.value); if (!enumValue) { return; // Invalid: intentionally return no value. } return { value: enumValue.value }; } if (isScalarType(type)) { // Scalars fulfill parsing a literal value via parseLiteral(). // Invalid values represent a failure to parse correctly, in which case // no value is returned. let result: any; try { if (type.parseLiteral.length > 1) { // eslint-disable-next-line console.error( "Scalar with variable inputs detected for parsing AST literals. This is not supported." ); } result = type.parseLiteral(valueNode, {}); } catch (error) { return; // Invalid: intentionally return no value. } if (isInvalid(result)) { return; // Invalid: intentionally return no value. } return { value: result }; } // Not reachable. All possible input types have been considered. /* istanbul ignore next */ throw new Error(`Unexpected input type: "${inspect(type)}".`); } /** * Creates a keyed JS object from an array, given a function to produce the keys * for each value in the array. * * This provides a convenient lookup for the array items if the key function * produces unique results. * * const phoneBook = [ * { name: 'Jon', num: '555-1234' }, * { name: 'Jenny', num: '867-5309' } * ] * * // { Jon: { name: 'Jon', num: '555-1234' }, * // Jenny: { name: 'Jenny', num: '867-5309' } } * const entriesByName = keyMap( * phoneBook, * entry => entry.name * ) * * // { name: 'Jenny', num: '857-6309' } * const jennyEntry = entriesByName['Jenny'] * */ function keyMap<T>( list: ReadonlyArray<T>, keyFn: (item: T) => string ): { [key: string]: T } { return list.reduce( // eslint-disable-next-line no-sequences (map, item) => ((map[keyFn(item)] = item), map), Object.create(null) ); } export function computeLocations(nodes: ASTNode[]): SourceLocation[] { return nodes.reduce((list, node) => { if (node.loc) { list.push(getLocation(node.loc.source, node.loc.start)); } return list; }, [] as SourceLocation[]); } export function addPath( responsePath: ObjectPath | undefined, key: string, type: ResponsePathType = "literal" ): ObjectPath { return { prev: responsePath, key, type }; } export function flattenPath( path: ObjectPath ): Array<{ key: string; type: ResponsePathType }> { const flattened = []; let curr: ObjectPath | undefined = path; while (curr) { flattened.push({ key: curr.key, type: curr.type }); curr = curr.prev; } return flattened; } function isInvalid(value: any): boolean { // eslint-disable-next-line no-self-compare return value === undefined || value !== value; }
the_stack
import React from "react"; import { RouteComponentProps } from "react-router-dom"; import { GoThreeBars, GoX } from "react-icons/go"; import { BsArrowRightShort } from "react-icons/bs"; import { useDisclosureState, Disclosure, DisclosureContent, } from "reakit/Disclosure"; import formatDistance from "date-fns/formatDistance"; import { useQueryParam, StringParam } from "use-query-params"; import toast, { Toaster } from "react-hot-toast"; import { ErrorState } from "./error-state"; import Bug from "../bug.svg"; import { BookmarkIcon, CommitIcon, LinkExternalIcon, RepoIcon, } from "@primer/octicons-react"; import { Title } from "react-head"; import { useCommits, useGetFiles } from "../hooks"; import { Repo } from "../types"; import { JSONDetail } from "./json-detail-container"; import { parseFlatCommitMessage } from "../lib"; import { Picker } from "./picker"; import { FilePicker } from "./file-picker"; import { DisplayCommit } from "./display-commit"; import truncate from "lodash/truncate"; interface RepoDetailProps extends RouteComponentProps<Repo> {} export function RepoDetail(props: RepoDetailProps) { const { match } = props; const { owner, name } = match.params; const [filename, setFilename] = useQueryParam("filename", StringParam); const [selectedSha, setSelectedSha] = useQueryParam("sha", StringParam); const disclosure = useDisclosureState(); const { data: files, status: filesStatus, error: filesError, } = useGetFiles( { owner, name }, { onSuccess: (data) => { if (!data.length) return; setFilename(filename || data[0], "replaceIn"); }, } ); // Hook for fetching commits, once we've determined this is a Flat repo. const { data: commits = [] } = useCommits( { owner, name, filename }, { enabled: Boolean(filename), onSuccess: (commits) => { const mostRecentCommitSha = commits[0].sha; if (commits.length > 0) { if (selectedSha) { if (commits.some((commit) => commit.sha === selectedSha)) { // noop } else { toast.error( "Hmm, we couldn't find a commit by that SHA. Reverting to the most recent commit.", { duration: 4000, } ); setSelectedSha(mostRecentCommitSha, "replaceIn"); } } else { setSelectedSha(mostRecentCommitSha, "replaceIn"); } } }, } ); const repoUrl = `https://github.com/${owner}/${name}`; const parsedCommit = selectedSha ? parseFlatCommitMessage( commits?.find((commit) => commit.sha === selectedSha)?.commit.message || "", filename || "" ) : null; const dataSource = parsedCommit?.file?.source; const selectedShaIndex = commits.findIndex((d) => d.sha === selectedSha); const selectedShaPrevious = selectedShaIndex !== -1 ? (commits[selectedShaIndex + 1] || {}).sha : undefined; const controls = ( <div className="lg:flex space-y-4 lg:space-y-0 lg:space-x-4"> <div className="space-y-2"> <p className="text-xs font-medium text-indigo-200">Repository</p> <div className="font-mono text-sm text-white"> <a className="hover:underline focus:underline bg-indigo-700 hover:bg-indigo-800 focus:bg-indigo-800 h-9 rounded text-white inline-flex items-center px-2 focus:outline-none focus:ring-2 focus:ring-indigo-400" target="_blank" rel="noopener noreferrer" href={repoUrl} > <div className="flex items-center space-x-2"> <RepoIcon /> <div className="overflow-ellipsis whitespace-nowrap overflow-hidden text-xs" style={{ maxWidth: "min(30em, 100% - 1em)", }} > {owner}/{name} </div> <div className="opacity-50"> <LinkExternalIcon /> </div> </div> </a> </div> </div> {!!(files || []).length && ( <div className="space-y-2"> <p className="text-xs font-medium text-indigo-200">Data File</p> <FilePicker value={filename || ""} placeholder="Select a file" onChange={(newFilename) => { setFilename(newFilename); }} items={files || []} itemRenderer={(item) => ( <span className="font-mono text-xs">{item}</span> )} /> </div> )} {Boolean(filename) && ( <div className="space-y-2"> <p className="text-xs font-medium text-indigo-200">Commit</p> {commits && ( <Picker<string> label="Choose a commit" placeholder="Select a SHA" onChange={setSelectedSha} value={selectedSha || ""} items={commits.map((commit) => commit.sha)} disclosureClass="appearance-none bg-indigo-700 hover:bg-indigo-800 focus:bg-indigo-800 h-9 px-2 rounded text-white text-xs focus:outline-none focus:ring-2 focus:ring-indigo-400 w-full lg:max-w-md" itemRenderer={(sha) => { const commit = commits.find((commit) => commit.sha === sha); return ( <div className="flex flex-col space-y-1 text-xs"> <DisplayCommit message={commit?.commit.message} author={commit?.commit.author?.email} filename={filename} /> <div className="flex items-center space-x-2"> <div className="flex items-center space-x-2"> <p className="text-gray-600"> {formatDistance( new Date(commit?.commit.author?.date || ""), new Date(), { addSuffix: true } )} </p> </div> </div> </div> ); }} selectedItemRenderer={(sha) => ( <div className="flex items-center space-x-2"> <CommitIcon size={16} /> <div className="flex-1 truncate"> <DisplayCommit message={ commits.find((commit) => commit.sha === sha)?.commit .message } author={ commits.find((commit) => commit.sha === sha)?.commit .author?.email } filename={filename} /> </div> </div> )} /> )} </div> )} {!!dataSource && ( <div className="space-y-2 min-w-0"> <p className="text-xs font-medium text-indigo-200">Data source</p> <a className="font-mono hover:underline focus:underline bg-indigo-700 hover:bg-indigo-800 focus:bg-indigo-800 h-9 rounded text-white flex items-center px-2 focus:outline-none focus:ring-2 focus:ring-indigo-400" href={dataSource} target="_blank" rel="noopener noreferrer" > <div className="flex items-center space-x-2 min-w-0"> <div className="flex-none"> <BookmarkIcon /> </div> <div className="overflow-ellipsis whitespace-nowrap overflow-hidden text-xs"> {dataSource} </div> <div className="opacity-50"> <LinkExternalIcon /> </div> </div> </a> </div> )} </div> ); return ( <React.Fragment> <Title> {owner}/{name} – Flat </Title> <Toaster position="bottom-left" /> <div className="p-4 bg-indigo-600"> <header className="flex justify-between items-center"> <div className="text-indigo-100 font-light text-sm"> <strong className="font-bold">Flat Viewer</strong> a simple tool for exploring flat data files in GitHub repositories. </div> <Disclosure {...disclosure} className="rounded-none focus:outline-none focus:ring lg:hidden text-white text-xl" > {disclosure.visible ? <GoX /> : <GoThreeBars />} </Disclosure> </header> <DisclosureContent className="lg:hidden overflow-visible mt-4" {...disclosure} > {controls} </DisclosureContent> <Disclosure {...disclosure} className="rounded-none focus:outline-none focus:ring lg:hidden text-white text-xl" > {!disclosure.visible && ( <div className="flex items-center lg:hidden mt-4 text-white text-xs"> <span className="">{truncate(`${owner}/${name}`)}</span> {Boolean(filename) && ( <> <span className="mx-1"> <BsArrowRightShort /> </span>{" "} {truncate(filename || "")} </> )} </div> )} </Disclosure> <div className="controls mt-4">{controls}</div> </div> <React.Fragment> {selectedSha && Boolean(filename) && filesStatus !== "error" && ( <JSONDetail key={selectedSha} filename={filename || ""} owner={owner as string} name={name as string} previousSha={selectedShaPrevious} sha={selectedSha} /> )} </React.Fragment> {match && !(files || []).length && filesStatus !== "loading" && !selectedSha && ( <ErrorState img={Bug} alt="Error icon"> {files ? "Hmm, we couldn't find any files in that repo" : // @ts-ignore filesError && filesError?.message === "Error: Rate limit exceeded" ? // @ts-ignore filesError?.message : "Hmm, are you sure that's a public GitHub repo?"} </ErrorState> )} </React.Fragment> ); }
the_stack
import Animations = require('../../Animations'); import _Base = require('../../Core/_Base'); import _BaseUtils = require('../../Core/_BaseUtils'); import _Control = require('../../Utilities/_Control'); import _Dispose = require('../../Utilities/_Dispose'); import _ElementUtilities = require('../../Utilities/_ElementUtilities'); import _ErrorFromName = require('../../Core/_ErrorFromName'); import _Events = require('../../Core/_Events'); import _Global = require('../../Core/_Global'); import _Hoverable = require('../../Utilities/_Hoverable'); import _LightDismissService = require('../../_LightDismissService'); import Promise = require('../../Promise'); import _OpenCloseMachine = require('../../Utilities/_OpenCloseMachine'); import _TransitionAnimation = require('../../Animations/_TransitionAnimation'); require(["require-style!less/styles-splitview"]); require(["require-style!less/colors-splitview"]); "use strict"; // // Implementation Overview // // SplitView's responsibilities are divided into the following: // // Open/close state management // This involves firing the beforeopen, afteropen, beforeclose, and afterclose events. // It also involves making sure the control behaves properly when things happen in a // variety of states such as: // - open is called while the control is already open // - close is called while the control is in the middle of opening // - dispose is called within a beforeopen event handler // The SplitView relies on the _OpenCloseMachine component for most of this // state management. The contract is: // - The SplitView is responsible for specifying how to play the open and close // animations // - The _OpenCloseMachine is responsible for everything else including: // - Ensuring that these animations get run at the appropriate times // - Tracking the current state of the control and ensuring the right thing happens // when a method is called // - Firing the events // // Light dismiss // The SplitView's pane is light dismissable when the pane is open and the SplitView // is configured to openedDisplayMode:overlay. This means that the pane can be closed // thru a variety of cues such as tapping off of the pane, pressing the escape key, // and resizing the window. SplitView relies on the _LightDismissService component for // most of this functionality. The only pieces the SplitView is responsible for are: // - Describing what happens when a light dismiss is triggered on the SplitView. // - Describing how the SplitView should take/restore focus when it becomes the // topmost light dismissable. // // Open/close animations // Much of the SplitView's implementation is dedicated to playing the open and close // animations. The general approach is for the SplitView to calculate the current and // final sizes and positions of its pane and content elements. Then it creates a CSS // transition to animate the control between these two visual states. // // One tricky part of the animation is that the SplitView creates an animation that looks // like the pane is changing its width/height. You cannot animate width/height changes in CSS // so this animation is actually an illusion. It involves animating 2 elements, one which // clips the other, to give the illusion that an element is resizing. This logic is carried // out by Animations._resizeTransition. Take a look at that method for more details. // // Update DOM // SplitView follows the Update DOM pattern. For more information about this pattern, see: // https://github.com/winjs/winjs/wiki/Update-DOM-Pattern // // Note that the SplitView reads from the DOM when it needs to measure the position and size // of its pane and content elements. When possible, it caches this information and reads from // the cache instead of the DOM. This minimizes the performance cost. // // Outside of updateDom, SplitView writes to the DOM in a couple of places: // - The initializeDom function runs during construction and creates the // initial version of the SplitView's DOM. // - During animations, the animations take ownership of the DOM and turn // updateDom into a no-op. When the animation completes, updateDom begins // running again. This disabling of updateDom during animations is carried // out by _OpenCloseMachine. // interface IRect { left: number; top: number; contentWidth: number; contentHeight: number totalWidth: number; totalHeight: number; } export interface IThickness { content: number; total: number; } var transformNames = _BaseUtils._browserStyleEquivalents["transform"]; var Strings = { get duplicateConstruction() { return "Invalid argument: Controls may only be instantiated one time for each DOM element"; } }; var ClassNames = { splitView: "win-splitview", pane: "win-splitview-pane", content: "win-splitview-content", // closed/opened paneClosed: "win-splitview-pane-closed", paneOpened: "win-splitview-pane-opened", _panePlaceholder: "win-splitview-paneplaceholder", _paneOutline: "win-splitview-paneoutline", _tabStop: "win-splitview-tabstop", _paneWrapper: "win-splitview-panewrapper", _contentWrapper: "win-splitview-contentwrapper", _animating: "win-splitview-animating", // placement _placementLeft: "win-splitview-placementleft", _placementRight: "win-splitview-placementright", _placementTop: "win-splitview-placementtop", _placementBottom: "win-splitview-placementbottom", // closed display mode _closedDisplayNone: "win-splitview-closeddisplaynone", _closedDisplayInline: "win-splitview-closeddisplayinline", // opened display mode _openedDisplayInline: "win-splitview-openeddisplayinline", _openedDisplayOverlay: "win-splitview-openeddisplayoverlay" }; var EventNames = { beforeOpen: "beforeopen", afterOpen: "afteropen", beforeClose: "beforeclose", afterClose: "afterclose" }; var Dimension = { width: "width", height: "height" }; var ClosedDisplayMode = { /// <field locid="WinJS.UI.SplitView.ClosedDisplayMode.none" helpKeyword="WinJS.UI.SplitView.ClosedDisplayMode.none"> /// When the pane is closed, it is not visible and doesn't take up any space. /// </field> none: "none", /// <field locid="WinJS.UI.SplitView.ClosedDisplayMode.inline" helpKeyword="WinJS.UI.SplitView.ClosedDisplayMode.inline"> /// When the pane is closed, it occupies space leaving less room for the SplitView's content. /// </field> inline: "inline" }; var OpenedDisplayMode = { /// <field locid="WinJS.UI.SplitView.OpenedDisplayMode.inline" helpKeyword="WinJS.UI.SplitView.OpenedDisplayMode.inline"> /// When the pane is open, it occupies space leaving less room for the SplitView's content. /// </field> inline: "inline", /// <field locid="WinJS.UI.SplitView.OpenedDisplayMode.overlay" helpKeyword="WinJS.UI.SplitView.OpenedDisplayMode.overlay"> /// When the pane is open, it doesn't take up any space and it is light dismissable. /// </field> overlay: "overlay" }; var PanePlacement = { /// <field locid="WinJS.UI.SplitView.PanePlacement.left" helpKeyword="WinJS.UI.SplitView.PanePlacement.left"> /// Pane is positioned left of the SplitView's content. /// </field> left: "left", /// <field locid="WinJS.UI.SplitView.PanePlacement.right" helpKeyword="WinJS.UI.SplitView.PanePlacement.right"> /// Pane is positioned right of the SplitView's content. /// </field> right: "right", /// <field locid="WinJS.UI.SplitView.PanePlacement.top" helpKeyword="WinJS.UI.SplitView.PanePlacement.top"> /// Pane is positioned above the SplitView's content. /// </field> top: "top", /// <field locid="WinJS.UI.SplitView.PanePlacement.bottom" helpKeyword="WinJS.UI.SplitView.PanePlacement.bottom"> /// Pane is positioned below the SplitView's content. /// </field> bottom: "bottom" }; var closedDisplayModeClassMap = {}; closedDisplayModeClassMap[ClosedDisplayMode.none] = ClassNames._closedDisplayNone; closedDisplayModeClassMap[ClosedDisplayMode.inline] = ClassNames._closedDisplayInline; var openedDisplayModeClassMap = {}; openedDisplayModeClassMap[OpenedDisplayMode.overlay] = ClassNames._openedDisplayOverlay; openedDisplayModeClassMap[OpenedDisplayMode.inline] = ClassNames._openedDisplayInline; var panePlacementClassMap = {}; panePlacementClassMap[PanePlacement.left] = ClassNames._placementLeft; panePlacementClassMap[PanePlacement.right] = ClassNames._placementRight; panePlacementClassMap[PanePlacement.top] = ClassNames._placementTop; panePlacementClassMap[PanePlacement.bottom] = ClassNames._placementBottom; // Versions of add/removeClass that are no ops when called with falsy class names. function addClass(element: HTMLElement, className: string): void { className && _ElementUtilities.addClass(element, className); } function removeClass(element: HTMLElement, className: string): void { className && _ElementUtilities.removeClass(element, className); } function rectToThickness(rect: IRect, dimension: string): IThickness { return (dimension === Dimension.width) ? { content: rect.contentWidth, total: rect.totalWidth }: { content: rect.contentHeight, total: rect.totalHeight }; } /// <field> /// <summary locid="WinJS.UI.SplitView"> /// Displays a SplitView which renders a collapsable pane next to arbitrary HTML content. /// </summary> /// </field> /// <icon src="ui_winjs.ui.splitview.12x12.png" width="12" height="12" /> /// <icon src="ui_winjs.ui.splitview.16x16.png" width="16" height="16" /> /// <htmlSnippet supportsContent="true"><![CDATA[<div data-win-control="WinJS.UI.SplitView"></div>]]></htmlSnippet> /// <event name="beforeopen" locid="WinJS.UI.SplitView_e:beforeopen">Raised just before opening the pane. Call preventDefault on this event to stop the pane from opening.</event> /// <event name="afteropen" locid="WinJS.UI.SplitView_e:afteropen">Raised immediately after the pane is fully opened.</event> /// <event name="beforeclose" locid="WinJS.UI.SplitView_e:beforeclose">Raised just before closing the pane. Call preventDefault on this event to stop the pane from closing.</event> /// <event name="afterclose" locid="WinJS.UI.SplitView_e:afterclose">Raised immediately after the pane is fully closed.</event> /// <part name="splitview" class="win-splitview" locid="WinJS.UI.SplitView_part:splitview">The entire SplitView control.</part> /// <part name="splitview-pane" class="win-splitview-pane" locid="WinJS.UI.SplitView_part:splitview-pane">The element which hosts the SplitView's pane.</part> /// <part name="splitview-content" class="win-splitview-content" locid="WinJS.UI.SplitView_part:splitview-content">The element which hosts the SplitView's content.</part> /// <resource type="javascript" src="//$(TARGET_DESTINATION)/js/WinJS.js" shared="true" /> /// <resource type="css" src="//$(TARGET_DESTINATION)/css/ui-dark.css" shared="true" /> export class SplitView { /// <field locid="WinJS.UI.SplitView.ClosedDisplayMode" helpKeyword="WinJS.UI.SplitView.ClosedDisplayMode"> /// Display options for a SplitView's pane when it is closed. /// </field> static ClosedDisplayMode = ClosedDisplayMode; /// <field locid="WinJS.UI.SplitView.OpenedDisplayMode" helpKeyword="WinJS.UI.SplitView.OpenedDisplayMode"> /// Display options for a SplitView's pane when it is open. /// </field> static OpenedDisplayMode = OpenedDisplayMode; /// <field locid="WinJS.UI.SplitView.PanePlacement" helpKeyword="WinJS.UI.SplitView.PanePlacement"> /// Placement options for a SplitView's pane. /// </field> static PanePlacement = PanePlacement; static supportedForProcessing: boolean = true; private static _ClassNames = ClassNames; private _disposed: boolean; private _machine: _OpenCloseMachine.OpenCloseMachine; _dom: { root: HTMLElement; pane: HTMLElement; startPaneTab: HTMLElement; endPaneTab: HTMLElement; paneOutline: HTMLElement; paneWrapper: HTMLElement; // Shouldn't have any margin, padding, or border. panePlaceholder: HTMLElement; // Shouldn't have any margin, padding, or border. content: HTMLElement; contentWrapper: HTMLElement; // Shouldn't have any margin, padding, or border. }; private _dismissable: _LightDismissService.LightDismissableElement; private _isOpenedMode: boolean; // Is ClassNames.paneOpened present on the SplitView? private _rtl: boolean; private _cachedHiddenPaneThickness: IThickness; private _lowestPaneTabIndex: number; private _highestPaneTabIndex: number; private _updateTabIndicesThrottled: Function; constructor(element?: HTMLElement, options: any = {}) { /// <signature helpKeyword="WinJS.UI.SplitView.SplitView"> /// <summary locid="WinJS.UI.SplitView.constructor"> /// Creates a new SplitView control. /// </summary> /// <param name="element" type="HTMLElement" domElement="true" isOptional="true" locid="WinJS.UI.SplitView.constructor_p:element"> /// The DOM element that hosts the SplitView control. /// </param> /// <param name="options" type="Object" isOptional="true" locid="WinJS.UI.SplitView.constructor_p:options"> /// An object that contains one or more property/value pairs to apply to the new control. /// Each property of the options object corresponds to one of the control's properties or events. /// Event names must begin with "on". For example, to provide a handler for the beforeclose event, /// add a property named "onbeforeclose" to the options object and set its value to the event handler. /// </param> /// <returns type="WinJS.UI.SplitView" locid="WinJS.UI.SplitView.constructor_returnValue"> /// The new SplitView. /// </returns> /// </signature> // Check to make sure we weren't duplicated if (element && element["winControl"]) { throw new _ErrorFromName("WinJS.UI.SplitView.DuplicateConstruction", Strings.duplicateConstruction); } this._initializeDom(element || _Global.document.createElement("div")); this._machine = new _OpenCloseMachine.OpenCloseMachine({ eventElement: this._dom.root, onOpen: () => { this._cachedHiddenPaneThickness = null; var hiddenPaneThickness = this._getHiddenPaneThickness(); this._isOpenedMode = true; this._updateDomImpl(); _ElementUtilities.addClass(this._dom.root, ClassNames._animating); return this._playShowAnimation(hiddenPaneThickness).then(() => { _ElementUtilities.removeClass(this._dom.root, ClassNames._animating); }); }, onClose: () => { _ElementUtilities.addClass(this._dom.root, ClassNames._animating); return this._playHideAnimation(this._getHiddenPaneThickness()).then(() => { _ElementUtilities.removeClass(this._dom.root, ClassNames._animating); this._isOpenedMode = false; this._updateDomImpl(); }); }, onUpdateDom: () => { this._updateDomImpl(); }, onUpdateDomWithIsOpened: (isOpened: boolean) => { this._isOpenedMode = isOpened; this._updateDomImpl(); } }); // Initialize private state. this._disposed = false; this._dismissable = new _LightDismissService.LightDismissableElement({ element: this._dom.paneWrapper, tabIndex: -1, onLightDismiss: () => { this.closePane(); }, onTakeFocus: (useSetActive) => { this._dismissable.restoreFocus() || _ElementUtilities._tryFocusOnAnyElement(this._dom.pane, useSetActive); } }); this._cachedHiddenPaneThickness = null; // Initialize public properties. this.paneOpened = false; this.closedDisplayMode = ClosedDisplayMode.inline; this.openedDisplayMode = OpenedDisplayMode.overlay; this.panePlacement = PanePlacement.left; _Control.setOptions(this, options); // Exit the Init state. _ElementUtilities._inDom(this._dom.root).then(() => { this._rtl = _ElementUtilities._getComputedStyle(this._dom.root).direction === 'rtl'; this._updateTabIndices(); this._machine.exitInit(); }); } /// <field type="HTMLElement" domElement="true" readonly="true" hidden="true" locid="WinJS.UI.SplitView.element" helpKeyword="WinJS.UI.SplitView.element"> /// Gets the DOM element that hosts the SplitView control. /// </field> get element(): HTMLElement { return this._dom.root; } /// <field type="HTMLElement" domElement="true" readonly="true" hidden="true" locid="WinJS.UI.SplitView.paneElement" helpKeyword="WinJS.UI.SplitView.paneElement"> /// Gets the DOM element that hosts the SplitView pane. /// </field> get paneElement(): HTMLElement { return this._dom.pane; } /// <field type="HTMLElement" domElement="true" readonly="true" hidden="true" locid="WinJS.UI.SplitView.contentElement" helpKeyword="WinJS.UI.SplitView.contentElement"> /// Gets the DOM element that hosts the SplitView's content. /// </field> get contentElement(): HTMLElement { return this._dom.content; } private _closedDisplayMode: string; /// <field type="String" oamOptionsDatatype="WinJS.UI.SplitView.ClosedDisplayMode" locid="WinJS.UI.SplitView.closedDisplayMode" helpKeyword="WinJS.UI.SplitView.closedDisplayMode"> /// Gets or sets the display mode of the SplitView's pane when it is hidden. /// </field> get closedDisplayMode(): string { return this._closedDisplayMode; } set closedDisplayMode(value: string) { if (ClosedDisplayMode[value] && this._closedDisplayMode !== value) { this._closedDisplayMode = value; this._cachedHiddenPaneThickness = null; this._machine.updateDom(); } } private _openedDisplayMode: string; /// <field type="String" oamOptionsDatatype="WinJS.UI.SplitView.OpenedDisplayMode" locid="WinJS.UI.SplitView.openedDisplayMode" helpKeyword="WinJS.UI.SplitView.openedDisplayMode"> /// Gets or sets the display mode of the SplitView's pane when it is open. /// </field> get openedDisplayMode(): string { return this._openedDisplayMode; } set openedDisplayMode(value: string) { if (OpenedDisplayMode[value] && this._openedDisplayMode !== value) { this._openedDisplayMode = value; this._cachedHiddenPaneThickness = null; this._machine.updateDom(); } } private _panePlacement: string; /// <field type="String" oamOptionsDatatype="WinJS.UI.SplitView.PanePlacement" locid="WinJS.UI.SplitView.panePlacement" helpKeyword="WinJS.UI.SplitView.panePlacement"> /// Gets or sets the placement of the SplitView's pane. /// </field> get panePlacement(): string { return this._panePlacement; } set panePlacement(value: string) { if (PanePlacement[value] && this._panePlacement !== value) { this._panePlacement = value; this._cachedHiddenPaneThickness = null; this._machine.updateDom(); } } /// <field type="Boolean" hidden="true" locid="WinJS.UI.SplitView.paneOpened" helpKeyword="WinJS.UI.SplitView.paneOpened"> /// Gets or sets whether the SpitView's pane is currently opened. /// </field> get paneOpened(): boolean { return this._machine.opened; } set paneOpened(value: boolean) { this._machine.opened = value; } dispose(): void { /// <signature helpKeyword="WinJS.UI.SplitView.dispose"> /// <summary locid="WinJS.UI.SplitView.dispose"> /// Disposes this control. /// </summary> /// </signature> if (this._disposed) { return; } this._disposed = true; this._machine.dispose(); _LightDismissService.hidden(this._dismissable); _Dispose._disposeElement(this._dom.pane); _Dispose._disposeElement(this._dom.content); } openPane(): void { /// <signature helpKeyword="WinJS.UI.SplitView.openPane"> /// <summary locid="WinJS.UI.SplitView.openPane"> /// Opens the SplitView's pane. /// </summary> /// </signature> this._machine.open(); } closePane(): void { /// <signature helpKeyword="WinJS.UI.SplitView.closePane"> /// <summary locid="WinJS.UI.SplitView.closePane"> /// Closes the SplitView's pane. /// </summary> /// </signature> this._machine.close(); } private _initializeDom(root: HTMLElement): void { // The first child is the pane var paneEl = <HTMLElement>root.firstElementChild || _Global.document.createElement("div"); _ElementUtilities.addClass(paneEl, ClassNames.pane); if (!paneEl.hasAttribute("tabIndex")) { paneEl.tabIndex = -1; } // All other children are members of the content var contentEl = _Global.document.createElement("div"); _ElementUtilities.addClass(contentEl, ClassNames.content); var child = paneEl.nextSibling; while (child) { var sibling = child.nextSibling; contentEl.appendChild(child); child = sibling; } var startPaneTabEl = _Global.document.createElement("div"); startPaneTabEl.className = ClassNames._tabStop; _ElementUtilities._ensureId(startPaneTabEl); var endPaneTabEl = _Global.document.createElement("div"); endPaneTabEl.className = ClassNames._tabStop; _ElementUtilities._ensureId(endPaneTabEl); // paneOutline's purpose is to render an outline around the pane in high contrast mode var paneOutlineEl = _Global.document.createElement("div"); paneOutlineEl.className = ClassNames._paneOutline; // paneWrapper's purpose is to clip the pane during the pane resize animation var paneWrapperEl = _Global.document.createElement("div"); paneWrapperEl.className = ClassNames._paneWrapper; paneWrapperEl.appendChild(startPaneTabEl); paneWrapperEl.appendChild(paneEl); paneWrapperEl.appendChild(paneOutlineEl); paneWrapperEl.appendChild(endPaneTabEl); var panePlaceholderEl = _Global.document.createElement("div"); panePlaceholderEl.className = ClassNames._panePlaceholder; // contentWrapper is an extra element we need to allow heights to be specified as percentages (e.g. height: 100%) // for elements within the content area. It works around this Chrome bug: // Issue 428049: 100% height doesn't work on child of a definite-flex-basis flex item (in vertical flex container) // https://code.google.com/p/chromium/issues/detail?id=428049 // The workaround is that putting a position: absolute element (_dom.content) within the flex item (_dom.contentWrapper) // allows percentage heights to work within the absolutely positioned element (_dom.content). var contentWrapperEl = _Global.document.createElement("div"); contentWrapperEl.className = ClassNames._contentWrapper; contentWrapperEl.appendChild(contentEl); root["winControl"] = this; _ElementUtilities.addClass(root, ClassNames.splitView); _ElementUtilities.addClass(root, "win-disposable"); this._dom = { root: root, pane: paneEl, startPaneTab: startPaneTabEl, endPaneTab: endPaneTabEl, paneOutline: paneOutlineEl, paneWrapper: paneWrapperEl, panePlaceholder: panePlaceholderEl, content: contentEl, contentWrapper: contentWrapperEl }; _ElementUtilities._addEventListener(paneEl, "keydown", this._onKeyDown.bind(this)); _ElementUtilities._addEventListener(startPaneTabEl, "focusin", this._onStartPaneTabFocusIn.bind(this)); _ElementUtilities._addEventListener(endPaneTabEl, "focusin", this._onEndPaneTabFocusIn.bind(this)); } private _onKeyDown(eventObject: KeyboardEvent) { if (eventObject.keyCode === _ElementUtilities.Key.tab) { this._updateTabIndices(); } } private _onStartPaneTabFocusIn(eventObject: FocusEvent) { _ElementUtilities._focusLastFocusableElement(this._dom.pane); } private _onEndPaneTabFocusIn(eventObject: FocusEvent) { _ElementUtilities._focusFirstFocusableElement(this._dom.pane); } private _measureElement(element: HTMLElement): IRect { var style = _ElementUtilities._getComputedStyle(element); var position = _ElementUtilities._getPositionRelativeTo(element, this._dom.root); var marginLeft = parseInt(style.marginLeft, 10); var marginTop = parseInt(style.marginTop, 10); return { left: position.left - marginLeft, top: position.top - marginTop, contentWidth: _ElementUtilities.getContentWidth(element), contentHeight: _ElementUtilities.getContentHeight(element), totalWidth: _ElementUtilities.getTotalWidth(element), totalHeight: _ElementUtilities.getTotalHeight(element) }; } private _setContentRect(contentRect: IRect) { var contentWrapperStyle = this._dom.contentWrapper.style; contentWrapperStyle.left = contentRect.left + "px"; contentWrapperStyle.top = contentRect.top + "px"; contentWrapperStyle.height = contentRect.contentHeight + "px"; contentWrapperStyle.width = contentRect.contentWidth + "px"; } // Overridden by tests. private _prepareAnimation(paneRect: IRect, contentRect: IRect): void { var paneWrapperStyle = this._dom.paneWrapper.style; paneWrapperStyle.position = "absolute"; paneWrapperStyle.left = paneRect.left + "px"; paneWrapperStyle.top = paneRect.top + "px"; paneWrapperStyle.height = paneRect.totalHeight + "px"; paneWrapperStyle.width = paneRect.totalWidth + "px"; var contentWrapperStyle = this._dom.contentWrapper.style; contentWrapperStyle.position = "absolute"; this._setContentRect(contentRect); } // Overridden by tests. private _clearAnimation(): void { var paneWrapperStyle = this._dom.paneWrapper.style; paneWrapperStyle.position = ""; paneWrapperStyle.left = ""; paneWrapperStyle.top = ""; paneWrapperStyle.height = ""; paneWrapperStyle.width = ""; paneWrapperStyle[transformNames.scriptName] = ""; var contentWrapperStyle = this._dom.contentWrapper.style; contentWrapperStyle.position = ""; contentWrapperStyle.left = ""; contentWrapperStyle.top = ""; contentWrapperStyle.height = ""; contentWrapperStyle.width = ""; contentWrapperStyle[transformNames.scriptName] = ""; var paneStyle = this._dom.pane.style; paneStyle.height = ""; paneStyle.width = ""; paneStyle[transformNames.scriptName] = ""; } private _getHiddenContentRect(shownContentRect: IRect, hiddenPaneThickness: IThickness, shownPaneThickness: IThickness): IRect { if (this.openedDisplayMode === OpenedDisplayMode.overlay) { return shownContentRect; } else { var placementRight = this._rtl ? PanePlacement.left : PanePlacement.right; var multiplier = this.panePlacement === placementRight || this.panePlacement === PanePlacement.bottom ? 0 : 1; var paneDiff = { content: shownPaneThickness.content - hiddenPaneThickness.content, total: shownPaneThickness.total - hiddenPaneThickness.total }; return this._horizontal ? { left: shownContentRect.left - multiplier * paneDiff.total, top: shownContentRect.top, contentWidth: shownContentRect.contentWidth + paneDiff.content, contentHeight: shownContentRect.contentHeight, totalWidth: shownContentRect.totalWidth + paneDiff.total, totalHeight: shownContentRect.totalHeight } : { left: shownContentRect.left, top: shownContentRect.top - multiplier * paneDiff.total, contentWidth: shownContentRect.contentWidth, contentHeight: shownContentRect.contentHeight + paneDiff.content, totalWidth: shownContentRect.totalWidth, totalHeight: shownContentRect.totalHeight + paneDiff.total } } } private get _horizontal(): boolean { return this.panePlacement === PanePlacement.left || this.panePlacement === PanePlacement.right; } private _getHiddenPaneThickness(): IThickness { if (this._cachedHiddenPaneThickness === null) { if (this._closedDisplayMode === ClosedDisplayMode.none) { this._cachedHiddenPaneThickness = { content: 0, total: 0 }; } else { if (this._isOpenedMode) { _ElementUtilities.removeClass(this._dom.root, ClassNames.paneOpened); _ElementUtilities.addClass(this._dom.root, ClassNames.paneClosed); } var size = this._measureElement(this._dom.pane); this._cachedHiddenPaneThickness = rectToThickness(size, this._horizontal ? Dimension.width : Dimension.height); if (this._isOpenedMode) { _ElementUtilities.removeClass(this._dom.root, ClassNames.paneClosed); _ElementUtilities.addClass(this._dom.root, ClassNames.paneOpened); } } } return this._cachedHiddenPaneThickness; } // Should be called while SplitView is rendered in its opened mode // Overridden by tests. private _playShowAnimation(hiddenPaneThickness: IThickness): Promise<any> { var dim = this._horizontal ? Dimension.width : Dimension.height; var shownPaneRect = this._measureElement(this._dom.pane); var shownContentRect = this._measureElement(this._dom.content); var shownPaneThickness = rectToThickness(shownPaneRect, dim); var hiddenContentRect = this._getHiddenContentRect(shownContentRect, hiddenPaneThickness, shownPaneThickness); this._prepareAnimation(shownPaneRect, hiddenContentRect); var playPaneAnimation = (): Promise<any> => { var placementRight = this._rtl ? PanePlacement.left : PanePlacement.right; // What percentage of the size change should be skipped? (e.g. let's do the first // 30% of the size change instantly and then animate the other 70%) var animationOffsetFactor = 0.3; var from = hiddenPaneThickness.total + animationOffsetFactor * (shownPaneThickness.total - hiddenPaneThickness.total); return Animations._resizeTransition(this._dom.paneWrapper, this._dom.pane, { from: from, to: shownPaneThickness.total, actualSize: shownPaneThickness.total, dimension: dim, anchorTrailingEdge: this.panePlacement === placementRight || this.panePlacement === PanePlacement.bottom }); }; var playShowAnimation = (): Promise<any> => { if (this.openedDisplayMode === OpenedDisplayMode.inline) { this._setContentRect(shownContentRect); } return playPaneAnimation(); }; return playShowAnimation().then(() => { this._clearAnimation(); }); } // Should be called while SplitView is rendered in its opened mode // Overridden by tests. private _playHideAnimation(hiddenPaneThickness: IThickness): Promise<any> { var dim = this._horizontal ? Dimension.width : Dimension.height; var shownPaneRect = this._measureElement(this._dom.pane); var shownContentRect = this._measureElement(this._dom.content); var shownPaneThickness = rectToThickness(shownPaneRect, dim); var hiddenContentRect = this._getHiddenContentRect(shownContentRect, hiddenPaneThickness, shownPaneThickness); this._prepareAnimation(shownPaneRect, shownContentRect); var playPaneAnimation = (): Promise<any> => { var placementRight = this._rtl ? PanePlacement.left : PanePlacement.right; // What percentage of the size change should be skipped? (e.g. let's do the first // 30% of the size change instantly and then animate the other 70%) var animationOffsetFactor = 0.3; var from = shownPaneThickness.total - animationOffsetFactor * (shownPaneThickness.total - hiddenPaneThickness.total); return Animations._resizeTransition(this._dom.paneWrapper, this._dom.pane, { from: from, to: hiddenPaneThickness.total, actualSize: shownPaneThickness.total, dimension: dim, anchorTrailingEdge: this.panePlacement === placementRight || this.panePlacement === PanePlacement.bottom }); }; var playHideAnimation = (): Promise<any> => { if (this.openedDisplayMode === OpenedDisplayMode.inline) { this._setContentRect(hiddenContentRect); } return playPaneAnimation(); }; return playHideAnimation().then(() => { this._clearAnimation(); }); } // _updateTabIndices and _updateTabIndicesImpl are used in tests private _updateTabIndices() { if (!this._updateTabIndicesThrottled) { this._updateTabIndicesThrottled = _BaseUtils._throttledFunction(100, this._updateTabIndicesImpl.bind(this)); } this._updateTabIndicesThrottled(); } private _updateTabIndicesImpl() { var tabIndex = _ElementUtilities._getHighAndLowTabIndices(this._dom.pane); this._highestPaneTabIndex = tabIndex.highest; this._lowestPaneTabIndex = tabIndex.lowest; this._machine.updateDom(); } // State private to _updateDomImpl. No other method should make use of it. // // Nothing has been rendered yet so these are all initialized to undefined. Because // they are undefined, the first time _updateDomImpl is called, they will all be // rendered. private _updateDomImpl_rendered = { paneIsFirst: <boolean>undefined, isOpenedMode: <boolean>undefined, closedDisplayMode: <string>undefined, openedDisplayMode: <string>undefined, panePlacement: <string>undefined, panePlaceholderWidth: <string>undefined, panePlaceholderHeight: <string>undefined, isOverlayShown: <boolean>undefined, startPaneTabIndex: <number>undefined, endPaneTabIndex: <number>undefined }; private _updateDomImpl(): void { var rendered = this._updateDomImpl_rendered; var paneShouldBeFirst = this.panePlacement === PanePlacement.left || this.panePlacement === PanePlacement.top; if (paneShouldBeFirst !== rendered.paneIsFirst) { // TODO: restore focus if (paneShouldBeFirst) { this._dom.root.appendChild(this._dom.panePlaceholder); this._dom.root.appendChild(this._dom.paneWrapper); this._dom.root.appendChild(this._dom.contentWrapper); } else { this._dom.root.appendChild(this._dom.contentWrapper); this._dom.root.appendChild(this._dom.paneWrapper); this._dom.root.appendChild(this._dom.panePlaceholder); } } rendered.paneIsFirst = paneShouldBeFirst; if (rendered.isOpenedMode !== this._isOpenedMode) { if (this._isOpenedMode) { _ElementUtilities.removeClass(this._dom.root, ClassNames.paneClosed); _ElementUtilities.addClass(this._dom.root, ClassNames.paneOpened); } else { _ElementUtilities.removeClass(this._dom.root, ClassNames.paneOpened); _ElementUtilities.addClass(this._dom.root, ClassNames.paneClosed); } } rendered.isOpenedMode = this._isOpenedMode; if (rendered.panePlacement !== this.panePlacement) { removeClass(this._dom.root, panePlacementClassMap[rendered.panePlacement]); addClass(this._dom.root, panePlacementClassMap[this.panePlacement]); rendered.panePlacement = this.panePlacement; } if (rendered.closedDisplayMode !== this.closedDisplayMode) { removeClass(this._dom.root, closedDisplayModeClassMap[rendered.closedDisplayMode]); addClass(this._dom.root, closedDisplayModeClassMap[this.closedDisplayMode]); rendered.closedDisplayMode = this.closedDisplayMode; } if (rendered.openedDisplayMode !== this.openedDisplayMode) { removeClass(this._dom.root, openedDisplayModeClassMap[rendered.openedDisplayMode]); addClass(this._dom.root, openedDisplayModeClassMap[this.openedDisplayMode]); rendered.openedDisplayMode = this.openedDisplayMode; } var isOverlayShown = this._isOpenedMode && this.openedDisplayMode === OpenedDisplayMode.overlay; var startPaneTabIndex = isOverlayShown ? this._lowestPaneTabIndex : -1; var endPaneTabIndex = isOverlayShown ? this._highestPaneTabIndex : -1; if (rendered.startPaneTabIndex !== startPaneTabIndex) { this._dom.startPaneTab.tabIndex = startPaneTabIndex; if (startPaneTabIndex === -1) { this._dom.startPaneTab.removeAttribute("x-ms-aria-flowfrom"); } else { this._dom.startPaneTab.setAttribute("x-ms-aria-flowfrom", this._dom.endPaneTab.id); } rendered.startPaneTabIndex = startPaneTabIndex; } if (rendered.endPaneTabIndex !== endPaneTabIndex) { this._dom.endPaneTab.tabIndex = endPaneTabIndex; if (endPaneTabIndex === -1) { this._dom.endPaneTab.removeAttribute("aria-flowto"); } else { this._dom.endPaneTab.setAttribute("aria-flowto", this._dom.startPaneTab.id); } rendered.endPaneTabIndex = endPaneTabIndex; } // panePlaceholder's purpose is to take up the amount of space occupied by the // hidden pane while the pane is shown in overlay mode. Without this, the content // would shift as the pane shows and hides in overlay mode. var width: string, height: string; if (isOverlayShown) { var hiddenPaneThickness = this._getHiddenPaneThickness(); if (this._horizontal) { width = hiddenPaneThickness.total + "px"; height = ""; } else { width = ""; height = hiddenPaneThickness.total + "px"; } } else { width = ""; height = ""; } if (rendered.panePlaceholderWidth !== width || rendered.panePlaceholderHeight !== height) { var style = this._dom.panePlaceholder.style; style.width = width; style.height = height; rendered.panePlaceholderWidth = width; rendered.panePlaceholderHeight = height; } if (rendered.isOverlayShown !== isOverlayShown) { if (isOverlayShown) { _LightDismissService.shown(this._dismissable); } else { _LightDismissService.hidden(this._dismissable); } rendered.isOverlayShown = isOverlayShown; } } } _Base.Class.mix(SplitView, _Events.createEventProperties( EventNames.beforeOpen, EventNames.afterOpen, EventNames.beforeClose, EventNames.afterClose )); _Base.Class.mix(SplitView, _Control.DOMEventMixin);
the_stack
import { ZoneId, LocalDateTime, LocalDate, LocalTime, ZonedDateTime, DateTimeParseException, DateTimeFormatter, Instant, convert, Temporal, DateTimeFormatterBuilder, ResolverStyle, IsoChronology, ChronoField, ChronoUnit, YearMonth, Year, TemporalQueries, } from "@js-joda/core"; import { Locale } from "@js-joda/locale_en-us"; import { DateIOFormats, IUtils, Unit } from "@date-io/core/IUtils"; type CalendarType = LocalDateTime | LocalDate | ZonedDateTime; const isoformatter = new DateTimeFormatterBuilder() .parseCaseInsensitive() .append(DateTimeFormatter.ISO_LOCAL_DATE) .appendLiteral("T") .append(DateTimeFormatter.ISO_LOCAL_TIME) .appendLiteral(".") .appendValue(ChronoField.MICRO_OF_SECOND, 3) .appendLiteral("Z") .toFormatter(ResolverStyle.STRICT) .withChronology(IsoChronology["INSTANCE"]); const OPTIONAL_FORMATTER = DateTimeFormatter.ofPattern( "yyyy-MM-dd['T'HH:mm[:ss[.SSS['Z']]]" ); const ampmregex = new RegExp(".*a.*"); // create a temporal query that create a new Temporal depending on the existing fields const dateOrDateTimeQuery = { queryFrom: function (temporal) { var date = temporal.query(TemporalQueries.localDate()); var time = temporal.query(TemporalQueries.localTime()); if (time == null) return date; else return date.atTime(time); }, }; // v2.0.0 // interface Opts { locale?: Locale; formats?: Partial<DateIOFormats>; } const defaultFormats: DateIOFormats = { dayOfMonth: "d", fullDate: "LLL d, yyyy", fullDateWithWeekday: "EEEE, LLLL d, yyyy", fullDateTime: "LLL d, yyyy hh:mm a", fullDateTime12h: "LLL d, yyyy hh:mm a", fullDateTime24h: "LLL d, yyyy HH:mm", fullTime: "hh:mm a", fullTime12h: "hh:mm a", fullTime24h: "HH:mm", hours12h: "hh", hours24h: "HH", keyboardDate: "MM/dd/yyyy", keyboardDateTime: "MM/dd/yyyy hh:mm a", keyboardDateTime12h: "MM/dd/yyyy hh:mm a", keyboardDateTime24h: "MM/dd/yyyy HH:mm", minutes: "mm", month: "LLLL", monthAndDate: "LLLL d", monthAndYear: "LLLL yyyy", monthShort: "LLL", weekday: "EEEE", weekdayShort: "EEE", normalDate: "d MMMM", normalDateWithWeekday: "EEE, MMM d", seconds: "ss", shortDate: "MMM d", year: "yyyy", }; function getChronoUnit(unit?: Unit): ChronoUnit { switch (unit) { case "years": return ChronoUnit.YEARS; case "quarters": return null; case "months": return ChronoUnit.MONTHS; case "weeks": return ChronoUnit.WEEKS; case "days": return ChronoUnit.DAYS; case "hours": return ChronoUnit.HOURS; case "minutes": return ChronoUnit.MINUTES; case "seconds": return ChronoUnit.SECONDS; default: { return ChronoUnit.MILLIS; } } } export default class JsJodaUtils implements IUtils<Temporal> { lib: "js-joda"; locale?: Locale; formats: DateIOFormats; constructor({ locale, formats, }: { formats?: Partial<DateIOFormats>; locale?: Locale } = {}) { this.locale = locale || Locale.US; this.formats = Object.assign({}, defaultFormats, formats); } parse(value: string, format: string): Temporal | null { if (value === "") { return null; } let formatter = DateTimeFormatter.ofPattern(format).withLocale(this.locale); try { let parsed_assessor = formatter.parse(value); if ( parsed_assessor.isSupported(ChronoField.YEAR) && parsed_assessor.isSupported(ChronoField.MONTH_OF_YEAR) && parsed_assessor.isSupported(ChronoField.DAY_OF_MONTH) ) { if ( parsed_assessor.isSupported(ChronoField.HOUR_OF_DAY) && parsed_assessor.isSupported(ChronoField.MINUTE_OF_HOUR) && parsed_assessor.isSupported(ChronoField.SECOND_OF_MINUTE) ) { return LocalDateTime.from(parsed_assessor); } else { return LocalDate.from(parsed_assessor); } } } catch (ex) { if (ex instanceof DateTimeParseException) { return <Temporal>(<unknown>ex); } } } date(value?: any): Temporal | null { if (value === null) { return null; } if (value === undefined) { return LocalDateTime.now(); } if (typeof value === "string") { try { return OPTIONAL_FORMATTER.parse(value, dateOrDateTimeQuery); } catch (ex) { if (ex instanceof DateTimeParseException) { return <Temporal>(<unknown>ex); } } } if (value instanceof Temporal) { return value; } if (value instanceof Date) { const instant = Instant.ofEpochMilli(value.valueOf()); return LocalDateTime.ofInstant(instant, ZoneId.systemDefault()); } // throw new Error(`Unknown Date value in function date(): ${value}`); } isNull(date: Temporal | null): boolean { return date === null; } isValid(value: any): boolean { if (value instanceof Error) { return false; } if (value === null) { return false; } if (value === undefined) { return true; } // if (value instanceof Date) { // return !isNaN(value.valueOf()); // } if (typeof value === "string") { return !isNaN(new Date(value).valueOf()); } if (value instanceof Temporal) { return true; } // throw new Error(`Unknown Date value in function isValid(): ${value}`); } getDiff = (value: CalendarType, comparing: CalendarType | string, unit?: Unit) => { let chronoUnit = getChronoUnit(unit); if (chronoUnit === null) { switch (unit) { case "quarters": return Math.floor(ChronoUnit.MONTHS.between(this.date(comparing), value) / 4); } } else { return chronoUnit.between(this.date(comparing), value); } }; isEqual(value: any, comparing: any): boolean { const first = this.date(value); const second = this.date(comparing); if (first === null && second === null) { return true; } if (first === null || second === null) { return false; } // if (first instanceof Error || second instanceof Error) { // throw first || second; // } if (first instanceof LocalDateTime && second instanceof LocalDateTime) { return first.isEqual(second); } if (first instanceof LocalDate && second instanceof LocalDate) { return first.isEqual(second); } // return false; } isSameDay(date: Temporal, comparing: Temporal): boolean { return LocalDate.from(date).isEqual(LocalDate.from(comparing)); } isSameMonth(date: Temporal, comparing: Temporal): boolean { return YearMonth.from(date).equals(YearMonth.from(comparing)); } isSameYear(date: Temporal, comparing: Temporal): boolean { return Year.from(date).equals(Year.from(comparing)); } isSameHour(date: Temporal, comparing: Temporal): boolean { return ( date.get(ChronoField.HOUR_OF_DAY) === comparing.get(ChronoField.HOUR_OF_DAY) && date.get(ChronoField.DAY_OF_MONTH) === comparing.get(ChronoField.DAY_OF_MONTH) && date.get(ChronoField.MONTH_OF_YEAR) === comparing.get(ChronoField.MONTH_OF_YEAR) && date.get(ChronoField.YEAR) === comparing.get(ChronoField.YEAR) ); } isAfter(date: Temporal, value: Temporal): boolean { if (date instanceof LocalDateTime && value instanceof LocalDateTime) { return date.isAfter(value); } else if (date instanceof LocalDate && value instanceof LocalDate) { return date.isAfter(value); } } isAfterDay(date: Temporal, value: Temporal): boolean { let datedate = LocalDate.from(date); let valuedate = LocalDate.from(value); return datedate.isAfter(valuedate); } isAfterYear(date: Temporal, value: Temporal): boolean { let datedate = Year.from(date); let valuedate = Year.from(value); return datedate.isAfter(valuedate); } isBeforeDay(date: Temporal, value: Temporal): boolean { let datedate = LocalDate.from(date); let valuedate = LocalDate.from(value); return datedate.isBefore(valuedate); } isBeforeYear(date: Temporal, value: Temporal): boolean { let datedate = Year.from(date); let valuedate = Year.from(value); return datedate.isBefore(valuedate); } startOfMonth(date: Temporal) { return YearMonth.from(date).atDay(1).atStartOfDay(); } endOfMonth(date: Temporal) { return YearMonth.from(date).atEndOfMonth().atTime(LocalTime.MAX); } addDays(date: Temporal, count: number): Temporal { return date.plus(count, ChronoUnit.DAYS); } startOfDay(date: Temporal) { return LocalDate.from(date).atStartOfDay(); } endOfDay(date: Temporal) { return LocalDate.from(date).atTime(LocalTime.MAX); } format(date: Temporal, formatKey: keyof DateIOFormats): string { let formatter = DateTimeFormatter.ofPattern(this.formats[formatKey]).withLocale( this.locale ); return formatter.format(date); } formatByString(date: Temporal, formatString: string): string { let formatter = DateTimeFormatter.ofPattern(formatString).withLocale(this.locale); return formatter.format(date); } formatNumber(numberToFormat: string): string { return numberToFormat; } getHours(date: Temporal): number { return date.get(ChronoField.HOUR_OF_DAY); } setHours(date: Temporal, count: number): Temporal { return date.with(ChronoField.HOUR_OF_DAY, count); } getMinutes(date: Temporal): number { return date.get(ChronoField.MINUTE_OF_HOUR); } setMinutes(date: Temporal, count: number): Temporal { return date.with(ChronoField.MINUTE_OF_HOUR, count); } getSeconds(date: Temporal): number { return date.get(ChronoField.SECOND_OF_MINUTE); } setSeconds(date: Temporal, count: number): Temporal { return date.with(ChronoField.SECOND_OF_MINUTE, count); } getMonth(date: Temporal): number { return date.get(ChronoField.MONTH_OF_YEAR) - 1; } setMonth(date: Temporal, count: number): Temporal { return date.with(ChronoField.MONTH_OF_YEAR, count + 1); } getPreviousMonth(date: Temporal): Temporal { return date.minus(1, ChronoUnit.MONTHS); // return YearMonth.from(date).minusMonths(1).atDay(1).atStartOfDay(); } getNextMonth(date: Temporal): Temporal { return date.plus(1, ChronoUnit.MONTHS); // return YearMonth.from(date).plusMonths(1).atDay(1).atStartOfDay(); } getMonthArray(date: Temporal): LocalDateTime[] { const months: Array<LocalDateTime> = []; const year: Year = Year.from(date); for (let i = 1; i <= 12; i++) { const localDateTime = year.atMonth(i).atDay(1).atStartOfDay(); months.push(localDateTime); } return months; } getYear(date: Temporal): number { return date.get(ChronoField.YEAR); } setYear(date: Temporal, year: number): Temporal { return date.with(ChronoField.YEAR, year); } mergeDateAndTime(date: Temporal, time: Temporal): Temporal { return LocalDate.from(date).atTime(LocalTime.from(time)); } getWeekdays(): string[] { const today = LocalDate.now(); const startOfWeek = LocalDate.from(this.startOfWeek(today)); const weekdays = []; const formatter = DateTimeFormatter.ofPattern("eee").withLocale(this.locale); for (let i = 0; i < 7; i++) { weekdays.push(startOfWeek.plus(i, ChronoUnit.DAYS).format(formatter)); } return weekdays; } getWeekArray(date: Temporal) { // if (!this.locale) { // throw new Error("Function getWeekArray() requires a locale to be set."); // } let startOfMonth = LocalDate.from(this.startOfMonth(date)); let endOfMonth = LocalDate.from(this.endOfMonth(date)); const start = LocalDate.from(this.startOfWeek(startOfMonth)); const end = LocalDate.from(this.endOfWeek(endOfMonth)); let count = 0; let current = start; const nestedWeeks: LocalDate[][] = []; while (current.isBefore(end) || current.isEqual(end)) { const weekNumber = Math.floor(count / 7); nestedWeeks[weekNumber] = nestedWeeks[weekNumber] || []; nestedWeeks[weekNumber].push(current); current = current.plusDays(1); count += 1; } return nestedWeeks; } getYearRange(start: Temporal, end: Temporal) { const years: Temporal[] = []; let startYear = Year.from(start); let endYear = Year.from(end).plusYears(1); while (startYear.isBefore(endYear)) { years.push(startYear.atDay(1).atStartOfDay()); startYear = startYear.plusYears(1); } return years; } isBefore(date: Temporal, value: Temporal): boolean { if (date instanceof LocalDateTime && value instanceof LocalDateTime) { return date.isBefore(value); } else if (date instanceof LocalDate && value instanceof LocalDate) { return date.isBefore(value); } } getMeridiemText(ampm: "am" | "pm"): string { return ampm === "am" ? "AM" : "PM"; } private naDayOfWeekFix(x: number): number { switch (x) { case 7: return 1; default: return x + 1; } } private localedayOfWeekValue(value: LocalDate): number { switch (this.locale.country()) { case "US": return this.naDayOfWeekFix(value.dayOfWeek().value()); // Sunday (day 7 in js-joda, which implements ISO8601 calendar only) default: return value.dayOfWeek().value(); } } startOfWeek(value: Temporal) { const day = LocalDate.from(value); const dayOfWeek = this.localedayOfWeekValue(day); return day.minus(dayOfWeek - 1, ChronoUnit.DAYS).atStartOfDay(); } endOfWeek(value: Temporal) { const day = LocalDate.from(value); const daysToEnd = 7 - this.localedayOfWeekValue(day); return day.plus(daysToEnd, ChronoUnit.DAYS).atTime(LocalTime.MAX); } addHours(value: Temporal, count: number): Temporal { return value.plus(count, ChronoUnit.HOURS); } addMinutes(value: Temporal, count: number): Temporal { return value.plus(count, ChronoUnit.MINUTES); } addMonths(value: Temporal, count: number): Temporal { return value.plus(count, ChronoUnit.MONTHS); } addSeconds(value: Temporal, count: number): Temporal { return value.plus(count, ChronoUnit.SECONDS); } addWeeks(value: Temporal, count: number): Temporal { return value.plus(count, ChronoUnit.WEEKS); } getCurrentLocaleCode(): string { return this.locale.localeString(); } getDaysInMonth(value: Temporal): number { return YearMonth.from(value).lengthOfMonth(); } getFormatHelperText = (format: string) => { return format.replace(/(aaa|aa|a)/g, "(a|p)m").toLocaleLowerCase(); }; is12HourCycleInCurrentLocale(): boolean { return ampmregex.test(this.formats.fullDateTime); } isWithinRange(value: Temporal, range: [Temporal, Temporal]): boolean { let [start, end] = range; if ( value instanceof LocalDateTime && start instanceof LocalDateTime && end instanceof LocalDateTime ) { return ( (value.isAfter(start) || value.isEqual(start)) && (value.isBefore(end) || value.isEqual(end)) ); } else if ( value instanceof LocalDate && start instanceof LocalDate && end instanceof LocalDate ) { return ( (value.isAfter(start) || value.isEqual(start)) && (value.isBefore(end) || value.isEqual(end)) ); } } parseISO(isString: string): Temporal { return ZonedDateTime.parse(isString).toLocalDateTime(); } toISO(value: Temporal): string { return isoformatter.format(value); } toJsDate(value: CalendarType): Date { return convert(value).toDate(); } }
the_stack
import { createElement } from '@syncfusion/ej2-base'; import { Diagram } from '../../../src/diagram/diagram'; import { ConnectorModel, Node, DataBinding, HierarchicalTree, NodeModel, Rect, TextElement, LayoutAnimation, Container, StackPanel, ImageElement, TreeInfo, TextModel, ConnectorConstraints, PortVisibility, NodeConstraints, PointPort } from '../../../src/diagram/index'; import { MindMap } from '../../../src/diagram/layout/mind-map'; import { SpatialSearch } from '../../../src/diagram/interaction/spatial-search/spatial-search'; import { profile, inMB, getMemoryProfile } from '../../../spec/common.spec'; Diagram.Inject(DataBinding, HierarchicalTree, MindMap); Diagram.Inject(LayoutAnimation); import { Animation } from '../../../src/diagram/objects/interface/IElement' import { DataManager, Query } from '@syncfusion/ej2-data'; /** * MindMapTree  */ let data: object[] = [ { id: 1, Label: 'StackPanel' }, { id: 2, Label: 'Label', parentId: 1 }, { id: 3, Label: 'ListBox', parentId: 1 }, { id: 4, Label: 'StackPanel', parentId: 1 }, { id: 5, Label: 'Border', parentId: 2 }, { id: 6, Label: 'Border', parentId: 3 }, { id: 7, Label: 'Button', parentId: 4 }, { id: 8, Label: 'ContentPresenter', parentId: 5 }, { id: 9, Label: 'Text Block', parentId: 8 }, { id: 10, Label: 'ScrollViewer', parentId: 6 }, { id: 11, Label: 'Grid', parentId: 10 }, { id: 12, Label: 'Rectangle', parentId: 11 }, { id: 13, Label: 'ScrollContentPresenter', parentId: 11 }, { id: 14, Label: 'ScrollBar', parentId: 11 }, { id: 15, Label: 'ScrollBar', parentId: 11 }, { id: 16, Label: 'ItemsPresenter', parentId: 13 }, { id: 17, Label: 'AdornerLayer', parentId: 13 }, { id: 18, Label: 'VirtualizingStackPanel', parentId: 15 }, { id: 19, Label: 'ListBoxItem', parentId: 18 }, { id: 20, Label: 'ListBoxItem', parentId: 18 }, { id: 21, Label: 'Border', parentId: 19 }, { id: 22, Label: 'ContentPresenter', parentId: 19 }, { id: 23, Label: 'TextBlock', parentId: 19 }, { id: 24, Label: 'Border', parentId: 20 }, { id: 25, Label: 'ContentPresenter', parentId: 20 }, { id: 26, Label: 'TextBlock', parentId: 20 }, { id: 27, Label: 'ButtonChrome', parentId: 7 }, { id: 28, Label: 'ContentPresenter', parentId: 27 }, { id: 29, Label: 'TextBlock', parentId: 28 } ]; let datas: object[] = [ { id: 1, Label: 'StackPanel' }, ]; describe('Diagram Control', () => { describe('Tree Layout', () => { let diagram: Diagram; let ele: HTMLElement; beforeAll(() => { ele = createElement('div', { id: 'diagramMindMap1' }); document.body.appendChild(ele); let items = new DataManager(data, new Query().take(7)); diagram = new Diagram({ width: '650px', height: '550px', layout: { type: 'MindMap', }, dataSourceSettings: { id: 'id', parentId: 'parentId', dataSource: items }, getNodeDefaults: (node: Node) => { let obj: NodeModel = {}; obj.shape = { type: 'Text', content: (node.data as { Label: 'string' }).Label }; obj.style = { fill: 'lightgrey', strokeColor: 'none', strokeWidth: 2 }; obj.borderColor = 'black'; obj.backgroundColor = 'lightgrey'; obj.borderWidth = 1; (obj.shape as TextModel).margin = { left: 5, right: 5, top: 5, bottom: 5 }; return obj; }, getConnectorDefaults: (obj: ConnectorModel, diagram: Diagram) => { let connector: ConnectorModel = {}; connector.type = 'Orthogonal'; return connector; }, }); diagram.appendTo('#diagramMindMap1'); }); afterAll(() => { diagram.destroy(); ele.remove(); }); it('With default Branch and without root', (done: Function) => { let bounds: Rect = diagram.spatialSearch.getPageBounds(); expect((bounds.x == -524 || bounds.x == -491 || bounds.x == -340 || bounds.x === -552 || bounds.x === -520 || bounds.x === -524) && (bounds.y == 155 || bounds.y == 160 || bounds.y == 130) && (bounds.width == 1398 || bounds.width == 1090 || bounds.width == 1451 || bounds.width === 1406 || bounds.width == 1399) && (bounds.height == 375 || bounds.height == 490 || bounds.height == 360)).toBe(true); expect((diagram.nodes[5].offsetX == 234.9765625 || diagram.nodes[5].offsetX == 245) && diagram.nodes[5].offsetY == 275).toBe(true); done(); }); it('Checking left layout', (done: Function) => { diagram.dataSourceSettings.root = String(1); diagram.layout.getBranch = (node: NodeModel, nodes: NodeModel[]) => { return 'Left'; } diagram.dataBind(); let bounds: Rect = diagram.spatialSearch.getPageBounds(); console.log(bounds.width); expect((bounds.x == 290 || bounds.x == 300 || bounds.x == 290) && (bounds.y == 108 || bounds.y == 70) && (bounds.width == 884 || bounds.width == 690 || bounds.width === 914 || bounds.width == 690 || bounds.width === 880) && (bounds.height == 412 || bounds.height == 490)).toBe(true); expect((diagram.nodes[5].offsetX == 415.0234375 || diagram.nodes[5].offsetX == 405) && (diagram.nodes[5].offsetY == 275 || diagram.nodes[5].offsetY == 215)).toBe(true); done(); }); it('Checking Right Layout', (done: Function) => { diagram.layout.getBranch = (node: NodeModel, nodes: NodeModel[]) => { return 'Right'; } diagram.spatialSearch = new SpatialSearch(diagram.nameTable); diagram.dataBind(); let bounds: Rect = diagram.spatialSearch.getPageBounds(); expect((bounds.x == -523 || bounds.x == -519 || bounds.x == -340) && (bounds.y == 101 || bounds.y == 108 || bounds.y == 70) && (bounds.width == 853 || bounds.width == 849 || bounds.width == 878 || bounds.width == 882 || bounds.width == 670 ||bounds.width == 690 || bounds.width == 853) && (bounds.height == 429 || bounds.height == 412 || bounds.height == 490)).toBe(true); expect((diagram.nodes[5].offsetX == 234.9765625 || diagram.nodes[5].offsetX == 245) && (diagram.nodes[5].offsetY == 275 || diagram.nodes[5].offsetY == 215)).toBe(true); done(); }); it('Checking with horizontal spacing', (done: Function) => { diagram.layout.getBranch = (node: NodeModel, nodes: NodeModel[]) => { return 'Left'; }; diagram.layout.horizontalSpacing = 20; diagram.spatialSearch = new SpatialSearch(diagram.nameTable); diagram.dataBind(); let bounds: Rect = diagram.spatialSearch.getPageBounds(); expect((bounds.x == 320||bounds.x == 300 || bounds.x == 451 || bounds.x == 536) && (bounds.y == 108 || bounds.y == 70) && (bounds.width == 769 || bounds.width == 773 || bounds.width == 590 || bounds.width == 642 || bounds.width == 554||bounds.width == 610 || bounds.width == 558) && (bounds.height == 412 || bounds.height == 490)).toBe(true); expect(Math.ceil(diagram.nodes[5].offsetX) == 406 || diagram.nodes[5].offsetX == 395 && (diagram.nodes[5].offsetY == 275 || diagram.nodes[5].offsetY == 215)).toBe(true); done(); }); it('Checking with vertical spacing', (done: Function) => { diagram.layout.getBranch = (node: NodeModel, nodes: NodeModel[]) => { return 'Right'; }; diagram.spatialSearch = new SpatialSearch(diagram.nameTable); diagram.layout.verticalSpacing = 20; diagram.dataBind(); let bounds: Rect = diagram.spatialSearch.getPageBounds(); expect((bounds.x == -443 || bounds.x == -439 || bounds.x == -260) && (bounds.y == 138 || bounds.y == 93) && (bounds.width == 769 || bounds.width == 554 || bounds.width == 590 ||bounds.width == 610|| bounds.width == 558) && (bounds.height == 337 || bounds.height == 435)).toBe(true); expect(Math.ceil(diagram.nodes[5].offsetX) == 245 || diagram.nodes[5].offsetX == 255 && (diagram.nodes[5].offsetY == 275 || diagram.nodes[5].offsetY == 222.5)).toBe(true); done(); }); }); describe('default branch and without root ', () => { let diagram: Diagram; let ele: HTMLElement; beforeAll(() => { ele = createElement('div', { id: 'diagram' }); document.body.appendChild(ele); let items = new DataManager(datas, new Query().take(7)); diagram = new Diagram({ width: '650px', height: '550px', layout: { type: 'MindMap', }, dataSourceSettings: { id: 'id', parentId: 'parentId', dataSource: items, root: String(1) }, getNodeDefaults: (node: Node) => { let obj: NodeModel = {}; obj.shape = { type: 'Text', content: (node.data as { Label: 'string' }).Label }; obj.style = { fill: 'lightgrey', strokeColor: 'none', strokeWidth: 2 }; obj.borderColor = 'black'; obj.backgroundColor = 'lightgrey'; obj.borderWidth = 1; (obj.shape as TextModel).margin = { left: 5, right: 5, top: 5, bottom: 5 }; return obj; }, getConnectorDefaults: (obj: ConnectorModel, diagram: Diagram) => { let connector: ConnectorModel = {}; connector.type = 'Orthogonal'; return connector; }, }); diagram.appendTo('#diagram'); }); afterAll(() => { diagram.destroy(); ele.remove(); }); it('With default Branch and without root', (done: Function) => { let bounds: Rect = diagram.spatialSearch.getPageBounds(); expect((bounds.x == 290 || bounds.x == 300) && (bounds.y == 264 || bounds.y == 250) && (bounds.width == 71 || bounds.width == 50) && (bounds.height == 22 || bounds.height == 50)).toBe(true); expect(diagram.nodes[0].offsetX == 325 && diagram.nodes[0].offsetY == 275).toBe(true); done(); }); }); describe('Without datasource and with root ', () => { let diagram: Diagram; let ele: HTMLElement; beforeAll(() => { ele = createElement('div', { id: 'diagram' }); document.body.appendChild(ele); let node: NodeModel = { id: 'node1', width: 70, height: 70, annotations: [{ content: 'node1' }] }; let node1: NodeModel = { id: 'node2', width: 70, height: 70, annotations: [{ content: 'node2' }] }; let node2: NodeModel = { id: 'node3', width: 70, height: 70, annotations: [{ content: 'node3' }] }; let connector: ConnectorModel = { id: 'connectr', sourceID: 'node1', targetID: 'node2' }; let connector1: ConnectorModel = { id: 'connectr1', sourceID: 'node2', targetID: 'node3' }; diagram = new Diagram({ width: 1000, height: 1000, nodes: [node, node1, node2], connectors: [connector, connector1, ], layout: { type: 'MindMap', root: 'node1' }, }); diagram.appendTo('#diagram'); }); afterAll(() => { diagram.destroy(); ele.remove(); }); it('Without datasource with root', (done: Function) => { let bounds: Rect = diagram.spatialSearch.getPageBounds(); expect(bounds.x == 465 && bounds.y == 465 && bounds.width == 270 && bounds.height == 70).toBe(true); expect(diagram.nodes[0].offsetX == 500 && diagram.nodes[0].offsetY == 500).toBe(true); done(); }); }); describe('Without datasource and without root ', () => { let diagram: Diagram; let ele: HTMLElement; beforeAll(() => { ele = createElement('div', { id: 'diagram' }); document.body.appendChild(ele); let node: NodeModel = { id: 'node1', width: 70, height: 70, annotations: [{ content: 'node1' }] }; let node1: NodeModel = { id: 'node2', width: 70, height: 70, annotations: [{ content: 'node2' }] }; let node2: NodeModel = { id: 'node3', width: 70, height: 70, annotations: [{ content: 'node3' }] }; let connector: ConnectorModel = { id: 'connectr', sourceID: 'node1', targetID: 'node2' }; let connector1: ConnectorModel = { id: 'connectr1', sourceID: 'node2', targetID: 'node3' }; diagram = new Diagram({ width: 1000, height: 1000, nodes: [node, node1, node2], connectors: [connector, connector1, ], layout: { type: 'MindMap' }, }); diagram.appendTo('#diagram'); }); afterAll(() => { diagram.destroy(); ele.remove(); }); it('Without datasource without root', (done: Function) => { let bounds: Rect = diagram.spatialSearch.getPageBounds(); expect(bounds.x == 465 && bounds.y == 465 && bounds.width == 270 && bounds.height == 70).toBe(true); expect(diagram.nodes[0].offsetX == 500 && diagram.nodes[0].offsetY == 500).toBe(true); done(); }); }); describe('Without datasource and without root ', () => { let diagram: Diagram; let ele: HTMLElement; beforeAll(() => { ele = createElement('div', { id: 'diagram' }); document.body.appendChild(ele); let node: NodeModel = { id: 'node1', offsetX: 550, offsetY: 750, width: 70, height: 70, annotations: [{ content: 'node1' }] }; diagram = new Diagram({ width: 500, height: 700, nodes: [node], layout: { type: 'MindMap' }, }); diagram.appendTo('#diagram'); }); afterAll(() => { diagram.destroy(); ele.remove(); }); it('Without datasource without root', (done: Function) => { diagram.bringIntoView(diagram.nodes[0].wrapper.bounds); diagram.startTextEdit(diagram.nodes[0]); let editBox = document.getElementById(diagram.element.id + '_editBox'); (editBox as HTMLInputElement).value = "Node"; expect(editBox !== null).toBe(true); expect((editBox as HTMLInputElement).value === "Node").toBe(true); done(); }); it('memory leak', () => { profile.sample(); let average: any = inMB(profile.averageChange) //Check average change in memory samples to not be over 10MB expect(average).toBeLessThan(10); let memory: any = inMB(getMemoryProfile()) //Check the final memory usage against the first usage, there should be little change if everything was properly deallocated expect(memory).toBeLessThan(profile.samples[0] + 0.25); }) }); describe('getBranch Support for the Blazor ', () => { let diagram: Diagram; let ele: HTMLElement; let data: object[] = [ { id: 1, Label: 'StackPanel', Branch: 'Left' }, { id: 2, Label: 'Label', parentId: 1, Branch: 'Left' }, { id: 3, Label: 'ListBox', parentId: 1, Branch: 'Left' }, { id: 4, Label: 'StackPanel', parentId: 1, Branch: 'Left' }, { id: 5, Label: 'Border', parentId: 2, Branch: 'Left' }, { id: 6, Label: 'Border', parentId: 3, Branch: 'Left' }, { id: 7, Label: 'Button', parentId: 4, Branch: 'Left' }, { id: 8, Label: 'ContentPresenter', parentId: 5, Branch: 'Left' }, { id: 9, Label: 'Text Block', parentId: 8, Branch: 'Left' }, { id: 10, Label: 'ScrollViewer', parentId: 6, Branch: 'Left' }, { id: 11, Label: 'Grid', parentId: 10, Branch: 'Left' }, { id: 12, Label: 'Rectangle', parentId: 11, Branch: 'Left' }, { id: 13, Label: 'ScrollContentPresenter', parentId: 11, Branch: 'Left' }, { id: 14, Label: 'ScrollBar', parentId: 11, Branch: 'Left' }, { id: 15, Label: 'ScrollBar', parentId: 11, Branch: 'Left' }, { id: 16, Label: 'ItemsPresenter', parentId: 13, Branch: 'Left' }, { id: 17, Label: 'AdornerLayer', parentId: 13, Branch: 'Left' }, { id: 18, Label: 'VirtualizingStackPanel', parentId: 15, Branch: 'Left' }, { id: 19, Label: 'ListBoxItem', parentId: 18, Branch: 'Left' }, { id: 20, Label: 'ListBoxItem', parentId: 18, Branch: 'Left' }, { id: 21, Label: 'Border', parentId: 19, Branch: 'Left' }, { id: 22, Label: 'ContentPresenter', parentId: 19, Branch: 'Left' }, { id: 23, Label: 'TextBlock', parentId: 19, Branch: 'Left' }, { id: 24, Label: 'Border', parentId: 20, Branch: 'Left' }, { id: 25, Label: 'ContentPresenter', parentId: 20, Branch: 'Left' }, { id: 26, Label: 'TextBlock', parentId: 20, Branch: 'Left' }, { id: 27, Label: 'ButtonChrome', parentId: 7, Branch: 'Left' }, { id: 28, Label: 'ContentPresenter', parentId: 27, Branch: 'Left' }, { id: 29, Label: 'TextBlock', parentId: 28, Branch: 'Left' } ]; let items: DataManager = new DataManager(data as JSON[], new Query().take(7)); beforeAll(() => { ele = createElement('div', { id: 'diagram' }); document.body.appendChild(ele); diagram = new Diagram({ width: '100%', height: '550px', layout: { type: 'MindMap' }, dataSourceSettings: { id: 'id', parentId: 'parentId', dataSource: items, root: String(1), dataMapSettings: [{ property: 'Branch', field: 'Branch' }] }, getNodeDefaults: (obj: Node) => { obj.shape = { type: 'Text', content: (obj.data as { Label: 'string' }).Label }; obj.style = { fill: 'lightgrey', strokeColor: 'none', strokeWidth: 2 }; obj.borderColor = 'black'; obj.backgroundColor = 'lightgrey'; obj.borderWidth = 1; (obj.shape as TextModel).margin = { left: 5, right: 5, top: 5, bottom: 5 }; return obj; }, getConnectorDefaults: (connector: ConnectorModel, diagram: Diagram) => { connector.type = 'Orthogonal'; return connector; } }); diagram.appendTo('#diagram'); }); afterAll(() => { diagram.destroy(); ele.remove(); }); it('Without datasource without root', (done: Function) => { expect(diagram.nodes[0].branch === 'Left').toBe(true); done(); }); }); describe('mindmap expand collapse icon not working issue fix ', () => { let diagram: Diagram; let ele: HTMLElement; let data: object[] = [ { id: 1, Label: 'Barbie Silks', fill: 'red', branch: 'Root' }, { id: 2, Label: 'Categories', parentId: 1, branch: 'Right', fill: 'red' }, { id: 3, Label: 'Products', parentId: 1, branch: 'Right', fill: 'red' }, { id: 4, Label: 'Orders', parentId: 1, branch: 'Left', fill: 'red' }, { id: 5, Label: 'Transactions', parentId: 1, branch: 'Left', fill: 'red' }, { id: 6, Label: 'Users', parentId: 1, branch: 'Left', fill: 'red' }, { id: 7, Label: 'Create Category', parentId: 2, branch: 'subRight' }, { id: 8, Label: 'Update Category', parentId: 2, branch: 'subRight' }, { id: 9, Label: 'Delete Category', parentId: 2, branch: 'subRight' }, { id: 10, Label: 'Create Product', parentId: 3, branch: 'subRight' }, { id: 11, Label: 'Update Product', parentId: 3, branch: 'subRight' }, { id: 12, Label: 'Delete Product', parentId: 3, branch: 'subRight' }, { id: 13, Label: 'Create Order', parentId: 4, branch: 'subLeft' }, { id: 14, Label: 'Delete Order', parentId: 4, branch: 'subLeft' }, { id: 15, Label: 'Initiate Transaction', parentId: 5, branch: 'subLeft' }, { id: 16, Label: 'Update Transaction', parentId: 5, branch: 'subLeft' }, { id: 17, Label: 'Cancel Transaction', parentId: 5, branch: 'subLeft' }, { id: 18, Label: 'Add User', parentId: 6, branch: 'subLeft' }, { id: 19, Label: 'Update User', parentId: 6, branch: 'subLeft' }, { id: 20, Label: 'Delete User', parentId: 6, branch: 'subLeft' }, ]; let items: DataManager = new DataManager(data as JSON[], new Query().take(7)); function getPort() { let port = [ { id: "port1", offset: { x: 0, y: 0.5 }, visibility: PortVisibility.Hidden, style: { fill: "black" } }, { id: "port2", offset: { x: 1, y: 0.5 }, visibility: PortVisibility.Hidden, style: { fill: "black" } } ]; return port; } beforeAll(() => { ele = createElement('div', { id: 'diagram' }); document.body.appendChild(ele); diagram = new Diagram({ width: '100%', height: '550px', layout: { type: "MindMap", getBranch: (node: any) => { return node.data.branch; }, horizontalSpacing: 50 }, dataSourceSettings: { id: "id", parentId: "parentId", dataSource: items, root: String(1) }, getNodeDefaults: (obj: any) => { obj.constraints = NodeConstraints.Default & ~NodeConstraints.Drag; if ( obj.data.branch === "Left" || obj.data.branch === "Right" || obj.data.branch === "Root" ) { obj.shape = { type: "Basic", shape: "Ellipse" }; obj.borderColor = "black"; /* tslint:disable:no-string-literal */ obj.style = { fill: obj.data.branch === "Root" ? "#E74C3C" : "#F39C12", strokeColor: "none", strokeWidth: 2 }; obj.annotations = [ { content: obj.data.Label, margin: { left: 10, right: 10, top: 10, bottom: 10 }, style: { color: "white" } } ]; let port = getPort(); for (let i = 0; i < port.length; i++) { obj.ports.push(new PointPort(obj, "ports", port[i], true)); } } else { let color; /* tslint:disable:no-string-literal */ if ( obj.data.branch === "Right" || obj.data.branch === "subRight" ) { color = "#8E44AD"; } else { color = "#3498DB"; } obj.shape = { type: "Basic", shape: "Rectangle" }; obj.style = { fill: color, strokeWidth: 0 }; obj.minWidth = 100; obj.height = 4; let port = getPort(); for (let i = 0; i < port.length; i++) { obj.ports.push(new PointPort(obj, "ports", port[i], true)); } obj.annotations = [ { content: obj.data.Label, offset: { x: 0.5, y: 0 }, verticalAlignment: "Bottom" } ]; obj.shape.margin = { left: 0, right: 0, top: 0, bottom: 0 }; } //define expand icon obj.expandIcon = { height: 10, width: 10, shape: "Minus", fill: "lightgray", offset: { x: 0.5, y: 1 } }; //define collapse icon obj.collapseIcon = { height: 10, width: 10, shape: "Plus", fill: "lightgray", offset: { x: 0.5, y: 1 } }; return obj; }, getConnectorDefaults: (connector: ConnectorModel, diagram: Diagram) => { connector.type = "Bezier"; connector.targetDecorator = { shape: "None" }; let sourceNode: any = diagram.getObject(connector.sourceID); let targetNode: any = diagram.getObject(connector.targetID); if ( targetNode.data.branch === "Right" || targetNode.data.branch === "subRight" ) { connector.sourcePortID = sourceNode.ports[0].id; connector.targetPortID = targetNode.ports[1].id; connector.style = { strokeWidth: 5, strokeColor: "#8E44AD" }; } else if ( targetNode.data.branch === "Left" || targetNode.data.branch === "subLeft" ) { connector.sourcePortID = sourceNode.ports[1].id; connector.targetPortID = targetNode.ports[0].id; connector.style = { strokeWidth: 5, strokeColor: "#3498DB" }; } connector.constraints &= ~ConnectorConstraints.Select; return connector; } }); diagram.appendTo('#diagram'); }); afterAll(() => { diagram.destroy(); ele.remove(); }); it('mindmap expand collapse icon not working issue fix ', (done: Function) => { expect(diagram.nodes[3].visible && diagram.nodes[4].visible).toBe(true); var node = diagram.nodes[1]; node.isExpanded = false diagram.dataBind(); expect(!diagram.nodes[3].visible && !diagram.nodes[4].visible).toBe(true); done(); }); }); });
the_stack
import AMQPChannel from './amqp-channel.js' import AMQPError from './amqp-error.js' import AMQPMessage from './amqp-message.js' import AMQPView from './amqp-view.js' const VERSION = '1.3.0' /** * Base class for AMQPClients. * Implements everything except how to connect, send data and close the socket */ export default abstract class AMQPBaseClient { vhost: string username: string password: string name?: string platform?: string channels: AMQPChannel[] protected connectPromise?: [(conn: AMQPBaseClient) => void, (err: Error) => void] protected closePromise?: [(value?: void) => void, (err: Error) => void] closed = false blocked?: string channelMax = 0 frameMax = 4096 heartbeat = 0 /** * @param name - name of the connection, set in client properties * @param platform - used in client properties */ constructor(vhost: string, username: string, password: string, name?: string, platform?: string) { this.vhost = vhost this.username = username this.password = "" Object.defineProperty(this, 'password', { value: password, enumerable: false // hide it from console.log etc. }) if (name) this.name = name // connection name if (platform) this.platform = platform this.channels = [new AMQPChannel(this, 0)] this.closed = false } /** * Open a channel * @param [id] - An existing or non existing specific channel */ channel(id?: number): Promise<AMQPChannel> { if (this.closed) return this.rejectClosed() if (id && id > 0) { const channel = this.channels[id] if (channel) return Promise.resolve(channel) } // Store channels in an array, set position to null when channel is closed // Look for first null value or add one the end if (!id) id = this.channels.findIndex((ch) => ch === undefined) if (id === -1) id = this.channels.length // FIXME: check max channels (or let the server deal with that?) const channel = new AMQPChannel(this, id) this.channels[id] = channel let j = 0 const channelOpen = new AMQPView(new ArrayBuffer(13)) channelOpen.setUint8(j, 1); j += 1 // type: method channelOpen.setUint16(j, id); j += 2 // channel id channelOpen.setUint32(j, 5); j += 4 // frameSize channelOpen.setUint16(j, 20); j += 2 // class: channel channelOpen.setUint16(j, 10); j += 2 // method: open channelOpen.setUint8(j, 0); j += 1 // reserved1 channelOpen.setUint8(j, 206); j += 1 // frame end byte return new Promise((resolve, reject) => { this.send(new Uint8Array(channelOpen.buffer, 0, 13)) .then(() => channel.promises.push([resolve, reject])) .catch(reject) }) } /** * Gracefully close the AMQP connection * @param [reason] might be logged by the server */ close(reason = "", code = 200) { if (this.closed) return this.rejectClosed() this.closed = true let j = 0 const frame = new AMQPView(new ArrayBuffer(512)) frame.setUint8(j, 1); j += 1 // type: method frame.setUint16(j, 0); j += 2 // channel: 0 frame.setUint32(j, 0); j += 4 // frameSize frame.setUint16(j, 10); j += 2 // class: connection frame.setUint16(j, 50); j += 2 // method: close frame.setUint16(j, code); j += 2 // reply code j += frame.setShortString(j, reason) // reply reason frame.setUint16(j, 0); j += 2 // failing-class-id frame.setUint16(j, 0); j += 2 // failing-method-id frame.setUint8(j, 206); j += 1 // frame end byte frame.setUint32(3, j - 8) // update frameSize return new Promise((resolve, reject) => { this.send(new Uint8Array(frame.buffer, 0, j)) .then(() => this.closePromise = [resolve, reject]) .catch(reject) }) } /** * Try establish a connection */ abstract connect(): Promise<AMQPBaseClient> /** * @ignore * @param bytes to send * @return fulfilled when the data is enqueued */ abstract send(bytes: Uint8Array): Promise<void> protected abstract closeSocket(): void private rejectClosed() { return Promise.reject(new AMQPError("Connection closed", this)) } private rejectConnect(err: Error) { if (this.connectPromise) { const [, reject] = this.connectPromise delete this.connectPromise reject(err) } this.closed = true this.closeSocket() } /** * Parse and act on frames in an AMQPView * @ignore */ protected parseFrames(view: AMQPView) { // Can possibly be multiple AMQP frames in a single WS frame for (let i = 0; i < view.byteLength;) { let j = 0 // position in outgoing frame const type = view.getUint8(i); i += 1 const channelId = view.getUint16(i); i += 2 const frameSize = view.getUint32(i); i += 4 try { const frameEnd = view.getUint8(i + frameSize) if (frameEnd !== 206) throw(new AMQPError(`Invalid frame end ${frameEnd}, expected 206`, this)) } catch (e) { throw(new AMQPError(`Frame end out of range, frameSize=${frameSize}, pos=${i}, byteLength=${view.byteLength}`, this)) } const channel = this.channels[channelId] if (!channel) { console.warn("AMQP channel", channelId, "not open") i += frameSize + 1 continue } switch (type) { case 1: { // method const classId = view.getUint16(i); i += 2 const methodId = view.getUint16(i); i += 2 switch (classId) { case 10: { // connection switch (methodId) { case 10: { // start // ignore start frame, just reply startok i += frameSize - 4 const startOk = new AMQPView(new ArrayBuffer(4096)) startOk.setUint8(j, 1); j += 1 // type: method startOk.setUint16(j, 0); j += 2 // channel: 0 startOk.setUint32(j, 0); j += 4 // frameSize: to be updated startOk.setUint16(j, 10); j += 2 // class: connection startOk.setUint16(j, 11); j += 2 // method: startok const clientProps = { connection_name: this.name || undefined, product: "amqp-client.js", information: "https://github.com/cloudamqp/amqp-client.js", version: VERSION, platform: this.platform, capabilities: { "authentication_failure_close": true, "basic.nack": true, "connection.blocked": true, "consumer_cancel_notify": true, "exchange_exchange_bindings": true, "per_consumer_qos": true, "publisher_confirms": true, } } j += startOk.setTable(j, clientProps) // client properties j += startOk.setShortString(j, "PLAIN") // mechanism const response = `\u0000${this.username}\u0000${this.password}` j += startOk.setLongString(j, response) // response j += startOk.setShortString(j, "") // locale startOk.setUint8(j, 206); j += 1 // frame end byte startOk.setUint32(3, j - 8) // update frameSize this.send(new Uint8Array(startOk.buffer, 0, j)).catch(this.rejectConnect) break } case 30: { // tune const channelMax = view.getUint16(i); i += 2 const frameMax = view.getUint32(i); i += 4 const heartbeat = view.getUint16(i); i += 2 this.channelMax = channelMax this.frameMax = Math.min(4096, frameMax) this.heartbeat = Math.min(0, heartbeat) const tuneOk = new AMQPView(new ArrayBuffer(20)) tuneOk.setUint8(j, 1); j += 1 // type: method tuneOk.setUint16(j, 0); j += 2 // channel: 0 tuneOk.setUint32(j, 12); j += 4 // frameSize: 12 tuneOk.setUint16(j, 10); j += 2 // class: connection tuneOk.setUint16(j, 31); j += 2 // method: tuneok tuneOk.setUint16(j, this.channelMax); j += 2 // channel max tuneOk.setUint32(j, this.frameMax); j += 4 // frame max tuneOk.setUint16(j, this.heartbeat); j += 2 // heartbeat tuneOk.setUint8(j, 206); j += 1 // frame end byte this.send(new Uint8Array(tuneOk.buffer, 0, j)).catch(this.rejectConnect) j = 0 const open = new AMQPView(new ArrayBuffer(512)) open.setUint8(j, 1); j += 1 // type: method open.setUint16(j, 0); j += 2 // channel: 0 open.setUint32(j, 0); j += 4 // frameSize: to be updated open.setUint16(j, 10); j += 2 // class: connection open.setUint16(j, 40); j += 2 // method: open j += open.setShortString(j, this.vhost) // vhost open.setUint8(j, 0); j += 1 // reserved1 open.setUint8(j, 0); j += 1 // reserved2 open.setUint8(j, 206); j += 1 // frame end byte open.setUint32(3, j - 8) // update frameSize this.send(new Uint8Array(open.buffer, 0, j)).catch(this.rejectConnect) break } case 41: { // openok i += 1 // reserved1 const promise = this.connectPromise if (promise) { const [resolve, ] = promise delete this.connectPromise resolve(this) } break } case 50: { // close const code = view.getUint16(i); i += 2 const [text, strLen] = view.getShortString(i); i += strLen const classId = view.getUint16(i); i += 2 const methodId = view.getUint16(i); i += 2 console.debug("connection closed by server", code, text, classId, methodId) const msg = `connection closed: ${text} (${code})` const err = new AMQPError(msg, this) this.channels.forEach((ch) => ch.setClosed(err)) this.channels = [new AMQPChannel(this, 0)] const closeOk = new AMQPView(new ArrayBuffer(12)) closeOk.setUint8(j, 1); j += 1 // type: method closeOk.setUint16(j, 0); j += 2 // channel: 0 closeOk.setUint32(j, 4); j += 4 // frameSize closeOk.setUint16(j, 10); j += 2 // class: connection closeOk.setUint16(j, 51); j += 2 // method: closeok closeOk.setUint8(j, 206); j += 1 // frame end byte this.send(new Uint8Array(closeOk.buffer, 0, j)) .catch(err => console.warn("Error while sending Connection#CloseOk", err)) this.rejectConnect(err) break } case 51: { // closeOk this.channels.forEach((ch) => ch.setClosed()) this.channels = [new AMQPChannel(this, 0)] const promise = this.closePromise if (promise) { const [resolve, ] = promise delete this.closePromise resolve() this.closeSocket() } break } case 60: { // blocked const [reason, len] = view.getShortString(i); i += len console.warn("AMQP connection blocked:", reason) this.blocked = reason break } case 61: { // unblocked console.info("AMQP connection unblocked") delete this.blocked break } default: i += frameSize - 4 console.error("unsupported class/method id", classId, methodId) } break } case 20: { // channel switch (methodId) { case 11: { // openok i += 4 // reserved1 (long string) channel.resolvePromise(channel) break } case 21: { // flowOk const active = view.getUint8(i) !== 0; i += 1 channel.resolvePromise(active) break } case 40: { // close const code = view.getUint16(i); i += 2 const [text, strLen] = view.getShortString(i); i += strLen const classId = view.getUint16(i); i += 2 const methodId = view.getUint16(i); i += 2 console.debug("channel", channelId, "closed", code, text, classId, methodId) const msg = `channel ${channelId} closed: ${text} (${code})` const err = new AMQPError(msg, this) channel.setClosed(err) delete this.channels[channelId] const closeOk = new AMQPView(new ArrayBuffer(12)) closeOk.setUint8(j, 1); j += 1 // type: method closeOk.setUint16(j, channelId); j += 2 // channel closeOk.setUint32(j, 4); j += 4 // frameSize closeOk.setUint16(j, 20); j += 2 // class: channel closeOk.setUint16(j, 41); j += 2 // method: closeok closeOk.setUint8(j, 206); j += 1 // frame end byte this.send(new Uint8Array(closeOk.buffer, 0, j)) .catch(err => console.error("Error while sending Channel#closeOk", err)) break } case 41: { // closeOk channel.setClosed() delete this.channels[channelId] channel.resolvePromise() break } default: i += frameSize - 4 // skip rest of frame console.error("unsupported class/method id", classId, methodId) } break } case 40: { // exchange switch (methodId) { case 11: // declareOk case 21: // deleteOk case 31: // bindOk case 51: { // unbindOk channel.resolvePromise() break } default: i += frameSize - 4 // skip rest of frame console.error("unsupported class/method id", classId, methodId) } break } case 50: { // queue switch (methodId) { case 11: { // declareOk const [name, strLen] = view.getShortString(i); i += strLen const messageCount = view.getUint32(i); i += 4 const consumerCount = view.getUint32(i); i += 4 channel.resolvePromise({ name, messageCount, consumerCount }) break } case 21: { // bindOk channel.resolvePromise() break } case 31: { // purgeOk const messageCount = view.getUint32(i); i += 4 channel.resolvePromise({ messageCount }) break } case 41: { // deleteOk const messageCount = view.getUint32(i); i += 4 channel.resolvePromise({ messageCount }) break } case 51: { // unbindOk channel.resolvePromise() break } default: i += frameSize - 4 console.error("unsupported class/method id", classId, methodId) } break } case 60: { // basic switch (methodId) { case 11: { // qosOk channel.resolvePromise() break } case 21: { // consumeOk const [consumerTag, len] = view.getShortString(i); i += len channel.resolvePromise(consumerTag) break } case 31: { // cancelOk const [consumerTag, len] = view.getShortString(i); i += len channel.resolvePromise(consumerTag) break } case 50: { // return const code = view.getUint16(i); i += 2 const [text, len] = view.getShortString(i); i += len const [exchange, exchangeLen] = view.getShortString(i); i += exchangeLen const [routingKey, routingKeyLen] = view.getShortString(i); i += routingKeyLen const message = new AMQPMessage(channel) message.exchange = exchange message.routingKey = routingKey message.replyCode = code message.replyText = text channel.returned = message break } case 60: { // deliver const [consumerTag, consumerTagLen] = view.getShortString(i); i += consumerTagLen const deliveryTag = view.getUint64(i); i += 8 const redelivered = view.getUint8(i) === 1; i += 1 const [exchange, exchangeLen] = view.getShortString(i); i += exchangeLen const [routingKey, routingKeyLen] = view.getShortString(i); i += routingKeyLen const message = new AMQPMessage(channel) message.consumerTag = consumerTag message.deliveryTag = deliveryTag message.exchange = exchange message.routingKey = routingKey message.redelivered = redelivered channel.delivery = message break } case 71: { // getOk const deliveryTag = view.getUint64(i); i += 8 const redelivered = view.getUint8(i) === 1; i += 1 const [exchange, exchangeLen]= view.getShortString(i); i += exchangeLen const [routingKey, routingKeyLen]= view.getShortString(i); i += routingKeyLen const messageCount = view.getUint32(i); i += 4 const message = new AMQPMessage(channel) message.deliveryTag = deliveryTag message.redelivered = redelivered message.exchange = exchange message.routingKey = routingKey message.messageCount = messageCount channel.getMessage = message break } case 72: { // getEmpty const [ , len]= view.getShortString(i); i += len // reserved1 channel.resolvePromise(null) break } case 80: { // confirm ack const deliveryTag = view.getUint64(i); i += 8 const multiple = view.getUint8(i) === 1; i += 1 channel.publishConfirmed(deliveryTag, multiple, false) break } case 111: { // recoverOk channel.resolvePromise() break } case 120: { // confirm nack const deliveryTag = view.getUint64(i); i += 8 const multiple = view.getUint8(i) === 1; i += 1 channel.publishConfirmed(deliveryTag, multiple, true) break } default: i += frameSize - 4 console.error("unsupported class/method id", classId, methodId) } break } case 85: { // confirm switch (methodId) { case 11: { // selectOk channel.confirmId = 1 channel.resolvePromise() break } default: i += frameSize - 4 console.error("unsupported class/method id", classId, methodId) } break } case 90: { // tx / transaction switch (methodId) { case 11: // selectOk case 21: // commitOk case 31: { // rollbackOk channel.resolvePromise() break } default: i += frameSize - 4 console.error("unsupported class/method id", classId, methodId) } break } default: i += frameSize - 2 console.error("unsupported class id", classId) } break } case 2: { // header i += 4 // ignoring class id and weight const bodySize = view.getUint64(i); i += 8 const [properties, propLen] = view.getProperties(i); i += propLen const message = channel.delivery || channel.getMessage || channel.returned if (message) { message.bodySize = bodySize message.properties = properties message.body = new Uint8Array(bodySize) if (bodySize === 0) channel.onMessageReady(message) } else { console.warn("Header frame but no message") } break } case 3: { // body const message = channel.delivery || channel.getMessage || channel.returned if (message && message.body) { const bodyPart = new Uint8Array(view.buffer, view.byteOffset + i, frameSize) message.body.set(bodyPart, message.bodyPos) message.bodyPos += frameSize i += frameSize if (message.bodyPos === message.bodySize) channel.onMessageReady(message) } else { console.warn("Body frame but no message") } break } case 8: { // heartbeat const heartbeat = new Uint8Array([1, 0, 0, 0, 0, 0, 0, 206]) this.send(heartbeat).catch(err => console.warn("Error while sending heartbeat", err)) break } default: console.error("invalid frame type:", type) i += frameSize } i += 1 // frame end } } }
the_stack
import * as path from 'path'; import { BitId } from '../bit-id'; import { DEFAULT_DIST_DIRNAME, DEFAULT_INDEX_NAME } from '../constants'; import BitMap from '../consumer/bit-map'; import ComponentMap from '../consumer/bit-map/component-map'; import { throwForNonLegacy } from '../consumer/component/component-schema'; import Component from '../consumer/component/consumer-component'; import { RelativePath } from '../consumer/component/dependencies/dependency'; import Consumer from '../consumer/consumer'; import logger from '../logger/logger'; import { getExt, getWithoutExt, searchFilesIgnoreExt } from '../utils'; import componentIdToPackageName from '../utils/bit/component-id-to-package-name'; import { pathNormalizeToLinux, PathOsBased, PathOsBasedAbsolute, PathOsBasedRelative } from '../utils/path'; import { EXTENSIONS_NOT_SUPPORT_DIRS, EXTENSIONS_TO_REPLACE_TO_JS_IN_PACKAGES, EXTENSIONS_TO_STRIP_FROM_PACKAGES, getLinkToPackageContent, } from './link-content'; export type LinkFileType = { linkPath: string; linkContent: string; isEs6?: boolean; postInstallLink?: boolean; // postInstallLink is needed when custom module resolution was used postInstallSymlink?: boolean; // postInstallSymlink is needed when custom module resolution was used with unsupported file extension symlinkTo?: PathOsBased | null | undefined; // symlink (instead of link) is needed for unsupported files, such as binary files customResolveMapping?: { [key: string]: string } | null | undefined; // needed when custom module resolution was used }; /** * a dependency component may have multiple files required by the main component. * this class generates the link content of one file of a dependency. * @see RelativePath docs for more info */ export default class DependencyFileLinkGenerator { consumer: Consumer | null | undefined; bitMap: BitMap; component: Component; componentMap: ComponentMap; relativePath: RelativePath; dependencyId: BitId; dependencyComponent: Component; createNpmLinkFiles: boolean; targetDir: string | null | undefined; dependencyComponentMap: ComponentMap | null | undefined; // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! linkFiles: LinkFileType[]; // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! relativePathInDependency: PathOsBased; // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! hasDist: boolean; // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! shouldDistsBeInsideTheComponent: boolean; constructor({ consumer, bitMap, component, relativePath, dependencyComponent, createNpmLinkFiles, targetDir, }: { consumer: Consumer | null | undefined; bitMap: BitMap; component: Component; relativePath: RelativePath; dependencyComponent: Component; createNpmLinkFiles: boolean; targetDir?: string; }) { throwForNonLegacy(component.isLegacy, DependencyFileLinkGenerator.name); this.consumer = consumer; this.bitMap = bitMap; this.component = component; // $FlowFixMe componentMap should be set here // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! this.componentMap = this.component.componentMap; this.relativePath = relativePath; this.dependencyComponent = dependencyComponent; this.dependencyId = dependencyComponent.id; this.createNpmLinkFiles = createNpmLinkFiles; this.targetDir = targetDir; } generate(): LinkFileType[] { this.linkFiles = []; if (this.component.dependenciesSavedAsComponents) { this.dependencyComponent.componentMap = this.bitMap.getComponent(this.dependencyId); this.dependencyComponentMap = this.dependencyComponent.componentMap; } this.relativePathInDependency = path.normalize(this.relativePath.destinationRelativePath); this.hasDist = this.component.dists.writeDistsFiles && !this.component.dists.isEmpty(); this.shouldDistsBeInsideTheComponent = this.consumer ? this.consumer.shouldDistsBeInsideTheComponent() : true; if (this.relativePath.isCustomResolveUsed) { return this.generateForCustomResolve(); } const linkFile = this.prepareLinkFile({ linkPath: this.getLinkPath(), relativePathInDependency: this.relativePathInDependency, depRootDir: this._getDepRootDir(), }); this.linkFiles.push(linkFile); if (this.hasDist) { this.generateForDist(); } return this.linkFiles; } generateForCustomResolve(): LinkFileType[] { const distRoot = this._getDistRoot(); const relativeDistPathInDependency = this._getRelativeDistPathInDependency(); const dependencyDistExt = getExt(relativeDistPathInDependency); const relativeDistExtInDependency = EXTENSIONS_TO_REPLACE_TO_JS_IN_PACKAGES.includes(dependencyDistExt) ? 'js' : dependencyDistExt; const depRootDir = this._getDepRootDir(); const depRootDirDist = this._getDepRootDirDist(); const isCustomResolvedWithDistInside = Boolean(this.shouldDistsBeInsideTheComponent && this.hasDist); const relativePathInDependency = `${getWithoutExt(this.relativePathInDependency)}.${relativeDistExtInDependency}`; const linkFile = this.prepareLinkFile({ linkPath: this.getLinkPathForCustomResolve(relativeDistExtInDependency), relativePathInDependency, depRootDir: isCustomResolvedWithDistInside ? depRootDirDist : depRootDir, }); if (this.createNpmLinkFiles && linkFile.linkContent) { linkFile.postInstallLink = true; } this.linkFiles.push(linkFile); if (this.hasDist && !this.shouldDistsBeInsideTheComponent) { // when isCustomResolvedUsed, the link is generated inside node_module directory, so for // dist inside the component, only one link is needed at the parentRootDir. for dist // outside the component dir, another link is needed for the dist/parentRootDir. const importSourcePath = this._getImportSourcePathForCustomResolve(relativeDistExtInDependency); const linkFileInNodeModules = this.prepareLinkFile({ linkPath: path.join(distRoot, importSourcePath), relativePathInDependency: relativeDistPathInDependency, depRootDir: depRootDirDist, }); this.linkFiles.push(linkFileInNodeModules); } if (getExt(this.relativePathInDependency) === 'ts') { // this is needed for when building Angular components inside a capsule, so we don't care // about the case when dist is outside the components const linkFileTs = this.prepareLinkFile({ linkPath: this.getLinkPathForCustomResolve(relativeDistExtInDependency).replace('.js', '.d.ts'), relativePathInDependency: relativePathInDependency.replace('.js', '.ts'), depRootDir: isCustomResolvedWithDistInside ? depRootDirDist : depRootDir, }); if (this.createNpmLinkFiles && linkFile.linkContent) { linkFileTs.postInstallLink = true; } this.linkFiles.push(linkFileTs); } return this.linkFiles; } generateForDist() { const distRoot = this._getDistRoot(); const relativeDistPathInDependency = this._getRelativeDistPathInDependency(); const relativeDistExtInDependency = getExt(relativeDistPathInDependency); const sourceRelativePathWithCompiledExt = `${getWithoutExt( this.relativePath.sourceRelativePath )}.${relativeDistExtInDependency}`; const linkFileInDist = this.prepareLinkFile({ linkPath: path.join(distRoot, sourceRelativePathWithCompiledExt), // Generate a link file inside dist folder of the dependent component relativePathInDependency: relativeDistPathInDependency, depRootDir: this._getDepRootDirDist(), }); this.linkFiles.push(linkFileInDist); } prepareLinkFile({ linkPath, relativePathInDependency, depRootDir, }: { linkPath: PathOsBased; relativePathInDependency: PathOsBased; depRootDir: PathOsBasedAbsolute | null | undefined; }): LinkFileType { const actualFilePath = depRootDir ? path.join(depRootDir, relativePathInDependency) : relativePathInDependency; const relativeFilePath = path.relative(path.dirname(linkPath), actualFilePath); const importSpecifiers = this.relativePath.importSpecifiers; const linkContent = this.getLinkContent(relativeFilePath); const customResolveMapping = this._getCustomResolveMapping(); logger.debug(`prepareLinkFile, on ${linkPath}`); const linkPathExt = getExt(linkPath); const isEs6 = Boolean(importSpecifiers && linkPathExt === 'js'); const symlinkTo = linkContent ? undefined : this._getSymlinkDest(actualFilePath); const postInstallSymlink = this.createNpmLinkFiles && !linkContent; return { linkPath, linkContent, isEs6, symlinkTo, customResolveMapping, postInstallSymlink }; } _getSymlinkDest(filePath: PathOsBased): string { if (this.createNpmLinkFiles) { return this._getPackagePathToInternalFile(); } if (!this.component.dependenciesSavedAsComponents) { return path.join(this.getTargetDir(), 'node_modules', this._getPackagePathToInternalFile()); } // if dependencies are saved as components, the above logic will create a symlink to a symlink return filePath; } getLinkContent(relativeFilePath: PathOsBased): string { return getLinkToPackageContent(relativeFilePath, this._getPackagePath(), this.relativePath.importSpecifiers); } _getPackagePath(): string { const ext = getExt(this.relativePath.destinationRelativePath); if ( this.relativePath.destinationRelativePath === pathNormalizeToLinux(this.dependencyComponent.mainFile) && !EXTENSIONS_NOT_SUPPORT_DIRS.includes(ext) ) { return this._getPackageName(); } const distFileIsNotFound = !this.dependencyComponent.dists.isEmpty() && !this.dependencyComponent.dists.hasFileParallelToSrcFile(this.relativePath.destinationRelativePath); if (distFileIsNotFound) { return this._getPackagePathByDistWithComponentPrefix(); } // the link is to an internal file, not to the main file return this._getPackagePathToInternalFile(); } /** * temporary workaround for Angular compiler when all dists have the prefix of the component id */ _getPackagePathByDistWithComponentPrefix() { const distFileWithDependencyPrefix = path.join( this.dependencyId.toStringWithoutVersion(), this.relativePath.destinationRelativePath ); if ( !this.dependencyComponent.dists.isEmpty() && this.dependencyComponent.dists.hasFileParallelToSrcFile(distFileWithDependencyPrefix) ) { const distFile = searchFilesIgnoreExt( this.dependencyComponent.dists.get(), distFileWithDependencyPrefix, 'relative' ); // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! return this._getPackagePathToInternalFile(distFile); } return this._getPackageName(); } _getPackageName() { return componentIdToPackageName(this.dependencyComponent); } // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! _getPackagePathToInternalFile(filePath?: string = this.relativePath.destinationRelativePath) { const packageName = this._getPackageName(); const internalFileInsidePackage = this._getInternalFileInsidePackage(filePath); const ext = getExt(internalFileInsidePackage); const internalFileWithoutExt = EXTENSIONS_TO_STRIP_FROM_PACKAGES.includes(ext) ? getWithoutExt(internalFileInsidePackage) : internalFileInsidePackage; return `${packageName}/${internalFileWithoutExt}`; } _getInternalFileInsidePackage(filePath: string) { const dependencySavedLocallyAndDistIsOutside = this.dependencyComponentMap && !this.shouldDistsBeInsideTheComponent; const distPrefix = this.dependencyComponent.dists.isEmpty() || this.relativePath.isCustomResolveUsed || dependencySavedLocallyAndDistIsOutside ? '' : `${DEFAULT_DIST_DIRNAME}/`; return distPrefix + filePath; } _getCustomResolveMapping() { if (!this.relativePath.isCustomResolveUsed) return null; // $FlowFixMe importSource is set for custom resolved // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! return { [this.relativePath.importSource]: this._getPackagePath() }; } getTargetDir(): PathOsBasedRelative { const determineTargetDir = () => { if (this.targetDir) return this.targetDir; const writtenPath = this.component.writtenPath; // $FlowFixMe when running from bit build, the writtenPath is not available but it should have rootDir as it's related to the dists links if (!writtenPath) return this.componentMap.rootDir; if (path.isAbsolute(writtenPath)) { throw new Error('getTargetDir: component.writtenPath should be relative'); } return writtenPath; }; const targetDir = determineTargetDir(); if (!targetDir || !(typeof targetDir === 'string')) { throw new Error('targetDir must be of type string'); } return targetDir; } getLinkPath(): PathOsBased { const sourceRelativePath = this.relativePath.sourceRelativePath; const parentDir = this.getTargetDir(); return path.join(parentDir, sourceRelativePath); } getLinkPathForCustomResolve(relativeDistExtInDependency: string): PathOsBased { const parentDir = this.getTargetDir(); const importSourcePath = this._getImportSourcePathForCustomResolve(relativeDistExtInDependency); // if createNpmLinkFiles, the path will be part of the postinstall script, so it shouldn't be absolute return this.createNpmLinkFiles ? importSourcePath : path.join(parentDir, importSourcePath); } _getDistRoot(): PathOsBasedRelative { return this.component.dists.getDistDir(this.consumer, this.componentMap.getRootDir()); } _getRelativeDistPathInDependency() { const relativeDistPathInDependency = searchFilesIgnoreExt( this.dependencyComponent.dists.get(), this.relativePathInDependency ); return relativeDistPathInDependency // $FlowFixMe relative is defined ? relativeDistPathInDependency.relative : this.relativePathInDependency; } _getImportSourcePathForCustomResolve(relativeDistExtInDependency: string): PathOsBased { // $FlowFixMe relativePath.importSource is set when isCustomResolveUsed // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! const importSource: string = this.relativePath.importSource; const importSourceFileExt = relativeDistExtInDependency || path.extname(this.relativePath.sourceRelativePath); // e.g. for require('utils/is-string'), the link should be at node_modules/utils/is-string/index.js const importSourceFile = path.extname(importSource) ? importSource : path.join(importSource, `${DEFAULT_INDEX_NAME}.${importSourceFileExt}`); return path.join('node_modules', importSourceFile); } _getDepRootDir(): PathOsBasedRelative | null | undefined { if (!this.dependencyComponentMap) return undefined; return this.dependencyComponentMap.getRootDir(); } _getDepRootDirDist(): PathOsBasedRelative | null | undefined { const rootDir = this._getDepRootDir(); return rootDir ? this.dependencyComponent.dists.getDistDir(this.consumer, rootDir) : undefined; } }
the_stack
/// <reference path="Interfaces.d.ts"/> /// <reference path="Common.ts"/> module EdgeDiagnosticsAdapter { "use strict"; enum BreakResumeAction { Abort, Continue, StepInto, StepOver, StepOut, Ignore, // Continue, but with state (fast refresh) StepDocument // Step to document boundary for JMC } enum ConnectionResult { Succeeded = 0, Failed = 1, FailedAlreadyAttached = 2 } enum BreakReason { Step, // User stepped Breakpoint, // Hit explicit breakpoint DebuggerBlock, // Debugger is breaking another thread HostInitiated, // Host (e.g. mshtml) initiated a breakpoint - not currently used LanguageInitiated, // "debugger;" DebuggerHalt, // Pause button Error, // Exception Jit, // JIT dialog MutationBreakpoint // Hit mutation breakpoint } enum MutationType { None = 0, Update = 1, Delete = 1 << 1, All = Update | Delete } enum CauseBreakAction { BreakOnAny = 0, BreakOnAnyNewWorkerStarting = 1, BreakIntoSpecificWorker = 2, UnsetBreakOnAnyNewWorkerStarting = 3 } interface ISourceLocation { docId: number; start: number; length: number; } interface IStackFrame { callFrameId: number; functionName: string; isInTryBlock: boolean; isInternal: boolean; location: ISourceLocation; } interface IGetSourceTextResult { loadFailed: boolean; text: string; } interface IBreakpointInfo { location: ISourceLocation; eventTypes: string[]; breakpointId: string; isBound: boolean; isEnabled?: boolean; condition?: string; isTracepoint?: boolean; failed?: boolean; isPseudoBreakpoint?: boolean; } interface IResolvedBreakpointInfo { breakpointId: number; newDocId: number; start: number; length: number; isBound: boolean; } interface IBreakEventInfo { firstFrameId: number; errorId: number; breakReason: BreakReason; description: string; isFirstChanceException: boolean; isUserUnhandled: boolean; breakpoints?: IBreakpointInfo[]; systemThreadId?: number; breakEventType: string; mutationBreakpointId: number; mutationType: MutationType; } interface IDocument { docId: number; parentDocId: number; url: string; mimeType: string; length: number; isDynamicCode: boolean; headers: string[]; sourceMapUrlFromHeader: string; longDocumentId: number; } interface IPropertyInfo { propertyId: string; name: string; type: string; fullName: string; value: string; expandable: boolean; readOnly: boolean; fake: boolean; invalid: boolean; returnValue: boolean; } interface IPropertyInfoContainer { propInfos: IPropertyInfo[]; hasAdditionalChildren: boolean; } interface ISetMutationBreakpointResult { success: boolean; breakpointId: any; objectName: string; } interface IDebuggerDispatch { addEventListener(type: string, listener: Function): void; addEventListener(type: "onAddDocuments", listener: (documents: IDocument[]) => void): void; addEventListener(type: "onRemoveDocuments", listener: (docIds: number[]) => void): void; addEventListener(type: "onUpdateDocuments", listener: (documents: IDocument[]) => void): void; addEventListener(type: "onResolveBreakpoints", listener: (breakpoints: IResolvedBreakpointInfo[]) => void): void; addEventListener(type: "onBreak", listener: (breakEventInfo: IBreakEventInfo) => void): void; removeEventListener(type: string, listener: Function): void; removeEventListener(type: "onAddDocuments", listener: (documents: IDocument[]) => void): void; removeEventListener(type: "onRemoveDocuments", listener: (docIds: number[]) => void): void; removeEventListener(type: "onUpdateDocuments", listener: (documents: IDocument[]) => void): void; removeEventListener(type: "onResolveBreakpoints", listener: (breakpoints: IResolvedBreakpointInfo[]) => void): void; removeEventListener(type: "onBreak", listener: (breakEventInfo: IBreakEventInfo) => void): void; enable(): boolean; disable(): boolean; isEnabled(): boolean; connect(enable: boolean): ConnectionResult; disconnect(): boolean; shutdown(): boolean; isConnected(): boolean; causeBreak(causeBreakAction: CauseBreakAction, workerId: number): boolean; resume(breakResumeAction: BreakResumeAction): boolean; addCodeBreakpoint(docId: number, start: number, condition: string, isTracepoint: boolean): IBreakpointInfo; addEventBreakpoint(eventTypes: string[], isEnabled: boolean, condition: string, isTracepoint: boolean): IBreakpointInfo; addPendingBreakpoint(url: string, start: number, condition: string, isEnabled: boolean, isTracepoint: boolean): number; removeBreakpoint(breakpointId: number): boolean; updateBreakpoint(breakpointId: number, condition: string, isTracepoint: boolean): boolean; setBreakpointEnabledState(breakpointId: number, enable: boolean): boolean; getBreakpointIdFromSourceLocation(docId: number, start: number): number; getThreadDescription(): string; getThreads(): string[]; getFrames(framesNeeded: number): IStackFrame[]; getSourceText(docId: number): IGetSourceTextResult; getLocals(frameId: number): number; /* propertyNum */ eval(frameId: number, evalString: string): IPropertyInfo; getChildProperties(propertyId: number, start: number, length: number): IPropertyInfoContainer; setPropertyValueAsString(propertyId: number, value: string): boolean; canSetNextStatement(docId: number, position: number): boolean; setNextStatement(docId: number, position: number): boolean; setBreakOnFirstChanceExceptions(value: boolean): boolean; canSetMutationBreakpoint(propertyId: number, setOnObject: boolean, mutationType: MutationType): boolean; setMutationBreakpoint(propertyId: number, setOnObject: boolean, mutationType: MutationType): ISetMutationBreakpointResult; deleteMutationBreakpoint(breakpointId: number): boolean; setMutationBreakpointEnabledState(breakpointId: number, enabled: boolean): boolean; } interface IWebKitPropResult { wasThrown: boolean; result: IWebKitRemoteObject; } declare var host: IProxyDebuggerDispatch; declare var debug: IDebuggerDispatch; class DebuggerProxy { private _debugger: IDebuggerDispatch; private _isAtBreakpoint: boolean; private _isAwaitingDebuggerEnableCall: boolean; private _isEnabled: boolean; private _documentMap: Map<string, number>; private _lineEndingsMap: Map<number, number[]>; private _intellisenseExpression: string; private _intellisenseFrame: any; private _documents: IDocument[] = []; constructor() { this._debugger = debug; this._isAtBreakpoint = false; this._documentMap = new Map<string, number>(); this._lineEndingsMap = new Map<number, number[]>(); this._intellisenseFrame = null; this._intellisenseExpression = ""; // Hook up notifications this._debugger.addEventListener("onAddDocuments", (documents: IDocument[]) => this.onAddDocuments(documents)); this._debugger.addEventListener("onRemoveDocuments", (docIds: number[]) => this.onRemoveDocuments(docIds)); this._debugger.addEventListener("onUpdateDocuments", (documents: IDocument[]) => this.onUpdateDocuments(documents)); this._debugger.addEventListener("onResolveBreakpoints", (breakpoints: IResolvedBreakpointInfo[]) => this.onResolveBreakpoints(breakpoints)); this._debugger.addEventListener("onBreak", (breakEventInfo: IBreakEventInfo) => this.onBreak(breakEventInfo)); host.addEventListener("onmessage", (data: string) => this.onMessage(data)); } private onMessage(data: string): void { // Try to parse the requested command var request: IWebKitRequest = null; try { request = <IWebKitRequest>JSON.parse(data); } catch (ex) { this.postResponse(0, { error: { description: "Invalid request" } }); return; } // Process a successful request if (request) { var methodParts = request.method.split("."); if (!this._isAtBreakpoint && methodParts[0] !== "Debugger" && methodParts[0] !== "Custom") { return host.postMessageToEngine("browser", this._isAtBreakpoint, JSON.stringify(request)); } switch (methodParts[0]) { case "Runtime": this.processRuntime(methodParts[1], request); break; case "Debugger": this.processDebugger(methodParts[1], request); break; case "Custom": this.processCustom(methodParts[1], request); break; default: return host.postMessageToEngine("browser", this._isAtBreakpoint, JSON.stringify(request)); } } } private getLineEndings(docId: number, text?: string): number[] { if (!this._lineEndingsMap.has(docId)) { var textResult = text || this._debugger.getSourceText(docId).text; if (textResult) { var total = []; var lines = textResult.split(/\r\n|\n|\r/); for (var i = 0; i < lines.length; i++) { total.push(lines[i].length + 2); } this._lineEndingsMap.set(docId, total); } else { this._lineEndingsMap.set(docId, [0]); } } return this._lineEndingsMap.get(docId); } private getLineColumnFromOffset(docId: number, offset: number): any { var lineEndings = this.getLineEndings(docId); var columnNumber = 0; var lineNumber = 0; var charCount = 0; for (var i = 0; i < lineEndings.length; i++) { charCount += lineEndings[i]; if (offset < charCount) { lineNumber = i; columnNumber = charCount - offset; break; } } return { lineNumber: lineNumber, columnNumber: columnNumber, scriptId: "" + docId }; } private getRemoteObjectFromProp(prop: IPropertyInfo): IWebKitPropResult { var type = prop.type.toLowerCase(); var subType = null; var value: any; var index = type.indexOf(","); if (index !== -1) { type = "object"; subType = type.substring(index + 2).toLowerCase(); } if (subType === "function") { type = "function"; subType = null; } if (type === "null") { type = "object"; subType = "null"; } if (type === "object" && prop.value === "undefined") { type = "undefined"; subType = null; } var wasThrown = false; if (type === "error") { type = "object"; wasThrown = true; } if (type === "number") { value = parseFloat(prop.value); } if (typeof prop.value === "string" && prop.value.length > 2 && prop.value.indexOf("\"") === 0 && prop.value.lastIndexOf("\"") === prop.value.length - 1) { prop.value = prop.value.substring(1, prop.value.length - 1); } var resultDesc = { objectId: (prop.expandable ? "" + prop.propertyId : null), type: type, value: (typeof value !== "undefined" ? value : prop.value), description: prop.value.toString() }; if (type === "object") { (<any>resultDesc).className = "Object"; (<any>resultDesc).subType = subType; } return { wasThrown: wasThrown, result: resultDesc }; } private postResponse(id: number, value: IWebKitResult): void { // Send the response back over the websocket var response: IWebKitResponse = Common.createResponse(id, value); host.postMessage(JSON.stringify(response)); } private postNotification(method: string, params: any): void { var notification: IWebKitNotification = { method: method, params: params }; host.postMessage(JSON.stringify(notification)); } private callFunctionOn(request: IWebKitRequest): IWebKitResult { if (this._intellisenseFrame && this._intellisenseExpression) { var prop = this._debugger.eval(this._intellisenseFrame, this._intellisenseExpression); this._intellisenseExpression = ""; this._intellisenseFrame = null; if (!prop) { return { error: "Could not find object" }; } var childProps = this._debugger.getChildProperties(<any>prop.propertyId, 0, 0); var value = {}; for (var i = 0; i < childProps.propInfos.length; i++) { var childProp: IPropertyInfo = childProps.propInfos[i]; if (!childProp.fake) { value[childProp.name] = true; } } return { result: { result: { type: "object", value: value }, wasThrown: false } }; } } private processRuntime(method: string, request: IWebKitRequest): void { var processedResult: IWebKitResult; switch (method) { // This function is handleded both here and in runtime.ts this implementation handles messages when at a breakpoint the runtime.ts one when not. case "enable": processedResult = { result: {} }; break; case "callFunctionOn": processedResult = this.callFunctionOn(request); break; case "evaluate": var prop = debug.eval(request.params.contextId, request.params.expression); if (prop) { processedResult = { result: this.getRemoteObjectFromProp(prop) }; } break; case "getProperties": var id = parseInt(request.params.objectId); var props = this._debugger.getChildProperties(id, 0, 0); var viewAccessorOnly = request.params.accessorPropertiesOnly; var propDescriptions = []; for (var i = 0; i < props.propInfos.length; i++) { var prop = props.propInfos[i]; if (!prop.fake) { if (typeof viewAccessorOnly !== "undefined") { if (viewAccessorOnly && !prop.readOnly) { continue; } else if (!viewAccessorOnly && prop.readOnly) { continue; } } var remote = this.getRemoteObjectFromProp(prop); propDescriptions.push({ name: prop.name, value: remote.result, wasThrown: remote.wasThrown }); } } processedResult = { result: { result: propDescriptions } }; break; default: processedResult = {}; break; } this.postResponse(request.id, processedResult); } private processCustom(method: string, request: IWebKitRequest): void { switch (method) { case "toolsDisconnected": this.debuggerResume(BreakResumeAction.Continue); return host.postMessageToEngine("browser", this._isAtBreakpoint, "{\"method\":\"Custom.toolsDisconnected\"}"); //this._debugger.disconnect(); //this._isEnabled = false; //break; case "testResetState": this.debuggerResume(BreakResumeAction.Continue); return host.postMessageToEngine("browser", this._isAtBreakpoint, "{\"method\":\"Custom.testResetState\"}"); //break; } } private processDebugger(method: string, request: IWebKitRequest): void { var processedResult: IWebKitResult; switch (method) { case "canSetScriptSource": processedResult = { result: { result: false } }; break; case "continueToLocation": break; case "disable": this.debuggerResume(BreakResumeAction.Continue); break; case "enable": this.debuggerEnable(request.id); return; case "evaluateOnCallFrame": // Intelisense from the chrome dev tools calls this than runtime.callFunctionOn. // We need to return information on the object when runtime.callFunctionOn is called, so save state we will need now if (request.params.objectGroup === "completion") { this._intellisenseExpression = request.params.expression; this._intellisenseFrame = request.params.callFrameId; } var frameId = parseInt(request.params.callFrameId); var prop = this._debugger.eval(frameId, request.params.expression); if (prop) { processedResult = { result: this.getRemoteObjectFromProp(prop) }; } break; case "getScriptSource": var docId: number = parseInt(request.params.scriptId); var textResult = this._debugger.getSourceText(docId); if (!textResult.loadFailed) { this.getLineEndings(docId, textResult.text); processedResult = { result: { scriptSource: " " + textResult.text } }; } break; case "pause": this._debugger.causeBreak(CauseBreakAction.BreakOnAny, 0); break; case "removeBreakpoint": var bpId = parseInt(request.params.breakpointId); this._debugger.removeBreakpoint(bpId); break; case "resume": this.debuggerResume(BreakResumeAction.Continue); break; case "searchInContent": break; case "setBreakpoint": break; case "setBreakpointByUrl": if (this._documentMap.has(request.params.url)) { try { var docId: number = this._documentMap.get(request.params.url); var lineEndings = this.getLineEndings(docId); var charCount = 0; for (var i = 0; i < request.params.lineNumber; i++) { charCount += lineEndings[i]; } charCount += request.params.columnNumber; var info = this._debugger.addCodeBreakpoint(docId, charCount, request.params.condition, false); var location = this.getLineColumnFromOffset(docId, info.location.start); processedResult = { result: { breakpointId: "" + info.breakpointId, locations: [location] } }; } catch (ex) { this.postResponse(request.id, { error: { description: "Invalid request" } }); return; } } else { processedResult = { error: { description: "Not implemented" } }; } break; case "setBreakpointsActive": break; case "setPauseOnExceptions": break; case "setScriptSource": host.postMessageToEngine("browser", this._isAtBreakpoint, JSON.stringify(request)); break; case "stepInto": this.debuggerResume(BreakResumeAction.StepInto); break; case "stepOut": this.debuggerResume(BreakResumeAction.StepOut); break; case "stepOver": this.debuggerResume(BreakResumeAction.StepOver); break; default: processedResult = {}; break; } if (!processedResult) { processedResult = {}; } this.postResponse(request.id, processedResult); } private debuggerEnable(id: number): void { if (!this._isEnabled && !this._isAwaitingDebuggerEnableCall) { var onDebuggerEnabled = (succeeded: boolean) => { this._debugger.removeEventListener("debuggingenabled", onDebuggerEnabled); this._isAwaitingDebuggerEnableCall = false; if (succeeded) { // Now that we have enabled debugging, try to connect to the target var connectionResult = this._debugger.connect(/*enabled=*/ true); if (connectionResult === ConnectionResult.Succeeded) { this._isEnabled = true; } } this.postResponse(id, { result: {} }); }; this._debugger.addEventListener("debuggingenabled", onDebuggerEnabled); // This call is asynchronous as it needs to go across threads this._isAwaitingDebuggerEnableCall = true; this._debugger.enable(); } else { // Already connected, so return success this.postResponse(id, { result: {} }); // Fire scriptParsed events for documents already loaded this.fireScriptParsedFor(this._documents); } } private debuggerResume(action: BreakResumeAction): void { this._debugger.resume(action); this._isAtBreakpoint = false; } private onAddDocuments(documents: IDocument[]): void { this._documents = this._documents.concat(documents); // Fire scriptParsed for new documents this.fireScriptParsedFor(documents); } private onRemoveDocuments(docIds: number[]): void { } private onUpdateDocuments(documents: IDocument[]): void { } private fireScriptParsedFor(documents: IDocument[]): void { for (var i = 0; i < documents.length; i++) { var document: IDocument = documents[i]; this._documentMap.set(document.url, document.docId); // document.sourceMapUrlFromHeader is an empty string if no map was found var sourceMapUrl = document.sourceMapUrlFromHeader; if (!sourceMapUrl || sourceMapUrl === "") { sourceMapUrl = this.findSourceAttribute("sourceMappingURL", this._debugger.getSourceText(document.docId).text); } var docUrl = document.url; var sourceUrlComment = this.findSourceAttribute("sourceURL", this._debugger.getSourceText(document.docId).text); if (sourceUrlComment && sourceUrlComment.length > 0) { docUrl = sourceUrlComment; } this.postNotification("Debugger.scriptParsed", { scriptId: document.docId.toString(), url: docUrl, startLine: 0, startColumn: 0, endLine: document.length, endColumn: document.length, isContentScript: false, sourceMapURL: sourceMapUrl }); } } private onResolveBreakpoints(breakpoints: IResolvedBreakpointInfo[]): void { } private onBreak(breakEventInfo: IBreakEventInfo): boolean { this._isAtBreakpoint = true; var callFrames = []; var frames = this._debugger.getFrames(0); for (var i = 0; i < frames.length; i++) { var scopes = []; var localId = this._debugger.getLocals(frames[i].callFrameId); if (localId) { scopes.push({ object: { className: "Object", description: "Object", objectId: "" + localId, type: "object" }, type: "local" }); var locals = this._debugger.getChildProperties(localId, 0, 0); for (var j = 0; j < locals.propInfos.length; j++) { var prop = locals.propInfos[j]; if (prop.fake) { scopes.push({ object: { className: "Object", description: "Object", objectId: "" + prop.propertyId, type: "object" }, type: "closure" }); } } } callFrames.push({ callFrameId: "" + frames[i].callFrameId, functionName: frames[i].functionName, location: this.getLineColumnFromOffset(frames[i].location.docId, frames[i].location.start), scopeChain: scopes, this: null }); } var reason: string = ""; switch (breakEventInfo.breakReason) { case BreakReason.Breakpoint: reason = "breakpoint"; break; case BreakReason.Step: reason = "step"; break; case BreakReason.Error: reason = "exception"; break; default: reason = "other"; break; } var notification: IWebKitDebuggerPaused = { callFrames: callFrames, reason: reason, data: null } if (breakEventInfo.breakReason == BreakReason.Breakpoint) { var breakpointIds: string[] = []; breakEventInfo.breakpoints.forEach(function (breakpoint) { breakpointIds.push(breakpoint.breakpointId); }); notification.hitBreakpoints = breakpointIds; } this.postNotification("Debugger.paused", notification); return true; } /** * Searches the specified code text for an attribute comment. Supported forms are line or * block comments followed by # (or @, though this is deprecated): * //# attribute=..., /*# attribute=... * /, //@ attribute=..., and /*@ attribute=... * / * @param attribute Name of the attribute to find * @param codeContent Source code to search for attribute comment * @return The attribute's value, or null if not exactly one is found */ private findSourceAttribute(attribute: string, codeContent: string): string { if (codeContent) { var prefixes = ["//#", "/*#", "//@", "/*@"]; var findString: string; var index = -1; var endIndex = -1; // Use pound-sign definitions first, but fall back to at-sign // The last instance of the attribute comment takes precedence for (var i = 0; index < 0 && i < prefixes.length; i++) { findString = "\n" + prefixes[i] + " " + attribute + "="; index = codeContent.lastIndexOf(findString); } if (index >= 0) { if (index >= 0) { if (findString.charAt(2) === "*") { endIndex = codeContent.indexOf("*/", index + findString.length); } else { endIndex = codeContent.indexOf("\n", index + findString.length); } if (endIndex < 0) { endIndex = codeContent.length; } return codeContent.substring(index + findString.length, endIndex).trim(); } } return null; } } } export class App { private _proxy: DebuggerProxy; public main(): void { this._proxy = new DebuggerProxy(); } } var app = new App(); app.main(); }
the_stack