text stringlengths 2.5k 6.39M | kind stringclasses 3
values |
|---|---|
import { Observable } from "data/observable";
import { ObservableArray } from "data/observable-array";
import { VirtualArray } from "data/virtual-array";
/**
* Regular expression for trimming a string
* at the beginning and the end.
*/
export declare const REGEX_TRIM: RegExp;
/**
* Describes a grouping.
*/
export interface IGrouping<K, T> extends IEnumerable<T> {
/**
* Gets the key.
*/
key: K;
}
/**
* Describes a sequence.
*/
export interface IEnumerable<T> {
/**
* Applies an accumulator function over the sequence.
*
* @param {Function} accumulator The accumulator.
* @param any [defaultValue] The value to return if sequence is empty.
*
* @return any The final accumulator value or the default value.
*/
aggregate(accumulator: any, defaultValue?: any): any;
/**
* Checks if all elements of the sequence match a condition.
*
* @param {Function} predicate The condition.
*
* @return {Boolean} All items match condition or not. If sequence is empty (true) is returned.
*/
all(predicate: any): boolean;
/**
* Checks if at least one element of the sequence matches a condition.
*
* @param {Function} [predicate] The condition.
*
* @return {Boolean} At least one element was found that matches the condition.
* If condition is not defined, the method checks if sequence contains at least one element.
*/
any(predicate?: any): boolean;
/**
* Computes the average of that sequence.
*
* @param any [defaultValue] The (default) value to return if sequence is empty.
*
* @return any The average of the sequence or the default value.
*/
average(defaultValue?: any): any;
/**
* Casts all items to a specific type.
*
* @param {String} type The target type.
*
* @return any The new sequence with the casted items.
*/
cast(type: string): IEnumerable<any>;
/**
* Concats the items of that sequence with the items of another one.
*
* @param any second The other sequence.
*
* @throws Value for other sequence is invalid.
*
* @return {IEnumerable} The new sequence.
*/
concat(second: any): IEnumerable<T>;
/**
* Checks if that sequence contains an item.
*
* @param any item The item to search for.
* @param {Function} [equalityComparer] The custom equality comparer to use.
*
* @return {Boolean} Contains item or not.
*/
contains(item: T, equalityComparer?: any): boolean;
/**
* Returns the number of elements.
*
* @param {Function} [predicate] The custom condition to use.
*
* @return {Number} The number of (matching) elements.
*/
count(predicate?: any): number;
/**
* Gets the current element.
*/
current: T;
/**
* Returns a default sequence if that sequence is empty.
*
* @param ...any [defaultItem] One or more items for the default sequence.
*
* @return {IEnumerable} A default sequence or that sequence if it is not empty.
*/
defaultIfEmpty(...defaultItems: T[]): IEnumerable<T>;
/**
* Removes the duplicates from that sequence.
*
* @param {Function} [equalityComparer] The custom equality comparer to use.
*
* @throws No valid equality comparer.
*
* @return {IEnumerable} The new sequence.
*/
distinct(equalityComparer?: any): IEnumerable<T>;
/**
* Iterates over the elements of that sequence.
*
* @param {Function} action The callback that is executed for an item.
*
* @return any The result of the last execution.
*/
each(action: any): any;
/**
* Return an element of the sequence at a specific index.
*
* @param {Number} index The zero based index.
*
* @throws Element was not found.
*
* @return any The element.
*/
elementAt(index: number): T;
/**
* Tries to return an element of the sequence at a specific index.
*
* @param {Number} index The zero based index.
* @param any [defaultValue] The (default) value to return if no matching element was found.
*
* @return any The element or the default value.
*/
elementAtOrDefault(index: number, defaultValue?: any): any;
/**
* Returns the items of that sequence except a list of specific ones.
*
* @param any second The sequence with the items to remove.
* @param any [equalityComparer] The custom equality comparer to use.
*
* @throws The second sequence and/or the equality comparer is invalid.
*
* @return {IEnumerable} The new sequence.
*/
except(second: any, equalityComparer?: any): IEnumerable<T>;
/**
* Returns the first element of the sequence.
*
* @param {Function} [predicate] The custom condition to use.
*
* @throws Sequence contains no (matching) element.
*
* @return any The first (matching) element.
*/
first(predciate?: any): T;
/**
* Tries to return the first element of the sequence.
*
* @param {Function} [predicateOrDefaultValue] The custom condition to use.
* If only one argument is defined and that value is NO function it will be handled as default value.
* @param any [defaultValue] The (default) value to return if no matching element was found.
*
* @return any The first (matching) element or the default value.
*/
firstOrDefault(predicateOrDefaultValue?: any, defaultValue?: any): any;
/**
* Groups the elements of the sequence.
*
* @param any keySelector The group key selector.
* @param any [keyEqualityComparer] The custom equality comparer for the keys to use.
*
* @throw At least one argument is invalid.
*
* @return {IEnumerable} The new sequence.
*/
groupBy<K>(keySelector: any, keyEqualityComparer?: any): IEnumerable<IGrouping<K, T>>;
/**
* Correlates the elements of that sequence and another based on matching keys and groups them.
*
* @param any inner The other sequence.
* @param any outerKeySelector The key selector for the items of that sequence.
* @param any innerKeySelector The key selector for the items of the other sequence.
* @param any resultSelector The function that provides the result value for two matching elements.
* @param any [keyEqualityComparer] The custom equality comparer for the keys to use.
*
* @throw At least one argument is invalid.
*
* @return {IEnumerable} The new sequence.
*/
groupJoin<U>(inner: any, outerKeySelector: any, innerKeySelector: any, resultSelector: any, keyEqualityComparer?: any): IEnumerable<U>;
/**
* Returns the intersection between this and a second sequence.
*
* @param any second The second sequence.
* @param any [equalityComparer] The custom equality comparer to use.
*
* @throws The second sequence and/or the equality comparer is invalid.
*
* @return {IEnumerable} The new sequence.
*/
intersect(second: any, equalityComparer?: any): IEnumerable<T>;
/**
* Gets the item key.
*/
itemKey: any;
/**
* Gets if the current state of that sequence is valid or not.
*/
isValid: boolean;
/**
* Correlates the elements of that sequence and another based on matching keys.
*
* @param any inner The other sequence.
* @param any outerKeySelector The key selector for the items of that sequence.
* @param any innerKeySelector The key selector for the items of the other sequence.
* @param any resultSelector The function that provides the result value for two matching elements.
* @param any [keyEqualityComparer] The custom equality comparer for the keys to use.
*
* @throw At least one argument is invalid.
*
* @return {IEnumerable} The new sequence.
*/
join<U>(inner: any, outerKeySelector: any, innerKeySelector: any, resultSelector: any, keyEqualityComparer?: any): any;
/**
* Returns the last element of the sequence.
*
* @param {Function} [predicate] The custom condition to use.
*
* @throws Sequence contains no (matching) element.
*
* @return any The last (matching) element.
*/
last(predicate?: any): any;
/**
* Tries to return the last element of the sequence.
*
* @param {Function} [predicateOrDefaultValue] The custom condition to use.
* If only one argument is defined and that value is NO function it will be handled as default value.
* @param any [defaultValue] The (default) value to return if no matching element was found.
*
* @return any The last (matching) element or the default value.
*/
lastOrDefault(predicateOrDefaultValue?: any, defaultValue?: any): any;
/**
* Tries to return the maximum value of the sequence.
*
* @param any [defaultValue] The (default) value to return if sequence is empty.
*
* @return any The maximum or the default value.
*/
max(defaultValue?: any): any;
/**
* Tries to return the minimum value of the sequence.
*
* @param any [defaultValue] The (default) value to return if sequence is empty.
*
* @return any The minimum or the default value.
*/
min(defaultValue?: any): any;
/**
* Tries to move to the next item.
*
* @return {Boolean} Operation was successful or not.
*/
moveNext(): boolean;
/**
* Returns elements of a specific type.
*
* @param {String} type The type.
*
* @return {IEnumerable} The new sequence.
*/
ofType(type: string): IEnumerable<any>;
/**
* Sorts the elements of that sequence in ascending order by using the values itself as keys.
*
* @param any [comparer] The custom key comparer to use.
*
* @throws The comparer is invalid.
*
* @return {IOrderedEnumerable} The new sequence.
*/
order(comparer?: any): IOrderedEnumerable<T>;
/**
* Sorts the elements of that sequence in ascending order.
*
* @param any selector The key selector.
* @param any [comparer] The custom key comparer to use.
*
* @throws At least one argument is invalid.
*
* @return {IOrderedEnumerable} The new sequence.
*/
orderBy(selector: any, comparer?: any): IOrderedEnumerable<T>;
/**
* Sorts the elements of that sequence in descending order.
*
* @param any selector The key selector.
* @param any [comparer] The custom key comparer to use.
*
* @throws At least one argument is invalid.
*
* @return {IOrderedEnumerable} The new sequence.
*/
orderByDescending(selector: any, comparer?: any): IOrderedEnumerable<T>;
/**
* Sorts the elements of that sequence in descending order by using the values as keys.
*
* @param any [comparer] The custom key comparer to use.
*
* @throws The comparer is invalid.
*
* @return {IOrderedEnumerable} The new sequence.
*/
orderDescending(comparer?: any): IOrderedEnumerable<T>;
/**
* Pushes the items of that sequence to an array.
*
* @param {any} arr The target array.
*
* @chainable
*/
pushToArray(arr: T[] | ObservableArray<T>): IEnumerable<T>;
/**
* Resets the sequence.
*
* @throws Reset is not possible.
*/
reset(): any;
/**
* Reverses the order of the elements.
*
* @method reverse
*
* @return {IOrderedEnumerable} The new sequence.
*/
reverse(): IEnumerable<T>;
/**
* Projects the elements of that sequence to new values.
*
* @param {Function} selector The selector.
*
* @throws Selector is no valid value for use as function.
*
* @return {IEnumerable} The new sequence.
*/
select<U>(selector: any): IEnumerable<U>;
/**
* Projects the elements of that sequence to new sequences that converted to one flatten sequence.
*
* @param {Function} selector The selector.
*
* @throws Selector is no valid value for use as function.
*
* @return {IEnumerable} The new sequence.
*/
selectMany<U>(selector: any): IEnumerable<U>;
/**
* Checks if that sequence has the same elements as another one.
*
* @param any other The other sequence.
* @param any [equalityComparer] The custom equality comparer to use.
*
* @throws Other sequence and/or equality comparer are invalid values.
*
* @return {IEnumerable} Both sequences are the same or not
*/
sequenceEqual(other: any, equalityComparer?: any): boolean;
/**
* Returns the one and only element of the sequence.
*
* @param {Function} [predicate] The custom condition to use.
*
* @throws Sequence contains more than one matching element or no element.
*
* @return T The only (matching) element or the default value.
*/
single(predicate?: any): T;
/**
* Tries to return the one and only element of the sequence.
*
* @param {Function} [predicateOrDefaultValue] The custom condition to use.
* If only one argument is defined and that value is NO function it will be handled as default value.
* @param any [defaultValue] The (default) value to return if no matching element was found.
*
* @throws Sequence contains more than one matching element.
*
* @return any The only (matching) element or the default value.
*/
singleOrDefault(predicateOrDefaultValue?: any, defaultValue?: any): any;
/**
* Skips a number of elements.
*
* @param {Number} cnt The number of elements to skip.
*
* @return {IEnumerable} The new sequence.
*/
skip(cnt: number): IEnumerable<T>;
/**
* Takes all elements but the last one.
*
* @return {IEnumerable} The new sequence.
*/
skipLast(): IEnumerable<T>;
/**
* Skips elements of that sequence while a condition matches.
*
* @method skipWhile
*
* @param {Function} predicate The condition to use.
*
* @throws Predicate is no valid value.
*
* @return {IEnumerable} The new sequence.
*/
skipWhile(predicate: any): IEnumerable<T>;
/**
* Calculates the sum of the elements.
*
* @param any defaultValue The value to return if sequence is empty.
*
* @return any The sum or the default value.
*/
sum(defaultValue?: any): any;
/**
* Takes a number of elements.
*
* @param {Number} cnt The number of elements to take.
*
* @return {IEnumerable} The new sequence.
*/
take(cnt: number): IEnumerable<T>;
/**
* Takes elements while a condition matches.
*
* @param {Function} predicate The condition to use.
*
* @throws Predicate is no valid value.
*
* @return {IEnumerable} The new sequence.
*/
takeWhile(predicate: any): IEnumerable<T>;
/**
* Returns the elements of that sequence as array.
*
* @return {Array} The sequence as new array.
*/
toArray(): T[];
/**
* Creates a lookup object from the sequence.
*
* @param any keySelector The group key selector.
* @param any [keyEqualityComparer] The custom equality comparer for the keys to use.
*
* @throw At least one argument is invalid.
*
* @return {Object} The lookup array.
*/
toLookup(keySelector: any, keyEqualityComparer?: any): any;
/**
* Creates a new object from the items of that sequence.
*
* @param any [keySelector] The custom key selector to use.
*
* @throws Key selector is invalid.
*
* @return {Object} The new object.
*/
toObject(keySelector?: any): any;
/**
* Creates a new observable object from the items of that sequence.
*
* @param any [keySelector] The custom key selector to use.
*
* @throws Key selector is invalid.
*
* @return {Observable} The new object.
*/
toObservable(keySelector?: any): Observable;
/**
* Creates a new observable array from the items of that sequence.
*
* @return {ObservableArray} The new array.
*/
toObservableArray(): ObservableArray<T>;
/**
* Creates a new virtual array from the items of that sequence.
*
* @return {VirtualArray} The new array.
*/
toVirtualArray(): VirtualArray<T>;
/**
* Produces the set union of that sequence and another.
*
* @param any second The second sequence.
* @param {Function} [equalityComparer] The custom equality comparer to use.
*
* @throws Sequence or equality comparer are no valid values.
*
* @return {IEnumerable} The new sequence.
*/
union(second: any, equalityComparer?: any): IEnumerable<T>;
/**
* Filters the elements of that sequence.
*
* @param {Function} predicate The predicate to use.
*
* @throws Predicate is no valid function / lambda expression.
*
* @return {IEnumerable} The new sequence.
*/
where(predicate: any): IEnumerable<T>;
/**
* Applies a specified function to the corresponding elements of that sequence
* and another, producing a sequence of the results.
*
* @param any second The second sequence.
* @param {Function} selector The selector for the combined result items of the elements of the two sequences.
*
* @throws Sequence or selector are no valid values.
*
* @return {IEnumerable} The new sequence.
*/
zip<U>(second: any, selector: any): IEnumerable<U>;
}
/**
* Describes the context of a current sequence item.
*/
export interface IEnumerableItemContext<T> {
/**
* Gets or sets if operation should be cancelled or not.
*/
cancel?: boolean;
/**
* Gets the zero based index.
*/
index?: number;
/**
* Gets the underlying item.
*/
item: T;
/**
* Gets the underlying key.
*/
key: any;
/**
* Gets the underlying sequence.
*/
sequence: IEnumerable<T>;
}
/**
* Describes an ordered sequence.
*/
export interface IOrderedEnumerable<T> extends IEnumerable<T> {
/**
* Performs a subsequent ordering of the elements in that sequence in ascending order,
* using the values itself as keys.
*
* @param any [comparer] The custom key comparer to use.
*
* @throws The comparer is invalid.
*
* @return {IOrderedEnumerable} The new sequence.
*/
then(comparer?: any): IOrderedEnumerable<T>;
/**
* Performs a subsequent ordering of the elements in that sequence in ascending order, according to a key.
*
* @param any selector The key selector.
* @param any [comparer] The custom key comparer to use.
*
* @throws At least one argument is invalid.
*
* @return {IOrderedEnumerable} The new sequence.
*/
thenBy(selector: any, comparer?: any): IOrderedEnumerable<T>;
/**
* Performs a subsequent ordering of the elements in that sequence in descending order, according to a key.
*
* @param any selector The key selector.
* @param any [comparer] The custom key comparer to use.
*
* @throws At least one argument is invalid.
*
* @return {IOrderedEnumerable} The new sequence.
*/
thenByDescending(selector: any, comparer?: any): IOrderedEnumerable<T>;
/**
* Performs a subsequent ordering of the elements in that sequence in descending order,
* using the values as keys.
*
* @param any [comparer] The custom key comparer to use.
*
* @throws The comparer is invalid.
*
* @return {IOrderedEnumerable} The new sequence.
*/
thenDescending(comparer?: any): IOrderedEnumerable<T>;
}
/**
* A basic sequence.
*/
export declare abstract class Sequence<T> implements IEnumerable<T> {
/**
* The custom selector.
*/
protected _selector: (x: T) => any;
/** @inheritdoc */
aggregate(accumulator: any, defaultValue?: any): any;
/** @inheritdoc */
all(predicate: any): boolean;
/** @inheritdoc */
any(predicate?: any): boolean;
/** @inheritdoc */
average(defaultValue?: any): any;
/** @inheritdoc */
cast(type: string): IEnumerable<any>;
/** @inheritdoc */
concat(second: any): IEnumerable<T>;
/** @inheritdoc */
contains(item: T, equalityComparer?: any): boolean;
/** @inheritdoc */
count(predicate?: any): number;
/** @inheritdoc */
current: T;
/** @inheritdoc */
defaultIfEmpty(...defaultItems: T[]): IEnumerable<T>;
/** @inheritdoc */
distinct(equalityComparer?: any): IEnumerable<T>;
/** @inheritdoc */
each(action: any): any;
/** @inheritdoc */
elementAt(index: number): T;
/** @inheritdoc */
elementAtOrDefault(index: number, defaultValue?: any): any;
/** @inheritdoc */
except(second: any, equalityComparer?: any): IEnumerable<T>;
/** @inheritdoc */
first(predicate?: any): T;
/** @inheritdoc */
firstOrDefault(predicateOrDefaultValue?: any, defaultValue?: any): any;
/**
* Gets the current item.
*
* @return any The current item.
*/
protected abstract getCurrent(): any;
/** @inheritdoc */
groupBy<K>(keySelector: any, keyEqualityComparer?: any): IEnumerable<IGrouping<K, T>>;
/** @inheritdoc */
groupJoin<U>(inner: any, outerKeySelector: any, innerKeySelector: any, resultSelector: any, keyEqualityComparer?: any): IEnumerable<U>;
/** @inheritdoc */
intersect(second: any, equalityComparer?: any): IEnumerable<T>;
/** @inheritdoc */
isValid: boolean;
/** @inheritdoc */
itemKey: any;
/** @inheritdoc */
join<U>(inner: any, outerKeySelector: any, innerKeySelector: any, resultSelector: any, keyEqualityComparer?: any): IEnumerable<any>;
/** @inheritdoc */
last(predicate?: any): any;
/** @inheritdoc */
lastOrDefault(predicateOrDefaultValue?: any, defaultValue?: any): any;
/** @inheritdoc */
max(defaultValue?: any): any;
/** @inheritdoc */
min(defaultValue?: any): any;
/** @inheritdoc */
abstract moveNext(): boolean;
/** @inheritdoc */
ofType(type: string): IEnumerable<T>;
/** @inheritdoc */
order(comparer?: any): IOrderedEnumerable<T>;
/** @inheritdoc */
orderBy(selector: any, comparer?: any): IOrderedEnumerable<T>;
/** @inheritdoc */
orderByDescending(selector: any, comparer?: any): IOrderedEnumerable<T>;
/** @inheritdoc */
orderDescending(comparer?: any): IOrderedEnumerable<T>;
/** @inheritdoc */
pushToArray(arr: T[] | ObservableArray<T>): Sequence<T>;
/** @inheritdoc */
abstract reset(): any;
/** @inheritdoc */
reverse(): IEnumerable<T>;
/** @inheritdoc */
select<U>(selector: any): IEnumerable<U>;
/**
* Projects an item to another type based on the inner selector.
*
* @param {T} x The input value.
*
* @return any The output value.
*/
protected selectInner(item: T): any;
/** @inheritdoc */
selectMany<U>(selector: any): IEnumerable<U>;
/** @inheritdoc */
sequenceEqual(other: any, equalityComparer?: any): boolean;
/** @inheritdoc */
single(predicate?: any): T;
/** @inheritdoc */
singleOrDefault(predicateOrDefaultValue?: any, defaultValue?: any): any;
/** @inheritdoc */
skip(cnt: number): IEnumerable<T>;
/** @inheritdoc */
skipLast(): IEnumerable<T>;
/** @inheritdoc */
skipWhile(predicate: any): IEnumerable<T>;
/** @inheritdoc */
sum(defaultValue?: any): any;
/** @inheritdoc */
take(cnt: number): IEnumerable<T>;
/** @inheritdoc */
takeWhile(predicate: any): IEnumerable<T>;
/** @inheritdoc */
toArray(): T[];
/** @inheritdoc */
toLookup(keySelector: any, keyEqualityComparer?: any): any;
/** @inheritdoc */
toObject(keySelector?: any): any;
/** @inheritdoc */
toObservable(keySelector?: any): Observable;
/** @inheritdoc */
toObservableArray(): ObservableArray<T>;
/** @inheritdoc */
toVirtualArray(): VirtualArray<T>;
/** @inheritdoc */
union(second: any, equalityComparer?: any): IEnumerable<T>;
/** @inheritdoc */
where(predicate: any): IEnumerable<T>;
/** @inheritdoc */
zip<U>(second: any, selector: any): IEnumerable<U>;
}
/**
* A grouping.
*/
export declare class Grouping<K, T> extends Sequence<T> implements IGrouping<K, T> {
private _key;
private _seq;
/**
* Initializes a new instance of that class.
*
* @param {K} key The key.
* @param {IEnumerable} seq The items of the grouping.
*/
constructor(key: K, seq: IEnumerable<T>);
/** @inheritdoc */
protected getCurrent(): T;
/** @inheritdoc */
isValid: boolean;
/** @inheritdoc */
key: K;
/** @inheritdoc */
moveNext(): boolean;
/** @inheritdoc */
reset(): any;
}
/**
* An ordered sequence.
*/
export declare class OrderedSequence<T> extends Sequence<T> implements IOrderedEnumerable<T> {
private _items;
private _originalItems;
private _orderComparer;
private _orderSelector;
/**
* Initializes a new instance of that class.
*
* @param {IEnumerable} seq The source sequence.
* @param {Function} selector The selector for the sort values.
* @param {Function} comparer The comparer to use.
*/
constructor(seq: IEnumerable<T>, selector: any, comparer: any);
/**
* Gets the comparer.
*/
comparer: (x: any, y: any) => number;
/** @inheritdoc */
protected getCurrent(): T;
/** @inheritdoc */
moveNext(): boolean;
/** @inheritdoc */
reset(): any;
/**
* Gets the selector.
*/
selector: (x: T) => any;
/** @inheritdoc */
then(comparer?: any): IOrderedEnumerable<T>;
/** @inheritdoc */
thenBy(selector: any, comparer?: any): IOrderedEnumerable<T>;
/** @inheritdoc */
thenByDescending(selector: any, comparer?: any): IOrderedEnumerable<T>;
/** @inheritdoc */
thenDescending(comparer?: any): IOrderedEnumerable<T>;
}
/**
* Returns a value as sequence.
*
* @param any v The input value.
* @param {Boolean} [throwException] Throws an exception if input value is no valid value.
*
* @throws Invalid value.
*
* @return any The value as sequence or (false) if input value is no valid object.
*/
export declare function asEnumerable(v: any, throwException?: boolean): IEnumerable<any>;
/**
* Returns a value as function.
*
* @param any v The value to convert. Can be a function or a string that is handled as lambda expression.
* @param {Boolean} [throwException] Throw an exception if value is no valid function or not.
*
* @throws Value is no valid function / lambda expression.
*
* @return {Function} Value as function or (false) if value is invalid.
*/
export declare function asFunc(v: any, throwException?: boolean): any;
/**
* Creates a new sequence from a list of values.
*
* @param any ...items One or more item to add.
*
* @return {IEnumerable} The new sequence.
*/
export declare function create<T>(...items: any[]): IEnumerable<T>;
/**
* Short hand version for 'each' method of a sequence.
*
* @param items any The sequence of items to iterate.
* @param action any The action to invoke for each item.
*
* @throws At least one argument is invalid.
*
* @return any The result of the last invocation.
*/
export declare function each(items: any, action: any): any;
/**
* Creates a new sequence from an array.
*
* @param {Array} arr The array.
*
* @return {IEnumerable} The new sequence.
*/
export declare function fromArray<T>(arr?: T[] | ObservableArray<T> | VirtualArray<T> | IArguments | string): IEnumerable<T>;
/**
* Creates a new sequence from an object.
*
* @param {Object} obj The object.
*
* @return {Sequence} The new sequence.
*/
export declare function fromObject(obj?: any): IEnumerable<any>;
/**
* Checks if a value is a sequence.
*
* @param any v The value to check.
*
* @return {Boolean} Is sequence or not.
*/
export declare function isEnumerable(v: any): boolean;
/**
* Short hand version for 'order(By)' methods of a sequence.
*
* @param items any The sequence of items to iterate.
* @param [comparer] any The custom comparer to use.
* @param [selector] any The custom key selector to use.
*
* @throws At least one argument is invalid.
*
* @return {IOrderedEnumerable} The sequences with the sorted items.
*/
export declare function sort<T>(items: any, comparer?: any, selector?: any): IOrderedEnumerable<T>;
/**
* Short hand version for 'order(By)Descending' methods of a sequence.
*
* @param items any The sequence of items to iterate.
* @param [comparer] any The custom comparer to use.
* @param [selector] any The custom key selector to use.
*
* @throws At least one argument is invalid.
*
* @return {IOrderedEnumerable} The sequences with the sorted items.
*/
export declare function sortDesc<T>(items: any, comparer?: any, selector?: any): IOrderedEnumerable<T>;
/**
* Returns a value as comparer.
*
* @param any predicate The input value.
*
* @throws Input value is no valid function / lambda expression.
*
* @return {Function} Input value as comparer.
*/
export declare function toComparerSafe(comparer: any): any;
/**
* Returns a value as equality comparer.
*
* @param any equalityComparer The input value.
*
* @throws Input value is no valid function / lambda expression.
*
* @return {Function} Input value as equality comparer.
*/
export declare function toEqualityComparerSafe(equalityComparer: any): any;
/**
* Returns a value as predicate.
*
* @param any predicate The input value.
*
* @throws Input value is no valid function / lambda expression.
*
* @return {Function} Input value as predicate.
*/
export declare function toPredicateSafe(predicate: any): any; | the_stack |
import { h, mount, patch, PetitDom, unmount } from "petit-dom";
function assertEqual<T>(a: T, b: T) { }
function eventHandler(event: Event): void { }
interface CustomProps {
name: string;
count: number;
onSomeEvent(event: Event): void;
}
/**
* Create an <a> element with text content, using HyperScript syntax and JSX syntax
*/
export function testHtmlElementWithTextContent() {
// HyperScript syntax returns an ElementNode<T> object, with typed properties
const aNode = h("a", { href: "link", onclick: eventHandler }, "click here");
assertEqual(aNode.isSVG, false);
assertEqual(aNode.type, "a");
assertEqual(aNode.key, null);
assertEqual(aNode.props.href, "link");
assertEqual(aNode.props.onclick, eventHandler);
assertEqual(aNode.content.length, 1);
// JSX syntax returns a VNode object, so the "type" and "props" properties are "any"
const jsxNode = <a href="link" onclick={eventHandler}>click here</a>;
const jsxNodeType = jsxNode.type as string;
const jsxNodeProps = jsxNode.props as PetitDom.Props<HTMLAnchorElement>;
assertEqual(jsxNode.isSVG, false);
assertEqual(jsxNodeType, "a");
assertEqual(jsxNode.key, null);
assertEqual(jsxNodeProps.href, "link");
assertEqual(jsxNodeProps.onclick, eventHandler);
assertEqual(jsxNode.content.length, 1);
}
/**
* Create a <form> element with both text content and child elements, using HyperScript syntax and JSX syntax
*/
export function testHtmlElementWithMixedContent() {
// HyperScript syntax returns an ElementNode<T> object, with typed properties
const formNode = h(
"form",
{ key: 1, method: "POST", onsubmit: eventHandler },
"Hello ", h("span", null, "World")
);
assertEqual(formNode.isSVG, false);
assertEqual(formNode.type, "form");
assertEqual(formNode.key, 1);
assertEqual(formNode.props.method, "POST");
assertEqual(formNode.props.onsubmit, eventHandler);
assertEqual(formNode.content.length, 2);
// JSX syntax returns a VNode object, so the "type" and "props" properties are "any"
const jsxNode = <form key={1} method="POST" onsubmit={eventHandler}>Hello <span>World</span></form>;
const jsxNodeType = jsxNode.type as string;
const jsxNodeProps = jsxNode.props as PetitDom.Props<HTMLFormElement>;
assertEqual(jsxNode.isSVG, false);
assertEqual(jsxNodeType, "form");
assertEqual(jsxNode.key, 1);
assertEqual(jsxNodeProps.method, "POST");
assertEqual(jsxNodeProps.onsubmit, eventHandler);
assertEqual(jsxNode.content.length, 2);
}
/**
* Create an <svg> element with a child element, using HyperScript syntax and JSX syntax
*/
export function testSvgElementWithChild() {
// HyperScript syntax returns an ElementNode<T> object, with typed properties
const svgNode = h("svg", { key: 2, currentScale: 1 }, h("path"));
assertEqual(svgNode.isSVG, true);
assertEqual(svgNode.type, "svg");
assertEqual(svgNode.key, 2);
assertEqual(svgNode.props.currentScale, 1);
assertEqual(svgNode.content.length, 1);
// JSX syntax returns a VNode object, so the "type" and "props" properties are "any"
const jsxNode = <svg key={2} currentScale={1}><path /></svg>;
const jsxNodeType = jsxNode.type as string;
const jsxNodeProps = jsxNode.props as PetitDom.Props<SVGSVGElement>;
assertEqual(jsxNode.isSVG, true);
assertEqual(jsxNodeType, "svg");
assertEqual(jsxNode.key, 2);
assertEqual(jsxNodeProps.currentScale, 1);
assertEqual(jsxNode.content.length, 1);
}
/**
* Create a function component, using HyperScript syntax and JSX syntax
*/
export function testFunctionComponent() {
function FunctionComponent(): JSX.Element {
return <div>Hello World</div>;
}
// HyperScript syntax returns a FunctionComponentNode<T> object, with typed properties
const node = h(FunctionComponent, { key: "1" });
assertEqual(node.isSVG, false);
assertEqual(node.type, FunctionComponent);
assertEqual(node.key, "1");
assertEqual(node.props.key, "1");
assertEqual(node.content.length, 0);
// JSX syntax returns a VNode object, so the "type" and "props" properties are "any"
const jsxNode = <FunctionComponent key="1" />;
const jsxNodeType = jsxNode.type as PetitDom.FunctionComponent<{}>;
const jsxNodeProps = jsxNode.props as PetitDom.IntrinsicProps;
assertEqual(jsxNode.isSVG, false);
assertEqual(jsxNodeType, FunctionComponent);
assertEqual(jsxNode.key, "1");
assertEqual(jsxNodeProps.key, "1");
assertEqual(jsxNode.content.length, 0);
}
/**
* Create a function component with props, using HyperScript syntax and JSX syntax
*/
export function testFunctionComponentWithProps() {
function FunctionComponentWithProps(props: CustomProps): JSX.Element {
const { name, count, onSomeEvent } = props;
return <div className={name} tabIndex={count} onclick={onSomeEvent}></div>;
}
// HyperScript syntax returns a FunctionComponentNode<T> object, with typed properties
const node = h(FunctionComponentWithProps, { name: "xyz", count: 123, onSomeEvent: eventHandler });
assertEqual(node.isSVG, false);
assertEqual(node.type, FunctionComponentWithProps);
assertEqual(node.key, null);
assertEqual(node.props.name, "xyz");
assertEqual(node.props.count, 123);
assertEqual(node.props.onSomeEvent, eventHandler);
assertEqual(node.content.length, 0);
// JSX syntax returns a VNode object, so the "type" and "props" properties are "any"
const jsxNode = <FunctionComponentWithProps name="xyz" count={123} onSomeEvent={eventHandler} />;
const jsxNodeType = jsxNode.type as PetitDom.FunctionComponent<CustomProps>;
const jsxNodeProps = jsxNode.props as CustomProps;
assertEqual(jsxNode.isSVG, false);
assertEqual(jsxNodeType, FunctionComponentWithProps);
assertEqual(jsxNode.key, null);
assertEqual(jsxNodeProps.name, "xyz");
assertEqual(jsxNodeProps.count, 123);
assertEqual(jsxNodeProps.onSomeEvent, eventHandler);
assertEqual(jsxNode.content.length, 0);
}
/**
* Create a function component with child content, using HyperScript syntax and JSX syntax
*/
export function testFunctionComponentWithChildren() {
function FunctionComponentWithChildren(props: CustomProps, content: ReadonlyArray<PetitDom.Content>): JSX.Element {
const { name, count, onSomeEvent } = props;
return <div className={name} tabIndex={count} onclick={onSomeEvent}>{content}</div>;
}
// HyperScript syntax returns a FunctionComponentNode<T> object, with typed properties
const node = h(
FunctionComponentWithChildren,
{ name: "xyz", count: 123, onSomeEvent: eventHandler },
"Hello",
h("span", null, "World")
);
assertEqual(node.isSVG, false);
assertEqual(node.type, FunctionComponentWithChildren);
assertEqual(node.key, null);
assertEqual(node.props.name, "xyz");
assertEqual(node.props.count, 123);
assertEqual(node.props.onSomeEvent, eventHandler);
assertEqual(node.content.length, 2);
// JSX syntax returns a VNode object, so the "type" and "props" properties are "any"
const jsxNode = (
<FunctionComponentWithChildren name="xyz" count={123} onSomeEvent={eventHandler}>
Hello <span>World</span>
</FunctionComponentWithChildren>
);
const jsxNodeType = jsxNode.type as PetitDom.FunctionComponent<CustomProps>;
const jsxNodeProps = jsxNode.props as CustomProps;
assertEqual(jsxNode.isSVG, false);
assertEqual(jsxNodeType, FunctionComponentWithChildren);
assertEqual(jsxNode.key, null);
assertEqual(jsxNodeProps.name, "xyz");
assertEqual(jsxNodeProps.count, 123);
assertEqual(jsxNodeProps.onSomeEvent, eventHandler);
assertEqual(jsxNode.content.length, 2);
}
/**
* Create a component class, using HyperScript syntax and JSX syntax
*/
export function testComponentClass() {
class ComponentClass {
props = {};
mount(): Element {
return mount(<div className="some-class"></div>);
}
patch(element: Element, newProps: object, oldProps: object, newContent: ReadonlyArray<PetitDom.VNode>, oldContent: ReadonlyArray<PetitDom.VNode>): Element {
patch(
<div {...oldProps}>{oldContent}</div>,
<div {...newProps}>{newContent}</div>
);
return element;
}
unmount(element: Element): void {
unmount(<div>Hello World</div>);
}
}
// HyperScript syntax returns a ComponentClassNode<T> object, with typed properties
const node = h(ComponentClass, { key: "1" });
assertEqual(node.isSVG, false);
assertEqual(node.type, ComponentClass);
assertEqual(node.key, "1");
assertEqual(node.props.key, "1");
assertEqual(node.content.length, 0);
// JSX syntax returns a VNode object, so the "type" and "props" properties are "any"
const jsxNode = <ComponentClass key="1" />;
const jsxNodeType = jsxNode.type as PetitDom.ComponentClass<{}>;
const jsxNodeProps = jsxNode.props as PetitDom.IntrinsicProps;
assertEqual(jsxNode.isSVG, false);
assertEqual(jsxNodeType, ComponentClass);
assertEqual(jsxNode.key, "1");
assertEqual(jsxNodeProps.key, "1");
assertEqual(jsxNode.content.length, 0);
}
/**
* Create a component class with props, using HyperScript syntax and JSX syntax
*/
export function testComponentClassWithProps() {
class ComponentClassWithProps {
props: CustomProps;
constructor(props: CustomProps) {
this.props = props;
}
mount(props: CustomProps): Element {
const { name, count, onSomeEvent } = props;
return mount(<div className={name} tabIndex={count} onclick={onSomeEvent} />);
}
patch(element: Element, newProps: CustomProps, oldProps: CustomProps, newContent: ReadonlyArray<PetitDom.VNode>, oldContent: ReadonlyArray<PetitDom.VNode>): Element {
patch(
<div {...oldProps}>{oldContent}</div>,
<div {...newProps}>{newContent}</div>
);
return element;
}
unmount(element: Element): void {
unmount(<div> Hello World</div >);
}
}
// HyperScript syntax returns a ComponentClassNode<T> object, with typed properties
const node = h(ComponentClassWithProps, { name: "xyz", count: 123, onSomeEvent: eventHandler });
assertEqual(node.isSVG, false);
assertEqual(node.type, ComponentClassWithProps);
assertEqual(node.key, null);
assertEqual(node.props.name, "xyz");
assertEqual(node.props.count, 123);
assertEqual(node.props.onSomeEvent, eventHandler);
assertEqual(node.content.length, 0);
// JSX syntax returns a VNode object, so the "type" and "props" properties are "any"
const jsxNode = <ComponentClassWithProps name="xyz" count={123} onSomeEvent={eventHandler} />;
const jsxNodeType = jsxNode.type as PetitDom.ComponentClass<CustomProps>;
const jsxNodeProps = jsxNode.props as CustomProps;
assertEqual(jsxNode.isSVG, false);
assertEqual(jsxNodeType, ComponentClassWithProps);
assertEqual(jsxNode.key, null);
assertEqual(jsxNodeProps.name, "xyz");
assertEqual(jsxNodeProps.count, 123);
assertEqual(jsxNodeProps.onSomeEvent, eventHandler);
assertEqual(jsxNode.content.length, 0);
}
/**
* Create a component class with child content, using HyperScript syntax and JSX syntax
*/
export function testComponentClassWithChildren() {
class ComponentClassWithChildren {
props: CustomProps;
constructor(props: CustomProps) {
this.props = props;
}
mount(props: CustomProps, content: ReadonlyArray<PetitDom.Content>): Element {
const { name, count, onSomeEvent } = props;
return mount(
<div className={name} tabIndex={count} onclick={onSomeEvent}>{content}</div>
);
}
patch(element: Element, newProps: CustomProps, oldProps: CustomProps, newContent: ReadonlyArray<PetitDom.VNode>, oldContent: ReadonlyArray<PetitDom.VNode>): Element {
patch(
<div {...oldProps}>{oldContent}</div>,
<div {...newProps}>{newContent}</div>
);
return element;
}
unmount(element: Element): void {
unmount(<div> Hello World</div >);
}
}
// HyperScript syntax returns a ComponentClassNode<T> object, with typed properties
const node = h(
ComponentClassWithChildren,
{ name: "xyz", count: 123, onSomeEvent: eventHandler },
"Hello",
h("span", null, "World")
);
assertEqual(node.isSVG, false);
assertEqual(node.type, ComponentClassWithChildren);
assertEqual(node.key, null);
assertEqual(node.props.name, "xyz");
assertEqual(node.props.count, 123);
assertEqual(node.props.onSomeEvent, eventHandler);
assertEqual(node.content.length, 2);
// JSX syntax returns a VNode object, so the "type" and "props" properties are "any"
const jsxNode = (
<ComponentClassWithChildren name="xyz" count={123} onSomeEvent={eventHandler}>
Hello <span>World</span>
</ComponentClassWithChildren>
);
const jsxNodeType = jsxNode.type as PetitDom.ComponentClass<CustomProps>;
const jsxNodeProps = jsxNode.props as CustomProps;
assertEqual(jsxNode.isSVG, false);
assertEqual(jsxNodeType, ComponentClassWithChildren);
assertEqual(jsxNode.key, null);
assertEqual(jsxNodeProps.name, "xyz");
assertEqual(jsxNodeProps.count, 123);
assertEqual(jsxNodeProps.onSomeEvent, eventHandler);
assertEqual(jsxNode.content.length, 2);
} | the_stack |
import { assert } from "chai";
import { Value, load, loadAll } from "../../src/dom";
import { Decimal, dom, IonType, IonTypes, Timestamp } from "../../src/Ion";
import * as ion from "../../src/Ion";
import JSBI from "jsbi";
import * as JsValueConversion from "../../src/dom/JsValueConversion";
import { Constructor } from "../../src/dom/Value";
import {
exampleDatesWhere,
exampleIonValuesWhere,
exampleJsValuesWhere,
exampleTimestampsWhere,
} from "../exampleValues";
import { valueName } from "../mochaSupport";
// Tests whether each value is or is not an instance of dom.Value
function instanceOfValueTest(expected: boolean, ...values: any[]) {
for (let value of values) {
it(`${valueName(value)} instanceof Value`, () => {
assert.equal(value instanceof Value, expected);
});
}
}
function instanceOfValueSubclassTest(
constructor: Constructor,
expected: boolean,
...values: any[]
) {
for (let value of values) {
it(`${valueName(value)} instanceof ${constructor.name}`, () => {
assert.equal(value instanceof constructor, expected);
});
}
}
// Describes the static side of dom.Value subclasses
interface DomValueConstructor extends Constructor {
_getIonType(): IonType;
}
// The constructors of all dom.Value subclasses
const DOM_VALUE_SUBCLASSES: DomValueConstructor[] = [
dom.Null,
dom.Boolean,
dom.Integer,
dom.Float,
dom.Decimal,
dom.Timestamp,
dom.Clob,
dom.Blob,
dom.String,
dom.Symbol,
dom.List,
dom.SExpression,
dom.Struct,
];
// Converts each argument in `valuesToRoundTrip` to a dom.Value, writes it to an Ion stream, and then load()s the Ion
// stream back into a dom.Value. Finally, compares the original dom.Value with the dom.Value load()ed from the stream
// to ensure that no data was lost.
function domRoundTripTest(typeName: string, ...valuesToRoundTrip: any[]) {
describe(typeName, () => {
for (let value of valuesToRoundTrip) {
it(value + "", () => {
let writer = ion.makeBinaryWriter();
// Make a dom.Value out of the provided value if it isn't one already
let domValue;
if (value instanceof Value) {
domValue = value as Value;
} else {
domValue = Value.from(value);
}
// Serialize the dom.Value using the newly instantiated writer
domValue.writeTo(writer);
writer.close();
// Load the serialized version of the value
let roundTripped = load(writer.getBytes())!;
// Verify that nothing was lost in the round trip
assert.isTrue(domValue.ionEquals(roundTripped));
});
}
});
}
/**
* Tests constructing an Ion dom.Value from a JS value. Verifies that the newly constructed
* dom.Value has the expected Ion type, the expected JS type, and a value equal to that of jsValue (or
* `expectValue` instead, if specified).
*
* @param jsValue A JS value to pass to Value.from().
* @param expectedIonType The new dom.Value's expected Ion type.
*/
function domValueTest(jsValue, expectedIonType) {
function validateDomValue(domValue: Value, annotations) {
let equalityTestValue = jsValue;
// Verify that the new dom.Value is considered equal to the original (unwrapped) JS value.
assert.isTrue(
domValue.equals(equalityTestValue)
);
assert.equal(expectedIonType, domValue.getType());
let expectedDomType: any = JsValueConversion._domConstructorFor(
expectedIonType
);
assert.isTrue(domValue instanceof expectedDomType);
assert.deepEqual(annotations, domValue.getAnnotations());
}
return () => {
// Test Value.from() with and without specifying annotations
let annotations = ["foo", "bar", "baz"];
it("" + jsValue, () => {
validateDomValue(Value.from(jsValue), []);
});
it(annotations.join("::") + "::" + jsValue, () => {
validateDomValue(Value.from(jsValue, annotations), annotations);
});
};
}
describe("Value", () => {
describe("from()", () => {
describe("null", domValueTest(null, IonTypes.NULL));
describe("boolean", domValueTest(true, IonTypes.BOOL));
describe("Boolean", domValueTest(new Boolean(true), IonTypes.BOOL));
describe("number (integer)", domValueTest(7, IonTypes.INT));
describe("Number (integer)", domValueTest(new Number(7), IonTypes.INT));
describe("BigInt", domValueTest(JSBI.BigInt(7), IonTypes.INT));
describe("number (floating point)", domValueTest(7.5, IonTypes.FLOAT));
describe(
"Number (floating point)",
domValueTest(new Number(7.5), IonTypes.FLOAT)
);
describe("Decimal", domValueTest(new Decimal("7.5"), IonTypes.DECIMAL));
describe("Date", () => {
for (let date of [...exampleDatesWhere(), new Date()]) {
domValueTest(date, IonTypes.TIMESTAMP)();
}
});
describe("Timestamp", () => {
for (let timestamp of exampleTimestampsWhere()) {
domValueTest(timestamp, IonTypes.TIMESTAMP)();
}
});
describe("string", domValueTest("Hello", IonTypes.STRING));
describe("String", domValueTest(new String("Hello"), IonTypes.STRING));
describe(
"Blob",
domValueTest(
new Uint8Array([9, 8, 7, 6, 5, 4, 3, 2, 1, 0]),
IonTypes.BLOB
)
);
describe(
"List",
domValueTest([9, 8, 7, 6, 5, 4, 3, 2, 1, 0], IonTypes.LIST)
);
describe(
"Struct",
domValueTest(
{ foo: 7, bar: true, baz: 98.6, qux: "Hello" },
IonTypes.STRUCT
)
);
describe(
"List inside Struct",
domValueTest({ foo: [9, 8, 7, 6, 5, 4, 3, 2, 1, 0] }, IonTypes.STRUCT)
);
describe(
"Struct inside List",
domValueTest(
[{ foo: 7, bar: true, baz: 98.6, qux: "Hello" }],
IonTypes.LIST
)
);
});
describe("instanceof", () => {
describe("All dom.Value subclasses are instances of dom.Value", () => {
instanceOfValueTest(true, ...exampleIonValuesWhere());
});
describe("No plain Javascript value is an instance of dom.Value", () => {
instanceOfValueTest(
false,
...exampleJsValuesWhere(),
Object.create(null)
);
});
for (let subclass of DOM_VALUE_SUBCLASSES) {
describe(`${subclass.name}`, () => {
// Javascript values are not instances of any dom.Value subclass
describe(`Plain Javascript value instanceof dom.${subclass.name}`, () => {
instanceOfValueSubclassTest(
subclass,
false,
...exampleJsValuesWhere()
);
});
// Non-null dom.Values whose Ion type matches that of the constructor must be instances of that
// dom.Value subclass.
describe(`Non-null ${subclass._getIonType().name} instanceof dom.${
subclass.name
}`, () => {
instanceOfValueSubclassTest(
subclass,
true,
...exampleIonValuesWhere(
(value) =>
(value.isNull() && subclass === dom.Null) ||
(!value.isNull() && value.getType() === subclass._getIonType())
)
);
});
// Null dom.Values and those whose Ion type does NOT match that of the constructor must not be instances
// of that dom.Value subclass.
describe(`Null or non-${subclass._getIonType().name} instanceof dom.${
subclass.name
}`, () => {
instanceOfValueSubclassTest(
subclass,
false,
...exampleIonValuesWhere(
(value) =>
(value.isNull() && subclass !== dom.Null) ||
(!value.isNull() && value.getType() !== subclass._getIonType())
)
);
});
});
}
});
describe("writeTo()", () => {
domRoundTripTest(
"Null",
// isNull() and getType() are already checked in `domRoundTripTest`
// Test `null` of every Ion type
...Object.values(IonTypes).map((ionType) => load("null." + ionType.name)!)
);
domRoundTripTest("Boolean", true, false);
domRoundTripTest(
"Integer",
Number.MIN_SAFE_INTEGER,
-8675309,
-24601,
0,
24601,
8675309,
Number.MAX_SAFE_INTEGER
);
domRoundTripTest(
"Float",
// Supports NaN equality
Number.NEGATIVE_INFINITY,
-867.5309,
-2.4601,
0.0,
2.4601,
867.5309,
Number.POSITIVE_INFINITY,
Number.NaN
);
domRoundTripTest(
"Decimal",
new Decimal("0"),
new Decimal("1.5"),
new Decimal("-1.5"),
new Decimal(".00001"),
new Decimal("-.00001")
);
domRoundTripTest(
"Timestamp",
...exampleDatesWhere(),
...exampleTimestampsWhere()
);
domRoundTripTest(
"String",
"",
"foo",
"bar",
"baz",
load('foo::bar::baz::"Hello"')
);
domRoundTripTest(
"Symbol",
load("foo"),
load("'bar'"),
load("foo::bar::baz")
);
domRoundTripTest(
"Blob",
load("{{aGVsbG8gd29ybGQ=}}"),
load("foo::bar::{{aGVsbG8gd29ybGQ=}}")
);
domRoundTripTest(
"Clob",
load('{{"February"}}'),
load('month::{{"February"}}')
);
domRoundTripTest(
"List",
[],
[1, 2, 3],
["foo", "bar", "baz"],
[new Date(0), true, "hello", null]
);
domRoundTripTest(
"S-Expression",
load("()"),
load("(1 2 3)"),
load('("foo" "bar" "baz")'),
load('(1970-01-01T00:00:00.000Z true "hello" null null.struct)')
);
domRoundTripTest(
"Struct",
{},
{ foo: 5, bar: "baz", qux: true },
{ foo: ["dog", "cat", "mouse"] }
);
});
describe("Large containers", () => {
const LARGE_CONTAINER_NUM_ENTRIES = 1_000_000;
let largeJsArray: Value[] = new Array(LARGE_CONTAINER_NUM_ENTRIES);
let largeJsObject = {};
for (let i = 0; i < LARGE_CONTAINER_NUM_ENTRIES; i++) {
let ionValue = Value.from(i);
largeJsArray[i] = ionValue;
largeJsObject[i] = ionValue;
}
it("List", () => {
let ionList = Value.from(largeJsArray) as any;
assert.equal(ionList.getType(), IonTypes.LIST);
assert.equal(ionList.length, LARGE_CONTAINER_NUM_ENTRIES);
});
it("S-Expression", () => {
let ionSExpression = new dom.SExpression(largeJsArray) as any;
assert.equal(ionSExpression.getType(), IonTypes.SEXP);
assert.equal(ionSExpression.length, LARGE_CONTAINER_NUM_ENTRIES);
});
it("Struct", function () {
this.timeout(6_000);
let ionStruct = Value.from(largeJsObject) as any;
assert.equal(ionStruct.getType(), IonTypes.STRUCT);
assert.equal(ionStruct.fields().length, LARGE_CONTAINER_NUM_ENTRIES);
});
});
}); | the_stack |
(function ($: JQueryStatic) {
// you have to extend jQuery with the fn["pluginName"] notation because in Typescript you can't extend
// the existing typing interface with fn.pluginName!
$.fn["butterExpandable"] = function () {
return this.each((index, element) => {
let rootElement: JQuery = $(element);
if (rootElement.find("textarea").length > 0) {
new ButterFaces.TextareaExpandable(rootElement);
} else {
new ButterFaces.DivExpandable(rootElement);
}
});
};
})(jQuery);
namespace ButterFaces {
const EXPAND_HEIGHT: number = 250; //in px
const EXPAND_WIDTH: number = 500; //in px
const ANIMATION_DURATION: number = 200; //in ms
const REPOSITION_INTERVAL: number = 500; //in ms
const EASING: string = "swing";
const KEYCODE_ESCAPE: number = 27;
abstract class AbstractExpandable {
rootElement: JQuery;
ghostElement: JQuery;
originalElement: JQuery;
initialHeight: number;
initialWidth: number;
initialOffset: JQuery.Coordinates;
positionTriggerInterval: number;
constructor(rootElement: JQuery) {
this.rootElement = rootElement;
}
abstract createGhostElement(): JQuery;
abstract isExpansionEventIgnored(event: any): boolean;
abstract onGhostElementCreated(): void;
abstract onGhostElementCollapsed(isCancelled: boolean): void;
abstract transferValueToGhostElement(): void;
expandElement(event: any): void {
if (this.isExpansionEventIgnored(event)) {
return;
}
this.initialHeight = this.originalElement.outerHeight();
this.initialWidth = this.originalElement.outerWidth();
this.initialOffset = this.originalElement.offset();
//create a ghost element that be animated on gets the focus
this.ghostElement = this.createGhostElement();
this.transferValueToGhostElement();
this.ghostElement.css("width", this.initialWidth)
.css("height", this.initialHeight)
.css("position", "absolute")
.css("top", this.initialOffset.top)
.css("left", this.initialOffset.left)
.css("z-index", 2000)
.css("box-shadow", "5px 5px 5px 0 #999")
.addClass("butter-component-expandable-ghost")
.appendTo($("body"))
.animate({
height: EXPAND_HEIGHT,
width: this.initialWidth > EXPAND_WIDTH ? this.initialWidth : EXPAND_WIDTH
}, ANIMATION_DURATION, EASING, () => {
$(document)
.on("click.expandable", event => {
this.handleMouseClick(event);
})
.on("keydown.expandable", event => {
this.handleEscapeKey(event);
});
$(window).on("resize.expandable", () => {
this.repositionGhostElement();
});
//keep track of the orginal element"s position
this.positionTriggerInterval = window.setInterval(() => this.repositionGhostElement, REPOSITION_INTERVAL);
});
//make original invisible
this.originalElement
.css("visibility", "hidden")
.siblings()
.css("visibility", "hidden");
this.onGhostElementCreated();
}
/**
* Collapses the ghost element and sets the value if not isCancelled
* @param isCancelled
*/
collapseElement(cancelled: any): void {
// "cancelled" can be an event object
let isCancelled = typeof cancelled === "boolean" && cancelled;
$(document)
.off("click.expandable")
.off("keydown.expandable");
//make original visible again
this.originalElement
.css("visibility", "visible")
.siblings()
.css("visibility", "visible");
let self = this;
this.ghostElement.animate({
height: self.initialHeight,
width: self.initialWidth
}, ANIMATION_DURATION, EASING, function () {
//on animation complete
self.onGhostElementCollapsed(isCancelled);
//delete the ghost element
self.ghostElement.remove();
self.ghostElement = null;
//delete position trigger timeout and resize listener
window.clearInterval(self.positionTriggerInterval);
$(window).off("resize.expandable");
});
}
private handleMouseClick(event: any): void {
// collapse ghost element if user clicks beside it
if (!$(event.target).is(".butter-component-expandable-ghost")) {
this.collapseElement(false);
}
}
private handleEscapeKey(event: any): void {
if (event.which === KEYCODE_ESCAPE) {
this.collapseElement(true);
}
}
private repositionGhostElement(): void {
//keep track of window resizing and reposition the ghost element
if (this.ghostElement !== undefined && this.ghostElement != null) {
this.initialOffset = this.originalElement.offset();
this.ghostElement
.css("top", this.initialOffset.top)
.css("left", this.initialOffset.left);
}
}
}
export class DivExpandable extends AbstractExpandable {
constructor(rootElement: JQuery) {
super(rootElement);
this.originalElement = this.rootElement.find(".butter-component-value-readonly");
this.rearrangeOriginalElementStructure();
}
private rearrangeOriginalElementStructure(): void {
let _label = this.rootElement.find(".butter-component-label");
this.originalElement
.addClass("butter-component-expandable-original")
.click(event => {
this.expandElement(event);
})
.detach();
let _container = $("<div>")
.addClass("butter-component-expandable-readonly-container")
.insertAfter(_label);
let _icon = $("<span>").addClass("input-group-text glyphicon glyphicon-resize-full");
this.originalElement.appendTo(_container);
$("<div>")
.addClass("butter-component-expandable-readonly-icon")
.append(_icon)
.appendTo(_container);
}
createGhostElement(): JQuery {
return $("<div>");
}
isExpansionEventIgnored(event: any): boolean {
return false;
}
onGhostElementCreated(): void {
// do nothing
}
onGhostElementCollapsed(isCancelled: boolean): void {
// do nothing
}
transferValueToGhostElement(): void {
$("<div>")
.html(this.originalElement.html())
.addClass("butter-component-expandable-ghost-readonlyContent")
.appendTo(this.ghostElement);
}
}
export class TextareaExpandable extends AbstractExpandable {
private blockFocusEventOnOriginal: boolean;
private blockBlurEventOnOriginal: boolean;
constructor(rootElement: JQuery) {
super(rootElement);
this.blockFocusEventOnOriginal = false;
this.blockBlurEventOnOriginal = false;
this.originalElement = this.rootElement.find("textarea");
this.originalElement.addClass("butter-component-expandable-original");
this.originalElement.focus(event => {
this.expandElement(event);
});
this.originalElement.blur(event => {
this.handleBlurEvent(event);
});
this.addInputGroupAddon();
}
private addInputGroupAddon(): void {
this.originalElement
.addClass("form-control")
.parent()
.addClass("input-group");
$("<span class=\"input-group-append\"><span class=\"input-group-text glyphicon glyphicon-resize-full\"></span></span>")
.insertAfter(this.originalElement);
}
private handleBlurEvent(event: any): void {
if (this.blockBlurEventOnOriginal) {
// prevent blur event bubbling, so it will not be triggered in jsf
event.preventDefault();
}
}
createGhostElement(): JQuery {
return $("<textarea>");
}
isExpansionEventIgnored(event: any): boolean {
this.blockBlurEventOnOriginal = true;
if (this.blockFocusEventOnOriginal) {
event.preventDefault();
return true;
} else {
return false;
}
}
onGhostElementCreated(): void {
this.ghostElement
.blur(event => {
this.collapseElement(event);
})
.focus();
this.moveCaretToEnd(this.ghostElement);
}
onGhostElementCollapsed(isCancelled: boolean): void {
if (!isCancelled) {
//transfer value back from ghost to original
this.originalElement.val(this.ghostElement.val());
// trigger blur and keyup event on original textarea and don"t block
// it for jsf
this.blockBlurEventOnOriginal = false;
this.blockFocusEventOnOriginal = true;
// defer the events a little bit, look at
// (http://stackoverflow.com/questions/8380759/why-isnt-this-textarea-focusing-with-focus#8380785)
window.setTimeout(() => {
this.originalElement.trigger("keyup");
this.originalElement.trigger("change");
this.originalElement.trigger("blur");
this.blockFocusEventOnOriginal = false;
}, 50);
} else {
this.blockBlurEventOnOriginal = true;
this.blockFocusEventOnOriginal = false;
}
}
transferValueToGhostElement(): void {
this.ghostElement.val(this.originalElement.val());
}
private moveCaretToEnd(element: any): void {
if (typeof element.selectionStart === "number") {
element.selectionStart = element.selectionEnd = element.value.length;
} else if (typeof element.createTextRange !== "undefined") {
let range = element.createTextRange();
range.collapse(false);
range.select();
} else {
let strLength = (<string>this.ghostElement.val()).length * 2;
(<HTMLInputElement>this.ghostElement.get(0)).setSelectionRange(strLength, strLength);
}
}
}
} | the_stack |
import { ShellRunner } from "../process/shell-runner.ts";
import {
Account,
AccountResponse,
AssumedRoleResponse,
CostResponse,
Credentials,
Group,
GroupResponse,
Policy,
PolicyResponse,
Tag,
TagResponse,
User,
UserResponse,
} from "./aws.model.ts";
import { ShellOutput } from "../process/shell-output.ts";
import { moment } from "../deps.ts";
import {
AwsErrorCode,
MeshAwsPlatformError,
MeshInvalidTagValueError,
MeshNotLoggedInError,
} from "../errors.ts";
import { sleep } from "../promises.ts";
import { CLICommand, CLIName } from "../config/config.model.ts";
import { parseJsonWithLog } from "../json.ts";
export class AwsCliFacade {
constructor(
private readonly shellRunner: ShellRunner,
) {}
private readonly errRegexInvalidTagValue =
/An error occurred \(InvalidInputException\) when calling the TagResource operation: You provided a value that does not match the required pattern/;
async listAccounts(): Promise<Account[]> {
let nextToken = null;
let accounts: Account[] = [];
do {
let command = "aws organizations list-accounts --output json";
if (nextToken != null) {
command += ` --starting-token ${nextToken}`;
}
const result = await this.shellRunner.run(command);
this.checkForErrors(result);
console.debug(`listAccounts: ${JSON.stringify(result)}`);
const jsonResult = parseJsonWithLog<AccountResponse>(result.stdout);
nextToken = jsonResult.NextToken;
accounts = accounts.concat(jsonResult.Accounts);
} while (nextToken != null);
return accounts;
}
async listTags(account: Account): Promise<Tag[]> {
const command =
`aws organizations list-tags-for-resource --resource-id ${account.Id}`;
const result = await this.shellRunner.run(command);
this.checkForErrors(result);
console.debug(`listTags: ${JSON.stringify(result)}`);
if (result.code === 254) {
console.debug("AWS is overheated. We wait one second and continue.");
await sleep(1000);
return await this.listTags(account);
}
return parseJsonWithLog<TagResponse>(result.stdout).Tags;
}
async addTags(account: Account, tags: Tag[]): Promise<void> {
const tagsStr = tags.map((t) => `Key=${t.Key},Value=${t.Value}`).join(" ");
const command =
`aws organizations tag-resource --resource-id ${account.Id} --tags ${tagsStr}`;
const result = await this.shellRunner.run(command);
this.checkForErrors(result);
console.debug(`addTags: ${JSON.stringify(result)}`);
}
async removeTags(account: Account, tags: Tag[]): Promise<void> {
const tagsKeys = tags.map((t) => t.Key).join(" ");
const command =
`aws organizations untag-resource --resource-id ${account.Id} --tag-keys "${tagsKeys}"`;
const result = await this.shellRunner.run(command);
this.checkForErrors(result);
console.debug(`removeTags: ${JSON.stringify(result)}`);
}
async assumeRole(
roleArn: string,
credentials?: Credentials,
): Promise<Credentials> {
const command =
`aws sts assume-role --role-arn ${roleArn} --role-session-name Collie-Session`;
const result = await this.shellRunner.run(
command,
this.credsToEnv(credentials),
);
this.checkForErrors(result);
console.debug(`assumeRole: ${JSON.stringify(result)}`);
return parseJsonWithLog<AssumedRoleResponse>(result.stdout).Credentials;
}
/**
* For debugging: will return the identity AWS thinks you are.
* @param credential Assumed credentials.
*/
async printCallerIdentity(credential?: Credentials) {
const command = "aws sts get-caller-identity";
const result = await this.shellRunner.run(
command,
this.credsToEnv(credential),
);
this.checkForErrors(result);
console.log(result.stdout);
}
async listUsers(credential: Credentials): Promise<User[]> {
const command = "aws iam list-users --max-items 50";
const result = await this.shellRunner.run(
command,
this.credsToEnv(credential),
);
this.checkForErrors(result);
console.debug(`listUsers: ${JSON.stringify(result)}`);
let response = parseJsonWithLog<UserResponse>(result.stdout);
const users = response.Users;
while (response.NextToken) {
const pagedCommand = `${command} --starting-token ${response.NextToken}`;
const result = await this.shellRunner.run(pagedCommand);
this.checkForErrors(result);
response = parseJsonWithLog<UserResponse>(result.stdout);
users.push(...response.Users);
}
return users;
}
async listGroups(credential: Credentials): Promise<Group[]> {
const command = `aws iam list-groups --max-items 50`;
const result = await this.shellRunner.run(
command,
this.credsToEnv(credential),
);
this.checkForErrors(result);
console.debug(`listGroups: ${JSON.stringify(result)}`);
let response = parseJsonWithLog<GroupResponse>(result.stdout);
const groups = response.Groups;
while (response.NextToken) {
const pagedCommand = `${command} --starting-token ${response.NextToken}`;
const result = await this.shellRunner.run(pagedCommand);
this.checkForErrors(result);
response = parseJsonWithLog<GroupResponse>(result.stdout);
groups.push(...response.Groups);
}
return groups;
}
async listUserOfGroup(
group: Group,
credential: Credentials,
): Promise<User[]> {
const command =
`aws iam get-group --group-name ${group.GroupName} --max-items 50`;
const result = await this.shellRunner.run(
command,
this.credsToEnv(credential),
);
this.checkForErrors(result);
console.debug(`listUserOfGroup: ${JSON.stringify(result)}`);
let response = parseJsonWithLog<UserResponse>(result.stdout);
const userOfGroup = response.Users;
while (response.NextToken) {
const pagedCommand = `${command} --starting-token ${response.NextToken}`;
const result = await this.shellRunner.run(pagedCommand);
this.checkForErrors(result);
response = parseJsonWithLog<UserResponse>(result.stdout);
userOfGroup.push(...response.Users);
}
return userOfGroup;
}
async listAttachedGroupPolicies(
group: Group,
credential: Credentials,
): Promise<Policy[]> {
const command =
`aws iam list-attached-group-policies --group-name ${group.GroupName}`;
const result = await this.shellRunner.run(
command,
this.credsToEnv(credential),
);
this.checkForErrors(result);
console.debug(`listAttachedGroupPolicies: ${JSON.stringify(result)}`);
let response = parseJsonWithLog<PolicyResponse>(result.stdout);
const policies = response.AttachedPolicies;
while (response.Marker) {
const pagedCommand = `${command} --starting-token ${response.Marker}`;
const result = await this.shellRunner.run(pagedCommand);
this.checkForErrors(result);
response = parseJsonWithLog<PolicyResponse>(result.stdout);
policies.push(...response.AttachedPolicies);
}
return policies;
}
async listAttachedUserPolicies(
user: User,
credential: Credentials,
): Promise<Policy[]> {
const command =
`aws iam list-attached-user-policies --user-name ${user.UserName}`;
const result = await this.shellRunner.run(
command,
this.credsToEnv(credential),
);
this.checkForErrors(result);
console.debug(`listAttachedUserPolicies: ${JSON.stringify(result)}`);
let response = parseJsonWithLog<PolicyResponse>(result.stdout);
const policies = response.AttachedPolicies;
while (response.Marker) {
const pagedCommand = `${command} --starting-token ${response.Marker}`;
const result = await this.shellRunner.run(pagedCommand);
this.checkForErrors(result);
response = parseJsonWithLog<PolicyResponse>(result.stdout);
policies.push(...response.AttachedPolicies);
}
return policies;
}
/**
* https://docs.aws.amazon.com/cli/latest/reference/ce/get-cost-and-usage.html
*
* Note: the actual paging handling has not been tested but has been built by using [listAccounts]' logic and AWS docs.
*/
async listCosts(startDate: Date, endDate: Date): Promise<CostResponse> {
let result: CostResponse | null = null;
let nextToken = null;
const format = "YYYY-MM-DD";
const start = moment(startDate).format(format);
const end = moment(endDate).format(format);
do {
let command =
`aws ce get-cost-and-usage --time-period Start=${start},End=${end} --granularity MONTHLY --metrics BLENDED_COST --group-by Type=DIMENSION,Key=LINKED_ACCOUNT`;
if (nextToken != null) {
command += ` --next-page-token=${nextToken}`;
}
const rawResult = await this.shellRunner.run(command);
this.checkForErrors(rawResult);
console.debug(`listCosts: ${JSON.stringify(rawResult)}`);
const costResult = parseJsonWithLog<CostResponse>(rawResult.stdout);
if (costResult.NextPageToken) {
nextToken = costResult.NextPageToken;
}
// This is a bit hacky but we extend the original response with new data, rather than overwriting it.
if (!result) {
result = costResult;
} else {
result.ResultsByTime = result.ResultsByTime.concat(
costResult.ResultsByTime,
);
// We do not concat the other values since (we assume) they do not change in-between requests.
}
} while (nextToken != null);
return result;
}
private checkForErrors(result: ShellOutput) {
switch (result.code) {
case 0:
return;
case 253:
throw new MeshNotLoggedInError(
`You are not correctly logged into AWS CLI. Please verify credentials with "aws config" or disconnect with "${CLICommand} config --disconnect AWS"\n${result.stderr}`,
);
case 254:
if (result.stderr.match(this.errRegexInvalidTagValue)) {
throw new MeshInvalidTagValueError(
"You provided an invalid tag value for AWS. Please try again with a different value.",
);
} else {
throw new MeshAwsPlatformError(
AwsErrorCode.AWS_UNAUTHORIZED,
`Access to required AWS API calls is not permitted. You must use ${CLIName} from a AWS management account user.\n${result.stderr}`,
);
}
default:
throw new MeshAwsPlatformError(
AwsErrorCode.AWS_CLI_GENERAL,
result.stderr,
);
}
}
private credsToEnv(credentials?: Credentials): { [key: string]: string } {
if (!credentials) {
return {};
}
return {
AWS_ACCESS_KEY_ID: credentials.AccessKeyId,
AWS_SECRET_ACCESS_KEY: credentials.SecretAccessKey,
AWS_SESSION_TOKEN: credentials.SessionToken,
};
}
} | the_stack |
import * as PIXI from 'pixi.js'
import FD from '../core/factorioData'
import G from '../common/globals'
import { Tile } from '../core/Tile'
import { Entity } from '../core/Entity'
import { Blueprint } from '../core/Blueprint'
import { IConnection } from '../core/WireConnections'
import { isActionActive, callAction } from '../actions'
import { Viewport } from './Viewport'
import { EntitySprite } from './EntitySprite'
import { WiresContainer } from './WiresContainer'
import { UnderlayContainer } from './UnderlayContainer'
import { EntityContainer } from './EntityContainer'
import { OverlayContainer } from './OverlayContainer'
import { PaintEntityContainer } from './PaintEntityContainer'
import { TileContainer } from './TileContainer'
import { PaintTileContainer } from './PaintTileContainer'
import { PaintContainer } from './PaintContainer'
import { PaintBlueprintContainer } from './PaintBlueprintContainer'
import { OptimizedContainer } from './OptimizedContainer'
import { GridData } from './GridData'
export type GridPattern = 'checker' | 'grid'
export enum EditorMode {
/** Default */
NONE,
/** Active when an entity is being hovered */
EDIT,
/** Active when "painting" */
PAINT,
/** Active when panning */
PAN,
/** Active when selecting multiple entities for copy/stamp */
COPY,
/** Active when selecting multiple entities for deletion */
DELETE,
}
export class BlueprintContainer extends PIXI.Container {
/** Nr of cunks needs to be odd because the chunk grid is offset */
private readonly chunks = 32 - 1
/** Chunk offset - from 0,0 - Measured in tiles */
private readonly chunkOffset = 16
private readonly size: IPoint = {
x: this.chunks * 32 * 32,
y: this.chunks * 32 * 32,
}
private readonly anchor: IPoint = {
x: 0.5,
y: 0.5,
}
private readonly viewport: Viewport = new Viewport(
this.size,
{
x: G.app.screen.width,
y: G.app.screen.height,
},
this.anchor,
3
)
private _moveSpeed = 10
private _gridColor = 0x303030
private _gridPattern: GridPattern = 'grid'
private _mode: EditorMode = EditorMode.NONE
public readonly bp: Blueprint
public readonly gridData: GridData
// Children
private grid: PIXI.TilingSprite
private readonly chunkGrid: PIXI.TilingSprite
private readonly tileSprites: OptimizedContainer
private readonly tilePaintSlot: PIXI.Container
public readonly underlayContainer: UnderlayContainer
private readonly entitySprites: OptimizedContainer
public readonly wiresContainer: WiresContainer
public readonly overlayContainer: OverlayContainer
private readonly entityPaintSlot: PIXI.Container
public hoverContainer: EntityContainer
public paintContainer: PaintContainer
private _entityForCopyData: Entity
private copyModeEntities: Entity[] = []
private deleteModeEntities: Entity[] = []
private copyModeUpdateFn: (endX: number, endY: number) => void
private deleteModeUpdateFn: (endX: number, endY: number) => void
public viewportCulling = true
// PIXI properties
public readonly interactive = true
public readonly interactiveChildren = false
public readonly hitArea = new PIXI.Rectangle(
-this.size.x * this.anchor.x,
-this.size.y * this.anchor.y,
this.size.x,
this.size.y
)
public constructor(bp: Blueprint) {
super()
this.bp = bp
this.gridData = new GridData(this)
this.grid = this.generateGrid()
this.chunkGrid = this.generateChunkGrid(this.chunkOffset)
this.tileSprites = new OptimizedContainer(this)
this.tilePaintSlot = new PIXI.Container()
this.underlayContainer = new UnderlayContainer()
this.entitySprites = new OptimizedContainer(this)
this.wiresContainer = new WiresContainer(this.bp)
this.overlayContainer = new OverlayContainer(this)
this.entityPaintSlot = new PIXI.Container()
this.addChild(
this.grid,
this.chunkGrid,
this.tileSprites,
this.tilePaintSlot,
this.underlayContainer,
this.entitySprites,
this.wiresContainer,
this.overlayContainer,
this.entityPaintSlot
)
this.on('pointerover', () => {
if (this.mode === EditorMode.PAINT) {
this.paintContainer.show()
}
this.updateHoverContainer()
})
this.on('pointerout', () => {
if (this.mode === EditorMode.PAINT) {
this.paintContainer.hide()
}
this.updateHoverContainer()
})
const panCb = (): void => {
if (this.mode !== EditorMode.PAN) {
const WSXOR = isActionActive('moveUp') !== isActionActive('moveDown')
const ADXOR = isActionActive('moveLeft') !== isActionActive('moveRight')
if (WSXOR || ADXOR) {
const finalSpeed = this.moveSpeed / (WSXOR && ADXOR ? 1.4142 : 1)
this.viewport.translateBy(
(ADXOR ? (isActionActive('moveLeft') ? 1 : -1) : 0) * finalSpeed,
(WSXOR ? (isActionActive('moveUp') ? 1 : -1) : 0) * finalSpeed
)
}
}
}
const onUpdate16 = (): void => {
if (this.mode === EditorMode.PAINT) {
this.paintContainer.moveAtCursor()
}
}
const onUpdate32 = (): void => {
// Instead of decreasing the global interactionFrequency, call the over and out entity events here
this.updateHoverContainer()
if (isActionActive('build')) {
callAction('build')
}
if (isActionActive('mine')) {
callAction('mine')
}
if (isActionActive('pasteEntitySettings')) {
callAction('pasteEntitySettings')
}
}
let lastX = 0
let lastY = 0
const onMouseMove = (e: MouseEvent): void => {
if (this.mode === EditorMode.PAN) {
this.viewport.translateBy(e.clientX - lastX, e.clientY - lastY)
}
lastX = e.clientX
lastY = e.clientY
}
const onResize = (): void => {
this.viewport.setSize(G.app.screen.width, G.app.screen.height)
}
G.app.ticker.add(panCb)
this.gridData.on('update16', onUpdate16)
this.gridData.on('update32', onUpdate32)
document.addEventListener('mousemove', onMouseMove)
window.addEventListener('resize', onResize, false)
this.on('destroy', () => {
G.app.ticker.remove(panCb)
this.gridData.off('update16', onUpdate16)
this.gridData.off('update32', onUpdate32)
this.gridData.destroy()
document.removeEventListener('mousemove', onMouseMove)
window.removeEventListener('resize', onResize, false)
})
}
public get entityForCopyData(): Entity {
return this._entityForCopyData
}
public copyEntitySettings(): void {
if (this.mode === EditorMode.EDIT) {
// Store reference to source entity
this._entityForCopyData = this.hoverContainer.entity
}
}
public pasteEntitySettings(): void {
if (this._entityForCopyData && this.mode === EditorMode.EDIT) {
// Hand over reference of source entity to target entity for pasting data
this.hoverContainer.entity.pasteSettings(this._entityForCopyData)
}
}
public getViewportScale(): number {
return this.viewport.getCurrentScale()
}
/** screen to world */
public toWorld(x: number, y: number): [number, number] {
const t = this.viewport.getTransform()
return [(x - t.tx) / t.a, (y - t.ty) / t.d]
}
public render(renderer: PIXI.Renderer): void {
if (this.viewport.update()) {
this.gridData.recalculate()
}
const destinationFrame = renderer.screen
const sourceFrame = destinationFrame.clone()
const t = this.viewport.getTransform()
sourceFrame.x -= t.tx / t.a
sourceFrame.y -= t.ty / t.d
sourceFrame.width /= t.a
sourceFrame.height /= t.d
const previous = renderer.renderTexture.current
for (const child of this.children) {
renderer.renderTexture.bind(null, sourceFrame, destinationFrame)
child.render(renderer)
}
renderer.batch.flush()
renderer.renderTexture.bind(previous)
}
public get mode(): EditorMode {
return this._mode
}
private setMode(mode: EditorMode): void {
this._mode = mode
this.emit('mode', mode)
}
public enterCopyMode(): void {
if (this.mode === EditorMode.COPY) return
if (this.mode === EditorMode.PAINT) this.paintContainer.destroy()
this.updateHoverContainer(true)
this.setMode(EditorMode.COPY)
this.overlayContainer.showSelectionArea(0x00d400)
const startPos = { x: this.gridData.x32, y: this.gridData.y32 }
this.copyModeUpdateFn = (endX: number, endY: number) => {
const X = Math.min(startPos.x, endX)
const Y = Math.min(startPos.y, endY)
const W = Math.abs(endX - startPos.x) + 1
const H = Math.abs(endY - startPos.y) + 1
for (const e of this.copyModeEntities) {
EntityContainer.mappings.get(e.entityNumber).cursorBox = undefined
}
this.copyModeEntities = this.bp.entityPositionGrid.getEntitiesInArea({
x: X + W / 2,
y: Y + H / 2,
w: W,
h: H,
})
for (const e of this.copyModeEntities) {
EntityContainer.mappings.get(e.entityNumber).cursorBox = 'copy'
}
}
this.copyModeUpdateFn(startPos.x, startPos.y)
this.gridData.on('update32', this.copyModeUpdateFn)
}
public exitCopyMode(cancel = false): void {
if (this.mode !== EditorMode.COPY) return
this.overlayContainer.hideSelectionArea()
this.gridData.off('update32', this.copyModeUpdateFn)
this.setMode(EditorMode.NONE)
this.updateHoverContainer()
if (!cancel && this.copyModeEntities.length !== 0) {
this.spawnPaintContainer(this.copyModeEntities)
}
for (const e of this.copyModeEntities) {
EntityContainer.mappings.get(e.entityNumber).cursorBox = undefined
}
this.copyModeEntities = []
}
public enterDeleteMode(): void {
if (this.mode === EditorMode.DELETE) return
if (this.mode === EditorMode.PAINT) this.paintContainer.destroy()
this.updateHoverContainer(true)
this.setMode(EditorMode.DELETE)
this.overlayContainer.showSelectionArea(0xff3200)
const startPos = { x: this.gridData.x32, y: this.gridData.y32 }
this.deleteModeUpdateFn = (endX: number, endY: number) => {
const X = Math.min(startPos.x, endX)
const Y = Math.min(startPos.y, endY)
const W = Math.abs(endX - startPos.x) + 1
const H = Math.abs(endY - startPos.y) + 1
for (const e of this.deleteModeEntities) {
EntityContainer.mappings.get(e.entityNumber).cursorBox = undefined
}
this.deleteModeEntities = this.bp.entityPositionGrid.getEntitiesInArea({
x: X + W / 2,
y: Y + H / 2,
w: W,
h: H,
})
for (const e of this.deleteModeEntities) {
EntityContainer.mappings.get(e.entityNumber).cursorBox = 'not_allowed'
}
}
this.deleteModeUpdateFn(startPos.x, startPos.y)
this.gridData.on('update32', this.deleteModeUpdateFn)
}
public exitDeleteMode(cancel = false): void {
if (this.mode !== EditorMode.DELETE) return
this.overlayContainer.hideSelectionArea()
this.gridData.off('update32', this.deleteModeUpdateFn)
this.setMode(EditorMode.NONE)
this.updateHoverContainer()
if (cancel) {
for (const e of this.deleteModeEntities) {
EntityContainer.mappings.get(e.entityNumber).cursorBox = undefined
}
} else {
this.bp.removeEntities(this.deleteModeEntities)
}
this.deleteModeEntities = []
}
public enterPanMode(): void {
if (this.mode === EditorMode.NONE && this.isPointerInside) {
this.setMode(EditorMode.PAN)
this.cursor = 'move'
}
}
public exitPanMode(): void {
if (this.mode === EditorMode.PAN) {
this.setMode(EditorMode.NONE)
this.cursor = 'inherit'
}
}
public zoom(zoomIn = true): void {
const zoomFactor = 0.1
this.viewport.setScaleCenter(this.gridData.x, this.gridData.y)
this.viewport.zoomBy(zoomFactor * (zoomIn ? 1 : -1))
}
private get isPointerInside(): boolean {
const container = G.app.renderer.plugins.interaction.hitTest(
G.app.renderer.plugins.interaction.mouse.global,
G.app.stage
)
return container === this
}
private updateHoverContainer(forceRemove = false): void {
const removeHoverContainer = (): void => {
this.hoverContainer.pointerOutEventHandler()
this.hoverContainer = undefined
this.setMode(EditorMode.NONE)
this.cursor = 'inherit'
this.emit('removeHoverContainer')
}
if (forceRemove || !this.isPointerInside) {
if (this.hoverContainer) {
removeHoverContainer()
}
return
}
if (!this.bp) return
const entity = this.bp.entityPositionGrid.getEntityAtPosition(
this.gridData.x32,
this.gridData.y32
)
const eC = entity ? EntityContainer.mappings.get(entity.entityNumber) : undefined
if (eC && this.hoverContainer === eC) return
if (this.mode === EditorMode.EDIT) {
removeHoverContainer()
}
if (eC && this.mode === EditorMode.NONE) {
this.hoverContainer = eC
this.setMode(EditorMode.EDIT)
this.cursor = 'pointer'
eC.pointerOverEventHandler()
this.emit('createHoverContainer')
}
}
public get moveSpeed(): number {
return this._moveSpeed
}
public set moveSpeed(speed: number) {
this._moveSpeed = speed
}
public get gridColor(): number {
return this._gridColor
}
public set gridColor(color: number) {
this._gridColor = color
this.grid.tint = color
}
public get gridPattern(): GridPattern {
return this._gridPattern
}
public set gridPattern(pattern: GridPattern) {
this._gridPattern = pattern
const index = this.getChildIndex(this.grid)
const old = this.grid
this.grid = this.generateGrid()
this.addChildAt(this.grid, index)
old.destroy()
}
private generateGrid(pattern = this.gridPattern): PIXI.TilingSprite {
const gridGraphics =
pattern === 'checker'
? new PIXI.Graphics()
.beginFill(0x808080)
.drawRect(0, 0, 32, 32)
.drawRect(32, 32, 32, 32)
.endFill()
.beginFill(0xffffff)
.drawRect(0, 32, 32, 32)
.drawRect(32, 0, 32, 32)
.endFill()
: new PIXI.Graphics()
.beginFill(0x808080)
.drawRect(0, 0, 32, 32)
.endFill()
.beginFill(0xffffff)
.drawRect(1, 1, 31, 31)
.endFill()
const renderTexture = PIXI.RenderTexture.create({
width: gridGraphics.width,
height: gridGraphics.height,
})
renderTexture.baseTexture.mipmap = PIXI.MIPMAP_MODES.POW2
G.app.renderer.render(gridGraphics, { renderTexture })
const grid = new PIXI.TilingSprite(renderTexture, this.size.x, this.size.y)
grid.anchor.set(this.anchor.x, this.anchor.y)
grid.tint = this.gridColor
return grid
}
private generateChunkGrid(chunkOffset: number): PIXI.TilingSprite {
const W = 32 * 32
const H = 32 * 32
const gridGraphics = new PIXI.Graphics()
.lineStyle({ width: 2, color: 0x000000 })
.moveTo(0, 0)
.lineTo(W, 0)
.lineTo(W, H)
.lineTo(0, H)
.lineTo(0, 0)
const renderTexture = PIXI.RenderTexture.create({
width: W,
height: H,
})
renderTexture.baseTexture.mipmap = PIXI.MIPMAP_MODES.POW2
G.app.renderer.render(gridGraphics, { renderTexture })
// Add one more chunk to the size because of the offset
const grid = new PIXI.TilingSprite(renderTexture, this.size.x + W, this.size.y + H)
// Offset chunk grid
grid.position.set(chunkOffset * 32, chunkOffset * 32)
grid.anchor.set(this.anchor.x, this.anchor.y)
return grid
}
public initBP(): void {
// Render Bp
for (const [, e] of this.bp.entities) {
new EntityContainer(e, false)
}
for (const [, t] of this.bp.tiles) {
new TileContainer(t)
}
const onCreateEntity = (entity: Entity): void => {
new EntityContainer(entity)
this.updateHoverContainer()
}
const onRemoveEntity = (): void => {
this.updateHoverContainer()
}
const onCreateTile = (tile: Tile): TileContainer => new TileContainer(tile)
this.bp.on('create-entity', onCreateEntity)
this.bp.on('remove-entity', onRemoveEntity)
this.bp.on('create-tile', onCreateTile)
const onConnectionCreated = (hash: string, connection: IConnection): void => {
this.wiresContainer.connect(hash, connection)
}
const onConnectionRemoved = (hash: string, connection: IConnection): void => {
this.wiresContainer.disconnect(hash, connection)
}
this.bp.wireConnections.on('create', onConnectionCreated)
this.bp.wireConnections.on('remove', onConnectionRemoved)
this.bp.wireConnections.forEach((connection, hash) =>
this.wiresContainer.add(hash, connection)
)
this.on('destroy', () => {
this.bp.off('create-entity', onCreateEntity)
this.bp.off('remove-entity', onRemoveEntity)
this.bp.off('create-tile', onCreateTile)
this.bp.wireConnections.off('create', onConnectionCreated)
this.bp.wireConnections.off('remove', onConnectionRemoved)
})
this.sortEntities()
this.centerViewport()
}
public destroy(): void {
this.emit('destroy')
super.destroy({ children: true })
}
public addEntitySprites(entitySprites: EntitySprite[], sort = true): void {
this.entitySprites.addChild(...entitySprites)
if (sort) {
this.sortEntities()
}
}
public addTileSprites(tileSprites: EntitySprite[]): void {
this.tileSprites.addChild(...tileSprites)
}
private sortEntities(): void {
this.entitySprites.children.sort(EntitySprite.compareFn)
}
public transparentEntities(bool = true): void {
const alpha = bool ? 0.5 : 1
this.entitySprites.alpha = alpha
this.wiresContainer.alpha = alpha
this.overlayContainer.alpha = alpha
}
public centerViewport(): void {
const bounds = this.bp.isEmpty()
? new PIXI.Rectangle(-16 * 32, -16 * 32, 32 * 32, 32 * 32)
: this.getBlueprintBounds()
this.viewport.centerViewPort(
{
x: bounds.width,
y: bounds.height,
},
{
x: (this.size.x - bounds.width) / 2 - bounds.x,
y: (this.size.y - bounds.height) / 2 - bounds.y,
}
)
}
public getBlueprintBounds(): PIXI.Rectangle {
const bounds = new PIXI.Bounds()
const addBounds = (sprite: EntitySprite): void => {
const sB = new PIXI.Bounds()
sB.minX = sprite.cachedBounds[0]
sB.minY = sprite.cachedBounds[1]
sB.maxX = sprite.cachedBounds[2]
sB.maxY = sprite.cachedBounds[3]
bounds.addBounds(sB)
}
this.entitySprites.children.forEach(addBounds)
this.tileSprites.children.forEach(addBounds)
const rect = bounds.getRectangle(new PIXI.Rectangle())
const X = Math.floor(rect.x / 32) * 32
const Y = Math.floor(rect.y / 32) * 32
const W = Math.ceil((rect.width + rect.x - X) / 32) * 32
const H = Math.ceil((rect.height + rect.y - Y) / 32) * 32
return new PIXI.Rectangle(X, Y, W, H)
}
public getPicture(): Promise<Blob> {
if (this.bp.isEmpty()) return
const region = this.getBlueprintBounds()
this.viewportCulling = false
// swap our custom render method with the original one
const _render = this.render
this.render = super.render
const texture = G.app.renderer.generateTexture(this, {
scaleMode: PIXI.SCALE_MODES.LINEAR,
resolution: 1,
region,
})
this.render = _render
this.viewportCulling = true
const canvas = G.app.renderer.plugins.extract.canvas(texture)
return new Promise(resolve => {
canvas.toBlob(blob => {
canvas.getContext('2d').clearRect(0, 0, canvas.width, canvas.height)
resolve(blob)
})
})
}
public spawnPaintContainer(itemNameOrEntities: string | Entity[], direction = 0): void {
if (this.mode === EditorMode.PAINT) {
this.paintContainer.destroy()
}
this.updateHoverContainer(true)
this.setMode(EditorMode.PAINT)
this.cursor = 'pointer'
if (typeof itemNameOrEntities === 'string') {
const itemData = FD.items[itemNameOrEntities]
const tileResult = itemData.place_as_tile && itemData.place_as_tile.result
const placeResult = itemData.place_result || tileResult
if (tileResult) {
this.paintContainer = new PaintTileContainer(this, placeResult)
this.tilePaintSlot.addChild(this.paintContainer)
} else {
this.paintContainer = new PaintEntityContainer(this, placeResult, direction)
this.entityPaintSlot.addChild(this.paintContainer)
}
} else {
this.paintContainer = new PaintBlueprintContainer(this, itemNameOrEntities)
this.entityPaintSlot.addChild(this.paintContainer)
}
if (!this.isPointerInside) {
this.paintContainer.hide()
}
this.paintContainer.on('destroy', () => {
this.paintContainer = undefined
this.setMode(EditorMode.NONE)
this.updateHoverContainer()
this.cursor = 'inherit'
})
}
} | the_stack |
import { LicenseScanResultItem, SecurityScanResultItem } from '@app/models';
import { LogProjectChangeCommand } from '@app/models/commands/LogProjectChangeCommand';
import { ProjectDistinctLicenseDto, ProjectDistinctVulnerabilityDto } from '@app/models/DTOs';
import { LicenseDto } from '@app/models/DTOs/LicenseDto';
import { LicenseModuleDto } from '@app/models/DTOs/LicenseModuleDto';
import { ObligationSearchDto } from '@app/models/DTOs/ObligationSearchDto';
import { ProjectDistinctSeverityDto } from '@app/models/DTOs/ProjectDistinctSeverityDto';
import { ProjectScanStateDto } from '@app/models/DTOs/ProjectScanStateDto';
import { ScanBranchDto } from '@app/models/DTOs/ScanBranchDto';
import { Project } from '@app/models/Project';
import { LicenseScanResultItemService } from '@app/services/license-scan-result-item/license-scan-result-item.service';
import { ProjectScanStatusTypeService } from '@app/services/project-scan-status-type/project-scan-status-type.service';
import { ProjectService } from '@app/services/project/project.service';
import { SecurityScanResultItemService } from '@app/services/security-scan-result-item/security-scan-result-item.service';
import PaginateArrayResult, { EmptyPaginateResult } from '@app/shared/util/paginate-array-result';
import {
Body,
Controller,
Get,
Param,
Post,
Query,
Request,
UseGuards,
UseInterceptors,
Header,
Res,
Logger,
} from '@nestjs/common';
import { CommandBus } from '@nestjs/cqrs';
import { AuthGuard } from '@nestjs/passport';
import { ApiBearerAuth, ApiResponse, ApiTags, ApiQuery } from '@nestjs/swagger';
import {
Crud,
CrudController,
CrudRequest,
CrudRequestInterceptor,
GetManyDefaultResponse,
Override,
ParsedBody,
ParsedRequest,
} from '@nestjsx/crud';
import gitP, { SimpleGit } from 'simple-git/promise';
import { Response } from 'express';
import { Swagger } from '@nestjsx/crud/lib/crud';
@UseGuards(AuthGuard('jwt'))
@ApiBearerAuth()
@Crud({
query: {
join: {
packageManager: {
eager: true,
exclude: ['createdAt', 'updatedAt'],
},
scans: {
eager: true,
allow: ['id'],
},
projectStatus: {
eager: true,
exclude: ['createdAt', 'updatedAt'],
},
outputFormat: {
eager: true,
exclude: ['createdAt', 'updatedAt'],
},
deploymentType: {
eager: true,
exclude: ['createdAt', 'updatedAt'],
},
developmentType: {
eager: true,
exclude: ['createdAt', 'updatedAt'],
},
},
sort: [
{
field: 'createdAt',
order: 'ASC',
},
],
},
routes: {
exclude: ['createOneBase'],
},
model: {
type: Project,
},
})
@ApiTags('Project')
@Controller('project')
export class ProjectController implements CrudController<Project> {
constructor(
public service: ProjectService,
private licenseScanResultItemService: LicenseScanResultItemService,
private securityScanResultItemService: SecurityScanResultItemService,
private commandBus: CommandBus,
) {
const metadata = Swagger.getParams(this.getProjectsWithStatus);
const queryParamsMeta = Swagger.createQueryParamsMeta('getManyBase');
Swagger.setParams([...metadata, ...queryParamsMeta], this.getProjectsWithStatus);
}
get base(): CrudController<Project> {
return this;
}
logger = new Logger('ProjectContoller');
private git: SimpleGit = gitP();
@Get('/:id/bill-of-materials/licenses')
@UseInterceptors(CrudRequestInterceptor)
@ApiResponse({ status: 200, type: [LicenseScanResultItem] })
async bomLicenses(
@Param('id') id: string,
@Query('page') page: number,
@Query('pageSize') pageSize: number,
@Query('filterText') filterText: string,
): Promise<GetManyDefaultResponse<LicenseScanResultItem>> {
const project = await this.service.db.findOne(Number(id));
const scan = await this.service.latestCompletedScan(project);
if (scan) {
const query = await this.licenseScanResultItemService.bomLicenseResultItemQuery(scan, filterText);
return PaginateArrayResult(query, +page, +pageSize);
} else {
return EmptyPaginateResult();
}
}
@Get('/:id/bill-of-materials/licenses-only')
@ApiResponse({ status: 200, type: LicenseDto, isArray: true })
async bomLicensesOnly(
@Param('id') id: string,
@Query('page') page: number,
@Query('pageSize') pageSize: number,
@Query('filterText') filterText: string,
): Promise<GetManyDefaultResponse<LicenseDto>> {
return await this.licenseScanResultItemService.bomLicensesOnly(+id, page, pageSize, filterText);
}
@Get('/:id/bill-of-materials/modules-from-license/:licenseId')
@ApiResponse({ status: 200, type: LicenseModuleDto, isArray: true })
async bomModulesFromLicense(
@Param('id') id: string,
@Param('licenseId') licenseId: number,
@Query('page') page: number = 0,
@Query('pageSize') pageSize: number = 50,
@Query('filterText') filterText: string = '',
): Promise<GetManyDefaultResponse<LicenseModuleDto>> {
return await this.licenseScanResultItemService.bomModulesFromLicense(+id, licenseId, page, pageSize, filterText);
}
@Get('/:id/bill-of-materials/vulnerabilities')
@UseInterceptors(CrudRequestInterceptor)
@ApiResponse({ status: 200, type: [SecurityScanResultItem] })
async bomVulnerabilities(
@Param('id') id: string,
@Query('page') page: number,
@Query('pageSize') pageSize: number,
@Query('filterText') filterText: string,
): Promise<GetManyDefaultResponse<SecurityScanResultItem>> {
const project = await this.service.db.findOne(Number(id));
const scan = await this.service.latestCompletedScan(project);
if (scan) {
const query = await this.securityScanResultItemService.bomSecurityResultItemQuery(scan, filterText);
return PaginateArrayResult(query, +page, +pageSize);
} else {
return EmptyPaginateResult();
}
}
@Override()
async createOne(@ParsedRequest() req: CrudRequest, @ParsedBody() dto: Project, @Request() request: any) {
const project = await this.base.createOneBase(req, dto);
const { id } = request.user;
await this.commandBus.execute(
new LogProjectChangeCommand(
project.id,
LogProjectChangeCommand.Actions.projectCreated,
`Project [${project.name}] created.`,
id,
),
);
return project;
}
@Post('/')
@UseInterceptors(CrudRequestInterceptor)
@ApiResponse({ status: 200, type: Project })
async createOneProject(
@Body() dto: Project,
@ParsedRequest() req: CrudRequest,
@Request() request: any,
): Promise<Project> {
const { id } = request.user;
dto.userId = id;
dto.name = dto.name.replace('(', '-').replace(')', '-');
const project = await this.service.createOne(req, dto);
await this.commandBus.execute(
new LogProjectChangeCommand(
project.id,
LogProjectChangeCommand.Actions.projectCreated,
`Project [${project.name}] created.`,
id,
),
);
return project;
}
@Get('/search')
@UseInterceptors(CrudRequestInterceptor)
@ApiResponse({ status: 200, type: [Project] })
async filteredProjects(
@Query('filterText') filter: string,
@Query('page') page: number,
@Query('pageSize') pageSize: number,
@Query('developmentType') developmentType: string,
): Promise<GetManyDefaultResponse<Project>> {
const query = await this.service.db
.createQueryBuilder('project')
.leftJoinAndSelect('project.developmentType', 'developmentType')
.where('(lower(name) like :filter or lower(git_url) like :filter) AND developmentType.code = :code', {
filter: '%' + filter.toLocaleLowerCase() + '%',
code: developmentType || 'organization',
});
return await PaginateArrayResult(query, +page, +pageSize);
}
@Get('/projects-with-statuses')
@UseInterceptors(CrudRequestInterceptor)
@ApiResponse({ status: 200, type: Project, isArray: true })
@ApiQuery({
name: 'applyUserFilter',
required: false,
type: String, // Boolean doesn't work....always becomes a string...WTF?
})
async getProjectsWithStatus(
@ParsedRequest() req: CrudRequest,
@Query('applyUserFilter') applyUserFilter: string = 'false',
@Request() request,
): Promise<Project[]> {
const { parsed, options } = req;
let userId = null;
if (applyUserFilter === 'true') {
userId = request.user.groups;
userId.push(request.user.id);
}
const answer = await this.service.getProjectsMany(parsed, options, userId);
return answer;
}
@Get('/validGithubRepo')
@UseInterceptors(CrudRequestInterceptor)
@ApiResponse({ status: 200 })
async getvalidGitRepo(@Query('githubUrl') gitUrl: string) {
const project = new Project();
project.gitUrl = gitUrl;
const gitUrl1 = await this.service.gitUrlAuthForProject(project);
const gitOptions = [];
gitOptions.push(gitUrl1);
try {
await this.git.listRemote(gitOptions);
return 'success';
} catch (e) {
this.logger.error(e);
return 'error';
}
}
@Get('/:id/gitbranches')
@UseInterceptors(CrudRequestInterceptor)
@ApiResponse({ status: 200, type: [ScanBranchDto] })
async getGitBranches(@Param('id') id: string): Promise<ScanBranchDto[]> {
const project = await this.service.db.findOne(Number(id));
if (project) {
const gitUrl = await this.service.gitUrlAuthForProject(project);
const gitOptions = [];
gitOptions.push(gitUrl);
const branches = this.git.listRemote(gitOptions);
const array = (await branches).substring(1, (await branches).length - 1).split('\n');
const branchesAndTags = [];
array.forEach((element) => {
const branch = element.indexOf('refs/heads/');
const branchName = element.substring(branch + 11);
const scanBranchDto = new ScanBranchDto();
if (branch > 0) {
scanBranchDto.branch = branchName;
branchesAndTags.push(scanBranchDto);
}
// const tag = element.indexOf('refs/tags/');
// const tagName = element.substring(tag + 12);
// if (tag > 0) {
// scanBranchDto.branch = tagName;
// branchesAndTags.push(scanBranchDto);
// }
});
return branchesAndTags;
}
}
@Get('/:id/stats/licenses')
@UseInterceptors(CrudRequestInterceptor)
@ApiResponse({ status: 200, type: [ProjectDistinctLicenseDto] })
async licenses(@Param('id') id: string): Promise<ProjectDistinctLicenseDto[]> {
const project = await this.service.db.findOne(Number(id));
if (project) {
return this.service.distinctLicenses(project);
} else {
return [];
}
}
@Get('/:id/obligations')
@UseInterceptors(CrudRequestInterceptor)
async obligations(@Param('id') id: string): Promise<any> {
const project = await this.service.db.findOne(Number(id));
if (project) {
return this.service.distinctObligations(project);
} else {
return [];
}
}
@Get('/:id/attributions')
@UseInterceptors(CrudRequestInterceptor)
async attributions(@Param('id') id: string): Promise<any> {
const project = await this.service.db.findOne(Number(id));
if (project) {
return this.service.getprojectAttribution(project);
} else {
return [];
}
}
@Get('/:id/attributions/download')
@Header('Content-Type', 'text/plain')
@Header('Content-Disposition', 'attachment; filename=attribution.txt')
async attributionsDownload(@Param('id') id: string, @Res() res: Response): Promise<any> {
const project = await this.service.db.findOne(Number(id));
if (project) {
const attribution = await this.service.getprojectAttribution(project);
return res.status(200).send(attribution.licenseText).end();
}
}
@Get('/:id/stats/project-scan-status')
@UseInterceptors(CrudRequestInterceptor)
@ApiResponse({ status: 200, type: ProjectScanStateDto })
async projectScanStatus(@Param('id') id: string): Promise<ProjectScanStateDto> {
const project = await this.service.db.findOne(Number(id));
const projectStatus = new ProjectScanStateDto();
projectStatus.licenseStatus = await ProjectScanStatusTypeService.Unknown();
projectStatus.securityStatus = await ProjectScanStatusTypeService.Unknown();
if (project) {
projectStatus.projectId = project.id;
projectStatus.licenseStatus = await this.service.highestLicenseStatus(project);
projectStatus.securityStatus = await this.service.highestSecurityStatus(project);
}
return projectStatus;
}
@Get('/:id/stats/severities')
@UseInterceptors(CrudRequestInterceptor)
@ApiResponse({ status: 200, type: [ProjectDistinctSeverityDto] })
async severities(@Param('id') id: string): Promise<ProjectDistinctSeverityDto[]> {
const project = await this.service.db.findOne(Number(id));
if (project) {
return this.service.distinctSeverities(project);
} else {
return [];
}
}
@Get('/:id/unique-bom-obligations')
@UseInterceptors(CrudRequestInterceptor)
@ApiResponse({ status: 200, type: ObligationSearchDto, isArray: true })
async uniqueBomObligations(
@Param('id') id: number,
@Query('page') page: number,
@Query('pageSize') pageSize: number,
): Promise<GetManyDefaultResponse<ObligationSearchDto>> {
return await this.service.uniqueBomObligations(+id, +page, +pageSize);
}
@Override()
async updateOne(@ParsedRequest() req: CrudRequest, @ParsedBody() dto: Project, @Request() request: any) {
const { id } = request.user;
await this.commandBus.execute(
new LogProjectChangeCommand(
dto.id,
LogProjectChangeCommand.Actions.projectDetailsUpdated,
'Project details have been updated.',
id,
),
);
return this.base.updateOneBase(req, dto);
}
@Get('/:id/stats/vulnerabilities')
@UseInterceptors(CrudRequestInterceptor)
@ApiResponse({ status: 200, type: [ProjectDistinctVulnerabilityDto] })
async vulnerabilities(@Param('id') id: string): Promise<ProjectDistinctVulnerabilityDto[]> {
const project = await this.service.db.findOne(Number(id));
if (project) {
return this.service.distinctVulnerabilities(project);
} else {
return [];
}
}
} | the_stack |
import 'mocha';
import expect from 'expect';
import { SpanKind } from '@opentelemetry/api';
import { ExpressInstrumentation } from '../src';
import { AddressInfo } from 'net';
import { ReadableSpan } from '@opentelemetry/sdk-trace-base';
import { SemanticAttributes } from '@opentelemetry/semantic-conventions';
import { HttpInstrumentation } from '@opentelemetry/instrumentation-http';
import * as bodyParser from 'body-parser';
const instrumentation = new ExpressInstrumentation();
// add http instrumentation so we can test proper assignment of route attribute.
const httpInstrumentation = new HttpInstrumentation();
httpInstrumentation.enable();
httpInstrumentation.disable();
instrumentation.enable();
instrumentation.disable();
import axios from 'axios';
import express from 'express';
import * as http from 'http';
import { getExpressSpans } from './utils';
import { ExpressRequestHookInformation } from '../src/types';
import { getTestSpans } from 'opentelemetry-instrumentation-testing-utils';
describe('opentelemetry-express', () => {
let app: express.Application;
before(() => {
instrumentation.enable();
httpInstrumentation.enable();
app = express();
app.use(bodyParser.json());
});
after(() => {
instrumentation.disable();
httpInstrumentation.disable();
});
it('express attributes', (done) => {
const router = express.Router();
app.use('/toto', router);
router.post('/:id', (req, res, next) => {
res.set('res-custom-header-key', 'res-custom-header-val');
return res.json({ hello: 'world' });
});
const server = http.createServer(app);
server.listen(0, async () => {
const port = (server.address() as AddressInfo).port;
const requestData = { 'req-data-key': 'req-data-val' };
try {
await axios.post(
`http://localhost:${port}/toto/tata?req-query-param-key=req-query-param-val`,
requestData,
{
headers: {
'req-custom-header-key': 'req-custom-header-val',
},
}
);
} catch (err) {}
try {
const expressSpans: ReadableSpan[] = getExpressSpans();
expect(expressSpans.length).toBe(1);
const span: ReadableSpan = expressSpans[0];
// Span name
expect(span.name).toBe('POST /toto/:id');
// HTTP Attributes
expect(span.attributes[SemanticAttributes.HTTP_METHOD]).toBeUndefined();
expect(span.attributes[SemanticAttributes.HTTP_TARGET]).toBeUndefined();
expect(span.attributes[SemanticAttributes.HTTP_SCHEME]).toBeUndefined();
expect(span.attributes[SemanticAttributes.HTTP_STATUS_CODE]).toBeUndefined();
expect(span.attributes[SemanticAttributes.HTTP_HOST]).toBeUndefined();
expect(span.attributes[SemanticAttributes.HTTP_FLAVOR]).toBeUndefined();
expect(span.attributes[SemanticAttributes.NET_PEER_IP]).toBeUndefined();
// http span route
const [incomingHttpSpan] = getTestSpans().filter(
(s) => s.kind === SpanKind.SERVER && s.instrumentationLibrary.name.includes('http')
);
expect(incomingHttpSpan.attributes[SemanticAttributes.HTTP_ROUTE]).toMatch('/toto/:id');
done();
} catch (error) {
done(error);
} finally {
server.close();
}
});
});
it('express with http attributes', (done) => {
instrumentation.disable();
instrumentation.setConfig({
includeHttpAttributes: true,
});
instrumentation.enable();
const router = express.Router();
app.use('/toto', router);
router.post('/:id', (req, res, next) => {
res.set('res-custom-header-key', 'res-custom-header-val');
return res.json({ hello: 'world' });
});
const server = http.createServer(app);
server.listen(0, async () => {
const port = (server.address() as AddressInfo).port;
const requestData = { 'req-data-key': 'req-data-val' };
try {
await axios.post(
`http://localhost:${port}/toto/tata?req-query-param-key=req-query-param-val`,
requestData,
{
headers: {
'req-custom-header-key': 'req-custom-header-val',
},
}
);
} catch (err) {}
const expressSpans: ReadableSpan[] = getExpressSpans();
expect(expressSpans.length).toBe(1);
const span: ReadableSpan = expressSpans[0];
// HTTP Attributes
expect(span.attributes[SemanticAttributes.HTTP_METHOD]).toBe('POST');
expect(span.attributes[SemanticAttributes.HTTP_TARGET]).toBe(
'/toto/tata?req-query-param-key=req-query-param-val'
);
expect(span.attributes[SemanticAttributes.HTTP_SCHEME]).toBe('http');
expect(span.attributes[SemanticAttributes.HTTP_STATUS_CODE]).toBe(200);
expect(span.attributes[SemanticAttributes.HTTP_HOST]).toBe(`localhost:${port}`);
expect(span.attributes[SemanticAttributes.HTTP_FLAVOR]).toBe('1.1');
expect(span.attributes[SemanticAttributes.NET_PEER_IP]).toBe('::ffff:127.0.0.1');
server.close();
done();
});
});
it('use empty res.end() to terminate response', (done) => {
app.get('/toto', (req, res, next) => {
res.end();
});
const server = http.createServer(app);
server.listen(0, async () => {
const port = (server.address() as AddressInfo).port;
try {
await axios.get(`http://localhost:${port}/toto`);
} catch (err) {}
const expressSpans: ReadableSpan[] = getExpressSpans();
expect(expressSpans.length).toBe(1);
server.close();
done();
});
});
it('mount app', (done) => {
const subApp = express();
subApp.get('/sub-app', (req, res) => res.end());
app.use('/top-level-app', subApp);
const server = http.createServer(app);
server.listen(0, async () => {
const port = (server.address() as AddressInfo).port;
try {
await axios.get(`http://localhost:${port}/top-level-app/sub-app`);
} catch (err) {}
const expressSpans: ReadableSpan[] = getExpressSpans();
expect(expressSpans.length).toBe(1);
server.close();
done();
});
});
it('should record exceptions as span events', async () => {
app.get('/throws-exception', (req, res, next) => {
next(new Error('internal exception'));
});
const server = http.createServer(app);
await new Promise<void>((resolve) => server.listen(0, () => resolve()));
const port = (server.address() as AddressInfo).port;
try {
await axios.get(`http://localhost:${port}/throws-exception`);
} catch (err) {
// we expect 500
}
const expressSpans: ReadableSpan[] = getExpressSpans();
expect(expressSpans.length).toBe(1);
const span: ReadableSpan = expressSpans[0];
expect(span.events?.length).toEqual(1);
const [event] = span.events;
expect(event).toMatchObject({
name: 'exception',
attributes: {
'exception.type': 'Error',
'exception.message': 'internal exception',
},
});
server.close();
});
it('should record multiple exceptions', async () => {
app.get('/throws-exception', (req, res, next) => {
next(new Error('internal exception'));
});
app.use((err, req, res, next) => {
next(new Error('error-handling middleware exception'));
});
const server = http.createServer(app);
await new Promise<void>((resolve) => server.listen(0, () => resolve()));
const port = (server.address() as AddressInfo).port;
try {
await axios.get(`http://localhost:${port}/throws-exception`);
} catch (err) {
// we expect 500
}
const expressSpans: ReadableSpan[] = getExpressSpans();
expect(expressSpans.length).toBe(1);
const span: ReadableSpan = expressSpans[0];
expect(span.events?.length).toEqual(2);
const [event1, event2] = span.events;
expect(event1).toMatchObject({
name: 'exception',
attributes: {
'exception.type': 'Error',
'exception.message': 'internal exception',
},
});
expect(event2).toMatchObject({
name: 'exception',
attributes: {
'exception.type': 'Error',
'exception.message': 'error-handling middleware exception',
},
});
server.close();
});
it('requestHook', async () => {
instrumentation.disable();
instrumentation.setConfig({
requestHook: (span, requestInfo: ExpressRequestHookInformation) => {
span.setAttribute('content_type', requestInfo.req.headers['content-type']);
},
});
instrumentation.enable();
app.post('/request-hook', (_req, res) => {
res.sendStatus(200);
});
const server = http.createServer(app);
await new Promise<void>((resolve) => server.listen(0, () => resolve()));
const port = (server.address() as AddressInfo).port;
await axios.post(`http://localhost:${port}/request-hook`, { rick: 'morty' });
const expressSpans: ReadableSpan[] = getExpressSpans();
expect(expressSpans.length).toBe(1);
const span: ReadableSpan = expressSpans[0];
expect(span.attributes['content_type']).toBe('application/json;charset=utf-8');
server.close();
});
}); | the_stack |
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import { Components, registerComponent } from '../../lib/vulcan-lib';
import classNames from 'classnames';
import withUser from '../common/withUser';
import { captureException }from '@sentry/core';
import { isServer } from '../../lib/executionEnvironment';
import { linkIsExcludedFromPreview } from '../linkPreview/HoverPreviewLink';
const styles = (theme: ThemeType): JssStyles => ({
scrollIndicatorWrapper: {
display: "block",
position: "relative",
paddingLeft: 13,
paddingRight: 13,
},
hidden: {
display: "none !important",
},
scrollIndicator: {
position: "absolute",
top: "50%",
marginTop: -28,
cursor: "pointer",
// Scroll arrows use the CSS Triangle hack - see
// https://css-tricks.com/snippets/css/css-triangle/ for a full explanation
borderTop: "20px solid transparent",
borderBottom: "20px solid transparent",
},
scrollIndicatorLeft: {
left: 0,
borderRight: `10px solid ${theme.palette.grey[310]}`,
"&:hover": {
borderRight: `10px solid ${theme.palette.grey[620]}`,
},
},
scrollIndicatorRight: {
right: 0,
borderLeft: `10px solid ${theme.palette.grey[310]}`,
"&:hover": {
borderLeft: `10px solid ${theme.palette.grey[620]}`,
},
},
scrollableLaTeX: {
// Cancel out the margin created by the block elements above and below,
// so that we can convert them into padding and get a larger touch
// target.
// !important to take precedence over .mjx-chtml
marginTop: "-1em !important",
marginBottom: "-1em !important",
paddingTop: "2em !important",
paddingBottom: "2em !important",
// Hide the scrollbar (on browsers that support it) because our scroll
// indicator is better
"-ms-overflow-style": "-ms-autohiding-scrollbar",
"&::-webkit-scrollbar": {
display: "none",
},
scrollbarWidth: "none",
}
});
interface ContentItemBodyProps extends WithStylesProps {
dangerouslySetInnerHTML: { __html: string },
className?: string,
description?: string,
// Only Implemented for Tag Hover Previews
noHoverPreviewPrefetch?: boolean,
}
interface ContentItemBodyState {
updatedElements: boolean,
}
// The body of a post/comment/etc, created by taking server-side-processed HTML
// out of the result of a GraphQL query and adding some decoration to it. In
// particular, if this is the client-side render, adds scroll indicators to
// horizontally-scrolling LaTeX blocks.
//
// This doesn't apply styling (other than for the decorators it adds) because
// it's shared between entity types, which have styling that differs.
//
// Props:
// className <string>: Name of an additional CSS class to apply to this element.
// dangerouslySetInnerHTML: Follows the same convention as
// dangerouslySetInnerHTML on a div, ie, you set the HTML content of this
// by passing dangerouslySetInnerHTML={{__html: "<p>foo</p>"}}.
// description: (Optional) A human-readable string describing where this
// content came from. Used in error logging only, not displayed to users.
class ContentItemBody extends Component<ContentItemBodyProps,ContentItemBodyState> {
bodyRef: any
replacedElements: Array<any>
constructor(props: ContentItemBodyProps) {
super(props);
this.bodyRef = React.createRef();
this.replacedElements = [];
this.state = {updatedElements:false}
}
componentDidMount () {
this.applyLocalModifications();
}
componentDidUpdate(prevProps) {
if (prevProps.dangerouslySetInnerHTML?.__html !== this.props.dangerouslySetInnerHTML?.__html) {
this.replacedElements = [];
this.applyLocalModifications();
}
}
applyLocalModifications() {
try {
this.markScrollableLaTeX();
this.markHoverableLinks();
this.markElicitBlocks();
this.setState({updatedElements: true})
} catch(e) {
// Don't let exceptions escape from here. This ensures that, if client-side
// modifications crash, the post/comment text still remains visible.
captureException(e);
// eslint-disable-next-line no-console
console.error(e);
}
}
render() {
return (<React.Fragment>
<div
className={this.props.className}
ref={this.bodyRef}
dangerouslySetInnerHTML={this.props.dangerouslySetInnerHTML}
/>
{
this.replacedElements.map(replaced => {
return ReactDOM.createPortal(
replaced.replacementElement,
replaced.container
);
})
}
</React.Fragment>);
}
// Given an HTMLCollection, return an array of the elements inside it. Note
// that this is covering for a browser-specific incompatibility: in Edge 17
// and earlier, HTMLCollection has `length` and `item` but isn't iterable.
htmlCollectionToArray(collection) {
if (!collection) return [];
let ret: Array<any> = [];
for (let i=0; i<collection.length; i++)
ret.push(collection.item(i));
return ret;
}
// Find LaTeX elements inside the body, check whether they're wide enough to
// need horizontal scroll, and if so, give them
// `classes.hasHorizontalScroll`. 1They will have a scrollbar regardless;
// this gives them additional styling which makes the scrollability
// obvious, if your browser hides scrollbars like Mac does and most
// mobile browsers do).
// This is client-only because it requires measuring widths.
markScrollableLaTeX = () => {
const { classes } = this.props;
if(!isServer && this.bodyRef && this.bodyRef.current) {
let latexBlocks = this.htmlCollectionToArray(this.bodyRef.current.getElementsByClassName("mjx-chtml"));
for(let i=0; i<latexBlocks.length; i++) {
let latexBlock = latexBlocks[i];
if (!latexBlock.classList.contains("MJXc-display")) {
// Skip inline LaTeX
continue;
}
latexBlock.className += " " + classes.scrollableLaTeX;
if(latexBlock.scrollWidth > latexBlock.clientWidth) {
this.addHorizontalScrollIndicators(latexBlock);
}
}
}
}
// Given an HTML block element which has horizontal scroll, give it scroll
// indicators: left and right arrows that tell you scrolling is possible.
// That is, wrap it in this DOM structure and replce it in-place in the
// browser DOM:
//
// <div class={classes.scrollIndicatorWrapper}>
// <div class={classes.scrollIndicator,classes.scrollIndicatorLeft}/>
// {block}
// <div class={classes.scrollIndicator,classes.scrollIndicatorRight}/>
// </div>
//
// Instead of doing it with React, we do it with legacy DOM APIs, because
// this needs to work when we take some raw non-REACT HTML from the database,
// rather than working in a normal React-component-tree context.
//
// Attaches a handler to `block.onscrol` which shows and hides the scroll
// indicators when it's scrolled all the way.
addHorizontalScrollIndicators = (block) => {
const { classes } = this.props;
// If already wrapped, don't re-wrap (so this is idempotent).
if (block.parentElement && block.parentElement.className === classes.scrollIndicatorWrapper)
return;
const scrollIndicatorWrapper = document.createElement("div");
scrollIndicatorWrapper.className = classes.scrollIndicatorWrapper;
const scrollIndicatorLeft = document.createElement("div");
scrollIndicatorWrapper.append(scrollIndicatorLeft);
block.parentElement.insertBefore(scrollIndicatorWrapper, block);
block.remove();
scrollIndicatorWrapper.append(block);
const scrollIndicatorRight = document.createElement("div");
scrollIndicatorWrapper.append(scrollIndicatorRight);
// Update scroll indicator classes, either for the first time (when newly
// constructed) or when we've scrolled. We apply `classes.hidden` when the
// scroll position is within 1px (exclusive) of an edge, rather than when
// it's exactly at an edge, because in at least one tested browser (Chrome
// on Windows) scrolling actually stopped a fraction of a pixel short of
// where `scrollWidth` said it would.
const updateScrollIndicatorClasses = () => {
scrollIndicatorLeft.className = classNames(
classes.scrollIndicator, classes.scrollIndicatorLeft,
{ [classes.hidden]: block.scrollLeft < 1 });
scrollIndicatorRight.className = classNames(
classes.scrollIndicator, classes.scrollIndicatorRight,
{ [classes.hidden]: block.scrollLeft+block.clientWidth+1 > block.scrollWidth });
}
scrollIndicatorLeft.onclick = (ev) => {
block.scrollLeft = Math.max(block.scrollLeft-block.clientWidth, 0);
};
scrollIndicatorRight.onclick = (ev) => {
block.scrollLeft += Math.min(block.scrollLeft+block.clientWidth, block.scrollWidth-block.clientWidth);
};
updateScrollIndicatorClasses();
block.onscroll = (ev) => updateScrollIndicatorClasses();
};
markHoverableLinks = () => {
if(this.bodyRef?.current) {
const linkTags = this.htmlCollectionToArray(this.bodyRef.current.getElementsByTagName("a"));
for (let linkTag of linkTags) {
const tagContentsHTML = linkTag.innerHTML;
const href = linkTag.getAttribute("href");
if (linkIsExcludedFromPreview(href))
continue;
const id = linkTag.getAttribute("id");
const rel = linkTag.getAttribute("rel")
const replacementElement = <Components.HoverPreviewLink href={href} innerHTML={tagContentsHTML} contentSourceDescription={this.props.description} id={id} rel={rel} noPrefetch={this.props.noHoverPreviewPrefetch}/>
this.replaceElement(linkTag, replacementElement);
}
}
}
markElicitBlocks = () => {
if(this.bodyRef?.current) {
const elicitBlocks = this.htmlCollectionToArray(this.bodyRef.current.getElementsByClassName("elicit-binary-prediction"));
for (const elicitBlock of elicitBlocks) {
if (elicitBlock.dataset?.elicitId) {
const replacementElement = <Components.ElicitBlock questionId={elicitBlock.dataset.elicitId}/>
this.replaceElement(elicitBlock, replacementElement)
}
}
}
}
replaceElement = (replacedElement, replacementElement) => {
const replacementContainer = document.createElement("span");
this.replacedElements.push({
replacementElement: replacementElement,
container: replacementContainer,
});
replacedElement.parentElement.replaceChild(replacementContainer, replacedElement);
}
}
const ContentItemBodyComponent = registerComponent('ContentItemBody', ContentItemBody, {
styles, hocs: [withUser]
});
declare global {
interface ComponentTypes {
ContentItemBody: typeof ContentItemBodyComponent
}
} | the_stack |
import { Config, ConfigParameters, getConfig, AuthorizationParameters, DeepPartial } from '../../src/auth0-session';
const defaultConfig = {
secret: '__test_session_secret__',
clientID: '__test_client_id__',
issuerBaseURL: 'https://op.example.com',
baseURL: 'https://example.org',
routes: {
callback: '/callback'
}
};
const validateAuthorizationParams = (authorizationParams: DeepPartial<AuthorizationParameters>): Config =>
getConfig({ ...defaultConfig, authorizationParams });
describe('Config', () => {
it('should get config for default config', () => {
const config = getConfig(defaultConfig);
expect(config).toMatchObject({
authorizationParams: {
response_type: 'id_token',
response_mode: 'form_post',
scope: 'openid profile email'
}
});
});
it('should throw with empty config', () => {
expect(getConfig).toThrow();
});
it('should get config for response_type=code', () => {
const config = getConfig({
...defaultConfig,
clientSecret: '__test_client_secret__',
authorizationParams: {
response_type: 'code'
}
});
expect(config).toMatchObject({
authorizationParams: {
response_type: 'code',
scope: 'openid profile email'
}
});
});
it('should require a fully qualified URL for issuer', () => {
const config = {
...defaultConfig,
issuerBaseURL: 'www.example.com'
};
expect(() => getConfig(config)).toThrowError(new TypeError('"issuerBaseURL" must be a valid uri'));
});
it('should set idpLogout to true when auth0Logout is true', () => {
const config = getConfig({
...defaultConfig,
auth0Logout: true
});
expect(config).toMatchObject({
auth0Logout: true,
idpLogout: true
});
});
it('auth0Logout and idpLogout should default to false', () => {
const config = getConfig(defaultConfig);
expect(config).toMatchObject({
auth0Logout: false,
idpLogout: false
});
});
it('should not set auth0Logout to true when idpLogout is true', () => {
const config = getConfig({
...defaultConfig,
idpLogout: true
});
expect(config).toMatchObject({
auth0Logout: false,
idpLogout: true
});
});
it('should set default route paths', () => {
const config = getConfig(defaultConfig);
expect(config.routes).toMatchObject({
callback: '/callback'
});
});
it('should set custom route paths', () => {
const config = getConfig({
...defaultConfig,
routes: {
callback: '/custom-callback',
postLogoutRedirect: '/custom-logout'
}
});
expect(config.routes).toMatchObject({
callback: '/custom-callback',
postLogoutRedirect: '/custom-logout'
});
});
it('should set default app session configuration', () => {
const config = getConfig(defaultConfig);
expect(config.session).toMatchObject({
rollingDuration: 86400,
name: 'appSession',
cookie: {
sameSite: 'lax',
httpOnly: true,
transient: false
}
});
});
it('should set custom cookie configuration', () => {
const config = getConfig({
...defaultConfig,
secret: ['__test_session_secret_1__', '__test_session_secret_2__'],
session: {
name: '__test_custom_session_name__',
rollingDuration: 1234567890,
cookie: {
domain: '__test_custom_domain__',
transient: true,
httpOnly: false,
secure: true,
sameSite: 'strict'
}
}
});
expect(config).toMatchObject({
secret: ['__test_session_secret_1__', '__test_session_secret_2__'],
session: {
name: '__test_custom_session_name__',
rollingDuration: 1234567890,
absoluteDuration: 604800,
rolling: true,
cookie: {
domain: '__test_custom_domain__',
transient: true,
httpOnly: false,
secure: true,
sameSite: 'strict'
}
}
});
});
it('should fail when the baseURL is invalid', function () {
expect(() =>
getConfig({
...defaultConfig,
baseURL: '__invalid_url__'
})
).toThrowError('"baseURL" must be a valid uri');
});
it('should fail when the clientID is not provided', function () {
expect(() =>
getConfig({
...defaultConfig,
clientID: undefined
})
).toThrowError('"clientID" is required');
});
it('should fail when the baseURL is not provided', function () {
expect(() =>
getConfig({
...defaultConfig,
baseURL: undefined
})
).toThrowError('"baseURL" is required');
});
it('should fail when the secret is not provided', function () {
expect(() =>
getConfig({
...defaultConfig,
secret: undefined
})
).toThrowError('"secret" is required');
});
it('should fail when app session length is not an integer', function () {
expect(() =>
getConfig({
...defaultConfig,
session: {
rollingDuration: 3.14159
}
})
).toThrow('"session.rollingDuration" must be an integer');
});
it('should fail when rollingDuration is defined and rolling is false', function () {
expect(() =>
getConfig({
...defaultConfig,
session: {
rolling: false,
rollingDuration: 100
}
})
).toThrow('"session.rollingDuration" must be false when "session.rolling" is disabled');
});
it('should fail when rollingDuration is not defined and rolling is true', function () {
expect(() =>
getConfig({
...defaultConfig,
session: {
rolling: true,
rollingDuration: (false as unknown) as undefined // testing invalid configuration
}
})
).toThrow('"session.rollingDuration" must be provided an integer value when "session.rolling" is true');
});
it('should fail when absoluteDuration is not defined and rolling is false', function () {
expect(() =>
getConfig({
...defaultConfig,
session: {
rolling: false,
absoluteDuration: false
}
})
).toThrowError('"session.absoluteDuration" must be provided an integer value when "session.rolling" is false');
});
it('should fail when app session secret is invalid', function () {
expect(() =>
getConfig({
...defaultConfig,
secret: ({ key: '__test_session_secret__' } as unknown) as string // testing invalid configuration
})
).toThrow('"secret" must be one of [string, binary, array]');
});
it('should fail when app session cookie httpOnly is not a boolean', function () {
expect(() =>
getConfig({
...defaultConfig,
session: {
cookie: {
httpOnly: ('__invalid_httponly__' as unknown) as boolean // testing invalid configuration
}
}
})
).toThrowError('"session.cookie.httpOnly" must be a boolean');
});
it('should fail when app session cookie secure is not a boolean', function () {
expect(() =>
getConfig({
...defaultConfig,
secret: '__test_session_secret__',
session: {
cookie: {
secure: ('__invalid_secure__' as unknown) as boolean // testing invalid configuration
}
}
})
).toThrowError('"session.cookie.secure" must be a boolean');
});
it('should fail when app session cookie sameSite is invalid', function () {
expect(() =>
getConfig({
...defaultConfig,
secret: '__test_session_secret__',
session: {
cookie: {
sameSite: ('__invalid_samesite__' as unknown) as any // testing invalid configuration
}
}
})
).toThrowError('"session.cookie.sameSite" must be one of [lax, strict, none]');
});
it('should fail when app session cookie domain is invalid', function () {
expect(() =>
getConfig({
...defaultConfig,
secret: '__test_session_secret__',
session: {
cookie: {
domain: (false as unknown) as string // testing invalid configuration
}
}
})
).toThrowError('"session.cookie.domain" must be a string');
});
it("shouldn't allow a secret of less than 8 chars", () => {
expect(() => getConfig({ ...defaultConfig, secret: 'short' })).toThrowError(
new TypeError('"secret" does not match any of the allowed types')
);
expect(() => getConfig({ ...defaultConfig, secret: ['short', 'too'] })).toThrowError(
new TypeError('"secret[0]" does not match any of the allowed types')
);
expect(() => getConfig({ ...defaultConfig, secret: Buffer.from('short').toString() })).toThrowError(
new TypeError('"secret" does not match any of the allowed types')
);
});
it("shouldn't allow code flow without clientSecret", () => {
expect(() =>
getConfig({
...defaultConfig,
authorizationParams: {
response_type: 'code'
}
})
).toThrowError(new TypeError('"clientSecret" is required for a response_type that includes code'));
});
it("shouldn't allow hybrid flow without clientSecret", () => {
expect(() =>
getConfig({
...defaultConfig,
authorizationParams: {
response_type: 'code id_token'
}
})
).toThrowError(new TypeError('"clientSecret" is required for a response_type that includes code'));
});
it('should not allow "none" for idTokenSigningAlg', () => {
const config = (idTokenSigningAlg: string) => (): Config =>
getConfig({
...defaultConfig,
idTokenSigningAlg
});
const expected = '"idTokenSigningAlg" contains an invalid value';
expect(config('none')).toThrowError(new TypeError(expected));
expect(config('NONE')).toThrowError(new TypeError(expected));
expect(config('noNE')).toThrowError(new TypeError(expected));
});
it('should require clientSecret for ID tokens with HMAC based algorithms', () => {
expect(() =>
getConfig({
...defaultConfig,
idTokenSigningAlg: 'HS256',
authorizationParams: {
response_type: 'id_token'
}
})
).toThrowError(new TypeError('"clientSecret" is required for ID tokens with HMAC based algorithms'));
});
it('should require clientSecret for ID tokens in hybrid flow with HMAC based algorithms', () => {
expect(() =>
getConfig({
...defaultConfig,
idTokenSigningAlg: 'HS256',
authorizationParams: {
response_type: 'code id_token'
}
})
).toThrowError(new TypeError('"clientSecret" is required for ID tokens with HMAC based algorithms'));
});
it('should require clientSecret for ID tokens in code flow with HMAC based algorithms', () => {
expect(() =>
getConfig({
...defaultConfig,
idTokenSigningAlg: 'HS256',
authorizationParams: {
response_type: 'code'
}
})
).toThrowError(new TypeError('"clientSecret" is required for ID tokens with HMAC based algorithms'));
});
it('should allow empty auth params', () => {
expect(validateAuthorizationParams).not.toThrow();
expect(() => validateAuthorizationParams({})).not.toThrow();
});
it('should not allow empty scope', () => {
expect(() => validateAuthorizationParams({ scope: (null as unknown) as undefined })).toThrowError(
new TypeError('"authorizationParams.scope" must be a string')
);
expect(() => validateAuthorizationParams({ scope: '' })).toThrowError(
new TypeError('"authorizationParams.scope" is not allowed to be empty')
);
});
it('should not allow scope without openid', () => {
expect(() => validateAuthorizationParams({ scope: 'profile email' })).toThrowError(
new TypeError('"authorizationParams.scope" with value "profile email" fails to match the contains openid pattern')
);
});
it('should allow scope with openid', () => {
expect(() => validateAuthorizationParams({ scope: 'openid read:users' })).not.toThrow();
expect(() => validateAuthorizationParams({ scope: 'read:users openid' })).not.toThrow();
expect(() => validateAuthorizationParams({ scope: 'read:users openid profile email' })).not.toThrow();
});
it('should not allow empty response_type', () => {
expect(() => validateAuthorizationParams({ response_type: (null as unknown) as undefined })).toThrowError(
new TypeError('"authorizationParams.response_type" must be one of [id_token, code id_token, code]')
);
expect(() => validateAuthorizationParams({ response_type: ('' as unknown) as undefined })).toThrowError(
new TypeError('"authorizationParams.response_type" must be one of [id_token, code id_token, code]')
);
});
it('should not allow invalid response_types', () => {
expect(() => validateAuthorizationParams({ response_type: 'foo' as 'code' })).toThrowError(
new TypeError('"authorizationParams.response_type" must be one of [id_token, code id_token, code]')
);
expect(() => validateAuthorizationParams({ response_type: 'foo id_token' as 'code' })).toThrowError(
new TypeError('"authorizationParams.response_type" must be one of [id_token, code id_token, code]')
);
expect(() => validateAuthorizationParams({ response_type: 'id_token code' as 'code' })).toThrowError(
new TypeError('"authorizationParams.response_type" must be one of [id_token, code id_token, code]')
);
});
it('should allow valid response_types', () => {
const config = (authorizationParams: DeepPartial<AuthorizationParameters>): ConfigParameters => ({
...defaultConfig,
clientSecret: 'foo',
authorizationParams
});
expect(() => validateAuthorizationParams({ response_type: 'id_token' })).not.toThrow();
expect(() => config({ response_type: 'code id_token' })).not.toThrow();
expect(() => config({ response_type: 'code' })).not.toThrow();
});
it('should not allow empty response_mode', () => {
expect(() => validateAuthorizationParams({ response_mode: (null as unknown) as undefined })).toThrowError(
new TypeError('"authorizationParams.response_mode" must be [form_post]')
);
expect(() => validateAuthorizationParams({ response_mode: ('' as unknown) as undefined })).toThrowError(
new TypeError('"authorizationParams.response_mode" must be [form_post]')
);
expect(() =>
validateAuthorizationParams({
response_type: 'code',
response_mode: ('' as unknown) as undefined
})
).toThrowError(new TypeError('"authorizationParams.response_mode" must be one of [query, form_post]'));
});
it('should not allow response_type id_token and response_mode query', () => {
expect(() =>
validateAuthorizationParams({
response_type: 'id_token',
response_mode: 'query'
})
).toThrowError(new TypeError('"authorizationParams.response_mode" must be [form_post]'));
expect(() =>
validateAuthorizationParams({
response_type: 'code id_token',
response_mode: 'query'
})
).toThrowError(new TypeError('"authorizationParams.response_mode" must be [form_post]'));
});
it('should allow valid response_type response_mode combinations', () => {
const config = (authorizationParams: DeepPartial<AuthorizationParameters>): ConfigParameters => ({
...defaultConfig,
clientSecret: 'foo',
authorizationParams
});
expect(() => config({ response_type: 'code', response_mode: 'query' })).not.toThrow();
expect(() => config({ response_type: 'code', response_mode: 'form_post' })).not.toThrow();
expect(() =>
validateAuthorizationParams({
response_type: 'id_token',
response_mode: 'form_post'
})
).not.toThrowError();
expect(() => config({ response_type: 'code id_token', response_mode: 'form_post' })).not.toThrow();
});
}); | the_stack |
import * as ipaddr from 'ipaddr.js';
import {Base64} from 'js-base64';
import * as punycode from 'punycode';
// Custom error base class
export class ShadowsocksConfigError extends Error {
constructor(message: string) {
super(message); // 'Error' breaks prototype chain here if this is transpiled to es5
Object.setPrototypeOf(this, new.target.prototype); // restore prototype chain
this.name = new.target.name;
}
}
export class InvalidConfigField extends ShadowsocksConfigError {}
export class InvalidUri extends ShadowsocksConfigError {}
// Self-validating/normalizing config data types implement this ValidatedConfigField interface.
// Constructors take some data, validate, normalize, and store if valid, or throw otherwise.
export abstract class ValidatedConfigField {}
function throwErrorForInvalidField(name: string, value: {}, reason?: string) {
throw new InvalidConfigField(`Invalid ${name}: ${value} ${reason || ''}`);
}
export class Host extends ValidatedConfigField {
public static HOSTNAME_PATTERN = /^[A-z0-9]+[A-z0-9_.-]*$/;
public readonly data: string;
public readonly isIPv4: boolean = false;
public readonly isIPv6: boolean = false;
public readonly isHostname: boolean = false;
constructor(host: Host | string) {
super();
if (!host) {
throwErrorForInvalidField('host', host);
}
if (host instanceof Host) {
host = host.data;
}
if (ipaddr.isValid(host)) {
const ip = ipaddr.parse(host);
this.isIPv4 = ip.kind() === 'ipv4';
this.isIPv6 = ip.kind() === 'ipv6';
// Previous versions of outline-ShadowsocksConfig only accept
// IPv6 in normalized (expanded) form, so we normalize the
// input here to ensure that access keys remain compatible.
host = ip.toNormalizedString();
} else {
host = punycode.toASCII(host) as string;
this.isHostname = Host.HOSTNAME_PATTERN.test(host);
if (!this.isHostname) {
throwErrorForInvalidField('host', host);
}
}
this.data = host;
}
}
export class Port extends ValidatedConfigField {
public static readonly PATTERN = /^[0-9]{1,5}$/;
public readonly data: number;
constructor(port: Port | string | number) {
super();
if (port instanceof Port) {
port = port.data;
}
if (typeof port === 'number') {
// Stringify in case negative or floating point -> the regex test below will catch.
port = port.toString();
}
if (!Port.PATTERN.test(port)) {
throwErrorForInvalidField('port', port);
}
// Could exceed the maximum port number, so convert to Number to check. Could also have leading
// zeros. Converting to Number drops those, so we get normalization for free. :)
port = Number(port);
if (port > 65535) {
throwErrorForInvalidField('port', port);
}
this.data = port;
}
}
// A method value must exactly match an element in the set of known ciphers.
// ref: https://github.com/shadowsocks/shadowsocks-libev/blob/10a2d3e3/completions/bash/ss-redir#L5
export const METHODS = new Set([
'rc4-md5',
'aes-128-gcm',
'aes-192-gcm',
'aes-256-gcm',
'aes-128-cfb',
'aes-192-cfb',
'aes-256-cfb',
'aes-128-ctr',
'aes-192-ctr',
'aes-256-ctr',
'camellia-128-cfb',
'camellia-192-cfb',
'camellia-256-cfb',
'bf-cfb',
'chacha20-ietf-poly1305',
'salsa20',
'chacha20',
'chacha20-ietf',
'xchacha20-ietf-poly1305',
]);
export class Method extends ValidatedConfigField {
public readonly data: string;
constructor(method: Method | string) {
super();
if (method instanceof Method) {
method = method.data;
}
if (!METHODS.has(method)) {
throwErrorForInvalidField('method', method);
}
this.data = method;
}
}
export class Password extends ValidatedConfigField {
public readonly data: string;
constructor(password: Password | string) {
super();
this.data = password instanceof Password ? password.data : password;
}
}
export class Tag extends ValidatedConfigField {
public readonly data: string;
constructor(tag: Tag | string = '') {
super();
this.data = tag instanceof Tag ? tag.data : tag;
}
}
export interface Config {
host: Host;
port: Port;
method: Method;
password: Password;
tag: Tag;
// Any additional configuration (e.g. `timeout`, SIP003 `plugin`, etc.) may be stored here.
extra: {[key: string]: string};
}
// tslint:disable-next-line:no-any
export function makeConfig(input: {[key: string]: any}): Config {
// Use "!" for the required fields to tell tsc that we handle undefined in the
// ValidatedConfigFields we call; tsc can't figure that out otherwise.
const config = {
host: new Host(input.host!),
port: new Port(input.port!),
method: new Method(input.method!),
password: new Password(input.password!),
tag: new Tag(input.tag), // input.tag might be undefined but Tag() handles that fine.
extra: {} as {[key: string]: string},
};
// Put any remaining fields in `input` into `config.extra`.
for (const key of Object.keys(input)) {
if (!/^(host|port|method|password|tag)$/.test(key)) {
config.extra[key] = input[key] && input[key].toString();
}
}
return config;
}
export const SHADOWSOCKS_URI = {
PROTOCOL: 'ss:',
getUriFormattedHost: (host: Host) => {
return host.isIPv6 ? `[${host.data}]` : host.data;
},
getHash: (tag: Tag) => {
return tag.data ? `#${encodeURIComponent(tag.data)}` : '';
},
validateProtocol: (uri: string) => {
if (!uri.startsWith(SHADOWSOCKS_URI.PROTOCOL)) {
throw new InvalidUri(`URI must start with "${SHADOWSOCKS_URI.PROTOCOL}"`);
}
},
parse: (uri: string): Config => {
let error: Error | undefined;
for (const uriType of [SIP002_URI, LEGACY_BASE64_URI]) {
try {
return uriType.parse(uri);
} catch (e) {
error = e;
}
}
if (!(error instanceof InvalidUri)) {
const originalErrorName = error!.name! || '(Unnamed Error)';
const originalErrorMessage = error!.message! || '(no error message provided)';
const originalErrorString = `${originalErrorName}: ${originalErrorMessage}`;
const newErrorMessage = `Invalid input: ${originalErrorString}`;
error = new InvalidUri(newErrorMessage);
}
throw error;
},
};
// Ref: https://shadowsocks.org/en/config/quick-guide.html
export const LEGACY_BASE64_URI = {
parse: (uri: string): Config => {
SHADOWSOCKS_URI.validateProtocol(uri);
const hashIndex = uri.indexOf('#');
const hasTag = hashIndex !== -1;
const b64EndIndex = hasTag ? hashIndex : uri.length;
const tagStartIndex = hasTag ? hashIndex + 1 : uri.length;
const tag = new Tag(decodeURIComponent(uri.substring(tagStartIndex)));
const b64EncodedData = uri.substring('ss://'.length, b64EndIndex);
const b64DecodedData = Base64.decode(b64EncodedData);
const atSignIndex = b64DecodedData.lastIndexOf('@');
if (atSignIndex === -1) {
throw new InvalidUri(`Missing "@"`);
}
const methodAndPassword = b64DecodedData.substring(0, atSignIndex);
const methodEndIndex = methodAndPassword.indexOf(':');
if (methodEndIndex === -1) {
throw new InvalidUri(`Missing password`);
}
const methodString = methodAndPassword.substring(0, methodEndIndex);
const method = new Method(methodString);
const passwordStartIndex = methodEndIndex + 1;
const passwordString = methodAndPassword.substring(passwordStartIndex);
const password = new Password(passwordString);
const hostStartIndex = atSignIndex + 1;
const hostAndPort = b64DecodedData.substring(hostStartIndex);
const hostEndIndex = hostAndPort.lastIndexOf(':');
if (hostEndIndex === -1) {
throw new InvalidUri(`Missing port`);
}
const uriFormattedHost = hostAndPort.substring(0, hostEndIndex);
let host: Host;
try {
host = new Host(uriFormattedHost);
} catch (_) {
// Could be IPv6 host formatted with surrounding brackets, so try stripping first and last
// characters. If this throws, give up and let the exception propagate.
host = new Host(uriFormattedHost.substring(1, uriFormattedHost.length - 1));
}
const portStartIndex = hostEndIndex + 1;
const portString = hostAndPort.substring(portStartIndex);
const port = new Port(portString);
const extra = {} as {[key: string]: string}; // empty because LegacyBase64Uri can't hold extra
return {method, password, host, port, tag, extra};
},
stringify: (config: Config) => {
const {host, port, method, password, tag} = config;
const hash = SHADOWSOCKS_URI.getHash(tag);
const data = `${method.data}:${password.data}@${host.data}:${port.data}`;
let b64EncodedData = Base64.encode(data);
// Remove "=" padding
while (b64EncodedData.slice(-1) === '=') {
b64EncodedData = b64EncodedData.slice(0, -1);
}
return `ss://${b64EncodedData}${hash}`;
},
};
// Ref: https://shadowsocks.org/en/spec/SIP002-URI-Scheme.html
export const SIP002_URI = {
parse: (uri: string): Config => {
SHADOWSOCKS_URI.validateProtocol(uri);
// Can use built-in URL parser for expedience. Just have to replace "ss" with "http" to ensure
// correct results, otherwise browsers like Safari fail to parse it.
const inputForUrlParser = `http${uri.substring(2)}`;
// The built-in URL parser throws as desired when given URIs with invalid syntax.
const urlParserResult = new URL(inputForUrlParser);
const uriFormattedHost = urlParserResult.hostname;
// URI-formatted IPv6 hostnames have surrounding brackets.
const last = uriFormattedHost.length - 1;
const brackets = uriFormattedHost[0] === '[' && uriFormattedHost[last] === ']';
const hostString = brackets ? uriFormattedHost.substring(1, last) : uriFormattedHost;
const host = new Host(hostString);
let parsedPort = urlParserResult.port;
if (!parsedPort && uri.match(/:80($|\/)/g)) {
// The default URL parser fails to recognize the default port (80) when the URI being parsed
// is HTTP. Check if the port is present at the end of the string or before the parameters.
parsedPort = '80';
}
const port = new Port(parsedPort);
const tag = new Tag(decodeURIComponent(urlParserResult.hash.substring(1)));
const b64EncodedUserInfo = urlParserResult.username.replace(/%3D/g, '=');
// base64.decode throws as desired when given invalid base64 input.
const b64DecodedUserInfo = Base64.decode(b64EncodedUserInfo);
const colonIdx = b64DecodedUserInfo.indexOf(':');
if (colonIdx === -1) {
throw new InvalidUri(`Missing password`);
}
const methodString = b64DecodedUserInfo.substring(0, colonIdx);
const method = new Method(methodString);
const passwordString = b64DecodedUserInfo.substring(colonIdx + 1);
const password = new Password(passwordString);
const queryParams = urlParserResult.search.substring(1).split('&');
const extra = {} as {[key: string]: string};
for (const pair of queryParams) {
const [key, value] = pair.split('=', 2);
if (!key) continue;
extra[key] = decodeURIComponent(value || '');
}
return {method, password, host, port, tag, extra};
},
stringify: (config: Config) => {
const {host, port, method, password, tag, extra} = config;
const userInfo = Base64.encodeURI(`${method.data}:${password.data}`);
const uriHost = SHADOWSOCKS_URI.getUriFormattedHost(host);
const hash = SHADOWSOCKS_URI.getHash(tag);
let queryString = '';
for (const key in extra) {
if (!key) continue;
queryString += (queryString ? '&' : '?') + `${key}=${encodeURIComponent(extra[key])}`;
}
return `ss://${userInfo}@${uriHost}:${port.data}/${queryString}${hash}`;
},
};
export interface ConfigFetchParams {
// URL endpoint to retrieve a Shadowsocks configuration.
readonly location: string;
// Server cerficate hash.
readonly certFingerprint?: string;
// HTTP method to use when accessing `url`.
readonly httpMethod?: string;
}
export const ONLINE_CONFIG_PROTOCOL = 'ssconf';
// Parses access parameters to retrieve a Shadowsocks proxy config from an
// online config URL. See: https://github.com/shadowsocks/shadowsocks-org/issues/89
export function parseOnlineConfigUrl(url: string): ConfigFetchParams {
if (!url || !url.startsWith(`${ONLINE_CONFIG_PROTOCOL}:`)) {
throw new InvalidUri(`URI protocol must be "${ONLINE_CONFIG_PROTOCOL}"`);
}
// Replace the protocol "ssconf" with "https" to ensure correct results,
// otherwise some Safari versions fail to parse it.
const inputForUrlParser = url.replace(new RegExp(`^${ONLINE_CONFIG_PROTOCOL}`), 'https');
// The built-in URL parser throws as desired when given URIs with invalid syntax.
const urlParserResult = new URL(inputForUrlParser);
// Use ValidatedConfigFields subclasses (Host, Port, Tag) to throw on validation failure.
const uriFormattedHost = urlParserResult.hostname;
let host: Host;
try {
host = new Host(uriFormattedHost);
} catch (_) {
// Could be IPv6 host formatted with surrounding brackets, so try stripping first and last
// characters. If this throws, give up and let the exception propagate.
host = new Host(uriFormattedHost.substring(1, uriFormattedHost.length - 1));
}
// The default URL parser fails to recognize the default HTTPs port (443).
const port = new Port(urlParserResult.port || '443');
// Parse extra parameters from the tag, which has the URL search parameters format.
const tag = new Tag(urlParserResult.hash.substring(1));
const params = new URLSearchParams(tag.data);
return {
// Build the access URL with the parsed parameters Exclude the query string and tag.
location: `https://${uriFormattedHost}:${port.data}${urlParserResult.pathname}`,
certFingerprint: params.get('certFp') || undefined,
httpMethod: params.get('httpMethod') || undefined
};
} | the_stack |
function isNullOrUndefined(object: any): object is null | undefined {
return object === undefined || object === null
}
/**
* 操作类型
*/
enum ActionType {
forEach = 'forEach',
filter = 'filter',
map = 'map',
flatMap = 'flatMap',
sort = 'sort',
reduce = 'reduce',
reduceRight = 'reduceRight',
findIndex = 'findIndex',
find = 'find',
every = 'every',
some = 'some',
parallel = 'parallel',
serial = 'serial',
}
/**
* 保存高阶函数传入的异步操作
* @field 异步操作的类型
* @field 异步操作
*/
class Action {
public static Type = ActionType
constructor(public readonly type: ActionType, public readonly args: any[]) {
this.type = type
this.args = args
}
}
/**
* 异步的 reduce 回调函数类型
*/
type AsyncArrayReduceCallback<T, R, IArray> = (
res: R,
item: T,
index: number,
arr: IArray,
) => Promise<R>
/**
* 异步的数组一般迭代类型
*/
type AsyncArrayCallback<T, R, IArray> = (
item: T,
index: number,
arr: IArray,
) => Promise<R>
/**
* 抽象异步数组,实现了一些公共的函数
*/
abstract class InnerBaseAsyncArray<T> {
/**
* 内部的数组
*/
protected _arr: T[]
/**
* 构造函数
* @param args 数组初始元素
*/
constructor(args: T[] = []) {
this._arr = args
}
/**
* 异步的 forEach
* @param fn 异步迭代函数
*/
public abstract forEach(fn: AsyncArrayCallback<T, void, any>): Promise<void>
/**
* 异步的 filter
* @param fn 异步过滤函数
* @returns 过滤后的新数组
*/
public abstract filter(fn: AsyncArrayCallback<T, boolean, any>): Promise<any>
/**
* 异步的 map
* @param fn 异步映射函数
* @returns 经过映射产生的新的异步数组
*/
public abstract map<R>(fn: AsyncArrayCallback<T, R, any>): Promise<any>
/**
* 异步的 flatMap
* @param fn 异步映射函数,产生一个新的数组
* @returns 压平一层的数组
*/
public abstract flatMap<R>(fn: AsyncArrayCallback<T, R[], any>): Promise<any>
/**
* 将整个数组排序
* @param fn 比较函数
* @returns 排序后的数组
*/
public async sort(
fn?: (t1: T, t2: T) => Promise<number>,
): Promise<InnerAsyncArray<T>> {
if (fn === undefined) {
return new InnerAsyncArray(this._arr.sort())
}
const arr: Array<[T, number]> = this._arr.map(
(v, i) => [v, i] as [T, number],
)
async function _sort<V>(
arr: V[],
fn: (v1: V, v2: V) => Promise<number>,
): Promise<V[]> {
// 边界条件,如果传入数组的值
if (arr.length <= 1) {
return arr
}
// 根据中间值对数组分治为两个数组
const medianIndex = Math.floor(arr.length / 2)
const medianValue = arr[medianIndex]
const left = []
const right = []
for (let i = 0, len = arr.length; i < len; i++) {
if (i === medianIndex) {
continue
}
const v = arr[i]
if ((await fn(v, medianValue)) <= 0) {
left.push(v)
} else {
right.push(v)
}
}
return (await _sort(left, fn))
.concat([medianValue])
.concat(await _sort(right, fn))
}
return new InnerAsyncArray<T>(
await (await _sort(arr, ([t1], [t2]) => fn(t1, t2))).map(
([_v, i]) => this._arr[i],
),
)
}
/**
* 异步的 reduce
* @param fn 归纳函数
* @param res 初始值,默认为第一个元素
* @returns 归纳后的值
*/
public abstract reduce<R = T>(
fn: AsyncArrayReduceCallback<T, R, any>,
res?: R,
): Promise<R>
/**
* 异步的 reduceRight
* @param fn 归纳函数
* @param res 初始值,默认为最后一个元素
* @returns 归纳后的值
*/
public abstract reduceRight<R = T>(
fn: AsyncArrayReduceCallback<T, R, any>,
res?: R,
): Promise<R>
/**
* 异步 findIndex
* @param fn 异步查询函数
* @returns 查询到的第一个值的下标
*/
public abstract findIndex(
fn: AsyncArrayCallback<T, boolean, any>,
): Promise<number>
/**
* 异步的 find
* @param fn 异步查询函数
* @returns 查询到的第一个值
*/
public async find(
fn: AsyncArrayCallback<T, boolean, any>,
): Promise<T | null> {
const i = await this.findIndex(fn)
return i === -1 ? null : this._arr[i]
}
/**
* 异步的 every
* @param fn 异步匹配函数
* @returns 是否全部匹配
*/
public async every(
fn: AsyncArrayCallback<T, boolean, any>,
): Promise<boolean> {
return (
(await this.findIndex(async (...args) => !(await fn(...args)))) === -1
)
}
/**
* 异步的 some
* @param fn 异步匹配函数
* @returns 是否有任意一个匹配
*/
public async some(fn: AsyncArrayCallback<T, boolean, any>): Promise<boolean> {
return (await this.findIndex(fn)) !== -1
}
/**
* 转换为并发异步数组
*/
public parallel(): any {
return new InnerAsyncArrayParallel(this._arr)
}
/**
* 转换为顺序异步数组
*/
public serial(): any {
return new InnerAsyncArray(this._arr)
}
/**
* 获取内部数组的值,将返回一个浅复制的数组
*/
public value(): T[] {
return this._arr.slice()
}
}
/**
* 串行的异步数组
*/
class InnerAsyncArray<T> extends InnerBaseAsyncArray<T> {
constructor(args?: T[]) {
super(args)
}
public async forEach(
fn: AsyncArrayCallback<T, void, InnerAsyncArray<T>>,
): Promise<void> {
for (let i = 0, len = this._arr.length; i < len; i++) {
await fn.call(this, this._arr[i], i, this)
}
}
public async filter(
fn: AsyncArrayCallback<T, boolean, InnerAsyncArray<T>>,
): Promise<InnerAsyncArray<T>> {
const res = new InnerAsyncArray<T>()
for (let i = 0, len = this._arr.length; i < len; i++) {
if (await fn.call(this, this._arr[i], i, this)) {
res._arr.push(this._arr[i])
}
}
return res
}
public async map<R>(
fn: AsyncArrayCallback<T, R, InnerAsyncArray<T>>,
): Promise<InnerAsyncArray<R>> {
const res = new InnerAsyncArray<R>()
for (let i = 0, len = this._arr.length; i < len; i++) {
res._arr.push(await fn.call(this, this._arr[i], i, this))
}
return res
}
public async flatMap<R>(
fn: AsyncArrayCallback<T, R[], InnerAsyncArray<T>>,
): Promise<InnerAsyncArray<R>> {
const res = new InnerAsyncArray<R>()
for (let i = 0, len = this._arr.length; i < len; i++) {
res._arr.push(...(await fn.call(this, this._arr[i], i, this)))
}
return res
}
public async reduce<R = T>(
fn: AsyncArrayReduceCallback<T, R, InnerAsyncArray<T>>,
res?: R,
): Promise<R> {
for (let i = 0, len = this._arr.length; i < len; i++) {
if (res) {
res = await fn.call(this, res, this._arr[i], i, this)
} else {
res = this._arr[i] as any
}
}
return res as any
}
public async reduceRight<R = T>(
fn: AsyncArrayReduceCallback<T, R, InnerAsyncArray<T>>,
res?: R,
): Promise<R> {
for (let i = this._arr.length - 1; i >= 0; i--) {
if (res) {
res = await fn.apply(this, [res, this._arr[i], i, this])
} else {
res = this._arr[i] as any
}
}
return res as any
}
public async findIndex(
fn: AsyncArrayCallback<T, boolean, InnerAsyncArray<T>>,
): Promise<number> {
for (let i = 0, len = this._arr.length; i < len; i++) {
const res = await fn.call(this, this._arr[i], i, this)
if (res) {
return i
}
}
return -1
}
}
/**
* 并发的异步数组
*/
class InnerAsyncArrayParallel<T> extends InnerBaseAsyncArray<T> {
constructor(args?: T[]) {
super(args)
}
public async forEach(
fn: AsyncArrayCallback<T, void, InnerAsyncArrayParallel<T>>,
): Promise<void> {
await this._all(fn)
}
public async filter(
fn: AsyncArrayCallback<T, boolean, InnerAsyncArrayParallel<T>>,
): Promise<InnerAsyncArrayParallel<T>> {
const res = await this._all(fn)
const result = new InnerAsyncArrayParallel<T>()
for (let i = 0, len = res.length; i < len; i++) {
if (res[i]) {
result._arr.push(this._arr[i])
}
}
return result
}
public async map<R>(
fn: AsyncArrayCallback<T, R, InnerAsyncArrayParallel<T>>,
): Promise<InnerAsyncArrayParallel<R>> {
return new InnerAsyncArrayParallel(await this._all(fn))
}
public async flatMap<R>(
fn: AsyncArrayCallback<T, R[], InnerAsyncArrayParallel<T>>,
): Promise<InnerAsyncArrayParallel<R>> {
const res = await this._all(fn)
return new InnerAsyncArrayParallel(res.flat())
}
public sort(
fn: (t1: T, t2: T) => Promise<number>,
): Promise<InnerAsyncArray<T>> {
throw new Error('Method not implemented.')
}
public async reduce<R = T>(
fn: AsyncArrayReduceCallback<T, R, InnerAsyncArrayParallel<T>>,
res?: R,
): Promise<R> {
for (let i = 0, len = this._arr.length; i < len; i++) {
if (res) {
res = await fn.call(this, res, this._arr[i], i, this)
} else {
res = this._arr[i] as any
}
}
return res as any
}
public async reduceRight<R = T>(
fn: AsyncArrayReduceCallback<T, R, InnerAsyncArrayParallel<T>>,
res?: R,
): Promise<R> {
for (let i = this._arr.length - 1; i >= 0; i--) {
if (res) {
res = await fn.apply(this, [res, this._arr[i], i, this])
} else {
res = this._arr[i] as any
}
}
return res as any
}
public async findIndex(
fn: AsyncArrayCallback<T, boolean, InnerAsyncArrayParallel<T>>,
): Promise<number> {
return (await this._all(fn)).findIndex((v) => v)
}
private async _all<R>(
fn: AsyncArrayCallback<T, R, InnerAsyncArrayParallel<T>>,
): Promise<R[]> {
return await Promise.all(
this._arr.map((v, i) => fn.apply(this, [v, i, this])),
)
}
}
/**
* 异步数组
*/
export class AsyncArray<T> implements PromiseLike<any> {
/**
* 为内置数组赋值
* 此处自动重新计算 length 属性
*/
public set _arr(arr: T[]) {
this.__arr = arr
this.length = this.__arr.length
}
public get _arr() {
return this.__arr
}
/**
* 提供一个函数方便根据已有的数组或类数组(Set/Map)创建 {@link AsyncArray}
* @param arr 一个可迭代元素
* @returns 创建一个新的异步数组包装
*/
public static from<T>(
arr: Iterable<T> | ArrayLike<T> | null | undefined,
): AsyncArray<T> {
const result = new AsyncArray<T>([])
if (isNullOrUndefined(arr)) {
throw new Error('arr not is null')
}
result._arr = Array.from(arr)
return result
}
/**
* 内部数组的长度,用于让 {@link AsyncArray} 的实例能作为 {@link Array.from} 的参数
*/
public length = 0
/**
* 内部的数组
*/
private __arr!: T[]
// noinspection TypeScriptFieldCanBeMadeReadonly
/**
* 保存的任务数组
*/
private _tasks: Action[]
/**
* 构造函数
* @param args 任意个参数
*/
constructor(args: T[]) {
this._arr = Array.from(args)
/**
* @field 保存异步任务
* @type {Action[]}
*/
this._tasks = []
}
public filter(
fn: AsyncArrayCallback<
T,
boolean,
InnerAsyncArray<T> | InnerAsyncArrayParallel<T>
>,
): AsyncArray<T> {
return this._addTask(new Action(Action.Type.filter, [fn]))
}
public map<R>(
fn: AsyncArrayCallback<
T,
R,
InnerAsyncArray<T> | InnerAsyncArrayParallel<T>
>,
): AsyncArray<R> {
return this._addTask(new Action(Action.Type.map, [fn])) as any
}
public flatMap<R>(
fn: AsyncArrayCallback<
T,
R[],
InnerAsyncArray<T> | InnerAsyncArrayParallel<T>
>,
): AsyncArray<R> {
return this._addTask(new Action(Action.Type.flatMap, [fn])) as any
}
public sort(fn?: (a: T, b: T) => number): AsyncArray<T> {
return this._addTask(new Action(Action.Type.sort, [fn]))
}
public parallel(): AsyncArray<T> {
return this._addTask(new Action(Action.Type.parallel, []))
}
public serial(): AsyncArray<T> {
return this._addTask(new Action(Action.Type.serial, []))
}
public forEach(
fn: AsyncArrayCallback<
T,
void,
InnerAsyncArray<T> | InnerAsyncArrayParallel<T>
>,
): Promise<void> {
return this._addTask(new Action(Action.Type.forEach, [fn])).then()
}
public some(
fn: AsyncArrayCallback<
T,
boolean,
InnerAsyncArray<T> | InnerAsyncArrayParallel<T>
>,
): Promise<boolean> {
return this._addTask(new Action(Action.Type.some, [fn])).then()
}
public every(
fn: AsyncArrayCallback<
T,
boolean,
InnerAsyncArray<T> | InnerAsyncArrayParallel<T>
>,
): Promise<boolean> {
return this._addTask(new Action(Action.Type.every, [fn])).then()
}
public find(
fn: AsyncArrayCallback<
T,
boolean,
InnerAsyncArray<T> | InnerAsyncArrayParallel<T>
>,
): Promise<T | null> {
return this._addTask(new Action(Action.Type.find, [fn])).then()
}
public findIndex(
fn: AsyncArrayCallback<
T,
boolean,
InnerAsyncArray<T> | InnerAsyncArrayParallel<T>
>,
): Promise<number> {
return this._addTask(new Action(Action.Type.findIndex, [fn])).then()
}
public reduce<R = T>(
fn: AsyncArrayReduceCallback<T, R, InnerAsyncArray<T>>,
res?: R,
): Promise<R> {
return this._addTask(new Action(Action.Type.reduce, [fn, res])).then()
}
public reduceRight<R = T>(
fn: AsyncArrayReduceCallback<T, R, InnerAsyncArray<T>>,
res?: R,
): Promise<R> {
return this._addTask(new Action(Action.Type.reduceRight, [fn, res])).then()
}
/**
* 终结整个链式操作并返回结果,可以使用 await 等待当前实例开始计算
*/
public async then<TResult1 = any, TResult2 = never>(
onfulfilled?:
| ((value: any) => TResult1 | PromiseLike<TResult1>)
| undefined
| null,
onrejected?:
| ((reason: any) => TResult2 | PromiseLike<TResult2>)
| undefined
| null,
): Promise<any> {
try {
let asyncArray = new InnerAsyncArray(this._arr)
let result: any = this._arr
for (const task of this._tasks) {
asyncArray = await Reflect.apply(
Reflect.get(asyncArray, task.type),
asyncArray,
task.args,
)
if (asyncArray instanceof InnerBaseAsyncArray) {
result = asyncArray.value()
} else {
if (!isNullOrUndefined(onfulfilled)) {
onfulfilled(result)
}
return asyncArray
}
}
if (!isNullOrUndefined(onfulfilled)) {
onfulfilled(result)
}
return result
} catch (err) {
if (!isNullOrUndefined(onrejected)) {
onrejected(err)
}
}
}
/**
* @deprecated 已废弃,请直接使用 await 进行等待获取结果值即可
*/
public value(): Promise<any> {
return this.then()
}
/**
* 允许使用 for-of 遍历内部的 _arr
*/
public *[Symbol.iterator]() {
for (const kv of this._arr) {
yield kv
}
}
private _addTask(task: Action): AsyncArray<T> {
const result = new AsyncArray(this._arr)
result._tasks = [...this._tasks, task]
return result
}
} | the_stack |
import type {GraphicProps, Series} from '../types';
import React from 'react';
import {scaleOrdinal} from 'd3-scale';
import {schemeCategory10} from 'd3-scale-chromatic';
import {create, act} from 'react-test-renderer';
import {Chart} from '../Chart';
import {generateRandomSeries, random, range} from '../helpers';
import {visibleProps} from './visibleProps';
import {attributesProps} from './attributesProps';
import {styleProps} from './styleProps';
import {testSelector} from './testSelector';
type Options = Partial<{
deepestTag: string;
oneDeepestTagPerSeries: boolean;
pointStyling: boolean;
delay: number;
pointGroupClassName: string;
colorProperty: string;
visibleProperties: Record<any, string[]>;
attributesProperties: Record<any, string[]>;
styleProperties: Record<any, string[]>;
chartWidth: number;
chartHeight: number;
seriesNumbers3x5: Series[];
seriesArrays3x5: Series[];
seriesObjects3x5: Series[];
}>;
export function graphicsComponent(Component: React.FC<GraphicProps>, options: Options = {}): void {
options = {
deepestTag: 'path',
oneDeepestTagPerSeries: false,
pointStyling: false,
delay: 100,
pointGroupClassName: '', // dot, bar
colorProperty: 'fill', // fill, stroke
visibleProperties: {
seriesVisible: ['g', 'series']
},
attributesProperties: {
seriesAttributes: ['g', 'series']
},
styleProperties: {
seriesStyle: ['g', 'series']
},
chartWidth: 100,
chartHeight: 100,
...options
};
const delay = () => {
act(() => {
jest.advanceTimersByTime(options.delay || 0);
});
};
const {
chartWidth,
chartHeight,
seriesNumbers3x5 = generateRandomSeries(3, 5, {type: 'number'}),
seriesArrays3x5 = generateRandomSeries(3, 5, {type: 'array'}),
seriesObjects3x5 = generateRandomSeries(3, 5, {type: 'object'}),
} = options;
const chartSeriesSelector = testSelector('g.chart-series');
const deepestTagSelector = testSelector(options.deepestTag);
describe('Graphics renderer component', () => {
describe('should support series property', () => {
describe('data', () => {
it('as an array of numbers', () => {
const renderer = create(<Chart width={chartWidth} height={chartHeight} series={seriesNumbers3x5}>
<Component />
</Chart>);
delay();
expect(checkNormalizedSeries(renderer.root.findByType(Component).props.series, 3, 5)).toBe(true);
});
it('as an array of [x,y] pairs', () => {
const renderer = create(<Chart width={chartWidth} height={chartHeight} series={seriesArrays3x5}>
<Component />
</Chart>);
delay();
expect(checkNormalizedSeries(renderer.root.findByType(Component).props.series, 3, 5)).toBe(true);
});
it('as an array of {x,y} objects', () => {
const renderer = create(<Chart width={chartWidth} height={chartHeight} series={seriesObjects3x5}>
<Component />
</Chart>);
delay();
expect(checkNormalizedSeries(renderer.root.findByType(Component).props.series, 3, 5)).toBe(true);
});
});
describe('color', () => {
it('as a string', () => {
const series = JSON.parse(JSON.stringify(seriesNumbers3x5));
series[0].color = 'violet';
const renderer = create(<Chart width={chartWidth} height={chartHeight} series={series}>
<Component />
</Chart>);
delay();
const path = renderer.root.findAll(deepestTagSelector)[0];
expect(path.props[options.colorProperty]).toEqual('violet');
});
// TODO:
// ('as an array of strings for gradient', () => {
// });
});
describe('opacity', () => {
it('as a number', () => {
const series = JSON.parse(JSON.stringify(seriesNumbers3x5));
series[0].opacity = 0.85;
const renderer = create(<Chart width={chartWidth} height={chartHeight} series={series}>
<Component className='chart' />
</Chart>);
delay();
const path = renderer.root.findAll(chartSeriesSelector)[0];
expect(path.props.opacity).toEqual(0.85);
});
});
describe('style', () => {
it('as an object', () => {
const series = JSON.parse(JSON.stringify(seriesNumbers3x5));
series[0].style = {
stroke: '#f0f',
fontSize: 24
};
const renderer = create(<Chart width={chartWidth} height={chartHeight} series={series}>
<Component />
</Chart>);
delay();
const path = renderer.root.findAll(deepestTagSelector)[0];
expect(path.props.style).toEqual(expect.objectContaining({
fontSize: 24,
stroke: '#f0f'
}));
});
});
if (options.pointStyling) {
describe('pointStyling', () => {
describe('color for specific point', () => {
it('as a string', () => {
const series = JSON.parse(JSON.stringify(seriesObjects3x5));
series[0].color = 'red';
series[0].data[0].color = 'violet';
const renderer = create(<Chart width={chartWidth} height={chartHeight} series={series}>
<Component />
</Chart>);
delay();
const path = renderer.root.findAll(deepestTagSelector)[0];
expect(path.props[options.colorProperty]).toEqual('violet');
});
// TODO:
// ('as an array of strings for gradient', () => {
// });
});
describe('opacity', () => {
it('as a number', () => {
const series = JSON.parse(JSON.stringify(seriesObjects3x5));
series[0].opacity = 0.85;
series[0].data[0].opacity = 0.74;
const renderer = create(<Chart width={chartWidth} height={chartHeight} series={series}>
<Component className='chart' />
</Chart>);
delay();
const path = renderer.root.findAll(deepestTagSelector)[0];
expect(path.props[options.colorProperty + 'Opacity']).toEqual(0.74);
});
});
describe('style', () => {
it('as an object', () => {
const series = JSON.parse(JSON.stringify(seriesObjects3x5));
series[0].style = {fill: 'red'};
series[0].data[0].style = {
stroke: '#f0f',
fontSize: 24
};
const renderer = create(<Chart width={chartWidth} height={chartHeight} series={series}>
<Component />
</Chart>);
delay();
const path = renderer.root.findAll(deepestTagSelector)[0];
expect(path.props['style']).toEqual(expect.objectContaining({
fontSize: 24,
stroke: '#f0f',
fill: 'red'
}));
});
});
});
}
it('should have no default value', () => {
const renderer = create(<Chart width={chartWidth} height={chartHeight}><Component /></Chart>);
expect(renderer.root.findByType(Component).props['series']).toBeUndefined();
});
// ('should not normalize series itself', () => {
/*
TODO:
graphics renderers don't normalize series, but Chart or any other wrapper do that,
that's not good to mutate child's property in the parent
so:
- don't normalize child's series
- or add series normalization in graphics renderer
or
we can make normalization only as a transfer method,
in that case graphics renderers will support just only normalized series data (object {x,y})
but it will increase complexity
but also it will increase performance
*/
// });
});
describe('should support seriesIndex property', () => {
it('as a number', () => {
const renderer = create(<Chart width={chartWidth} height={chartHeight} series={seriesObjects3x5}>
<Component className='chart' seriesIndex={1} />
<Component className='chart2' seriesIndex={2} />
</Chart>);
delay();
const list = renderer.root.findAllByType(Component);
expect(renderer.root.findAll(chartSeriesSelector).length).toEqual(1);
expect(list[0].props['series'][0].data).toEqual(seriesObjects3x5[1].data);
expect(renderer.root.findAll(testSelector('g.chart2-series')).length).toEqual(1);
expect(list[list.length - 1].props['series'][0].data).toEqual(seriesObjects3x5[2].data);
});
it('as an array of numbers', () => {
const renderer = create(<Chart width={chartWidth} height={chartHeight} series={seriesObjects3x5}>
<Component className='chart' seriesIndex={[0, 2]} />
</Chart>);
delay();
expect(renderer.root.findAll(chartSeriesSelector).length).toEqual(2);
const instance = renderer.root.findByType(Component);
expect(instance.props['series'][0].data).toEqual(seriesObjects3x5[0].data);
expect(instance.props['series'][1].data).toEqual(seriesObjects3x5[2].data);
});
it('as a function that filters series property', () => {
const renderer = create(<Chart width={chartWidth} height={chartHeight} series={seriesObjects3x5}>
<Component className='chart' seriesIndex={(series, seriesIndex) => seriesIndex > 1} />
</Chart>);
delay();
expect(renderer.root.findAll(chartSeriesSelector).length).toEqual(1);
expect(renderer.root.findByType(Component).props['series'][0].data).toEqual(seriesObjects3x5[2].data);
});
it('should have no default value', () => {
const renderer = create(<Chart width={chartWidth} height={chartHeight}><Component /></Chart>);
delay();
expect(renderer.root.findByType(Component).props['seriesIndex']).toBeUndefined();
});
});
describe('should support className property', () => {
it('should render proper class names', () => {
const renderer = create(<Chart width={chartWidth} height={chartHeight} series={seriesObjects3x5}>
<Component className='chart' />
</Chart>);
delay();
const chart = renderer.root.findAll(testSelector('g.chart'));
expect(chart.length).toEqual(1);
const root = chart[0];
const series = root.findAll(chartSeriesSelector);
expect(series.length).toEqual(3);
const series0 = root.findAll(testSelector('g.chart-series.chart-series-0'));
expect(series0.length).toEqual(1);
if (options.pointGroupClassName) {
const points = root.findAll(testSelector(`.chart-${options.pointGroupClassName}`));
expect(points.length).toEqual(3 * 5);
const points0 = root.findAll(testSelector(`.chart-${options.pointGroupClassName}-0`));
expect(points0.length).toEqual(3);
}
const path = series0[0].findAll(deepestTagSelector);
// we have at least 1 or 5 paths
expect(path.length).not.toBeLessThan(options.oneDeepestTagPerSeries ? 1 : 5);
});
it('should have no default value', () => {
const renderer = create(<Chart width={chartWidth} height={chartHeight}><Component /></Chart>);
expect(renderer.root.findByType(Component).props['className']).toBeUndefined();
});
});
describe('should support style property', () => {
it('should render style in the root element', () => {
const renderer = create(<Chart width={chartWidth} height={chartHeight}>
<Component className='chart' style={{fill: 'red'}} />
</Chart>);
delay();
const root = renderer.root.find(testSelector('g.chart'));
expect(root.props['style'].fill).toEqual('red');
});
it('should have no default value', () => {
const renderer = create(<Chart width={chartWidth} height={chartHeight}><Component /></Chart>);
expect(renderer.root.findByType(Component).props['style']).toBeUndefined();
});
});
describe('should support colors property', () => {
it('can be name of predefined color schema', () => {
const renderer = create(<Chart width={chartWidth} height={chartHeight} series={seriesObjects3x5}>
<Component className='chart' colors='category10' />
</Chart>);
delay();
const paths = renderer.root.findAll(deepestTagSelector);
const colors = scaleOrdinal(schemeCategory10).domain(range(3).map(String));
expect(paths[0].props[options.colorProperty]).toEqual(colors('0'));
expect(paths[paths.length - 1].props[options.colorProperty]).toEqual(colors('2'));
});
it('can be array', () => {
const renderer = create(<Chart width={chartWidth} height={chartHeight} series={seriesObjects3x5}>
<Component className='chart' colors={['red', 'green', 'blue']} />
</Chart>);
delay();
const paths = renderer.root.findAll(deepestTagSelector);
const colors = scaleOrdinal(['red', 'green', 'blue']).domain(range(3).map(String));
expect(paths[0].props[options.colorProperty]).toEqual(colors('0'));
expect(paths[paths.length - 1].props[options.colorProperty]).toEqual(colors('2'));
});
it('can be function or d3 scale', () => {
const renderer = create(<Chart width={chartWidth} height={chartHeight} series={seriesObjects3x5}>
<Component className='chart' colors={seriesIndex => '#fff00' + seriesIndex} />
</Chart>);
delay();
const paths = renderer.root.findAll(deepestTagSelector);
expect(paths[0].props[options.colorProperty]).toEqual('#fff000');
expect(paths[paths.length - 1].props[options.colorProperty]).toEqual('#fff002');
});
});
describe('should support opacity property', () => {
it('should apply opacity attribute to the root element', () => {
const renderer = create(<Chart width={chartWidth} height={chartHeight} series={seriesObjects3x5}>
<Component className='chart' opacity={0.9} />
</Chart>);
delay();
const root = renderer.root.find(testSelector('g.chart'));
expect(root.props['opacity']).toEqual(0.9);
});
it('should have no default value', () => {
const renderer = create(<Chart width={chartWidth} height={chartHeight}><Component /></Chart>);
expect(renderer.root.findByType(Component).props['opacity']).toBeUndefined();
});
});
visibleProps(Component, {
chartWidth,
chartHeight,
seriesObjects3x5,
delay: options.delay,
props: options.visibleProperties
});
attributesProps(Component, {
chartWidth,
chartHeight,
seriesObjects3x5,
delay: options.delay,
props: options.attributesProperties
});
styleProps(Component, {
chartWidth,
chartHeight,
seriesObjects3x5,
delay: options.delay,
props: options.styleProperties
});
describe('should receive some properties from the parent', () => {
it('layerWidth and layerHeight', () => {
const renderer = create(<Chart width={chartWidth + 23} height={chartHeight * 3}>
<Component />
</Chart>);
const chart = renderer.root.findByType(Component);
expect(chart.props['layerWidth']).toEqual(chartWidth + 23);
expect(chart.props['layerHeight']).toEqual(chartHeight * 3);
});
it('minimums and maximums for each axis', () => {
const minY = Math.min(...seriesNumbers3x5.map(series => Math.min.apply(null, series.data)));
const maxY = Math.max(...seriesNumbers3x5.map(series => Math.max.apply(null, series.data)));
const renderer = create(<Chart width={chartWidth} height={chartHeight} series={seriesNumbers3x5}>
<Component />
</Chart>);
const chart = renderer.root.findByType(Component);
expect(chart.props['minX']).toEqual(0);
expect(chart.props['maxX']).toEqual(4);
expect(chart.props['minY']).toEqual(minY);
expect(chart.props['maxY']).toEqual(maxY);
});
it('scaleX and scaleY', () => {
const renderer = create(<Chart width={chartWidth} height={chartHeight}>
<Component />
</Chart>);
const chart = renderer.root.findByType(Component);
expect(chart.props['scaleX'].direction).toEqual(expect.any(Number));
expect(chart.props['scaleX'].factory).toEqual(expect.any(Function));
expect(chart.props['scaleY'].direction).toEqual(expect.any(Number));
expect(chart.props['scaleY'].factory).toEqual(expect.any(Function));
});
});
it('should have no children', () => {
const renderer1 = create(<Chart width={chartWidth} height={chartHeight} series={seriesObjects3x5}>
<Component />
</Chart>);
const renderer2 = create(<Chart width={chartWidth} height={chartHeight} series={seriesObjects3x5}>
<Component>
<g>
<text />
</g>
</Component>
</Chart>);
delay();
expect(renderer1.toJSON()).toEqual(renderer2.toJSON());
});
});
function checkNormalizedSeries(series, seriesCount, pointsCount): boolean {
expect(series.length).toEqual(seriesCount);
const seriesIndex = random(seriesCount - 1);
expect(series[seriesIndex].data.length).toEqual(pointsCount);
range(3).forEach(() => {
const seriesIndex = random(0, seriesCount - 1);
const pointIndex = random(0, pointsCount - 1);
expect(series[seriesIndex].data[pointIndex].x).toEqual(pointIndex);
expect(series[seriesIndex].data[pointIndex].y).toEqual(expect.any(Number));
});
return true;
}
} | the_stack |
import { state, mechanicsEngine, Combat, template, SpecialObjectsUse, CombatTurn, GndDiscipline, translations, gameView } from "../..";
/**
* Combats mechanics
*/
export class CombatMechanics {
/** Selector for elude buttons */
public static readonly ELUDE_BTN_SELECTOR = ".mechanics-elude";
/** Selector for play turn buttons */
public static readonly PLAY_TURN_BTN_SELECTOR = ".mechanics-playTurn";
/** Selector for combat ratio text */
public static readonly COMBAT_RATIO_SELECTOR = ".mechanics-combatRatio";
/** Selector for XXX surge checkbox */
public static readonly SURGE_CHECK_SELECTOR = ".psisurgecheck input";
/**
* Render section combats
*/
public static renderCombats() {
// Get combats to render
const sectionState = state.sectionStates.getSectionState();
if ( sectionState.combats.length === 0 ) {
return;
}
// If the player is death, do nothing
if ( state.actionChart.currentEndurance <= 0 ) {
return;
}
// Combat UI template:
const $template = mechanicsEngine.getMechanicsUI("mechanics-combat");
$template.attr("id", null);
// Populate combats
$.each(sectionState.combats, (index: number, combat: Combat) => {
const $combatUI = $template.clone();
// Set the combat index
$combatUI.attr("data-combatIdx", index);
// Add combats UI
const $combatOriginal = $(".combat:eq(" + index + ")");
$combatOriginal.append( $combatUI )
.find(CombatMechanics.PLAY_TURN_BTN_SELECTOR).click(function(e) {
// Play turn button click
e.preventDefault();
CombatMechanics.runCombatTurn( $(this).parents(".mechanics-combatUI").first(), false );
});
// Move the show combat tables as the first child (needed because it's a float)
const $btnCombatTables = $combatUI.find(".mechanics-combatTables");
$btnCombatTables.remove();
$combatOriginal.prepend( $btnCombatTables );
// Bind the show combat tables button click
$btnCombatTables.click((e) => {
e.preventDefault();
template.showCombatTables();
});
// Elude combat button click
$combatOriginal.find(CombatMechanics.ELUDE_BTN_SELECTOR).click(function(e) {
e.preventDefault();
CombatMechanics.runCombatTurn( $(this).parents(".mechanics-combatUI").first() ,
true );
});
// Bind combat ratio link click
$combatUI.find(".crlink").click(function( e: Event ) {
e.preventDefault();
CombatMechanics.showCombatRatioDetails( $(this).parents(".mechanics-combatUI").first() );
});
// Set enemy name on table
$combatUI.find(".mechanics-enemyName").html( combat.enemy );
// Set combat ratio:
CombatMechanics.updateCombatRatio( $combatUI, combat );
// Add already played turns
if ( combat.turns.length > 0 ) {
// Add already played turns
const $turnsTable = $combatUI.find( "table" );
$turnsTable.show();
const $turnsTableBody = $turnsTable.find( "> tbody" );
$.each( combat.turns, (idxTurn, turn) => {
CombatMechanics.renderCombatTurn( $turnsTableBody , turn );
});
// Update enemy current endurance
CombatMechanics.updateEnemyEndurance( $combatUI , combat , true );
}
if ( sectionState.combatEluded || combat.isFinished() || combat.disabled ) {
// Hide button to run more turns
CombatMechanics.hideCombatButtons( $combatUI );
} else {
// Check if the combat can be eluded
CombatMechanics.showHideEludeButton( combat , $combatUI );
}
// Setup XXX-Surge checkbox
CombatMechanics.setupSurgeUI($combatUI, combat);
});
}
private static updateEnemyEndurance( $combatUI: JQuery<HTMLElement> , combat: Combat , doNotAnimate: boolean ) {
template.animateValueChange( $combatUI.parent().find( ".enemy-current-endurance" ) ,
combat.endurance , doNotAnimate , combat.endurance > 0 ? null : "red" );
}
private static updateCombatRatio( $combatUI: JQuery<HTMLElement> , combat: Combat ) {
// Set combat ratio:
$combatUI.find(CombatMechanics.COMBAT_RATIO_SELECTOR).text( combat.getCombatRatio() );
}
/**
* Update all combats ratio on UI
*/
public static updateCombats() {
// Get combats to render
const sectionState = state.sectionStates.getSectionState();
if ( sectionState.combats.length === 0 ) {
return;
}
$.each(sectionState.combats, (index, combat) => {
const $combatUI = $(".mechanics-combatUI:eq(" + index + ")");
CombatMechanics.updateCombatRatio( $combatUI , combat);
});
}
/**
* Hide combat UI buttons
* @param {jquery} $combatUI The combat UI where disable buttons. If it's null, all
* combats buttons on the section will be hidden
*/
public static hideCombatButtons( $combatUI: JQuery<HTMLElement> ) {
if ( !$combatUI ) {
// Disable all combats
$combatUI = $(".mechanics-combatUI");
}
$combatUI.find(CombatMechanics.PLAY_TURN_BTN_SELECTOR).hide();
$combatUI.find(CombatMechanics.ELUDE_BTN_SELECTOR).hide();
}
/**
* Show combat UI buttons
* @param {jquery} $combatUI The combat UI where enable buttons. If it's null, all
* combats buttons on the section will be hidden
*/
public static showCombatButtons( $combatUI: JQuery<HTMLElement> ) {
if ( !$combatUI ) {
// Disable all combats
$combatUI = $(".mechanics-combatUI");
}
if ( $combatUI.length === 0 ) {
return;
}
// Get combat data
const sectionState = state.sectionStates.getSectionState();
const combatIndex = parseInt( $combatUI.attr( "data-combatIdx" ), 10 );
const combat = sectionState.combats[ combatIndex ];
if ( !(sectionState.combatEluded || combat.isFinished() || combat.disabled) ) {
$combatUI.find(CombatMechanics.PLAY_TURN_BTN_SELECTOR).show();
CombatMechanics.showHideEludeButton( combat , $combatUI );
}
}
/**
* Run a combat turn
* @param {jquery} $combatUI The combat UI
* @param elude True if the player is eluding the combat
*/
private static runCombatTurn( $combatUI: JQuery<HTMLElement>, elude: boolean ) {
// Get the combat info:
const combatIndex = parseInt( $combatUI.attr( "data-combatIdx" ), 10 );
const sectionState = state.sectionStates.getSectionState();
const combat = sectionState.combats[ combatIndex ];
combat.nextTurnAsync( elude )
.then((turn) => {
// Apply turn combat losses
combat.applyTurn(turn);
// Combat has been eluded?
sectionState.combatEluded = elude;
// Update player statistics:
template.updateStatistics();
// Render new turn
const $turnsTable = $combatUI.find( "table" ).first();
$turnsTable.show();
CombatMechanics.renderCombatTurn( $turnsTable.find( "> tbody" ), turn );
// Update enemy current endurance
CombatMechanics.updateEnemyEndurance( $combatUI , combat , false );
if ( sectionState.combatEluded || combat.isFinished() ) {
// Combat finished
// Hide button to run more turns
CombatMechanics.hideCombatButtons( $combatUI );
// Test player death
mechanicsEngine.testDeath();
// Fire turn events:
mechanicsEngine.fireAfterCombatTurn(combat);
// Post combat rules execution:
const combatsResult = sectionState.areAllCombatsFinished(state.actionChart);
if ( combatsResult === "finished" && mechanicsEngine.onAfterCombatsRule ) {
// Fire "afterCombats" rule
mechanicsEngine.runChildRules( $(mechanicsEngine.onAfterCombatsRule) );
}
if ( combatsResult === "eluded" && mechanicsEngine.onEludeCombatsRule ) {
// Fire "afterElude" rule
mechanicsEngine.runChildRules( $(mechanicsEngine.onEludeCombatsRule) );
}
if ( ( combatsResult === "finished" || combatsResult === "eluded" ) && combat.adganaUsed ) {
// Fire post-combat adgana effects
SpecialObjectsUse.postAdganaUse();
}
} else {
// Combat continues
// Check if the combat can be eluded
CombatMechanics.showHideEludeButton( combat , $combatUI );
// Fire turn events:
mechanicsEngine.fireAfterCombatTurn(combat);
// Update combat ratio (it can be changed by combat turn rules):
CombatMechanics.updateCombatRatio( $combatUI , combat );
}
// Combat has been eluded?
if ( elude ) {
// Disable other combats
CombatMechanics.hideCombatButtons( null );
}
// Check if the XXX-surge should be disabled after this turn
CombatMechanics.checkSurgeEnabled();
// For testing, add marker to notify to the test we are ready
template.addSectionReadyMarker();
});
}
/**
* Update visibility of the elude combat button
* @param combat The combat to update
* @param {jQuery} $combatUI The combat UI
*/
private static showHideEludeButton( combat: Combat , $combatUI: JQuery<HTMLElement> ) {
if ( combat.canBeEluded() ) {
// The combat can be eluded after this turn
$combatUI.find(CombatMechanics.ELUDE_BTN_SELECTOR).show();
} else {
$combatUI.find(CombatMechanics.ELUDE_BTN_SELECTOR).hide();
}
}
/**
* Render a combat turn
* @param $combatTableBody Table where to append the turn
* @param turn The turn to render
*/
private static renderCombatTurn( $combatTableBody: JQuery<HTMLElement> , turn: CombatTurn ) {
$combatTableBody.append(
'<tr><td class="hidden-xs">' + turn.turnNumber + "</td><td>" + turn.randomValue +
"</td><td>" + turn.getPlayerLossText() + "</td><td>" +
turn.getEnemyLossText() + "</td></tr>"
);
}
/**
* Setup the XXX-Surge checkbox for a given combat
* @param $combatUI Combat UI main tag
* @param combat Related combat info
*/
private static setupSurgeUI($combatUI: JQuery<HTMLElement>, combat: Combat) {
// Check what XXX-Surge discipline can player use
const surgeDisciplineId = combat.getSurgeDiscipline();
if (!surgeDisciplineId) {
// Hide XXX-surge check
$combatUI.find(".psisurgecheck").hide();
return;
}
const $psiSurgeCheck = $combatUI.find(CombatMechanics.SURGE_CHECK_SELECTOR);
// Initialice XXX surge:
if (combat.psiSurge) {
$psiSurgeCheck.attr( "checked" , "true" );
}
// Check if the XXX-surge cannot be used (EP <= Limit)
if ( state.actionChart.currentEndurance <= Combat.minimumEPForSurge(surgeDisciplineId) ) {
CombatMechanics.disableSurge( $combatUI , combat );
}
// XXX surge selection
$psiSurgeCheck.click(function(e: Event) {
CombatMechanics.onSurgeClick(e , $(this) );
});
// UI XXX-Surge texts
const surgeTextId = surgeDisciplineId === GndDiscipline.KaiSurge ? "mechanics-combat-kaisurge" : "mechanics-combat-psisurge";
const surgeText = translations.text(surgeTextId , [ combat.getFinalSurgeBonus(surgeDisciplineId) ,
Combat.surgeTurnLoss(surgeDisciplineId) ] );
$combatUI.find(".mechanics-combat-psisurge").text( surgeText );
}
/**
* XXX-Surge checkbox event handler
*/
private static onSurgeClick(e: Event, $psiSurgeCheck: JQuery<HTMLElement>) {
const $combatUI = $psiSurgeCheck.parents(".mechanics-combatUI").first();
const combatIndex = parseInt( $combatUI.attr( "data-combatIdx" ), 10 );
const sectionState = state.sectionStates.getSectionState();
const combat = sectionState.combats[ combatIndex ];
const selected: boolean = $psiSurgeCheck.prop( "checked" ) ? true : false;
combat.psiSurge = selected;
const surgeDisciplineId = combat.getSurgeDiscipline();
if ( !selected && state.actionChart.currentEndurance <= Combat.minimumEPForSurge(surgeDisciplineId) ) {
CombatMechanics.disableSurge( $combatUI , combat );
}
CombatMechanics.updateCombatRatio( $combatUI , combat);
template.addSectionReadyMarker();
}
/**
* Check if the XXX-Surge can be enabled on current section combats
* It cannot be used if the EP <= (minimum for XXX-Surge discipline)
*/
public static checkSurgeEnabled() {
const sectionState = state.sectionStates.getSectionState();
for ( let i = 0; i < sectionState.combats.length; i++ ) {
const $combatUI = $(".mechanics-combatUI:eq(" + i + ")");
CombatMechanics.checkSurgeEnabledInCombat( $combatUI , sectionState.combats[i]);
}
}
/**
* Check if the XXX-Surge can be enabled on a given combat
* @param $combatUI Combat UI main tag
* @param combat Related combat info
*/
private static checkSurgeEnabledInCombat($combatUI: JQuery<HTMLElement>, combat: Combat) {
const surgeDisciplineId = combat.getSurgeDiscipline();
if (!surgeDisciplineId) {
return;
}
if ( state.actionChart.currentEndurance > Combat.minimumEPForSurge(surgeDisciplineId) ) {
return;
}
// TODO: This check is really needed ??? I suspect no
const sectionState = state.sectionStates.getSectionState();
if ( sectionState.combats.length === 0 ) {
return;
}
CombatMechanics.disableSurge($combatUI , combat);
}
/**
* Disable XXX-surge on a combat
*/
private static disableSurge( $combatUI: JQuery<HTMLElement> , combat: Combat ) {
combat.psiSurge = false;
const $psiSurgeCheck = $combatUI.find(CombatMechanics.SURGE_CHECK_SELECTOR);
$psiSurgeCheck.prop("checked", false);
$psiSurgeCheck.prop("disabled", true);
CombatMechanics.updateCombatRatio( $combatUI , combat );
}
/**
* Show dialog with combat ratio details
* @param $combatUI The combat UI
*/
private static showCombatRatioDetails( $combatUI: JQuery<HTMLElement> ) {
// Get the combat info:
const combatIndex = parseInt( $combatUI.attr( "data-combatIdx" ), 10 );
const sectionState = state.sectionStates.getSectionState();
const combat = sectionState.combats[ combatIndex ];
const finalCSPlayer = combat.getCurrentCombatSkill();
// Player CS for this combat:
let csPlayer: string = state.actionChart.combatSkill.toString();
const bonuses = combat.getCSBonuses();
for ( const bonus of bonuses ) {
csPlayer += " ";
if ( bonus.increment >= 0 ) {
csPlayer += "+";
}
csPlayer += bonus.increment.toString() + " (" + bonus.concept + ")";
}
if ( bonuses.length > 0 ) {
csPlayer += " = " + finalCSPlayer.toString();
}
$("#game-ratioplayer").text( csPlayer );
// Enemy info:
$("#game-ratioenemyname").html( combat.enemy );
$("#game-ratioenemy").text( combat.combatSkill );
// Combat ratio result:
$("#game-ratioresult").text( finalCSPlayer + " - " + combat.combatSkill + " = " + ( finalCSPlayer - combat.combatSkill ) );
// Show dialog
$("#game-ratiodetails").modal();
}
} | the_stack |
import { device_sources, logger } from "..";
import { RegisterTallyInput } from "../_decorators/RegisterTallyInput.decorator";
import { FreePort, UsePort } from "../_decorators/UsesPort.decorator";
import { Source } from '../_models/Source';
import { TallyInputConfigField } from "../_types/TallyInputConfigField";
import { TallyInput } from './_Source';
import TSLUMD from 'tsl-umd';
import packet from "packet";
import net from "net";
const RossCarboniteFields: TallyInputConfigField[] = [
{ fieldName: 'port', fieldLabel: 'Port', fieldType: 'port' },
{
fieldName: 'transport_type', fieldLabel: 'Transport Type', fieldType: 'dropdown',
options: [
{ id: 'udp', label: 'UDP' },
{ id: 'tcp', label: 'TCP' }
]
},
];
const RossCarboniteBusAdresses = [
{ address: 'onair_program', bus: 'onair', label: "OnAir Program", type: "program" },
{ address: 'onair_preview', bus: 'onair', label: "OnAir Preview", type: "preview" },
{ address: '25', bus: 'me1', label: "ME 1 BKGD", type: "program" },
{ address: '26', bus: 'me1', label: "ME 1 PST", type: "preview" },
{ address: '35', bus: 'me2', label: "ME 2 BKGD", type: "program" },
{ address: '36', bus: 'me2', label: "ME 2 PST", type: "preview" },
{ address: '45', bus: 'me3', label: "ME 3 BKGD", type: "program" },
{ address: '46', bus: 'me3', label: "ME 3 PST", type: "preview" },
{ address: '65', bus: 'aux1', label: "Aux 1", type: "program" },
{ address: '66', bus: 'aux2', label: "Aux 2", type: "program" },
{ address: '67', bus: 'aux3', label: "Aux 3", type: "program" },
{ address: '68', bus: 'aux4', label: "Aux 4", type: "program" },
{ address: '69', bus: 'aux5', label: "Aux 5", type: "program" },
{ address: '70', bus: 'aux6', label: "Aux 6", type: "program" },
{ address: '71', bus: 'aux7', label: "Aux 7", type: "program" },
{ address: '72', bus: 'aux8', label: "Aux 8", type: "program" },
{ address: '81', bus: 'mme1', label: "MiniME™ 1 BKGD", type: "program" },
{ address: '82', bus: 'mme1', label: "MiniME™ 1 PST", type: "preview" },
{ address: '86', bus: 'mme2', label: "MiniME™ 2 BKGD", type: "program" },
{ address: '87', bus: 'mme2', label: "MiniME™ 2 PST", type: "preview" },
{ address: '91', bus: 'mme3', label: "MiniME™ 3 BKGD", type: "program" },
{ address: '92', bus: 'mme3', label: "MiniME™ 3 PST", type: "preview" },
{ address: '96', bus: 'mme4', label: "MiniME™ 4 BKGD", type: "program" },
{ address: '97', bus: 'mme4', label: "MiniME™ 4 PST", type: "preview" },
];
const RossCarboniteBlackSoloBusAddresses = [
{ address: 'onair_program', bus: 'onair', label: "OnAir Program", type: "program" },
{ address: 'onair_preview', bus: 'onair', label: "OnAir Preview", type: "preview" },
{ address: '37', bus: 'me1', label: "ME 1 BKGD", type: "program" },
{ address: '38', bus: 'me1', label: "ME 1 PST", type: "preview" },
{ address: '67', bus: 'aux1', label: "Aux 1", type: "program" },
{ address: '68', bus: 'aux2', label: "Aux 2", type: "program" },
{ address: '69', bus: 'aux3', label: "Aux 3", type: "program" },
{ address: '70', bus: 'aux4', label: "Aux 4", type: "program" },
{ address: '71', bus: 'aux5', label: "Aux 5", type: "program" },
{ address: '72', bus: 'aux6', label: "Aux 6", type: "program" },
{ address: '73', bus: 'aux7', label: "Aux 7", type: "program" },
{ address: '74', bus: 'aux8', label: "Aux 8", type: "program" },
{ address: '75', bus: 'aux9', label: "Aux 9", type: "program" },
{ address: '76', bus: 'aux10', label: "Aux 10", type: "program" },
{ address: '77', bus: 'aux11', label: "Aux 11", type: "program" },
{ address: '78', bus: 'aux12', label: "Aux 12", type: "program" },
{ address: '79', bus: 'aux13', label: "Aux 13", type: "program" },
{ address: '80', bus: 'aux14', label: "Aux 14", type: "program" },
{ address: '81', bus: 'aux15', label: "Aux 15", type: "program" },
{ address: '82', bus: 'aux16', label: "Aux 16", type: "program" },
];
const RossGraphiteBusAddresses = [
{ address: 'onair_program', bus: 'onair', label: "OnAir Program", type: "program" },
{ address: 'onair_preview', bus: 'onair', label: "OnAir Preview", type: "preview" },
{ address: '37', bus: 'me1', label: "ME 1 BKGD", type: "program" },
{ address: '38', bus: 'me1', label: "ME 1 PST", type: "preview" },
{ address: '47', bus: 'me2', label: "ME 2 BKGD", type: "program" },
{ address: '48', bus: 'me2', label: "ME 2 PST", type: "preview" },
{ address: '67', bus: 'aux1', label: "Aux 1", type: "program" },
{ address: '68', bus: 'aux2', label: "Aux 2", type: "program" },
{ address: '69', bus: 'aux3', label: "Aux 3", type: "program" },
{ address: '70', bus: 'aux4', label: "Aux 4", type: "program" },
{ address: '71', bus: 'aux5', label: "Aux 5", type: "program" },
{ address: '72', bus: 'aux6', label: "Aux 6", type: "program" },
{ address: '73', bus: 'aux7', label: "Aux 7", type: "program" },
{ address: '74', bus: 'aux8', label: "Aux 8", type: "program" },
{ address: '75', bus: 'aux9', label: "Aux 9", type: "program" },
{ address: '76', bus: 'aux10', label: "Aux 10", type: "program" },
{ address: '77', bus: 'aux11', label: "Aux 11", type: "program" },
{ address: '78', bus: 'aux12', label: "Aux 12", type: "program" },
{ address: '79', bus: 'aux13', label: "Aux 13", type: "program" },
{ address: '80', bus: 'aux14', label: "Aux 14", type: "program" },
{ address: '81', bus: 'aux15', label: "Aux 15", type: "program" },
{ address: '82', bus: 'aux16', label: "Aux 16", type: "program" },
{ address: '83', bus: 'aux17', label: "Aux 17", type: "program" },
{ address: '84', bus: 'aux18', label: "Aux 18", type: "program" },
{ address: '85', bus: 'aux19', label: "Aux 19", type: "program" },
{ address: '86', bus: 'aux20', label: "Aux 20", type: "program" },
{ address: '87', bus: 'mme1', label: "MiniME™ 1 BKGD", type: "program" },
{ address: '98', bus: 'mme1', label: "MiniME™ 1 PST", type: "preview" },
{ address: '91', bus: 'mme2', label: "MiniME™ 2 BKGD", type: "program" },
{ address: '92', bus: 'mme2', label: "MiniME™ 2 PST", type: "preview" },
{ address: '95', bus: 'mme3', label: "MiniME™ 3 BKGD", type: "program" },
{ address: '96', bus: 'mme3', label: "MiniME™ 3 PST", type: "preview" },
{ address: '105', bus: 'mme4', label: "MiniME™ 4 BKGD", type: "program" },
{ address: '106', bus: 'mme4', label: "MiniME™ 4 PST", type: "preview" },
];
const RossCarboniteBlackSoloSDHDBusAddresses = [
{ address: 'onair_program', bus: 'onair', label: "OnAir Program", type: "program" },
{ address: 'onair_preview', bus: 'onair', label: "OnAir Preview", type: "preview" },
{ address: '37', bus: 'me1', label: "ME 1 BKGD", type: "program" },
{ address: '38', bus: 'me1', label: "ME 1 PST", type: "preview" },
{ address: '47', bus: 'me2', label: "ME 2 BKGD", type: "program" },
{ address: '48', bus: 'me2', label: "ME 2 PST", type: "preview" },
{ address: '57', bus: 'me3', label: "ME 3 BKGD", type: "program" },
{ address: '58', bus: 'me3', label: "ME 3 PST", type: "preview" },
{ address: '67', bus: 'aux1', label: "Aux 1", type: "program" },
{ address: '68', bus: 'aux2', label: "Aux 2", type: "program" },
{ address: '69', bus: 'aux3', label: "Aux 3", type: "program" },
{ address: '70', bus: 'aux4', label: "Aux 4", type: "program" },
{ address: '71', bus: 'aux5', label: "Aux 5", type: "program" },
{ address: '72', bus: 'aux6', label: "Aux 6", type: "program" },
{ address: '73', bus: 'aux7', label: "Aux 7", type: "program" },
{ address: '74', bus: 'aux8', label: "Aux 8", type: "program" },
{ address: '75', bus: 'aux9', label: "Aux 9", type: "program" },
{ address: '76', bus: 'aux10', label: "Aux 10", type: "program" },
{ address: '77', bus: 'aux11', label: "Aux 11", type: "program" },
{ address: '78', bus: 'aux12', label: "Aux 12", type: "program" },
{ address: '79', bus: 'aux13', label: "Aux 13", type: "program" },
{ address: '80', bus: 'aux14', label: "Aux 14", type: "program" },
{ address: '81', bus: 'aux15', label: "Aux 15", type: "program" },
{ address: '82', bus: 'aux16', label: "Aux 16", type: "program" },
{ address: '83', bus: 'aux17', label: "Aux 17", type: "program" },
{ address: '84', bus: 'aux18', label: "Aux 18", type: "program" },
{ address: '85', bus: 'aux19', label: "Aux 19", type: "program" },
{ address: '86', bus: 'aux20', label: "Aux 20", type: "program" },
{ address: '87', bus: 'mme1', label: "MiniME™ 1 BKGD", type: "program" },
{ address: '88', bus: 'mme1', label: "MiniME™ 1 PST", type: "preview" },
{ address: '91', bus: 'mme2', label: "MiniME™ 2 BKGD", type: "program" },
{ address: '92', bus: 'mme2', label: "MiniME™ 2 PST", type: "preview" },
{ address: '95', bus: 'mme3', label: "MiniME™ 3 BKGD", type: "program" },
{ address: '96', bus: 'mme3', label: "MiniME™ 3 PST", type: "preview" },
{ address: '105', bus: 'mme4', label: "MiniME™ 4 BKGD", type: "program" },
{ address: '106', bus: 'mme4', label: "MiniME™ 4 PST", type: "preview" },
];
const RossCarboniteUltraBusAddresses = [
{ address: 'onair_program', bus: 'onair', label: "OnAir Program", type: "program" },
{ address: 'onair_preview', bus: 'onair', label: "OnAir Preview", type: "preview" },
{ address: '25', bus: 'mepp', label: "ME P/P BKGD", type: "program" },
{ address: '26', bus: 'mepp', label: "ME P/P PST", type: "preview" },
{ address: '35', bus: 'me1', label: "ME 1 BKGD", type: "program" },
{ address: '36', bus: 'me1', label: "ME 1 PST", type: "preview" },
{ address: '45', bus: 'me2', label: "ME 2 BKGD", type: "program" },
{ address: '46', bus: 'me2', label: "ME 2 PST", type: "preview" },
{ address: '64', bus: 'mme1', label: "MiniME™ 1 BKGD", type: "program" },
{ address: '65', bus: 'mme1', label: "MiniME™ 1 PST", type: "preview" },
{ address: '68', bus: 'mme2', label: "MiniME™ 2 BKGD", type: "program" },
{ address: '69', bus: 'mme2', label: "MiniME™ 2 PST", type: "preview" },
{ address: '72', bus: 'mme3', label: "MiniME™ 3 BKGD", type: "program" },
{ address: '73', bus: 'mme3', label: "MiniME™ 3 PST", type: "preview" },
{ address: '76', bus: 'mme4', label: "MiniME™ 4 BKGD", type: "program" },
{ address: '77', bus: 'mme4', label: "MiniME™ 4 PST", type: "preview" },
{ address: '100', bus: 'aux1', label: "Aux 1", type: "program" },
{ address: '101', bus: 'aux2', label: "Aux 2", type: "program" },
{ address: '102', bus: 'aux3', label: "Aux 3", type: "program" },
{ address: '103', bus: 'aux4', label: "Aux 4", type: "program" },
{ address: '104', bus: 'aux5', label: "Aux 5", type: "program" },
{ address: '105', bus: 'aux6', label: "Aux 6", type: "program" },
{ address: '106', bus: 'aux7', label: "Aux 7", type: "program" },
{ address: '107', bus: 'aux8', label: "Aux 8", type: "program" },
{ address: '108', bus: 'aux9', label: "Aux 9", type: "program" },
{ address: '109', bus: 'aux10', label: "Aux 10", type: "program" },
{ address: '110', bus: 'aux11', label: "Aux 11", type: "program" },
{ address: '111', bus: 'aux12', label: "Aux 12", type: "program" },
{ address: '112', bus: 'aux13', label: "Aux 13", type: "program" },
{ address: '113', bus: 'aux14', label: "Aux 14", type: "program" },
{ address: '114', bus: 'aux15', label: "Aux 15", type: "program" },
{ address: '115', bus: 'aux16', label: "Aux 16", type: "program" },
{ address: '116', bus: 'aux17', label: "Aux 17", type: "program" },
{ address: '117', bus: 'aux18', label: "Aux 18", type: "program" },
{ address: '118', bus: 'aux19', label: "Aux 19", type: "program" },
{ address: '119', bus: 'aux20', label: "Aux 20", type: "program" },
{ address: '120', bus: 'aux21', label: "Aux 21", type: "program" },
{ address: '121', bus: 'aux22', label: "Aux 22", type: "program" },
{ address: '122', bus: 'aux23', label: "Aux 23", type: "program" },
{ address: '123', bus: 'aux24', label: "Aux 24", type: "program" },
{ address: '124', bus: 'aux25', label: "Aux 25", type: "program" },
{ address: '125', bus: 'aux26', label: "Aux 26", type: "program" },
{ address: '126', bus: 'aux27', label: "Aux 27", type: "program" },
];
const RossSwitcherBusAddresses = {
"039bb9d6": RossCarboniteBusAdresses,
"e1c46de9": RossCarboniteBlackSoloBusAddresses,
"63d7ebc6": RossGraphiteBusAddresses,
"22d507ab": RossCarboniteBlackSoloSDHDBusAddresses,
"7da3b524": RossCarboniteUltraBusAddresses,
}
@RegisterTallyInput("039bb9d6", "Ross Carbonite", "", RossCarboniteFields, [
{ bus: 'onair', name: 'Follow OnAir Setting' },
{ bus: 'me1', name: 'ME 1' },
{ bus: 'me2', name: 'ME 2' },
{ bus: 'me3', name: 'ME 3' },
{ bus: 'mme1', name: 'MiniME 1' },
{ bus: 'mme2', name: 'MiniME 2' },
{ bus: 'mme3', name: 'MiniME 3' },
{ bus: 'mme4', name: 'MiniME 4' },
{ bus: 'aux1', name: 'Aux 1' },
{ bus: 'aux2', name: 'Aux 2' },
{ bus: 'aux3', name: 'Aux 3' },
{ bus: 'aux4', name: 'Aux 4' },
{ bus: 'aux5', name: 'Aux 5' },
{ bus: 'aux6', name: 'Aux 6' },
{ bus: 'aux7', name: 'Aux 7' },
{ bus: 'aux8', name: 'Aux 8' },
])
@RegisterTallyInput("e1c46de9", "Ross Carbonite Black Solo", "", RossCarboniteFields, [
{ bus: 'onair', name: 'Follow OnAir Setting' },
{ bus: 'me1', name: 'ME 1' },
{ bus: 'aux1', name: 'Aux 1' },
{ bus: 'aux2', name: 'Aux 2' },
{ bus: 'aux3', name: 'Aux 3' },
{ bus: 'aux4', name: 'Aux 4' },
{ bus: 'aux5', name: 'Aux 5' },
{ bus: 'aux6', name: 'Aux 6' },
{ bus: 'aux7', name: 'Aux 7' },
{ bus: 'aux8', name: 'Aux 8' },
{ bus: 'aux9', name: 'Aux 9' },
{ bus: 'au10', name: 'Aux 10' },
{ bus: 'aux11', name: 'Aux 11' },
{ bus: 'aux12', name: 'Aux 12' },
{ bus: 'aux13', name: 'Aux 13' },
{ bus: 'aux14', name: 'Aux 14' },
{ bus: 'aux15', name: 'Aux 15' },
{ bus: 'aux16', name: 'Aux 16' },
])
@RegisterTallyInput("63d7ebc6", "Ross Graphite", "", RossCarboniteFields, [
{ bus: 'onair', name: 'Follow OnAir Setting' },
{ bus: 'me1', name: 'ME 1' },
{ bus: 'me2', name: 'ME 2' },
{ bus: 'mme1', name: 'MiniME 1' },
{ bus: 'mme2', name: 'MiniME 2' },
{ bus: 'mme3', name: 'MiniME 3' },
{ bus: 'mme4', name: 'MiniME 4' },
{ bus: 'aux1', name: 'Aux 1' },
{ bus: 'aux2', name: 'Aux 2' },
{ bus: 'aux3', name: 'Aux 3' },
{ bus: 'aux4', name: 'Aux 4' },
{ bus: 'aux5', name: 'Aux 5' },
{ bus: 'aux6', name: 'Aux 6' },
{ bus: 'aux7', name: 'Aux 7' },
{ bus: 'aux8', name: 'Aux 8' },
{ bus: 'aux9', name: 'Aux 9' },
{ bus: 'au10', name: 'Aux 10' },
{ bus: 'aux11', name: 'Aux 11' },
{ bus: 'aux12', name: 'Aux 12' },
{ bus: 'aux13', name: 'Aux 13' },
{ bus: 'aux14', name: 'Aux 14' },
{ bus: 'aux15', name: 'Aux 15' },
{ bus: 'aux16', name: 'Aux 16' },
{ bus: 'aux17', name: 'Aux 17' },
{ bus: 'aux18', name: 'Aux 18' },
{ bus: 'aux19', name: 'Aux 19' },
{ bus: 'aux20', name: 'Aux 20' },
])
@RegisterTallyInput("22d507ab", "Ross Carbonite Black SD/HD", "", RossCarboniteFields, [
{ bus: 'onair', name: 'Follow OnAir Setting' },
{ bus: 'me1', name: 'ME 1' },
{ bus: 'me2', name: 'ME 2' },
{ bus: 'me3', name: 'ME 3' },
{ bus: 'mme1', name: 'MiniME 1' },
{ bus: 'mme2', name: 'MiniME 2' },
{ bus: 'mme3', name: 'MiniME 3' },
{ bus: 'mme4', name: 'MiniME 4' },
{ bus: 'aux1', name: 'Aux 1' },
{ bus: 'aux2', name: 'Aux 2' },
{ bus: 'aux3', name: 'Aux 3' },
{ bus: 'aux4', name: 'Aux 4' },
{ bus: 'aux5', name: 'Aux 5' },
{ bus: 'aux6', name: 'Aux 6' },
{ bus: 'aux7', name: 'Aux 7' },
{ bus: 'aux8', name: 'Aux 8' },
{ bus: 'aux9', name: 'Aux 9' },
{ bus: 'au10', name: 'Aux 10' },
{ bus: 'aux11', name: 'Aux 11' },
{ bus: 'aux12', name: 'Aux 12' },
{ bus: 'aux13', name: 'Aux 13' },
{ bus: 'aux14', name: 'Aux 14' },
{ bus: 'aux15', name: 'Aux 15' },
{ bus: 'aux16', name: 'Aux 16' },
{ bus: 'aux17', name: 'Aux 17' },
{ bus: 'aux18', name: 'Aux 18' },
{ bus: 'aux19', name: 'Aux 19' },
{ bus: 'aux20', name: 'Aux 20' },
])
@RegisterTallyInput("7da3b524", "Ross Carbonite Ultra", "", RossCarboniteFields, [
{ bus: 'onair', name: 'Follow OnAir Setting' },
{ bus: 'mepp', name: 'ME P/P' },
{ bus: 'me1', name: 'ME 1' },
{ bus: 'me2', name: 'ME 2' },
{ bus: 'mme1', name: 'MiniME 1' },
{ bus: 'mme2', name: 'MiniME 2' },
{ bus: 'mme3', name: 'MiniME 3' },
{ bus: 'mme4', name: 'MiniME 4' },
{ bus: 'aux1', name: 'Aux 1' },
{ bus: 'aux2', name: 'Aux 2' },
{ bus: 'aux3', name: 'Aux 3' },
{ bus: 'aux4', name: 'Aux 4' },
{ bus: 'aux5', name: 'Aux 5' },
{ bus: 'aux6', name: 'Aux 6' },
{ bus: 'aux7', name: 'Aux 7' },
{ bus: 'aux8', name: 'Aux 8' },
{ bus: 'aux9', name: 'Aux 9' },
{ bus: 'au10', name: 'Aux 10' },
{ bus: 'aux11', name: 'Aux 11' },
{ bus: 'aux12', name: 'Aux 12' },
{ bus: 'aux13', name: 'Aux 13' },
{ bus: 'aux14', name: 'Aux 14' },
{ bus: 'aux15', name: 'Aux 15' },
{ bus: 'aux16', name: 'Aux 16' },
{ bus: 'aux17', name: 'Aux 17' },
{ bus: 'aux18', name: 'Aux 18' },
{ bus: 'aux19', name: 'Aux 19' },
{ bus: 'aux20', name: 'Aux 20' },
{ bus: 'aux21', name: 'Aux 21' },
{ bus: 'aux22', name: 'Aux 22' },
{ bus: 'aux23', name: 'Aux 23' },
{ bus: 'aux24', name: 'Aux 24' },
{ bus: 'aux25', name: 'Aux 25' },
{ bus: 'aux26', name: 'Aux 26' },
{ bus: 'aux27', name: 'Aux 27' }
])
export class RossCarboniteSource extends TallyInput {
private server: any;
private tallydata_RossCarbonite = [];
constructor(source: Source) {
super(source);
let port = source.data.port;
let transport = source.data.transport_type;
if (transport === 'udp') {
UsePort(port, this.source.id);
this.server = new TSLUMD(port);
this.server.on('message', (tally) => {
this.processRossCarboniteTally(tally);
});
this.connected.next(true);
}
else {
let parser = packet.createParser();
parser.packet('tsl', 'b8{x1, b7 => address},b8{x2, b2 => brightness, b1 => tally4, b1 => tally3, b1 => tally2, b1 => tally1 }, b8[16] => label');
UsePort(port, this.source.id);
this.server = net.createServer((socket) => {
socket.on('data', (data) => {
parser.extract('tsl', (result) => {
result.label = Buffer.from(result.label).toString();
this.processRossCarboniteTally(result);
});
parser.parse(data);
});
socket.on('close', () => {
this.connected.next(false);
});
}).listen(port, () => {
this.connected.next(true);
});
}
}
private processRossCarboniteTally(tallyObj) {
let labelAddress = parseInt(tallyObj.label.substring(0, tallyObj.label.indexOf(':'))) as any;
if (!isNaN(labelAddress)) {
//if it's a number, then the address in the label field is the "real" tally address we care about
labelAddress = labelAddress.toString(); //convert it to a string since all other addresses are stored as strings
this.addRossCarboniteTally(tallyObj.address.toString(), labelAddress);
} else {
//if it's not a number, then process the normal tally address
for (let i = 0; i < device_sources.length; i++) {
if (device_sources[i].sourceId === this.source.id) { //this device_source is associated with the tally data of this source
if (device_sources[i].address === tallyObj.address.toString()) { //this device_source's address matches what was in the address field
if (device_sources[i].bus === 'onair') {
if (tallyObj.tally1) {
this.addRossCarboniteTally('onair_preview', tallyObj.address.toString());
}
else {
this.removeRossCarboniteTally('onair_preview', tallyObj.address.toString());
}
if (tallyObj.tally2) {
this.addRossCarboniteTally('onair_program', tallyObj.address.toString());
}
else {
this.removeRossCarboniteTally('onair_program', tallyObj.address.toString());
}
}
}
}
}
}
}
private addRossCarboniteTally(busAddress, address) {
let found = false;
for (let i = 0; i < this.tallydata_RossCarbonite.length; i++) {
if (this.tallydata_RossCarbonite[i].address === address) {
found = true;
if (!this.tallydata_RossCarbonite[i].busses.includes(busAddress)) {
this.tallydata_RossCarbonite[i].busses.push(busAddress); //add the bus address to this item
this.updateRossCarboniteTallyData(this.tallydata_RossCarbonite[i].address);
}
}
else {
if (this.tallydata_RossCarbonite[i].busses.includes(busAddress)) {
//remove this bus from this entry, as it is no longer in it (the label field can only hold one entry at a time)
if ((busAddress !== 'onair_preview') && (busAddress !== 'onair_program')) {
this.removeRossCarboniteTally(busAddress, this.tallydata_RossCarbonite[i].address);
}
}
}
}
if (!found) { //if there was not an entry in the array for this address
let tallyObj = {
busses: [busAddress],
address,
};
this.tallydata_RossCarbonite.push(tallyObj);
}
}
private removeRossCarboniteTally(busAddress, address) {
for (let i = 0; i < this.tallydata_RossCarbonite.length; i++) {
if (this.tallydata_RossCarbonite[i].address === address) {
this.tallydata_RossCarbonite[i].busses = this.tallydata_RossCarbonite[i].busses.filter(bus => bus !== busAddress);
this.updateRossCarboniteTallyData(this.tallydata_RossCarbonite[i].address);
}
}
}
private updateRossCarboniteTallyData(address) {
//build a new TSL tally obj based on this address and whatever busses it might be in
let inPreview = false;
let inProgram = false;
let found = false;
for (let i = 0; i < device_sources.length; i++) {
inPreview = false;
inProgram = false;
if (device_sources[i].address === address) {
//this device_source has this address in it, so let's loop through the tallydata_carbonite array
// and find all the busses that match this address
let busses = this.tallydata_RossCarbonite.find(({ address }) => address === device_sources[i].address).busses;
for (let j = 0; j < busses.length; j++) {
let bus = RossCarboniteBusAdresses[this.source.sourceTypeId].find( (busAddress) => (busAddress.address === busses[j]));
if (bus) { //if bus is undefined, it's not a bus we monitor anyways
if (bus.bus === device_sources[i].bus) {
if (bus.type === 'preview') {
inPreview = true;
}
else if (bus.type === 'program') {
inProgram = true;
}
}
}
}
const b = [];
if (inPreview) {
b.push("preview");
}
if (inProgram) {
b.push("program");
}
this.setBussesForAddress(address, b);
}
}
this.sendTallyData();
}
public exit(): void {
super.exit();
const transport = this.source.data.transport_type;
if (transport === 'udp') {
this.server.server.close();
} else {
this.server.close(() => { });
}
FreePort(this.source.data.port, this.source.id);
this.connected.next(false);
}
} | the_stack |
import { Translation } from '../i18';
// Brazilian Portuguese
//
// Translated by: Celio Rodrigues (https://github.com/rodriguescelio)
export const translation: Translation = {
__plugins: {
reload: {
failed: 'Não foi possivel recarregar os plugins: {0}',
loaded: {
more: '{0:trim} plugins carregados.',
none: 'Nenhum plugin carregado.',
one: '1 plugin carregado.',
}
}
},
canceled: '[Cancelado]',
commands: {
executionFailed: "A execução do comando {0:trim,surround} falhou: {1}",
},
compare: {
failed: 'Não foi possível baixar o arquivo {0:trim,surround}: {1}',
noPlugins: 'Nenhum plugin encontrado!',
noPluginsForType: 'Nenhum plugin correspondente encontrado para {0:trim,surround}!',
selectSource: 'Selecione a fonte de onde baixar...',
},
deploy: {
after: {
button: {
text: "{2}Implementação: [{1}] {0}{3}",
tooltip: "Clique aqui para exibir o resultado...",
},
failed: "Não foi possível executar as operações 'after deployed': {0}",
},
before: {
failed: "Não foi possível executar as operações 'before deploy': {0}",
},
button: {
cancelling: 'Cancelando...',
prepareText: 'Preparando implementação...',
text: 'Implementando...',
tooltip: 'Clique aqui para cancelar a implementação...',
},
canceled: 'Cancelado.',
canceledWithErrors: 'Cancelado com erros!',
cancelling: 'Cancelando implementação...',
file: {
deploying: 'Implementando arquivo {0:trim,surround}{1:trim,leading_space}... ',
deployingWithDestination: 'Implementando arquivo {0:trim,surround} para {1:trim,surround}{2:trim,leading_space}... ',
failed: 'Não foi possível implementar o arquivo {0:trim,surround}: {1}',
isIgnored: "O arquivo {0:trim,surround} foi ignorado!",
succeeded: 'Arquivo {0:trim,surround} foi implementado com sucesso!',
succeededWithTarget: 'Arquivo {0:trim,surround} foi implementado com sucesso para {1:trim,surround}.',
},
fileOrFolder: {
failed: 'Não foi possível implementar o arquivo / pasta {0:trim,surround}: {1}',
},
finished: 'Finalizado.',
finished2: 'Finalizado',
finishedWithErrors: 'Finalizado com erros!',
folder: {
failed: 'Não foi possível implementar a pasta {0:trim,surround}: {1}',
selectTarget: 'Selecione o destino para implementar a pasta...',
},
newerFiles: {
deploy: 'Implementar',
localFile: 'Arquivo local',
message: "{0} arquivo(s) mais recente(s) foi/foram encontrado(s)!",
modifyTime: 'Ultima modificação',
pull: 'Baixar',
remoteFile: 'Arquivo remoto',
show: 'Exibir arquivos',
size: 'Tamanho',
title: 'Novos arquivos em {0:trim,surround}',
titleNoTarget: 'Novos arquivos',
},
noFiles: 'Não existem arquivos a serem implementados!',
noPlugins: 'Nenhum plugin encontrado!',
noPluginsForType: 'Nenhum plugin correspondente encontrado para {0:trim,surround}!',
onSave: {
couldNotFindTarget: 'O destino da implementação {0:trim,surround} definido no pacote {1:trim,surround,leading_space} não existe!',
failed: 'Não foi possível implementar {0:trim,surround} ao salvar ({1:trim}): {2}',
failedTarget: 'Não foi possível implementar {0:trim,surround} para {1:trim} ao salvar: {2}',
},
operations: {
failed: "[ERRO: {0:trim,surround}]",
finished: "[Feito]",
noFileCompiled: "Nenhum dos arquivos {0:trim} puderam ser compilados!",
noFunctionInScript: "A função {0:trim,surround} não foi encontrada em {1:trim,surround}!",
open: 'Abrindo {0:trim,surround}... ',
someFilesNotCompiled: "{0:trim} de {1:trim} arquivo(s) não puderam ser compilados!",
unknownCompiler: 'Compilador {0:trim,surround} é desconhecido!',
unknownSqlEngine: 'SQL engine desconhecida {0:trim,surround}!',
unknownType: 'TIPO DESCONHECIDO: {0:trim,surround}',
},
startQuestion: 'Iniciar implementação?',
workspace: {
allFailed: 'Nenhum arquivo foi implementado: {0}',
allFailedWithTarget: 'Nenhum arquivo foi implementado para {0:trim,surround}: {1}',
allSucceeded: 'Todos os {0:trim} arquivo(s) foram implementados com sucesso.',
allSucceededWithTarget: 'Todos os {0:trim} arquivos(s) foram implementados com sucesso para {1:trim,surround}.',
alreadyStarted: 'Você já iniciou uma implementação para {0:trim,surround}! Você realmente deseja executar esta operação?',
clickToCancel: 'clique aqui para cancelar',
deploying: 'Implementando pacote {0:trim,surround,leading_space}...',
deployingWithTarget: 'Implementando pacote {0:trim,surround,leading_space} para {1:trim,surround}...',
failed: 'Não foi possível implementar os arquivos: {0}',
failedWithCategory: 'Não foi possível implementar os arquivos ({0:trim}): {1}',
failedWithTarget: 'Não foi possível implementar os arquivos para {0:trim,surround}: {1}',
nothingDeployed: 'Nenhum arquivo implementado!',
nothingDeployedWithTarget: 'Nenhum arquivo implementado para {0:trim,surround}!',
selectPackage: 'Selecione um pacote...',
selectTarget: 'Selecione um destino...',
someFailed: '{0:trim} de {1:trim} arquivo(s) não foram implementados!',
someFailedWithTarget: '{0:trim} de {1:trim} arquivo(s) não foram implementados para {2:trim,surround}!',
status: 'Implementando {0:trim,surround}... ',
statusWithDestination: 'Implementando {0:trim,surround} para {1:trim,surround}... ',
virtualTargetName: 'Lote virtual de destino para o pacote atual',
virtualTargetNameWithPackage: 'Lote virtual de destino para o pacote {0:trim,surround}',
}
},
errors: {
countable: 'ERRO #{0:trim}: {1}',
withCategory: '[ERRO] {0:trim}: {1}',
},
extension: {
update: "Atualizando...",
updateRequired: "A extensão precisa ser atualizada!",
},
extensions: {
notInstalled: 'A extensão {0:trim,surround} NÃO está instalada.',
},
failed: '[FALHOU: {0}]',
format: {
dateTime: 'HH:mm:ss DD/MM/YYYY',
},
host: {
button: {
text: 'Aguardando arquivos...',
tooltip: 'Clique aqui para fechar o host de implementação',
},
errors: {
cannotListen: 'Não foi possível iniciar a escuta para os arquivos: {0}',
couldNotStop: 'Não foi possível fechar o host de implementação: {0}',
fileRejected: 'O arquivo foi rejeitado!',
noData: 'Sem dados!',
noFilename: 'Sem filename {0:trim}!',
},
receiveFile: {
failed: '[FALHOU:{0:trim,leading_space}]',
ok: '[OK{0:trim}]',
receiving: "Recebendo arquivos {2:trim,leading_space} de '{0:trim}:{1:trim}'... ",
},
started: 'Host de implementação iniciado na porta {0:trim}, no diretório {1:trim,surround}.',
stopped: 'Host de implementação foi fechado.',
},
install: 'Instalar',
isNo: {
directory: "{0:trim,surround} não é um diretório!",
file: "{0:trim,surround} não é um arquivo!",
validItem: '{0:trim,surround} não é um item válido que possa ser implementado!',
},
load: {
from: {
failed: "Carregamento dos dados de {0:trim,surround} falhou: {1}",
}
},
network: {
hostname: 'Seu hostname: {0:trim,surround}',
interfaces: {
failed: 'Não foi possível identificar as interfaces de rede: {0}',
list: 'Sua interface de rede:',
}
},
ok: '[OK]',
packages: {
couldNotFindTarget: 'Não foi possível encontrar o destino {0:trim,surround} no pacote {1:trim,surround}!',
defaultName: '(Pacote #{0:trim})',
noneDefined: "Por favor, defina pelo menos um pacote em seu 'settings.json'!",
notFound: 'Pacote {0:trim,surround} não encontrado!',
nothingToDeploy: 'Nenhum pacote para implementar!',
},
plugins: {
api: {
clientErrors: {
noPermissions: "Sem permissão de escrita!",
notFound: 'Arquivo não encontrado!',
unauthorized: "Usuário não autorizado!",
unknown: "Erro desconhecido no cliente: {0:trim} {2:trim,surround}",
},
description: "Implemente para uma API REST, com 'vs-rest-api'",
serverErrors: {
unknown: "Erro desconhecido no servidor: {0:trim} {2:trim,surround}",
},
},
app: {
description: 'Implemente para um app, como um script ou executável, na máquina local',
},
azureblob: {
description: 'Implemente para um Armazenamento de blobs Microsoft Azure',
},
batch: {
description: 'Implemente para outros destinos',
},
dropbox: {
description: 'Implemente para uma pasta do DropBox.',
notFound: 'Arquivo não encontrado!',
unknownResponse: 'Resposta inesperada {0:trim} ({1:trim}): {2:trim,surround}',
},
each: {
description: 'Implemente arquivos usando uma lista de valores',
},
ftp: {
description: 'Implemente para um servidor FTP',
},
http: {
description: 'Implemente para um servidor/serviço HTTP',
protocolNotSupported: 'Protocolo {0:trim,surround} não é suportado!',
},
list: {
description: 'Permite que o usuário selecione um registro com configurações para um ou mais destinos',
selectEntry: 'Por favor, selecione um registro...',
},
local: {
description: 'Implementa para uma pasta local ou compartilhada (como SMB) dentro da sua rede',
emptyTargetDirectory: 'Diretório local de destino vazio {0:trim,surround}... ',
},
mail: {
addressSelector: {
placeholder: 'Endereço(s) de email de destino',
prompt: 'Um ou mais endereço(s) de email (separados por vírgula) para implementar para...',
},
description: 'Implementa em um arquivo ZIP e envia como anexo por email via SMTP',
},
map: {
description: 'Implementa os asquivos utilizando uma lista de valores',
},
pipeline: {
description: 'Pipes a list of sources files to a new destination, by using a script and sends the new file list to a target',
noPipeFunction: "{0:trim,surround} implements no 'pipe()' function!",
},
prompt: {
description: "Solicita ao usuário uma lista de configurações para serem aplicadas em um ou mais destinos",
invalidInput: "Entrada invália!",
},
remote: {
description: 'Implementa para uma maquina remota utilizando uma conexão TCP',
},
s3bucket: {
credentialTypeNotSupported: 'Tipo de credencial {0:trim,surround} não é suportada!',
description: 'Implementa para um Amazon S3 bucket',
},
script: {
deployFileFailed: 'Não foi possível implementar o arquivo {0:trim,surround} utilizando o script {1:trim,surround}!',
deployWorkspaceFailed: 'Não foi possível implementar o espaço de trabalho utilizando o script {0:trim,surround}!',
description: 'Implementa utilizando um script JS',
noDeployFileFunction: "{0:trim,surround} não possui a função 'deployFile()'!",
},
sftp: {
description: 'Implementa para um servidor SFTP',
},
sql: {
description: 'Executa scripts SQL',
invalidFile: 'Arquivo inválido!',
unknownEngine: 'Engine desconhecida {0:trim,surround}!',
},
test: {
description: 'A mock deployer that only displays what files would be deployed',
},
zip: {
description: 'Implementa para um arquivo ZIP',
fileAlreadyExists: 'Arquivo {0:trim,surround} já existe! Tente novamente...',
fileNotFound: 'Arquivo não encontrado!',
noFileFound: "Nenhum arquivo ZIP encontrado!",
}
},
popups: {
newVersion: {
message: "Você está utilizando uma versão nova do 'vs-deploy' ({0:trim})!",
showChangeLog: 'Visualizar histórico de mudanças...',
},
},
prompts: {
inputAccessKey: 'Insira a chave de acesso...',
inputAccessToken: 'Insira o token de acesso...',
inputPassword: 'Insira a senha...',
},
pull: {
button: {
cancelling: 'Cancelando...',
prepareText: 'Preparando download...',
text: 'Baixando...',
tooltip: 'Clique aqui para cancelar o download...',
},
canceled: 'Cancelado.',
canceledWithErrors: 'Cancelado com erros!',
file: {
failed: 'Não foi possível baixar o arquivo {0:trim,surround}: {1}',
pulling: 'Baixando o arquivo {0:trim,surround}{1:trim,leading_space}... ',
pullingWithDestination: 'Baixando o arquivo {0:trim,surround} para {1:trim,surround}{2:trim,leading_space}... ',
succeeded: 'Arquivo {0:trim,surround} foi baixado com sucesso.',
succeededWithTarget: 'Arquivo {0:trim,surround} foi baixado com sucesso para {1:trim,surround}.',
},
fileOrFolder: {
failed: "Não foi possível baixar o arquivo/pasta {0:trim,surround}: {1}",
},
finished2: 'Finalizado',
finishedWithErrors: 'Finalizado com erros!',
noPlugins: 'Nenhum plugin encontrado!',
noPluginsForType: 'Nenhum plugin correspondente encontrado para {0:trim,surround}!',
workspace: {
allFailed: 'Nenhum arquivo foi baixado: {0}',
allFailedWithTarget: 'Nenhum arquivo foi baixado para {0:trim,surround}: {1}',
allSucceeded: 'Todos os {0:trim} arquivo(s) foram baixados com sucesso.',
allSucceededWithTarget: 'Todos os {0:trim} arquivo(s) foram baixados com sucesso para {1:trim,surround}.',
alreadyStarted: 'Vocẽ já havia iniciado uma operação para {0:trim,surround}! Você realmente deseja executar esta operação?',
clickToCancel: 'clique aqui para cancelar',
failed: 'Não foi possível baixar os arquivos: {0}',
failedWithCategory: 'Não foi possível baixar os arquivos ({0:trim}): {1}',
failedWithTarget: 'Não foi possível baixar os arquivos para {0:trim,surround}: {1}',
nothingPulled: 'Nenhum arquivo baixado!',
nothingPulledWithTarget: 'Nenhum arquivo baixado para {0:trim,surround}!',
pulling: 'Baixando pacote {0:trim,surround,leading_space}...',
pullingWithTarget: 'Baixando pacote {0:trim,surround,leading_space} para {1:trim,surround}...',
selectPackage: 'Selecione um pacote...',
selectSource: 'Selecione uma fonte...',
someFailed: '{0:trim} de {1:trim} arquivos(s) não foram baixados!',
someFailedWithTarget: '{0:trim} de {1:trim} arquivos(s) não foram baixados para {2:trim,surround}!',
status: 'Baixando {0:trim,surround}... ',
statusWithDestination: 'Baixando {0:trim,surround} para {1:trim,surround}... ',
virtualTargetName: 'Lote virtual de destino para o pacote atual',
virtualTargetNameWithPackage: 'Lote virtual de destino para o pacote {0:trim,surround}',
}
},
quickDeploy: {
caption: 'Implementação rápida!',
failed: 'Implementação rápida falhou: {0}',
start: 'Iniciar uma implementação rápida...',
},
relativePaths: {
couldNotResolve: "Não foi possível obter o caminho relativo para {0:trim,surround}!",
isEmpty: 'Caminho relativo para o arquivo {0:trim,surround} está vazio!',
},
sync: {
file: {
doesNotExistOnRemote: '[Remoto não existe]',
localChangedWithinSession: '[Local mudou dentro da sessão]',
localIsNewer: '[Local é novo]',
synchronize: 'Sincronizar arquivo {0:trim,surround}{1:trim,leading_space}... ',
}
},
targets: {
cannotUseRecurrence: 'Não é possível utilizar o destino {0:trim,surround} (recurrence)!',
defaultName: '(Destino #{0:trim})',
noneDefined: "Por favor, defina pelo menos um destino em seu 'settings.json'!",
notFound: 'Não foi possível encontrar o destino {0:trim,surround}!',
select: 'Selecione o destino da implementação...',
selectSource: 'Selecione a fonte do download...',
},
templates: {
browserTitle: "Modelo {0:trim,surround,leading_space}",
currentPath: 'Caminho atual:{0:trim,leading_space}',
noneDefined: "Por favor, defina pelo menos uma fonte de Modelos em seu 'settings.json'!",
officialRepositories: {
newAvailable: "A fonte de modelos oficial foi atualizada.",
openTemplates: "Abrir modelos...",
},
placeholder: 'Por favor, selecione um item...',
publishOrRequest: {
label: 'Publicar ou solicitar um exemplo...',
}
},
warnings: {
withCategory: '[AVISO] {0:trim}: {1}',
},
yes: 'Sim',
}; | the_stack |
import Singleton from '../../src/server'
import BaseClient from '../../src/core/client'
import { nullLogger } from './helpers'
import sinon from 'sinon'
import nock from 'nock'
import express from 'express'
import request from 'supertest'
describe('server client', function () {
let client
beforeEach(function () {
client = Singleton.factory({
logger: nullLogger(),
environment: null
})
})
it('inherits from base client', function () {
expect(client).toEqual(expect.any(BaseClient))
})
it('sets the default hostname', function () {
expect(client.config.hostname).toEqual(expect.any(String))
})
it('reports an error over https by default', function () {
client.configure({
apiKey: 'testing'
})
const request = nock('https://api.honeybadger.io')
.post('/v1/notices/js')
.reply(201, {
id: '48b98609-dd3b-48ee-bffc-d51f309a2dfa'
})
return new Promise(resolve => {
client.afterNotify(function (_err, _notice) {
expect(request.isDone()).toBe(true)
resolve(true)
})
client.notify('testing')
})
})
it('reports an error over http when configured', function () {
client.configure({
apiKey: 'testing',
endpoint: 'http://api.honeybadger.io'
})
const request = nock('http://api.honeybadger.io')
.post('/v1/notices/js')
.reply(201, {
id: '48b98609-dd3b-48ee-bffc-d51f309a2dfa'
})
return new Promise(resolve => {
client.afterNotify(function (_err, _notice) {
expect(request.isDone()).toBe(true)
resolve(true)
})
client.notify('testing')
})
})
it('flags app lines in the backtrace', function () {
client.configure({
apiKey: 'testing'
})
nock('https://api.honeybadger.io')
.post('/v1/notices/js')
.reply(201, {
id: '48b98609-dd3b-48ee-bffc-d51f309a2dfa'
})
return new Promise(resolve => {
client.notify('testing', {
afterNotify: (err, notice) => {
expect(err).toBeUndefined()
expect(notice.message).toEqual('testing')
expect(notice.backtrace[0].file).toMatch('[PROJECT_ROOT]')
resolve(true)
}
})
})
})
describe('afterNotify', function () {
beforeEach(function () {
client.configure({
apiKey: 'testing'
})
})
it('is called without an error when the request succeeds', function () {
const id = '48b98609-dd3b-48ee-bffc-d51f309a2dfa'
nock('https://api.honeybadger.io')
.post('/v1/notices/js')
.reply(201, {
id: id
})
return new Promise(resolve => {
client.afterNotify(function (err, notice) {
expect(err).toBeUndefined()
expect(notice.message).toEqual('testing')
expect(notice.id).toBe(id)
resolve(true)
})
client.notify('testing')
})
})
it('is called with an error when the request fails', function () {
nock('https://api.honeybadger.io')
.post('/v1/notices/js')
.reply(403)
return new Promise(resolve => {
client.afterNotify(function (err, notice) {
expect(notice.message).toEqual('testing')
expect(err.message).toMatch(/403/)
resolve(true)
})
client.notify('testing')
})
})
it('is called without an error when passed as an option and the request succeeds', function () {
const id = '48b98609-dd3b-48ee-bffc-d51f309a2dfa'
nock('https://api.honeybadger.io')
.post('/v1/notices/js')
.reply(201, {
id: id
})
return new Promise(resolve => {
client.notify('testing', {
afterNotify: (err, notice) => {
expect(err).toBeUndefined()
expect(notice.message).toEqual('testing')
expect(notice.id).toBe(id)
resolve(true)
}
})
})
})
it('is called with an error when passed as an option and the request fails', function () {
nock('https://api.honeybadger.io')
.post('/v1/notices/js')
.reply(403)
return new Promise(resolve => {
client.notify('testing', {
afterNotify: (err, notice) => {
expect(notice.message).toEqual('testing')
expect(err.message).toMatch(/403/)
resolve(true)
}
})
})
})
})
describe('Express Middleware', function () {
let client_mock
const error = new Error('Badgers!')
beforeEach(function () {
client_mock = sinon.mock(client)
})
// eslint-disable-next-line jest/expect-expect
it('is sane', function () {
const app = express()
app.get('/user', function (req, res) {
res.status(200).json({ name: 'john' })
})
client_mock.expects('notify').never()
return request(app)
.get('/user')
.set('Accept', 'application/json')
.expect('Content-Type', /json/)
.expect(200)
})
it('reports the error to Honeybadger and calls next error handler', function() {
const app = express()
const expected = sinon.spy()
app.use(client.requestHandler)
app.get('/', function(_req, _res) {
throw(error)
})
app.use(client.errorHandler)
app.use(function(err, _req, _res, next) {
expected()
next(err)
})
client_mock.expects('notify').once().withArgs(error)
return request(app)
.get('/')
.expect(500)
.then(() => {
client_mock.verify()
expect(expected.calledOnce).toBeTruthy()
})
})
it('reports async errors to Honeybadger and calls next error handler', function() {
const app = express()
const expected = sinon.spy()
app.use(client.requestHandler)
app.get('/', function(_req, _res) {
setTimeout(function asyncThrow() {
throw(error)
}, 0)
})
app.use(client.errorHandler)
app.use(function(err, _req, _res, next) {
expected()
next(err)
})
client_mock.expects('notify').once().withArgs(error)
return request(app)
.get('/')
.expect(500)
.then(() => {
client_mock.verify()
expect(expected.calledOnce).toBeTruthy()
})
})
it('resets context between requests', function() {
const app = express()
const expected = sinon.spy()
app.use(client.requestHandler)
app.get('/', function(_req, res) {
res.send('Hello World!')
})
app.use(client.errorHandler)
client_mock.expects('clear').once()
return request(app)
.get('/')
.expect(200)
.then(() => {
expect(client_mock.verify()).toBeTruthy()
})
})
})
describe('Lambda Handler', function () {
describe('with arguments', function() {
let handlerFunc
beforeEach(function() {
handlerFunc = sinon.spy()
const handler = client.lambdaHandler(handlerFunc)
handler(1, 2, 3)
return new Promise((resolve => {
process.nextTick(function () {
resolve(true)
})
}))
})
it('calls original handler with arguments', function() {
expect(handlerFunc.calledWith(1, 2, 3)).toBeTruthy()
})
})
describe('async handlers', function() {
it('calls handler if notify exits on preconditions', function (done) {
client.configure({
apiKey: null
})
const handler = client.lambdaHandler(async function(_event) {
throw new Error("Badgers!")
})
handler({}, {}, (err) => {
expect(err).toBeDefined()
done()
})
})
// eslint-disable-next-line jest/expect-expect
it('reports errors to Honeybadger', function(done) {
client.configure({
apiKey: 'testing'
})
nock.cleanAll()
const api = nock("https://api.honeybadger.io")
.post("/v1/notices/js")
.reply(201, '{"id":"1a327bf6-e17a-40c1-ad79-404ea1489c7a"}')
const callback = function(_err) {
api.done()
done()
}
const handler = client.lambdaHandler(async function(_event) {
throw new Error("Badgers!")
})
handler({}, {}, callback)
})
// eslint-disable-next-line jest/expect-expect
it('reports async errors to Honeybadger', function(done) {
client.configure({
apiKey: 'testing'
})
nock.cleanAll()
const api = nock("https://api.honeybadger.io")
.post("/v1/notices/js")
.reply(201, '{"id":"1a327bf6-e17a-40c1-ad79-404ea1489c7a"}')
const callback = function(_err) {
api.done()
done()
}
const handler = client.lambdaHandler(async function(_event) {
setTimeout(function() {
throw new Error("Badgers!")
}, 0)
})
handler({}, {}, callback)
})
})
describe('non-async handlers', function() {
it('calls handler if notify exits on preconditions', function (done) {
client.configure({
apiKey: null
})
const handler = client.lambdaHandler(function(_event, _context, _callback) {
throw new Error("Badgers!")
})
handler({}, {}, (err) => {
expect(err).toBeDefined()
//revert the client to use a key
client.configure({
apiKey: 'testing'
})
done()
})
})
// eslint-disable-next-line jest/expect-expect
it('reports errors to Honeybadger', function(done) {
client.configure({
apiKey: 'testing'
})
nock.cleanAll()
const api = nock("https://api.honeybadger.io")
.post("/v1/notices/js")
.reply(201, '{"id":"1a327bf6-e17a-40c1-ad79-404ea1489c7a"}')
const callback = function(_err) {
api.done()
done()
}
const handler = client.lambdaHandler(function(_event, _context, _callback) {
throw new Error("Badgers!")
})
handler({}, {}, callback)
})
// eslint-disable-next-line jest/expect-expect
it('reports async errors to Honeybadger', function(done) {
client.configure({
apiKey: 'testing'
})
nock.cleanAll()
const api = nock("https://api.honeybadger.io")
.post("/v1/notices/js")
.reply(201, '{"id":"1a327bf6-e17a-40c1-ad79-404ea1489c7a"}')
const callback = function(_err) {
api.done()
done()
}
const handler = client.lambdaHandler(function(_event, _context, _callback) {
setTimeout(function() {
throw new Error("Badgers!")
}, 0)
})
handler({}, {}, callback)
})
})
})
}) | the_stack |
import { BoxBufferGeometry, Mesh, MeshBasicMaterial, Quaternion, Vector3, Group, Color, Ray, Box3 } from 'three';
import FootstepsSFX from '../assets/sfx/walking.wav';
import { PhysicalType, Peer, PointerLockControls, raycast } from '../libs';
import { Coords3 } from '../libs/types';
import { Helper } from '../utils';
import { Engine } from '.';
type PlayerOptionsType = {
sensitivity: number;
acceleration: number;
flyingInertia: number;
reachDistance: number;
lookBlockScale: number;
lookBlockLerp: number;
lookBlockColor: string;
perspectiveLerpFactor: number;
perspectiveDistance: number;
distToGround: number;
distToTop: number;
bodyWidth: number;
};
type PerspectiveType = 'first' | 'second' | 'third';
const LOCAL_STORAGE_PLAYER_NAME = 'mine.js-player';
const DEFAULT_PLAYER_NAME = 'naenaebaby';
const PY_ROTATION = 0;
const NY_ROTATION = 1;
const PX_ROTATION = 2;
const NX_ROTATION = 3;
const PZ_ROTATION = 4;
const NZ_ROTATION = 5;
const FOOTSTEP_SFX_NAME = 'footsteps';
type TargetBlock = { voxel: Coords3; rotation?: number; yRotation?: number };
class Player {
public id: string;
public name: string;
public spectatorMode = false;
public controls: PointerLockControls;
public lookBlock: Coords3 | null = [0, 0, 0];
public targetBlock: TargetBlock | null = {
voxel: [0, 0, 0],
rotation: PY_ROTATION,
yRotation: 0,
};
public entity: PhysicalType;
public perspective: PerspectiveType = 'first';
public own: Peer;
private acc = new Vector3();
private vel = new Vector3();
private vec = new Vector3();
private movements = {
up: false,
down: false,
left: false,
right: false,
front: false,
back: false,
sprint: false,
};
private lookBlockMesh: Group;
private shadowMesh: Mesh;
private blockRay: Ray;
constructor(public engine: Engine, public options: PlayerOptionsType) {
// three.js pointerlock controls
this.controls = new PointerLockControls(engine.camera, engine.container.canvas);
engine.rendering.scene.add(this.controls.getObject());
// retrieve name from localStorage
this.name = localStorage.getItem(LOCAL_STORAGE_PLAYER_NAME) || DEFAULT_PLAYER_NAME;
this.own = new Peer(this.name);
this.own.mesh.visible = false;
this.own.mesh.rotation.y = Math.PI * 2;
this.object.add(this.own.mesh);
engine.on('ready', () => {
// register camera as entity
if (!this.spectatorMode) {
this.addEntity();
}
this.setupListeners();
this.setupLookTargets();
// add own shadow
this.shadowMesh = this.engine.shadows.add(this.object);
this.blockRay = new Ray();
this.engine.sounds.add(FOOTSTEP_SFX_NAME, FootstepsSFX, {
loop: true,
fadeTime: 600,
maxVolume: 1.0,
multiple: false,
});
});
engine.on('chat-enabled', () => {
this.resetMovements();
});
}
setupListeners = () => {
// movement handling
document.addEventListener('keydown', this.onKeyDown, false);
document.addEventListener('keyup', this.onKeyUp, false);
const { inputs, world, inventory, chat } = this.engine;
inputs.click('left', () => world.breakVoxel(), 'in-game');
inputs.click('right', () => world.placeVoxel(inventory.hand), 'in-game');
inputs.click(
'middle',
() => {
if (this.lookBlock) this.engine.inventory.setHand(world.getVoxelByVoxel(this.lookBlock));
},
'in-game',
);
let lastSpace = -1;
inputs.bind(
'space',
() => {
let now = performance.now();
if (now - lastSpace < 250) {
this.toggleFly();
now = 0;
}
lastSpace = now;
},
'in-game',
{ occasion: 'keyup' },
);
inputs.bind('f', this.toggleSpectatorMode, 'in-game');
inputs.bind('c', this.togglePerspective, 'in-game');
this.controls.addEventListener('lock', () => {
this.engine.emit('lock');
inputs.setNamespace('in-game');
});
this.controls.addEventListener('unlock', () => {
this.engine.emit('unlock');
inputs.setNamespace(chat.enabled ? 'chat' : 'menu');
});
};
setupLookTargets = () => {
const { lookBlockScale, lookBlockColor } = this.options;
const { config, rendering } = this.engine;
const { dimension } = config.world;
this.lookBlockMesh = new Group();
const mat = new MeshBasicMaterial({
color: new Color(lookBlockColor),
opacity: 0.3,
transparent: true,
});
const w = 0.01;
const dim = dimension * lookBlockScale;
const side = new Mesh(new BoxBufferGeometry(dim, w, w), mat);
for (let i = -1; i <= 1; i += 2) {
for (let j = -1; j <= 1; j += 2) {
const temp = side.clone();
temp.position.y = ((dim - w) / 2) * i;
temp.position.z = ((dim - w) / 2) * j;
this.lookBlockMesh.add(temp);
}
}
for (let i = -1; i <= 1; i += 2) {
for (let j = -1; j <= 1; j += 2) {
const temp = side.clone();
temp.position.x = ((dim - w) / 2) * i;
temp.position.y = ((dim - w) / 2) * j;
temp.rotation.y = Math.PI / 2;
this.lookBlockMesh.add(temp);
}
}
for (let i = -1; i <= 1; i += 2) {
for (let j = -1; j <= 1; j += 2) {
const temp = side.clone();
temp.position.z = ((dim - w) / 2) * i;
temp.position.x = ((dim - w) / 2) * j;
temp.rotation.z = Math.PI / 2;
this.lookBlockMesh.add(temp);
}
}
this.lookBlockMesh.frustumCulled = false;
this.lookBlockMesh.renderOrder = 1000000;
rendering.scene.add(this.lookBlockMesh);
};
onKeyDown = ({ code }: KeyboardEvent) => {
if (!this.controls.isLocked || this.engine.chat.enabled) return;
if (this.engine.inputs.namespace !== 'in-game') return;
switch (code) {
case 'KeyR':
this.movements.sprint = true;
break;
case 'ArrowUp':
case 'KeyW':
this.movements.front = true;
break;
case 'ArrowLeft':
case 'KeyA':
this.movements.left = true;
break;
case 'ArrowDown':
case 'KeyS':
this.movements.back = true;
break;
case 'ArrowRight':
case 'KeyD':
this.movements.right = true;
break;
case 'Space':
this.movements.up = true;
break;
case 'ShiftLeft':
this.movements.down = true;
break;
}
};
onKeyUp = ({ code }: KeyboardEvent) => {
if (!this.controls.isLocked || this.engine.chat.enabled) return;
if (this.engine.inputs.namespace !== 'in-game') return;
switch (code) {
case 'ArrowUp':
case 'KeyW':
this.movements.front = false;
break;
case 'ArrowLeft':
case 'KeyA':
this.movements.left = false;
break;
case 'ArrowDown':
case 'KeyS':
this.movements.back = false;
break;
case 'ArrowRight':
case 'KeyD':
this.movements.right = false;
break;
case 'Space':
this.movements.up = false;
break;
case 'ShiftLeft':
this.movements.down = false;
break;
}
};
tick = () => {
if (this.spectatorMode) {
this.spectatorModeMovements();
} else {
this.moveEntity();
this.playFootsteps();
}
this.updateLookBlock();
this.updatePerspective();
};
spectatorModeMovements = () => {
const { delta } = this.engine.clock;
const { right, left, up, down, front, back } = this.movements;
const { acceleration, flyingInertia } = this.options;
const movementVec = new Vector3();
movementVec.x = Number(right) - Number(left);
movementVec.z = Number(front) - Number(back);
movementVec.normalize();
const yMovement = Number(up) - Number(down);
this.acc.x = -movementVec.x * acceleration;
this.acc.y = yMovement * acceleration;
this.acc.z = -movementVec.z * acceleration;
this.vel.x -= this.vel.x * flyingInertia * delta;
this.vel.y -= this.vel.y * flyingInertia * delta;
this.vel.z -= this.vel.z * flyingInertia * delta;
this.vel.add(this.acc.multiplyScalar(delta));
this.acc.set(0, 0, 0);
this.controls.moveRight(-this.vel.x);
this.controls.moveForward(-this.vel.z);
this.controls.getObject().position.y += this.vel.y;
};
moveEntity = () => {
const { object } = this.controls;
const { state, body } = this.entity.brain;
const { sprint, right, left, up, down, front, back } = this.movements;
const fb = front ? (back ? 0 : 1) : back ? -1 : 0;
const rl = left ? (right ? 0 : 1) : right ? -1 : 0;
// get the frontwards-backwards direction vectors
this.vec.setFromMatrixColumn(object.matrix, 0);
this.vec.crossVectors(object.up, this.vec);
const { x: forwardX, z: forwardZ } = this.vec;
// get the side-ways vectors
this.vec.setFromMatrixColumn(object.matrix, 0);
const { x: sideX, z: sideZ } = this.vec;
const totalX = forwardX + sideX;
const totalZ = forwardZ + sideZ;
let angle = Math.atan2(totalX, totalZ);
if ((fb | rl) === 0) {
state.running = false;
if (state.sprinting) {
this.movements.sprint = false;
state.sprinting = false;
}
} else {
state.running = true;
if (fb) {
if (fb === -1) angle += Math.PI;
if (rl) {
angle += (Math.PI / 4) * fb * rl;
}
} else {
angle += (rl * Math.PI) / 2;
}
// not sure why add Math.PI / 4, but it was always off by that.
state.heading = angle + Math.PI / 4;
}
// set jump as true, and brain will handle the jumping
state.jumping = up ? (down ? false : true) : down ? false : false;
// crouch to true, so far used for flying
state.crouching = down;
// apply sprint state change
state.sprinting = sprint;
// means landed, no more fly
if (body.gravityMultiplier === 0 && body.atRestY === -1) {
this.toggleFly();
}
};
playFootsteps = () => {
const { state } = this.entity.brain;
const { atRestY } = this.entity.body;
if (state.running && atRestY === -1) {
this.engine.sounds.play(FOOTSTEP_SFX_NAME, { object: this.object });
} else {
this.engine.sounds.pause(FOOTSTEP_SFX_NAME);
}
};
teleport = (voxel: Coords3) => {
const {
config: {
world: { dimension },
player: { bodyWidth, distToGround },
},
} = this.engine;
const [vx, vy, vz] = voxel;
let newPosition: Coords3;
if (this.spectatorMode) {
newPosition = [(vx + 0.5) * dimension, (vy + 1 + distToGround) * dimension, (vz + 0.5) * dimension];
this.controls.getObject().position.set(...newPosition);
} else {
newPosition = [
(vx - bodyWidth / 2 + 0.5) * dimension,
(vy + 1) * dimension,
(vz - bodyWidth / 2 + 0.5) * dimension,
];
this.entity.body.setPosition(newPosition);
}
return newPosition;
};
toggleFly = () => {
if (this.spectatorMode) return;
const { body } = this.entity;
const isFlying = body.gravityMultiplier === 0;
body.gravityMultiplier = isFlying ? 1 : 0;
};
toggleSpectatorMode = () => {
this.spectatorMode = !this.spectatorMode;
this.shadowMesh.visible = !this.spectatorMode;
if (this.spectatorMode) {
this.vel.set(0, 0, 0);
this.acc.set(0, 0, 0);
this.engine.entities.removePhysical('player');
this.engine.sounds.pause(FOOTSTEP_SFX_NAME);
} else {
// activated again
this.addEntity();
}
};
addEntity = () => {
const { bodyWidth, distToGround, distToTop } = this.options;
const { dimension } = this.engine.world.options;
const cameraWorldWidth = bodyWidth * dimension;
const cameraWorldHeight = (distToGround + distToTop) * dimension;
this.entity = this.engine.entities.addPhysical(
'player',
this.controls.getObject(),
[cameraWorldWidth, cameraWorldHeight, cameraWorldWidth],
[0, (distToGround - (distToGround + distToTop) / 2) * dimension, 0],
);
this.entity.body.applyImpulse([0, 4, 0]);
};
setName = (name: string) => {
this.name = name || ' ';
localStorage.setItem(LOCAL_STORAGE_PLAYER_NAME, this.name);
};
resetMovements = () => {
this.movements = {
sprint: false,
front: false,
back: false,
left: false,
right: false,
down: false,
up: false,
};
};
togglePerspective = () => {
this.perspective = this.perspective === 'first' ? 'third' : this.perspective === 'third' ? 'second' : 'first';
this.controls.camera.threeCamera.position.copy(new Vector3(0, 0, 0));
this.controls.camera.threeCamera.quaternion.copy(new Quaternion(0, 0, 0, 0));
this.own.mesh.visible = this.perspective !== 'first';
};
dispose = () => {
this.controls.dispose();
};
private updatePerspective = () => {
const {
world,
camera: { threeCamera },
} = this.engine;
const { object } = this.controls;
const { perspectiveLerpFactor, perspectiveDistance } = this.options;
this.own.update(this.name, this.object.position, this.object.quaternion);
const getDistance = () => {
const camDir = new Vector3();
const camPos = object.position;
const point: Coords3 = [0, 0, 0];
const normal: Coords3 = [0, 0, 0];
(this.perspective === 'second' ? object : threeCamera).getWorldDirection(camDir);
camDir.normalize();
camDir.multiplyScalar(-1);
raycast(
(x, y, z) => Boolean(world.getVoxelByWorld([Math.floor(x), Math.floor(y), Math.floor(z)])),
[camPos.x, camPos.y, camPos.z],
[camDir.x, camDir.y, camDir.z],
10,
point,
normal,
);
const pointVec = new Vector3(...point);
const dist = object.position.distanceTo(pointVec);
return Math.min(dist, perspectiveDistance);
};
switch (this.perspective) {
case 'first': {
break;
}
case 'second': {
const newPos = threeCamera.position.clone();
newPos.z = -getDistance();
threeCamera.position.lerp(newPos, perspectiveLerpFactor);
threeCamera.lookAt(object.position);
break;
}
case 'third': {
const newPos = threeCamera.position.clone();
newPos.z = getDistance();
threeCamera.position.lerp(newPos, perspectiveLerpFactor);
break;
}
}
};
private updateLookBlock = () => {
const { world, camera, registry } = this.engine;
const { dimension, maxHeight } = world.options;
const { reachDistance, lookBlockLerp } = this.options;
const camDir = new Vector3();
const camPos = this.controls.object.position;
camera.threeCamera.getWorldDirection(camDir);
camDir.normalize();
const point: Coords3 = [0, 0, 0];
const normal: Coords3 = [0, 0, 0];
const result = raycast(
(x, y, z, hx, hy, hz) => {
const vCoords = Helper.mapWorldPosToVoxelPos([x, y, z], dimension);
const type = world.getVoxelByVoxel(vCoords);
if (registry.isPlant(type)) {
const boxMin = [vCoords[0] + 0.2, vCoords[1] + 0, vCoords[2] + 0.2];
const boxMax = [vCoords[0] + 0.8, vCoords[1] + 0.7, vCoords[2] + 0.8];
this.blockRay.origin = new Vector3(hx / dimension, hy / dimension, hz / dimension);
this.blockRay.direction = camDir;
const tempBox = new Box3(new Vector3(...boxMin), new Vector3(...boxMax));
return !!this.blockRay.intersectBox(tempBox, new Vector3());
}
return y < maxHeight * dimension && world.getSolidityByWorld([Math.floor(x), Math.floor(y), Math.floor(z)]);
},
[camPos.x, camPos.y, camPos.z],
[camDir.x, camDir.y, camDir.z],
reachDistance * dimension,
point,
normal,
);
if (!result) {
// no target
this.lookBlockMesh.visible = false;
this.lookBlock = null;
this.targetBlock = null;
return;
}
this.lookBlockMesh.visible = true;
const flooredPoint = point.map((n, i) => Math.floor(parseFloat(n.toFixed(3))) - Number(normal[i] > 0));
const [nx, ny, nz] = normal;
const newLookBlock = Helper.mapWorldPosToVoxelPos(<Coords3>flooredPoint, world.options.dimension);
const isPlant = registry.isPlant(world.getVoxelByVoxel(newLookBlock));
// check different block type
if (isPlant) {
this.lookBlockMesh.scale.set(0.6, 0.7, 0.6);
} else {
this.lookBlockMesh.scale.set(1, 1, 1);
}
if (!world.getVoxelByVoxel(newLookBlock)) {
// this means the look block isn't actually a block
return;
}
const [lbx, lby, lbz] = newLookBlock;
this.lookBlockMesh.position.lerp(
new Vector3(
lbx * dimension + 0.5 * dimension,
lby * dimension + 0.5 * dimension - (isPlant ? 0.15 : 0),
lbz * dimension + 0.5 * dimension,
),
lookBlockLerp,
);
this.lookBlock = newLookBlock;
// target block is look block summed with the normal
const rotation =
nx !== 0
? nx > 0
? PX_ROTATION
: NX_ROTATION
: ny !== 0
? ny > 0
? PY_ROTATION
: NY_ROTATION
: nz !== 0
? nz > 0
? PZ_ROTATION
: NZ_ROTATION
: 0;
this.targetBlock = {
voxel: [this.lookBlock[0] + nx, this.lookBlock[1] + ny, this.lookBlock[2] + nz],
rotation,
yRotation: 0,
};
};
get object() {
return this.controls.object;
}
get lookBlockStr() {
const { lookBlock } = this;
return lookBlock ? `${lookBlock[0]} ${lookBlock[1]} ${lookBlock[2]}` : 'None';
}
get position(): Coords3 {
const { x, y, z } = this.controls.object.position;
const { distToGround } = this.engine.config.player;
return [x, y - distToGround + 0.01, z];
}
get voxel(): Coords3 {
return Helper.mapWorldPosToVoxelPos(this.position, this.engine.world.options.dimension);
}
get voxelPositionStr() {
const { position } = this;
const { dimension } = this.engine.world.options;
return `${(position[0] / dimension).toFixed(2)} / ${(position[1] / dimension).toFixed(2)} / ${(
position[2] / dimension
).toFixed(2)}`;
}
}
export { Player, PlayerOptionsType, TargetBlock }; | the_stack |
import {jsn, fruits, people, pets, unorderedMix, unorderedStr} from "./data";
import {assert} from "chai";
import {asEnumerable, Range} from "../lib/linq";
describe('Custom Iterator based -', function () {
const comparator = (a : string, b : string) => {
var a1 = a.charCodeAt(3);
var b1 = b.charCodeAt(3);
var a2 = a.charCodeAt(2);
var b2 = b.charCodeAt(2);
return a1 > b1 ? 1
: a1 < b1 ? -1
: a2 > b2 ? 1
: a2 < b2 ? -1 : 0;
}
const test = [
{ isControlled: true, no: 'C01', id: 1 },
{ isControlled: false, no: 'C01', id: 3 },
{ isControlled: true, no: 'C02', id: 2 },
{ isControlled: false, no: 'C02', id: 4 },
];
it('Reverse()', function () {
var array = Range(1, 100).ToArray();
var iterator = asEnumerable(array).Reverse()[Symbol.iterator]()
for (var i = 100; i > 0; i--) {
assert.equal(i, iterator.next().value);
}
assert.isTrue(iterator.next().done);
iterator = Range(1, 100).Reverse()[Symbol.iterator]()
for (i = 100; i > 0; i--) {
assert.equal(i, iterator.next().value);
}
assert.isTrue(iterator.next().done);
});
it('DefaultIfEmpty() - Not empty', function () {
var iterable = Range(0, 5).DefaultIfEmpty(0);
var iterator = iterable[Symbol.iterator]()
assert.equal(iterator.next().value, 0);
assert.equal(iterator.next().value, 1);
assert.equal(iterator.next().value, 2);
assert.equal(iterator.next().value, 3);
assert.equal(iterator.next().value, 4);
assert.isTrue(iterator.next().done);
});
it('DefaultIfEmpty() - Default', function () {
var iterable = asEnumerable([]).DefaultIfEmpty(0);
var iterator = iterable[Symbol.iterator]()
assert.equal(iterator.next().value, 0);
assert.isTrue(iterator.next().done);
});
it('DefaultIfEmpty() - No Default', function () {
var iterable = asEnumerable([]).DefaultIfEmpty();
var iterator = iterable[Symbol.iterator]()
assert.isUndefined(iterator.next().value);
assert.isTrue(iterator.next().done);
});
it('OrderBy() - Default', function () {
var enumerable = asEnumerable(unorderedStr);
var iterable = enumerable.OrderBy();
var iterator = iterable[Symbol.iterator]()
for (let exp of enumerable.ToArray().sort()) {
var actual = iterator.next().value;
if (isNaN(<any>exp) && isNaN(<any>actual)) continue;
assert.equal(actual, exp);
}
});
it('OrderBy() - Default (String)', function () {
var enumerable = asEnumerable(unorderedStr);
var iterable = enumerable.OrderBy();
var iterator = iterable[Symbol.iterator]()
for (let exp of enumerable.ToArray().sort()) {
var actual = iterator.next().value;
if (isNaN(<any>exp) && isNaN(<any>actual)) continue;
assert.equal(actual, exp);
}
});
it('OrderBy() - Selector', function () {
const iterable = asEnumerable(jsn).OrderBy(a => a.name);
const actual = [...iterable];
const expected = jsn.sort((a,b) => a.name.localeCompare(b.name));
assert.sameOrderedMembers(actual, expected);
});
it('OrderBy() - Comparator', function () {
var etalon = asEnumerable(jsn).ToArray().sort((a, b) => a.name.charCodeAt(0) - b.name.charCodeAt(0));
var iterable = asEnumerable(jsn).OrderBy(undefined, (b : any, c : any) => b.name.charCodeAt(0) - c.name.charCodeAt(0));
var iterator = iterable[Symbol.iterator]()
for (let exp of etalon) {
assert.equal(iterator.next().value, exp);
}
});
it('OrderBy() - Comparator and Selector', function () {
var etalon = asEnumerable(jsn).ToArray().sort((a, b) => a.name.charCodeAt(0) - b.name.charCodeAt(0));
var iterable = asEnumerable(jsn).OrderBy(a => a.name, (b, c) => b.charCodeAt(0) - c.charCodeAt(0));
var iterator = iterable[Symbol.iterator]()
for (let exp of etalon) {
assert.equal(iterator.next().value, exp);
}
});
it('OrderByDescending() - Default', function () {
var enumerable = asEnumerable(unorderedStr);
var iterable = enumerable.OrderByDescending();
var etalon = enumerable.ToArray().sort();
var iterator = iterable[Symbol.iterator]()
for (let i = etalon.length - 1; i >= 0; i--) {
var exp = etalon[i];
var actual = iterator.next().value;
if (isNaN(<any>exp) && isNaN(<any>actual)) continue;
assert.equal(actual, exp);
}
});
it('OrderByDescending() - Selector', function () {
const iterable = asEnumerable(jsn).OrderByDescending(a => a.name);
const actual = [...iterable];
const expected = jsn.sort((a,b) => a.name.localeCompare(b.name)).reverse();
assert.sameOrderedMembers(actual, expected);
});
it('OrderByDescending() - Key', function () {
var iterable = asEnumerable(unorderedStr).OrderByDescending(a => a);
var iterator = iterable[Symbol.iterator]()
assert.equal(iterator.next().value, "zjgf");
assert.equal(iterator.next().value, "axgh");
assert.equal(iterator.next().value, "afgh");
assert.equal(iterator.next().value, "1324");
assert.equal(iterator.next().value, "1314");
assert.equal(iterator.next().value, "1234");
assert.equal(iterator.next().value, "1234");
assert.isTrue(iterator.next().done);
});
it('OrderByDescending() - Comparator', function () {
var etalon = asEnumerable(unorderedStr).ToArray().sort(comparator);
var iterable = asEnumerable(unorderedStr).OrderByDescending(a => a, comparator);
var iterator = iterable[Symbol.iterator]()
for (let i = etalon.length - 1; i >= 0; i--) {
var exp = etalon[i];
var actual = iterator.next().value;
assert.equal(actual, exp);
}
});
it('ThenBy() - Default', function () {
var enumerable = asEnumerable(unorderedStr);
var iterable = enumerable.OrderBy().ThenBy();
var iterator = iterable[Symbol.iterator]()
for (let exp of enumerable.ToArray().sort()) {
var actual = iterator.next().value;
if (isNaN(<any>exp) && isNaN(<any>actual)) continue;
assert.equal(actual, exp);
}
});
it('ThenBy() - Selector', function () {
var enumerable = asEnumerable(unorderedStr);
var iterable = enumerable.OrderBy(s => s.charCodeAt(3)).ThenBy(s => s.charCodeAt(2));
var iterator = iterable[Symbol.iterator]()
assert.equal(iterator.next().value, "1314");
assert.equal(iterator.next().value, "1324");
assert.equal(iterator.next().value, "1234");
assert.equal(iterator.next().value, "1234");
assert.equal(iterator.next().value, "zjgf");
assert.equal(iterator.next().value, "afgh");
assert.equal(iterator.next().value, "axgh");
assert.isTrue(iterator.next().done);
});
it('ThenBy() - Default Key', function () {
var enumerable = asEnumerable(unorderedStr);
var iterable = enumerable.OrderBy().ThenBy(undefined, comparator);
var iterator = iterable[Symbol.iterator]()
for (let exp of enumerable.ToArray().sort(comparator)) {
assert.equal(iterator.next().value, exp);
}
});
it('ThenBy() - Function', function () {
var enumerable = asEnumerable(unorderedStr);
var iterable = enumerable.OrderBy().ThenBy(s => s, comparator);
var iterator = iterable[Symbol.iterator]()
for (let exp of enumerable.ToArray().sort(comparator)) {
assert.equal(iterator.next().value, exp);
}
});
it('ThenBy() - QJesus', function () {
var iterable = asEnumerable(test).OrderByDescending(x => x.isControlled)
.ThenBy(x => x.no);
var iterator = iterable[Symbol.iterator]()
assert.equal(iterator.next().value.id, 1);
assert.equal(iterator.next().value.id, 2);
assert.equal(iterator.next().value.id, 3);
assert.equal(iterator.next().value.id, 4);
assert.isTrue(iterator.next().done);
});
it('ThenByDescending() - Default', function () {
var enumerable = asEnumerable(unorderedStr);
var iterable = enumerable.OrderByDescending().ThenByDescending();
var iterator = iterable[Symbol.iterator]()
assert.equal(iterator.next().value, "zjgf");
assert.equal(iterator.next().value, "axgh");
assert.equal(iterator.next().value, "afgh");
assert.equal(iterator.next().value, "1324");
assert.equal(iterator.next().value, "1314");
assert.equal(iterator.next().value, "1234");
assert.equal(iterator.next().value, "1234");
assert.isTrue(iterator.next().done);
});
it('ThenByDescending() - Selector', function () {
var enumerable = asEnumerable(unorderedStr);
var etalon = enumerable.ToArray().sort(comparator);
var iterable = enumerable.OrderByDescending(s => s.charCodeAt(3)).ThenByDescending(s => s.charCodeAt(2));
var iterator = iterable[Symbol.iterator]()
for (let i = etalon.length - 1; i >= 0; i--) {
var exp = etalon[i];
var actual = iterator.next().value;
if (isNaN(<any>exp) && isNaN(<any>actual)) continue;
assert.equal(actual, exp);
}
});
it('ThenByDescending() - QJesus', function () {
var iterable = asEnumerable(test).OrderBy(x => x.isControlled)
.ThenByDescending(x => x.no);
var iterator = iterable[Symbol.iterator]()
assert.equal(iterator.next().value.id, 4);
assert.equal(iterator.next().value.id, 3);
assert.equal(iterator.next().value.id, 2);
assert.equal(iterator.next().value.id, 1);
assert.isTrue(iterator.next().done);
});
it('ThenByDescending() - Function', function () {
var enumerable = asEnumerable(unorderedStr);
var etalon = enumerable.ToArray().sort(comparator);
var iterable = enumerable.OrderBy(s => 0).ThenByDescending(s => s, comparator);
var iterator = iterable[Symbol.iterator]()
for (let i = etalon.length - 1; i >= 0; i--) {
var exp = etalon[i];
var actual = iterator.next().value;
assert.equal(actual.charCodeAt(2), exp.charCodeAt(2));
assert.equal(actual.charCodeAt(3), exp.charCodeAt(3));
}
});
it('Ordering chain', function () {
function toObjects(items: { a: string[]; b: number[]; c: string[]; d: number[]; }): { a: string; b: number; c: string; d: number }[] {
return items.a.map((a, i) => ({a, b: items.b[i], c: items.c[i], d: items.d[i]}));
}
const unorderedItems = toObjects({
a: ["C", "C", "C", "C", "C", "C", "C", "C", "A", "A", "A", "A", "A", "A", "A", "A", "B", "B", "B", "B", "B", "B", "B", "B" ],
b: [ 0, 0 , 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 1 ],
c: ["A", "B", "A", "B", "A", "B", "A", "B", "A", "B", "A", "B", "B", "A", "B", "A", "B", "A", "B", "A", "A", "B", "A", "B" ],
d: [ 0, 0 , 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0 ]
});
const expectedByAscDescAscDesc = toObjects({
a: ["A", "A", "A", "A", "A", "A", "A", "A", "B", "B", "B", "B", "B", "B", "B", "B", "C", "C", "C", "C", "C", "C", "C", "C"],
b: [ 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0 ],
c: ["A", "A", "B", "B", "A", "A", "B", "B", "A", "A", "B", "B", "A", "A", "B", "B", "A", "A", "B", "B", "A", "A", "B", "B"],
d: [ 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0 ]
});
const actualByAscDescAscDesc = asEnumerable(unorderedItems).OrderBy(x => x.a).ThenByDescending(x => x.b).ThenBy(x => x.c).ThenByDescending(x => x.d).ToArray();
assert.sameDeepOrderedMembers(actualByAscDescAscDesc, expectedByAscDescAscDesc);
// Change order of chain
const expectedByDescAscDescAsc = toObjects({
a: ["C", "C", "C", "C", "C", "C", "C", "C", "B", "B", "B", "B", "B", "B", "B", "B", "A", "A", "A", "A", "A", "A", "A", "A"],
b: [ 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1 ],
c: ["B", "B", "A", "A", "B", "B", "A", "A", "B", "B", "A", "A", "B", "B", "A", "A", "B", "B", "A", "A", "B", "B", "A", "A"],
d: [ 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1 ]
});
const actualByDescAscDescAsc = asEnumerable(unorderedItems).OrderByDescending(x => x.a).ThenBy(x => x.b).ThenByDescending(x => x.c).ThenBy(x => x.d).ToArray();
assert.sameDeepOrderedMembers(actualByDescAscDescAsc, expectedByDescAscDescAsc);
});
it('Ordering chain - immutability', function () {
const unorderedItems = [
{name:"C" , age:30, grade:50},
{name:"C" , age:10, grade:0},
{name:"C" , age:20, grade:100},
{name:"A" , age:30, grade:50},
{name:"A" , age:10, grade:0},
{name:"A" , age:20, grade:100},
{name:"B" , age:30, grade:50},
{name:"B" , age:10, grade:0},
{name:"B" , age:20, grade:100},
];
const expectedByNameThenByAge = unorderedItems.slice().sort((a,b)=> a.name.localeCompare(b.name) || (a.age - b.age));
const expectedByNameThenByGradeDescending = unorderedItems.slice().sort((a,b)=> a.name.localeCompare(b.name) || (b.grade - a.grade));
const immutableOrderedByName = asEnumerable(unorderedItems).OrderBy(x => x.name);
const actualByNameThenByAge = immutableOrderedByName.ThenBy(x => x.age).ToArray();
const actualByNameThenByGradeDescending = immutableOrderedByName.ThenByDescending(x => x.grade).ToArray();
assert.sameDeepOrderedMembers(actualByNameThenByAge, expectedByNameThenByAge);
assert.sameDeepOrderedMembers(actualByNameThenByGradeDescending, expectedByNameThenByGradeDescending);
// Change order of execution
const immutableOrderedByName2 = asEnumerable(unorderedItems).OrderBy(x => x.name);
const actualByNameThenByGradeDescending2 = immutableOrderedByName2.ThenByDescending(x => x.grade).ToArray();
const actualByNameThenByAge2 = immutableOrderedByName2.ThenBy(x => x.age).ToArray();
assert.sameOrderedMembers(actualByNameThenByGradeDescending2, expectedByNameThenByGradeDescending);
assert.sameOrderedMembers(actualByNameThenByAge2, expectedByNameThenByAge);
});
it('Zip()', function () {
var numbers = [1, 2, 3, 4];
var words = ["one", "two", "three"];
var numbersAndWords = asEnumerable(numbers).Zip(words, (first, second) => first + " " + second);
var iterator = numbersAndWords[Symbol.iterator]()
assert.equal("1 one", iterator.next().value);
assert.equal("2 two", iterator.next().value);
assert.equal("3 three", iterator.next().value);
assert.isTrue(iterator.next().done);
});
});
/** Copyright (c) ENikS. All rights reserved. */ | the_stack |
import { opConcatMap, pipeSync } from '@cspell/cspell-pipe';
import type { CSpellSettingsWithSourceTrace, CSpellUserSettings, PnPSettings } from '@cspell/cspell-types';
import assert from 'assert';
import { CSpellSettingsInternal } from '../Models/CSpellSettingsInternalDef';
import { TextDocument, updateTextDocument } from '../Models/TextDocument';
import { finalizeSettings, loadConfig, mergeSettings, searchForConfig } from '../Settings';
import { loadConfigSync, searchForConfigSync } from '../Settings/configLoader';
import { getDictionaryInternal, getDictionaryInternalSync, SpellingDictionaryCollection } from '../SpellingDictionary';
import { toError } from '../util/errors';
import { callOnce } from '../util/Memorizer';
import { AutoCache } from '../util/simpleCache';
import { MatchRange } from '../util/TextRange';
import { createTimer } from '../util/timer';
import { clean } from '../util/util';
import { determineTextDocumentSettings } from './determineTextDocumentSettings';
import {
calcTextInclusionRanges,
LineValidator,
lineValidatorFactory,
mapLineSegmentAgainstRangesFactory,
ValidationOptions,
type LineSegment,
} from './textValidator';
import { settingsToValidateOptions, ValidateTextOptions, ValidationIssue } from './validator';
export interface DocumentValidatorOptions extends ValidateTextOptions {
/**
* Optional path to a configuration file.
* If given, it will be used instead of searching for a configuration file.
*/
configFile?: string;
/**
* Prevents searching for local configuration files
* By default the spell checker looks for configuration files
* starting at the location of given filename.
* If `configFile` is defined it will still be loaded instead of searching.
* `false` will override the value in `settings.noConfigSearch`.
* @defaultValue undefined
*/
noConfigSearch?: boolean;
}
export class DocumentValidator {
private _document: TextDocument;
private _ready = false;
readonly errors: Error[] = [];
private _prepared: Promise<void> | undefined;
private _preparations: Preparations | undefined;
private _preparationTime = -1;
private _suggestions = new AutoCache((text: string) => this.genSuggestions(text), 1000);
/**
* @param doc - Document to validate
* @param config - configuration to use (not finalized).
*/
constructor(doc: TextDocument, readonly options: DocumentValidatorOptions, readonly settings: CSpellUserSettings) {
this._document = doc;
// console.error(`DocumentValidator: ${doc.uri}`);
}
get ready() {
return this._ready;
}
prepareSync() {
// @todo
// Determine doc settings.
// Calc include ranges
// Load dictionaries
if (this._ready) return;
const timer = createTimer();
const { options, settings } = this;
const useSearchForConfig =
(!options.noConfigSearch && !settings.noConfigSearch) || options.noConfigSearch === false;
const optionsConfigFile = options.configFile;
const localConfig = optionsConfigFile
? this.errorCatcherWrapper(() => loadConfigSync(optionsConfigFile, settings))
: useSearchForConfig
? this.errorCatcherWrapper(() => searchForDocumentConfigSync(this._document, settings, settings))
: undefined;
this.addPossibleError(localConfig?.__importRef?.error);
const config = mergeSettings(settings, localConfig);
const docSettings = determineTextDocumentSettings(this._document, config);
const dict = getDictionaryInternalSync(docSettings);
const shouldCheck = docSettings.enabled ?? true;
const finalSettings = finalizeSettings(docSettings);
const validateOptions = settingsToValidateOptions(finalSettings);
const includeRanges = calcTextInclusionRanges(this._document.text, validateOptions);
const segmenter = mapLineSegmentAgainstRangesFactory(includeRanges);
const lineValidator = lineValidatorFactory(dict, validateOptions);
this._preparations = {
config,
dictionary: dict,
docSettings,
shouldCheck,
validateOptions,
includeRanges,
segmenter,
lineValidator,
};
this._ready = true;
this._preparationTime = timer.elapsed();
// console.error(`prepareSync ${this._preparationTime.toFixed(2)}ms`);
}
async prepare(): Promise<void> {
if (this._ready) return;
if (this._prepared) return this._prepared;
this._prepared = this._prepareAsync();
return this._prepared;
}
private async _prepareAsync(): Promise<void> {
assert(!this._ready);
const timer = createTimer();
const { options, settings } = this;
const useSearchForConfig =
(!options.noConfigSearch && !settings.noConfigSearch) || options.noConfigSearch === false;
const pLocalConfig = options.configFile
? this.catchError(loadConfig(options.configFile, settings))
: useSearchForConfig
? this.catchError(searchForDocumentConfig(this._document, settings, settings))
: undefined;
const localConfig = (await pLocalConfig) || {};
this.addPossibleError(localConfig?.__importRef?.error);
const config = mergeSettings(settings, localConfig);
const docSettings = determineTextDocumentSettings(this._document, config);
const dict = await getDictionaryInternal(docSettings);
const shouldCheck = docSettings.enabled ?? true;
const finalSettings = finalizeSettings(docSettings);
const validateOptions = settingsToValidateOptions(finalSettings);
const includeRanges = calcTextInclusionRanges(this._document.text, validateOptions);
const segmenter = mapLineSegmentAgainstRangesFactory(includeRanges);
const lineValidator = lineValidatorFactory(dict, validateOptions);
this._preparations = {
config,
dictionary: dict,
docSettings,
shouldCheck,
validateOptions,
includeRanges,
segmenter,
lineValidator,
};
this._ready = true;
this._preparationTime = timer.elapsed();
}
private _updatePrep() {
assert(this._preparations);
const timer = createTimer();
const { config } = this._preparations;
const docSettings = determineTextDocumentSettings(this._document, config);
const dict = getDictionaryInternalSync(docSettings);
const shouldCheck = docSettings.enabled ?? true;
const finalSettings = finalizeSettings(docSettings);
const validateOptions = settingsToValidateOptions(finalSettings);
const includeRanges = calcTextInclusionRanges(this._document.text, validateOptions);
const segmenter = mapLineSegmentAgainstRangesFactory(includeRanges);
const lineValidator = lineValidatorFactory(dict, validateOptions);
this._preparations = {
config,
dictionary: dict,
docSettings,
shouldCheck,
validateOptions,
includeRanges,
segmenter,
lineValidator,
};
this._preparationTime = timer.elapsed();
}
/**
* The amount of time in ms to prepare for validation.
*/
get prepTime(): number {
return this._preparationTime;
}
checkText(range: SimpleRange, _text: string, _scope: string[]): ValidationIssue[] {
assert(this._ready);
assert(this._preparations);
const { segmenter, lineValidator } = this._preparations;
// Determine settings for text range
// Slice text based upon include ranges
// Check text against dictionaries.
const offset = range[0];
const offsetEnd = range[1];
const text = this._document.text.slice(offset, offsetEnd);
const line = this._document.lineAt(offset);
const lineSeg: LineSegment = {
line,
segment: {
text,
offset,
},
};
const aIssues = pipeSync(segmenter(lineSeg), opConcatMap(lineValidator));
const issues = [...aIssues];
if (!this.options.generateSuggestions) {
return issues;
}
const withSugs = issues.map((t) => {
// lazy suggestion calculation.
const text = t.text;
const suggestions = callOnce(() => this.suggest(text));
return Object.defineProperty({ ...t }, 'suggestions', { enumerable: true, get: suggestions });
});
return withSugs;
}
get document() {
return this._document;
}
public updateDocumentText(text: string) {
updateTextDocument(this._document, [{ text }]);
this._updatePrep();
}
private addPossibleError(error: Error | undefined | unknown) {
if (!error) return;
error = this.errors.push(toError(error));
}
private catchError<P>(p: Promise<P>): Promise<P | undefined> {
return p.catch((error) => {
this.addPossibleError(error);
return undefined;
});
}
private errorCatcherWrapper<P>(fn: () => P): P | undefined {
try {
return fn();
} catch (error) {
this.addPossibleError(error);
}
return undefined;
}
private suggest(text: string) {
return this._suggestions.get(text);
}
private genSuggestions(text: string): string[] {
assert(this._preparations);
const settings = this._preparations.docSettings;
const dict = this._preparations.dictionary;
const sugOptions = clean({
compoundMethod: 0,
numSuggestions: this.options.numSuggestions,
includeTies: false,
ignoreCase: !(settings.caseSensitive ?? false),
timeout: settings.suggestionsTimeout,
numChanges: settings.suggestionNumChanges,
});
return dict.suggest(text, sugOptions).map((r) => r.word);
}
}
export type Offset = number;
export type SimpleRange = readonly [Offset, Offset];
interface Preparations {
/** loaded config */
config: CSpellSettingsInternal;
dictionary: SpellingDictionaryCollection;
/** configuration after applying in-doc settings */
docSettings: CSpellSettingsInternal;
includeRanges: MatchRange[];
lineValidator: LineValidator;
segmenter: (lineSegment: LineSegment) => LineSegment[];
shouldCheck: boolean;
validateOptions: ValidationOptions;
}
async function searchForDocumentConfig(
document: TextDocument,
defaultConfig: CSpellSettingsWithSourceTrace,
pnpSettings: PnPSettings
): Promise<CSpellSettingsWithSourceTrace> {
const { uri } = document;
if (uri.scheme !== 'file') return Promise.resolve(defaultConfig);
return searchForConfig(uri.fsPath, pnpSettings).then((s) => s || defaultConfig);
}
function searchForDocumentConfigSync(
document: TextDocument,
defaultConfig: CSpellSettingsWithSourceTrace,
pnpSettings: PnPSettings
): CSpellSettingsWithSourceTrace {
const { uri } = document;
if (uri.scheme !== 'file') defaultConfig;
return searchForConfigSync(uri.fsPath, pnpSettings) || defaultConfig;
} | the_stack |
import { Form as RemixForm, useFetcher, useSubmit } from "@remix-run/react";
import uniq from "lodash/uniq";
import React, {
ComponentProps,
FormEvent,
RefObject,
useCallback,
useEffect,
useMemo,
useRef,
useState,
} from "react";
import { useIsSubmitting, useIsValid } from "./hooks";
import { FORM_ID_FIELD } from "./internal/constants";
import {
InternalFormContext,
InternalFormContextValue,
} from "./internal/formContext";
import {
useDefaultValuesFromLoader,
useErrorResponseForForm,
useHasActiveFormSubmit,
useSetFieldErrors,
} from "./internal/hooks";
import { MultiValueMap, useMultiValueMap } from "./internal/MultiValueMap";
import { useControlledFieldStore } from "./internal/state/controlledFieldStore";
import {
SyncedFormProps,
useRootFormStore,
} from "./internal/state/createFormStore";
import { useFormStore } from "./internal/state/storeHooks";
import { useSubmitComplete } from "./internal/submissionCallbacks";
import {
mergeRefs,
useDeepEqualsMemo,
useIsomorphicLayoutEffect as useLayoutEffect,
} from "./internal/util";
import { FieldErrors, Validator } from "./validation/types";
export type FormProps<DataType> = {
/**
* A `Validator` object that describes how to validate the form.
*/
validator: Validator<DataType>;
/**
* A submit callback that gets called when the form is submitted
* after all validations have been run.
*/
onSubmit?: (
data: DataType,
event: React.FormEvent<HTMLFormElement>
) => void | Promise<void>;
/**
* Allows you to provide a `fetcher` from remix's `useFetcher` hook.
* The form will use the fetcher for loading states, action data, etc
* instead of the default form action.
*/
fetcher?: ReturnType<typeof useFetcher>;
/**
* Accepts an object of default values for the form
* that will automatically be propagated to the form fields via `useField`.
*/
defaultValues?: Partial<DataType>;
/**
* A ref to the form element.
*/
formRef?: React.RefObject<HTMLFormElement>;
/**
* An optional sub-action to use for the form.
* Setting a value here will cause the form to be submitted with an extra `subaction` value.
* This can be useful when there are multiple forms on the screen handled by the same action.
*/
subaction?: string;
/**
* Reset the form to the default values after the form has been successfully submitted.
* This is useful if you want to submit the same form multiple times,
* and don't redirect in-between submissions.
*/
resetAfterSubmit?: boolean;
/**
* Normally, the first invalid input will be focused when the validation fails on form submit.
* Set this to `false` to disable this behavior.
*/
disableFocusOnError?: boolean;
} & Omit<ComponentProps<typeof RemixForm>, "onSubmit">;
const getDataFromForm = (el: HTMLFormElement) => new FormData(el);
function nonNull<T>(value: T | null | undefined): value is T {
return value !== null;
}
const focusFirstInvalidInput = (
fieldErrors: FieldErrors,
customFocusHandlers: MultiValueMap<string, () => void>,
formElement: HTMLFormElement
) => {
const namesInOrder = [...formElement.elements]
.map((el) => {
const input = el instanceof RadioNodeList ? el[0] : el;
if (input instanceof HTMLInputElement) return input.name;
return null;
})
.filter(nonNull)
.filter((name) => name in fieldErrors);
const uniqueNamesInOrder = uniq(namesInOrder);
for (const fieldName of uniqueNamesInOrder) {
if (customFocusHandlers.has(fieldName)) {
customFocusHandlers.getAll(fieldName).forEach((handler) => {
handler();
});
break;
}
const elem = formElement.elements.namedItem(fieldName);
if (!elem) continue;
if (elem instanceof RadioNodeList) {
const selectedRadio =
[...elem]
.filter(
(item): item is HTMLInputElement => item instanceof HTMLInputElement
)
.find((item) => item.value === elem.value) ?? elem[0];
if (selectedRadio && selectedRadio instanceof HTMLInputElement) {
selectedRadio.focus();
break;
}
}
if (elem instanceof HTMLInputElement) {
if (elem.type === "hidden") {
continue;
}
elem.focus();
break;
}
}
};
const useFormId = (providedId?: string): string | symbol => {
// We can use a `Symbol` here because we only use it after hydration
const [symbolId] = useState(() => Symbol("remix-validated-form-id"));
return providedId ?? symbolId;
};
/**
* Use a component to access the state so we don't cause
* any extra rerenders of the whole form.
*/
const FormResetter = ({
resetAfterSubmit,
formRef,
}: {
resetAfterSubmit: boolean;
formRef: RefObject<HTMLFormElement>;
}) => {
const isSubmitting = useIsSubmitting();
const isValid = useIsValid();
useSubmitComplete(isSubmitting, () => {
if (isValid && resetAfterSubmit) {
formRef.current?.reset();
}
});
return null;
};
function formEventProxy<T extends object>(event: T): T {
let defaultPrevented = false;
return new Proxy(event, {
get: (target, prop) => {
if (prop === "preventDefault") {
return () => {
defaultPrevented = true;
};
}
if (prop === "defaultPrevented") {
return defaultPrevented;
}
return target[prop as keyof T];
},
}) as T;
}
type HTMLSubmitEvent = React.BaseSyntheticEvent<
SubmitEvent,
Event,
HTMLFormElement
>;
type HTMLFormSubmitter = HTMLButtonElement | HTMLInputElement;
/**
* The primary form component of `remix-validated-form`.
*/
export function ValidatedForm<DataType>({
validator,
onSubmit,
children,
fetcher,
action,
defaultValues: unMemoizedDefaults,
formRef: formRefProp,
onReset,
subaction,
resetAfterSubmit = false,
disableFocusOnError,
method,
replace,
id,
...rest
}: FormProps<DataType>) {
const formId = useFormId(id);
const providedDefaultValues = useDeepEqualsMemo(unMemoizedDefaults);
const contextValue = useMemo<InternalFormContextValue>(
() => ({
formId,
action,
subaction,
defaultValuesProp: providedDefaultValues,
fetcher,
}),
[action, fetcher, formId, providedDefaultValues, subaction]
);
const backendError = useErrorResponseForForm(contextValue);
const backendDefaultValues = useDefaultValuesFromLoader(contextValue);
const hasActiveSubmission = useHasActiveFormSubmit(contextValue);
const formRef = useRef<HTMLFormElement>(null);
const Form = fetcher?.Form ?? RemixForm;
const submit = useSubmit();
const setFieldErrors = useSetFieldErrors(formId);
const setFieldError = useFormStore(formId, (state) => state.setFieldError);
const reset = useFormStore(formId, (state) => state.reset);
const resetControlledFields = useControlledFieldStore((state) => state.reset);
const startSubmit = useFormStore(formId, (state) => state.startSubmit);
const endSubmit = useFormStore(formId, (state) => state.endSubmit);
const syncFormProps = useFormStore(formId, (state) => state.syncFormProps);
const setFormElementInState = useFormStore(
formId,
(state) => state.setFormElement
);
const cleanupForm = useRootFormStore((state) => state.cleanupForm);
const registerForm = useRootFormStore((state) => state.registerForm);
const customFocusHandlers = useMultiValueMap<string, () => void>();
const registerReceiveFocus: SyncedFormProps["registerReceiveFocus"] =
useCallback(
(fieldName, handler) => {
customFocusHandlers().add(fieldName, handler);
return () => {
customFocusHandlers().remove(fieldName, handler);
};
},
[customFocusHandlers]
);
// TODO: all these hooks running at startup cause extra, unnecessary renders
// There must be a nice way to avoid this.
useLayoutEffect(() => {
registerForm(formId);
return () => cleanupForm(formId);
}, [cleanupForm, formId, registerForm]);
useLayoutEffect(() => {
syncFormProps({
action,
defaultValues: providedDefaultValues ?? backendDefaultValues ?? {},
subaction,
registerReceiveFocus,
validator,
});
}, [
action,
providedDefaultValues,
registerReceiveFocus,
subaction,
syncFormProps,
backendDefaultValues,
validator,
]);
useLayoutEffect(() => {
setFormElementInState(formRef.current);
}, [setFormElementInState]);
useEffect(() => {
setFieldErrors(backendError?.fieldErrors ?? {});
}, [backendError?.fieldErrors, setFieldErrors, setFieldError]);
useSubmitComplete(hasActiveSubmission, () => {
endSubmit();
});
const handleSubmit = async (
e: FormEvent<HTMLFormElement>,
target: typeof e.currentTarget,
nativeEvent: HTMLSubmitEvent["nativeEvent"]
) => {
startSubmit();
const result = await validator.validate(getDataFromForm(e.currentTarget));
if (result.error) {
endSubmit();
setFieldErrors(result.error.fieldErrors);
if (!disableFocusOnError) {
focusFirstInvalidInput(
result.error.fieldErrors,
customFocusHandlers(),
formRef.current!
);
}
} else {
const eventProxy = formEventProxy(e);
await onSubmit?.(result.data, eventProxy);
if (eventProxy.defaultPrevented) {
endSubmit();
return;
}
const submitter = nativeEvent.submitter as HTMLFormSubmitter | null;
// We deviate from the remix code here a bit because of our async submit.
// In remix's `FormImpl`, they use `event.currentTarget` to get the form,
// but we already have the form in `formRef.current` so we can just use that.
// If we use `event.currentTarget` here, it will break because `currentTarget`
// will have changed since the start of the submission.
if (fetcher) fetcher.submit(submitter || e.currentTarget);
else submit(submitter || target, { method, replace });
}
};
return (
<Form
ref={mergeRefs([formRef, formRefProp])}
{...rest}
id={id}
action={action}
method={method}
replace={replace}
onSubmit={(e) => {
e.preventDefault();
handleSubmit(
e,
e.currentTarget,
(e as unknown as HTMLSubmitEvent).nativeEvent
);
}}
onReset={(event) => {
onReset?.(event);
if (event.defaultPrevented) return;
reset();
resetControlledFields(formId);
}}
>
<InternalFormContext.Provider value={contextValue}>
<>
<FormResetter formRef={formRef} resetAfterSubmit={resetAfterSubmit} />
{subaction && (
<input type="hidden" value={subaction} name="subaction" />
)}
{id && <input type="hidden" value={id} name={FORM_ID_FIELD} />}
{children}
</>
</InternalFormContext.Provider>
</Form>
);
} | the_stack |
import { SignerWithAddress } from "@nomiclabs/hardhat-ethers/dist/src/signer-with-address";
import { id } from "../src/index";
import ERC20MockArtifact from "../artifacts/contracts/mocks/ERC20Mock.sol/ERC20Mock.json";
import TimelockArtifact from "../artifacts/contracts/utils/Timelock.sol/Timelock.json";
import { ERC20Mock as ERC20 } from "../typechain/ERC20Mock";
import { Timelock } from "../typechain/Timelock";
import { BigNumber } from "ethers";
import { ethers, waffle } from "hardhat";
import { expect } from "chai";
const { deployContract, loadFixture } = waffle;
describe("Timelock", async function () {
const STATE = {
UNKNOWN: 0,
PROPOSED: 1,
APPROVED: 2,
};
let governorAcc: SignerWithAddress;
let governor: string;
let executorAcc: SignerWithAddress;
let executor: string;
let otherAcc: SignerWithAddress;
let other: string;
let target1: ERC20;
let target2: ERC20;
let timelock: Timelock;
let timestamp: number;
let resetChain: number;
let now: BigNumber;
before(async () => {
resetChain = await ethers.provider.send("evm_snapshot", []);
const signers = await ethers.getSigners();
governorAcc = signers[0];
governor = governorAcc.address;
executorAcc = signers[1];
executor = executorAcc.address;
otherAcc = signers[2];
other = otherAcc.address;
});
after(async () => {
await ethers.provider.send("evm_revert", [resetChain]);
});
beforeEach(async () => {
target1 = (await deployContract(governorAcc, ERC20MockArtifact, [
"Target1",
"TG1",
])) as ERC20;
target2 = (await deployContract(governorAcc, ERC20MockArtifact, [
"Target2",
"TG2",
])) as ERC20;
timelock = (await deployContract(governorAcc, TimelockArtifact, [
governor,
executor,
])) as Timelock;
({ timestamp } = await ethers.provider.getBlock("latest"));
now = BigNumber.from(timestamp);
const setDelayCall = [
{
target: timelock.address,
data: timelock.interface.encodeFunctionData("setDelay", [
2 * 24 * 60 * 60,
]),
},
];
const txHash = await timelock.callStatic.propose(setDelayCall);
await timelock.propose(setDelayCall);
await timelock.approve(txHash);
await timelock.execute(setDelayCall);
});
it("doesn't allow governance changes to governor", async () => {
await expect(timelock.setDelay(0)).to.be.revertedWith("Access denied");
await expect(timelock.grantRole("0x00000000", governor)).to.be.revertedWith(
"Only admin"
);
await expect(
timelock.grantRole(id(timelock.interface, "setDelay(uint32)"), governor)
).to.be.revertedWith("Only admin");
await expect(
timelock.revokeRole(id(timelock.interface, "setDelay(uint32)"), governor)
).to.be.revertedWith("Only admin");
});
it("only the governor can propose", async () => {
const functionCalls = [
{
target: target1.address,
data: target1.interface.encodeFunctionData("mint", [governor, 1]),
},
];
await expect(
timelock.connect(otherAcc).propose(functionCalls)
).to.be.revertedWith("Access denied");
});
it("proposes a transaction", async () => {
const functionCalls = [
{
target: target1.address,
data: target1.interface.encodeFunctionData("mint", [governor, 1]),
},
];
const txHash = await timelock.callStatic.propose(functionCalls);
await expect(await timelock.propose(functionCalls)).to.emit(
timelock,
"Proposed"
);
// .withArgs(txHash, targets, data, eta)
const proposal = await timelock.proposals(txHash);
expect(proposal.state).to.equal(STATE.PROPOSED);
});
describe("with a proposed transaction", async () => {
let functionCalls: { target: string; data: string }[];
let txHash: string;
beforeEach(async () => {
functionCalls = [
{
target: target1.address,
data: target1.interface.encodeFunctionData("mint", [governor, 1]),
},
{
target: target2.address,
data: target1.interface.encodeFunctionData("approve", [governor, 1]),
},
];
txHash = await timelock.callStatic.propose(functionCalls);
await timelock.propose(functionCalls);
});
it("doesn't allow to propose the same transaction twice", async () => {
await expect(timelock.propose(functionCalls)).to.be.revertedWith(
"Already proposed."
);
});
it("allows proposing repeated transactions", async () => {
const txHash2 = await timelock.callStatic.proposeRepeated(
functionCalls,
1
);
await expect(await timelock.proposeRepeated(functionCalls, 1)).to.emit(
timelock,
"Proposed"
);
// .withArgs(txHash, targets, data, eta)
const proposal = await timelock.proposals(txHash2);
expect(proposal.state).to.equal(STATE.PROPOSED);
});
it("only the governor can approve", async () => {
await expect(
timelock.connect(otherAcc).approve(txHash)
).to.be.revertedWith("Access denied");
});
it("doesn't allow to approve if not proposed", async () => {
const txHash =
"0x00004732e64f236e5182740fa5473c496f60cecc294538c44897d62be999d1ed";
await expect(timelock.approve(txHash)).to.be.revertedWith(
"Not proposed."
);
});
it("approves a transaction", async () => {
await expect(await timelock.approve(txHash)).to.emit(
timelock,
"Approved"
);
// .withArgs(txHash, targets, data, eta)
expect(await timelock.proposals(txHash)).not.equal(0);
});
describe("with an approved transaction", async () => {
let snapshotId: string;
let timestamp: number;
let now: BigNumber;
let eta: BigNumber;
let txHash2: string;
let txHash3: string;
beforeEach(async () => {
({ timestamp } = await ethers.provider.getBlock("latest"));
now = BigNumber.from(timestamp);
eta = now.add(await timelock.delay()).add(100);
await timelock.approve(txHash);
txHash2 = await timelock.callStatic.proposeRepeated(functionCalls, 1);
await timelock.proposeRepeated(functionCalls, 1);
await timelock.approve(txHash2);
txHash3 = await timelock.callStatic.proposeRepeated(functionCalls, 2);
await timelock.proposeRepeated(functionCalls, 2);
});
it("only the governor can execute", async () => {
await expect(
timelock.connect(otherAcc).execute(functionCalls)
).to.be.revertedWith("Access denied");
});
it("doesn't allow to execute before eta", async () => {
await expect(timelock.execute(functionCalls)).to.be.revertedWith(
"ETA not reached"
);
});
it("doesn't allow to execute if not approved", async () => {
const functionCalls = [
{
target: target1.address,
data: target1.interface.encodeFunctionData("mint", [governor, 1]),
},
];
await expect(timelock.execute(functionCalls)).to.be.revertedWith(
"Not approved."
);
});
it("doesn't allow to execute after grace period", async () => {
const eta = now.add(await timelock.delay()).add(100);
const snapshotId = await ethers.provider.send("evm_snapshot", []);
await ethers.provider.send("evm_mine", [
eta
.add(await timelock.GRACE_PERIOD())
.add(100)
.toNumber(),
]);
await expect(timelock.execute(functionCalls)).to.be.revertedWith(
"Proposal is stale"
);
await ethers.provider.send("evm_revert", [snapshotId]);
});
it("doesn't allow to execute to a non-contract", async () => {
const functionCalls = [
{
target: governor,
data: target1.interface.encodeFunctionData("mint", [governor, 1]),
},
];
const tmpTxHash = await timelock.callStatic.propose(functionCalls);
await timelock.propose(functionCalls);
await timelock.approve(tmpTxHash);
const snapshotId = await ethers.provider.send("evm_snapshot", []);
await ethers.provider.send("evm_mine", [eta.add(100).toNumber()]);
await expect(timelock.execute(functionCalls)).to.be.revertedWith(
"Call to a non-contract"
);
await ethers.provider.send("evm_revert", [snapshotId]);
});
describe("once the eta arrives", async () => {
beforeEach(async () => {
snapshotId = await ethers.provider.send("evm_snapshot", []);
await ethers.provider.send("evm_mine", [eta.toNumber()]);
});
afterEach(async () => {
await ethers.provider.send("evm_revert", [snapshotId]);
});
it("executes a transaction", async () => {
await expect(await timelock.execute(functionCalls))
.to.emit(timelock, "Executed")
// .withArgs(txHash, targets, data, eta)
.to.emit(target1, "Transfer")
// .withArgs(null, governor, 1)
.to.emit(target2, "Approval");
// .withArgs(governor, governor, 1)
expect((await timelock.proposals(txHash)).state).to.equal(
STATE.UNKNOWN
);
expect(await target1.balanceOf(governor)).to.equal(1);
expect(await target2.allowance(timelock.address, governor)).to.equal(
1
);
});
it("executes a repeated transaction", async () => {
await expect(await timelock.executeRepeated(functionCalls, 1))
.to.emit(timelock, "Executed")
// .withArgs(txHash, targets, data, eta)
.to.emit(target1, "Transfer")
// .withArgs(null, governor, 1)
.to.emit(target2, "Approval");
// .withArgs(governor, governor, 1)
expect((await timelock.proposals(txHash2)).state).to.equal(
STATE.UNKNOWN
);
expect(await target1.balanceOf(governor)).to.equal(1);
expect(await target2.allowance(timelock.address, governor)).to.equal(
1
);
});
});
});
});
}); | the_stack |
import * as React from 'react';
import { IDataGridStore } from '../providers';
import { connectStore } from '../hoc';
import { isFunction, getDataItem } from '../utils';
import { DataGridEnums } from '../common/@enums';
import { IDataGrid } from '../common/@types';
import getAvailScrollTop from '../utils/getAvailScrollTop';
import getAvailScrollLeft from '../utils/getAvailScrollLeft';
interface IProps extends IDataGridStore {}
interface IState {}
class DataGridEvents extends React.Component<IProps, IState> {
busy: boolean = false;
state = {};
// onKeyUp = (e: React.KeyboardEvent<any>) => {
// const {
// colGroup = [],
// focusedRow = 0,
// focusedCol = 0,
// setStoreState,
// } = this.props;
// switch (e.which) {
// case DataGridEnums.KeyCodes.ENTER:
// const col = colGroup[focusedCol];
// if (!col.editor) {
// return;
// }
// setStoreState({
// isInlineEditing: true,
// inlineEditingCell: {
// rowIndex: focusedRow,
// colIndex: col.colIndex,
// editor: col.editor,
// },
// });
// return;
// default:
// return;
// }
// };
handleKeyDown = (e: KeyboardEvent) => {
return new Promise((resolve, reject) => {
const {
data = {},
dataLength = 0,
rootNode,
clipBoardNode,
colGroup = [],
headerColGroup = [],
selectionRows = {},
selectionCols = {},
setStoreState,
scrollTop = 0,
scrollLeft = 0,
focusedRow = 0,
focusedCol = 0,
options = {},
styles = {},
predefinedFormatter = {},
isInlineEditing,
inlineEditingCell,
} = this.props;
const {
printStartColIndex = 0,
printEndColIndex = colGroup.length - 1,
} = this.props;
const {
frozenRowIndex = 0,
frozenColumnIndex = 0,
disableClipboard = false,
} = options;
const {
bodyTrHeight = 0,
scrollContentWidth = 0,
scrollContentHeight = 0,
scrollContentContainerWidth = 0,
scrollContentContainerHeight = 0,
frozenPanelWidth = 0,
rightPanelWidth = 0,
verticalScrollerWidth = 0,
} = styles;
const sRowIndex = Math.floor(-scrollTop / bodyTrHeight) + frozenRowIndex;
const eRowIndex =
Math.floor(-scrollTop / bodyTrHeight) +
// frozenRowIndex +
Math.floor(scrollContentContainerHeight / bodyTrHeight);
const sColIndex = printStartColIndex;
const eColIndex = printEndColIndex;
const pRowSize = Math.floor(scrollContentContainerHeight / bodyTrHeight);
const getScrollLeftOptions = {
colGroup,
sColIndex,
eColIndex,
frozenColumnIndex,
frozenPanelWidth,
verticalScrollerWidth,
rightPanelWidth,
scrollContentWidth,
scrollContentHeight,
scrollContentContainerWidth,
scrollContentContainerHeight,
scrollTop,
scrollLeft,
};
const getScrollTopOptions = {
frozenRowIndex,
sRowIndex,
eRowIndex,
scrollTop,
scrollLeft,
scrollContentWidth,
scrollContentHeight,
scrollContentContainerWidth,
scrollContentContainerHeight,
bodyTrHeight,
pRowSize,
};
if (e.metaKey || e.ctrlKey) {
switch (e.which) {
case DataGridEnums.MetaKeycodes.C:
if (!disableClipboard) {
e.preventDefault();
let copySuccess: boolean = false;
const copiedString: string[] = [];
for (let rk in selectionRows) {
if (selectionRows[rk]) {
const item = getDataItem(data, Number(rk));
const copiedRow: string[] = [];
if (item) {
for (let ck in selectionCols) {
if (selectionCols[ck]) {
let val = '';
const { formatter, key: colKey = '' } = headerColGroup[
ck
];
const formatterData = {
item,
index: Number(rk),
key: colKey,
value: item.value[colKey],
};
if (
typeof formatter === 'string' &&
formatter in predefinedFormatter
) {
val = predefinedFormatter[formatter](formatterData);
} else if (isFunction(formatter)) {
val = (formatter as IDataGrid.formatterFunction)(
formatterData,
);
} else {
val = item.value[headerColGroup[ck].key];
}
copiedRow.push(val || '');
}
}
}
copiedString.push(copiedRow.join('\t'));
}
}
if (clipBoardNode && clipBoardNode.current) {
clipBoardNode.current.value = copiedString.join('\n');
clipBoardNode.current.select();
}
try {
copySuccess = document.execCommand('copy');
} catch (e) {}
rootNode && rootNode.current && rootNode.current.focus();
if (copySuccess) {
resolve();
} else {
reject('not working execCommand');
}
} else {
reject('disableClipboard');
}
break;
case DataGridEnums.MetaKeycodes.A:
e.preventDefault();
let state = {
dragging: false,
selectionRows: {},
selectionCols: {},
selectionSCol: 0,
selectionECol: 0,
selectionSRow: 0,
selectionERow: dataLength,
// focusedRow: 0,
// focusedCol: 0,
};
Array.from(new Array(dataLength), (x, i) => {
state.selectionRows[i] = true;
});
Object.values(colGroup).forEach(col => {
state.selectionCols[col.colIndex || 0] = true;
state.selectionECol = col.colIndex || 0;
});
setStoreState(state, () => {
resolve();
});
break;
default:
resolve();
break;
}
} else {
let focusRow: number;
let focusCol: number;
switch (e.which) {
case DataGridEnums.KeyCodes.ESC:
setStoreState(
{
selectionRows: {
[focusedRow]: true,
},
selectionCols: {
[focusedCol]: true,
},
},
() => {
resolve();
},
);
break;
case DataGridEnums.KeyCodes.HOME:
focusRow = 0;
setStoreState(
{
scrollTop: getAvailScrollTop(focusRow, getScrollTopOptions),
selectionRows: {
[focusRow]: true,
},
focusedRow: focusRow,
},
() => {
resolve();
},
);
break;
case DataGridEnums.KeyCodes.END:
focusRow = dataLength - 1;
setStoreState(
{
scrollTop: getAvailScrollTop(focusRow, getScrollTopOptions),
selectionRows: {
[focusRow]: true,
},
focusedRow: focusRow,
},
() => {
resolve();
},
);
break;
case DataGridEnums.KeyCodes.PAGE_UP:
e.preventDefault();
focusRow = focusedRow - pRowSize < 1 ? 0 : focusedRow - pRowSize;
setStoreState(
{
scrollTop: getAvailScrollTop(focusRow, getScrollTopOptions),
selectionRows: {
[focusRow]: true,
},
focusedRow: focusRow,
},
() => {
resolve();
},
);
break;
case DataGridEnums.KeyCodes.PAGE_DOWN:
e.preventDefault();
focusRow =
focusedRow + pRowSize >= dataLength
? dataLength - 1
: focusedRow + pRowSize;
setStoreState(
{
scrollTop: getAvailScrollTop(focusRow, getScrollTopOptions),
selectionRows: {
[focusRow]: true,
},
focusedRow: focusRow,
},
() => {
resolve();
},
);
break;
case DataGridEnums.KeyCodes.UP_ARROW:
e.preventDefault();
focusRow = focusedRow < 1 ? 0 : focusedRow - 1;
setStoreState(
{
scrollTop: getAvailScrollTop(focusRow, getScrollTopOptions),
selectionRows: {
[focusRow]: true,
},
focusedRow: focusRow,
},
() => {
setTimeout(() => {
resolve();
});
},
);
break;
case DataGridEnums.KeyCodes.DOWN_ARROW:
e.preventDefault();
focusRow =
focusedRow + 1 >= dataLength ? dataLength - 1 : focusedRow + 1;
setStoreState(
{
scrollTop: getAvailScrollTop(focusRow, getScrollTopOptions),
selectionRows: {
[focusRow]: true,
},
focusedRow: focusRow,
},
() => {
setTimeout(() => {
resolve();
});
},
);
break;
case DataGridEnums.KeyCodes.LEFT_ARROW:
e.preventDefault();
focusCol = focusedCol < 1 ? 0 : focusedCol - 1;
setStoreState(
{
scrollLeft: getAvailScrollLeft(focusCol, getScrollLeftOptions),
selectionCols: {
[focusCol]: true,
},
focusedCol: focusCol,
},
() => {
setTimeout(() => {
resolve();
});
},
);
break;
case DataGridEnums.KeyCodes.RIGHT_ARROW:
e.preventDefault();
focusCol =
focusedCol + 1 >= colGroup.length
? colGroup.length - 1
: focusedCol + 1;
setStoreState(
{
scrollLeft: getAvailScrollLeft(focusCol, getScrollLeftOptions),
selectionCols: {
[focusCol]: true,
},
focusedCol: focusCol,
},
() => {
setTimeout(() => {
resolve();
});
},
);
break;
case DataGridEnums.KeyCodes.ENTER:
const col = colGroup[focusedCol];
if (!col.editor) {
resolve();
break;
}
setStoreState(
{
isInlineEditing: true,
inlineEditingCell: {
rowIndex: focusedRow,
colIndex: col.colIndex,
editor: col.editor,
},
},
() => {
setTimeout(() => {
resolve();
});
},
);
break;
default:
resolve();
break;
}
}
});
};
onContextmenu = (e: MouseEvent) => {
const {
onRightClick,
focusedRow,
focusedCol,
data,
colGroup,
loading,
loadingData,
} = this.props;
if (this.busy || loadingData || loading) {
e.preventDefault();
return;
}
if (
onRightClick &&
data &&
typeof focusedRow !== 'undefined' &&
typeof focusedCol !== 'undefined' &&
colGroup
) {
const { key: itemKey = '' } = colGroup[focusedCol];
const item = getDataItem(data, focusedRow);
if (!item) {
return;
}
onRightClick({
e,
item,
value: item.value[itemKey],
focusedRow,
focusedCol,
});
}
};
onKeyDownInlineEditor = (e: KeyboardEvent) => {
const {
data = {},
inlineEditingCell,
colGroup = [],
printStartColIndex: sColIndex = 0,
printEndColIndex: eColIndex = 0,
scrollTop = 0,
scrollLeft = 0,
focusedCol = -1,
focusedRow: rowIndex = 0,
options: { frozenColumnIndex = 0 } = {},
styles: {
scrollContentWidth = 0,
scrollContentHeight = 0,
scrollContentContainerWidth = 0,
scrollContentContainerHeight = 0,
frozenPanelWidth = 0,
rightPanelWidth = 0,
verticalScrollerWidth = 0,
} = {},
dispatch,
setStoreState,
} = this.props;
const { colIndex = 0, editor: colEditor } = colGroup[focusedCol];
const editor: IDataGrid.IColEditor =
colEditor === 'text'
? { type: 'text' }
: (colEditor as IDataGrid.IColEditor);
if (editor.type === 'checkbox') {
// console.log('catch in onKeyDownInlineEditor', inlineEditingCell);
switch (e.which) {
case DataGridEnums.KeyCodes.TAB:
e.preventDefault();
const getScrollLeftOptions = {
colGroup,
sColIndex,
eColIndex,
frozenColumnIndex,
frozenPanelWidth,
verticalScrollerWidth,
rightPanelWidth,
scrollContentWidth,
scrollContentHeight,
scrollContentContainerWidth,
scrollContentContainerHeight,
scrollTop,
scrollLeft,
};
const nextCol =
colGroup[
e && e.shiftKey
? colIndex - 1 > -1
? colIndex - 1
: colGroup.length - 1
: colIndex + 1 < colGroup.length
? colIndex + 1
: 0
];
if (nextCol.colIndex !== undefined) {
setStoreState({
scrollLeft: getAvailScrollLeft(
nextCol.colIndex,
getScrollLeftOptions,
),
selectionCols: {
[nextCol.colIndex]: true,
},
focusedCol: nextCol.colIndex,
isInlineEditing: true,
inlineEditingCell: {
rowIndex: rowIndex,
colIndex: nextCol.colIndex,
editor: nextCol.editor,
},
});
}
break;
// case DataGridEnums.KeyCodes.SPACE:
case DataGridEnums.KeyCodes.ENTER:
e.preventDefault();
const item: IDataGrid.IDataItem = data[rowIndex];
const value = item.value[colGroup[colIndex].key!];
// console.log('checkbox event fire SPACE, ENTER', e.which);
const disabled = editor.disable
? editor.disable({
col: colGroup[colIndex],
rowIndex,
colIndex,
item,
value,
})
: false;
if (disabled) {
return;
}
dispatch(DataGridEnums.DispatchTypes.UPDATE, {
row: rowIndex,
col: colGroup[colIndex],
colIndex,
value: !value,
eventWhichKey: 'click-checkbox',
keepEditing: false,
});
break;
default:
}
}
};
// onFireEvent = async (e: any) => {
// const {
// loading,
// loadingData,
// isInlineEditing = false,
// inlineEditingCell,
// colGroup = [],
// focusedRow = -1,
// focusedCol = -1,
// data = {},
// } = this.props;
// let stopEvent =
// isInlineEditing &&
// inlineEditingCell &&
// inlineEditingCell.colIndex === focusedCol &&
// inlineEditingCell.rowIndex === focusedRow;
// if (this.busy || loadingData || loading) {
// e.preventDefault();
// return;
// }
// if (e.type === DataGridEnums.EventNames.KEYDOWN && colGroup[focusedCol]) {
// const colEditor = colGroup[focusedCol].editor;
// const editor: IDataGrid.IColEditor =
// colEditor === 'text'
// ? { type: 'text' }
// : (colEditor as IDataGrid.IColEditor);
// if (editor) {
// if (editor.type === 'checkbox') {
// this.onKeyDownInlineEditor(e);
// stopEvent = false;
// } else {
// const item: IDataGrid.IDataItem = data[focusedRow];
// if (item) {
// const value = item.value[colGroup[focusedCol].key!];
// const disabled = editor.disable
// ? editor.disable({
// col: colGroup[focusedCol],
// rowIndex: focusedRow,
// colIndex: focusedCol,
// item,
// value,
// })
// : false;
// if (disabled) {
// stopEvent = false;
// }
// }
// }
// }
// }
// if (stopEvent) {
// return;
// }
// if (this.props.onBeforeEvent) {
// this.props.onBeforeEvent({ e, eventName: e.type });
// }
// switch (e.type) {
// case DataGridEnums.EventNames.KEYDOWN:
// this.busy = true;
// try {
// await this.onKeyDown(e);
// } catch (err) {
// if (this.props.onError) {
// this.props.onError(err, e);
// } else {
// // console.log(err);
// }
// }
// this.busy = false;
// break;
// case DataGridEnums.EventNames.KEYUP:
// this.onKeyUp(e);
// break;
// case DataGridEnums.EventNames.CONTEXTMENU:
// this.onContextmenu(e);
// break;
// default:
// break;
// }
// };
onKeyDown = async (e: KeyboardEvent) => {
const {
loading,
loadingData,
isInlineEditing = false,
inlineEditingCell,
colGroup = [],
focusedRow = -1,
focusedCol = -1,
data = {},
} = this.props;
let stopEvent =
isInlineEditing &&
inlineEditingCell &&
inlineEditingCell.colIndex === focusedCol &&
inlineEditingCell.rowIndex === focusedRow;
if (this.busy || loadingData || loading) {
e.preventDefault();
return;
}
if (colGroup[focusedCol]) {
const colEditor = colGroup[focusedCol].editor;
const editor: IDataGrid.IColEditor =
colEditor === 'text'
? { type: 'text' }
: (colEditor as IDataGrid.IColEditor);
if (editor) {
if (editor.type === 'checkbox') {
this.onKeyDownInlineEditor(e);
stopEvent = false;
} else {
const item: IDataGrid.IDataItem = data[focusedRow];
if (item) {
const value = item.value[colGroup[focusedCol].key!];
const disabled = editor.disable
? editor.disable({
col: colGroup[focusedCol],
rowIndex: focusedRow,
colIndex: focusedCol,
item,
value,
})
: false;
if (disabled) {
stopEvent = false;
}
}
}
}
}
if (stopEvent) {
return;
}
e.preventDefault();
this.busy = true;
try {
await this.handleKeyDown(e);
} catch (err) {
if (this.props.onError) {
this.props.onError(err, e);
} else {
// console.log(err);
}
}
this.busy = false;
};
componentDidMount() {
const { rootNode } = this.props;
if (rootNode && rootNode.current) {
rootNode.current.addEventListener('keydown', this.onKeyDown, false);
// rootNode.current.addEventListener('keyup', this.onFireEvent, false);
rootNode.current.addEventListener(
'contextmenu',
this.onContextmenu,
false,
);
}
}
componentWillUnmount() {
const { rootNode } = this.props;
if (rootNode && rootNode.current) {
rootNode.current.removeEventListener('keydown', this.onKeyDown);
// rootNode.current.removeEventListener('keyup', this.onFireEvent);
rootNode.current.removeEventListener('contextmenu', this.onContextmenu);
}
}
render() {
return <div>{this.props.children}</div>;
}
}
export default connectStore(DataGridEvents); | the_stack |
import * as coreClient from "@azure/core-client";
export const ResourceSku: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "ResourceSku",
modelProperties: {
name: {
serializedName: "name",
required: true,
type: {
name: "String"
}
},
tier: {
serializedName: "tier",
type: {
name: "String"
}
},
capacity: {
defaultValue: 1,
constraints: {
InclusiveMaximum: 8,
InclusiveMinimum: 1
},
serializedName: "capacity",
type: {
name: "Number"
}
}
}
}
};
export const AnalysisServicesServerMutableProperties: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "AnalysisServicesServerMutableProperties",
modelProperties: {
asAdministrators: {
serializedName: "asAdministrators",
type: {
name: "Composite",
className: "ServerAdministrators"
}
},
backupBlobContainerUri: {
serializedName: "backupBlobContainerUri",
type: {
name: "String"
}
},
gatewayDetails: {
serializedName: "gatewayDetails",
type: {
name: "Composite",
className: "GatewayDetails"
}
},
ipV4FirewallSettings: {
serializedName: "ipV4FirewallSettings",
type: {
name: "Composite",
className: "IPv4FirewallSettings"
}
},
querypoolConnectionMode: {
defaultValue: "All",
serializedName: "querypoolConnectionMode",
type: {
name: "Enum",
allowedValues: ["All", "ReadOnly"]
}
},
managedMode: {
defaultValue: "1",
serializedName: "managedMode",
type: {
name: "Enum",
allowedValues: [0, 1]
}
},
serverMonitorMode: {
defaultValue: "1",
serializedName: "serverMonitorMode",
type: {
name: "Enum",
allowedValues: [0, 1]
}
}
}
}
};
export const ServerAdministrators: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "ServerAdministrators",
modelProperties: {
members: {
serializedName: "members",
type: {
name: "Sequence",
element: {
type: {
name: "String"
}
}
}
}
}
}
};
export const GatewayDetails: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "GatewayDetails",
modelProperties: {
gatewayResourceId: {
serializedName: "gatewayResourceId",
type: {
name: "String"
}
},
gatewayObjectId: {
serializedName: "gatewayObjectId",
readOnly: true,
type: {
name: "String"
}
},
dmtsClusterUri: {
serializedName: "dmtsClusterUri",
readOnly: true,
type: {
name: "String"
}
}
}
}
};
export const IPv4FirewallSettings: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "IPv4FirewallSettings",
modelProperties: {
firewallRules: {
serializedName: "firewallRules",
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "IPv4FirewallRule"
}
}
}
},
enablePowerBIService: {
serializedName: "enablePowerBIService",
type: {
name: "Boolean"
}
}
}
}
};
export const IPv4FirewallRule: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "IPv4FirewallRule",
modelProperties: {
firewallRuleName: {
serializedName: "firewallRuleName",
type: {
name: "String"
}
},
rangeStart: {
serializedName: "rangeStart",
type: {
name: "String"
}
},
rangeEnd: {
serializedName: "rangeEnd",
type: {
name: "String"
}
}
}
}
};
export const Resource: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "Resource",
modelProperties: {
id: {
serializedName: "id",
readOnly: true,
type: {
name: "String"
}
},
name: {
serializedName: "name",
readOnly: true,
type: {
name: "String"
}
},
type: {
serializedName: "type",
readOnly: true,
type: {
name: "String"
}
},
location: {
serializedName: "location",
required: true,
type: {
name: "String"
}
},
sku: {
serializedName: "sku",
type: {
name: "Composite",
className: "ResourceSku"
}
},
tags: {
serializedName: "tags",
type: {
name: "Dictionary",
value: { type: { name: "String" } }
}
}
}
}
};
export const ErrorResponse: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "ErrorResponse",
modelProperties: {
error: {
serializedName: "error",
type: {
name: "Composite",
className: "ErrorDetail"
}
}
}
}
};
export const ErrorDetail: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "ErrorDetail",
modelProperties: {
code: {
serializedName: "code",
readOnly: true,
type: {
name: "String"
}
},
message: {
serializedName: "message",
readOnly: true,
type: {
name: "String"
}
},
target: {
serializedName: "target",
readOnly: true,
type: {
name: "String"
}
},
subCode: {
serializedName: "subCode",
readOnly: true,
type: {
name: "Number"
}
},
httpStatusCode: {
serializedName: "httpStatusCode",
readOnly: true,
type: {
name: "Number"
}
},
timeStamp: {
serializedName: "timeStamp",
readOnly: true,
type: {
name: "String"
}
},
details: {
serializedName: "details",
readOnly: true,
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "ErrorDetail"
}
}
}
},
additionalInfo: {
serializedName: "additionalInfo",
readOnly: true,
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "ErrorAdditionalInfo"
}
}
}
}
}
}
};
export const ErrorAdditionalInfo: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "ErrorAdditionalInfo",
modelProperties: {
type: {
serializedName: "type",
readOnly: true,
type: {
name: "String"
}
},
info: {
serializedName: "info",
readOnly: true,
type: {
name: "Dictionary",
value: { type: { name: "any" } }
}
}
}
}
};
export const AnalysisServicesServerUpdateParameters: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "AnalysisServicesServerUpdateParameters",
modelProperties: {
sku: {
serializedName: "sku",
type: {
name: "Composite",
className: "ResourceSku"
}
},
tags: {
serializedName: "tags",
type: {
name: "Dictionary",
value: { type: { name: "String" } }
}
},
asAdministrators: {
serializedName: "properties.asAdministrators",
type: {
name: "Composite",
className: "ServerAdministrators"
}
},
backupBlobContainerUri: {
serializedName: "properties.backupBlobContainerUri",
type: {
name: "String"
}
},
gatewayDetails: {
serializedName: "properties.gatewayDetails",
type: {
name: "Composite",
className: "GatewayDetails"
}
},
ipV4FirewallSettings: {
serializedName: "properties.ipV4FirewallSettings",
type: {
name: "Composite",
className: "IPv4FirewallSettings"
}
},
querypoolConnectionMode: {
defaultValue: "All",
serializedName: "properties.querypoolConnectionMode",
type: {
name: "Enum",
allowedValues: ["All", "ReadOnly"]
}
},
managedMode: {
defaultValue: "1",
serializedName: "properties.managedMode",
type: {
name: "Enum",
allowedValues: [0, 1]
}
},
serverMonitorMode: {
defaultValue: "1",
serializedName: "properties.serverMonitorMode",
type: {
name: "Enum",
allowedValues: [0, 1]
}
}
}
}
};
export const AnalysisServicesServers: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "AnalysisServicesServers",
modelProperties: {
value: {
serializedName: "value",
required: true,
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "AnalysisServicesServer"
}
}
}
}
}
}
};
export const SkuEnumerationForNewResourceResult: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "SkuEnumerationForNewResourceResult",
modelProperties: {
value: {
serializedName: "value",
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "ResourceSku"
}
}
}
}
}
}
};
export const SkuEnumerationForExistingResourceResult: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "SkuEnumerationForExistingResourceResult",
modelProperties: {
value: {
serializedName: "value",
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "SkuDetailsForExistingResource"
}
}
}
}
}
}
};
export const SkuDetailsForExistingResource: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "SkuDetailsForExistingResource",
modelProperties: {
sku: {
serializedName: "sku",
type: {
name: "Composite",
className: "ResourceSku"
}
},
resourceType: {
serializedName: "resourceType",
type: {
name: "String"
}
}
}
}
};
export const GatewayListStatusLive: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "GatewayListStatusLive",
modelProperties: {
status: {
defaultValue: 0,
isConstant: true,
serializedName: "status",
type: {
name: "Number"
}
}
}
}
};
export const GatewayListStatusError: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "GatewayListStatusError",
modelProperties: {
error: {
serializedName: "error",
type: {
name: "Composite",
className: "ErrorDetail"
}
}
}
}
};
export const CheckServerNameAvailabilityParameters: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "CheckServerNameAvailabilityParameters",
modelProperties: {
name: {
constraints: {
Pattern: new RegExp("^[a-z][a-z0-9]*$"),
MaxLength: 63,
MinLength: 3
},
serializedName: "name",
type: {
name: "String"
}
},
type: {
defaultValue: "Microsoft.AnalysisServices/servers",
serializedName: "type",
type: {
name: "String"
}
}
}
}
};
export const CheckServerNameAvailabilityResult: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "CheckServerNameAvailabilityResult",
modelProperties: {
nameAvailable: {
serializedName: "nameAvailable",
type: {
name: "Boolean"
}
},
reason: {
serializedName: "reason",
type: {
name: "String"
}
},
message: {
serializedName: "message",
type: {
name: "String"
}
}
}
}
};
export const OperationStatus: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "OperationStatus",
modelProperties: {
id: {
serializedName: "id",
type: {
name: "String"
}
},
name: {
serializedName: "name",
type: {
name: "String"
}
},
startTime: {
serializedName: "startTime",
type: {
name: "String"
}
},
endTime: {
serializedName: "endTime",
type: {
name: "String"
}
},
status: {
serializedName: "status",
type: {
name: "String"
}
},
error: {
serializedName: "error",
type: {
name: "Composite",
className: "ErrorDetail"
}
}
}
}
};
export const OperationListResult: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "OperationListResult",
modelProperties: {
value: {
serializedName: "value",
readOnly: true,
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "Operation"
}
}
}
},
nextLink: {
serializedName: "nextLink",
readOnly: true,
type: {
name: "String"
}
}
}
}
};
export const Operation: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "Operation",
modelProperties: {
name: {
serializedName: "name",
readOnly: true,
type: {
name: "String"
}
},
display: {
serializedName: "display",
type: {
name: "Composite",
className: "OperationDisplay"
}
},
origin: {
serializedName: "origin",
readOnly: true,
type: {
name: "String"
}
},
properties: {
serializedName: "properties",
type: {
name: "Composite",
className: "OperationProperties"
}
}
}
}
};
export const OperationDisplay: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "OperationDisplay",
modelProperties: {
provider: {
serializedName: "provider",
readOnly: true,
type: {
name: "String"
}
},
resource: {
serializedName: "resource",
readOnly: true,
type: {
name: "String"
}
},
operation: {
serializedName: "operation",
readOnly: true,
type: {
name: "String"
}
},
description: {
serializedName: "description",
readOnly: true,
type: {
name: "String"
}
}
}
}
};
export const OperationProperties: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "OperationProperties",
modelProperties: {
serviceSpecification: {
serializedName: "serviceSpecification",
type: {
name: "Composite",
className: "OperationPropertiesServiceSpecification"
}
}
}
}
};
export const OperationPropertiesServiceSpecification: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "OperationPropertiesServiceSpecification",
modelProperties: {
metricSpecifications: {
serializedName: "metricSpecifications",
readOnly: true,
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "MetricSpecifications"
}
}
}
},
logSpecifications: {
serializedName: "logSpecifications",
readOnly: true,
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "LogSpecifications"
}
}
}
}
}
}
};
export const MetricSpecifications: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "MetricSpecifications",
modelProperties: {
name: {
serializedName: "name",
readOnly: true,
type: {
name: "String"
}
},
displayName: {
serializedName: "displayName",
readOnly: true,
type: {
name: "String"
}
},
displayDescription: {
serializedName: "displayDescription",
readOnly: true,
type: {
name: "String"
}
},
unit: {
serializedName: "unit",
readOnly: true,
type: {
name: "String"
}
},
aggregationType: {
serializedName: "aggregationType",
readOnly: true,
type: {
name: "String"
}
},
dimensions: {
serializedName: "dimensions",
readOnly: true,
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "MetricDimensions"
}
}
}
}
}
}
};
export const MetricDimensions: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "MetricDimensions",
modelProperties: {
name: {
serializedName: "name",
readOnly: true,
type: {
name: "String"
}
},
displayName: {
serializedName: "displayName",
readOnly: true,
type: {
name: "String"
}
}
}
}
};
export const LogSpecifications: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "LogSpecifications",
modelProperties: {
name: {
serializedName: "name",
readOnly: true,
type: {
name: "String"
}
},
displayName: {
serializedName: "displayName",
readOnly: true,
type: {
name: "String"
}
},
blobDuration: {
serializedName: "blobDuration",
readOnly: true,
type: {
name: "String"
}
}
}
}
};
export const AnalysisServicesServerProperties: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "AnalysisServicesServerProperties",
modelProperties: {
...AnalysisServicesServerMutableProperties.type.modelProperties,
state: {
serializedName: "state",
readOnly: true,
type: {
name: "String"
}
},
provisioningState: {
serializedName: "provisioningState",
readOnly: true,
type: {
name: "String"
}
},
serverFullName: {
serializedName: "serverFullName",
readOnly: true,
type: {
name: "String"
}
},
sku: {
serializedName: "sku",
type: {
name: "Composite",
className: "ResourceSku"
}
}
}
}
};
export const AnalysisServicesServer: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "AnalysisServicesServer",
modelProperties: {
...Resource.type.modelProperties,
asAdministrators: {
serializedName: "properties.asAdministrators",
type: {
name: "Composite",
className: "ServerAdministrators"
}
},
backupBlobContainerUri: {
serializedName: "properties.backupBlobContainerUri",
type: {
name: "String"
}
},
gatewayDetails: {
serializedName: "properties.gatewayDetails",
type: {
name: "Composite",
className: "GatewayDetails"
}
},
ipV4FirewallSettings: {
serializedName: "properties.ipV4FirewallSettings",
type: {
name: "Composite",
className: "IPv4FirewallSettings"
}
},
querypoolConnectionMode: {
defaultValue: "All",
serializedName: "properties.querypoolConnectionMode",
type: {
name: "Enum",
allowedValues: ["All", "ReadOnly"]
}
},
managedMode: {
defaultValue: "1",
serializedName: "properties.managedMode",
type: {
name: "Enum",
allowedValues: [0, 1]
}
},
serverMonitorMode: {
defaultValue: "1",
serializedName: "properties.serverMonitorMode",
type: {
name: "Enum",
allowedValues: [0, 1]
}
},
state: {
serializedName: "properties.state",
readOnly: true,
type: {
name: "String"
}
},
provisioningState: {
serializedName: "properties.provisioningState",
readOnly: true,
type: {
name: "String"
}
},
serverFullName: {
serializedName: "properties.serverFullName",
readOnly: true,
type: {
name: "String"
}
},
skuPropertiesSku: {
serializedName: "properties.sku",
type: {
name: "Composite",
className: "ResourceSku"
}
}
}
}
}; | the_stack |
import { Collection } from '../util';
import { BaseManager } from './BaseManager';
import { SearchTweetsBook, TweetsCountBook } from '../books';
import {
RemovedRetweetResponse,
RequestData,
RetweetResponse,
TweetLikeResponse,
TweetReplyHideUnhideResponse,
TweetUnlikeResponse,
SimplifiedTweet,
User,
Tweet,
TweetCountBucket,
} from '../structures';
import { CustomError, CustomTypeError } from '../errors';
import type { Client } from '../client';
import type {
TweetManagerFetchResult,
TweetResolvable,
FetchTweetOptions,
FetchTweetsOptions,
SearchTweetsOptions,
SearchTweetsBookOptions,
TweetsCountBookOptions,
CountTweetsOptions,
} from '../typings';
import type {
DeleteTweetsLikeResponse,
DeleteUsersRetweetsResponse,
GetMultipleTweetsByIdsQuery,
GetMultipleTweetsByIdsResponse,
GetSingleTweetByIdQuery,
GetSingleTweetByIdResponse,
GetTweetsLikingUsersQuery,
GetTweetsLikingUsersResponse,
GetTweetsRetweetingUsersQuery,
GetTweetsRetweetingUsersResponse,
PostTweetsLikeJSONBody,
PostTweetsLikeResponse,
PostUsersRetweetsJSONBody,
PostUsersRetweetsResponse,
PutTweetReplyHideUnhideJSONBody,
PutTweetReplyHideUnhideResponse,
Snowflake,
} from 'twitter-types';
/**
* The manager class that holds API methods for {@link Tweet} objects and stores their cache
*/
export class TweetManager extends BaseManager<Snowflake, TweetResolvable, Tweet> {
/**
* @param client The logged in {@link Client} instance
*/
constructor(client: Client) {
super(client, Tweet);
}
/**
* Resolves a tweet resolvable to its respective {@link Tweet} object.
* @param tweetResolvable An ID or instance that can be resolved to a tweet object
* @returns The resolved tweet object
*/
override resolve(tweetResolvable: TweetResolvable): Tweet | null {
const tweet = super.resolve(tweetResolvable);
if (tweet) return tweet;
if (tweetResolvable instanceof SimplifiedTweet) return super.resolve(tweetResolvable.id);
return null;
}
/**
* Resolves a tweet resolvable to its respective id.
* @param tweetResolvable An ID or instance that can be resolved to a tweet object
* @returns The id of the resolved tweet object
*/
override resolveId(tweetResolvable: TweetResolvable): Snowflake | null {
const tweetId = super.resolveId(tweetResolvable);
if (typeof tweetId === 'string') return tweetId;
if (tweetResolvable instanceof SimplifiedTweet) return tweetResolvable.id;
return null;
}
/**
* Fetches tweets from twitter.
* @param options The options for fetching tweets
* @returns A {@link Tweet} or a {@link Collection} of them as a `Promise`
*/
async fetch<T extends FetchTweetOptions | FetchTweetsOptions>(options: T): Promise<TweetManagerFetchResult<T>> {
if (typeof options !== 'object') throw new CustomTypeError('INVALID_TYPE', 'options', 'object', true);
if ('tweet' in options) {
const tweetId = this.resolveId(options.tweet);
if (!tweetId) throw new CustomError('TWEET_RESOLVE_ID', 'fetch');
return this.#fetchSingleTweet(tweetId, options) as Promise<TweetManagerFetchResult<T>>;
}
if ('tweets' in options) {
if (!Array.isArray(options.tweets)) throw new CustomTypeError('INVALID_TYPE', 'tweets', 'array', true);
const tweetIds = options.tweets.map(tweet => {
const tweetId = this.resolveId(tweet);
if (!tweetId) throw new CustomError('TWEET_RESOLVE_ID', 'fetch');
return tweetId;
});
return this.#fetchMultipleTweets(tweetIds, options) as Promise<TweetManagerFetchResult<T>>;
}
throw new CustomError('INVALID_FETCH_OPTIONS');
}
/**
* Likes a tweet.
* @param targetTweet The tweet to like
* @returns A {@link TweetLikeResponse} object
*/
async like(targetTweet: TweetResolvable): Promise<TweetLikeResponse> {
const tweetId = this.resolveId(targetTweet);
if (!tweetId) throw new CustomError('TWEET_RESOLVE_ID', 'like');
const loggedInUser = this.client.me;
if (!loggedInUser) throw new CustomError('NO_LOGGED_IN_USER');
const body: PostTweetsLikeJSONBody = {
tweet_id: tweetId,
};
const requestData = new RequestData({ body, isUserContext: true });
const data: PostTweetsLikeResponse = await this.client._api.users(loggedInUser.id).likes.post(requestData);
return new TweetLikeResponse(data);
}
/**
* Unlikes a tweet.
* @param targetTweet The tweet to unlike
* @returns A {@link TweetUnlikeResponse} object
*/
async unlike(targetTweet: TweetResolvable): Promise<TweetUnlikeResponse> {
const tweetId = this.resolveId(targetTweet);
if (!tweetId) throw new CustomError('TWEET_RESOLVE_ID', 'unlike');
const loggedInUser = this.client.me;
if (!loggedInUser) throw new CustomError('NO_LOGGED_IN_USER');
const requestData = new RequestData({ isUserContext: true });
const data: DeleteTweetsLikeResponse = await this.client._api
.users(loggedInUser.id)
.likes(tweetId)
.delete(requestData);
return new TweetUnlikeResponse(data);
}
/**
* Hides a reply to a tweet of the authorized user.
* @param targetTweet The reply to hide. This should be a tweet reply to a tweet of the authorized user
* @returns A {@link TweetReplyHideUnhideResponse} object
*/
async hide(targetTweet: TweetResolvable): Promise<TweetReplyHideUnhideResponse> {
return this.#editTweetReplyVisibility(targetTweet, true);
}
/**
* Unhides a reply to a tweet of the authorized user.
* @param targetTweet The reply to unhide. This should be a tweet reply to one of the tweets of the authorized user
* @returns A {@link TweetReplyHideUnhideResponse} object
*/
async unhide(targetTweet: TweetResolvable): Promise<TweetReplyHideUnhideResponse> {
return this.#editTweetReplyVisibility(targetTweet, false);
}
/**
* Retweets a tweet.
* @param targetTweet The tweet to retweet
* @returns A {@link RetweetResponse} object
*/
async retweet(targetTweet: TweetResolvable): Promise<RetweetResponse> {
const tweetId = this.resolveId(targetTweet);
if (!tweetId) throw new CustomError('TWEET_RESOLVE_ID', 'retweet');
const loggedInUser = this.client.me;
if (!loggedInUser) throw new CustomError('NO_LOGGED_IN_USER');
const body: PostUsersRetweetsJSONBody = {
tweet_id: tweetId,
};
const requestData = new RequestData({ body, isUserContext: true });
const data: PostUsersRetweetsResponse = await this.client._api.users(loggedInUser.id).retweets.post(requestData);
return new RetweetResponse(data);
}
/**
* Removes the retweet of a tweet.
* @param targetTweet The tweet whose retweet is to be removed
* @returns A {@link RemovedRetweetResponse} object
*/
async unRetweet(targetTweet: TweetResolvable): Promise<RemovedRetweetResponse> {
const tweetId = this.resolveId(targetTweet);
if (!tweetId) throw new CustomError('TWEET_RESOLVE_ID', 'remove retweet');
const loggedInUser = this.client.me;
if (!loggedInUser) throw new CustomError('NO_LOGGED_IN_USER');
const requestData = new RequestData({ isUserContext: true });
const data: DeleteUsersRetweetsResponse = await this.client._api
.users(loggedInUser.id)
.retweets(tweetId)
.delete(requestData);
return new RemovedRetweetResponse(data);
}
/**
* Fetches users who have retweeted a tweet.
* @param targetTweet The tweet whose retweeters are to be fetched
* @returns A {@link Collection} of {@link User} objects
*/
async fetchRetweetedBy(targetTweet: TweetResolvable): Promise<Collection<Snowflake, User>> {
const tweetId = this.resolveId(targetTweet);
if (!tweetId) throw new CustomError('TWEET_RESOLVE_ID', 'remove retweet');
const queryParameters = this.client.options.queryParameters;
const query: GetTweetsRetweetingUsersQuery = {
expansions: queryParameters?.userExpansions,
'user.fields': queryParameters?.userFields,
'tweet.fields': queryParameters?.tweetFields,
};
const requestData = new RequestData({ query });
const data: GetTweetsRetweetingUsersResponse = await this.client._api.tweets(tweetId).retweeted_by.get(requestData);
const retweetedByUsersCollection = new Collection<Snowflake, User>();
if (data.meta.result_count === 0) return retweetedByUsersCollection;
const rawUsers = data.data;
const rawIncludes = data.includes;
for (const rawUser of rawUsers) {
const user = new User(this.client, { data: rawUser, includes: rawIncludes });
retweetedByUsersCollection.set(user.id, user);
}
return retweetedByUsersCollection;
}
/**
* Fetches a collection of users who liked a tweet.
* @param targetTweet The tweet whose liking users are to be fetched
* @returns A {@link Collection} of {@link User} objects who liked the specified tweet
*/
async fetchLikedBy(targetTweet: TweetResolvable): Promise<Collection<Snowflake, User>> {
const tweetId = this.resolveId(targetTweet);
if (!tweetId) throw new CustomError('TWEET_RESOLVE_ID', 'fetch liking users');
const queryParameters = this.client.options.queryParameters;
const query: GetTweetsLikingUsersQuery = {
expansions: queryParameters?.userExpansions,
'user.fields': queryParameters?.userFields,
'tweet.fields': queryParameters?.tweetFields,
};
const requestData = new RequestData({ query });
const data: GetTweetsLikingUsersResponse = await this.client._api.tweets(tweetId).liking_users.get(requestData);
const likedByUsersCollection = new Collection<Snowflake, User>();
if (data.meta.result_count === 0) return likedByUsersCollection;
const rawUsers = data.data;
const rawIncludes = data.includes;
for (const rawUser of rawUsers) {
const user = new User(this.client, { data: rawUser, includes: rawIncludes });
likedByUsersCollection.set(user.id, user);
}
return likedByUsersCollection;
}
/**
* Fetches tweets using a search query.
* @param query The query to match tweets with
* @param options The options for searching tweets
* @returns A tuple containing {@link SearchTweetsBook} object and a {@link Collection} of {@link Tweet} objects representing the first page
*/
async search(
query: string,
options?: SearchTweetsOptions,
): Promise<[SearchTweetsBook, Collection<Snowflake, Tweet>]> {
const bookData: SearchTweetsBookOptions = { query };
if (options?.afterTweet) {
const afterTweetId = this.client.tweets.resolveId(options.afterTweet);
if (afterTweetId) bookData.afterTweetId = afterTweetId;
}
if (options?.beforeTweet) {
const beforeTweetId = this.client.tweets.resolveId(options.beforeTweet);
if (beforeTweetId) bookData.beforeTweetId = beforeTweetId;
}
if (options?.afterTime) {
const afterTimestamp = new Date(options.afterTime).getTime();
if (afterTimestamp) bookData.afterTimestamp = afterTimestamp;
}
if (options?.beforeTime) {
const beforeTimestamp = new Date(options.beforeTime).getTime();
if (beforeTimestamp) bookData.beforeTimestamp = beforeTimestamp;
}
if (options?.maxResultsPerPage) {
bookData.maxResultsPerPage = options.maxResultsPerPage;
}
const searchTweetsBook = new SearchTweetsBook(this.client, bookData);
const firstPage = await searchTweetsBook.fetchNextPage();
return [searchTweetsBook, firstPage];
}
/**
* Fetches count of tweets matching a search query.
* @param query The query to match the tweets with
* @param options The options for searching tweets
* @returns A tuple containing {@link TweetsCountBook} object and an array of {@link TweetCountBucket} objects representing the first page
*/
async count(query: string, options?: CountTweetsOptions): Promise<[TweetsCountBook, Array<TweetCountBucket>]> {
const bookData: TweetsCountBookOptions = { query };
if (options?.afterTweet) {
const afterTweetId = this.client.tweets.resolveId(options.afterTweet);
if (afterTweetId) bookData.afterTweetId = afterTweetId;
}
if (options?.beforeTweet) {
const beforeTweetId = this.client.tweets.resolveId(options.beforeTweet);
if (beforeTweetId) bookData.beforeTweetId = beforeTweetId;
}
if (options?.afterTime) {
const afterTimestamp = new Date(options.afterTime).getTime();
if (afterTimestamp) bookData.afterTimestamp = afterTimestamp;
}
if (options?.beforeTime) {
const beforeTimestamp = new Date(options.beforeTime).getTime();
if (beforeTimestamp) bookData.beforeTimestamp = beforeTimestamp;
}
if (options?.granularity) {
bookData.granularity = options.granularity;
}
const tweetsCountBook = new TweetsCountBook(this.client, bookData);
const firstPage = await tweetsCountBook.fetchNextPage();
return [tweetsCountBook, firstPage];
}
// #### 🚧 PRIVATE METHODS 🚧 ####
async #fetchSingleTweet(tweetId: Snowflake, options: FetchTweetOptions): Promise<Tweet> {
if (!options.skipCacheCheck) {
const cachedTweet = this.cache.get(tweetId);
if (cachedTweet) return cachedTweet;
}
const queryParameters = this.client.options.queryParameters;
const query: GetSingleTweetByIdQuery = {
expansions: queryParameters?.tweetExpansions,
'media.fields': queryParameters?.mediaFields,
'place.fields': queryParameters?.placeFields,
'poll.fields': queryParameters?.pollFields,
'tweet.fields': queryParameters?.tweetFields,
'user.fields': queryParameters?.userFields,
};
const requestData = new RequestData({ query });
const data: GetSingleTweetByIdResponse = await this.client._api.tweets(tweetId).get(requestData);
return this._add(data.data.id, data, options.cacheAfterFetching);
}
async #fetchMultipleTweets(
tweetIds: Array<Snowflake>,
options: FetchTweetsOptions,
): Promise<Collection<Snowflake, Tweet>> {
const fetchedTweetCollection = new Collection<Snowflake, Tweet>();
const queryParameters = this.client.options.queryParameters;
const query: GetMultipleTweetsByIdsQuery = {
ids: tweetIds,
expansions: queryParameters?.tweetExpansions,
'media.fields': queryParameters?.mediaFields,
'place.fields': queryParameters?.placeFields,
'poll.fields': queryParameters?.pollFields,
'tweet.fields': queryParameters?.tweetFields,
'user.fields': queryParameters?.userFields,
};
const requestData = new RequestData({ query });
const data: GetMultipleTweetsByIdsResponse = await this.client._api.tweets.get(requestData);
const rawTweets = data.data;
const rawTweetsIncludes = data.includes;
for (const rawTweet of rawTweets) {
const tweet = this._add(rawTweet.id, { data: rawTweet, includes: rawTweetsIncludes }, options.cacheAfterFetching);
fetchedTweetCollection.set(tweet.id, tweet);
}
return fetchedTweetCollection;
}
async #editTweetReplyVisibility(
targetTweet: TweetResolvable,
isHidden: boolean,
): Promise<TweetReplyHideUnhideResponse> {
const tweetId = this.resolveId(targetTweet);
if (!tweetId) throw new CustomError('TWEET_RESOLVE_ID', `${isHidden ? 'hide' : 'unhide'}`);
const body: PutTweetReplyHideUnhideJSONBody = {
hidden: isHidden,
};
const requestData = new RequestData({ body, isUserContext: true });
const data: PutTweetReplyHideUnhideResponse = await this.client._api.tweets(tweetId).hidden.put(requestData);
return new TweetReplyHideUnhideResponse(data);
}
} | the_stack |
import {
SchemaRegistry,
AvroKafka,
AvroProducer,
AvroConsumer,
AvroEachMessagePayload,
AvroBatch,
AvroKafkaMessage,
} from '../src';
import { Kafka, logLevel, Admin, CompressionTypes } from 'kafkajs';
import { retry } from 'ts-retry-promise';
import * as uuid from 'uuid';
import { schema } from 'avsc';
import axios, { AxiosInstance } from 'axios';
interface MessageType {
stringField: string;
intField?: number | null;
}
interface Message2Type {
stringField: string;
otherField?: number;
intField: number | null;
}
interface Message3Type {
incompatibleName: string;
}
interface KeyType {
id: number;
section: 'first' | 'second';
}
interface LightType {
userId: number;
enum: 'A' | 'B' | 'C';
}
interface HeavyType {
userId: number;
actions: string[];
time: number;
enum: 'A' | 'B';
}
const schema: schema.RecordType = {
type: 'record',
name: 'TestMessage',
fields: [
{ type: 'string', name: 'stringField' },
{ type: ['null', 'int'], name: 'intField' },
],
};
const schema2: schema.RecordType = {
type: 'record',
name: 'TestMessage2',
fields: [
{ type: 'string', name: 'stringField' },
{ type: 'int', name: 'otherField', default: 20 },
{ type: ['null', 'int'], name: 'intField' },
],
};
const schema3: schema.RecordType = {
type: 'record',
name: 'TestMessag3',
fields: [{ type: 'string', name: 'incompatibleName' }],
};
const keySchema: schema.RecordType = {
type: 'record',
name: 'TestKey',
fields: [
{ type: 'int', name: 'id' },
{ type: { type: 'enum', symbols: ['first', 'second'], name: 'SectionType' }, name: 'section' },
],
};
const heavySchema: schema.RecordType = {
name: 'Event',
type: 'record',
fields: [
{ name: 'time', type: 'long' },
{ name: 'userId', type: 'int' },
{ name: 'actions', type: { type: 'array', items: 'string' } },
{ name: 'enum', type: { name: 'T', type: 'enum', symbols: ['A', 'B'] } },
],
};
const lightSchema: schema.RecordType = {
name: 'LightEvent',
aliases: ['Event'],
type: 'record',
fields: [
{ name: 'userId', type: 'int' },
{ name: 'enum', type: { name: 'T', type: 'enum', symbols: ['A', 'B', 'C'] } },
],
};
const TOPIC_ALIAS = 'topic-alias';
describe('Class', () => {
let producer: AvroProducer;
let consumer: AvroConsumer;
let admin: Admin;
let schemaRegistryApi: AxiosInstance;
let groupId: string;
let realTopicName: string;
beforeEach(async () => {
const schemaRegistry = new SchemaRegistry({ uri: 'http://localhost:8081' });
const kafka = new Kafka({ brokers: ['localhost:29092'], logLevel: logLevel.NOTHING });
realTopicName = `dev_avroKafkajs_${uuid.v4()}`;
const avroKafka = new AvroKafka(schemaRegistry, kafka, { [TOPIC_ALIAS]: realTopicName });
groupId = uuid.v4();
schemaRegistryApi = axios.create({
headers: { 'Content-Type': 'application/vnd.schemaregistry.v1+json' },
baseURL: 'http://localhost:8081',
});
admin = avroKafka.admin();
consumer = avroKafka.consumer({ groupId });
producer = avroKafka.producer();
await Promise.all([consumer.connect(), producer.connect(), admin.connect()]);
});
afterEach(() => Promise.all([consumer.disconnect(), producer.disconnect(), admin.disconnect()]));
it('Should process avro messages one by one', async () => {
jest.setTimeout(12000);
const consumed: AvroEachMessagePayload<MessageType | Message2Type | Message3Type>[] = [];
await admin.createTopics({ topics: [{ topic: realTopicName, numPartitions: 2 }] });
await consumer.subscribe({ topic: TOPIC_ALIAS });
await consumer.run<MessageType | Message2Type | Message3Type>({
partitionsConsumedConcurrently: 2,
eachMessage: async (payload) => {
consumed.push(payload);
},
});
await producer.send<MessageType>({
topic: TOPIC_ALIAS,
schema,
messages: [
{ value: { intField: 10, stringField: 'test1' }, partition: 0, key: 'test-1' },
{ value: { intField: null, stringField: 'test2' }, partition: 1, key: 'test-2' },
],
});
await producer.send<Message2Type>({
topic: TOPIC_ALIAS,
schema: schema2,
messages: [
{
value: { intField: 10, stringField: 'test1', otherField: 2 },
partition: 0,
key: 'test-other-1',
},
{
value: { intField: null, stringField: 'test2' },
partition: 1,
key: 'test-other-2',
},
],
});
await schemaRegistryApi.put(`/config/${realTopicName}-value`, { compatibility: 'NONE' });
await producer.send<Message3Type>({
topic: TOPIC_ALIAS,
schema: schema3,
messages: [
{ value: { incompatibleName: 'totally different' }, partition: 0, key: 'test-different-1' },
],
});
const description = await consumer.describeGroup();
expect(description).toMatchObject({ errorCode: 0, groupId });
expect(consumer.paused()).toHaveLength(0);
consumer.pause([{ topic: TOPIC_ALIAS }]);
expect(consumer.paused()).toHaveLength(1);
consumer.resume([{ topic: TOPIC_ALIAS }]);
expect(consumer.paused()).toHaveLength(0);
await retry(
async () => {
expect(consumed).toHaveLength(5);
expect(consumed).toContainEqual(
expect.objectContaining({
partition: 0,
message: expect.objectContaining({
key: Buffer.from('test-1'),
value: { intField: 10, stringField: 'test1' },
schema,
}),
}),
);
expect(consumed).toContainEqual(
expect.objectContaining({
partition: 1,
message: expect.objectContaining({
key: Buffer.from('test-2'),
value: { intField: null, stringField: 'test2' },
schema,
}),
}),
);
expect(consumed).toContainEqual(
expect.objectContaining({
partition: 0,
message: expect.objectContaining({
key: Buffer.from('test-other-1'),
value: { intField: 10, stringField: 'test1', otherField: 2 },
}),
}),
);
expect(consumed).toContainEqual(
expect.objectContaining({
partition: 1,
message: expect.objectContaining({
key: Buffer.from('test-other-2'),
value: { intField: null, stringField: 'test2', otherField: 20 },
}),
}),
);
expect(consumed).toContainEqual(
expect.objectContaining({
partition: 0,
message: expect.objectContaining({
key: Buffer.from('test-different-1'),
value: { incompatibleName: 'totally different' },
schema: schema3,
}),
}),
);
},
{ delay: 1000, retries: 4 },
);
let stopped = false;
consumer.on('consumer.stop', () => (stopped = true));
await consumer.stop();
await retry(async () => expect(stopped).toBe(true), { delay: 1000, timeout: 2000 });
});
it('Should process avro messages with encoded keys', async () => {
jest.setTimeout(12000);
const consumed: AvroEachMessagePayload<MessageType, KeyType>[] = [];
await admin.createTopics({ topics: [{ topic: realTopicName, numPartitions: 2 }] });
await consumer.subscribe({ topic: TOPIC_ALIAS });
await consumer.run<MessageType, KeyType>({
partitionsConsumedConcurrently: 2,
encodedKey: true,
eachMessage: async (payload) => {
consumed.push(payload);
},
});
await producer.send<MessageType, KeyType>({
topic: TOPIC_ALIAS,
schema,
keySchema,
messages: [
{
value: { intField: 10, stringField: 'test1' },
partition: 0,
key: { id: 10, section: 'first' },
},
{
value: { intField: null, stringField: 'test2' },
partition: 1,
key: { id: 12, section: 'second' },
},
],
});
const description = await consumer.describeGroup();
expect(description).toMatchObject({ errorCode: 0, groupId });
expect(consumer.paused()).toHaveLength(0);
consumer.pause([{ topic: TOPIC_ALIAS }]);
expect(consumer.paused()).toHaveLength(1);
consumer.resume([{ topic: TOPIC_ALIAS }]);
expect(consumer.paused()).toHaveLength(0);
await retry(
async () => {
expect(consumed).toHaveLength(2);
expect(consumed).toContainEqual(
expect.objectContaining({
partition: 0,
message: expect.objectContaining({
key: { id: 10, section: 'first' },
value: { intField: 10, stringField: 'test1' },
schema,
}),
}),
);
expect(consumed).toContainEqual(
expect.objectContaining({
partition: 1,
message: expect.objectContaining({
key: { id: 12, section: 'second' },
value: { intField: null, stringField: 'test2' },
schema,
}),
}),
);
},
{ delay: 1000, retries: 4 },
);
let stopped = false;
consumer.on('consumer.stop', () => (stopped = true));
await consumer.stop();
await retry(async () => expect(stopped).toBe(true), { delay: 1000, timeout: 2000 });
});
it('Should process avro messages in batches', async () => {
jest.setTimeout(12000);
const consumed: AvroBatch<MessageType>[] = [];
await admin.createTopics({ topics: [{ topic: realTopicName, numPartitions: 2 }] });
await consumer.subscribe({ topic: TOPIC_ALIAS });
await consumer.run<MessageType>({
eachBatch: async (payload) => {
consumed.push(payload.batch);
},
});
await producer.sendBatch({
acks: -1,
timeout: 3000,
compression: CompressionTypes.None,
topicMessages: [
{
topic: TOPIC_ALIAS,
schema,
messages: [
{ value: { intField: 1, stringField: 'test1' }, partition: 0, key: 'test-1' },
{ value: { intField: 2, stringField: 'test2' }, partition: 0, key: 'test-2' },
{ value: { intField: 3, stringField: 'test3' }, partition: 0, key: 'test-3' },
{ value: { intField: null, stringField: 'test4' }, partition: 1, key: 'test-4' },
],
},
],
});
await retry(
async () => {
expect(consumed).toHaveLength(2);
expect(consumed).toContainEqual(
expect.objectContaining({
partition: 0,
topic: realTopicName,
messages: [
expect.objectContaining({
key: Buffer.from('test-1'),
value: { intField: 1, stringField: 'test1' },
schema,
}),
expect.objectContaining({
key: Buffer.from('test-2'),
value: { intField: 2, stringField: 'test2' },
schema,
}),
expect.objectContaining({
key: Buffer.from('test-3'),
value: { intField: 3, stringField: 'test3' },
schema,
}),
],
}),
);
expect(consumed).toContainEqual(
expect.objectContaining({
partition: 1,
topic: realTopicName,
messages: [
expect.objectContaining({
key: Buffer.from('test-4'),
value: { intField: null, stringField: 'test4' },
}),
],
}),
);
},
{ delay: 1000, retries: 4 },
);
});
it('Should process avro messages in batches with encoded keys', async () => {
jest.setTimeout(12000);
const consumed: AvroBatch<MessageType, KeyType>[] = [];
await admin.createTopics({ topics: [{ topic: realTopicName, numPartitions: 2 }] });
await consumer.subscribe({ topic: TOPIC_ALIAS });
await consumer.run<MessageType, KeyType>({
encodedKey: true,
eachBatch: async (payload) => {
consumed.push(payload.batch);
},
});
await producer.sendBatch({
acks: -1,
timeout: 3000,
compression: CompressionTypes.None,
topicMessages: [
{
topic: TOPIC_ALIAS,
schema,
keySchema,
messages: [
{
value: { intField: 1, stringField: 'test1' },
partition: 0,
key: { id: 1, section: 'first' },
},
{
value: { intField: 2, stringField: 'test2' },
partition: 0,
key: { id: 2, section: 'first' },
},
{
value: { intField: 3, stringField: 'test3' },
partition: 0,
key: { id: 3, section: 'first' },
},
{
value: { intField: null, stringField: 'test4' },
partition: 1,
key: { id: 4, section: 'second' },
},
],
},
],
});
await retry(
async () => {
expect(consumed).toHaveLength(2);
expect(consumed).toContainEqual(
expect.objectContaining({
partition: 0,
topic: realTopicName,
messages: [
expect.objectContaining({
key: { id: 1, section: 'first' },
value: { intField: 1, stringField: 'test1' },
schema,
}),
expect.objectContaining({
key: { id: 2, section: 'first' },
value: { intField: 2, stringField: 'test2' },
schema,
}),
expect.objectContaining({
key: { id: 3, section: 'first' },
value: { intField: 3, stringField: 'test3' },
schema,
}),
],
}),
);
expect(consumed).toContainEqual(
expect.objectContaining({
partition: 1,
topic: realTopicName,
messages: [
expect.objectContaining({
key: { id: 4, section: 'second' },
value: { intField: null, stringField: 'test4' },
}),
],
}),
);
},
{ delay: 1000, retries: 4 },
);
});
it('Should produce avro messages with custom subject', async () => {
jest.setTimeout(12000);
const consumed: AvroKafkaMessage<MessageType>[] = [];
await consumer.subscribe({ topic: TOPIC_ALIAS });
await consumer.run<MessageType>({
eachMessage: async (payload) => {
consumed.push(payload.message);
},
});
// Produce normally to create the subject
await producer.send<MessageType>({
topic: TOPIC_ALIAS,
schema,
messages: [{ value: { stringField: '1', intField: null }, key: null }],
});
// Use the subject directly to produce the messages
await producer.send<MessageType>({
topic: TOPIC_ALIAS,
subject: `${realTopicName}-value`,
messages: [
{ value: { stringField: '2', intField: null }, key: null },
{ value: { stringField: '3', intField: null }, key: null },
],
});
await retry(
async () => {
expect(consumed).toHaveLength(3);
expect(consumed).toContainEqual(
expect.objectContaining({ value: { stringField: '1', intField: null }, schema }),
);
expect(consumed).toContainEqual(
expect.objectContaining({ value: { stringField: '2', intField: null }, schema }),
);
expect(consumed).toContainEqual(
expect.objectContaining({ value: { stringField: '3', intField: null }, schema }),
);
},
{ delay: 1000, retries: 4 },
);
});
it('Should produce avro messages with custom subject for key and value', async () => {
jest.setTimeout(12000);
const consumed: AvroKafkaMessage<MessageType, KeyType>[] = [];
await consumer.subscribe({ topic: TOPIC_ALIAS });
await consumer.run<MessageType, KeyType>({
encodedKey: true,
eachMessage: async (payload) => {
consumed.push(payload.message);
},
});
// Produce normally to create the subject
await producer.send<MessageType, KeyType>({
topic: TOPIC_ALIAS,
schema,
keySchema,
messages: [{ value: { stringField: '1', intField: null }, key: { id: 1, section: 'first' } }],
});
// Use the subject directly to produce the messages
await producer.send<MessageType, KeyType>({
topic: TOPIC_ALIAS,
subject: `${realTopicName}-value`,
keySubject: `${realTopicName}-key`,
messages: [
{ value: { stringField: '2', intField: null }, key: { id: 2, section: 'first' } },
{ value: { stringField: '3', intField: null }, key: { id: 3, section: 'second' } },
],
});
await retry(
async () => {
expect(consumed).toHaveLength(3);
expect(consumed).toContainEqual(
expect.objectContaining({
value: { stringField: '1', intField: null },
key: { id: 1, section: 'first' },
schema,
}),
);
expect(consumed).toContainEqual(
expect.objectContaining({
value: { stringField: '2', intField: null },
key: { id: 2, section: 'first' },
schema,
}),
);
expect(consumed).toContainEqual(
expect.objectContaining({
value: { stringField: '3', intField: null },
key: { id: 3, section: 'second' },
schema,
}),
);
},
{ delay: 1000, retries: 4 },
);
});
it('Should consume avro messages with reader schema', async () => {
jest.setTimeout(12000);
const consumed: AvroKafkaMessage<LightType>[] = [];
await consumer.subscribe({ topic: TOPIC_ALIAS });
await consumer.run<LightType>({
readerSchema: lightSchema,
eachMessage: async (payload) => {
consumed.push(payload.message);
},
});
// Produce normally to create the subject
await producer.send<HeavyType>({
topic: TOPIC_ALIAS,
schema: heavySchema,
messages: [
{ value: { userId: 123, actions: ['add', 'remove'], time: 100, enum: 'A' }, key: null },
],
});
await retry(
async () => {
expect(consumed).toHaveLength(1);
expect(consumed).toContainEqual(
expect.objectContaining({
value: { userId: 123, enum: 'A' },
schema: heavySchema,
}),
);
},
{ delay: 1000, retries: 6 },
);
});
}); | the_stack |
import { TestBed, fakeAsync, tick } from '@angular/core/testing';
import { Component, Type } from '@angular/core';
import { LIST_DIRECTIVES } from './mdc.list.directive';
import { hasRipple } from '../../testutils/page.test';
// TODO tests for checbox/radio input controlled list items
describe('mdcList', () => {
@Component({
template: `
<ul mdcList [selectionMode]="selectionMode" [nonInteractive]="nonInteractive">
<li *ngFor="let item of items; let i = index" mdcListItem [disabled]="disabled === i"
(action)="action(i)" (selectedChange)="active($event, i)">
<span mdcListItemText>{{item}}</span>
</li>
</ul>
`
})
class TestComponent {
actions: number[] = [];
selectedChange: {index: number, value: boolean}[] = [];
items = ['item 1', 'item 2', 'item 3'];
nonInteractive = false;
selectionMode: string = null;
disabled: number = null;
action(i: number) {
this.actions.push(i);
}
active(value: boolean, index: number) {
this.selectedChange.push({index, value});
}
}
it('should render the list and items with correct styles and attributes', fakeAsync(() => {
const { list, items } = setup();
expect(list).toBeDefined();
expect(list.getAttribute('role')).toBeNull();
expect(list.getAttribute('tabindex')).toBeNull();
expect(items.length).toBe(3);
// by default items are set to be focusable, but only the first item is tabbable (tabindex=-1):
expectTabbable(items, 0);
expectRoles(items, null);
expect(items.map(it => it.getAttribute('tabindex'))).toEqual(['0', '-1', '-1']);
items.forEach(item => expect(hasRipple(item)).toBe(true));
}));
it('clicking an item affects tabindexes', fakeAsync(() => {
const { fixture, items } = setup();
// focus by clicking:
focusItem(fixture, items, 1);
expectTabbable(items, 1);
// remove focus should restore tabindex=0 on first item:
blurItem(fixture, items, 1);
expectTabbable(items, 0);
}));
it('keyboard navigation affects tabindexes', fakeAsync(() => {
const { fixture, items } = setup();
// tabbing will focus the element with tabindex=0 (default first elm):
items[0].focus();
items[0].dispatchEvent(newFocusEvent('focusin'));
tick(); fixture.detectChanges();
expectTabbable(items, 0); // tabindexes on items should not have been changed
// Down key:
items[0].dispatchEvent(newKeydownEvent('ArrowDown'));
tick(); fixture.detectChanges();
expectTabbable(items, 1);
// focusOut should make first element tabbable again:
blurItem(fixture, items, 1);
expectTabbable(items, 0);
}));
it('adding items will not change focus', fakeAsync(() => {
const { fixture, items, testComponent } = setup();
focusItem(fixture, items, 1);
testComponent.items = ['new text', ...testComponent.items];
fixture.detectChanges(); tick();
const currentItems: HTMLElement[] = [...fixture.nativeElement.querySelectorAll('.mdc-list-item')];
expect(currentItems.length).toBe(4);
expectTabbable(currentItems, 2); // next item, because one was inserted before
blurItem(fixture, currentItems, 2);
expectTabbable(currentItems, 0);
}));
it('nonInteractive lists ignore interaction and are not focusable', fakeAsync(() => {
const { fixture, items, testComponent } = setup();
testComponent.nonInteractive = true;
fixture.detectChanges();
expectTabbable(items, -1); // not focusable
focusItem(fixture, items, 1); // will not focus:
expectTabbable(items, -1); // not focusable
// not listening to keyboard input:
items[0].dispatchEvent(newKeydownEvent('ArrowDown'));
tick(); fixture.detectChanges();
expectTabbable(items, -1);
// no action events have been emitted:
expect(testComponent.actions).toEqual([]);
expect(testComponent.selectedChange).toEqual([]);
}));
it('disabled items are correctly styled, not actionable, and not selectable', fakeAsync(() => {
const { fixture, items, testComponent } = setup();
testComponent.disabled = 1;
fixture.detectChanges(); tick();
expectDisabled(items, 1);
testComponent.selectionMode = 'single';
fixture.detectChanges(); tick();
// try to focus and activate disabled item:
focusItem(fixture, items, 1);
expectTabbable(items, 1); // is focusable
expectActive(items, -1, 'selected'); // can not be activated
// no action events have been emitted:
expect(testComponent.actions).toEqual([]);
expect(testComponent.selectedChange).toEqual([]);
}));
it('selectionMode=single/current', fakeAsync(() => {
const { fixture, items, testComponent } = setup();
testComponent.selectionMode = 'single';
fixture.detectChanges(); tick();
validateSelectionMode('selected', -1);
testComponent.selectionMode = 'active';
fixture.detectChanges(); tick();
testComponent.actions.length = 0;
testComponent.selectedChange.length = 0;
validateSelectionMode('current', 2);
function validateSelectionMode(type, initialActive) {
expectActive(items, initialActive, type);
// activate on click:
focusItem(fixture, items, 1);
expectTabbable(items, 1);
expectActive(items, 1, type);
// should also emit action event:
expect(testComponent.actions).toEqual([1]);
if (initialActive !== -1)
expect(testComponent.selectedChange).toEqual([
{index: initialActive, value: false},
{index: 1, value: true}
]);
else
expect(testComponent.selectedChange).toEqual([
{index: 1, value: true}
]);
testComponent.selectedChange.length = 0;
// active on keyboard on input:
items[1].dispatchEvent(newKeydownEvent('ArrowDown'));
tick(); fixture.detectChanges();
expectTabbable(items, 2);
expectActive(items, 1,type);
items[2].dispatchEvent(newKeydownEvent('Enter'));
tick(); fixture.detectChanges();
expectActive(items, 2, type);
// should also emit action event:
expect(testComponent.actions).toEqual([1, 2]);
expect(testComponent.selectedChange).toEqual([
{index: 1, value: false},
{index: 2, value: true}
]);
}
}));
@Component({
template: `
<div mdcListGroup>
<h3 mdcListGroupSubHeader>Header</h3>
<ul mdcList>
<li mdcListItem>
<span mdcListItemGraphic></span>
<span mdcListItemText>
<span mdcListItemPrimaryText>primary</span>
<span mdcListItemSecondaryText>secondary</span>
</span>
<span mdcListItemMeta></span>
</li>
<li mdcListDivider [inset]="inset" [padded]="padded"></li>
</ul>
<hr mdcListDivider>
</div>
`
})
class TestOptionalDirectivesComponent {
inset = null;
padded = null;
}
it('should render optional directives correctly', fakeAsync(() => {
const { fixture, list, testComponent } = setup(TestOptionalDirectivesComponent);
expect(fixture.nativeElement.querySelector('div.mdc-list-group')).not.toBeNull();
expect(fixture.nativeElement.querySelector('h3.mdc-list-group__subheader')).not.toBeNull();
expect(list.classList).toContain('mdc-list--two-line');
expect(fixture.nativeElement.querySelector('li.mdc-list-item')).not.toBeNull();
expect(fixture.nativeElement.querySelector('span.mdc-list-item__text')).not.toBeNull();
expect(fixture.nativeElement.querySelector('span.mdc-list-item__primary-text')).not.toBeNull();
expect(fixture.nativeElement.querySelector('span.mdc-list-item__secondary-text')).not.toBeNull();
const itemDivider = fixture.nativeElement.querySelector('li.mdc-list-divider');
expect(itemDivider.getAttribute('role')).toBe('separator');
expect(itemDivider.classList).not.toContain('mdc-list-divider--inset');
expect(itemDivider.classList).not.toContain('mdc-list-divider--padded');
const listDivider = fixture.nativeElement.querySelector('hr.mdc-list-divider');
expect(listDivider.getAttribute('role')).toBeNull();
expect(fixture.nativeElement.querySelector('span.mdc-list-item__graphic')).not.toBeNull();
expect(fixture.nativeElement.querySelector('span.mdc-list-item__meta')).not.toBeNull();
testComponent.inset = true;
testComponent.padded = true;
fixture.detectChanges();
expect(itemDivider.classList).toContain('mdc-list-divider--inset');
expect(itemDivider.classList).toContain('mdc-list-divider--padded');
}));
@Component({
template: `
<ul mdcList [selectionMode]="selectionMode" [nonInteractive]="nonInteractive">
<li *ngFor="let item of items" mdcListItem [value]="item.value" [selected]="item.active" (selectedChange)="active($event, item.value)">
<span mdcListItemText>{{item.value}}</span>
</li>
</ul>
`
})
class TestProgrammaticActivationComponent {
selectedChange: {value: string, active: boolean}[] = [];
items = [
{value: 'item1', active: true},
{value: 'item2', active: false},
{value: 'item3', active: false}
];
nonInteractive = false;
selectionMode: string = null;
active(active: boolean, value: string) {
this.selectedChange.push({value, active});
}
}
it('single selection list: programmatic change of active/selected items', fakeAsync(() => {
const { fixture, items, testComponent } = setup(TestProgrammaticActivationComponent);
expectActive(items, 0, 'selected', true); // first item selected, no aria-selected, because plain list should not have aria-selected attributes
expect(testComponent.selectedChange).toEqual([{active: true, value: 'item1'}]);
// switch to single selection mode:
testComponent.selectionMode = 'single';
testComponent.selectedChange = [];
fixture.detectChanges(); tick();
expectActive(items, 0, 'selected');
testComponent.items[0].active = false;
testComponent.items[2].active = true;
fixture.detectChanges(); tick();
expectActive(items, 2, 'selected');
expect(testComponent.selectedChange).toEqual([
{active: false, value: 'item1'},
{active: true, value: 'item3'},
]);
testComponent.selectionMode = 'active';
fixture.detectChanges(); tick();
expectActive(items, 2, 'current');
testComponent.items[1].active = true;
fixture.detectChanges(); tick();
expectActive(items, 1, 'current'); // only the first of the two 'active' items selected
}));
it('simple list: programmatic change of active/selected items', fakeAsync(() => {
const { fixture, items, testComponent } = setup(TestProgrammaticActivationComponent);
expectActive(items, 0, 'selected', true);
expect(testComponent.selectedChange).toEqual([{active: true, value: 'item1'}]);
testComponent.selectedChange = [];
// activate all items:
testComponent.items[1].active = true;
testComponent.items[2].active = true;
fixture.detectChanges(); tick();
expectActive(items, [0, 1, 2], 'selected', true);
expect(testComponent.selectedChange).toEqual([
{active: true, value: 'item2'},
{active: true, value: 'item3'},
]);
testComponent.nonInteractive = true;
testComponent.items[0].active = false;
fixture.detectChanges(); tick();
expectActive(items, [1, 2], 'selected', true);
}));
function expectTabbable(items: HTMLElement[], index: number) {
const expected = Array.apply(null, Array(items.length)).map((_, i) => i === index ? '0' : '-1');
expect(items.map(it => it.getAttribute('tabindex'))).toEqual(expected);
}
function expectRoles(items: HTMLElement[], role: string) {
items.forEach(item => expect(item.getAttribute('role')).toBe(role));
}
function expectActive(items: HTMLElement[], index: number | number[], type: 'current' | 'selected' | 'checked' | null, noAria = false) {
const indexes = typeof index === 'number' ? [index] : index;
const expectSelected = Array.apply(null, Array(items.length)).map((_, i) => indexes.indexOf(i) !== -1 && type === 'selected');
const expectActived = Array.apply(null, Array(items.length)).map((_, i) => indexes.indexOf(i) !== -1 && type === 'current');
const expectAriaSelected = Array.apply(null, Array(items.length)).map((_, i) => ariaValueForType('selected', i, noAria));
const expectAriaCurrent = Array.apply(null, Array(items.length)).map((_, i) => ariaValueForType('current', i, noAria));
const expectAriaChecked = Array.apply(null, Array(items.length)).map((_, i) => ariaValueForType('checked', i, noAria));
expect(items.map(it => it.classList.contains('mdc-list-item--selected'))).toEqual(expectSelected);
expect(items.map(it => it.classList.contains('mdc-list-item--activated'))).toEqual(expectActived);
expect(items.map(it => it.getAttribute('aria-selected'))).toEqual(expectAriaSelected);
expect(items.map(it => it.getAttribute('aria-current'))).toEqual(expectAriaCurrent);
expect(items.map(it => it.getAttribute('aria-checked'))).toEqual(expectAriaChecked);
function ariaValueForType(forType: 'current' | 'selected' | 'checked', i, noAria) {
if (!noAria && type === forType)
return indexes.indexOf(i) !== -1 ? 'true' : 'false';
return null;
}
}
function expectDisabled(items: HTMLElement[], index: number) {
const expected = Array.apply(null, Array(items.length)).map((_, i) => i === index);
expect(items.map(it => it.classList.contains('mdc-list-item--disabled'))).toEqual(expected);
expect(items.map(it => !!it.getAttribute('aria-disabled'))).toEqual(expected);
expect(items.map(it => it.getAttribute('aria-disabled') === 'true')).toEqual(expected);
}
function newFocusEvent(name: string) {
const event = document.createEvent('FocusEvent');
event.initEvent(name, true, true);
return event;
}
function newKeydownEvent(key: string) {
let event = new KeyboardEvent('keydown', {key});
event.initEvent('keydown', true, true);
return event;
}
function newClickEvent() {
let event = document.createEvent('MouseEvent');
event.initEvent('click', true, true);
return event;
}
function blurActive() {
(<HTMLElement>document.activeElement).blur();
}
function focusItem(fixture, items: HTMLElement[], index: number) {
items[index].focus();
items[index].dispatchEvent(newFocusEvent('focusin'));
items[index].dispatchEvent(newClickEvent());
tick(); fixture.detectChanges();
}
function blurItem(fixture, items, focusedIndex) {
blurActive();
items[focusedIndex].dispatchEvent(newFocusEvent('focusout'));
tick(); fixture.detectChanges();
}
function setup(compType: Type<any> = TestComponent) {
const fixture = TestBed.configureTestingModule({
declarations: [...LIST_DIRECTIVES, compType]
}).createComponent(compType);
fixture.detectChanges();
const testComponent = fixture.debugElement.injector.get(compType);
const list: HTMLElement = fixture.nativeElement.querySelector('.mdc-list');
const items: HTMLElement[] = [...fixture.nativeElement.querySelectorAll('.mdc-list-item')];
return { fixture, list, items, testComponent };
}
}); | the_stack |
import { RedisClient } from './redis-client';
import {
ICallback,
IConfig,
TConsumerOptions,
TRedisClientMulti,
TUnaryFunction,
} from '../types';
import { redisKeys } from './redis-keys';
import { Message } from './message';
import { Instance } from './instance';
import { events } from './events';
import { Consumer } from './consumer';
import { Scheduler } from './scheduler';
import BLogger from 'bunyan';
import { Logger } from './logger';
import { PowerManager } from './power-manager';
const dequeueScript = `
if redis.call("EXISTS", KEYS[1]) == 1 then
local result = redis.call("ZRANGE", KEYS[1], 0, 0)
if #(result) then
local message = result[1]
redis.call("RPUSH", KEYS[2], message)
redis.call("ZREM", KEYS[1], message)
return message
end
end
return nil
`;
export class Broker {
protected instance: Instance;
protected queueName: string;
protected config: IConfig;
protected logger: BLogger;
protected powerManager: PowerManager;
protected schedulerInstance: Scheduler | null = null;
protected redisClient: RedisClient | null = null;
protected dequeueScriptId: string | null | undefined = null;
constructor(instance: Instance) {
this.instance = instance;
this.queueName = instance.getQueueName();
this.config = instance.getConfig();
this.logger = Logger(
`broker (${instance.getQueueName()}/${instance.getId()})`,
instance.getConfig().log,
);
this.powerManager = new PowerManager();
}
protected getRedisClient(cb: TUnaryFunction<RedisClient>): void {
if (!this.redisClient)
this.instance.emit(
events.ERROR,
new Error('Expected an instance of RedisClient'),
);
else cb(this.redisClient);
}
getScheduler(cb: ICallback<Scheduler>): void {
if (!this.schedulerInstance) {
Scheduler.getInstance(this.queueName, this.config, (scheduler) => {
this.schedulerInstance = scheduler;
this.schedulerInstance.once(events.SCHEDULER_QUIT, () => {
this.schedulerInstance = null;
});
cb(null, this.schedulerInstance);
});
} else cb(null, this.schedulerInstance);
}
bootstrap(cb: ICallback<void>): void {
this.getRedisClient((client) => {
const multi = client.multi();
const { keyIndexQueue, keyQueue, keyQueueDLQ, keyIndexQueueDLQ } =
this.instance.getInstanceRedisKeys();
multi.sadd(keyIndexQueueDLQ, keyQueueDLQ);
multi.sadd(keyIndexQueue, keyQueue);
if (this.instance instanceof Consumer) {
const {
keyConsumerProcessingQueue,
keyIndexQueueProcessing,
keyIndexQueueQueuesProcessing,
} = this.instance.getInstanceRedisKeys();
multi.hset(
keyIndexQueueQueuesProcessing,
keyConsumerProcessingQueue,
this.instance.getId(),
);
multi.sadd(keyIndexQueueProcessing, keyConsumerProcessingQueue);
}
client.execMulti(multi, (err) => {
if (err) cb(err);
else this.loadScripts(cb);
});
});
}
protected loadScripts(cb: ICallback<void>): void {
this.getRedisClient((client) => {
client.loadScript(dequeueScript, (err, sha) => {
if (err) cb(err);
else {
this.dequeueScriptId = sha;
cb();
}
});
});
}
handleMessageWithExpiredTTL(
message: Message,
processingQueue: string,
cb: ICallback<void>,
): void {
this.getRedisClient((client) => {
const multi = client.multi();
multi.rpop(processingQueue);
this.moveMessageToDLQQueue(message, multi);
client.execMulti(multi, (err) => {
if (err) cb(err);
else {
this.instance.emit(events.MESSAGE_DEAD_LETTER, message);
cb();
}
});
});
}
deleteProcessingQueue(
queueName: string,
processingQueueName: string,
cb: ICallback<void>,
): void {
this.getRedisClient((client) => {
const multi = client.multi();
const { keyIndexQueueProcessing, keyIndexQueueQueuesProcessing } =
this.instance.getInstanceRedisKeys();
multi.srem(keyIndexQueueProcessing, processingQueueName);
multi.hdel(keyIndexQueueQueuesProcessing, processingQueueName);
multi.del(processingQueueName);
multi.exec((err) => cb(err));
});
}
moveMessageToDLQQueue(message: Message, multi: TRedisClientMulti): void {
const { keyQueueDLQ } = this.instance.getInstanceRedisKeys();
this.logger.debug(`Moving message [${message.getId()}] to DLQ...`);
multi.lpush(keyQueueDLQ, message.toString());
}
protected enqueueMessageAfterDelay(
message: Message,
delay: number,
multi: TRedisClientMulti,
): void {
this.getScheduler((err, scheduler) => {
if (err) this.instance.emit(events.ERROR, err);
else if (!scheduler)
this.instance.emit(
events.ERROR,
new Error('Expected an instance of Scheduler'),
);
else {
this.logger.debug(
`Scheduling message ID [${message.getId()}] (delay: [${delay}])...`,
);
message.setScheduledDelay(delay);
scheduler.schedule(message, multi);
}
});
}
protected enqueueMessageWithPriority(
message: Message,
mixed: TRedisClientMulti | ICallback<void>,
): void {
const { keyQueuePriorityQueue } = this.instance.getInstanceRedisKeys();
const priority = message.getPriority() ?? Message.MessagePriority.NORMAL;
if (typeof mixed === 'function') {
this.getRedisClient((client) => {
client.zadd(
keyQueuePriorityQueue,
priority,
message.toString(),
(err?: Error | null) => mixed(err),
);
});
} else mixed.zadd(keyQueuePriorityQueue, priority, message.toString());
}
protected dequeueMessageWithPriority(
redisClient: RedisClient,
consumerOptions: TConsumerOptions,
): void {
if (!this.dequeueScriptId)
this.instance.emit(
events.ERROR,
new Error('dequeueScriptSha is required'),
);
else {
const { keyQueuePriorityQueue, keyConsumerProcessingQueue } =
this.instance.getInstanceRedisKeys();
redisClient.evalsha(
this.dequeueScriptId,
[2, keyQueuePriorityQueue, keyConsumerProcessingQueue],
(err, json) => {
if (err) this.instance.emit(events.ERROR, err);
else if (typeof json === 'string')
this.handleReceivedMessage(json, consumerOptions);
else
setTimeout(
() =>
this.dequeueMessageWithPriority(redisClient, consumerOptions),
1000,
);
},
);
}
}
enqueueMessage(
message: Message,
mixed: TRedisClientMulti | ICallback<void>,
): void {
if (this.config.priorityQueue === true)
this.enqueueMessageWithPriority(message, mixed);
else {
const { keyQueue } = this.instance.getInstanceRedisKeys();
if (typeof mixed === 'function') {
this.getRedisClient((client) => {
client.lpush(keyQueue, message.toString(), (err?: Error | null) =>
mixed(err),
);
});
} else mixed.lpush(keyQueue, message.toString());
}
}
// Requires an exclusive RedisClient client as brpoplpush will block the connection until a message is received.
dequeueMessage(
redisClient: RedisClient,
consumerOptions: TConsumerOptions,
): void {
if (this.config.priorityQueue === true) {
this.dequeueMessageWithPriority(redisClient, consumerOptions);
} else {
const { keyQueue, keyConsumerProcessingQueue } =
this.instance.getInstanceRedisKeys();
redisClient.brpoplpush(
keyQueue,
keyConsumerProcessingQueue,
0,
(err, json) => {
if (err) this.instance.emit(events.ERROR, err);
else if (!json)
this.instance.emit(
events.ERROR,
new Error('Expected a non empty string'),
);
else this.handleReceivedMessage(json, consumerOptions);
},
);
}
}
protected handleReceivedMessage(
json: string,
consumerOptions: TConsumerOptions,
): void {
const message = Message.createFromMessage(json);
this.applyConsumerOptions(message, consumerOptions);
if (message.hasExpired())
this.instance.emit(events.MESSAGE_EXPIRED, message);
else this.instance.emit(events.MESSAGE_RECEIVED, message);
}
acknowledgeMessage(cb: ICallback<void>): void {
this.getRedisClient((client) => {
const { keyConsumerProcessingQueue } =
this.instance.getInstanceRedisKeys();
client.rpop(keyConsumerProcessingQueue, (err?: Error | null) => cb(err));
});
}
protected applyConsumerOptions(
msg: Message,
consumerOptions: TConsumerOptions,
): void {
const {
messageConsumeTimeout,
messageRetryDelay,
messageRetryThreshold,
messageTTL,
} = consumerOptions;
if (msg.getTTL() === null) {
msg.setTTL(messageTTL);
}
if (msg.getRetryDelay() === null) {
msg.setRetryDelay(messageRetryDelay);
}
if (msg.getConsumeTimeout() === null) {
msg.setConsumeTimeout(messageConsumeTimeout);
}
if (msg.getRetryThreshold() === null) {
msg.setRetryThreshold(messageRetryThreshold);
}
}
/**
* Move the message to DLQ queue when max attempts threshold is reached or otherwise re-queue it again.
* Only non-periodic messages are re-queued. Failure of periodic messages is ignored since such messages
* are periodically scheduled for delivery.
*/
retry(
message: Message,
processingQueue: string,
consumerOptions: TConsumerOptions,
cb: ICallback<void | string>,
): void {
this.applyConsumerOptions(message, consumerOptions);
this.getRedisClient((client) => {
this.getScheduler((err, scheduler) => {
if (err) cb(err);
else if (!scheduler) cb(new Error('Expected an instance of Scheduler'));
else {
if (message.hasExpired()) {
this.logger.debug(`Message ID [${message.getId()}] has expired.`);
this.handleMessageWithExpiredTTL(message, processingQueue, cb);
} else if (scheduler.isPeriodic(message)) {
this.logger.debug(
`Message ID [${message.getId()}] has a periodic schedule. Cleaning processing queue...`,
);
client.rpop(processingQueue, cb);
} else {
let delayed = false;
let requeued = false;
const multi = client.multi();
multi.rpop(processingQueue);
if (!message.hasRetryThresholdExceeded()) {
message.incrAttempts();
this.logger.debug(
`Message ID [${message.getId()}] is valid (threshold not exceeded) for re-queuing...`,
);
const delay = message.getRetryDelay();
if (delay) {
this.logger.debug(
`Delaying message ID [${message.getId()}] before re-queuing...`,
);
delayed = true;
this.enqueueMessageAfterDelay(message, delay, multi);
} else {
this.logger.debug(
`Re-queuing message ID [${message.getId()}] for one more time...`,
);
requeued = true;
this.enqueueMessage(message, multi);
}
} else {
this.logger.debug(
`Message ID [${message.getId()}] retry threshold exceeded. Moving message to DLQ...`,
);
this.moveMessageToDLQQueue(message, multi);
}
client.execMulti(multi, (err) => {
if (err) cb(err);
else {
if (requeued) {
this.instance.emit(events.MESSAGE_REQUEUED, message);
} else if (delayed) {
this.instance.emit(events.MESSAGE_DELAYED, message);
} else {
this.instance.emit(events.MESSAGE_DEAD_LETTER, message);
}
cb();
}
});
}
}
});
});
}
start(): void {
this.powerManager.goingUp();
RedisClient.getInstance(this.config, (client) => {
this.redisClient = client;
this.bootstrap((err) => {
if (err) this.instance.emit(events.ERROR, err);
else {
this.powerManager.commit();
this.instance.emit(events.BROKER_UP);
}
});
});
}
stop(): void {
this.powerManager.goingDown();
if (this.schedulerInstance) {
this.schedulerInstance.quit();
this.schedulerInstance = null;
}
if (this.redisClient) {
this.redisClient.end(true);
this.redisClient = null;
}
this.powerManager.commit();
this.instance.emit(events.BROKER_DOWN);
}
static getProcessingQueues(
client: RedisClient,
queueName: string,
cb: ICallback<string[]>,
): void {
const { keyIndexQueueQueuesProcessing } = redisKeys.getKeys(queueName);
client.hkeys(keyIndexQueueQueuesProcessing, cb);
}
static getMessageQueues(
redisClient: RedisClient,
cb: ICallback<string[]>,
): void {
const { keyIndexQueue } = redisKeys.getGlobalKeys();
redisClient.smembers(keyIndexQueue, cb);
}
static getDLQQueues(redisClient: RedisClient, cb: ICallback<string[]>): void {
const { keyIndexQueueDLQ } = redisKeys.getGlobalKeys();
redisClient.smembers(keyIndexQueueDLQ, cb);
}
} | the_stack |
import * as ts from 'typescript';
import * as base from './base';
import {FacadeConverter} from './facade_converter';
import {Transpiler} from './main';
export default class DeclarationTranspiler extends base.TranspilerBase {
constructor(
tr: Transpiler, private fc: FacadeConverter, private enforceUnderscoreConventions: boolean) {
super(tr);
}
visitNode(node: ts.Node): boolean {
switch (node.kind) {
case ts.SyntaxKind.VariableDeclarationList:
// Note: VariableDeclarationList can only occur as part of a for loop.
let varDeclList = <ts.VariableDeclarationList>node;
this.visitList(varDeclList.declarations);
break;
case ts.SyntaxKind.VariableDeclaration:
let varDecl = <ts.VariableDeclaration>node;
this.visitVariableDeclarationType(varDecl);
this.visit(varDecl.name);
if (varDecl.initializer) {
this.emit('=');
this.visit(varDecl.initializer);
}
break;
case ts.SyntaxKind.ClassDeclaration:
let classDecl = <ts.ClassDeclaration>node;
if (classDecl.modifiers && (classDecl.modifiers.flags & ts.NodeFlags.Abstract)) {
this.visitClassLike('abstract class', classDecl);
} else {
this.visitClassLike('class', classDecl);
}
break;
case ts.SyntaxKind.InterfaceDeclaration:
let ifDecl = <ts.InterfaceDeclaration>node;
// Function type interface in an interface with a single declaration
// of a call signature (http://goo.gl/ROC5jN).
if (ifDecl.members.length === 1 && ifDecl.members[0].kind === ts.SyntaxKind.CallSignature) {
let member = <ts.CallSignatureDeclaration>ifDecl.members[0];
this.visitFunctionTypedefInterface(ifDecl.name.text, member, ifDecl.typeParameters);
} else {
this.visitClassLike('abstract class', ifDecl);
}
break;
case ts.SyntaxKind.HeritageClause:
let heritageClause = <ts.HeritageClause>node;
if (heritageClause.token === ts.SyntaxKind.ExtendsKeyword &&
heritageClause.parent.kind !== ts.SyntaxKind.InterfaceDeclaration) {
this.emit('extends');
} else {
this.emit('implements');
}
// Can only have one member for extends clauses.
this.visitList(heritageClause.types);
break;
case ts.SyntaxKind.ExpressionWithTypeArguments:
let exprWithTypeArgs = <ts.ExpressionWithTypeArguments>node;
this.visit(exprWithTypeArgs.expression);
this.maybeVisitTypeArguments(exprWithTypeArgs);
break;
case ts.SyntaxKind.EnumDeclaration:
let decl = <ts.EnumDeclaration>node;
// The only legal modifier for an enum decl is const.
let isConst = decl.modifiers && (decl.modifiers.flags & ts.NodeFlags.Const);
if (isConst) {
this.reportError(node, 'const enums are not supported');
}
this.emit('enum');
this.fc.visitTypeName(decl.name);
this.emit('{');
// Enums can be empty in TS ...
if (decl.members.length === 0) {
// ... but not in Dart.
this.reportError(node, 'empty enums are not supported');
}
this.visitList(decl.members);
this.emit('}');
break;
case ts.SyntaxKind.EnumMember:
let member = <ts.EnumMember>node;
this.visit(member.name);
if (member.initializer) {
this.reportError(node, 'enum initializers are not supported');
}
break;
case ts.SyntaxKind.Constructor:
let ctorDecl = <ts.ConstructorDeclaration>node;
// Find containing class name.
let className: ts.Identifier;
for (let parent = ctorDecl.parent; parent; parent = parent.parent) {
if (parent.kind === ts.SyntaxKind.ClassDeclaration) {
className = (<ts.ClassDeclaration>parent).name;
break;
}
}
if (!className) this.reportError(ctorDecl, 'cannot find outer class node');
this.visitDeclarationMetadata(ctorDecl);
if (this.fc.isConstClass(<base.ClassLike>ctorDecl.parent)) {
this.emit('const');
}
this.visit(className);
this.visitParameters(ctorDecl.parameters);
this.visit(ctorDecl.body);
break;
case ts.SyntaxKind.PropertyDeclaration:
this.visitProperty(<ts.PropertyDeclaration>node);
break;
case ts.SyntaxKind.SemicolonClassElement:
// No-op, don't emit useless declarations.
break;
case ts.SyntaxKind.MethodDeclaration:
this.visitDeclarationMetadata(<ts.MethodDeclaration>node);
this.visitFunctionLike(<ts.MethodDeclaration>node);
break;
case ts.SyntaxKind.GetAccessor:
this.visitDeclarationMetadata(<ts.MethodDeclaration>node);
this.visitFunctionLike(<ts.AccessorDeclaration>node, 'get');
break;
case ts.SyntaxKind.SetAccessor:
this.visitDeclarationMetadata(<ts.MethodDeclaration>node);
this.visitFunctionLike(<ts.AccessorDeclaration>node, 'set');
break;
case ts.SyntaxKind.FunctionDeclaration:
let funcDecl = <ts.FunctionDeclaration>node;
this.visitDecorators(funcDecl.decorators);
this.visitFunctionLike(funcDecl);
break;
case ts.SyntaxKind.ArrowFunction:
let arrowFunc = <ts.FunctionExpression>node;
// Dart only allows expressions following the fat arrow operator.
// If the body is a block, we have to drop the fat arrow and emit an
// anonymous function instead.
if (arrowFunc.body.kind === ts.SyntaxKind.Block) {
this.visitFunctionLike(arrowFunc);
} else {
this.visitParameters(arrowFunc.parameters);
this.emit('=>');
this.visit(arrowFunc.body);
}
break;
case ts.SyntaxKind.FunctionExpression:
let funcExpr = <ts.FunctionExpression>node;
this.visitFunctionLike(funcExpr);
break;
case ts.SyntaxKind.PropertySignature:
let propSig = <ts.PropertyDeclaration>node;
this.visitProperty(propSig);
break;
case ts.SyntaxKind.MethodSignature:
let methodSignatureDecl = <ts.FunctionLikeDeclaration>node;
this.visitEachIfPresent(methodSignatureDecl.modifiers);
this.visitFunctionLike(methodSignatureDecl);
break;
case ts.SyntaxKind.Parameter:
let paramDecl = <ts.ParameterDeclaration>node;
// Property parameters will have an explicit property declaration, so we just
// need the dart assignment shorthand to reference the property.
if (this.hasFlag(paramDecl.modifiers, ts.NodeFlags.Public) ||
this.hasFlag(paramDecl.modifiers, ts.NodeFlags.Private) ||
this.hasFlag(paramDecl.modifiers, ts.NodeFlags.Protected)) {
this.visitDeclarationMetadata(paramDecl);
this.emit('this .');
this.visit(paramDecl.name);
if (paramDecl.initializer) {
this.emit('=');
this.visit(paramDecl.initializer);
}
break;
}
if (paramDecl.dotDotDotToken) this.reportError(node, 'rest parameters are unsupported');
if (paramDecl.name.kind === ts.SyntaxKind.ObjectBindingPattern) {
this.visitNamedParameter(paramDecl);
break;
}
this.visitDecorators(paramDecl.decorators);
if (paramDecl.type && paramDecl.type.kind === ts.SyntaxKind.FunctionType) {
// Dart uses "returnType paramName ( parameters )" syntax.
let fnType = <ts.FunctionOrConstructorTypeNode>paramDecl.type;
let hasRestParameter = fnType.parameters.some(p => !!p.dotDotDotToken);
if (hasRestParameter) {
// Dart does not support rest parameters/varargs, degenerate to just "Function".
this.emit('Function');
this.visit(paramDecl.name);
} else {
this.visit(fnType.type);
this.visit(paramDecl.name);
this.visitParameters(fnType.parameters);
}
} else {
if (paramDecl.type) this.visit(paramDecl.type);
this.visit(paramDecl.name);
}
if (paramDecl.initializer) {
this.emit('=');
this.visit(paramDecl.initializer);
}
break;
case ts.SyntaxKind.StaticKeyword:
this.emit('static');
break;
case ts.SyntaxKind.AbstractKeyword:
// Abstract methods in Dart simply lack implementation,
// and don't use the 'abstract' modifier
// Abstract classes are handled in `case ts.SyntaxKind.ClassDeclaration` above.
break;
case ts.SyntaxKind.PrivateKeyword:
// no-op, handled through '_' naming convention in Dart.
break;
case ts.SyntaxKind.PublicKeyword:
// Handled in `visitDeclarationMetadata` below.
break;
case ts.SyntaxKind.ProtectedKeyword:
// Handled in `visitDeclarationMetadata` below.
break;
default:
return false;
}
return true;
}
private visitVariableDeclarationType(varDecl: ts.VariableDeclaration) {
/* Note: VariableDeclarationList can only occur as part of a for loop. This helper method
* is meant for processing for-loop variable declaration types only.
*
* In Dart, all variables in a variable declaration list must have the same type. Since
* we are doing syntax directed translation, we cannot reliably determine if distinct
* variables are declared with the same type or not. Hence we support the following cases:
*
* - A variable declaration list with a single variable can be explicitly typed.
* - When more than one variable is in the list, all must be implicitly typed.
*/
let firstDecl = varDecl.parent.declarations[0];
let msg = 'Variables in a declaration list of more than one variable cannot by typed';
let isFinal = this.hasFlag(varDecl.parent, ts.NodeFlags.Const);
let isConst = false;
if (isFinal && varDecl.initializer) {
// "const" in TypeScript/ES6 corresponds to "final" in Dart, i.e. reference constness.
// If a "const" variable is immediately initialized to a CONST_EXPR(), special case it to be
// a deeply const constant, and generate "const ...".
isConst = varDecl.initializer.kind === ts.SyntaxKind.StringLiteral ||
varDecl.initializer.kind === ts.SyntaxKind.NumericLiteral ||
this.fc.isConstExpr(varDecl.initializer);
}
if (firstDecl === varDecl) {
if (isConst) {
this.emit('const');
} else if (isFinal) {
this.emit('final');
}
if (!varDecl.type) {
if (!isFinal) this.emit('var');
} else if (varDecl.parent.declarations.length > 1) {
this.reportError(varDecl, msg);
} else {
this.visit(varDecl.type);
}
} else if (varDecl.type) {
this.reportError(varDecl, msg);
}
}
private visitFunctionLike(fn: ts.FunctionLikeDeclaration, accessor?: string) {
this.fc.pushTypeParameterNames(fn);
try {
if (fn.type) {
if (fn.kind === ts.SyntaxKind.ArrowFunction ||
fn.kind === ts.SyntaxKind.FunctionExpression) {
// The return type is silently dropped for function expressions (including arrow
// functions), it is not supported in Dart.
this.emit('/*');
this.visit(fn.type);
this.emit('*/');
} else {
this.visit(fn.type);
}
}
if (accessor) this.emit(accessor);
if (fn.name) this.visit(fn.name);
if (fn.typeParameters) {
this.emit('/*<');
// Emit the names literally instead of visiting, otherwise they will be replaced with the
// comment hack themselves.
this.emit(fn.typeParameters.map(p => base.ident(p.name)).join(', '));
this.emit('>*/');
}
// Dart does not even allow the parens of an empty param list on getter
if (accessor !== 'get') {
this.visitParameters(fn.parameters);
} else {
if (fn.parameters && fn.parameters.length > 0) {
this.reportError(fn, 'getter should not accept parameters');
}
}
if (fn.body) {
this.visit(fn.body);
} else {
this.emit(';');
}
} finally {
this.fc.popTypeParameterNames(fn);
}
}
private visitParameters(parameters: ts.ParameterDeclaration[]) {
this.emit('(');
let firstInitParamIdx = 0;
for (; firstInitParamIdx < parameters.length; firstInitParamIdx++) {
// ObjectBindingPatterns are handled within the parameter visit.
let isOpt =
parameters[firstInitParamIdx].initializer || parameters[firstInitParamIdx].questionToken;
if (isOpt && parameters[firstInitParamIdx].name.kind !== ts.SyntaxKind.ObjectBindingPattern) {
break;
}
}
if (firstInitParamIdx !== 0) {
let requiredParams = parameters.slice(0, firstInitParamIdx);
this.visitList(requiredParams);
}
if (firstInitParamIdx !== parameters.length) {
if (firstInitParamIdx !== 0) this.emit(',');
let positionalOptional = parameters.slice(firstInitParamIdx, parameters.length);
this.emit('[');
this.visitList(positionalOptional);
this.emit(']');
}
this.emit(')');
}
/**
* Visit a property declaration.
* In the special case of property parameters in a constructor, we also allow a parameter to be
* emitted as a property.
*/
private visitProperty(decl: ts.PropertyDeclaration|ts.ParameterDeclaration, isParameter = false) {
if (!isParameter) this.visitDeclarationMetadata(decl);
let containingClass = <base.ClassLike>(isParameter ? decl.parent.parent : decl.parent);
let isConstField =
this.fc.hasConstComment(decl) || this.hasAnnotation(decl.decorators, 'CONST');
let hasConstCtor = this.fc.isConstClass(containingClass);
if (isConstField) {
// const implies final
this.emit('const');
} else {
if (hasConstCtor) {
this.emit('final');
}
}
if (decl.type) {
this.visit(decl.type);
} else if (!isConstField && !hasConstCtor) {
this.emit('var');
}
this.visit(decl.name);
if (decl.initializer && !isParameter) {
this.emit('=');
this.visit(decl.initializer);
}
this.emit(';');
}
private visitClassLike(keyword: string, decl: base.ClassLike) {
this.visitDecorators(decl.decorators);
this.emit(keyword);
this.fc.visitTypeName(decl.name);
if (decl.typeParameters) {
this.emit('<');
this.visitList(decl.typeParameters);
this.emit('>');
}
this.visitEachIfPresent(decl.heritageClauses);
this.emit('{');
// Synthesize explicit properties for ctor with 'property parameters'
let synthesizePropertyParam = (param: ts.ParameterDeclaration) => {
if (this.hasFlag(param.modifiers, ts.NodeFlags.Public) ||
this.hasFlag(param.modifiers, ts.NodeFlags.Private) ||
this.hasFlag(param.modifiers, ts.NodeFlags.Protected)) {
// TODO: we should enforce the underscore prefix on privates
this.visitProperty(param, true);
}
};
(<ts.NodeArray<ts.Declaration>>decl.members)
.filter((m) => m.kind === ts.SyntaxKind.Constructor)
.forEach(
(ctor) =>
(<ts.ConstructorDeclaration>ctor).parameters.forEach(synthesizePropertyParam));
this.visitEachIfPresent(decl.members);
// Generate a constructor to host the const modifier, if needed
if (this.fc.isConstClass(decl) &&
!(<ts.NodeArray<ts.Declaration>>decl.members)
.some((m) => m.kind === ts.SyntaxKind.Constructor)) {
this.emit('const');
this.fc.visitTypeName(decl.name);
this.emit('();');
}
this.emit('}');
}
private visitDecorators(decorators: ts.NodeArray<ts.Decorator>) {
if (!decorators) return;
decorators.forEach((d) => {
// Special case @CONST
let name = base.ident(d.expression);
if (!name && d.expression.kind === ts.SyntaxKind.CallExpression) {
// Unwrap @CONST()
let callExpr = (<ts.CallExpression>d.expression);
name = base.ident(callExpr.expression);
}
// Make sure these match IGNORED_ANNOTATIONS below.
if (name === 'CONST') {
// Ignore @CONST - it is handled above in visitClassLike.
return;
}
this.emit('@');
this.visit(d.expression);
});
}
private visitDeclarationMetadata(decl: ts.Declaration) {
this.visitDecorators(decl.decorators);
this.visitEachIfPresent(decl.modifiers);
if (this.hasFlag(decl.modifiers, ts.NodeFlags.Protected)) {
this.reportError(decl, 'protected declarations are unsupported');
return;
}
if (!this.enforceUnderscoreConventions) return;
// Early return in case this is a decl with no name, such as a constructor
if (!decl.name) return;
let name = base.ident(decl.name);
if (!name) return;
let isPrivate = this.hasFlag(decl.modifiers, ts.NodeFlags.Private);
let matchesPrivate = !!name.match(/^_/);
if (isPrivate && !matchesPrivate) {
this.reportError(decl, 'private members must be prefixed with "_"');
}
if (!isPrivate && matchesPrivate) {
this.reportError(decl, 'public members must not be prefixed with "_"');
}
}
private visitNamedParameter(paramDecl: ts.ParameterDeclaration) {
this.visitDecorators(paramDecl.decorators);
let bp = <ts.BindingPattern>paramDecl.name;
let propertyTypes = this.fc.resolvePropertyTypes(paramDecl.type);
let initMap = this.getInitializers(paramDecl);
this.emit('{');
for (let i = 0; i < bp.elements.length; i++) {
let elem = bp.elements[i];
let propDecl = propertyTypes[base.ident(elem.name)];
if (propDecl && propDecl.type) this.visit(propDecl.type);
this.visit(elem.name);
if (elem.initializer && initMap[base.ident(elem.name)]) {
this.reportError(elem, 'cannot have both an inner and outer initializer');
}
let init = elem.initializer || initMap[base.ident(elem.name)];
if (init) {
this.emit(':');
this.visit(init);
}
if (i + 1 < bp.elements.length) this.emit(',');
}
this.emit('}');
}
private getInitializers(paramDecl: ts.ParameterDeclaration) {
let res: ts.Map<ts.Expression> = {};
if (!paramDecl.initializer) return res;
if (paramDecl.initializer.kind !== ts.SyntaxKind.ObjectLiteralExpression) {
this.reportError(paramDecl, 'initializers for named parameters must be object literals');
return res;
}
for (let i of (<ts.ObjectLiteralExpression>paramDecl.initializer).properties) {
if (i.kind !== ts.SyntaxKind.PropertyAssignment) {
this.reportError(i, 'named parameter initializers must be properties, got ' + i.kind);
continue;
}
let ole = <ts.PropertyAssignment>i;
res[base.ident(ole.name)] = ole.initializer;
}
return res;
}
/**
* Handles a function typedef-like interface, i.e. an interface that only declares a single
* call signature, by translating to a Dart `typedef`.
*/
private visitFunctionTypedefInterface(
name: string, signature: ts.CallSignatureDeclaration,
typeParameters: ts.NodeArray<ts.TypeParameterDeclaration>) {
this.emit('typedef');
if (signature.type) {
this.visit(signature.type);
}
this.emit(name);
if (typeParameters) {
this.emit('<');
this.visitList(typeParameters);
this.emit('>');
}
this.visitParameters(signature.parameters);
this.emit(';');
}
} | the_stack |
import * as $protobuf from "protobufjs";
/** Namespace protoManage. */
export namespace protoManage {
/** Order enum. */
enum Order {
Unknow = 0,
ManagerUpdate = 101,
ManagerDel = 102,
NodeFuncCallReq = 608,
NodeFuncCallAns = 609,
NodeReportUpdateVal = 704,
NodeNotifyAdd = 801,
NodeNotifyError = 803
}
/** State enum. */
enum State {
StateNot = 0,
StateUnknow = 1,
StateNormal = 2,
StateWarn = 3,
StateError = 4
}
/** Level enum. */
enum Level {
LevelNot = 0,
LevelPrimary = 1,
LevelIntermediate = 2,
LevelSenior = 3,
LevelSuper = 4
}
/** NodeFuncReturnType enum. */
enum NodeFuncReturnType {
Unknown = 0,
NotReturn = 1,
Error = 2,
Text = 3,
Json = 4,
Link = 5,
Image = 6,
Media = 7,
File = 8,
Table = 9,
Charts = 10
}
/** NodeReportType enum. */
enum NodeReportType {
NodeReportTypeUnknown = 0,
NodeReportTypeTable = 1,
NodeReportTypeLine = 2
}
/** NotifySenderType enum. */
enum NotifySenderType {
NotifySenderTypeUnknow = 0,
NotifySenderTypeUser = 1,
NotifySenderTypeNode = 2
}
/** NodeResourceType enum. */
enum NodeResourceType {
NodeResourceTypeUnknow = 0,
NodeResourceTypeCache = 1
}
/** HttpError enum. */
enum HttpError {
HttpErrorNull = 0,
HttpErrorGetHeader = 601,
HttpErrorGetBody = 602,
HttpErrorGetFile = 603,
HttpErrorCheckFile = 604,
HttpErrorMarshal = 605,
HttpErrorUnmarshal = 606,
HttpErrorRegister = 607,
HttpErrorLoginWithAccount = 608,
HttpErrorPasswordWithAccount = 609,
HttpErrorLoginWithToken = 610,
HttpErrorLevelLow = 611,
HttpErrorRequest = 612
}
/** Properties of a Message. */
interface IMessage {
/** Message order */
order?: (protoManage.Order|null);
/** Message message */
message?: (Uint8Array|null);
}
/** Represents a Message. */
class Message implements IMessage {
/**
* Constructs a new Message.
* @param [properties] Properties to set
*/
constructor(properties?: protoManage.IMessage);
/** Message order. */
public order: protoManage.Order;
/** Message message. */
public message: Uint8Array;
/**
* Creates a new Message instance using the specified properties.
* @param [properties] Properties to set
* @returns Message instance
*/
public static create(properties?: protoManage.IMessage): protoManage.Message;
/**
* Encodes the specified Message message. Does not implicitly {@link protoManage.Message.verify|verify} messages.
* @param message Message message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: protoManage.IMessage, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified Message message, length delimited. Does not implicitly {@link protoManage.Message.verify|verify} messages.
* @param message Message message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: protoManage.IMessage, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a Message message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns Message
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): protoManage.Message;
/**
* Decodes a Message message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns Message
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): protoManage.Message;
/**
* Verifies a Message message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a Message message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns Message
*/
public static fromObject(object: { [k: string]: any }): protoManage.Message;
/**
* Creates a plain object from a Message message. Also converts values to other types if specified.
* @param message Message
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: protoManage.Message, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this Message to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a HttpMessage. */
interface IHttpMessage {
/** HttpMessage order */
order?: (protoManage.Order|null);
/** HttpMessage message */
message?: (Uint8Array|null);
/** HttpMessage token */
token?: (string|null);
}
/** Represents a HttpMessage. */
class HttpMessage implements IHttpMessage {
/**
* Constructs a new HttpMessage.
* @param [properties] Properties to set
*/
constructor(properties?: protoManage.IHttpMessage);
/** HttpMessage order. */
public order: protoManage.Order;
/** HttpMessage message. */
public message: Uint8Array;
/** HttpMessage token. */
public token: string;
/**
* Creates a new HttpMessage instance using the specified properties.
* @param [properties] Properties to set
* @returns HttpMessage instance
*/
public static create(properties?: protoManage.IHttpMessage): protoManage.HttpMessage;
/**
* Encodes the specified HttpMessage message. Does not implicitly {@link protoManage.HttpMessage.verify|verify} messages.
* @param message HttpMessage message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: protoManage.IHttpMessage, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified HttpMessage message, length delimited. Does not implicitly {@link protoManage.HttpMessage.verify|verify} messages.
* @param message HttpMessage message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: protoManage.IHttpMessage, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a HttpMessage message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns HttpMessage
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): protoManage.HttpMessage;
/**
* Decodes a HttpMessage message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns HttpMessage
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): protoManage.HttpMessage;
/**
* Verifies a HttpMessage message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a HttpMessage message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns HttpMessage
*/
public static fromObject(object: { [k: string]: any }): protoManage.HttpMessage;
/**
* Creates a plain object from a HttpMessage message. Also converts values to other types if specified.
* @param message HttpMessage
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: protoManage.HttpMessage, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this HttpMessage to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Represents a RpcEngine */
class RpcEngine extends $protobuf.rpc.Service {
/**
* Constructs a new RpcEngine service.
* @param rpcImpl RPC implementation
* @param [requestDelimited=false] Whether requests are length-delimited
* @param [responseDelimited=false] Whether responses are length-delimited
*/
constructor(rpcImpl: $protobuf.RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean);
/**
* Creates new RpcEngine service using the specified rpc implementation.
* @param rpcImpl RPC implementation
* @param [requestDelimited=false] Whether requests are length-delimited
* @param [responseDelimited=false] Whether responses are length-delimited
* @returns RPC service. Useful where requests and/or responses are streamed.
*/
public static create(rpcImpl: $protobuf.RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean): RpcEngine;
/**
* Calls RegisterNode.
* @param request Node message or plain object
* @param callback Node-style callback called with the error, if any, and Node
*/
public registerNode(request: protoManage.INode, callback: protoManage.RpcEngine.RegisterNodeCallback): void;
/**
* Calls RegisterNode.
* @param request Node message or plain object
* @returns Promise
*/
public registerNode(request: protoManage.INode): Promise<protoManage.Node>;
/**
* Calls RegisterNodeFunc.
* @param request NodeFunc message or plain object
* @param callback Node-style callback called with the error, if any, and NodeFunc
*/
public registerNodeFunc(request: protoManage.INodeFunc, callback: protoManage.RpcEngine.RegisterNodeFuncCallback): void;
/**
* Calls RegisterNodeFunc.
* @param request NodeFunc message or plain object
* @returns Promise
*/
public registerNodeFunc(request: protoManage.INodeFunc): Promise<protoManage.NodeFunc>;
/**
* Calls RegisterNodeReport.
* @param request NodeReport message or plain object
* @param callback Node-style callback called with the error, if any, and NodeReport
*/
public registerNodeReport(request: protoManage.INodeReport, callback: protoManage.RpcEngine.RegisterNodeReportCallback): void;
/**
* Calls RegisterNodeReport.
* @param request NodeReport message or plain object
* @returns Promise
*/
public registerNodeReport(request: protoManage.INodeReport): Promise<protoManage.NodeReport>;
/**
* Calls CheckNodeResource.
* @param request NodeResource message or plain object
* @param callback Node-style callback called with the error, if any, and NodeResource
*/
public checkNodeResource(request: protoManage.INodeResource, callback: protoManage.RpcEngine.CheckNodeResourceCallback): void;
/**
* Calls CheckNodeResource.
* @param request NodeResource message or plain object
* @returns Promise
*/
public checkNodeResource(request: protoManage.INodeResource): Promise<protoManage.NodeResource>;
/**
* Calls UploadNodeResource.
* @param request ReqNodeResourceUpload message or plain object
* @param callback Node-style callback called with the error, if any, and AnsNodeResourceUpload
*/
public uploadNodeResource(request: protoManage.IReqNodeResourceUpload, callback: protoManage.RpcEngine.UploadNodeResourceCallback): void;
/**
* Calls UploadNodeResource.
* @param request ReqNodeResourceUpload message or plain object
* @returns Promise
*/
public uploadNodeResource(request: protoManage.IReqNodeResourceUpload): Promise<protoManage.AnsNodeResourceUpload>;
/**
* Calls DownloadNodeResource.
* @param request ReqNodeResourceDownload message or plain object
* @param callback Node-style callback called with the error, if any, and AnsNodeResourceDownload
*/
public downloadNodeResource(request: protoManage.IReqNodeResourceDownload, callback: protoManage.RpcEngine.DownloadNodeResourceCallback): void;
/**
* Calls DownloadNodeResource.
* @param request ReqNodeResourceDownload message or plain object
* @returns Promise
*/
public downloadNodeResource(request: protoManage.IReqNodeResourceDownload): Promise<protoManage.AnsNodeResourceDownload>;
/**
* Calls RpcChannel.
* @param request Message message or plain object
* @param callback Node-style callback called with the error, if any, and Message
*/
public rpcChannel(request: protoManage.IMessage, callback: protoManage.RpcEngine.RpcChannelCallback): void;
/**
* Calls RpcChannel.
* @param request Message message or plain object
* @returns Promise
*/
public rpcChannel(request: protoManage.IMessage): Promise<protoManage.Message>;
}
namespace RpcEngine {
/**
* Callback as used by {@link protoManage.RpcEngine#registerNode}.
* @param error Error, if any
* @param [response] Node
*/
type RegisterNodeCallback = (error: (Error|null), response?: protoManage.Node) => void;
/**
* Callback as used by {@link protoManage.RpcEngine#registerNodeFunc}.
* @param error Error, if any
* @param [response] NodeFunc
*/
type RegisterNodeFuncCallback = (error: (Error|null), response?: protoManage.NodeFunc) => void;
/**
* Callback as used by {@link protoManage.RpcEngine#registerNodeReport}.
* @param error Error, if any
* @param [response] NodeReport
*/
type RegisterNodeReportCallback = (error: (Error|null), response?: protoManage.NodeReport) => void;
/**
* Callback as used by {@link protoManage.RpcEngine#checkNodeResource}.
* @param error Error, if any
* @param [response] NodeResource
*/
type CheckNodeResourceCallback = (error: (Error|null), response?: protoManage.NodeResource) => void;
/**
* Callback as used by {@link protoManage.RpcEngine#uploadNodeResource}.
* @param error Error, if any
* @param [response] AnsNodeResourceUpload
*/
type UploadNodeResourceCallback = (error: (Error|null), response?: protoManage.AnsNodeResourceUpload) => void;
/**
* Callback as used by {@link protoManage.RpcEngine#downloadNodeResource}.
* @param error Error, if any
* @param [response] AnsNodeResourceDownload
*/
type DownloadNodeResourceCallback = (error: (Error|null), response?: protoManage.AnsNodeResourceDownload) => void;
/**
* Callback as used by {@link protoManage.RpcEngine#rpcChannel}.
* @param error Error, if any
* @param [response] Message
*/
type RpcChannelCallback = (error: (Error|null), response?: protoManage.Message) => void;
}
/** Properties of a Base. */
interface IBase {
/** Base ID */
ID?: (number|null);
/** Base UpdateTime */
UpdateTime?: (number|null);
}
/** Represents a Base. */
class Base implements IBase {
/**
* Constructs a new Base.
* @param [properties] Properties to set
*/
constructor(properties?: protoManage.IBase);
/** Base ID. */
public ID: number;
/** Base UpdateTime. */
public UpdateTime: number;
/**
* Creates a new Base instance using the specified properties.
* @param [properties] Properties to set
* @returns Base instance
*/
public static create(properties?: protoManage.IBase): protoManage.Base;
/**
* Encodes the specified Base message. Does not implicitly {@link protoManage.Base.verify|verify} messages.
* @param message Base message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: protoManage.IBase, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified Base message, length delimited. Does not implicitly {@link protoManage.Base.verify|verify} messages.
* @param message Base message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: protoManage.IBase, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a Base message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns Base
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): protoManage.Base;
/**
* Decodes a Base message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns Base
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): protoManage.Base;
/**
* Verifies a Base message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a Base message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns Base
*/
public static fromObject(object: { [k: string]: any }): protoManage.Base;
/**
* Creates a plain object from a Base message. Also converts values to other types if specified.
* @param message Base
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: protoManage.Base, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this Base to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a Page. */
interface IPage {
/** Page Count */
Count?: (number|null);
/** Page Num */
Num?: (number|null);
}
/** Represents a Page. */
class Page implements IPage {
/**
* Constructs a new Page.
* @param [properties] Properties to set
*/
constructor(properties?: protoManage.IPage);
/** Page Count. */
public Count: number;
/** Page Num. */
public Num: number;
/**
* Creates a new Page instance using the specified properties.
* @param [properties] Properties to set
* @returns Page instance
*/
public static create(properties?: protoManage.IPage): protoManage.Page;
/**
* Encodes the specified Page message. Does not implicitly {@link protoManage.Page.verify|verify} messages.
* @param message Page message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: protoManage.IPage, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified Page message, length delimited. Does not implicitly {@link protoManage.Page.verify|verify} messages.
* @param message Page message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: protoManage.IPage, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a Page message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns Page
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): protoManage.Page;
/**
* Decodes a Page message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns Page
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): protoManage.Page;
/**
* Verifies a Page message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a Page message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns Page
*/
public static fromObject(object: { [k: string]: any }): protoManage.Page;
/**
* Creates a plain object from a Page message. Also converts values to other types if specified.
* @param message Page
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: protoManage.Page, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this Page to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a Time. */
interface ITime {
/** Time BeginTime */
BeginTime?: (number|null);
/** Time EndTime */
EndTime?: (number|null);
}
/** Represents a Time. */
class Time implements ITime {
/**
* Constructs a new Time.
* @param [properties] Properties to set
*/
constructor(properties?: protoManage.ITime);
/** Time BeginTime. */
public BeginTime: number;
/** Time EndTime. */
public EndTime: number;
/**
* Creates a new Time instance using the specified properties.
* @param [properties] Properties to set
* @returns Time instance
*/
public static create(properties?: protoManage.ITime): protoManage.Time;
/**
* Encodes the specified Time message. Does not implicitly {@link protoManage.Time.verify|verify} messages.
* @param message Time message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: protoManage.ITime, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified Time message, length delimited. Does not implicitly {@link protoManage.Time.verify|verify} messages.
* @param message Time message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: protoManage.ITime, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a Time message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns Time
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): protoManage.Time;
/**
* Decodes a Time message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns Time
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): protoManage.Time;
/**
* Verifies a Time message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a Time message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns Time
*/
public static fromObject(object: { [k: string]: any }): protoManage.Time;
/**
* Creates a plain object from a Time message. Also converts values to other types if specified.
* @param message Time
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: protoManage.Time, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this Time to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a Manager. */
interface IManager {
/** Manager Base */
Base?: (protoManage.IBase|null);
/** Manager Name */
Name?: (string|null);
/** Manager Password */
Password?: (string|null);
/** Manager NickName */
NickName?: (string|null);
/** Manager Token */
Token?: (string|null);
/** Manager Setting */
Setting?: (string|null);
/** Manager Level */
Level?: (protoManage.Level|null);
/** Manager State */
State?: (protoManage.State|null);
}
/** Represents a Manager. */
class Manager implements IManager {
/**
* Constructs a new Manager.
* @param [properties] Properties to set
*/
constructor(properties?: protoManage.IManager);
/** Manager Base. */
public Base?: (protoManage.IBase|null);
/** Manager Name. */
public Name: string;
/** Manager Password. */
public Password: string;
/** Manager NickName. */
public NickName: string;
/** Manager Token. */
public Token: string;
/** Manager Setting. */
public Setting: string;
/** Manager Level. */
public Level: protoManage.Level;
/** Manager State. */
public State: protoManage.State;
/**
* Creates a new Manager instance using the specified properties.
* @param [properties] Properties to set
* @returns Manager instance
*/
public static create(properties?: protoManage.IManager): protoManage.Manager;
/**
* Encodes the specified Manager message. Does not implicitly {@link protoManage.Manager.verify|verify} messages.
* @param message Manager message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: protoManage.IManager, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified Manager message, length delimited. Does not implicitly {@link protoManage.Manager.verify|verify} messages.
* @param message Manager message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: protoManage.IManager, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a Manager message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns Manager
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): protoManage.Manager;
/**
* Decodes a Manager message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns Manager
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): protoManage.Manager;
/**
* Verifies a Manager message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a Manager message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns Manager
*/
public static fromObject(object: { [k: string]: any }): protoManage.Manager;
/**
* Creates a plain object from a Manager message. Also converts values to other types if specified.
* @param message Manager
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: protoManage.Manager, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this Manager to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a TopLink. */
interface ITopLink {
/** TopLink Base */
Base?: (protoManage.IBase|null);
/** TopLink Name */
Name?: (string|null);
/** TopLink Url */
Url?: (string|null);
/** TopLink State */
State?: (protoManage.State|null);
}
/** Represents a TopLink. */
class TopLink implements ITopLink {
/**
* Constructs a new TopLink.
* @param [properties] Properties to set
*/
constructor(properties?: protoManage.ITopLink);
/** TopLink Base. */
public Base?: (protoManage.IBase|null);
/** TopLink Name. */
public Name: string;
/** TopLink Url. */
public Url: string;
/** TopLink State. */
public State: protoManage.State;
/**
* Creates a new TopLink instance using the specified properties.
* @param [properties] Properties to set
* @returns TopLink instance
*/
public static create(properties?: protoManage.ITopLink): protoManage.TopLink;
/**
* Encodes the specified TopLink message. Does not implicitly {@link protoManage.TopLink.verify|verify} messages.
* @param message TopLink message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: protoManage.ITopLink, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified TopLink message, length delimited. Does not implicitly {@link protoManage.TopLink.verify|verify} messages.
* @param message TopLink message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: protoManage.ITopLink, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a TopLink message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns TopLink
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): protoManage.TopLink;
/**
* Decodes a TopLink message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns TopLink
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): protoManage.TopLink;
/**
* Verifies a TopLink message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a TopLink message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns TopLink
*/
public static fromObject(object: { [k: string]: any }): protoManage.TopLink;
/**
* Creates a plain object from a TopLink message. Also converts values to other types if specified.
* @param message TopLink
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: protoManage.TopLink, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this TopLink to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a Node. */
interface INode {
/** Node Base */
Base?: (protoManage.IBase|null);
/** Node Name */
Name?: (string|null);
/** Node State */
State?: (protoManage.State|null);
}
/** Represents a Node. */
class Node implements INode {
/**
* Constructs a new Node.
* @param [properties] Properties to set
*/
constructor(properties?: protoManage.INode);
/** Node Base. */
public Base?: (protoManage.IBase|null);
/** Node Name. */
public Name: string;
/** Node State. */
public State: protoManage.State;
/**
* Creates a new Node instance using the specified properties.
* @param [properties] Properties to set
* @returns Node instance
*/
public static create(properties?: protoManage.INode): protoManage.Node;
/**
* Encodes the specified Node message. Does not implicitly {@link protoManage.Node.verify|verify} messages.
* @param message Node message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: protoManage.INode, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified Node message, length delimited. Does not implicitly {@link protoManage.Node.verify|verify} messages.
* @param message Node message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: protoManage.INode, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a Node message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns Node
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): protoManage.Node;
/**
* Decodes a Node message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns Node
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): protoManage.Node;
/**
* Verifies a Node message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a Node message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns Node
*/
public static fromObject(object: { [k: string]: any }): protoManage.Node;
/**
* Creates a plain object from a Node message. Also converts values to other types if specified.
* @param message Node
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: protoManage.Node, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this Node to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a NodeFunc. */
interface INodeFunc {
/** NodeFunc Base */
Base?: (protoManage.IBase|null);
/** NodeFunc NodeID */
NodeID?: (number|null);
/** NodeFunc Name */
Name?: (string|null);
/** NodeFunc Func */
Func?: (string|null);
/** NodeFunc Schema */
Schema?: (string|null);
/** NodeFunc Level */
Level?: (protoManage.Level|null);
/** NodeFunc State */
State?: (protoManage.State|null);
}
/** Represents a NodeFunc. */
class NodeFunc implements INodeFunc {
/**
* Constructs a new NodeFunc.
* @param [properties] Properties to set
*/
constructor(properties?: protoManage.INodeFunc);
/** NodeFunc Base. */
public Base?: (protoManage.IBase|null);
/** NodeFunc NodeID. */
public NodeID: number;
/** NodeFunc Name. */
public Name: string;
/** NodeFunc Func. */
public Func: string;
/** NodeFunc Schema. */
public Schema: string;
/** NodeFunc Level. */
public Level: protoManage.Level;
/** NodeFunc State. */
public State: protoManage.State;
/**
* Creates a new NodeFunc instance using the specified properties.
* @param [properties] Properties to set
* @returns NodeFunc instance
*/
public static create(properties?: protoManage.INodeFunc): protoManage.NodeFunc;
/**
* Encodes the specified NodeFunc message. Does not implicitly {@link protoManage.NodeFunc.verify|verify} messages.
* @param message NodeFunc message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: protoManage.INodeFunc, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified NodeFunc message, length delimited. Does not implicitly {@link protoManage.NodeFunc.verify|verify} messages.
* @param message NodeFunc message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: protoManage.INodeFunc, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a NodeFunc message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns NodeFunc
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): protoManage.NodeFunc;
/**
* Decodes a NodeFunc message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns NodeFunc
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): protoManage.NodeFunc;
/**
* Verifies a NodeFunc message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a NodeFunc message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns NodeFunc
*/
public static fromObject(object: { [k: string]: any }): protoManage.NodeFunc;
/**
* Creates a plain object from a NodeFunc message. Also converts values to other types if specified.
* @param message NodeFunc
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: protoManage.NodeFunc, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this NodeFunc to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a NodeFuncCall. */
interface INodeFuncCall {
/** NodeFuncCall Base */
Base?: (protoManage.IBase|null);
/** NodeFuncCall RequesterID */
RequesterID?: (number|null);
/** NodeFuncCall RequesterName */
RequesterName?: (string|null);
/** NodeFuncCall FuncID */
FuncID?: (number|null);
/** NodeFuncCall Parameter */
Parameter?: (string|null);
/** NodeFuncCall ReturnVal */
ReturnVal?: (string|null);
/** NodeFuncCall ReturnType */
ReturnType?: (protoManage.NodeFuncReturnType|null);
/** NodeFuncCall State */
State?: (protoManage.State|null);
}
/** Represents a NodeFuncCall. */
class NodeFuncCall implements INodeFuncCall {
/**
* Constructs a new NodeFuncCall.
* @param [properties] Properties to set
*/
constructor(properties?: protoManage.INodeFuncCall);
/** NodeFuncCall Base. */
public Base?: (protoManage.IBase|null);
/** NodeFuncCall RequesterID. */
public RequesterID: number;
/** NodeFuncCall RequesterName. */
public RequesterName: string;
/** NodeFuncCall FuncID. */
public FuncID: number;
/** NodeFuncCall Parameter. */
public Parameter: string;
/** NodeFuncCall ReturnVal. */
public ReturnVal: string;
/** NodeFuncCall ReturnType. */
public ReturnType: protoManage.NodeFuncReturnType;
/** NodeFuncCall State. */
public State: protoManage.State;
/**
* Creates a new NodeFuncCall instance using the specified properties.
* @param [properties] Properties to set
* @returns NodeFuncCall instance
*/
public static create(properties?: protoManage.INodeFuncCall): protoManage.NodeFuncCall;
/**
* Encodes the specified NodeFuncCall message. Does not implicitly {@link protoManage.NodeFuncCall.verify|verify} messages.
* @param message NodeFuncCall message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: protoManage.INodeFuncCall, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified NodeFuncCall message, length delimited. Does not implicitly {@link protoManage.NodeFuncCall.verify|verify} messages.
* @param message NodeFuncCall message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: protoManage.INodeFuncCall, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a NodeFuncCall message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns NodeFuncCall
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): protoManage.NodeFuncCall;
/**
* Decodes a NodeFuncCall message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns NodeFuncCall
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): protoManage.NodeFuncCall;
/**
* Verifies a NodeFuncCall message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a NodeFuncCall message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns NodeFuncCall
*/
public static fromObject(object: { [k: string]: any }): protoManage.NodeFuncCall;
/**
* Creates a plain object from a NodeFuncCall message. Also converts values to other types if specified.
* @param message NodeFuncCall
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: protoManage.NodeFuncCall, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this NodeFuncCall to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a NodeReport. */
interface INodeReport {
/** NodeReport Base */
Base?: (protoManage.IBase|null);
/** NodeReport NodeID */
NodeID?: (number|null);
/** NodeReport Name */
Name?: (string|null);
/** NodeReport Type */
Type?: (protoManage.NodeReportType|null);
/** NodeReport Func */
Func?: (string|null);
/** NodeReport Schema */
Schema?: (string|null);
/** NodeReport Interval */
Interval?: (number|null);
/** NodeReport Level */
Level?: (protoManage.Level|null);
/** NodeReport State */
State?: (protoManage.State|null);
}
/** Represents a NodeReport. */
class NodeReport implements INodeReport {
/**
* Constructs a new NodeReport.
* @param [properties] Properties to set
*/
constructor(properties?: protoManage.INodeReport);
/** NodeReport Base. */
public Base?: (protoManage.IBase|null);
/** NodeReport NodeID. */
public NodeID: number;
/** NodeReport Name. */
public Name: string;
/** NodeReport Type. */
public Type: protoManage.NodeReportType;
/** NodeReport Func. */
public Func: string;
/** NodeReport Schema. */
public Schema: string;
/** NodeReport Interval. */
public Interval: number;
/** NodeReport Level. */
public Level: protoManage.Level;
/** NodeReport State. */
public State: protoManage.State;
/**
* Creates a new NodeReport instance using the specified properties.
* @param [properties] Properties to set
* @returns NodeReport instance
*/
public static create(properties?: protoManage.INodeReport): protoManage.NodeReport;
/**
* Encodes the specified NodeReport message. Does not implicitly {@link protoManage.NodeReport.verify|verify} messages.
* @param message NodeReport message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: protoManage.INodeReport, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified NodeReport message, length delimited. Does not implicitly {@link protoManage.NodeReport.verify|verify} messages.
* @param message NodeReport message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: protoManage.INodeReport, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a NodeReport message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns NodeReport
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): protoManage.NodeReport;
/**
* Decodes a NodeReport message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns NodeReport
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): protoManage.NodeReport;
/**
* Verifies a NodeReport message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a NodeReport message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns NodeReport
*/
public static fromObject(object: { [k: string]: any }): protoManage.NodeReport;
/**
* Creates a plain object from a NodeReport message. Also converts values to other types if specified.
* @param message NodeReport
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: protoManage.NodeReport, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this NodeReport to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a NodeReportVal. */
interface INodeReportVal {
/** NodeReportVal Base */
Base?: (protoManage.IBase|null);
/** NodeReportVal ReportID */
ReportID?: (number|null);
/** NodeReportVal Value */
Value?: (string|null);
/** NodeReportVal State */
State?: (protoManage.State|null);
}
/** Represents a NodeReportVal. */
class NodeReportVal implements INodeReportVal {
/**
* Constructs a new NodeReportVal.
* @param [properties] Properties to set
*/
constructor(properties?: protoManage.INodeReportVal);
/** NodeReportVal Base. */
public Base?: (protoManage.IBase|null);
/** NodeReportVal ReportID. */
public ReportID: number;
/** NodeReportVal Value. */
public Value: string;
/** NodeReportVal State. */
public State: protoManage.State;
/**
* Creates a new NodeReportVal instance using the specified properties.
* @param [properties] Properties to set
* @returns NodeReportVal instance
*/
public static create(properties?: protoManage.INodeReportVal): protoManage.NodeReportVal;
/**
* Encodes the specified NodeReportVal message. Does not implicitly {@link protoManage.NodeReportVal.verify|verify} messages.
* @param message NodeReportVal message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: protoManage.INodeReportVal, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified NodeReportVal message, length delimited. Does not implicitly {@link protoManage.NodeReportVal.verify|verify} messages.
* @param message NodeReportVal message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: protoManage.INodeReportVal, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a NodeReportVal message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns NodeReportVal
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): protoManage.NodeReportVal;
/**
* Decodes a NodeReportVal message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns NodeReportVal
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): protoManage.NodeReportVal;
/**
* Verifies a NodeReportVal message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a NodeReportVal message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns NodeReportVal
*/
public static fromObject(object: { [k: string]: any }): protoManage.NodeReportVal;
/**
* Creates a plain object from a NodeReportVal message. Also converts values to other types if specified.
* @param message NodeReportVal
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: protoManage.NodeReportVal, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this NodeReportVal to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a NodeNotify. */
interface INodeNotify {
/** NodeNotify Base */
Base?: (protoManage.IBase|null);
/** NodeNotify SenderID */
SenderID?: (number|null);
/** NodeNotify SenderName */
SenderName?: (string|null);
/** NodeNotify SenderType */
SenderType?: (protoManage.NotifySenderType|null);
/** NodeNotify Message */
Message?: (string|null);
/** NodeNotify State */
State?: (protoManage.State|null);
/** NodeNotify showPop */
showPop?: (boolean|null);
}
/** Represents a NodeNotify. */
class NodeNotify implements INodeNotify {
/**
* Constructs a new NodeNotify.
* @param [properties] Properties to set
*/
constructor(properties?: protoManage.INodeNotify);
/** NodeNotify Base. */
public Base?: (protoManage.IBase|null);
/** NodeNotify SenderID. */
public SenderID: number;
/** NodeNotify SenderName. */
public SenderName: string;
/** NodeNotify SenderType. */
public SenderType: protoManage.NotifySenderType;
/** NodeNotify Message. */
public Message: string;
/** NodeNotify State. */
public State: protoManage.State;
/** NodeNotify showPop. */
public showPop: boolean;
/**
* Creates a new NodeNotify instance using the specified properties.
* @param [properties] Properties to set
* @returns NodeNotify instance
*/
public static create(properties?: protoManage.INodeNotify): protoManage.NodeNotify;
/**
* Encodes the specified NodeNotify message. Does not implicitly {@link protoManage.NodeNotify.verify|verify} messages.
* @param message NodeNotify message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: protoManage.INodeNotify, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified NodeNotify message, length delimited. Does not implicitly {@link protoManage.NodeNotify.verify|verify} messages.
* @param message NodeNotify message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: protoManage.INodeNotify, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a NodeNotify message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns NodeNotify
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): protoManage.NodeNotify;
/**
* Decodes a NodeNotify message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns NodeNotify
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): protoManage.NodeNotify;
/**
* Verifies a NodeNotify message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a NodeNotify message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns NodeNotify
*/
public static fromObject(object: { [k: string]: any }): protoManage.NodeNotify;
/**
* Creates a plain object from a NodeNotify message. Also converts values to other types if specified.
* @param message NodeNotify
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: protoManage.NodeNotify, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this NodeNotify to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a NodeResource. */
interface INodeResource {
/** NodeResource Base */
Base?: (protoManage.IBase|null);
/** NodeResource Name */
Name?: (string|null);
/** NodeResource Md5 */
Md5?: (string|null);
/** NodeResource Sizes */
Sizes?: (number|null);
/** NodeResource Type */
Type?: (protoManage.NodeResourceType|null);
/** NodeResource UploaderID */
UploaderID?: (number|null);
/** NodeResource UploaderName */
UploaderName?: (string|null);
/** NodeResource UploaderType */
UploaderType?: (protoManage.NotifySenderType|null);
/** NodeResource UploadTime */
UploadTime?: (number|null);
/** NodeResource DownLoadCnt */
DownLoadCnt?: (number|null);
/** NodeResource State */
State?: (protoManage.State|null);
}
/** Represents a NodeResource. */
class NodeResource implements INodeResource {
/**
* Constructs a new NodeResource.
* @param [properties] Properties to set
*/
constructor(properties?: protoManage.INodeResource);
/** NodeResource Base. */
public Base?: (protoManage.IBase|null);
/** NodeResource Name. */
public Name: string;
/** NodeResource Md5. */
public Md5: string;
/** NodeResource Sizes. */
public Sizes: number;
/** NodeResource Type. */
public Type: protoManage.NodeResourceType;
/** NodeResource UploaderID. */
public UploaderID: number;
/** NodeResource UploaderName. */
public UploaderName: string;
/** NodeResource UploaderType. */
public UploaderType: protoManage.NotifySenderType;
/** NodeResource UploadTime. */
public UploadTime: number;
/** NodeResource DownLoadCnt. */
public DownLoadCnt: number;
/** NodeResource State. */
public State: protoManage.State;
/**
* Creates a new NodeResource instance using the specified properties.
* @param [properties] Properties to set
* @returns NodeResource instance
*/
public static create(properties?: protoManage.INodeResource): protoManage.NodeResource;
/**
* Encodes the specified NodeResource message. Does not implicitly {@link protoManage.NodeResource.verify|verify} messages.
* @param message NodeResource message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: protoManage.INodeResource, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified NodeResource message, length delimited. Does not implicitly {@link protoManage.NodeResource.verify|verify} messages.
* @param message NodeResource message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: protoManage.INodeResource, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a NodeResource message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns NodeResource
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): protoManage.NodeResource;
/**
* Decodes a NodeResource message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns NodeResource
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): protoManage.NodeResource;
/**
* Verifies a NodeResource message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a NodeResource message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns NodeResource
*/
public static fromObject(object: { [k: string]: any }): protoManage.NodeResource;
/**
* Creates a plain object from a NodeResource message. Also converts values to other types if specified.
* @param message NodeResource
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: protoManage.NodeResource, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this NodeResource to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a ReqSystemInitInfo. */
interface IReqSystemInitInfo {
}
/** Represents a ReqSystemInitInfo. */
class ReqSystemInitInfo implements IReqSystemInitInfo {
/**
* Constructs a new ReqSystemInitInfo.
* @param [properties] Properties to set
*/
constructor(properties?: protoManage.IReqSystemInitInfo);
/**
* Creates a new ReqSystemInitInfo instance using the specified properties.
* @param [properties] Properties to set
* @returns ReqSystemInitInfo instance
*/
public static create(properties?: protoManage.IReqSystemInitInfo): protoManage.ReqSystemInitInfo;
/**
* Encodes the specified ReqSystemInitInfo message. Does not implicitly {@link protoManage.ReqSystemInitInfo.verify|verify} messages.
* @param message ReqSystemInitInfo message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: protoManage.IReqSystemInitInfo, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ReqSystemInitInfo message, length delimited. Does not implicitly {@link protoManage.ReqSystemInitInfo.verify|verify} messages.
* @param message ReqSystemInitInfo message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: protoManage.IReqSystemInitInfo, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ReqSystemInitInfo message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ReqSystemInitInfo
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): protoManage.ReqSystemInitInfo;
/**
* Decodes a ReqSystemInitInfo message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ReqSystemInitInfo
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): protoManage.ReqSystemInitInfo;
/**
* Verifies a ReqSystemInitInfo message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a ReqSystemInitInfo message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ReqSystemInitInfo
*/
public static fromObject(object: { [k: string]: any }): protoManage.ReqSystemInitInfo;
/**
* Creates a plain object from a ReqSystemInitInfo message. Also converts values to other types if specified.
* @param message ReqSystemInitInfo
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: protoManage.ReqSystemInitInfo, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this ReqSystemInitInfo to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of an AnsSystemInitInfo. */
interface IAnsSystemInitInfo {
/** AnsSystemInitInfo systemInit */
systemInit?: (boolean|null);
/** AnsSystemInitInfo openRegister */
openRegister?: (boolean|null);
}
/** Represents an AnsSystemInitInfo. */
class AnsSystemInitInfo implements IAnsSystemInitInfo {
/**
* Constructs a new AnsSystemInitInfo.
* @param [properties] Properties to set
*/
constructor(properties?: protoManage.IAnsSystemInitInfo);
/** AnsSystemInitInfo systemInit. */
public systemInit: boolean;
/** AnsSystemInitInfo openRegister. */
public openRegister: boolean;
/**
* Creates a new AnsSystemInitInfo instance using the specified properties.
* @param [properties] Properties to set
* @returns AnsSystemInitInfo instance
*/
public static create(properties?: protoManage.IAnsSystemInitInfo): protoManage.AnsSystemInitInfo;
/**
* Encodes the specified AnsSystemInitInfo message. Does not implicitly {@link protoManage.AnsSystemInitInfo.verify|verify} messages.
* @param message AnsSystemInitInfo message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: protoManage.IAnsSystemInitInfo, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified AnsSystemInitInfo message, length delimited. Does not implicitly {@link protoManage.AnsSystemInitInfo.verify|verify} messages.
* @param message AnsSystemInitInfo message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: protoManage.IAnsSystemInitInfo, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes an AnsSystemInitInfo message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns AnsSystemInitInfo
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): protoManage.AnsSystemInitInfo;
/**
* Decodes an AnsSystemInitInfo message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns AnsSystemInitInfo
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): protoManage.AnsSystemInitInfo;
/**
* Verifies an AnsSystemInitInfo message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates an AnsSystemInitInfo message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns AnsSystemInitInfo
*/
public static fromObject(object: { [k: string]: any }): protoManage.AnsSystemInitInfo;
/**
* Creates a plain object from an AnsSystemInitInfo message. Also converts values to other types if specified.
* @param message AnsSystemInitInfo
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: protoManage.AnsSystemInitInfo, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this AnsSystemInitInfo to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a ReqTopLinkList. */
interface IReqTopLinkList {
}
/** Represents a ReqTopLinkList. */
class ReqTopLinkList implements IReqTopLinkList {
/**
* Constructs a new ReqTopLinkList.
* @param [properties] Properties to set
*/
constructor(properties?: protoManage.IReqTopLinkList);
/**
* Creates a new ReqTopLinkList instance using the specified properties.
* @param [properties] Properties to set
* @returns ReqTopLinkList instance
*/
public static create(properties?: protoManage.IReqTopLinkList): protoManage.ReqTopLinkList;
/**
* Encodes the specified ReqTopLinkList message. Does not implicitly {@link protoManage.ReqTopLinkList.verify|verify} messages.
* @param message ReqTopLinkList message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: protoManage.IReqTopLinkList, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ReqTopLinkList message, length delimited. Does not implicitly {@link protoManage.ReqTopLinkList.verify|verify} messages.
* @param message ReqTopLinkList message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: protoManage.IReqTopLinkList, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ReqTopLinkList message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ReqTopLinkList
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): protoManage.ReqTopLinkList;
/**
* Decodes a ReqTopLinkList message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ReqTopLinkList
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): protoManage.ReqTopLinkList;
/**
* Verifies a ReqTopLinkList message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a ReqTopLinkList message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ReqTopLinkList
*/
public static fromObject(object: { [k: string]: any }): protoManage.ReqTopLinkList;
/**
* Creates a plain object from a ReqTopLinkList message. Also converts values to other types if specified.
* @param message ReqTopLinkList
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: protoManage.ReqTopLinkList, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this ReqTopLinkList to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of an AnsTopLinkList. */
interface IAnsTopLinkList {
/** AnsTopLinkList TopLinkList */
TopLinkList?: (protoManage.ITopLink[]|null);
}
/** Represents an AnsTopLinkList. */
class AnsTopLinkList implements IAnsTopLinkList {
/**
* Constructs a new AnsTopLinkList.
* @param [properties] Properties to set
*/
constructor(properties?: protoManage.IAnsTopLinkList);
/** AnsTopLinkList TopLinkList. */
public TopLinkList: protoManage.ITopLink[];
/**
* Creates a new AnsTopLinkList instance using the specified properties.
* @param [properties] Properties to set
* @returns AnsTopLinkList instance
*/
public static create(properties?: protoManage.IAnsTopLinkList): protoManage.AnsTopLinkList;
/**
* Encodes the specified AnsTopLinkList message. Does not implicitly {@link protoManage.AnsTopLinkList.verify|verify} messages.
* @param message AnsTopLinkList message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: protoManage.IAnsTopLinkList, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified AnsTopLinkList message, length delimited. Does not implicitly {@link protoManage.AnsTopLinkList.verify|verify} messages.
* @param message AnsTopLinkList message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: protoManage.IAnsTopLinkList, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes an AnsTopLinkList message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns AnsTopLinkList
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): protoManage.AnsTopLinkList;
/**
* Decodes an AnsTopLinkList message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns AnsTopLinkList
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): protoManage.AnsTopLinkList;
/**
* Verifies an AnsTopLinkList message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates an AnsTopLinkList message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns AnsTopLinkList
*/
public static fromObject(object: { [k: string]: any }): protoManage.AnsTopLinkList;
/**
* Creates a plain object from an AnsTopLinkList message. Also converts values to other types if specified.
* @param message AnsTopLinkList
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: protoManage.AnsTopLinkList, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this AnsTopLinkList to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a ReqManagerList. */
interface IReqManagerList {
}
/** Represents a ReqManagerList. */
class ReqManagerList implements IReqManagerList {
/**
* Constructs a new ReqManagerList.
* @param [properties] Properties to set
*/
constructor(properties?: protoManage.IReqManagerList);
/**
* Creates a new ReqManagerList instance using the specified properties.
* @param [properties] Properties to set
* @returns ReqManagerList instance
*/
public static create(properties?: protoManage.IReqManagerList): protoManage.ReqManagerList;
/**
* Encodes the specified ReqManagerList message. Does not implicitly {@link protoManage.ReqManagerList.verify|verify} messages.
* @param message ReqManagerList message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: protoManage.IReqManagerList, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ReqManagerList message, length delimited. Does not implicitly {@link protoManage.ReqManagerList.verify|verify} messages.
* @param message ReqManagerList message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: protoManage.IReqManagerList, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ReqManagerList message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ReqManagerList
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): protoManage.ReqManagerList;
/**
* Decodes a ReqManagerList message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ReqManagerList
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): protoManage.ReqManagerList;
/**
* Verifies a ReqManagerList message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a ReqManagerList message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ReqManagerList
*/
public static fromObject(object: { [k: string]: any }): protoManage.ReqManagerList;
/**
* Creates a plain object from a ReqManagerList message. Also converts values to other types if specified.
* @param message ReqManagerList
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: protoManage.ReqManagerList, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this ReqManagerList to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of an AnsManagerList. */
interface IAnsManagerList {
/** AnsManagerList ManagerList */
ManagerList?: (protoManage.IManager[]|null);
}
/** Represents an AnsManagerList. */
class AnsManagerList implements IAnsManagerList {
/**
* Constructs a new AnsManagerList.
* @param [properties] Properties to set
*/
constructor(properties?: protoManage.IAnsManagerList);
/** AnsManagerList ManagerList. */
public ManagerList: protoManage.IManager[];
/**
* Creates a new AnsManagerList instance using the specified properties.
* @param [properties] Properties to set
* @returns AnsManagerList instance
*/
public static create(properties?: protoManage.IAnsManagerList): protoManage.AnsManagerList;
/**
* Encodes the specified AnsManagerList message. Does not implicitly {@link protoManage.AnsManagerList.verify|verify} messages.
* @param message AnsManagerList message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: protoManage.IAnsManagerList, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified AnsManagerList message, length delimited. Does not implicitly {@link protoManage.AnsManagerList.verify|verify} messages.
* @param message AnsManagerList message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: protoManage.IAnsManagerList, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes an AnsManagerList message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns AnsManagerList
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): protoManage.AnsManagerList;
/**
* Decodes an AnsManagerList message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns AnsManagerList
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): protoManage.AnsManagerList;
/**
* Verifies an AnsManagerList message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates an AnsManagerList message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns AnsManagerList
*/
public static fromObject(object: { [k: string]: any }): protoManage.AnsManagerList;
/**
* Creates a plain object from an AnsManagerList message. Also converts values to other types if specified.
* @param message AnsManagerList
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: protoManage.AnsManagerList, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this AnsManagerList to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a ReqNodeList. */
interface IReqNodeList {
/** ReqNodeList ID */
ID?: (number[]|null);
/** ReqNodeList Name */
Name?: (string[]|null);
/** ReqNodeList State */
State?: (protoManage.State[]|null);
/** ReqNodeList UpdateTime */
UpdateTime?: (protoManage.ITime[]|null);
/** ReqNodeList Page */
Page?: (protoManage.IPage|null);
}
/** Represents a ReqNodeList. */
class ReqNodeList implements IReqNodeList {
/**
* Constructs a new ReqNodeList.
* @param [properties] Properties to set
*/
constructor(properties?: protoManage.IReqNodeList);
/** ReqNodeList ID. */
public ID: number[];
/** ReqNodeList Name. */
public Name: string[];
/** ReqNodeList State. */
public State: protoManage.State[];
/** ReqNodeList UpdateTime. */
public UpdateTime: protoManage.ITime[];
/** ReqNodeList Page. */
public Page?: (protoManage.IPage|null);
/**
* Creates a new ReqNodeList instance using the specified properties.
* @param [properties] Properties to set
* @returns ReqNodeList instance
*/
public static create(properties?: protoManage.IReqNodeList): protoManage.ReqNodeList;
/**
* Encodes the specified ReqNodeList message. Does not implicitly {@link protoManage.ReqNodeList.verify|verify} messages.
* @param message ReqNodeList message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: protoManage.IReqNodeList, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ReqNodeList message, length delimited. Does not implicitly {@link protoManage.ReqNodeList.verify|verify} messages.
* @param message ReqNodeList message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: protoManage.IReqNodeList, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ReqNodeList message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ReqNodeList
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): protoManage.ReqNodeList;
/**
* Decodes a ReqNodeList message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ReqNodeList
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): protoManage.ReqNodeList;
/**
* Verifies a ReqNodeList message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a ReqNodeList message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ReqNodeList
*/
public static fromObject(object: { [k: string]: any }): protoManage.ReqNodeList;
/**
* Creates a plain object from a ReqNodeList message. Also converts values to other types if specified.
* @param message ReqNodeList
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: protoManage.ReqNodeList, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this ReqNodeList to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of an AnsNodeList. */
interface IAnsNodeList {
/** AnsNodeList Length */
Length?: (number|null);
/** AnsNodeList NodeList */
NodeList?: (protoManage.INode[]|null);
}
/** Represents an AnsNodeList. */
class AnsNodeList implements IAnsNodeList {
/**
* Constructs a new AnsNodeList.
* @param [properties] Properties to set
*/
constructor(properties?: protoManage.IAnsNodeList);
/** AnsNodeList Length. */
public Length: number;
/** AnsNodeList NodeList. */
public NodeList: protoManage.INode[];
/**
* Creates a new AnsNodeList instance using the specified properties.
* @param [properties] Properties to set
* @returns AnsNodeList instance
*/
public static create(properties?: protoManage.IAnsNodeList): protoManage.AnsNodeList;
/**
* Encodes the specified AnsNodeList message. Does not implicitly {@link protoManage.AnsNodeList.verify|verify} messages.
* @param message AnsNodeList message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: protoManage.IAnsNodeList, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified AnsNodeList message, length delimited. Does not implicitly {@link protoManage.AnsNodeList.verify|verify} messages.
* @param message AnsNodeList message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: protoManage.IAnsNodeList, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes an AnsNodeList message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns AnsNodeList
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): protoManage.AnsNodeList;
/**
* Decodes an AnsNodeList message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns AnsNodeList
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): protoManage.AnsNodeList;
/**
* Verifies an AnsNodeList message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates an AnsNodeList message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns AnsNodeList
*/
public static fromObject(object: { [k: string]: any }): protoManage.AnsNodeList;
/**
* Creates a plain object from an AnsNodeList message. Also converts values to other types if specified.
* @param message AnsNodeList
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: protoManage.AnsNodeList, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this AnsNodeList to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a ReqNodeFuncList. */
interface IReqNodeFuncList {
/** ReqNodeFuncList ID */
ID?: (number[]|null);
/** ReqNodeFuncList Name */
Name?: (string[]|null);
/** ReqNodeFuncList Level */
Level?: (protoManage.Level[]|null);
/** ReqNodeFuncList LevelMax */
LevelMax?: (protoManage.Level|null);
/** ReqNodeFuncList NodeID */
NodeID?: (number[]|null);
/** ReqNodeFuncList NodeName */
NodeName?: (string[]|null);
/** ReqNodeFuncList UpdateTime */
UpdateTime?: (protoManage.ITime[]|null);
/** ReqNodeFuncList Page */
Page?: (protoManage.IPage|null);
}
/** Represents a ReqNodeFuncList. */
class ReqNodeFuncList implements IReqNodeFuncList {
/**
* Constructs a new ReqNodeFuncList.
* @param [properties] Properties to set
*/
constructor(properties?: protoManage.IReqNodeFuncList);
/** ReqNodeFuncList ID. */
public ID: number[];
/** ReqNodeFuncList Name. */
public Name: string[];
/** ReqNodeFuncList Level. */
public Level: protoManage.Level[];
/** ReqNodeFuncList LevelMax. */
public LevelMax: protoManage.Level;
/** ReqNodeFuncList NodeID. */
public NodeID: number[];
/** ReqNodeFuncList NodeName. */
public NodeName: string[];
/** ReqNodeFuncList UpdateTime. */
public UpdateTime: protoManage.ITime[];
/** ReqNodeFuncList Page. */
public Page?: (protoManage.IPage|null);
/**
* Creates a new ReqNodeFuncList instance using the specified properties.
* @param [properties] Properties to set
* @returns ReqNodeFuncList instance
*/
public static create(properties?: protoManage.IReqNodeFuncList): protoManage.ReqNodeFuncList;
/**
* Encodes the specified ReqNodeFuncList message. Does not implicitly {@link protoManage.ReqNodeFuncList.verify|verify} messages.
* @param message ReqNodeFuncList message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: protoManage.IReqNodeFuncList, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ReqNodeFuncList message, length delimited. Does not implicitly {@link protoManage.ReqNodeFuncList.verify|verify} messages.
* @param message ReqNodeFuncList message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: protoManage.IReqNodeFuncList, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ReqNodeFuncList message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ReqNodeFuncList
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): protoManage.ReqNodeFuncList;
/**
* Decodes a ReqNodeFuncList message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ReqNodeFuncList
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): protoManage.ReqNodeFuncList;
/**
* Verifies a ReqNodeFuncList message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a ReqNodeFuncList message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ReqNodeFuncList
*/
public static fromObject(object: { [k: string]: any }): protoManage.ReqNodeFuncList;
/**
* Creates a plain object from a ReqNodeFuncList message. Also converts values to other types if specified.
* @param message ReqNodeFuncList
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: protoManage.ReqNodeFuncList, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this ReqNodeFuncList to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of an AnsNodeFuncList. */
interface IAnsNodeFuncList {
/** AnsNodeFuncList Length */
Length?: (number|null);
/** AnsNodeFuncList NodeFuncList */
NodeFuncList?: (protoManage.INodeFunc[]|null);
/** AnsNodeFuncList NodeList */
NodeList?: (protoManage.INode[]|null);
}
/** Represents an AnsNodeFuncList. */
class AnsNodeFuncList implements IAnsNodeFuncList {
/**
* Constructs a new AnsNodeFuncList.
* @param [properties] Properties to set
*/
constructor(properties?: protoManage.IAnsNodeFuncList);
/** AnsNodeFuncList Length. */
public Length: number;
/** AnsNodeFuncList NodeFuncList. */
public NodeFuncList: protoManage.INodeFunc[];
/** AnsNodeFuncList NodeList. */
public NodeList: protoManage.INode[];
/**
* Creates a new AnsNodeFuncList instance using the specified properties.
* @param [properties] Properties to set
* @returns AnsNodeFuncList instance
*/
public static create(properties?: protoManage.IAnsNodeFuncList): protoManage.AnsNodeFuncList;
/**
* Encodes the specified AnsNodeFuncList message. Does not implicitly {@link protoManage.AnsNodeFuncList.verify|verify} messages.
* @param message AnsNodeFuncList message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: protoManage.IAnsNodeFuncList, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified AnsNodeFuncList message, length delimited. Does not implicitly {@link protoManage.AnsNodeFuncList.verify|verify} messages.
* @param message AnsNodeFuncList message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: protoManage.IAnsNodeFuncList, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes an AnsNodeFuncList message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns AnsNodeFuncList
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): protoManage.AnsNodeFuncList;
/**
* Decodes an AnsNodeFuncList message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns AnsNodeFuncList
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): protoManage.AnsNodeFuncList;
/**
* Verifies an AnsNodeFuncList message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates an AnsNodeFuncList message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns AnsNodeFuncList
*/
public static fromObject(object: { [k: string]: any }): protoManage.AnsNodeFuncList;
/**
* Creates a plain object from an AnsNodeFuncList message. Also converts values to other types if specified.
* @param message AnsNodeFuncList
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: protoManage.AnsNodeFuncList, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this AnsNodeFuncList to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a ReqNodeReportList. */
interface IReqNodeReportList {
/** ReqNodeReportList ID */
ID?: (number[]|null);
/** ReqNodeReportList Name */
Name?: (string[]|null);
/** ReqNodeReportList Level */
Level?: (protoManage.Level[]|null);
/** ReqNodeReportList LevelMax */
LevelMax?: (protoManage.Level|null);
/** ReqNodeReportList NodeID */
NodeID?: (number[]|null);
/** ReqNodeReportList NodeName */
NodeName?: (string[]|null);
/** ReqNodeReportList UpdateTime */
UpdateTime?: (protoManage.ITime[]|null);
/** ReqNodeReportList Page */
Page?: (protoManage.IPage|null);
}
/** Represents a ReqNodeReportList. */
class ReqNodeReportList implements IReqNodeReportList {
/**
* Constructs a new ReqNodeReportList.
* @param [properties] Properties to set
*/
constructor(properties?: protoManage.IReqNodeReportList);
/** ReqNodeReportList ID. */
public ID: number[];
/** ReqNodeReportList Name. */
public Name: string[];
/** ReqNodeReportList Level. */
public Level: protoManage.Level[];
/** ReqNodeReportList LevelMax. */
public LevelMax: protoManage.Level;
/** ReqNodeReportList NodeID. */
public NodeID: number[];
/** ReqNodeReportList NodeName. */
public NodeName: string[];
/** ReqNodeReportList UpdateTime. */
public UpdateTime: protoManage.ITime[];
/** ReqNodeReportList Page. */
public Page?: (protoManage.IPage|null);
/**
* Creates a new ReqNodeReportList instance using the specified properties.
* @param [properties] Properties to set
* @returns ReqNodeReportList instance
*/
public static create(properties?: protoManage.IReqNodeReportList): protoManage.ReqNodeReportList;
/**
* Encodes the specified ReqNodeReportList message. Does not implicitly {@link protoManage.ReqNodeReportList.verify|verify} messages.
* @param message ReqNodeReportList message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: protoManage.IReqNodeReportList, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ReqNodeReportList message, length delimited. Does not implicitly {@link protoManage.ReqNodeReportList.verify|verify} messages.
* @param message ReqNodeReportList message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: protoManage.IReqNodeReportList, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ReqNodeReportList message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ReqNodeReportList
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): protoManage.ReqNodeReportList;
/**
* Decodes a ReqNodeReportList message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ReqNodeReportList
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): protoManage.ReqNodeReportList;
/**
* Verifies a ReqNodeReportList message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a ReqNodeReportList message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ReqNodeReportList
*/
public static fromObject(object: { [k: string]: any }): protoManage.ReqNodeReportList;
/**
* Creates a plain object from a ReqNodeReportList message. Also converts values to other types if specified.
* @param message ReqNodeReportList
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: protoManage.ReqNodeReportList, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this ReqNodeReportList to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of an AnsNodeReportList. */
interface IAnsNodeReportList {
/** AnsNodeReportList Length */
Length?: (number|null);
/** AnsNodeReportList NodeReportList */
NodeReportList?: (protoManage.INodeReport[]|null);
/** AnsNodeReportList NodeList */
NodeList?: (protoManage.INode[]|null);
}
/** Represents an AnsNodeReportList. */
class AnsNodeReportList implements IAnsNodeReportList {
/**
* Constructs a new AnsNodeReportList.
* @param [properties] Properties to set
*/
constructor(properties?: protoManage.IAnsNodeReportList);
/** AnsNodeReportList Length. */
public Length: number;
/** AnsNodeReportList NodeReportList. */
public NodeReportList: protoManage.INodeReport[];
/** AnsNodeReportList NodeList. */
public NodeList: protoManage.INode[];
/**
* Creates a new AnsNodeReportList instance using the specified properties.
* @param [properties] Properties to set
* @returns AnsNodeReportList instance
*/
public static create(properties?: protoManage.IAnsNodeReportList): protoManage.AnsNodeReportList;
/**
* Encodes the specified AnsNodeReportList message. Does not implicitly {@link protoManage.AnsNodeReportList.verify|verify} messages.
* @param message AnsNodeReportList message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: protoManage.IAnsNodeReportList, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified AnsNodeReportList message, length delimited. Does not implicitly {@link protoManage.AnsNodeReportList.verify|verify} messages.
* @param message AnsNodeReportList message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: protoManage.IAnsNodeReportList, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes an AnsNodeReportList message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns AnsNodeReportList
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): protoManage.AnsNodeReportList;
/**
* Decodes an AnsNodeReportList message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns AnsNodeReportList
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): protoManage.AnsNodeReportList;
/**
* Verifies an AnsNodeReportList message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates an AnsNodeReportList message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns AnsNodeReportList
*/
public static fromObject(object: { [k: string]: any }): protoManage.AnsNodeReportList;
/**
* Creates a plain object from an AnsNodeReportList message. Also converts values to other types if specified.
* @param message AnsNodeReportList
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: protoManage.AnsNodeReportList, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this AnsNodeReportList to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a ReqNodeFuncCall. */
interface IReqNodeFuncCall {
/** ReqNodeFuncCall NodeFuncCall */
NodeFuncCall?: (protoManage.INodeFuncCall|null);
}
/** Represents a ReqNodeFuncCall. */
class ReqNodeFuncCall implements IReqNodeFuncCall {
/**
* Constructs a new ReqNodeFuncCall.
* @param [properties] Properties to set
*/
constructor(properties?: protoManage.IReqNodeFuncCall);
/** ReqNodeFuncCall NodeFuncCall. */
public NodeFuncCall?: (protoManage.INodeFuncCall|null);
/**
* Creates a new ReqNodeFuncCall instance using the specified properties.
* @param [properties] Properties to set
* @returns ReqNodeFuncCall instance
*/
public static create(properties?: protoManage.IReqNodeFuncCall): protoManage.ReqNodeFuncCall;
/**
* Encodes the specified ReqNodeFuncCall message. Does not implicitly {@link protoManage.ReqNodeFuncCall.verify|verify} messages.
* @param message ReqNodeFuncCall message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: protoManage.IReqNodeFuncCall, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ReqNodeFuncCall message, length delimited. Does not implicitly {@link protoManage.ReqNodeFuncCall.verify|verify} messages.
* @param message ReqNodeFuncCall message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: protoManage.IReqNodeFuncCall, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ReqNodeFuncCall message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ReqNodeFuncCall
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): protoManage.ReqNodeFuncCall;
/**
* Decodes a ReqNodeFuncCall message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ReqNodeFuncCall
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): protoManage.ReqNodeFuncCall;
/**
* Verifies a ReqNodeFuncCall message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a ReqNodeFuncCall message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ReqNodeFuncCall
*/
public static fromObject(object: { [k: string]: any }): protoManage.ReqNodeFuncCall;
/**
* Creates a plain object from a ReqNodeFuncCall message. Also converts values to other types if specified.
* @param message ReqNodeFuncCall
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: protoManage.ReqNodeFuncCall, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this ReqNodeFuncCall to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of an AnsNodeFuncCall. */
interface IAnsNodeFuncCall {
/** AnsNodeFuncCall NodeFuncCall */
NodeFuncCall?: (protoManage.INodeFuncCall|null);
/** AnsNodeFuncCall Error */
Error?: (string|null);
}
/** Represents an AnsNodeFuncCall. */
class AnsNodeFuncCall implements IAnsNodeFuncCall {
/**
* Constructs a new AnsNodeFuncCall.
* @param [properties] Properties to set
*/
constructor(properties?: protoManage.IAnsNodeFuncCall);
/** AnsNodeFuncCall NodeFuncCall. */
public NodeFuncCall?: (protoManage.INodeFuncCall|null);
/** AnsNodeFuncCall Error. */
public Error: string;
/**
* Creates a new AnsNodeFuncCall instance using the specified properties.
* @param [properties] Properties to set
* @returns AnsNodeFuncCall instance
*/
public static create(properties?: protoManage.IAnsNodeFuncCall): protoManage.AnsNodeFuncCall;
/**
* Encodes the specified AnsNodeFuncCall message. Does not implicitly {@link protoManage.AnsNodeFuncCall.verify|verify} messages.
* @param message AnsNodeFuncCall message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: protoManage.IAnsNodeFuncCall, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified AnsNodeFuncCall message, length delimited. Does not implicitly {@link protoManage.AnsNodeFuncCall.verify|verify} messages.
* @param message AnsNodeFuncCall message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: protoManage.IAnsNodeFuncCall, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes an AnsNodeFuncCall message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns AnsNodeFuncCall
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): protoManage.AnsNodeFuncCall;
/**
* Decodes an AnsNodeFuncCall message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns AnsNodeFuncCall
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): protoManage.AnsNodeFuncCall;
/**
* Verifies an AnsNodeFuncCall message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates an AnsNodeFuncCall message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns AnsNodeFuncCall
*/
public static fromObject(object: { [k: string]: any }): protoManage.AnsNodeFuncCall;
/**
* Creates a plain object from an AnsNodeFuncCall message. Also converts values to other types if specified.
* @param message AnsNodeFuncCall
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: protoManage.AnsNodeFuncCall, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this AnsNodeFuncCall to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a ReqNodeFuncCallList. */
interface IReqNodeFuncCallList {
/** ReqNodeFuncCallList FuncID */
FuncID?: (number|null);
/** ReqNodeFuncCallList Page */
Page?: (protoManage.IPage|null);
}
/** Represents a ReqNodeFuncCallList. */
class ReqNodeFuncCallList implements IReqNodeFuncCallList {
/**
* Constructs a new ReqNodeFuncCallList.
* @param [properties] Properties to set
*/
constructor(properties?: protoManage.IReqNodeFuncCallList);
/** ReqNodeFuncCallList FuncID. */
public FuncID: number;
/** ReqNodeFuncCallList Page. */
public Page?: (protoManage.IPage|null);
/**
* Creates a new ReqNodeFuncCallList instance using the specified properties.
* @param [properties] Properties to set
* @returns ReqNodeFuncCallList instance
*/
public static create(properties?: protoManage.IReqNodeFuncCallList): protoManage.ReqNodeFuncCallList;
/**
* Encodes the specified ReqNodeFuncCallList message. Does not implicitly {@link protoManage.ReqNodeFuncCallList.verify|verify} messages.
* @param message ReqNodeFuncCallList message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: protoManage.IReqNodeFuncCallList, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ReqNodeFuncCallList message, length delimited. Does not implicitly {@link protoManage.ReqNodeFuncCallList.verify|verify} messages.
* @param message ReqNodeFuncCallList message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: protoManage.IReqNodeFuncCallList, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ReqNodeFuncCallList message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ReqNodeFuncCallList
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): protoManage.ReqNodeFuncCallList;
/**
* Decodes a ReqNodeFuncCallList message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ReqNodeFuncCallList
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): protoManage.ReqNodeFuncCallList;
/**
* Verifies a ReqNodeFuncCallList message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a ReqNodeFuncCallList message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ReqNodeFuncCallList
*/
public static fromObject(object: { [k: string]: any }): protoManage.ReqNodeFuncCallList;
/**
* Creates a plain object from a ReqNodeFuncCallList message. Also converts values to other types if specified.
* @param message ReqNodeFuncCallList
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: protoManage.ReqNodeFuncCallList, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this ReqNodeFuncCallList to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of an AnsNodeFuncCallList. */
interface IAnsNodeFuncCallList {
/** AnsNodeFuncCallList NodeFuncCallList */
NodeFuncCallList?: (protoManage.INodeFuncCall[]|null);
}
/** Represents an AnsNodeFuncCallList. */
class AnsNodeFuncCallList implements IAnsNodeFuncCallList {
/**
* Constructs a new AnsNodeFuncCallList.
* @param [properties] Properties to set
*/
constructor(properties?: protoManage.IAnsNodeFuncCallList);
/** AnsNodeFuncCallList NodeFuncCallList. */
public NodeFuncCallList: protoManage.INodeFuncCall[];
/**
* Creates a new AnsNodeFuncCallList instance using the specified properties.
* @param [properties] Properties to set
* @returns AnsNodeFuncCallList instance
*/
public static create(properties?: protoManage.IAnsNodeFuncCallList): protoManage.AnsNodeFuncCallList;
/**
* Encodes the specified AnsNodeFuncCallList message. Does not implicitly {@link protoManage.AnsNodeFuncCallList.verify|verify} messages.
* @param message AnsNodeFuncCallList message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: protoManage.IAnsNodeFuncCallList, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified AnsNodeFuncCallList message, length delimited. Does not implicitly {@link protoManage.AnsNodeFuncCallList.verify|verify} messages.
* @param message AnsNodeFuncCallList message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: protoManage.IAnsNodeFuncCallList, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes an AnsNodeFuncCallList message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns AnsNodeFuncCallList
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): protoManage.AnsNodeFuncCallList;
/**
* Decodes an AnsNodeFuncCallList message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns AnsNodeFuncCallList
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): protoManage.AnsNodeFuncCallList;
/**
* Verifies an AnsNodeFuncCallList message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates an AnsNodeFuncCallList message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns AnsNodeFuncCallList
*/
public static fromObject(object: { [k: string]: any }): protoManage.AnsNodeFuncCallList;
/**
* Creates a plain object from an AnsNodeFuncCallList message. Also converts values to other types if specified.
* @param message AnsNodeFuncCallList
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: protoManage.AnsNodeFuncCallList, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this AnsNodeFuncCallList to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a ReqNodeReportValList. */
interface IReqNodeReportValList {
/** ReqNodeReportValList ID */
ID?: (number|null);
/** ReqNodeReportValList ReportID */
ReportID?: (number|null);
/** ReqNodeReportValList Page */
Page?: (protoManage.IPage|null);
}
/** Represents a ReqNodeReportValList. */
class ReqNodeReportValList implements IReqNodeReportValList {
/**
* Constructs a new ReqNodeReportValList.
* @param [properties] Properties to set
*/
constructor(properties?: protoManage.IReqNodeReportValList);
/** ReqNodeReportValList ID. */
public ID: number;
/** ReqNodeReportValList ReportID. */
public ReportID: number;
/** ReqNodeReportValList Page. */
public Page?: (protoManage.IPage|null);
/**
* Creates a new ReqNodeReportValList instance using the specified properties.
* @param [properties] Properties to set
* @returns ReqNodeReportValList instance
*/
public static create(properties?: protoManage.IReqNodeReportValList): protoManage.ReqNodeReportValList;
/**
* Encodes the specified ReqNodeReportValList message. Does not implicitly {@link protoManage.ReqNodeReportValList.verify|verify} messages.
* @param message ReqNodeReportValList message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: protoManage.IReqNodeReportValList, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ReqNodeReportValList message, length delimited. Does not implicitly {@link protoManage.ReqNodeReportValList.verify|verify} messages.
* @param message ReqNodeReportValList message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: protoManage.IReqNodeReportValList, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ReqNodeReportValList message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ReqNodeReportValList
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): protoManage.ReqNodeReportValList;
/**
* Decodes a ReqNodeReportValList message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ReqNodeReportValList
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): protoManage.ReqNodeReportValList;
/**
* Verifies a ReqNodeReportValList message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a ReqNodeReportValList message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ReqNodeReportValList
*/
public static fromObject(object: { [k: string]: any }): protoManage.ReqNodeReportValList;
/**
* Creates a plain object from a ReqNodeReportValList message. Also converts values to other types if specified.
* @param message ReqNodeReportValList
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: protoManage.ReqNodeReportValList, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this ReqNodeReportValList to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of an AnsNodeReportValList. */
interface IAnsNodeReportValList {
/** AnsNodeReportValList NodeReportValList */
NodeReportValList?: (protoManage.INodeReportVal[]|null);
}
/** Represents an AnsNodeReportValList. */
class AnsNodeReportValList implements IAnsNodeReportValList {
/**
* Constructs a new AnsNodeReportValList.
* @param [properties] Properties to set
*/
constructor(properties?: protoManage.IAnsNodeReportValList);
/** AnsNodeReportValList NodeReportValList. */
public NodeReportValList: protoManage.INodeReportVal[];
/**
* Creates a new AnsNodeReportValList instance using the specified properties.
* @param [properties] Properties to set
* @returns AnsNodeReportValList instance
*/
public static create(properties?: protoManage.IAnsNodeReportValList): protoManage.AnsNodeReportValList;
/**
* Encodes the specified AnsNodeReportValList message. Does not implicitly {@link protoManage.AnsNodeReportValList.verify|verify} messages.
* @param message AnsNodeReportValList message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: protoManage.IAnsNodeReportValList, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified AnsNodeReportValList message, length delimited. Does not implicitly {@link protoManage.AnsNodeReportValList.verify|verify} messages.
* @param message AnsNodeReportValList message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: protoManage.IAnsNodeReportValList, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes an AnsNodeReportValList message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns AnsNodeReportValList
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): protoManage.AnsNodeReportValList;
/**
* Decodes an AnsNodeReportValList message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns AnsNodeReportValList
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): protoManage.AnsNodeReportValList;
/**
* Verifies an AnsNodeReportValList message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates an AnsNodeReportValList message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns AnsNodeReportValList
*/
public static fromObject(object: { [k: string]: any }): protoManage.AnsNodeReportValList;
/**
* Creates a plain object from an AnsNodeReportValList message. Also converts values to other types if specified.
* @param message AnsNodeReportValList
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: protoManage.AnsNodeReportValList, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this AnsNodeReportValList to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a ReqNodeNotifyList. */
interface IReqNodeNotifyList {
/** ReqNodeNotifyList Message */
Message?: (string[]|null);
/** ReqNodeNotifyList State */
State?: (protoManage.State[]|null);
/** ReqNodeNotifyList SenderName */
SenderName?: (string[]|null);
/** ReqNodeNotifyList SenderType */
SenderType?: (protoManage.NotifySenderType[]|null);
/** ReqNodeNotifyList SenderTime */
SenderTime?: (protoManage.ITime[]|null);
/** ReqNodeNotifyList Page */
Page?: (protoManage.IPage|null);
}
/** Represents a ReqNodeNotifyList. */
class ReqNodeNotifyList implements IReqNodeNotifyList {
/**
* Constructs a new ReqNodeNotifyList.
* @param [properties] Properties to set
*/
constructor(properties?: protoManage.IReqNodeNotifyList);
/** ReqNodeNotifyList Message. */
public Message: string[];
/** ReqNodeNotifyList State. */
public State: protoManage.State[];
/** ReqNodeNotifyList SenderName. */
public SenderName: string[];
/** ReqNodeNotifyList SenderType. */
public SenderType: protoManage.NotifySenderType[];
/** ReqNodeNotifyList SenderTime. */
public SenderTime: protoManage.ITime[];
/** ReqNodeNotifyList Page. */
public Page?: (protoManage.IPage|null);
/**
* Creates a new ReqNodeNotifyList instance using the specified properties.
* @param [properties] Properties to set
* @returns ReqNodeNotifyList instance
*/
public static create(properties?: protoManage.IReqNodeNotifyList): protoManage.ReqNodeNotifyList;
/**
* Encodes the specified ReqNodeNotifyList message. Does not implicitly {@link protoManage.ReqNodeNotifyList.verify|verify} messages.
* @param message ReqNodeNotifyList message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: protoManage.IReqNodeNotifyList, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ReqNodeNotifyList message, length delimited. Does not implicitly {@link protoManage.ReqNodeNotifyList.verify|verify} messages.
* @param message ReqNodeNotifyList message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: protoManage.IReqNodeNotifyList, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ReqNodeNotifyList message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ReqNodeNotifyList
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): protoManage.ReqNodeNotifyList;
/**
* Decodes a ReqNodeNotifyList message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ReqNodeNotifyList
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): protoManage.ReqNodeNotifyList;
/**
* Verifies a ReqNodeNotifyList message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a ReqNodeNotifyList message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ReqNodeNotifyList
*/
public static fromObject(object: { [k: string]: any }): protoManage.ReqNodeNotifyList;
/**
* Creates a plain object from a ReqNodeNotifyList message. Also converts values to other types if specified.
* @param message ReqNodeNotifyList
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: protoManage.ReqNodeNotifyList, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this ReqNodeNotifyList to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of an AnsNodeNotifyList. */
interface IAnsNodeNotifyList {
/** AnsNodeNotifyList Length */
Length?: (number|null);
/** AnsNodeNotifyList NodeNotifyList */
NodeNotifyList?: (protoManage.INodeNotify[]|null);
}
/** Represents an AnsNodeNotifyList. */
class AnsNodeNotifyList implements IAnsNodeNotifyList {
/**
* Constructs a new AnsNodeNotifyList.
* @param [properties] Properties to set
*/
constructor(properties?: protoManage.IAnsNodeNotifyList);
/** AnsNodeNotifyList Length. */
public Length: number;
/** AnsNodeNotifyList NodeNotifyList. */
public NodeNotifyList: protoManage.INodeNotify[];
/**
* Creates a new AnsNodeNotifyList instance using the specified properties.
* @param [properties] Properties to set
* @returns AnsNodeNotifyList instance
*/
public static create(properties?: protoManage.IAnsNodeNotifyList): protoManage.AnsNodeNotifyList;
/**
* Encodes the specified AnsNodeNotifyList message. Does not implicitly {@link protoManage.AnsNodeNotifyList.verify|verify} messages.
* @param message AnsNodeNotifyList message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: protoManage.IAnsNodeNotifyList, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified AnsNodeNotifyList message, length delimited. Does not implicitly {@link protoManage.AnsNodeNotifyList.verify|verify} messages.
* @param message AnsNodeNotifyList message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: protoManage.IAnsNodeNotifyList, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes an AnsNodeNotifyList message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns AnsNodeNotifyList
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): protoManage.AnsNodeNotifyList;
/**
* Decodes an AnsNodeNotifyList message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns AnsNodeNotifyList
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): protoManage.AnsNodeNotifyList;
/**
* Verifies an AnsNodeNotifyList message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates an AnsNodeNotifyList message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns AnsNodeNotifyList
*/
public static fromObject(object: { [k: string]: any }): protoManage.AnsNodeNotifyList;
/**
* Creates a plain object from an AnsNodeNotifyList message. Also converts values to other types if specified.
* @param message AnsNodeNotifyList
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: protoManage.AnsNodeNotifyList, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this AnsNodeNotifyList to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a ReqNodeResourceList. */
interface IReqNodeResourceList {
/** ReqNodeResourceList Name */
Name?: (string[]|null);
/** ReqNodeResourceList State */
State?: (protoManage.State[]|null);
/** ReqNodeResourceList UploaderName */
UploaderName?: (string[]|null);
/** ReqNodeResourceList UploaderType */
UploaderType?: (protoManage.NotifySenderType[]|null);
/** ReqNodeResourceList UploadTime */
UploadTime?: (protoManage.ITime[]|null);
/** ReqNodeResourceList Page */
Page?: (protoManage.IPage|null);
}
/** Represents a ReqNodeResourceList. */
class ReqNodeResourceList implements IReqNodeResourceList {
/**
* Constructs a new ReqNodeResourceList.
* @param [properties] Properties to set
*/
constructor(properties?: protoManage.IReqNodeResourceList);
/** ReqNodeResourceList Name. */
public Name: string[];
/** ReqNodeResourceList State. */
public State: protoManage.State[];
/** ReqNodeResourceList UploaderName. */
public UploaderName: string[];
/** ReqNodeResourceList UploaderType. */
public UploaderType: protoManage.NotifySenderType[];
/** ReqNodeResourceList UploadTime. */
public UploadTime: protoManage.ITime[];
/** ReqNodeResourceList Page. */
public Page?: (protoManage.IPage|null);
/**
* Creates a new ReqNodeResourceList instance using the specified properties.
* @param [properties] Properties to set
* @returns ReqNodeResourceList instance
*/
public static create(properties?: protoManage.IReqNodeResourceList): protoManage.ReqNodeResourceList;
/**
* Encodes the specified ReqNodeResourceList message. Does not implicitly {@link protoManage.ReqNodeResourceList.verify|verify} messages.
* @param message ReqNodeResourceList message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: protoManage.IReqNodeResourceList, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ReqNodeResourceList message, length delimited. Does not implicitly {@link protoManage.ReqNodeResourceList.verify|verify} messages.
* @param message ReqNodeResourceList message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: protoManage.IReqNodeResourceList, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ReqNodeResourceList message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ReqNodeResourceList
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): protoManage.ReqNodeResourceList;
/**
* Decodes a ReqNodeResourceList message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ReqNodeResourceList
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): protoManage.ReqNodeResourceList;
/**
* Verifies a ReqNodeResourceList message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a ReqNodeResourceList message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ReqNodeResourceList
*/
public static fromObject(object: { [k: string]: any }): protoManage.ReqNodeResourceList;
/**
* Creates a plain object from a ReqNodeResourceList message. Also converts values to other types if specified.
* @param message ReqNodeResourceList
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: protoManage.ReqNodeResourceList, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this ReqNodeResourceList to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of an AnsNodeResourceList. */
interface IAnsNodeResourceList {
/** AnsNodeResourceList Length */
Length?: (number|null);
/** AnsNodeResourceList NodeResourceList */
NodeResourceList?: (protoManage.INodeResource[]|null);
}
/** Represents an AnsNodeResourceList. */
class AnsNodeResourceList implements IAnsNodeResourceList {
/**
* Constructs a new AnsNodeResourceList.
* @param [properties] Properties to set
*/
constructor(properties?: protoManage.IAnsNodeResourceList);
/** AnsNodeResourceList Length. */
public Length: number;
/** AnsNodeResourceList NodeResourceList. */
public NodeResourceList: protoManage.INodeResource[];
/**
* Creates a new AnsNodeResourceList instance using the specified properties.
* @param [properties] Properties to set
* @returns AnsNodeResourceList instance
*/
public static create(properties?: protoManage.IAnsNodeResourceList): protoManage.AnsNodeResourceList;
/**
* Encodes the specified AnsNodeResourceList message. Does not implicitly {@link protoManage.AnsNodeResourceList.verify|verify} messages.
* @param message AnsNodeResourceList message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: protoManage.IAnsNodeResourceList, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified AnsNodeResourceList message, length delimited. Does not implicitly {@link protoManage.AnsNodeResourceList.verify|verify} messages.
* @param message AnsNodeResourceList message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: protoManage.IAnsNodeResourceList, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes an AnsNodeResourceList message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns AnsNodeResourceList
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): protoManage.AnsNodeResourceList;
/**
* Decodes an AnsNodeResourceList message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns AnsNodeResourceList
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): protoManage.AnsNodeResourceList;
/**
* Verifies an AnsNodeResourceList message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates an AnsNodeResourceList message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns AnsNodeResourceList
*/
public static fromObject(object: { [k: string]: any }): protoManage.AnsNodeResourceList;
/**
* Creates a plain object from an AnsNodeResourceList message. Also converts values to other types if specified.
* @param message AnsNodeResourceList
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: protoManage.AnsNodeResourceList, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this AnsNodeResourceList to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a ReqNodeResourceUpload. */
interface IReqNodeResourceUpload {
/** ReqNodeResourceUpload Data */
Data?: (Uint8Array|null);
}
/** Represents a ReqNodeResourceUpload. */
class ReqNodeResourceUpload implements IReqNodeResourceUpload {
/**
* Constructs a new ReqNodeResourceUpload.
* @param [properties] Properties to set
*/
constructor(properties?: protoManage.IReqNodeResourceUpload);
/** ReqNodeResourceUpload Data. */
public Data: Uint8Array;
/**
* Creates a new ReqNodeResourceUpload instance using the specified properties.
* @param [properties] Properties to set
* @returns ReqNodeResourceUpload instance
*/
public static create(properties?: protoManage.IReqNodeResourceUpload): protoManage.ReqNodeResourceUpload;
/**
* Encodes the specified ReqNodeResourceUpload message. Does not implicitly {@link protoManage.ReqNodeResourceUpload.verify|verify} messages.
* @param message ReqNodeResourceUpload message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: protoManage.IReqNodeResourceUpload, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ReqNodeResourceUpload message, length delimited. Does not implicitly {@link protoManage.ReqNodeResourceUpload.verify|verify} messages.
* @param message ReqNodeResourceUpload message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: protoManage.IReqNodeResourceUpload, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ReqNodeResourceUpload message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ReqNodeResourceUpload
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): protoManage.ReqNodeResourceUpload;
/**
* Decodes a ReqNodeResourceUpload message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ReqNodeResourceUpload
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): protoManage.ReqNodeResourceUpload;
/**
* Verifies a ReqNodeResourceUpload message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a ReqNodeResourceUpload message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ReqNodeResourceUpload
*/
public static fromObject(object: { [k: string]: any }): protoManage.ReqNodeResourceUpload;
/**
* Creates a plain object from a ReqNodeResourceUpload message. Also converts values to other types if specified.
* @param message ReqNodeResourceUpload
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: protoManage.ReqNodeResourceUpload, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this ReqNodeResourceUpload to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of an AnsNodeResourceUpload. */
interface IAnsNodeResourceUpload {
/** AnsNodeResourceUpload NodeResource */
NodeResource?: (protoManage.INodeResource|null);
}
/** Represents an AnsNodeResourceUpload. */
class AnsNodeResourceUpload implements IAnsNodeResourceUpload {
/**
* Constructs a new AnsNodeResourceUpload.
* @param [properties] Properties to set
*/
constructor(properties?: protoManage.IAnsNodeResourceUpload);
/** AnsNodeResourceUpload NodeResource. */
public NodeResource?: (protoManage.INodeResource|null);
/**
* Creates a new AnsNodeResourceUpload instance using the specified properties.
* @param [properties] Properties to set
* @returns AnsNodeResourceUpload instance
*/
public static create(properties?: protoManage.IAnsNodeResourceUpload): protoManage.AnsNodeResourceUpload;
/**
* Encodes the specified AnsNodeResourceUpload message. Does not implicitly {@link protoManage.AnsNodeResourceUpload.verify|verify} messages.
* @param message AnsNodeResourceUpload message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: protoManage.IAnsNodeResourceUpload, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified AnsNodeResourceUpload message, length delimited. Does not implicitly {@link protoManage.AnsNodeResourceUpload.verify|verify} messages.
* @param message AnsNodeResourceUpload message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: protoManage.IAnsNodeResourceUpload, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes an AnsNodeResourceUpload message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns AnsNodeResourceUpload
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): protoManage.AnsNodeResourceUpload;
/**
* Decodes an AnsNodeResourceUpload message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns AnsNodeResourceUpload
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): protoManage.AnsNodeResourceUpload;
/**
* Verifies an AnsNodeResourceUpload message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates an AnsNodeResourceUpload message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns AnsNodeResourceUpload
*/
public static fromObject(object: { [k: string]: any }): protoManage.AnsNodeResourceUpload;
/**
* Creates a plain object from an AnsNodeResourceUpload message. Also converts values to other types if specified.
* @param message AnsNodeResourceUpload
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: protoManage.AnsNodeResourceUpload, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this AnsNodeResourceUpload to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a ReqNodeResourceDownload. */
interface IReqNodeResourceDownload {
/** ReqNodeResourceDownload NodeResource */
NodeResource?: (protoManage.INodeResource|null);
}
/** Represents a ReqNodeResourceDownload. */
class ReqNodeResourceDownload implements IReqNodeResourceDownload {
/**
* Constructs a new ReqNodeResourceDownload.
* @param [properties] Properties to set
*/
constructor(properties?: protoManage.IReqNodeResourceDownload);
/** ReqNodeResourceDownload NodeResource. */
public NodeResource?: (protoManage.INodeResource|null);
/**
* Creates a new ReqNodeResourceDownload instance using the specified properties.
* @param [properties] Properties to set
* @returns ReqNodeResourceDownload instance
*/
public static create(properties?: protoManage.IReqNodeResourceDownload): protoManage.ReqNodeResourceDownload;
/**
* Encodes the specified ReqNodeResourceDownload message. Does not implicitly {@link protoManage.ReqNodeResourceDownload.verify|verify} messages.
* @param message ReqNodeResourceDownload message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: protoManage.IReqNodeResourceDownload, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ReqNodeResourceDownload message, length delimited. Does not implicitly {@link protoManage.ReqNodeResourceDownload.verify|verify} messages.
* @param message ReqNodeResourceDownload message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: protoManage.IReqNodeResourceDownload, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ReqNodeResourceDownload message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ReqNodeResourceDownload
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): protoManage.ReqNodeResourceDownload;
/**
* Decodes a ReqNodeResourceDownload message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ReqNodeResourceDownload
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): protoManage.ReqNodeResourceDownload;
/**
* Verifies a ReqNodeResourceDownload message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a ReqNodeResourceDownload message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ReqNodeResourceDownload
*/
public static fromObject(object: { [k: string]: any }): protoManage.ReqNodeResourceDownload;
/**
* Creates a plain object from a ReqNodeResourceDownload message. Also converts values to other types if specified.
* @param message ReqNodeResourceDownload
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: protoManage.ReqNodeResourceDownload, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this ReqNodeResourceDownload to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of an AnsNodeResourceDownload. */
interface IAnsNodeResourceDownload {
/** AnsNodeResourceDownload Data */
Data?: (Uint8Array|null);
}
/** Represents an AnsNodeResourceDownload. */
class AnsNodeResourceDownload implements IAnsNodeResourceDownload {
/**
* Constructs a new AnsNodeResourceDownload.
* @param [properties] Properties to set
*/
constructor(properties?: protoManage.IAnsNodeResourceDownload);
/** AnsNodeResourceDownload Data. */
public Data: Uint8Array;
/**
* Creates a new AnsNodeResourceDownload instance using the specified properties.
* @param [properties] Properties to set
* @returns AnsNodeResourceDownload instance
*/
public static create(properties?: protoManage.IAnsNodeResourceDownload): protoManage.AnsNodeResourceDownload;
/**
* Encodes the specified AnsNodeResourceDownload message. Does not implicitly {@link protoManage.AnsNodeResourceDownload.verify|verify} messages.
* @param message AnsNodeResourceDownload message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: protoManage.IAnsNodeResourceDownload, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified AnsNodeResourceDownload message, length delimited. Does not implicitly {@link protoManage.AnsNodeResourceDownload.verify|verify} messages.
* @param message AnsNodeResourceDownload message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: protoManage.IAnsNodeResourceDownload, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes an AnsNodeResourceDownload message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns AnsNodeResourceDownload
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): protoManage.AnsNodeResourceDownload;
/**
* Decodes an AnsNodeResourceDownload message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns AnsNodeResourceDownload
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): protoManage.AnsNodeResourceDownload;
/**
* Verifies an AnsNodeResourceDownload message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates an AnsNodeResourceDownload message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns AnsNodeResourceDownload
*/
public static fromObject(object: { [k: string]: any }): protoManage.AnsNodeResourceDownload;
/**
* Creates a plain object from an AnsNodeResourceDownload message. Also converts values to other types if specified.
* @param message AnsNodeResourceDownload
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: protoManage.AnsNodeResourceDownload, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this AnsNodeResourceDownload to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of a ReqNodeTest. */
interface IReqNodeTest {
/** ReqNodeTest ID */
ID?: (number|null);
/** ReqNodeTest Type */
Type?: (number|null);
/** ReqNodeTest Message */
Message?: (string|null);
/** ReqNodeTest State */
State?: (protoManage.State|null);
}
/** Represents a ReqNodeTest. */
class ReqNodeTest implements IReqNodeTest {
/**
* Constructs a new ReqNodeTest.
* @param [properties] Properties to set
*/
constructor(properties?: protoManage.IReqNodeTest);
/** ReqNodeTest ID. */
public ID: number;
/** ReqNodeTest Type. */
public Type: number;
/** ReqNodeTest Message. */
public Message: string;
/** ReqNodeTest State. */
public State: protoManage.State;
/**
* Creates a new ReqNodeTest instance using the specified properties.
* @param [properties] Properties to set
* @returns ReqNodeTest instance
*/
public static create(properties?: protoManage.IReqNodeTest): protoManage.ReqNodeTest;
/**
* Encodes the specified ReqNodeTest message. Does not implicitly {@link protoManage.ReqNodeTest.verify|verify} messages.
* @param message ReqNodeTest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: protoManage.IReqNodeTest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified ReqNodeTest message, length delimited. Does not implicitly {@link protoManage.ReqNodeTest.verify|verify} messages.
* @param message ReqNodeTest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: protoManage.IReqNodeTest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes a ReqNodeTest message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns ReqNodeTest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): protoManage.ReqNodeTest;
/**
* Decodes a ReqNodeTest message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns ReqNodeTest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): protoManage.ReqNodeTest;
/**
* Verifies a ReqNodeTest message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates a ReqNodeTest message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns ReqNodeTest
*/
public static fromObject(object: { [k: string]: any }): protoManage.ReqNodeTest;
/**
* Creates a plain object from a ReqNodeTest message. Also converts values to other types if specified.
* @param message ReqNodeTest
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: protoManage.ReqNodeTest, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this ReqNodeTest to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
/** Properties of an AnsNodeTest. */
interface IAnsNodeTest {
}
/** Represents an AnsNodeTest. */
class AnsNodeTest implements IAnsNodeTest {
/**
* Constructs a new AnsNodeTest.
* @param [properties] Properties to set
*/
constructor(properties?: protoManage.IAnsNodeTest);
/**
* Creates a new AnsNodeTest instance using the specified properties.
* @param [properties] Properties to set
* @returns AnsNodeTest instance
*/
public static create(properties?: protoManage.IAnsNodeTest): protoManage.AnsNodeTest;
/**
* Encodes the specified AnsNodeTest message. Does not implicitly {@link protoManage.AnsNodeTest.verify|verify} messages.
* @param message AnsNodeTest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encode(message: protoManage.IAnsNodeTest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Encodes the specified AnsNodeTest message, length delimited. Does not implicitly {@link protoManage.AnsNodeTest.verify|verify} messages.
* @param message AnsNodeTest message or plain object to encode
* @param [writer] Writer to encode to
* @returns Writer
*/
public static encodeDelimited(message: protoManage.IAnsNodeTest, writer?: $protobuf.Writer): $protobuf.Writer;
/**
* Decodes an AnsNodeTest message from the specified reader or buffer.
* @param reader Reader or buffer to decode from
* @param [length] Message length if known beforehand
* @returns AnsNodeTest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): protoManage.AnsNodeTest;
/**
* Decodes an AnsNodeTest message from the specified reader or buffer, length delimited.
* @param reader Reader or buffer to decode from
* @returns AnsNodeTest
* @throws {Error} If the payload is not a reader or valid buffer
* @throws {$protobuf.util.ProtocolError} If required fields are missing
*/
public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): protoManage.AnsNodeTest;
/**
* Verifies an AnsNodeTest message.
* @param message Plain object to verify
* @returns `null` if valid, otherwise the reason why it is not
*/
public static verify(message: { [k: string]: any }): (string|null);
/**
* Creates an AnsNodeTest message from a plain object. Also converts values to their respective internal types.
* @param object Plain object
* @returns AnsNodeTest
*/
public static fromObject(object: { [k: string]: any }): protoManage.AnsNodeTest;
/**
* Creates a plain object from an AnsNodeTest message. Also converts values to other types if specified.
* @param message AnsNodeTest
* @param [options] Conversion options
* @returns Plain object
*/
public static toObject(message: protoManage.AnsNodeTest, options?: $protobuf.IConversionOptions): { [k: string]: any };
/**
* Converts this AnsNodeTest to JSON.
* @returns JSON object
*/
public toJSON(): { [k: string]: any };
}
} | the_stack |
import * as msRest from "@azure/ms-rest-js";
import * as Models from "../models";
import * as Mappers from "../models/webTestsMappers";
import * as Parameters from "../models/parameters";
import { ApplicationInsightsManagementClientContext } from "../applicationInsightsManagementClientContext";
/** Class representing a WebTests. */
export class WebTests {
private readonly client: ApplicationInsightsManagementClientContext;
/**
* Create a WebTests.
* @param {ApplicationInsightsManagementClientContext} client Reference to the service client.
*/
constructor(client: ApplicationInsightsManagementClientContext) {
this.client = client;
}
/**
* Get all Application Insights web tests defined within a specified resource group.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param [options] The optional parameters
* @returns Promise<Models.WebTestsListByResourceGroupResponse>
*/
listByResourceGroup(resourceGroupName: string, options?: msRest.RequestOptionsBase): Promise<Models.WebTestsListByResourceGroupResponse>;
/**
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param callback The callback
*/
listByResourceGroup(resourceGroupName: string, callback: msRest.ServiceCallback<Models.WebTestListResult>): void;
/**
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param options The optional parameters
* @param callback The callback
*/
listByResourceGroup(resourceGroupName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.WebTestListResult>): void;
listByResourceGroup(resourceGroupName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.WebTestListResult>, callback?: msRest.ServiceCallback<Models.WebTestListResult>): Promise<Models.WebTestsListByResourceGroupResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
options
},
listByResourceGroupOperationSpec,
callback) as Promise<Models.WebTestsListByResourceGroupResponse>;
}
/**
* Get a specific Application Insights web test definition.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param webTestName The name of the Application Insights webtest resource.
* @param [options] The optional parameters
* @returns Promise<Models.WebTestsGetResponse>
*/
get(resourceGroupName: string, webTestName: string, options?: msRest.RequestOptionsBase): Promise<Models.WebTestsGetResponse>;
/**
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param webTestName The name of the Application Insights webtest resource.
* @param callback The callback
*/
get(resourceGroupName: string, webTestName: string, callback: msRest.ServiceCallback<Models.WebTest>): void;
/**
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param webTestName The name of the Application Insights webtest resource.
* @param options The optional parameters
* @param callback The callback
*/
get(resourceGroupName: string, webTestName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.WebTest>): void;
get(resourceGroupName: string, webTestName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.WebTest>, callback?: msRest.ServiceCallback<Models.WebTest>): Promise<Models.WebTestsGetResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
webTestName,
options
},
getOperationSpec,
callback) as Promise<Models.WebTestsGetResponse>;
}
/**
* Creates or updates an Application Insights web test definition.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param webTestName The name of the Application Insights webtest resource.
* @param webTestDefinition Properties that need to be specified to create or update an Application
* Insights web test definition.
* @param [options] The optional parameters
* @returns Promise<Models.WebTestsCreateOrUpdateResponse>
*/
createOrUpdate(resourceGroupName: string, webTestName: string, webTestDefinition: Models.WebTest, options?: msRest.RequestOptionsBase): Promise<Models.WebTestsCreateOrUpdateResponse>;
/**
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param webTestName The name of the Application Insights webtest resource.
* @param webTestDefinition Properties that need to be specified to create or update an Application
* Insights web test definition.
* @param callback The callback
*/
createOrUpdate(resourceGroupName: string, webTestName: string, webTestDefinition: Models.WebTest, callback: msRest.ServiceCallback<Models.WebTest>): void;
/**
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param webTestName The name of the Application Insights webtest resource.
* @param webTestDefinition Properties that need to be specified to create or update an Application
* Insights web test definition.
* @param options The optional parameters
* @param callback The callback
*/
createOrUpdate(resourceGroupName: string, webTestName: string, webTestDefinition: Models.WebTest, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.WebTest>): void;
createOrUpdate(resourceGroupName: string, webTestName: string, webTestDefinition: Models.WebTest, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.WebTest>, callback?: msRest.ServiceCallback<Models.WebTest>): Promise<Models.WebTestsCreateOrUpdateResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
webTestName,
webTestDefinition,
options
},
createOrUpdateOperationSpec,
callback) as Promise<Models.WebTestsCreateOrUpdateResponse>;
}
/**
* Creates or updates an Application Insights web test definition.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param webTestName The name of the Application Insights webtest resource.
* @param webTestTags Updated tag information to set into the web test instance.
* @param [options] The optional parameters
* @returns Promise<Models.WebTestsUpdateTagsResponse>
*/
updateTags(resourceGroupName: string, webTestName: string, webTestTags: Models.TagsResource, options?: msRest.RequestOptionsBase): Promise<Models.WebTestsUpdateTagsResponse>;
/**
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param webTestName The name of the Application Insights webtest resource.
* @param webTestTags Updated tag information to set into the web test instance.
* @param callback The callback
*/
updateTags(resourceGroupName: string, webTestName: string, webTestTags: Models.TagsResource, callback: msRest.ServiceCallback<Models.WebTest>): void;
/**
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param webTestName The name of the Application Insights webtest resource.
* @param webTestTags Updated tag information to set into the web test instance.
* @param options The optional parameters
* @param callback The callback
*/
updateTags(resourceGroupName: string, webTestName: string, webTestTags: Models.TagsResource, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.WebTest>): void;
updateTags(resourceGroupName: string, webTestName: string, webTestTags: Models.TagsResource, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.WebTest>, callback?: msRest.ServiceCallback<Models.WebTest>): Promise<Models.WebTestsUpdateTagsResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
webTestName,
webTestTags,
options
},
updateTagsOperationSpec,
callback) as Promise<Models.WebTestsUpdateTagsResponse>;
}
/**
* Deletes an Application Insights web test.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param webTestName The name of the Application Insights webtest resource.
* @param [options] The optional parameters
* @returns Promise<msRest.RestResponse>
*/
deleteMethod(resourceGroupName: string, webTestName: string, options?: msRest.RequestOptionsBase): Promise<msRest.RestResponse>;
/**
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param webTestName The name of the Application Insights webtest resource.
* @param callback The callback
*/
deleteMethod(resourceGroupName: string, webTestName: string, callback: msRest.ServiceCallback<void>): void;
/**
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param webTestName The name of the Application Insights webtest resource.
* @param options The optional parameters
* @param callback The callback
*/
deleteMethod(resourceGroupName: string, webTestName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<void>): void;
deleteMethod(resourceGroupName: string, webTestName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<void>, callback?: msRest.ServiceCallback<void>): Promise<msRest.RestResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
webTestName,
options
},
deleteMethodOperationSpec,
callback);
}
/**
* Get all Application Insights web test alerts definitions within a subscription.
* @param [options] The optional parameters
* @returns Promise<Models.WebTestsListResponse>
*/
list(options?: msRest.RequestOptionsBase): Promise<Models.WebTestsListResponse>;
/**
* @param callback The callback
*/
list(callback: msRest.ServiceCallback<Models.WebTestListResult>): void;
/**
* @param options The optional parameters
* @param callback The callback
*/
list(options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.WebTestListResult>): void;
list(options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.WebTestListResult>, callback?: msRest.ServiceCallback<Models.WebTestListResult>): Promise<Models.WebTestsListResponse> {
return this.client.sendOperationRequest(
{
options
},
listOperationSpec,
callback) as Promise<Models.WebTestsListResponse>;
}
/**
* Get all Application Insights web tests defined for the specified component.
* @param componentName The name of the Application Insights component resource.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param [options] The optional parameters
* @returns Promise<Models.WebTestsListByComponentResponse>
*/
listByComponent(componentName: string, resourceGroupName: string, options?: msRest.RequestOptionsBase): Promise<Models.WebTestsListByComponentResponse>;
/**
* @param componentName The name of the Application Insights component resource.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param callback The callback
*/
listByComponent(componentName: string, resourceGroupName: string, callback: msRest.ServiceCallback<Models.WebTestListResult>): void;
/**
* @param componentName The name of the Application Insights component resource.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param options The optional parameters
* @param callback The callback
*/
listByComponent(componentName: string, resourceGroupName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.WebTestListResult>): void;
listByComponent(componentName: string, resourceGroupName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.WebTestListResult>, callback?: msRest.ServiceCallback<Models.WebTestListResult>): Promise<Models.WebTestsListByComponentResponse> {
return this.client.sendOperationRequest(
{
componentName,
resourceGroupName,
options
},
listByComponentOperationSpec,
callback) as Promise<Models.WebTestsListByComponentResponse>;
}
/**
* Get all Application Insights web tests defined within a specified resource group.
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param [options] The optional parameters
* @returns Promise<Models.WebTestsListByResourceGroupNextResponse>
*/
listByResourceGroupNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.WebTestsListByResourceGroupNextResponse>;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param callback The callback
*/
listByResourceGroupNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.WebTestListResult>): void;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param options The optional parameters
* @param callback The callback
*/
listByResourceGroupNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.WebTestListResult>): void;
listByResourceGroupNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.WebTestListResult>, callback?: msRest.ServiceCallback<Models.WebTestListResult>): Promise<Models.WebTestsListByResourceGroupNextResponse> {
return this.client.sendOperationRequest(
{
nextPageLink,
options
},
listByResourceGroupNextOperationSpec,
callback) as Promise<Models.WebTestsListByResourceGroupNextResponse>;
}
/**
* Get all Application Insights web test alerts definitions within a subscription.
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param [options] The optional parameters
* @returns Promise<Models.WebTestsListNextResponse>
*/
listNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.WebTestsListNextResponse>;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param callback The callback
*/
listNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.WebTestListResult>): void;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param options The optional parameters
* @param callback The callback
*/
listNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.WebTestListResult>): void;
listNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.WebTestListResult>, callback?: msRest.ServiceCallback<Models.WebTestListResult>): Promise<Models.WebTestsListNextResponse> {
return this.client.sendOperationRequest(
{
nextPageLink,
options
},
listNextOperationSpec,
callback) as Promise<Models.WebTestsListNextResponse>;
}
/**
* Get all Application Insights web tests defined for the specified component.
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param [options] The optional parameters
* @returns Promise<Models.WebTestsListByComponentNextResponse>
*/
listByComponentNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.WebTestsListByComponentNextResponse>;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param callback The callback
*/
listByComponentNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.WebTestListResult>): void;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param options The optional parameters
* @param callback The callback
*/
listByComponentNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.WebTestListResult>): void;
listByComponentNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.WebTestListResult>, callback?: msRest.ServiceCallback<Models.WebTestListResult>): Promise<Models.WebTestsListByComponentNextResponse> {
return this.client.sendOperationRequest(
{
nextPageLink,
options
},
listByComponentNextOperationSpec,
callback) as Promise<Models.WebTestsListByComponentNextResponse>;
}
}
// Operation Specifications
const serializer = new msRest.Serializer(Mappers);
const listByResourceGroupOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/webtests",
urlParameters: [
Parameters.resourceGroupName,
Parameters.subscriptionId
],
queryParameters: [
Parameters.apiVersion0
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.WebTestListResult
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const getOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/webtests/{webTestName}",
urlParameters: [
Parameters.resourceGroupName,
Parameters.subscriptionId,
Parameters.webTestName
],
queryParameters: [
Parameters.apiVersion0
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.WebTest
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const createOrUpdateOperationSpec: msRest.OperationSpec = {
httpMethod: "PUT",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/webtests/{webTestName}",
urlParameters: [
Parameters.resourceGroupName,
Parameters.subscriptionId,
Parameters.webTestName
],
queryParameters: [
Parameters.apiVersion0
],
headerParameters: [
Parameters.acceptLanguage
],
requestBody: {
parameterPath: "webTestDefinition",
mapper: {
...Mappers.WebTest,
required: true
}
},
responses: {
200: {
bodyMapper: Mappers.WebTest
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const updateTagsOperationSpec: msRest.OperationSpec = {
httpMethod: "PATCH",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/webtests/{webTestName}",
urlParameters: [
Parameters.resourceGroupName,
Parameters.subscriptionId,
Parameters.webTestName
],
queryParameters: [
Parameters.apiVersion0
],
headerParameters: [
Parameters.acceptLanguage
],
requestBody: {
parameterPath: "webTestTags",
mapper: {
...Mappers.TagsResource,
required: true
}
},
responses: {
200: {
bodyMapper: Mappers.WebTest
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const deleteMethodOperationSpec: msRest.OperationSpec = {
httpMethod: "DELETE",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/webtests/{webTestName}",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.webTestName
],
queryParameters: [
Parameters.apiVersion0
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {},
204: {},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const listOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "subscriptions/{subscriptionId}/providers/Microsoft.Insights/webtests",
urlParameters: [
Parameters.subscriptionId
],
queryParameters: [
Parameters.apiVersion0
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.WebTestListResult
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const listByComponentOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Insights/components/{componentName}/webtests",
urlParameters: [
Parameters.componentName,
Parameters.resourceGroupName,
Parameters.subscriptionId
],
queryParameters: [
Parameters.apiVersion0
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.WebTestListResult
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const listByResourceGroupNextOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
baseUrl: "https://management.azure.com",
path: "{nextLink}",
urlParameters: [
Parameters.nextPageLink
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.WebTestListResult
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const listNextOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
baseUrl: "https://management.azure.com",
path: "{nextLink}",
urlParameters: [
Parameters.nextPageLink
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.WebTestListResult
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
};
const listByComponentNextOperationSpec: msRest.OperationSpec = {
httpMethod: "GET",
baseUrl: "https://management.azure.com",
path: "{nextLink}",
urlParameters: [
Parameters.nextPageLink
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.WebTestListResult
},
default: {
bodyMapper: Mappers.CloudError
}
},
serializer
}; | the_stack |
import { __Foo__ as Foo, __Bar__ as Bar } from './shared-utils.fixture';
// Wrong cases for private-instance-field-fields
class InvalidFixture1 {
private static readonly a1: string;
private a2 = 'someString';
protected static a3: string;
private a4 = 5;
protected a5;
private a6;
a7;
private a8 = 5;
public static a9 = 5;
private a10: string;
@Foo() a11 = 5;
private a12;
@Bar() a13 = 'someString';
private a14;
public get some15() {
return 1;
}
private a16 = 5;
set some17(_) {
// noop
}
private a18;
protected get some19() {
return 1;
}
private readonly a20 = 5;
protected set some21(_) {
// noop
}
private readonly a22 = 5;
private get some23() {
return 1;
}
private readonly a24 = 5;
private set some25(_) {
// noop
}
private readonly a26;
c27(a: number): number {
return a;
}
private readonly a28;
static c29(a: number): number {
return a;
}
private readonly a30 = 5;
protected c31(a: number): number {
return a;
}
private readonly a32 = 5;
protected static a33() {
return 5;
}
private readonly a34 = 5;
private b35(): number {
return 5;
}
private readonly a36 = 'someString';
private static a37() {
return 5;
}
private readonly a38 = 5;
}
class InvalidFixture2 {
private static readonly a1 = 5;
private a2;
protected static a3: string;
private a4 = 5;
protected a5;
private a6: string;
a7 = 'someString';
private a8: string;
public static a9 = 'someString';
private a10: string;
@Foo() a11 = 'someString';
private a12 = 5;
@Bar() a13 = 5;
private a14 = 'someString';
get some15() {
return 1;
}
private a16 = 'someString';
public set some17(_) {
// noop
}
private a18 = 5;
protected get some19() {
return 1;
}
private readonly a20: string;
protected set some21(_) {
// noop
}
private readonly a22 = 5;
private get some23() {
return 1;
}
private readonly a24 = 5;
private set some25(_) {
// noop
}
private readonly a26 = 5;
public b27(): number {
return 5;
}
private readonly a28;
public static b29(): number {
return 5;
}
private readonly a30 = 5;
protected c31(a: number): number {
return a;
}
private readonly a32;
protected static b33(): number {
return 5;
}
private readonly a34 = 5;
private b35(): number {
return 5;
}
private readonly a36: string;
private static a37() {
return 5;
}
private readonly a38;
}
class InvalidFixture3 {
private static readonly a1;
private a2 = 'someString';
protected static a3: string;
private a4: string;
protected a5 = 5;
private a6 = 'someString';
public a7;
private a8 = 5;
static a9 = 'someString';
private a10: string;
@Foo() a11 = 5;
private a12;
@Bar() a13 = 'someString';
private a14;
get some15() {
return 1;
}
private a16 = 5;
public set some17(_) {
// noop
}
private a18 = 'someString';
protected get some19() {
return 1;
}
private readonly a20 = 5;
protected set some21(_) {
// noop
}
private readonly a22 = 5;
private get some23() {
return 1;
}
private readonly a24: string;
private set some25(_) {
// noop
}
private readonly a26;
a27() {
return 5;
}
private readonly a28 = 5;
static a29() {
return 5;
}
private readonly a30 = 'someString';
protected c32(c: number): number {
return c;
}
private readonly a33 = 'someString';
protected static b34(): number {
return 5;
}
private readonly a35;
private b36(): number {
return 5;
}
private readonly a37 = 'someString';
private static a38() {
return 5;
}
private readonly a39: string;
}
// Wrong cases for private-static-field-fields
class InvalidFixture4 {
protected static a1 = 5;
private static a2 = 5;
protected a3;
private static a4;
public a5: string;
private static a6 = 5;
static a7 = 5;
private static a8 = 5;
@Foo() a9: string;
private static a10: string;
@Bar() a11 = 5;
private static a12;
get some12() {
return 1;
}
private static a13 = 5;
set some14(_) {
// noop
}
private static a15 = 'someString';
protected get some16() {
return 1;
}
private static readonly a17 = 'someString';
protected set some18(_) {
// noop
}
private static readonly a19 = 5;
private get some20() {
return 1;
}
private static readonly a21 = 'someString';
private set some22(_) {
// noop
}
private static readonly a23: string;
c24(a: number): number {
return a;
}
private static readonly a25: string;
static b26(): number {
return 5;
}
private static readonly a27 = 'someString';
protected c28(a: number): number {
return a;
}
private static readonly a29 = 'someString';
protected static a30() {
return 5;
}
private static readonly a31 = 5;
private c32(a: number): number {
return a;
}
private static readonly a33: string;
private static a34() {
return 5;
}
private static readonly a35 = 5;
}
class InvalidFixture5 {
protected static a1 = 5;
private static a2 = 5;
protected a3 = 5;
private static a4 = 5;
public a5 = 5;
private static a6 = 5;
static a7: string;
private static a8 = 5;
@Foo() a9;
private static a10 = 'someString';
@Bar() a11 = 5;
private static a12;
get some13() {
return 1;
}
private static a14;
public set some15(_) {
// noop
}
private static a16 = 5;
protected get some17() {
return 1;
}
private static readonly a18;
protected set some19(_) {
// noop
}
private static readonly a20: string;
private get some21() {
return 1;
}
private static readonly a22 = 'someString';
private set some23(_) {
// noop
}
private static readonly a24 = 5;
c25(a: number): number {
return a;
}
private static readonly a26: string;
static a27() {
return 5;
}
private static readonly a28 = 5;
protected a29() {
return 5;
}
private static readonly a30 = 5;
protected static c31(a: number): number {
return a;
}
private static readonly a32 = 5;
private a33() {
return 5;
}
private static readonly a34 = 5;
private static a35() {
return 5;
}
private static readonly a36;
}
class InvalidFixture6 {
protected static a1 = 5;
private static a2;
protected a3 = 5;
private static a4 = 5;
public a5 = 5;
private static a6 = 'someString';
public static a7 = 5;
private static a8 = 'someString';
@Foo() a9: string;
private static a10 = 5;
@Bar() a11: string;
private static a12 = 5;
public get some13() {
return 1;
}
private static a14 = 5;
set some15(_) {
// noop
}
private static a16;
protected get some17() {
return 1;
}
private static readonly a18 = 'someString';
protected set some19(_) {
// noop
}
private static readonly a20 = 5;
private get some21() {
return 1;
}
private static readonly a22 = 5;
private set some23(_) {
// noop
}
private static readonly a24 = 'someString';
a25() {
return 5;
}
private static readonly a26;
static c27(a: number): number {
return a;
}
private static readonly a29 = 'someString';
protected b30(): number {
return 5;
}
private static readonly a31: string;
protected static a32() {
return 5;
}
private static readonly a33 = 5;
private c34(a: number): number {
return a;
}
private static readonly a35 = 5;
private static a36() {
return 5;
}
private static readonly a37 = 5;
}
// Wrong cases for protected-static-field-fields
class InvalidFixture7 {
protected a1: string;
protected static a2;
public a3 = 5;
protected static a4 = 5;
public static a5;
protected static a6 = 5;
@Foo() a7 = 5;
protected static a8 = 5;
@Bar() a9 = 'someString';
protected static a10 = 5;
public get some11() {
return 1;
}
protected static a12 = 'someString';
public set some13(_) {
// noop
}
protected static a14: string;
protected get some15() {
return 1;
}
protected static a16: string;
protected set some17(_) {
// noop
}
protected static a18 = 'someString';
private get some19() {
return 1;
}
protected static a20 = 5;
private set some21(_) {
// noop
}
protected static a22: string;
public b23(): number {
return 5;
}
protected static a24 = 5;
static b25(): number {
return 5;
}
protected static a26: string;
protected c27(a: number): number {
return a;
}
protected static a28 = 5;
protected static c29(a: number): number {
return a;
}
protected static a30: string;
private b31(): number {
return 5;
}
protected static a32 = 'someString';
private static a33() {
return 5;
}
protected static a34;
}
class InvalidFixture8 {
protected a1 = 'someString';
protected static a2: string;
a3 = 5;
protected static a4: string;
static a5: string;
protected static a6 = 5;
@Foo() a7 = 5;
protected static a8;
@Bar() a9 = 'someString';
protected static a10 = 5;
get some11() {
return 1;
}
protected static a12 = 5;
public set some13(_) {
// noop
}
protected static a14;
protected get some15() {
return 1;
}
protected static a16 = 'someString';
protected set some17(_) {
// noop
}
protected static a18 = 5;
private get some19() {
return 1;
}
protected static a20;
private set some21(_) {
// noop
}
protected static a22 = 'someString';
c23(a: number): number {
return a;
}
protected static a24 = 'someString';
public static a25() {
return 5;
}
protected static a26 = 5;
protected c27(a: number): number {
return a;
}
protected static a28;
protected static b29(): number {
return 5;
}
protected static a30 = 5;
private a31() {
return 5;
}
protected static a32 = 'someString';
private static c33(a: number): number {
return a;
}
protected static a34 = 5;
}
class Failure9 {
protected a1: string;
protected static a2: string;
public a3 = 5;
protected static a4: string;
public static a5 = 5;
protected static a6: string;
@Foo() a7: string;
protected static a8: string;
@Bar() a9;
protected static a10: string;
get some11() {
return 1;
}
protected static a12 = 5;
public set some13(_) {
// noop
}
protected static a14 = 5;
protected get some15() {
return 1;
}
protected static a16;
protected set some17(_) {
// noop
}
protected static a18 = 5;
private get some19() {
return 1;
}
protected static a20 = 5;
private set some21(_) {
// noop
}
protected static a22 = 5;
public c23(a: number): number {
return a;
}
protected static a24 = 5;
static c25(a: number): number {
return a;
}
protected static a26: string;
protected b27(): number {
return 5;
}
protected static a28 = 5;
protected static a29() {
return 5;
}
protected static a30 = 'someString';
private b31(): number {
return 5;
}
protected static a32;
private static c33(a: number): number {
return a;
}
protected static a34 = 'someString';
}
// Wrong cases for protected-instance-field-fields
class InvalidFixture10 {
public a1 = 5;
protected a2 = 5;
public static a3 = 5;
protected a4 = 5;
@Foo() a5 = 'someString';
protected a6 = 'someString';
@Bar() a7 = 'someString';
protected a8 = 5;
get some9() {
return 1;
}
protected a10 = 5;
set some11(_) {
// noop
}
protected a12 = 'someString';
protected get some13() {
return 1;
}
protected a14: string;
protected set some15(_) {
// noop
}
protected a16 = 'someString';
private get some17() {
return 1;
}
protected a18 = 5;
protected set some19(_) {
// noop
}
protected a20 = 'someString';
public c21(a: number): number {
return a;
}
protected a22: string;
public static a23() {
return 5;
}
protected a24: string;
protected b25(): number {
return 5;
}
protected a26 = 'someString';
protected static c27(a: number): number {
return a;
}
protected a28 = 'someString';
private b29(): number {
return 5;
}
protected a30 = 5;
private static a31() {
return 5;
}
protected a32 = 5;
}
class InvalidFixture11 {
public a1;
protected a2: string;
static a3;
protected a4 = 5;
@Foo() a5: string;
protected a6 = 'someString';
@Bar() a7 = 5;
protected a8 = 5;
public get some9() {
return 1;
}
protected a10 = 5;
set some11(_) {
// noop
}
protected a12;
protected get some13() {
return 1;
}
protected a14: string;
protected set some15(_) {
// noop
}
protected a16;
private get some17() {
return 1;
}
protected a18 = 'someString';
protected set some19(_) {
// noop
}
protected a20: string;
b21(): number {
return 5;
}
protected a22 = 5;
static b23(): number {
return 5;
}
protected a24;
protected a25() {
return 5;
}
protected a26 = 'someString';
protected static b27(): number {
return 5;
}
protected a28 = 5;
private a29() {
return 5;
}
protected a30 = 'someString';
private static c31(a: number): number {
return a;
}
protected a32: string;
}
class InvalidFixture12 {
public a1;
protected a2 = 5;
public static a3;
protected a4 = 'someString';
@Foo() a5 = 5;
protected a6;
@Bar() a7 = 5;
protected a8 = 5;
get some9() {
return 1;
}
protected a10: string;
public set some11(_) {
// noop
}
protected a12 = 5;
protected get some13() {
return 1;
}
protected a14;
protected set some15(_) {
// noop
}
protected a16 = 5;
private get some17() {
return 1;
}
protected a18 = 5;
protected set some19(_) {
// noop
}
protected a20;
public a21() {
return 5;
}
protected a22: string;
static c23(a: number): number {
return a;
}
protected a24: string;
protected b25(): number {
return 5;
}
protected a26 = 5;
protected static a() {
return 5;
}
protected a27 = 5;
private b28(): number {
return 5;
}
protected a29 = 5;
private static c30(a: number): number {
return a;
}
protected a31: string;
}
// Wrong cases for public-instance-field-fields
class InvalidFixture13 {
public static a1 = 'someString';
a2: string;
@Foo() a3 = 'someString';
public a4: string;
@Bar() a5: string;
a6;
public get some7() {
return 1;
}
a8 = 'someString';
set some9(_) {
// noop
}
public a10 = 5;
protected get some11() {
return 1;
}
a12: string;
protected set some13(_) {
// noop
}
public a14 = 5;
private get some15() {
return 1;
}
a16: string;
protected set some17(_) {
// noop
}
public a18: string;
c19(a: number): number {
return a;
}
a20 = 5;
static c21(a: number): number {
return a;
}
a22 = 5;
protected a23() {
return 5;
}
a24;
protected static a25() {
return 5;
}
a26 = 5;
private c27(a: number): number {
return a;
}
a28 = 5;
private static b29(): number {
return 5;
}
a30 = 5;
}
class InvalidFixture14 {
static a1 = 5;
public a2 = 5;
@Foo() a3;
a4 = 5;
@Bar() a5;
public a6 = 5;
get some7() {
return 1;
}
public a8 = 5;
set some9(_) {
// noop
}
public a10 = 5;
protected get some11() {
return 1;
}
public a12 = 'someString';
protected set some13(_) {
// noop
}
public a14 = 'someString';
private get some15() {
return 1;
}
public a16 = 5;
protected set some17(_) {
// noop
}
a18 = 5;
public a19() {
return 5;
}
public a20;
static b21(): number {
return 5;
}
public a22 = 5;
protected c23(a: number): number {
return a;
}
public a24 = 5;
protected static b25(): number {
return 5;
}
public a26 = 5;
private b27(): number {
return 5;
}
a28 = 5;
private static a29() {
return 5;
}
public a30: string;
}
class InvalidFixture15 {
static a1: string;
a2: string;
@Foo() a3 = 'someString';
a4 = 5;
@Bar() a5: string;
a6 = 5;
public get some7() {
return 1;
}
a8: string;
set some9(_) {
// noop
}
public a10 = 5;
protected get some11() {
return 1;
}
public a12;
protected set some13(_) {
// noop
}
public a14 = 5;
private get some15() {
return 1;
}
public a16 = 5;
protected set some17(_) {
// noop
}
a18 = 'someString';
public b19(): number {
return 5;
}
public a20: string;
static c21(a: number): number {
return a;
}
public a22;
protected b23(): number {
return 5;
}
public a24 = 5;
protected static c25(a: number): number {
return a;
}
a26 = 'someString';
private a27() {
return 5;
}
public a28 = 'someString';
private static a29() {
return 5;
}
public a30 = 5;
}
// Wrong cases for public-static-field-fields
class InvalidFixture16 {
@Foo() a1 = 'someString';
public static a2 = 5;
@Bar() a2 = 5;
static a3 = 5;
get some4() {
return 1;
}
static a5 = 5;
public set some6(_) {
// noop
}
public static a7;
protected get some8() {
return 1;
}
static a9 = 5;
protected set some10(_) {
// noop
}
static a11;
private get some12() {
return 1;
}
static a13 = 'someString';
protected set some14(_) {
// noop
}
static a15 = 'someString';
c16(a: number): number {
return a;
}
public static a17: string;
public static b18(): number {
return 5;
}
static a19: string;
protected b20(): number {
return 5;
}
public static a21: string;
protected static b22(): number {
return 5;
}
static a23: string;
private a24() {
return 5;
}
public static a25: string;
private static a26() {
return 5;
}
public static a27 = 5;
}
class InvalidFixture17 {
@Foo() a1 = 'someString';
static a2 = 5;
@Bar() a3 = 5;
public static a4: string;
get some5() {
return 1;
}
static a6 = 5;
public set some7(_) {
// noop
}
public static a8: string;
protected get some9() {
return 1;
}
public static a10 = 5;
protected set some11(_) {
// noop
}
static a12 = 5;
private get some13() {
return 1;
}
static a14 = 5;
protected set some15(_) {
// noop
}
static a16 = 5;
public b17(): number {
return 5;
}
public static a18 = 'someString';
public static b19(): number {
return 5;
}
public static a20: string;
protected b21(): number {
return 5;
}
static a22;
protected static a23() {
return 5;
}
static a24 = 5;
private b25(): number {
return 5;
}
static a26 = 5;
private static a27() {
return 5;
}
static a28 = 5;
}
class InvalidFixture18 {
@Foo() a1: string;
public static a2 = 5;
@Bar() a3: string;
static a4;
public get some5() {
return 1;
}
static a6 = 5;
set some7(_) {
// noop
}
public static a8 = 5;
protected get some9() {
return 1;
}
static a10;
protected set some11(_) {
// noop
}
public static a12;
private get some13() {
return 1;
}
public static a14 = 'someString';
protected set some15(_) {
// noop
}
static a16: string;
a17() {
return 5;
}
static a18: string;
public static c19(a: number): number {
return a;
}
public static a20: string;
protected a21() {
return 5;
}
static a22 = 5;
protected static b23(): number {
return 5;
}
public static a24 = 5;
private a25() {
return 5;
}
static a26;
private static b27(): number {
return 5;
}
public static a28: string;
}
// Wrong cases for @Input-fields
class InvalidFixture19 {
@Bar() a1 = 5;
@Foo() a2;
get some3() {
return 1;
}
@Foo() a4 = 5;
set some5(_) {
// noop
}
@Foo() a6 = 'someString';
protected get some7() {
return 1;
}
@Foo() a8 = 'someString';
protected set some9(_) {
// noop
}
@Foo() a10;
private get some11() {
return 1;
}
@Foo() a12: string;
protected set some13(_) {
// noop
}
@Foo() a14: string;
public a15() {
return 5;
}
@Foo() a16: string;
static c17(a: number): number {
return a;
}
@Foo() a18: string;
protected b19(): number {
return 5;
}
@Foo() a20 = 'someString';
protected static b21(): number {
return 5;
}
@Foo() a22 = 5;
private a23() {
return 5;
}
@Foo() a24 = 'someString';
private static b25(): number {
return 5;
}
@Foo() a26 = 5;
}
class InvalidFixture20 {
@Bar() a1 = 5;
@Foo() a2: string;
public get some3() {
return 1;
}
@Foo() a4: string;
set some5(_) {
// noop
}
@Foo() a6 = 5;
protected get some7() {
return 1;
}
@Foo() a8;
protected set some9(_) {
// noop
}
@Foo() a10 = 5;
private get some11() {
return 1;
}
@Foo() a12 = 5;
protected set some13(_) {
// noop
}
@Foo() a14 = 'someString';
b15(): number {
return 5;
}
@Foo() a16 = 'someString';
public static c17(a: number): number {
return a;
}
@Foo() a18 = 'someString';
protected a19() {
return 5;
}
@Foo() a20 = 5;
protected static c21(a: number): number {
return a;
}
@Foo() a22 = 5;
private c23(a: number): number {
return a;
}
@Foo() a24 = 5;
private static b25(): number {
return 5;
}
@Foo() a26: string;
}
class InvalidFixture21 {
@Bar() a1 = 5;
@Foo() a2 = 'someString';
get some3() {
return 1;
}
@Foo() a4 = 5;
set some5(_) {
// noop
}
@Foo() a6 = 5;
protected get some7() {
return 1;
}
@Foo() a8: string;
protected set some9(_) {
// noop
}
@Foo() a10: string;
private get some11() {
return 1;
}
@Foo() a12 = 5;
protected set some13(_) {
// noop
}
@Foo() a14 = 5;
public c15(a: number): number {
return a;
}
@Foo() a16 = 5;
public static a17() {
return 5;
}
@Foo() a18 = 5;
protected c19(a: number): number {
return a;
}
@Foo() a20;
protected static c21(a: number): number {
return a;
}
@Foo() a22: string;
private b23(): number {
return 5;
}
@Foo() a24: string;
private static c25(a: number): number {
return a;
}
@Foo() a26 = 5;
}
// Wrong cases for @Output-fields
class InvalidFixture22 {
get some1() {
return 1;
}
@Bar() a2;
public set some3(_) {
// noop
}
@Bar() a4 = 5;
protected get some5() {
return 1;
}
@Bar() a6: string;
protected set some7(_) {
// noop
}
@Bar() a8 = 5;
private get some9() {
return 1;
}
@Bar() a10: string;
protected set some11(_) {
// noop
}
@Bar() a12 = 'someString';
c(a: number): number {
return a;
}
@Bar() a13 = 'someString';
public static b(): number {
return 5;
}
@Bar() a14;
protected b15(): number {
return 5;
}
@Bar() a16 = 5;
protected static c17(a: number): number {
return a;
}
@Bar() a18 = 5;
private a19() {
return 5;
}
@Bar() a20 = 5;
private static c21(a: number): number {
return a;
}
@Bar() a22 = 'someString';
}
class InvalidFixture23 {
get some1() {
return 1;
}
@Bar() a2;
public set some3(_) {
// noop
}
@Bar() a4;
protected get some5() {
return 1;
}
@Bar() a6;
protected set some7(_) {
// noop
}
@Bar() a8: string;
private get some9() {
return 1;
}
@Bar() a10: string;
protected set some11(_) {
// noop
}
@Bar() a12;
public a13() {
return 5;
}
@Bar() a14 = 'someString';
public static c15(a: number): number {
return a;
}
@Bar() a16: string;
protected a17() {
return 5;
}
@Bar() a18: string;
protected static b19(): number {
return 5;
}
@Bar() a20;
private a() {
return 5;
}
@Bar() a21;
private static c22(a: number): number {
return a;
}
@Bar() a23 = 'someString';
}
class InvalidFixture24 {
public get some1() {
return 1;
}
@Bar() a2;
set some3(_) {
// noop
}
@Bar() a4 = 'someString';
protected get some5() {
return 1;
}
@Bar() a6 = 5;
protected set some7(_) {
// noop
}
@Bar() a8 = 5;
private get some9() {
return 1;
}
@Bar() a10: string;
protected set some11(_) {
// noop
}
@Bar() a12 = 'someString';
c13(a: number): number {
return a;
}
@Bar() a14;
public static c15(a: number): number {
return a;
}
@Bar() a16;
protected a17() {
return 5;
}
@Bar() a18: string;
protected static a() {
return 5;
}
@Bar() a19 = 5;
private a20() {
return 5;
}
@Bar() a21 = 'someString';
private static c22(a: number): number {
return a;
}
@Bar() a23 = 5;
}
// Wrong cases for public-getter-fields
class InvalidFixture25 {
set some1(_) {
// noop
}
get some2() {
return 1;
}
protected get some3() {
return 1;
}
get some4() {
return 1;
}
protected set some5(_) {
// noop
}
public get some6() {
return 1;
}
private get some7() {
return 1;
}
get some8() {
return 1;
}
protected set some9(_) {
// noop
}
public get some10() {
return 1;
}
public a11() {
return 5;
}
public get some12() {
return 1;
}
public static a13() {
return 5;
}
public get some14() {
return 1;
}
protected a15() {
return 5;
}
public get some16() {
return 1;
}
protected static b17(): number {
return 5;
}
get some18() {
return 1;
}
private b19(): number {
return 5;
}
get some20() {
return 1;
}
private static c21(a: number): number {
return a;
}
public get some22() {
return 1;
}
}
class InvalidFixture26 {
set some1(_) {
// noop
}
public get some2() {
return 1;
}
protected get some3() {
return 1;
}
public get some4() {
return 1;
}
protected set some5(_) {
// noop
}
get some6() {
return 1;
}
private get some7() {
return 1;
}
public get some8() {
return 1;
}
protected set some9(_) {
// noop
}
get some10() {
return 1;
}
c11(a: number): number {
return a;
}
get some12() {
return 1;
}
public static b13(): number {
return 5;
}
public get some14() {
return 1;
}
protected b15(): number {
return 5;
}
get some16() {
return 1;
}
protected static a17() {
return 5;
}
get some18() {
return 1;
}
private a19() {
return 5;
}
get some20() {
return 1;
}
private static c21(a: number): number {
return a;
}
get some22() {
return 1;
}
}
class InvalidFixture27 {
set some1(_) {
// noop
}
get some2() {
return 1;
}
protected get some3() {
return 1;
}
public get some4() {
return 1;
}
protected set some5(_) {
// noop
}
public get some6() {
return 1;
}
private get some7() {
return 1;
}
public get some9() {
return 1;
}
protected set some10(_) {
// noop
}
public get some11() {
return 1;
}
public c12(a: number): number {
return a;
}
get some13() {
return 1;
}
public static c14(a: number): number {
return a;
}
get some15() {
return 1;
}
protected c16(a: number): number {
return a;
}
get some17() {
return 1;
}
protected static c18(a: number): number {
return a;
}
get some19() {
return 1;
}
private b20(): number {
return 5;
}
get some21() {
return 1;
}
private static a22() {
return 5;
}
public get some23() {
return 1;
}
}
// Wrong cases for public-setter-fields
class InvalidFixture28 {
protected get some1() {
return 1;
}
set some2(_) {
// noop
}
protected set some3(_) {
// noop
}
set some4(_) {
// noop
}
private get some5() {
return 1;
}
set some6(_) {
// noop
}
protected set some7(_) {
// noop
}
public set some9(_) {
// noop
}
public c10(a: number): number {
return a;
}
public set some11(_) {
// noop
}
static b12(): number {
return 5;
}
set some13(_) {
// noop
}
protected b14(): number {
return 5;
}
set some15(_) {
// noop
}
protected static b16(): number {
return 5;
}
public set some17(_) {
// noop
}
private a18() {
return 5;
}
public set some19(_) {
// noop
}
private static a20() {
return 5;
}
public set some21(_) {
// noop
}
}
class InvalidFixture29 {
protected get some1() {
return 1;
}
set some2(_) {
// noop
}
protected set some3(_) {
// noop
}
set some4(_) {
// noop
}
private get some5() {
return 1;
}
public set some6(_) {
// noop
}
protected set some7(_) {
// noop
}
set some8(_) {
// noop
}
public a9() {
return 5;
}
public set some10(_) {
// noop
}
public static b11(): number {
return 5;
}
set some12(_) {
// noop
}
protected a13() {
return 5;
}
set some14(_) {
// noop
}
protected static b15(): number {
return 5;
}
set some15(_) {
// noop
}
private c16(a: number): number {
return a;
}
public set some17(_) {
// noop
}
private static b18(): number {
return 5;
}
public set some19(_) {
// noop
}
}
class InvalidFixture30 {
protected get some1() {
return 1;
}
set some2(_) {
// noop
}
protected set some3(_) {
// noop
}
set some4(_) {
// noop
}
private get some5() {
return 1;
}
set some6(_) {
// noop
}
protected set some7(_) {
// noop
}
set some8(_) {
// noop
}
public b9(): number {
return 5;
}
set some10(_) {
// noop
}
static b(): number {
return 5;
}
set some11(_) {
// noop
}
protected c12(a: number): number {
return a;
}
set some13(_) {
// noop
}
protected static a14() {
return 5;
}
set some15(_) {
// noop
}
private b16(): number {
return 5;
}
public set some17(_) {
// noop
}
private static c18(a: number): number {
return a;
}
set some19(_) {
// noop
}
}
// Wrong cases for protected-getter-fields
class InvalidFixture31 {
protected set some1(_) {
// noop
}
protected get some2() {
return 1;
}
private get some3() {
return 1;
}
protected get some4() {
return 1;
}
protected set some5(_) {
// noop
}
protected get some6() {
return 1;
}
public c7(a: number): number {
return a;
}
protected get some8() {
return 1;
}
static b9(): number {
return 5;
}
protected get some10() {
return 1;
}
protected a11() {
return 5;
}
protected get some12() {
return 1;
}
protected static b13(): number {
return 5;
}
protected get some14() {
return 1;
}
private a15() {
return 5;
}
protected get some16() {
return 1;
}
private static b17(): number {
return 5;
}
protected get some18() {
return 1;
}
}
class InvalidFixture32 {
protected set some1(_) {
// noop
}
protected get some2() {
return 1;
}
private get some3() {
return 1;
}
protected get some4() {
return 1;
}
protected set some5(_) {
// noop
}
protected get some6() {
return 1;
}
public a7() {
return 5;
}
protected get some8() {
return 1;
}
static c9(a: number): number {
return a;
}
protected get some10() {
return 1;
}
protected c11(a: number): number {
return a;
}
protected get some12() {
return 1;
}
protected static c13(a: number): number {
return a;
}
protected get some14() {
return 1;
}
private c15(a: number): number {
return a;
}
protected get some16() {
return 1;
}
private static c17(a: number): number {
return a;
}
protected get some18() {
return 1;
}
}
class InvalidFixture33 {
protected set some1(_) {
// noop
}
protected get some2() {
return 1;
}
private get some3() {
return 1;
}
protected get some4() {
return 1;
}
protected set some5(_) {
// noop
}
protected get some6() {
return 1;
}
b7(): number {
return 5;
}
protected get some8() {
return 1;
}
static a9() {
return 5;
}
protected get some10() {
return 1;
}
protected c11(a: number): number {
return a;
}
protected get some12() {
return 1;
}
protected static b13(): number {
return 5;
}
protected get some14() {
return 1;
}
private a15() {
return 5;
}
protected get some16() {
return 1;
}
private static c17(a: number): number {
return a;
}
protected get some18() {
return 1;
}
}
// Wrong cases for protected-setter-fields
class InvalidFixture34 {
private get some1() {
return 1;
}
protected set some2(_) {
// noop
}
protected set some3(_) {
// noop
}
protected set some4(_) {
// noop
}
public a5() {
return 5;
}
protected set some6(_) {
// noop
}
public static b(): number {
return 5;
}
protected set some7(_) {
// noop
}
protected c8(a: number): number {
return a;
}
protected set some9(_) {
// noop
}
protected static a10() {
return 5;
}
protected set some11(_) {
// noop
}
private b12(): number {
return 5;
}
protected set some13(_) {
// noop
}
private static a14() {
return 5;
}
protected set some15(_) {
// noop
}
}
class InvalidFixture35 {
private get some1() {
return 1;
}
protected set some2(_) {
// noop
}
protected set some3(_) {
// noop
}
protected set some4(_) {
// noop
}
b4(): number {
return 5;
}
protected set some5(_) {
// noop
}
public static c6(a: number): number {
return a;
}
protected set some7(_) {
// noop
}
protected c8(a: number): number {
return a;
}
protected set some9(_) {
// noop
}
protected static c10(a: number): number {
return a;
}
protected set some11(_) {
// noop
}
private c12(a: number): number {
return a;
}
protected set some13(_) {
// noop
}
private static b14(): number {
return 5;
}
protected set some15(_) {
// noop
}
}
class InvalidFixture36 {
private get some1() {
return 1;
}
protected set some2(_) {
// noop
}
protected set some3(_) {
// noop
}
protected set some4(_) {
// noop
}
public a5() {
return 5;
}
protected set some6(_) {
// noop
}
static c7(a: number): number {
return a;
}
protected set some8(_) {
// noop
}
protected c9(a: number): number {
return a;
}
protected set some10(_) {
// noop
}
protected static b11(): number {
return 5;
}
protected set some12(_) {
// noop
}
private b13(): number {
return 5;
}
protected set some14(_) {
// noop
}
private static a15() {
return 5;
}
protected set some16(_) {
// noop
}
}
// Wrong cases for private-getter-fields
class InvalidFixture37 {
protected set some1(_) {
// noop
}
private get some2() {
return 1;
}
a3() {
return 5;
}
private get some4() {
return 1;
}
public static a5() {
return 5;
}
private get some6() {
return 1;
}
protected b7(): number {
return 5;
}
private get some8() {
return 1;
}
protected static c9(a: number): number {
return a;
}
private get some10() {
return 1;
}
private b11(): number {
return 5;
}
private get some12() {
return 1;
}
private static b13(): number {
return 5;
}
private get some14() {
return 1;
}
}
class InvalidFixture38 {
protected set some1(_) {
// noop
}
private get some2() {
return 1;
}
public a3() {
return 5;
}
private get some4() {
return 1;
}
static a5() {
return 5;
}
private get some6() {
return 1;
}
protected c7(a: number): number {
return a;
}
private get some8() {
return 1;
}
protected static a9() {
return 5;
}
private get some10() {
return 1;
}
private a11() {
return 5;
}
private get some12() {
return 1;
}
private static b13(): number {
return 5;
}
private get some14() {
return 1;
}
}
class InvalidFixture39 {
protected set some1(_) {
// noop
}
private get some2() {
return 1;
}
a3() {
return 5;
}
private get some4() {
return 1;
}
static a5() {
return 5;
}
private get some6() {
return 1;
}
protected c7(a: number): number {
return a;
}
private get some8() {
return 1;
}
protected static a9() {
return 5;
}
private get some10() {
return 1;
}
private a10() {
return 5;
}
private get some11() {
return 1;
}
private static c12(a: number): number {
return a;
}
private get some13() {
return 1;
}
}
// Wrong cases for private-setter-fields
class InvalidFixture40 {
a1() {
return 5;
}
protected set some2(_) {
// noop
}
static a3() {
return 5;
}
protected set some4(_) {
// noop
}
protected b5(): number {
return 5;
}
protected set some6(_) {
// noop
}
protected static a7() {
return 5;
}
protected set some8(_) {
// noop
}
private b9(): number {
return 5;
}
protected set some10(_) {
// noop
}
private static c11(a: number): number {
return a;
}
protected set some12(_) {
// noop
}
}
class InvalidFixture41 {
a1() {
return 5;
}
protected set some2(_) {
// noop
}
static c3(a: number): number {
return a;
}
protected set some4(_) {
// noop
}
protected c5(a: number): number {
return a;
}
protected set some6(_) {
// noop
}
protected static a7() {
return 5;
}
protected set some8(_) {
// noop
}
private b9(): number {
return 5;
}
protected set some10(_) {
// noop
}
private static c11(a: number): number {
return a;
}
protected set some12(_) {
// noop
}
}
class InvalidFixture42 {
public b1(): number {
return 5;
}
protected set some2(_) {
// noop
}
public static a3() {
return 5;
}
protected set some4(_) {
// noop
}
protected a5() {
return 5;
}
protected set some6(_) {
// noop
}
protected static a7() {
return 5;
}
protected set some8(_) {
// noop
}
private b9(): number {
return 5;
}
protected set some10(_) {
// noop
}
private static c11(a: number): number {
return a;
}
protected set some12(_) {
// noop
}
}
// Wrong cases for public-instance-method-fields
class InvalidFixture43 {
static b1(): number {
return 5;
}
c2(a: number): number {
return a;
}
protected b3(): number {
return 5;
}
public b4(): number {
return 5;
}
protected static b5(): number {
return 5;
}
public b6(): number {
return 5;
}
private a7() {
return 5;
}
public c8(a: number): number {
return a;
}
private static a9() {
return 5;
}
a10() {
return 5;
}
}
class InvalidFixture44 {
public static c1(a: number): number {
return a;
}
public c2(a: number): number {
return a;
}
protected b3(): number {
return 5;
}
public b4(): number {
return 5;
}
protected static b5(): number {
return 5;
}
public b6(): number {
return 5;
}
private a7() {
return 5;
}
a8() {
return 5;
}
private static c9(a: number): number {
return a;
}
a10() {
return 5;
}
}
class InvalidFixture45 {
public static c1(a: number): number {
return a;
}
public b2(): number {
return 5;
}
protected c3(a: number): number {
return a;
}
b4(): number {
return 5;
}
protected static c5(a: number): number {
return a;
}
public a6() {
return 5;
}
private a7() {
return 5;
}
public b8(): number {
return 5;
}
private static a9() {
return 5;
}
public a10() {
return 5;
}
}
// Wrong cases for public-static-method-fields
class InvalidFixture46 {
protected c1(a: number): number {
return a;
}
public static b2(): number {
return 5;
}
protected static b3(): number {
return 5;
}
static a4() {
return 5;
}
private a5() {
return 5;
}
public static b6(): number {
return 5;
}
private static c7(a: number): number {
return a;
}
public static a8() {
return 5;
}
}
class InvalidFixture47 {
protected c1(a: number): number {
return a;
}
static a2() {
return 5;
}
protected static c3(a: number): number {
return a;
}
public static c4(a: number): number {
return a;
}
private c5(a: number): number {
return a;
}
static b6(): number {
return 5;
}
private static c7(a: number): number {
return a;
}
public static a8() {
return 5;
}
}
class InvalidFixture48 {
protected c1(a: number): number {
return a;
}
static c2(a: number): number {
return a;
}
protected static c3(a: number): number {
return a;
}
public static b4(): number {
return 5;
}
private a5() {
return 5;
}
public static a6() {
return 5;
}
private static c7(a: number): number {
return a;
}
public static a8() {
return 5;
}
}
// Wrong cases for protected-instance-method-fields
class InvalidFixture49 {
protected static b1(): number {
return 5;
}
protected c2(a: number): number {
return a;
}
private c3(a: number): number {
return a;
}
protected c4(a: number): number {
return a;
}
private static a5() {
return 5;
}
protected b6(): number {
return 5;
}
}
class InvalidFixture50 {
protected static a1() {
return 5;
}
protected c2(a: number): number {
return a;
}
private c3(a: number): number {
return a;
}
protected c4(a: number): number {
return a;
}
private static c5(a: number): number {
return a;
}
protected b6(): number {
return 5;
}
}
class InvalidFixture51 {
protected static c1(a: number): number {
return a;
}
protected b2(): number {
return 5;
}
private c3(a: number): number {
return a;
}
protected b4(): number {
return 5;
}
private static b5(): number {
return 5;
}
protected a6() {
return 5;
}
}
// Wrong cases for protected-static-method-fields
class InvalidFixture52 {
private b1(): number {
return 5;
}
protected static a2() {
return 5;
}
private static b3(): number {
return 5;
}
protected static c4(a: number): number {
return a;
}
}
class InvalidFixture53 {
private a1() {
return 5;
}
protected static c2(a: number): number {
return a;
}
private static c3(a: number): number {
return a;
}
protected static b4(): number {
return 5;
}
}
class InvalidFixture54 {
private b1(): number {
return 5;
}
protected static a2() {
return 5;
}
private static a3() {
return 5;
}
protected static a4() {
return 5;
}
}
// Wrong cases for private-instance-method-fields
class InvalidFixture55 {
private static a1() {
return 5;
}
private a2() {
return 5;
}
}
class InvalidFixture56 {
private static b1(): number {
return 5;
}
private c2(a: number): number {
return a;
}
}
class InvalidFixture57 {
private static b1(): number {
return 5;
}
private b2(): number {
return 5;
}
} | the_stack |
import { Address, BigInt } from "@graphprotocol/graph-ts";
// Import event types from the registrar contract ABIs
import {
BondingManager,
ClaimEarningsCall,
BondCall,
Unbond,
WithdrawStake,
TranscoderUpdate,
TranscoderResigned,
TranscoderEvicted,
} from "../types/BondingManagerV1/BondingManager";
// Import entity types generated from the GraphQL schema
import {
Transaction,
Transcoder,
Delegator,
Protocol,
TranscoderUpdateEvent,
TranscoderResignedEvent,
TranscoderEvictedEvent,
BondEvent,
UnbondEvent,
EarningsClaimedEvent,
WithdrawStakeEvent,
} from "../types/schema";
import {
makeEventId,
convertToDecimal,
ZERO_BD,
EMPTY_ADDRESS,
createOrLoadDelegator,
createOrLoadTranscoder,
createOrLoadRound,
} from "../../utils/helpers";
import { integer } from "@protofire/subgraph-toolkit";
// Handler for TranscoderUpdate events
export function transcoderUpdate(event: TranscoderUpdate): void {
let round = createOrLoadRound(event.block.number);
let transcoder = createOrLoadTranscoder(event.params.transcoder.toHex());
// Update transcoder
transcoder.delegator = event.params.transcoder.toHex();
transcoder.pendingRewardCut = event.params.pendingRewardCut as BigInt;
transcoder.pendingFeeShare = event.params.pendingFeeShare as BigInt;
transcoder.pendingPricePerSegment = event.params.pendingPricePerSegment;
transcoder.save();
let tx =
Transaction.load(event.transaction.hash.toHex()) ||
new Transaction(event.transaction.hash.toHex());
tx.blockNumber = event.block.number;
tx.gasUsed = event.transaction.gasUsed;
tx.gasPrice = event.transaction.gasPrice;
tx.timestamp = event.block.timestamp.toI32();
tx.from = event.transaction.from.toHex();
tx.to = event.transaction.to.toHex();
tx.save();
let transcoderUpdateEvent = new TranscoderUpdateEvent(
makeEventId(event.transaction.hash, event.logIndex)
);
transcoderUpdateEvent.transaction = event.transaction.hash.toHex();
transcoderUpdateEvent.timestamp = event.block.timestamp.toI32();
transcoderUpdateEvent.round = round.id;
transcoderUpdateEvent.delegate = event.params.transcoder.toHex();
transcoderUpdateEvent.rewardCut = event.params.pendingRewardCut as BigInt;
transcoderUpdateEvent.feeShare = event.params.pendingFeeShare as BigInt;
transcoderUpdateEvent.save();
}
// Handler for TranscoderResigned events
export function transcoderResigned(event: TranscoderResigned): void {
let transcoder = Transcoder.load(event.params.transcoder.toHex());
let round = createOrLoadRound(event.block.number);
// Update transcoder
transcoder.active = false;
transcoder.status = "NotRegistered";
transcoder.delegator = null;
transcoder.save();
let tx =
Transaction.load(event.transaction.hash.toHex()) ||
new Transaction(event.transaction.hash.toHex());
tx.blockNumber = event.block.number;
tx.gasUsed = event.transaction.gasUsed;
tx.gasPrice = event.transaction.gasPrice;
tx.timestamp = event.block.timestamp.toI32();
tx.from = event.transaction.from.toHex();
tx.to = event.transaction.to.toHex();
tx.save();
let transcoderResignedEvent = new TranscoderResignedEvent(
makeEventId(event.transaction.hash, event.logIndex)
);
transcoderResignedEvent.transaction = event.transaction.hash.toHex();
transcoderResignedEvent.timestamp = event.block.timestamp.toI32();
transcoderResignedEvent.round = round.id;
transcoderResignedEvent.delegate = event.params.transcoder.toHex();
transcoderResignedEvent.save();
}
// Handler for TranscoderEvicted events
export function transcoderEvicted(event: TranscoderEvicted): void {
let transcoder = Transcoder.load(event.params.transcoder.toHex());
let round = createOrLoadRound(event.block.number);
// Update transcoder
transcoder.active = false;
// Apply store updates
transcoder.save();
let tx =
Transaction.load(event.transaction.hash.toHex()) ||
new Transaction(event.transaction.hash.toHex());
tx.blockNumber = event.block.number;
tx.gasUsed = event.transaction.gasUsed;
tx.gasPrice = event.transaction.gasPrice;
tx.timestamp = event.block.timestamp.toI32();
tx.from = event.transaction.from.toHex();
tx.to = event.transaction.to.toHex();
tx.save();
let transcoderEvictedEvent = new TranscoderEvictedEvent(
makeEventId(event.transaction.hash, event.logIndex)
);
transcoderEvictedEvent.transaction = event.transaction.hash.toHex();
transcoderEvictedEvent.timestamp = event.block.timestamp.toI32();
transcoderEvictedEvent.round = round.id;
transcoderEvictedEvent.delegate = event.params.transcoder.toHex();
transcoderEvictedEvent.save();
}
export function bond(call: BondCall): void {
// After LIP11 was deployed (at block 6192000), we no longer have to rely on
// this call handler to get the amount bonded.
// https://forum.livepeer.org/t/tributary-release-protocol-upgrade/354
if (call.block.number.le(BigInt.fromI32(6192000))) {
let bondingManager = BondingManager.bind(call.to);
let newDelegateAddress = call.inputs._to;
let delegatorAddress = call.from;
let oldDelegateAddress = EMPTY_ADDRESS;
let amount = convertToDecimal(call.inputs._amount);
let delegatorData = bondingManager.getDelegator(delegatorAddress);
let delegateData = bondingManager.getDelegator(newDelegateAddress);
let round = createOrLoadRound(call.block.number);
let transcoder = createOrLoadTranscoder(newDelegateAddress.toHex());
let delegate = createOrLoadDelegator(newDelegateAddress.toHex());
let delegator = createOrLoadDelegator(delegatorAddress.toHex());
let protocol = Protocol.load("0");
if (delegator.delegate) {
oldDelegateAddress = Address.fromString(delegator.delegate);
}
// If self delegating, set status and assign reference to self
if (delegatorAddress.toHex() == newDelegateAddress.toHex()) {
transcoder.status = "Registered";
transcoder.delegator = delegatorAddress.toHex();
}
// Changing delegate
if (
delegator.delegate != null &&
delegator.delegate != newDelegateAddress.toHex()
) {
let oldTranscoder = Transcoder.load(
oldDelegateAddress.toHex()
) as Transcoder;
let oldDelegate = Delegator.load(oldDelegateAddress.toHex()) as Delegator;
// if previous delegate was itself, set status and unassign reference to self
if (oldDelegateAddress.toHex() == delegatorAddress.toHex()) {
oldTranscoder.status = "NotRegistered";
oldTranscoder.delegator = null;
}
let oldDelegateData = bondingManager.getDelegator(
Address.fromString(oldTranscoder.id)
);
oldTranscoder.totalStake = convertToDecimal(oldDelegateData.value3);
oldDelegate.delegatedAmount = convertToDecimal(oldDelegateData.value3);
oldDelegate.save();
oldTranscoder.save();
// keep track of how much new stake was moved this round
round.movedStake = round.movedStake.plus(
convertToDecimal(oldDelegateData.value0).minus(amount)
);
// keep track of how much new stake was introduced this round
round.newStake = round.newStake.plus(amount);
round.save();
}
transcoder.totalStake = convertToDecimal(delegateData.value3);
delegate.delegatedAmount = convertToDecimal(delegateData.value3);
// delegator rebonding
if (!delegator.delegate && delegator.bondedAmount.gt(ZERO_BD)) {
delegator.unbonded = delegator.unbonded.minus(delegator.bondedAmount);
}
delegator.delegate = newDelegateAddress.toHex();
delegator.lastClaimRound = round.id;
delegator.bondedAmount = convertToDecimal(delegatorData.value0);
delegator.fees = convertToDecimal(delegatorData.value1);
delegator.startRound = delegatorData.value4;
delegator.principal = delegator.principal.plus(amount);
delegate.save();
delegator.save();
transcoder.save();
protocol.save();
let tx = new Transaction(call.transaction.hash.toHex());
tx.blockNumber = call.block.number;
tx.gasUsed = call.transaction.gasUsed;
tx.gasPrice = call.transaction.gasPrice;
tx.timestamp = call.block.timestamp.toI32();
tx.from = call.transaction.from.toHex();
tx.to = call.transaction.to.toHex();
tx.save();
let bondEvent = new BondEvent(
makeEventId(call.transaction.hash, call.transaction.index)
);
bondEvent.transaction = call.transaction.hash.toHex();
bondEvent.timestamp = call.block.timestamp.toI32();
bondEvent.round = round.id;
bondEvent.oldDelegate = oldDelegateAddress.toHex();
bondEvent.newDelegate = newDelegateAddress.toHex();
bondEvent.bondedAmount = convertToDecimal(delegatorData.value0);
bondEvent.additionalAmount = amount;
bondEvent.delegator = delegatorAddress.toHex();
bondEvent.save();
}
}
export function unbond(event: Unbond): void {
let bondingManager = BondingManager.bind(event.address);
let delegator = Delegator.load(event.params.delegator.toHex());
let transcoderAddress = delegator.delegate;
let round = createOrLoadRound(event.block.number);
let transcoder = Transcoder.load(transcoderAddress);
let delegate = Delegator.load(transcoderAddress);
let delegateData = bondingManager.getDelegator(
Address.fromString(transcoderAddress)
);
let protocol = Protocol.load("0");
let delegatorData = bondingManager.getDelegator(event.params.delegator);
transcoder.totalStake = convertToDecimal(delegateData.value3);
delegate.delegatedAmount = convertToDecimal(delegateData.value3);
// Delegator no longer bonded to anyone
delegator.delegate = null;
delegator.lastClaimRound = round.id;
delegator.bondedAmount = convertToDecimal(delegatorData.value0);
delegator.fees = convertToDecimal(delegatorData.value1);
delegator.startRound = delegatorData.value4;
delegator.unbonded = delegator.unbonded.plus(
convertToDecimal(delegatorData.value0)
);
// Apply store updates
delegate.save();
delegator.save();
transcoder.save();
protocol.save();
let tx =
Transaction.load(event.transaction.hash.toHex()) ||
new Transaction(event.transaction.hash.toHex());
tx.blockNumber = event.block.number;
tx.gasUsed = event.transaction.gasUsed;
tx.gasPrice = event.transaction.gasPrice;
tx.timestamp = event.block.timestamp.toI32();
tx.from = event.transaction.from.toHex();
tx.to = event.transaction.to.toHex();
tx.save();
let unbondEvent = new UnbondEvent(
makeEventId(event.transaction.hash, event.logIndex)
);
unbondEvent.transaction = event.transaction.hash.toHex();
unbondEvent.timestamp = event.block.timestamp.toI32();
unbondEvent.round = round.id;
unbondEvent.amount = convertToDecimal(delegatorData.value0);
unbondEvent.withdrawRound = delegatorData.value5;
unbondEvent.delegate = transcoderAddress;
unbondEvent.delegator = event.params.delegator.toHex();
unbondEvent.save();
}
export function claimEarnings(call: ClaimEarningsCall): void {
// The Streamflow release introduced an event emitter for EarningsClaimed, so
// we can ignore this call handler henceforth after the block in which the
// protocol was paused prior to the streamflow upgrade
if (call.block.number.le(BigInt.fromI32(9274414))) {
let delegatorAddress = call.from;
let endRound = call.inputs._endRound;
let round = createOrLoadRound(call.block.number);
let delegator = createOrLoadDelegator(delegatorAddress.toHex());
let bondingManager = BondingManager.bind(call.to);
let delegatorData = bondingManager.getDelegator(delegatorAddress);
let bondedAmount = delegator.bondedAmount;
let lastClaimRound = delegator.lastClaimRound;
delegator.bondedAmount = convertToDecimal(delegatorData.value0);
delegator.fees = convertToDecimal(delegatorData.value1);
delegator.lastClaimRound = endRound.toString();
delegator.save();
let tx =
Transaction.load(call.transaction.hash.toHex()) ||
new Transaction(call.transaction.hash.toHex());
tx.blockNumber = call.block.number;
tx.gasUsed = call.transaction.gasUsed;
tx.gasPrice = call.transaction.gasPrice;
tx.timestamp = call.block.timestamp.toI32();
tx.from = call.transaction.from.toHex();
tx.to = call.transaction.to.toHex();
tx.save();
let earningsClaimedEvent = new EarningsClaimedEvent(
makeEventId(call.transaction.hash, call.transaction.index)
);
earningsClaimedEvent.transaction = call.transaction.hash.toHex();
earningsClaimedEvent.timestamp = call.block.timestamp.toI32();
earningsClaimedEvent.round = round.id;
earningsClaimedEvent.delegate = delegator.id;
earningsClaimedEvent.delegator = delegatorAddress.toHex();
earningsClaimedEvent.startRound = integer.fromString(lastClaimRound);
earningsClaimedEvent.endRound = endRound.toString();
earningsClaimedEvent.rewardTokens = convertToDecimal(
delegatorData.value0
).minus(bondedAmount);
earningsClaimedEvent.fees = convertToDecimal(delegatorData.value1).minus(
delegator.fees
);
earningsClaimedEvent.save();
}
}
// Handler for WithdrawStake events
export function withdrawStake(event: WithdrawStake): void {
let delegator = Delegator.load(event.params.delegator.toHex());
let round = createOrLoadRound(event.block.number);
let tx =
Transaction.load(event.transaction.hash.toHex()) ||
new Transaction(event.transaction.hash.toHex());
tx.blockNumber = event.block.number;
tx.gasUsed = event.transaction.gasUsed;
tx.gasPrice = event.transaction.gasPrice;
tx.timestamp = event.block.timestamp.toI32();
tx.from = event.transaction.from.toHex();
tx.to = event.transaction.to.toHex();
tx.save();
let withdrawStakeEvent = new WithdrawStakeEvent(
makeEventId(event.transaction.hash, event.logIndex)
);
withdrawStakeEvent.transaction = event.transaction.hash.toHex();
withdrawStakeEvent.timestamp = event.block.timestamp.toI32();
withdrawStakeEvent.round = round.id;
withdrawStakeEvent.amount = delegator.bondedAmount;
withdrawStakeEvent.delegator = event.params.delegator.toHex();
withdrawStakeEvent.save();
delegator.bondedAmount = ZERO_BD;
delegator.save();
} | the_stack |
//@ts-check
///<reference path="devkit.d.ts" />
declare namespace DevKit {
namespace Formmsdyn_omnichannelconfiguration_Information {
interface tab_tab_skillbasedrouting_new_Sections {
tab_2_section_1_2: DevKit.Controls.Section;
tab_skillbasedrouting_section_2_3: DevKit.Controls.Section;
}
interface tab_tab_skillbasedrouting_new extends DevKit.Controls.ITab {
Section: tab_tab_skillbasedrouting_new_Sections;
}
interface Tabs {
tab_skillbasedrouting_new: tab_tab_skillbasedrouting_new;
}
interface Body {
Tab: Tabs;
/** Enable Skill Based Routing for Agents & Supervisors */
msdyn_IsSkillBasedRoutingEnabled: DevKit.Controls.Boolean;
/** This will enable agents to view and update skills for a conversation. */
msdyn_IsUpdateSkillsEnabled: DevKit.Controls.Boolean;
/** The name of the custom entity. */
msdyn_name: DevKit.Controls.String;
}
interface Grid {
RatingModelDetails: DevKit.Controls.Grid;
}
}
class Formmsdyn_omnichannelconfiguration_Information extends DevKit.IForm {
/**
* DynamicsCrm.DevKit form msdyn_omnichannelconfiguration_Information
* @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 msdyn_omnichannelconfiguration_Information */
Body: DevKit.Formmsdyn_omnichannelconfiguration_Information.Body;
/** The Grid of form msdyn_omnichannelconfiguration_Information */
Grid: DevKit.Formmsdyn_omnichannelconfiguration_Information.Grid;
}
namespace FormMasking_settings {
interface tab__DCC1EB86_7EF2_4FF4_8D56_2A0F28FD1B5E_Sections {
_26FF56C2_88FE_41F2_BE7F_AF3C273CFCE3: DevKit.Controls.Section;
_44EFFE7C_A18D_4D4C_B111_DB98E28BC808_SECTION_3: DevKit.Controls.Section;
}
interface tab_Self_service_settings_Sections {
_44EFFE7C_A18D_4D4C_B111_DB98E28BC808_SECTION_2: DevKit.Controls.Section;
}
interface tab__DCC1EB86_7EF2_4FF4_8D56_2A0F28FD1B5E extends DevKit.Controls.ITab {
Section: tab__DCC1EB86_7EF2_4FF4_8D56_2A0F28FD1B5E_Sections;
}
interface tab_Self_service_settings extends DevKit.Controls.ITab {
Section: tab_Self_service_settings_Sections;
}
interface Tabs {
_DCC1EB86_7EF2_4FF4_8D56_2A0F28FD1B5E: tab__DCC1EB86_7EF2_4FF4_8D56_2A0F28FD1B5E;
Self_service_settings: tab_Self_service_settings;
}
interface Body {
Tab: Tabs;
/** Enables supervisor assign feature for the org */
msdyn_enable_supervisor_assign: DevKit.Controls.Boolean;
/** Enables supervisor monitor feature for the org */
msdyn_enable_supervisor_monitor: DevKit.Controls.Boolean;
/** Enables self service feature for the org */
msdyn_enable_visitorjourney: DevKit.Controls.Boolean;
/** Mask agent data */
msdyn_maskforagent: DevKit.Controls.Boolean;
/** Mask customer data */
msdyn_maskforcustomer: DevKit.Controls.Boolean;
/** The name of the custom entity. */
msdyn_name: DevKit.Controls.String;
}
interface Grid {
MaskingRulesInSettings: DevKit.Controls.Grid;
}
}
class FormMasking_settings extends DevKit.IForm {
/**
* DynamicsCrm.DevKit form Masking_settings
* @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 Masking_settings */
Body: DevKit.FormMasking_settings.Body;
/** The Grid of form Masking_settings */
Grid: DevKit.FormMasking_settings.Grid;
}
namespace FormNotifications {
interface tab_missed_notification_settings_Sections {
missed_notifications_settings_section: DevKit.Controls.Section;
}
interface tab_notification_templates_Sections {
notification_templates_section: DevKit.Controls.Section;
}
interface tab_tab_sound_notification_settings_Sections {
tab_sound_notification_settings_section_3: DevKit.Controls.Section;
tab_sound_notification_settings_section_4: DevKit.Controls.Section;
}
interface tab_missed_notification_settings extends DevKit.Controls.ITab {
Section: tab_missed_notification_settings_Sections;
}
interface tab_notification_templates extends DevKit.Controls.ITab {
Section: tab_notification_templates_Sections;
}
interface tab_tab_sound_notification_settings extends DevKit.Controls.ITab {
Section: tab_tab_sound_notification_settings_Sections;
}
interface Tabs {
missed_notification_settings: tab_missed_notification_settings;
notification_templates: tab_notification_templates;
tab_sound_notification_settings: tab_tab_sound_notification_settings;
}
interface Body {
Tab: Tabs;
/** Setting to change agent status when a notification has been missed. */
msdyn_enable_missed_notifications: DevKit.Controls.Boolean;
/** Enable sound notifications feature */
msdyn_enablesoundnotifications: DevKit.Controls.Boolean;
/** Lookup to display inactive presence settings. */
msdyn_inactive_presence_lookup: DevKit.Controls.Lookup;
msdyn_missednotificationssubheading: DevKit.Controls.ActionCards;
/** Field to host sound form control */
msdyn_SoundFormControl: DevKit.Controls.String;
}
interface quickForm_missed_notification_presence_update_quick_view_form_Body {
msdyn_description: DevKit.Controls.QuickView;
msdyn_presencestatustext: DevKit.Controls.QuickView;
}
interface quickForm_missed_notification_presence_update_quick_view_form extends DevKit.Controls.IQuickView {
Body: quickForm_missed_notification_presence_update_quick_view_form_Body;
}
interface QuickForm {
missed_notification_presence_update_quick_view_form: quickForm_missed_notification_presence_update_quick_view_form;
}
interface Grid {
templates_grid: DevKit.Controls.Grid;
}
}
class FormNotifications extends DevKit.IForm {
/**
* DynamicsCrm.DevKit form Notifications
* @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 Notifications */
Body: DevKit.FormNotifications.Body;
/** The QuickForm of form Notifications */
QuickForm: DevKit.FormNotifications.QuickForm;
/** The Grid of form Notifications */
Grid: DevKit.FormNotifications.Grid;
}
namespace FormPersonal_quick_replies {
interface tab_personal_message_settings_Sections {
personal_messaages_settings_section: DevKit.Controls.Section;
}
interface tab_personal_message_settings extends DevKit.Controls.ITab {
Section: tab_personal_message_settings_Sections;
}
interface Tabs {
personal_message_settings: tab_personal_message_settings;
}
interface Body {
Tab: Tabs;
/** Enable personal messages feature for the org */
msdyn_isPersonalMessagesEnabled: DevKit.Controls.Boolean;
}
}
class FormPersonal_quick_replies extends DevKit.IForm {
/**
* DynamicsCrm.DevKit form Personal_quick_replies
* @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 Personal_quick_replies */
Body: DevKit.FormPersonal_quick_replies.Body;
}
namespace FormReal_Time_Translation_Settings {
interface tab_Real_Time_Translation_Sections {
RealTimeTranslation_section_2: DevKit.Controls.Section;
tab_3_section_1: DevKit.Controls.Section;
}
interface tab_Real_Time_Translation extends DevKit.Controls.ITab {
Section: tab_Real_Time_Translation_Sections;
}
interface Tabs {
Real_Time_Translation: tab_Real_Time_Translation;
}
interface Body {
Tab: Tabs;
/** Default language in which customer's messages are translated for an org */
msdyn_defaultAgentInputLanguage: DevKit.Controls.OptionSet;
/** Enable real time translation feature for the org */
msdyn_EnableRealTimeTranslation: DevKit.Controls.Boolean;
/** Webresource URL used for real time translation of the messages */
msdyn_translationwebresourceurl: DevKit.Controls.String;
WebResource_featureEnableTerms: DevKit.Controls.WebResource;
WebResource_ocpreviewterms: DevKit.Controls.WebResource;
}
}
class FormReal_Time_Translation_Settings extends DevKit.IForm {
/**
* DynamicsCrm.DevKit form Real_Time_Translation_Settings
* @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 Real_Time_Translation_Settings */
Body: DevKit.FormReal_Time_Translation_Settings.Body;
}
namespace FormSelf_service_settings {
interface tab__44EFFE7C_A18D_4D4C_B111_DB98E28BC808_Sections {
_311AD6D5_5179_4AC3_BE91_EF746DE66813: DevKit.Controls.Section;
}
interface tab_Self_service_settings_Sections {
_44EFFE7C_A18D_4D4C_B111_DB98E28BC808_SECTION_2: DevKit.Controls.Section;
}
interface tab__44EFFE7C_A18D_4D4C_B111_DB98E28BC808 extends DevKit.Controls.ITab {
Section: tab__44EFFE7C_A18D_4D4C_B111_DB98E28BC808_Sections;
}
interface tab_Self_service_settings extends DevKit.Controls.ITab {
Section: tab_Self_service_settings_Sections;
}
interface Tabs {
_44EFFE7C_A18D_4D4C_B111_DB98E28BC808: tab__44EFFE7C_A18D_4D4C_B111_DB98E28BC808;
Self_service_settings: tab_Self_service_settings;
}
interface Body {
Tab: Tabs;
/** Enables supervisor assign feature for the org */
msdyn_enable_supervisor_assign: DevKit.Controls.Boolean;
/** Enables supervisor monitor feature for the org */
msdyn_enable_supervisor_monitor: DevKit.Controls.Boolean;
/** Enables self service feature for the org */
msdyn_enable_visitorjourney: DevKit.Controls.Boolean;
/** The name of the custom entity. */
msdyn_name: DevKit.Controls.String;
}
}
class FormSelf_service_settings extends DevKit.IForm {
/**
* DynamicsCrm.DevKit form Self_service_settings
* @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 Self_service_settings */
Body: DevKit.FormSelf_service_settings.Body;
}
namespace FormSkill_based_routing_settings {
interface tab_tab_1_Sections {
tab_1_section_1: DevKit.Controls.Section;
tab_1_section_2: DevKit.Controls.Section;
}
interface tab_tab_1 extends DevKit.Controls.ITab {
Section: tab_tab_1_Sections;
}
interface Tabs {
tab_1: tab_tab_1;
}
interface Body {
Tab: Tabs;
/** This will enable agents to view and update skills for a conversation. */
msdyn_IsUpdateSkillsEnabled: DevKit.Controls.Boolean;
}
interface Grid {
RatingModelDetails: DevKit.Controls.Grid;
}
}
class FormSkill_based_routing_settings extends DevKit.IForm {
/**
* DynamicsCrm.DevKit form Skill_based_routing_settings
* @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 Skill_based_routing_settings */
Body: DevKit.FormSkill_based_routing_settings.Body;
/** The Grid of form Skill_based_routing_settings */
Grid: DevKit.FormSkill_based_routing_settings.Grid;
}
namespace FormSupervisor_settings {
interface tab__44EFFE7C_A18D_4D4C_B111_DB98E28BC808_Sections {
_26FF56C2_88FE_41F2_BE7F_AF3C273CFCE3: DevKit.Controls.Section;
}
interface tab_Supervisor_settings_Sections {
_44EFFE7C_A18D_4D4C_B111_DB98E28BC808_SECTION_2: DevKit.Controls.Section;
}
interface tab__44EFFE7C_A18D_4D4C_B111_DB98E28BC808 extends DevKit.Controls.ITab {
Section: tab__44EFFE7C_A18D_4D4C_B111_DB98E28BC808_Sections;
}
interface tab_Supervisor_settings extends DevKit.Controls.ITab {
Section: tab_Supervisor_settings_Sections;
}
interface Tabs {
_44EFFE7C_A18D_4D4C_B111_DB98E28BC808: tab__44EFFE7C_A18D_4D4C_B111_DB98E28BC808;
Supervisor_settings: tab_Supervisor_settings;
}
interface Body {
Tab: Tabs;
/** Enables supervisor assign feature for the org */
msdyn_enable_supervisor_assign: DevKit.Controls.Boolean;
/** Enables supervisor monitor feature for the org */
msdyn_enable_supervisor_monitor: DevKit.Controls.Boolean;
/** The name of the custom entity. */
msdyn_name: DevKit.Controls.String;
}
}
class FormSupervisor_settings extends DevKit.IForm {
/**
* DynamicsCrm.DevKit form Supervisor_settings
* @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 Supervisor_settings */
Body: DevKit.FormSupervisor_settings.Body;
}
class msdyn_omnichannelconfigurationApi {
/**
* DynamicsCrm.DevKit msdyn_omnichannelconfigurationApi
* @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;
/** Unique identifier of the user who created the record. */
CreatedBy: DevKit.WebApi.LookupValueReadonly;
/** Date and time when the record was created. */
CreatedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly;
/** Unique identifier of the delegate user who created the record. */
CreatedOnBehalfBy: DevKit.WebApi.LookupValueReadonly;
/** Sequence number of the import that created this record. */
ImportSequenceNumber: DevKit.WebApi.IntegerValue;
/** Unique identifier of the user who modified the record. */
ModifiedBy: DevKit.WebApi.LookupValueReadonly;
/** Date and time when the record was modified. */
ModifiedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly;
/** Unique identifier of the delegate user who modified the record. */
ModifiedOnBehalfBy: DevKit.WebApi.LookupValueReadonly;
/** Default language in which customer's messages are translated for an org */
msdyn_defaultAgentInputLanguage: DevKit.WebApi.OptionSetValue;
/** Setting to change advance entity routing for the org. */
msdyn_enable_advance_entity_routing: DevKit.WebApi.BooleanValue;
/** Setting to change agent status when a notification has been missed. */
msdyn_enable_missed_notifications: DevKit.WebApi.BooleanValue;
/** Enables supervisor assign feature for the org */
msdyn_enable_supervisor_assign: DevKit.WebApi.BooleanValue;
/** Enables supervisor monitor feature for the org */
msdyn_enable_supervisor_monitor: DevKit.WebApi.BooleanValue;
/** Setting to change unified routing diagnostic for the org. */
msdyn_enable_unified_routing_diagnostic: DevKit.WebApi.BooleanValue;
/** Enables self service feature for the org */
msdyn_enable_visitorjourney: DevKit.WebApi.BooleanValue;
/** Enable real time translation feature for the org */
msdyn_EnableRealTimeTranslation: DevKit.WebApi.BooleanValue;
/** Enable sound notifications feature */
msdyn_enablesoundnotifications: DevKit.WebApi.BooleanValue;
/** Lookup to display inactive presence settings. */
msdyn_inactive_presence_lookup: DevKit.WebApi.LookupValue;
msdyn_isdefaultpersonamapped: DevKit.WebApi.BooleanValue;
/** Allow agents to create personal sound settings */
msdyn_ispersonalizationofsoundenabled: DevKit.WebApi.BooleanValue;
/** Enable personal messages feature for the org */
msdyn_isPersonalMessagesEnabled: DevKit.WebApi.BooleanValue;
msdyn_ispersonasecurityrolemappingenabled: DevKit.WebApi.BooleanValue;
/** Enable Skill Based Routing for Agents & Supervisors */
msdyn_IsSkillBasedRoutingEnabled: DevKit.WebApi.BooleanValue;
/** This will enable agents to view and update skills for a conversation. */
msdyn_IsUpdateSkillsEnabled: DevKit.WebApi.BooleanValue;
/** Mask agent data */
msdyn_maskforagent: DevKit.WebApi.BooleanValue;
/** Mask customer data */
msdyn_maskforcustomer: DevKit.WebApi.BooleanValue;
/** The name of the custom entity. */
msdyn_name: DevKit.WebApi.StringValue;
/** Unique identifier for entity instances */
msdyn_omnichannelconfigurationId: DevKit.WebApi.GuidValue;
/** Field to host sound form control */
msdyn_SoundFormControl: DevKit.WebApi.StringValue;
/** Webresource URL used for real time translation of the messages */
msdyn_translationwebresourceurl: DevKit.WebApi.StringValue;
/** Unique identifier for the organization */
OrganizationId: DevKit.WebApi.LookupValueReadonly;
/** Date and time that the record was migrated. */
OverriddenCreatedOn_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue;
/** Status of the Omnichannel Configuration */
statecode: DevKit.WebApi.OptionSetValue;
/** Reason for the status of the Omnichannel Configuration */
statuscode: DevKit.WebApi.OptionSetValue;
/** For internal use only. */
TimeZoneRuleVersionNumber: DevKit.WebApi.IntegerValue;
/** Time zone code that was in use when the record was created. */
UTCConversionTimeZoneCode: DevKit.WebApi.IntegerValue;
/** Version Number */
VersionNumber: DevKit.WebApi.BigIntValueReadonly;
}
}
declare namespace OptionSet {
namespace msdyn_omnichannelconfiguration {
enum msdyn_defaultAgentInputLanguage {
/** 1025 */
Arabic_Saudi_Arabia,
/** 1069 */
Basque_Spain,
/** 1026 */
Bulgarian_Bulgaria,
/** 1027 */
Catalan_Spain,
/** 2052 */
Chinese_China,
/** 3076 */
Chinese_Hong_Kong,
/** 1050 */
Croatian_Croatia,
/** 1029 */
Czech_Czech_Republic,
/** 1030 */
Danish_Denmark,
/** 1043 */
Dutch_Netherlands,
/** 1033 */
English_United_States,
/** 1061 */
Estonian_Estonia,
/** 1035 */
Finnish_Finland,
/** 1036 */
French_France,
/** 1110 */
Galician_Spain,
/** 1031 */
German_Germany,
/** 1032 */
Greek_Greece,
/** 1037 */
Hebrew_Israel,
/** 1081 */
Hindi_India,
/** 1038 */
Hungarian_Hungary,
/** 1057 */
Indonesian_Indonesia,
/** 1040 */
Italian_Italy,
/** 1041 */
Japanese_Japan,
/** 1087 */
Kazakh_Kazakhstan,
/** 1042 */
Korean_Korea,
/** 1062 */
Latvian_Latvia,
/** 1063 */
Lithuanian_Lithuania,
/** 1086 */
Malay_Malaysia,
/** 1044 */
Norwegian_Bokmal_Norway,
/** 1045 */
Polish_Poland,
/** 1046 */
Portuguese_Brazil,
/** 2070 */
Portuguese_Portugal,
/** 1048 */
Romanian_Romania,
/** 1049 */
Russian_Russia,
/** 3098 */
Serbian_Cyrillic_Serbia,
/** 2074 */
Serbian_Latin_Serbia,
/** 1051 */
Slovak_Slovakia,
/** 1060 */
Slovenian_Slovenia,
/** 3082 */
Spanish_Spain,
/** 1053 */
Swedish_Sweden,
/** 1054 */
Thai_Thailand,
/** 1055 */
Turkish_Turkey,
/** 1058 */
Ukrainian_Ukraine,
/** 1066 */
Vietnamese_Vietnam
}
enum statecode {
/** 0 */
Active,
/** 1 */
Inactive
}
enum statuscode {
/** 1 */
Active,
/** 2 */
Inactive
}
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':['Information','Masking settings','Notifications','Personal quick replies','Real Time Translation Settings','Self service settings','Skill based routing settings','Supervisor settings'],'JsWebApi':true,'IsDebugForm':true,'IsDebugWebApi':true,'Version':'2.12.31','JsFormVersion':'v2'} | the_stack |
import React from 'react';
import Navigation, { NavigateEvent, BackEvent } from './Navigation';
import AnimationLayer from './AnimationLayer';
import GhostLayer from './GhostLayer';
import { ScreenChild } from '.';
import {AnimationConfig, AnimationKeyframeEffectConfig, ReducedAnimationConfigSet, SwipeDirection} from './common/types';
import RouterData, {RoutesData, RouterDataContext} from './RouterData';
import AnimationLayerData, {AnimationLayerDataContext} from './AnimationLayerData';
interface Config {
animation: ReducedAnimationConfigSet | AnimationConfig | AnimationKeyframeEffectConfig;
defaultRoute?: string;
swipeAreaWidth?: number;
minFlingVelocity?: number;
hysteresis?: number;
disableDiscovery?: boolean;
swipeDirection?: SwipeDirection;
disableBrowserRouting?: boolean;
paramsSerialiser?(params: {[key:string]: any}): string;
paramsDeserialiser?(queryString: string): {[key:string]: any};
}
interface RouterProps {
config: Config;
children: ScreenChild | ScreenChild[];
}
interface RouterState {
currentPath: string;
backNavigating: boolean;
gestureNavigating: boolean;
routesData: RoutesData;
implicitBack: boolean;
}
export function useNavigation() {
const routerData = React.useContext(RouterDataContext);
return routerData.navigation;
}
export default class Router extends React.Component<RouterProps, RouterState> {
private navigation = new Navigation(this.props.config.disableBrowserRouting || false, this.props.config.defaultRoute || null);
private config: Config;
private _routerData: RouterData;
private animationLayerData = new AnimationLayerData();
private onBackListener = this.onBack.bind(this) as EventListener;
private onNavigateListener = this.onNavigate.bind(this) as EventListener;
private onPopStateListener = this.onPopstate.bind(this);
static defaultProps = {
config: {
animation: {
in: {
type: "none",
duration: 0,
}
}
}
}
constructor(props: RouterProps) {
super(props);
if (props.config) {
this.config = props.config;
} else {
this.config = {
animation: {
in: {
type: "none",
duration: 0,
},
out: {
type: "none",
duration: 0,
}
}
}
}
this._routerData = new RouterData();
this._routerData.navigation = this.navigation;
if ('in' in this.config.animation) {
this._routerData.animation = {
in: this.config.animation.in,
out: this.config.animation.out || this.config.animation.in
};
} else {
this._routerData.animation = {
in: this.config.animation,
out: this.config.animation
};
}
}
state: RouterState = {
currentPath: "",
backNavigating: false,
gestureNavigating: false,
routesData: new Map<string | RegExp, any>(),
implicitBack: false
}
componentDidMount() {
// get url search params and append to existing route params
this.navigation.paramsDeserialiser = this.config.paramsDeserialiser;
this.navigation.paramsSerialiser = this.config.paramsSerialiser;
const searchParams = this.navigation.searchParamsToObject(window.location.search);
const routesData = this.state.routesData;
if (searchParams) {
routesData.set(this.navigation.location.pathname, {
...this.state.routesData.get(this.navigation.location.pathname),
params: searchParams
});
}
let currentPath = this.navigation.location.pathname;
if (this.props.config.defaultRoute && this.navigation.location.pathname === '/' && this.props.config.defaultRoute !== '/') {
this.navigation.navigate(this.props.config.defaultRoute);
currentPath = this.props.config.defaultRoute;
}
this._routerData.routesData = this.state.routesData;
this._routerData.paramsDeserialiser = this.props.config.paramsDeserialiser;
this._routerData.paramsSerialiser = this.props.config.paramsSerialiser;
this.setState({currentPath: currentPath, routesData: routesData});
this._routerData.currentPath = this.navigation.location.pathname;
window.addEventListener('go-back', this.onBackListener, true);
window.addEventListener('popstate', this.onPopStateListener, true);
window.addEventListener('navigate', this.onNavigateListener, true);
}
componentWillUnmount() {
window.removeEventListener('navigate', this.onNavigateListener);
window.removeEventListener('popstate', this.onPopStateListener);
window.removeEventListener('go-back', this.onBackListener);
}
private onAnimationEnd() {
if (this.state.backNavigating) {
this._routerData.backNavigating = false;
this.setState({backNavigating: false});
}
}
onPopstate(e: Event) {
e.preventDefault();
if (window.location.pathname === this.navigation.history.previous) {
if (!this.state.implicitBack) {
this.setState({backNavigating: true});
this._routerData.backNavigating = true;
} else {
this.setState({implicitBack: false});
}
this.navigation.implicitBack();
} else {
if (!this.state.backNavigating && !this.state.implicitBack) {
this.navigation.implicitNavigate(window.location.pathname);
}
if (this.state.implicitBack) {
this.setState({implicitBack: false});
}
}
window.addEventListener('page-animation-end', this.onAnimationEnd.bind(this), {once: true});
this._routerData.currentPath = window.location.pathname;
this.setState({currentPath: window.location.pathname});
}
onBack(e: BackEvent) {
this.setState({backNavigating: true});
let pathname = this.navigation.location.pathname;
// if (this.config.disableBrowserRouting) {
// pathname = this.navigation.history.current || pathname;
// }
if (e.detail.replaceState && !this.config.disableBrowserRouting) { // replaced state with default route
this._routerData.currentPath = pathname;
this.setState({currentPath: pathname});
}
if (this.config.disableBrowserRouting) {
this._routerData.currentPath = pathname;
this.setState({currentPath: pathname});
if (this.state.implicitBack) {
this.setState({implicitBack: false});
}
}
window.addEventListener('page-animation-end', this.onAnimationEnd.bind(this), {once: true});
this._routerData.backNavigating = true;
}
onNavigate(e: NavigateEvent) {
e.preventDefault();
const currentPath = e.detail.route;
this._routerData.currentPath = currentPath;
if (e.detail.routeParams) {
const routesData = this.state.routesData;
//store per route data in object
//with pathname as key and route data as value
routesData.set(currentPath, {
params: e.detail.routeParams
});
this._routerData.routesData = routesData;
this.setState({routesData: routesData}, () => {
this.setState({currentPath: currentPath});
});
} else {
this.setState({currentPath: currentPath});
}
}
onGestureNavigationStart = () => {
this._routerData.gestureNavigating = true;
this.setState({gestureNavigating: true});
}
onGestureNavigationEnd = () => {
this._routerData.gestureNavigating = false;
this.setState({implicitBack: true, gestureNavigating: false}, () => {
this.navigation.goBack();
this.setState({backNavigating: false});
this._routerData.backNavigating = false;
});
}
render() {
return (
<div className="react-motion-router" style={{width: '100%', height: '100%', position: 'relative'}}>
<RouterDataContext.Provider value={this._routerData}>
<AnimationLayerDataContext.Provider value={this.animationLayerData}>
<GhostLayer
instance={(instance: GhostLayer | null) => {
this._routerData.ghostLayer = instance;
}}
backNavigating={this.state.backNavigating}
/>
<AnimationLayer
disableBrowserRouting={this.props.config.disableBrowserRouting || false}
disableDiscovery={this.props.config.disableDiscovery || false}
hysteresis={this.props.config.hysteresis || 50}
minFlingVelocity={this.props.config.minFlingVelocity || 400}
swipeAreaWidth={this.props.config.swipeAreaWidth || 100}
swipeDirection={this.props.config.swipeDirection || 'right'}
navigation={this._routerData.navigation}
currentPath={this.state.currentPath}
backNavigating={this.state.backNavigating}
lastPath={this.navigation.history.previous}
onGestureNavigationStart={this.onGestureNavigationStart}
onGestureNavigationEnd={this.onGestureNavigationEnd}
>
{this.props.children}
</AnimationLayer>
</AnimationLayerDataContext.Provider>
</RouterDataContext.Provider>
</div>
);
}
} | the_stack |
import React from 'react';
import renderer from 'react-test-renderer';
import { cleanup, fireEvent, render } from '@testing-library/react';
import '@testing-library/jest-dom';
import { expectFnCalled } from '@test/utils';
import { EditorTree, IOpenEditProps } from '../explore/editorTree';
import {
editorTreeActiveItemClassName,
editorTreeGroupClassName,
} from '../explore/base';
import { constants } from 'mo/services/builtinService/const';
const PaneEditorTree = (props: Omit<IOpenEditProps, 'panel'>) => {
return <EditorTree panel={{ id: 'test', name: 'test' }} {...props} />;
};
const mockTab1 = {
id: 'tab1',
name: 'tab1',
data: {
path: 'tab',
},
};
const mockTab2 = {
id: 'tab2',
name: 'tab2',
data: {
path: 'tab',
},
};
const TAB1_PATH = `${mockTab1.data.path}/${mockTab1.name}`;
const TAB2_PATH = `${mockTab2.data.path}/${mockTab2.name}`;
const mockGroups = [
{
id: 1,
tab: {
id: 'tab1',
name: 'tab1',
},
data: [mockTab1, mockTab2],
},
];
// mock Toolbar component
jest.mock('mo/components/toolbar', () => {
const originalModule = jest.requireActual('mo/components/toolbar');
return {
...originalModule,
Toolbar: ({ onClick, data = [] }) => (
<div data-testid="toolbar">
{data.map((item, index) => (
<span key={index} onClick={(e) => onClick(e, item)}>
toolbar-{index}
</span>
))}
</div>
),
};
});
// to mock useRef
jest.mock('react', () => {
const originReact = jest.requireActual('react');
return {
...originReact,
useRef: jest.fn(() => ({
current: null,
})),
};
});
describe('The EditorTree Component', () => {
afterEach(cleanup);
test('Match Snapshot', () => {
const component = renderer.create(
<PaneEditorTree groups={mockGroups} />
);
expect(component.toJSON()).toMatchSnapshot();
});
test('Should get null without groups', () => {
const { container } = render(<PaneEditorTree />);
expect(container.innerHTML).toBe('');
});
test('Should not render title without path in data', () => {
const { container } = render(
<PaneEditorTree
groups={[
{
id: 1,
tab: {
id: 'tab1',
name: 'tab1',
},
data: [
{
id: 'tab1',
name: 'tab1',
},
{
id: 'tab2',
name: 'tab2',
},
],
},
]}
/>
);
expect(container.querySelector("*[title='tab/tab1']")).toBeNull();
});
test('Should support to active the pane', () => {
const { getByTitle } = render(
<PaneEditorTree groups={mockGroups} current={mockGroups[0]} />
);
const tab1 = getByTitle('tab/tab1');
expect(tab1.classList).toContain(editorTreeActiveItemClassName);
});
test('Should support to close tab', () => {
expectFnCalled((testFn) => {
const { getByTitle } = render(
<PaneEditorTree
groups={mockGroups}
onClose={testFn}
current={mockGroups[0]}
/>
);
const tab1 = getByTitle(TAB1_PATH);
fireEvent.click(tab1.querySelector('span.codicon-close')!);
expect(testFn.mock.calls[0][0]).toBe(mockTab1.name);
expect(testFn.mock.calls[0][1]).toBe(1);
});
});
test('Should support to contextMenu event', () => {
const contextMenu = {
id: 'test',
name: 'menu',
};
expectFnCalled((contextMenuFn) => {
const { getByTitle, getByRole } = render(
<PaneEditorTree
groups={mockGroups}
current={mockGroups[0]}
contextMenu={[contextMenu]}
onContextMenu={contextMenuFn}
/>
);
const tab1 = getByTitle(TAB1_PATH);
fireEvent.contextMenu(tab1);
const menu = getByRole('menu');
expect(menu).toBeInTheDocument();
fireEvent.click(menu.firstElementChild!);
expect(contextMenuFn.mock.calls[0][0]).toEqual(
expect.objectContaining(contextMenu)
);
expect(contextMenuFn.mock.calls[0][1]).toEqual(1);
expect(contextMenuFn.mock.calls[0][2]).toEqual(mockTab1);
});
});
test('Should support to select tab', () => {
expectFnCalled((selectFn) => {
const { getByTitle } = render(
<PaneEditorTree
groups={mockGroups}
current={mockGroups[0]}
onSelect={selectFn}
/>
);
const tab1 = getByTitle(TAB1_PATH);
fireEvent.click(tab1);
// same current tab won't triiger onSelect event
expect(selectFn).not.toBeCalled();
const tab2 = getByTitle(TAB2_PATH);
fireEvent.click(tab2);
});
});
test('Should not to scroll into view when scollerHeight is invalid', () => {
const mockScroll = jest.fn();
(React.useRef as jest.Mock).mockImplementation(() => ({
current: { scrollHeight: 100, scrollTo: mockScroll },
}));
const current = mockGroups[0];
render(<PaneEditorTree groups={mockGroups} current={current} />);
expect(mockScroll).not.toBeCalled();
});
test('Should scroll into view when add an active tab', () => {
const mockScroll = jest.fn();
(React.useRef as jest.Mock).mockImplementation(() => ({
current: { scrollHeight: 200, scrollTo: mockScroll },
}));
const current = mockGroups[0];
render(<PaneEditorTree groups={mockGroups} current={current} />);
expect(mockScroll).toBeCalled();
});
});
const multipleGroups = [
{
id: 1,
tab: {
id: 'tab1',
name: 'tab1',
},
data: [mockTab1, mockTab2],
},
{
id: 2,
tab: {
id: 'tab1',
name: 'tab1',
},
data: [mockTab1, mockTab2],
},
];
describe('The EditorTree Component With multiple groups', () => {
afterEach(cleanup);
test('Match Snapshot', () => {
const component = renderer.create(
<PaneEditorTree groups={multipleGroups} />
);
expect(component.toJSON()).toMatchSnapshot();
});
test('Should focus the first child in group when click group title', () => {
expectFnCalled((selectFn) => {
const { container } = render(
<PaneEditorTree
groups={multipleGroups}
current={multipleGroups[0]}
onSelect={selectFn}
/>
);
const groups = container.querySelectorAll(
`.${editorTreeGroupClassName}`
);
expect(groups).toHaveLength(2);
const group1 = groups[0];
fireEvent.click(group1);
expect(
(group1.nextElementSibling! as HTMLDivElement).focus
).toBeTruthy();
expect(selectFn.mock.calls[0][0]).toBe(mockTab1.name);
expect(selectFn.mock.calls[0][1]).toBe(multipleGroups[0].id);
});
});
test('Should support trigger contextMenu event in group title', () => {
const contextMenu = {
id: 'test',
name: 'menu',
};
expectFnCalled((contextMenuFn) => {
const { container, getByRole } = render(
<PaneEditorTree
groups={multipleGroups}
current={multipleGroups[0]}
headerContextMenu={[contextMenu]}
onContextMenu={contextMenuFn}
/>
);
const group1 = container.querySelector(
`.${editorTreeGroupClassName}`
);
fireEvent.contextMenu(group1!);
const menu = getByRole('menu');
expect(menu).toBeInTheDocument();
fireEvent.click(menu.firstElementChild!);
expect(contextMenuFn.mock.calls[0][0]).toEqual(
expect.objectContaining(contextMenu)
);
expect(contextMenuFn.mock.calls[0][1]).toEqual(
multipleGroups[0].id
);
expect(contextMenuFn.mock.calls[0][2]).toBeUndefined();
});
});
test('Should have a toolbar in group title', () => {
const closeMockFn = jest.fn();
const saveMockFn = jest.fn();
const toolbarMockFn = jest.fn();
const { getAllByTestId } = render(
<PaneEditorTree
groups={multipleGroups}
current={multipleGroups[0]}
groupToolbar={[
{
id: constants.EXPLORER_TOGGLE_SAVE_GROUP,
title: 'Save Group',
icon: 'save-all',
},
{
id: constants.EXPLORER_TOGGLE_CLOSE_GROUP_EDITORS,
title: 'Close Group Editors',
icon: 'close-all',
},
{
id: 'test',
title: 'testing',
},
]}
onCloseGroup={closeMockFn}
onSaveGroup={saveMockFn}
onToolbarClick={toolbarMockFn}
/>
);
const toolbars = getAllByTestId('toolbar');
expect(toolbars).toHaveLength(multipleGroups.length);
const index = 0;
let triggerBtn = toolbars[index].firstElementChild!;
fireEvent.click(triggerBtn);
// first button is for saving
expect(saveMockFn).toBeCalled();
expect(saveMockFn.mock.calls[0][0]).toBe(multipleGroups[index].id);
triggerBtn = triggerBtn.nextElementSibling!;
fireEvent.click(triggerBtn);
// next button is for closing
expect(closeMockFn).toBeCalled();
expect(closeMockFn.mock.calls[0][0]).toBe(multipleGroups[index].id);
triggerBtn = triggerBtn.nextElementSibling!;
fireEvent.click(triggerBtn);
// last button is extra button
expect(toolbarMockFn).toBeCalled();
expect(toolbarMockFn.mock.calls[0][0]).toEqual({
id: 'test',
title: 'testing',
});
expect(toolbarMockFn.mock.calls[0][1]).toBe(multipleGroups[index].id);
});
}); | the_stack |
import merge from 'lodash.merge'
import logger from '@wdio/logger'
import {
WebDriverProtocol, MJsonWProtocol, JsonWProtocol, AppiumProtocol, ChromiumProtocol,
SauceLabsProtocol, SeleniumProtocol, GeckoProtocol
} from '@wdio/protocols'
import Protocols from '@wdio/protocols'
import { Options, Capabilities } from '@wdio/types'
import RequestFactory from './request/factory'
import { WebDriverResponse } from './request'
import command from './command'
import { transformCommandLogResult } from '@wdio/utils'
import { VALID_CAPS, REG_EXPS } from './constants'
import type { JSONWPCommandError, SessionFlags } from './types'
const log = logger('webdriver')
const BROWSER_DRIVER_ERRORS = [
'unknown command: wd/hub/session', // chromedriver
'HTTP method not allowed', // geckodriver
"'POST /wd/hub/session' was not found.", // safaridriver
'Command not found' // iedriver
]
/**
* start browser session with WebDriver protocol
*/
export async function startWebDriverSession (params: Options.WebDriver): Promise<{ sessionId: string, capabilities: Capabilities.DesiredCapabilities }> {
/**
* validate capabilities to check if there are no obvious mix between
* JSONWireProtocol and WebDriver protoocol, e.g.
*/
if (params.capabilities) {
const extensionCaps = Object.keys(params.capabilities).filter((cap) => cap.includes(':'))
const invalidWebDriverCaps = Object.keys(params.capabilities)
.filter((cap) => !VALID_CAPS.includes(cap) && !cap.includes(':'))
/**
* if there are vendor extensions, e.g. sauce:options or appium:app
* used (only WebDriver compatible) and caps that aren't defined
* in the WebDriver spec
*/
if (extensionCaps.length && invalidWebDriverCaps.length) {
throw new Error(
`Invalid or unsupported WebDriver capabilities found ("${invalidWebDriverCaps.join('", "')}"). ` +
'Ensure to only use valid W3C WebDriver capabilities (see https://w3c.github.io/webdriver/#capabilities).' +
'If you run your tests on a remote vendor, like Sauce Labs or BrowserStack, make sure that you put them ' +
'into vendor specific capabilities, e.g. "sauce:options" or "bstack:options". Please reach out to ' +
'to your vendor support team if you have further questions.'
)
}
}
/**
* the user could have passed in either w3c style or jsonwp style caps
* and we want to pass both styles to the server, which means we need
* to check what style the user sent in so we know how to construct the
* object for the other style
*/
const [w3cCaps, jsonwpCaps] = params.capabilities && (params.capabilities as Capabilities.W3CCapabilities).alwaysMatch
/**
* in case W3C compliant capabilities are provided
*/
? [params.capabilities, (params.capabilities as Capabilities.W3CCapabilities).alwaysMatch]
/**
* otherwise assume they passed in jsonwp-style caps (flat object)
*/
: [{ alwaysMatch: params.capabilities, firstMatch: [{}] }, params.capabilities]
const sessionRequest = RequestFactory.getInstance(
'POST',
'/session',
{
capabilities: w3cCaps, // W3C compliant
desiredCapabilities: jsonwpCaps // JSONWP compliant
}
)
let response
try {
response = await sessionRequest.makeRequest(params)
} catch (err: any) {
log.error(err)
const message = getSessionError(err, params)
throw new Error('Failed to create session.\n' + message)
}
const sessionId = response.value.sessionId || response.sessionId
/**
* save actual receveived session details
*/
params.capabilities = response.value.capabilities || response.value
return { sessionId, capabilities: params.capabilities as Capabilities.DesiredCapabilities }
}
/**
* check if WebDriver requests was successful
* @param {Number} statusCode status code of request
* @param {Object} body body payload of response
* @return {Boolean} true if request was successful
*/
export function isSuccessfulResponse (statusCode?: number, body?: WebDriverResponse) {
/**
* response contains a body
*/
if (!body || typeof body.value === 'undefined') {
log.debug('request failed due to missing body')
return false
}
/**
* ignore failing element request to enable lazy loading capability
*/
if (
body.status === 7 && body.value && body.value.message &&
(
body.value.message.toLowerCase().startsWith('no such element') ||
// Appium
body.value.message === 'An element could not be located on the page using the given search parameters.' ||
// Internet Explorter
body.value.message.toLowerCase().startsWith('unable to find element')
)
) {
return true
}
/**
* if it has a status property, it should be 0
* (just here to stay backwards compatible to the jsonwire protocol)
*/
if (body.status && body.status !== 0) {
log.debug(`request failed due to status ${body.status}`)
return false
}
const hasErrorResponse = body.value && (body.value.error || body.value.stackTrace || body.value.stacktrace)
/**
* check status code
*/
if (statusCode === 200 && !hasErrorResponse) {
return true
}
/**
* if an element was not found we don't flag it as failed request because
* we lazy load it
*/
if (statusCode === 404 && body.value && body.value.error === 'no such element') {
return true
}
/**
* that has no error property (Appium only)
*/
if (hasErrorResponse) {
log.debug('request failed due to response error:', body.value.error)
return false
}
return true
}
/**
* creates the base prototype for the webdriver monad
*/
export function getPrototype ({ isW3C, isChrome, isFirefox, isMobile, isSauce, isSeleniumStandalone }: Partial<SessionFlags>) {
const prototype: Record<string, PropertyDescriptor> = {}
const ProtocolCommands: Protocols.Protocol = merge(
/**
* if mobile apply JSONWire and WebDriver protocol because
* some legacy JSONWire commands are still used in Appium
* (e.g. set/get geolocation)
*/
isMobile
? merge({}, JsonWProtocol, WebDriverProtocol)
: isW3C ? WebDriverProtocol : JsonWProtocol,
/**
* only apply mobile protocol if session is actually for mobile
*/
isMobile ? merge({}, MJsonWProtocol, AppiumProtocol) : {},
/**
* only apply special Chrome commands if session is using Chrome
*/
isChrome ? ChromiumProtocol : {},
/**
* only apply special Firefox commands if session is using Firefox
*/
isFirefox ? GeckoProtocol : {},
/**
* only Sauce Labs specific vendor commands
*/
isSauce ? SauceLabsProtocol : {},
/**
* only apply special commands when running tests using
* Selenium Grid or Selenium Standalone server
*/
isSeleniumStandalone ? SeleniumProtocol : {}
)
for (const [endpoint, methods] of Object.entries(ProtocolCommands)) {
for (const [method, commandData] of Object.entries(methods)) {
prototype[commandData.command] = { value: command(method, endpoint, commandData, isSeleniumStandalone) }
}
}
return prototype
}
/**
* helper method to determine the error from webdriver response
* @param {Object} body body object
* @return {Object} error
*/
export function getErrorFromResponseBody (body: any) {
if (!body) {
return new Error('Response has empty body')
}
if (typeof body === 'string' && body.length) {
return new Error(body)
}
if (typeof body !== 'object') {
return new Error('Unknown error')
}
return new CustomRequestError(body)
}
//Exporting for testability
export class CustomRequestError extends Error {
constructor(body: WebDriverResponse) {
const errorObj = body.value || body
super(errorObj.message || errorObj.class || 'unknown error')
if (errorObj.error) {
this.name = errorObj.error
} else if (errorObj.message && errorObj.message.includes('stale element reference')) {
this.name = 'stale element reference'
} else {
this.name = errorObj.name || 'WebDriver Error'
}
if (errorObj.stacktrace) {
this.stack = errorObj.stacktrace
}
}
}
/**
* return all supported flags and return them in a format so we can attach them
* to the instance protocol
* @param {Object} options driver instance or option object containing these flags
* @return {Object} prototype object
*/
export function getEnvironmentVars({ isW3C, isMobile, isIOS, isAndroid, isChrome, isFirefox, isSauce, isSeleniumStandalone }: Partial<SessionFlags>) {
return {
isW3C: { value: isW3C },
isMobile: { value: isMobile },
isIOS: { value: isIOS },
isAndroid: { value: isAndroid },
isFirefox: { value: isFirefox },
isChrome: { value: isChrome },
isSauce: { value: isSauce },
isSeleniumStandalone: { value: isSeleniumStandalone }
}
}
/**
* get human readable message from response error
* @param {Error} err response error
*/
export const getSessionError = (err: JSONWPCommandError, params: Partial<Options.WebDriver> = {}) => {
// browser driver / service is not started
if (err.code === 'ECONNREFUSED') {
return `Unable to connect to "${params.protocol}://${params.hostname}:${params.port}${params.path}", make sure browser driver is running on that address.` +
'\nIf you use services like chromedriver see initialiseServices logs above or in wdio.log file as the service might had problems to start the driver.'
}
if (err.message === 'unhandled request') {
return 'The browser driver couldn\'t start the session. Make sure you have set the "path" correctly!'
}
if (!err.message) {
return 'See wdio.* logs for more information.'
}
// wrong path: selenium-standalone
if (err.message.includes('Whoops! The URL specified routes to this help page.')) {
return "It seems you are running a Selenium Standalone server and point to a wrong path. Please set `path: '/wd/hub'` in your wdio.conf.js!"
}
// wrong path: chromedriver, geckodriver, etc
if (BROWSER_DRIVER_ERRORS.some(m => err && err.message && err.message.includes(m))) {
return "Make sure to set `path: '/'` in your wdio.conf.js!"
}
// edge driver on localhost
if (err.message.includes('Bad Request - Invalid Hostname') && err.message.includes('HTTP Error 400')) {
return "Run edge driver on 127.0.0.1 instead of localhost, ex: --host=127.0.0.1, or set `hostname: 'localhost'` in your wdio.conf.js"
}
const w3cCapMessage = '\nMake sure to add vendor prefix like "goog:", "appium:", "moz:", etc to non W3C capabilities.' +
'\nSee more https://www.w3.org/TR/webdriver/#capabilities'
// Illegal w3c capability passed to selenium standalone
if (err.message.includes('Illegal key values seen in w3c capabilities')) {
return err.message + w3cCapMessage
}
// wrong host/port, port in use, illegal w3c capability passed to selenium grid
if (err.message === 'Response has empty body') {
return 'Make sure to connect to valid hostname:port or the port is not in use.' +
'\nIf you use a grid server ' + w3cCapMessage
}
if (err.message.includes('failed serving request POST /wd/hub/session: Unauthorized') && params.hostname?.endsWith('saucelabs.com')) {
return 'Session request was not authorized because you either did provide a wrong access key or tried to run ' +
'in a region that has not been enabled for your user. If have registered a free trial account it is connected ' +
'to a specific region. Ensure this region is set in your configuration (https://webdriver.io/docs/options.html#region).'
}
return err.message
}
/**
* return timeout error with information about the executing command on which the test hangs
*/
export const getTimeoutError = (error: Error, requestOptions: Options.RequestLibOptions): Error => {
const cmdName = getExecCmdName(requestOptions)
const cmdArgs = getExecCmdArgs(requestOptions)
const cmdInfoMsg = `when running "${cmdName}" with method "${requestOptions.method}"`
const cmdArgsMsg = cmdArgs ? ` and args ${cmdArgs}` : ''
const timeoutErr = new Error(`${error.message} ${cmdInfoMsg}${cmdArgsMsg}`)
return Object.assign(timeoutErr, error)
}
function getExecCmdName(requestOptions: Options.RequestLibOptions): string {
const { href } = requestOptions.url as URL
const res = href.match(REG_EXPS.commandName) || []
return res[1] || href
}
function getExecCmdArgs(requestOptions: Options.RequestLibOptions): string {
const { json: cmdJson } = requestOptions
if (typeof cmdJson !== 'object') {
return ''
}
const transformedRes = transformCommandLogResult(cmdJson)
if (typeof transformedRes === 'string') {
return transformedRes
}
if (typeof cmdJson.script === 'string') {
const scriptRes = cmdJson.script.match(REG_EXPS.execFn) || []
return `"${scriptRes[1] || cmdJson.script}"`
}
return Object.keys(cmdJson).length ? `"${JSON.stringify(cmdJson)}"` : ''
} | the_stack |
import '../../../test/common-test-setup-karma';
import './gr-rule-editor';
import {GrRuleEditor} from './gr-rule-editor';
import {AccessPermissionId} from '../../../utils/access-util';
import {query, queryAll, queryAndAssert} from '../../../test/test-utils';
import {GrButton} from '../../shared/gr-button/gr-button';
import {GrSelect} from '../../shared/gr-select/gr-select';
import * as MockInteractions from '@polymer/iron-test-helpers/mock-interactions';
const basicFixture = fixtureFromElement('gr-rule-editor');
suite('gr-rule-editor tests', () => {
let element: GrRuleEditor;
setup(async () => {
element = basicFixture.instantiate() as GrRuleEditor;
await element.updateComplete;
});
suite('unit tests', () => {
test('computeForce and computeForceOptions', () => {
const ForcePushOptions = {
ALLOW: [
{name: 'Allow pushing (but not force pushing)', value: false},
{name: 'Allow pushing with or without force', value: true},
],
BLOCK: [
{name: 'Block pushing with or without force', value: false},
{name: 'Block force pushing', value: true},
],
};
const FORCE_EDIT_OPTIONS = [
{
name: 'No Force Edit',
value: false,
},
{
name: 'Force Edit',
value: true,
},
];
element.permission = 'push' as AccessPermissionId;
let action = 'ALLOW';
assert.isTrue(element.computeForce(action));
assert.deepEqual(
element.computeForceOptions(action),
ForcePushOptions.ALLOW
);
action = 'BLOCK';
assert.isTrue(element.computeForce(action));
assert.deepEqual(
element.computeForceOptions(action),
ForcePushOptions.BLOCK
);
action = 'DENY';
assert.isFalse(element.computeForce(action));
assert.equal(element.computeForceOptions(action).length, 0);
element.permission = 'editTopicName' as AccessPermissionId;
assert.isTrue(element.computeForce());
assert.deepEqual(element.computeForceOptions(), FORCE_EDIT_OPTIONS);
element.permission = 'submit' as AccessPermissionId;
assert.isFalse(element.computeForce());
assert.deepEqual(element.computeForceOptions(), []);
});
test('computeSectionClass', () => {
element.deleted = true;
element.editing = false;
assert.equal(element.computeSectionClass(), 'deleted');
element.deleted = false;
assert.equal(element.computeSectionClass(), '');
element.editing = true;
assert.equal(element.computeSectionClass(), 'editing');
element.deleted = true;
assert.equal(element.computeSectionClass(), 'editing deleted');
});
test('getDefaultRuleValues', () => {
element.permission = 'priority' as AccessPermissionId;
assert.deepEqual(element.getDefaultRuleValues(), {
action: 'BATCH',
});
element.permission = 'label-Code-Review' as AccessPermissionId;
element.label = {
values: [
{value: -2, text: 'This shall not be merged'},
{value: -1, text: 'I would prefer this is not merged as is'},
{value: -0, text: 'No score'},
{value: 1, text: 'Looks good to me, but someone else must approve'},
{value: 2, text: 'Looks good to me, approved'},
],
};
assert.deepEqual(element.getDefaultRuleValues(), {
action: 'ALLOW',
max: 2,
min: -2,
});
element.permission = 'push' as AccessPermissionId;
element.label = undefined;
assert.deepEqual(element.getDefaultRuleValues(), {
action: 'ALLOW',
force: false,
});
element.permission = 'submit' as AccessPermissionId;
assert.deepEqual(element.getDefaultRuleValues(), {
action: 'ALLOW',
});
});
test('setDefaultRuleValues', async () => {
element.rule = {value: {}};
const defaultValue = {action: 'ALLOW'};
const getDefaultRuleValuesStub = sinon
.stub(element, 'getDefaultRuleValues')
.returns(defaultValue);
element.setDefaultRuleValues();
assert.isTrue(getDefaultRuleValuesStub.called);
assert.equal(element.rule!.value, defaultValue);
});
test('computeOptions', () => {
const PRIORITY_OPTIONS = ['BATCH', 'INTERACTIVE'];
const DROPDOWN_OPTIONS = ['ALLOW', 'DENY', 'BLOCK'];
element.permission = 'priority' as AccessPermissionId;
assert.deepEqual(element.computeOptions(), PRIORITY_OPTIONS);
element.permission = 'submit' as AccessPermissionId;
assert.deepEqual(element.computeOptions(), DROPDOWN_OPTIONS);
});
test('handleValueChange', () => {
const modifiedHandler = sinon.stub();
element.rule = {value: {}};
element.addEventListener('access-modified', modifiedHandler);
element.handleValueChange();
assert.isNotOk(element.rule!.value!.modified);
element.originalRuleValues = {};
element.handleValueChange();
assert.isTrue(element.rule!.value!.modified);
assert.isTrue(modifiedHandler.called);
});
test('handleAccessSaved', () => {
const originalValue = {action: 'DENY'};
const newValue = {action: 'ALLOW'};
element.originalRuleValues = originalValue;
element.rule = {value: newValue};
element.handleAccessSaved();
assert.deepEqual(element.originalRuleValues, newValue);
});
test('setOriginalRuleValues', () => {
element.rule = {
value: {
action: 'ALLOW',
force: false,
},
};
element.setOriginalRuleValues();
assert.deepEqual(element.originalRuleValues, element.rule.value);
});
});
suite('already existing generic rule', () => {
setup(async () => {
element.groupName = 'Group Name';
element.permission = 'submit' as AccessPermissionId;
element.rule = {
value: {
action: 'ALLOW',
force: false,
},
};
element.section = 'refs/*';
element.setupValues();
element.setOriginalRuleValues();
await element.updateComplete;
});
test('_ruleValues and originalRuleValues are set correctly', () => {
assert.deepEqual(element.originalRuleValues, element.rule!.value);
});
test('values are set correctly', () => {
assert.equal(
queryAndAssert<GrSelect>(element, '#action').bindValue,
element.rule!.value!.action
);
assert.isNotOk(query<GrSelect>(element, '#labelMin'));
assert.isNotOk(query<GrSelect>(element, '#labelMax'));
assert.isFalse(
queryAndAssert<GrSelect>(element, '#force').classList.contains('force')
);
});
test('modify and cancel restores original values', async () => {
element.rule = {value: {}};
element.editing = true;
await element.updateComplete;
assert.notEqual(
getComputedStyle(queryAndAssert<GrButton>(element, '#removeBtn'))
.display,
'none'
);
assert.isNotOk(element.rule!.value!.modified);
const actionBindValue = queryAndAssert<GrSelect>(element, '#action');
actionBindValue.bindValue = 'DENY';
assert.isTrue(element.rule!.value!.modified);
element.editing = false;
await element.updateComplete;
assert.equal(
getComputedStyle(queryAndAssert<GrButton>(element, '#removeBtn'))
.display,
'none'
);
assert.deepEqual(element.originalRuleValues, element.rule!.value);
assert.equal(
queryAndAssert<GrSelect>(element, '#action').bindValue,
'ALLOW'
);
assert.isNotOk(element.rule!.value!.modified);
});
test('modify value', async () => {
assert.isNotOk(element.rule!.value!.modified);
const actionBindValue = queryAndAssert<GrSelect>(element, '#action');
actionBindValue.bindValue = 'DENY';
await element.updateComplete;
assert.isTrue(element.rule!.value!.modified);
// The original value should now differ from the rule values.
assert.notDeepEqual(element.originalRuleValues, element.rule!.value);
});
test('all selects are disabled when not in edit mode', async () => {
const selects = queryAll<HTMLSelectElement>(element, 'select');
for (const select of selects) {
assert.isTrue(select.disabled);
}
element.editing = true;
await element.updateComplete;
for (const select of selects) {
assert.isFalse(select.disabled);
}
});
test('remove rule and undo remove', async () => {
element.editing = true;
element.rule = {value: {action: 'ALLOW'}};
await element.updateComplete;
assert.isFalse(
queryAndAssert<HTMLDivElement>(
element,
'#deletedContainer'
).classList.contains('deleted')
);
MockInteractions.tap(queryAndAssert<GrButton>(element, '#removeBtn'));
await element.updateComplete;
assert.isTrue(
queryAndAssert<HTMLDivElement>(
element,
'#deletedContainer'
).classList.contains('deleted')
);
assert.isTrue(element.deleted);
assert.isTrue(element.rule!.value!.deleted);
MockInteractions.tap(queryAndAssert<GrButton>(element, '#undoRemoveBtn'));
await element.updateComplete;
assert.isFalse(element.deleted);
assert.isNotOk(element.rule!.value!.deleted);
});
test('remove rule and cancel', async () => {
element.editing = true;
await element.updateComplete;
assert.notEqual(
getComputedStyle(queryAndAssert<GrButton>(element, '#removeBtn'))
.display,
'none'
);
assert.equal(
getComputedStyle(
queryAndAssert<HTMLDivElement>(element, '#deletedContainer')
).display,
'none'
);
element.rule = {value: {action: 'ALLOW'}};
await element.updateComplete;
MockInteractions.tap(queryAndAssert<GrButton>(element, '#removeBtn'));
await element.updateComplete;
assert.notEqual(
getComputedStyle(queryAndAssert<GrButton>(element, '#removeBtn'))
.display,
'none'
);
assert.notEqual(
getComputedStyle(
queryAndAssert<HTMLDivElement>(element, '#deletedContainer')
).display,
'none'
);
assert.isTrue(element.deleted);
assert.isTrue(element.rule!.value!.deleted);
element.editing = false;
await element.updateComplete;
assert.isFalse(element.deleted);
assert.isNotOk(element.rule!.value!.deleted);
assert.isNotOk(element.rule!.value!.modified);
assert.deepEqual(element.originalRuleValues, element.rule!.value);
assert.equal(
getComputedStyle(queryAndAssert<GrButton>(element, '#removeBtn'))
.display,
'none'
);
assert.equal(
getComputedStyle(
queryAndAssert<HTMLDivElement>(element, '#deletedContainer')
).display,
'none'
);
});
test('computeGroupPath', () => {
const group = '123';
assert.equal(element.computeGroupPath(group), '/admin/groups/123');
});
});
suite('new edit rule', () => {
setup(async () => {
element.groupName = 'Group Name';
element.permission = 'editTopicName' as AccessPermissionId;
element.rule = {};
element.section = 'refs/*';
element.setupValues();
await element.updateComplete;
element.rule!.value!.added = true;
await element.updateComplete;
element.connectedCallback();
});
test('_ruleValues and originalRuleValues are set correctly', () => {
// Since the element does not already have default values, they should
// be set. The original values should be set to those too.
assert.isNotOk(element.rule!.value!.modified);
const expectedRuleValue = {
action: 'ALLOW',
force: false,
added: true,
};
assert.deepEqual(element.rule!.value, expectedRuleValue);
test('values are set correctly', () => {
assert.equal(
queryAndAssert<GrSelect>(element, '#action').bindValue,
expectedRuleValue.action
);
assert.equal(
queryAndAssert<GrSelect>(element, '#force').bindValue,
expectedRuleValue.action
);
});
});
test('modify value', async () => {
assert.isNotOk(element.rule!.value!.modified);
const forceBindValue = queryAndAssert<GrSelect>(element, '#force');
forceBindValue.bindValue = 'true';
await element.updateComplete;
assert.isTrue(element.rule!.value!.modified);
// The original value should now differ from the rule values.
assert.notDeepEqual(element.originalRuleValues, element.rule!.value);
});
test('remove value', async () => {
element.editing = true;
const removeStub = sinon.stub();
element.addEventListener('added-rule-removed', removeStub);
MockInteractions.tap(queryAndAssert<GrButton>(element, '#removeBtn'));
await element.updateComplete;
assert.isTrue(removeStub.called);
});
});
suite('already existing rule with labels', () => {
setup(async () => {
element.label = {
values: [
{value: -2, text: 'This shall not be merged'},
{value: -1, text: 'I would prefer this is not merged as is'},
{value: -0, text: 'No score'},
{value: 1, text: 'Looks good to me, but someone else must approve'},
{value: 2, text: 'Looks good to me, approved'},
],
};
element.groupName = 'Group Name';
element.permission = 'label-Code-Review' as AccessPermissionId;
element.rule = {
value: {
action: 'ALLOW',
force: false,
max: 2,
min: -2,
},
};
element.section = 'refs/*';
element.setupValues();
await element.updateComplete;
element.connectedCallback();
});
test('_ruleValues and originalRuleValues are set correctly', () => {
assert.deepEqual(element.originalRuleValues, element.rule!.value);
});
test('values are set correctly', () => {
assert.equal(
queryAndAssert<GrSelect>(element, '#action').bindValue,
element.rule!.value!.action
);
assert.equal(
queryAndAssert<GrSelect>(element, '#labelMin').bindValue,
element.rule!.value!.min
);
assert.equal(
queryAndAssert<GrSelect>(element, '#labelMax').bindValue,
element.rule!.value!.max
);
assert.isFalse(
queryAndAssert<GrSelect>(element, '#force').classList.contains('force')
);
});
test('modify value', async () => {
const removeStub = sinon.stub();
element.addEventListener('added-rule-removed', removeStub);
assert.isNotOk(element.rule!.value!.modified);
const labelMinBindValue = queryAndAssert<GrSelect>(element, '#labelMin');
labelMinBindValue.bindValue = 1;
await element.updateComplete;
assert.isTrue(element.rule!.value!.modified);
assert.isFalse(removeStub.called);
// The original value should now differ from the rule values.
assert.notDeepEqual(element.originalRuleValues, element.rule!.value);
});
});
suite('new rule with labels', () => {
let setDefaultRuleValuesSpy: sinon.SinonSpy;
setup(async () => {
setDefaultRuleValuesSpy = sinon.spy(element, 'setDefaultRuleValues');
element.label = {
values: [
{value: -2, text: 'This shall not be merged'},
{value: -1, text: 'I would prefer this is not merged as is'},
{value: -0, text: 'No score'},
{value: 1, text: 'Looks good to me, but someone else must approve'},
{value: 2, text: 'Looks good to me, approved'},
],
};
element.groupName = 'Group Name';
element.permission = 'label-Code-Review' as AccessPermissionId;
element.rule = {};
element.section = 'refs/*';
element.setupValues();
await element.updateComplete;
element.rule!.value!.added = true;
await element.updateComplete;
element.connectedCallback();
});
test('_ruleValues and originalRuleValues are set correctly', () => {
// Since the element does not already have default values, they should
// be set. The original values should be set to those too.
assert.isNotOk(element.rule!.value!.modified);
assert.isTrue(setDefaultRuleValuesSpy.called);
const expectedRuleValue = {
max: element.label!.values![element.label!.values.length - 1].value,
min: element.label!.values![0].value,
action: 'ALLOW',
added: true,
};
assert.deepEqual(element.rule!.value, expectedRuleValue);
test('values are set correctly', () => {
assert.equal(
queryAndAssert<GrSelect>(element, '#action').bindValue,
expectedRuleValue.action
);
assert.equal(
queryAndAssert<GrSelect>(element, '#labelMin').bindValue,
expectedRuleValue.min
);
assert.equal(
queryAndAssert<GrSelect>(element, '#labelMax').bindValue,
expectedRuleValue.max
);
});
});
test('modify value', async () => {
assert.isNotOk(element.rule!.value!.modified);
const labelMinBindValue = queryAndAssert<GrSelect>(element, '#labelMin');
labelMinBindValue.bindValue = 1;
await element.updateComplete;
assert.isTrue(element.rule!.value!.modified);
// The original value should now differ from the rule values.
assert.notDeepEqual(element.originalRuleValues, element.rule!.value);
});
});
suite('already existing push rule', () => {
setup(async () => {
element.groupName = 'Group Name';
element.permission = 'push' as AccessPermissionId;
element.rule = {
value: {
action: 'ALLOW',
force: true,
},
};
element.section = 'refs/*';
element.setupValues();
await element.updateComplete;
element.connectedCallback();
});
test('_ruleValues and originalRuleValues are set correctly', () => {
assert.deepEqual(element.originalRuleValues, element.rule!.value);
});
test('values are set correctly', () => {
assert.isTrue(
queryAndAssert<GrSelect>(element, '#force').classList.contains('force')
);
assert.equal(
queryAndAssert<GrSelect>(element, '#action').bindValue,
element.rule!.value!.action
);
assert.equal(
queryAndAssert<GrSelect>(element, '#force').bindValue,
element.rule!.value!.force
);
assert.isNotOk(query<GrSelect>(element, '#labelMin'));
assert.isNotOk(query<GrSelect>(element, '#labelMax'));
});
test('modify value', async () => {
assert.isNotOk(element.rule!.value!.modified);
const actionBindValue = queryAndAssert<GrSelect>(element, '#action');
actionBindValue.bindValue = false;
await element.updateComplete;
assert.isTrue(element.rule!.value!.modified);
// The original value should now differ from the rule values.
assert.notDeepEqual(element.originalRuleValues, element.rule!.value);
});
});
suite('new push rule', async () => {
setup(async () => {
element.groupName = 'Group Name';
element.permission = 'push' as AccessPermissionId;
element.rule = {};
element.section = 'refs/*';
element.setupValues();
await element.updateComplete;
element.rule!.value!.added = true;
await element.updateComplete;
element.connectedCallback();
});
test('_ruleValues and originalRuleValues are set correctly', () => {
// Since the element does not already have default values, they should
// be set. The original values should be set to those too.
assert.isNotOk(element.rule!.value!.modified);
const expectedRuleValue = {
action: 'ALLOW',
force: false,
added: true,
};
assert.deepEqual(element.rule!.value, expectedRuleValue);
test('values are set correctly', () => {
assert.equal(
queryAndAssert<GrSelect>(element, '#action').bindValue,
expectedRuleValue.action
);
assert.equal(
queryAndAssert<GrSelect>(element, '#force').bindValue,
expectedRuleValue.action
);
});
});
test('modify value', async () => {
assert.isNotOk(element.rule!.value!.modified);
const forceBindValue = queryAndAssert<GrSelect>(element, '#force');
forceBindValue.bindValue = true;
await element.updateComplete;
assert.isTrue(element.rule!.value!.modified);
// The original value should now differ from the rule values.
assert.notDeepEqual(element.originalRuleValues, element.rule!.value);
});
});
suite('already existing edit rule', () => {
setup(async () => {
element.groupName = 'Group Name';
element.permission = 'editTopicName' as AccessPermissionId;
element.rule = {
value: {
action: 'ALLOW',
force: true,
},
};
element.section = 'refs/*';
element.setupValues();
await element.updateComplete;
element.connectedCallback();
});
test('_ruleValues and originalRuleValues are set correctly', () => {
assert.deepEqual(element.originalRuleValues, element.rule!.value);
});
test('values are set correctly', () => {
assert.isTrue(
queryAndAssert<GrSelect>(element, '#force').classList.contains('force')
);
assert.equal(
queryAndAssert<GrSelect>(element, '#action').bindValue,
element.rule!.value!.action
);
assert.equal(
queryAndAssert<GrSelect>(element, '#force').bindValue,
element.rule!.value!.force
);
assert.isNotOk(query<GrSelect>(element, '#labelMin'));
assert.isNotOk(query<GrSelect>(element, '#labelMax'));
});
test('modify value', async () => {
assert.isNotOk(element.rule!.value!.modified);
const actionBindValue = queryAndAssert<GrSelect>(element, '#action');
actionBindValue.bindValue = false;
await element.updateComplete;
assert.isTrue(element.rule!.value!.modified);
// The original value should now differ from the rule values.
assert.notDeepEqual(element.originalRuleValues, element.rule!.value);
});
});
}); | the_stack |
import React, { useState, useEffect } from "react";
import _find from "lodash/find";
import _sortBy from "lodash/sortBy";
import _isEmpty from "lodash/isEmpty";
import {
makeStyles,
createStyles,
Popover,
Button,
Typography,
IconButton,
Grid,
MenuItem,
TextField,
Switch,
Chip,
} from "@material-ui/core";
import FilterIcon from "@material-ui/icons/FilterList";
import CloseIcon from "@material-ui/icons/Close";
import MultiSelect from "@antlerengineering/multiselect";
import ButtonWithStatus from "components/ButtonWithStatus";
import { FieldType } from "constants/fields";
import { FireTableFilter } from "hooks/useFiretable";
import { useFiretableContext } from "contexts/FiretableContext";
import { useAppContext } from "contexts/AppContext";
import { DocActions } from "hooks/useDoc";
const getType = (column) =>
column.type === FieldType.derivative
? column.config.renderFieldType
: column.type;
const OPERATORS = [
{
value: "==",
label: "Equals",
compatibleTypes: [
FieldType.phone,
FieldType.color,
FieldType.date,
FieldType.dateTime,
FieldType.shortText,
FieldType.singleSelect,
FieldType.url,
FieldType.email,
FieldType.checkbox,
],
},
{
value: "in",
label: "matches any of",
compatibleTypes: [FieldType.singleSelect],
},
// {
// value: "array-contains",
// label: "includes",
// compatibleTypes: [FieldType.connectTable],
// },
// {
// value: "array-contains",
// label: "Has",
// compatibleTypes: [FieldType.multiSelect],
// },
{
value: "array-contains-any",
label: "Has any",
compatibleTypes: [FieldType.multiSelect, FieldType.connectTable],
},
{ value: "<", label: "<", compatibleTypes: [FieldType.number] },
{ value: "<=", label: "<=", compatibleTypes: [FieldType.number] },
{ value: "==", label: "==", compatibleTypes: [FieldType.number] },
{ value: ">=", label: ">=", compatibleTypes: [FieldType.number] },
{ value: ">", label: ">", compatibleTypes: [FieldType.number] },
{
value: "<",
label: "before",
compatibleTypes: [FieldType.date, FieldType.dateTime],
},
{
value: ">=",
label: "after",
compatibleTypes: [FieldType.date, FieldType.dateTime],
},
];
const useStyles = makeStyles((theme) =>
createStyles({
paper: { width: 640 },
closeButton: {
position: "absolute",
top: theme.spacing(0.5),
right: theme.spacing(0.5),
},
content: { padding: theme.spacing(4) },
topRow: { marginBottom: theme.spacing(3.5) },
bottomButtons: { marginTop: theme.spacing(4.5) },
activeButton: {
borderTopRightRadius: 0,
borderBottomRightRadius: 0,
},
filterChip: {
borderTopLeftRadius: 0,
borderBottomLeftRadius: 0,
backgroundColor: theme.palette.background.paper,
marginLeft: -1,
borderColor: theme.palette.action.disabled,
},
filterChipLabel: {
...theme.typography.subtitle2,
lineHeight: 1,
},
filterChipDelete: {
color: theme.palette.primary.main,
"&:hover": { color: theme.palette.primary.dark },
},
})
);
const UNFILTERABLES = [
FieldType.image,
FieldType.file,
FieldType.action,
FieldType.subTable,
FieldType.last,
FieldType.longText,
];
const Filters = () => {
const { userClaims, tableState, tableActions } = useFiretableContext();
const { userDoc } = useAppContext();
useEffect(() => {
if (userDoc.state.doc && tableState?.tablePath) {
if (userDoc.state.doc.tables?.[tableState?.tablePath]?.filters) {
tableActions?.table.filter(
userDoc.state.doc.tables[tableState?.tablePath].filters
);
tableActions?.table.orderBy();
}
}
}, [userDoc.state, tableState?.tablePath]);
const filterColumns = _sortBy(Object.values(tableState!.columns), "index")
.filter((c) => !UNFILTERABLES.includes(c.type))
.map((c) => ({
key: c.key,
label: c.name,
type: c.type,
options: c.options,
...c,
}));
const classes = useStyles();
const filters = [];
const combineType = "all";
const [selectedColumn, setSelectedColumn] = useState<any>();
const [query, setQuery] = useState<FireTableFilter>({
key: "",
operator: "",
value: "",
});
useEffect(() => {
if (selectedColumn) {
let updatedQuery: FireTableFilter = {
key: selectedColumn.key,
operator: "",
value: "",
};
const type = getType(selectedColumn);
if (
[
FieldType.phone,
FieldType.shortText,
FieldType.url,
FieldType.email,
FieldType.checkbox,
].includes(type)
) {
updatedQuery = { ...updatedQuery, operator: "==" };
}
if (type === FieldType.checkbox) {
updatedQuery = { ...updatedQuery, value: false };
}
if (type === FieldType.connectTable) {
updatedQuery = {
key: `${selectedColumn.key}ID`,
operator: "array-contains-any",
value: [],
};
}
if (type === FieldType.multiSelect) {
updatedQuery = {
...updatedQuery,
operator: "array-contains-any",
value: [],
};
}
setQuery(updatedQuery);
}
}, [selectedColumn]);
const operators = selectedColumn
? OPERATORS.filter((operator) =>
operator.compatibleTypes.includes(getType(selectedColumn))
)
: [];
const [anchorEl, setAnchorEl] = useState<null | HTMLElement>(null);
const handleClose = () => setAnchorEl(null);
const handleClick = (event: React.MouseEvent<HTMLElement>) => {
setAnchorEl(anchorEl ? null : event.currentTarget);
};
const handleChangeColumn = (e) => {
const column = _find(filterColumns, (c) => c.key === e.target.value);
setSelectedColumn(column);
};
const open = Boolean(anchorEl);
const id = open ? "simple-popper" : undefined;
const renderInputField = (selectedColumn, operator) => {
const type = getType(selectedColumn);
switch (type) {
case FieldType.checkbox:
return (
<Switch
value={query.value}
onChange={(e, checked) => {
setQuery((query) => ({ ...query, value: checked }));
}}
/>
);
case FieldType.email:
case FieldType.phone:
case FieldType.shortText:
case FieldType.longText:
case FieldType.url:
return (
<TextField
onChange={(e) => {
const value = e.target.value;
if (value) setQuery((query) => ({ ...query, value: value }));
}}
variant="filled"
hiddenLabel
placeholder="Text value"
/>
);
case FieldType.number:
return (
<TextField
onChange={(e) => {
const value = e.target.value;
if (query.value || value)
setQuery((query) => ({
...query,
value: value !== "" ? parseFloat(value) : "",
}));
}}
value={typeof query.value === "number" ? query.value : ""}
variant="filled"
hiddenLabel
type="number"
placeholder="number value"
/>
);
case FieldType.singleSelect:
if (operator === "in")
return (
<MultiSelect
multiple
max={10}
freeText={true}
onChange={(value) => setQuery((query) => ({ ...query, value }))}
options={
selectedColumn.config.options
? selectedColumn.config.options.sort()
: []
}
label=""
value={Array.isArray(query?.value) ? query.value : []}
TextFieldProps={{ hiddenLabel: true }}
/>
);
return (
<MultiSelect
freeText={true}
multiple={false}
onChange={(value) => {
if (value !== null) setQuery((query) => ({ ...query, value }));
}}
options={
selectedColumn.config.options
? selectedColumn.config.options.sort()
: []
}
label=""
value={typeof query?.value === "string" ? query.value : null}
TextFieldProps={{ hiddenLabel: true }}
/>
);
case FieldType.multiSelect:
return (
<MultiSelect
multiple
onChange={(value) => setQuery((query) => ({ ...query, value }))}
value={query.value as string[]}
max={10}
options={
selectedColumn.config.options
? selectedColumn.config.options.sort()
: []
}
label={""}
searchable={false}
freeText={true}
/>
);
case FieldType.date:
case FieldType.dateTime:
return <>//TODO:Date/Time picker</>;
default:
return <>Not available</>;
// return <TextField variant="filled" fullWidth disabled />;
break;
}
};
const handleUpdateFilters = (filters: FireTableFilter[]) => {
userDoc.dispatch({
action: DocActions.update,
data: {
tables: { [`${tableState?.tablePath}`]: { filters } },
},
});
};
return (
<>
<Grid container direction="row" wrap="nowrap">
<ButtonWithStatus
variant="outlined"
color="primary"
onClick={handleClick}
startIcon={<FilterIcon />}
active={tableState?.filters && tableState?.filters.length > 0}
className={
tableState?.filters && tableState?.filters.length > 0
? classes.activeButton
: ""
}
>
{tableState?.filters && tableState?.filters.length > 0
? "Filtered"
: "Filter"}
</ButtonWithStatus>
{(tableState?.filters ?? []).map((filter) => (
<Chip
key={filter.key}
label={`${filter.key} ${filter.operator} ${filter.value}`}
onDelete={() => handleUpdateFilters([])}
classes={{
root: classes.filterChip,
label: classes.filterChipLabel,
deleteIcon: classes.filterChipDelete,
}}
variant="outlined"
/>
))}
</Grid>
<Popover
id={id}
open={open}
anchorEl={anchorEl}
classes={{ paper: classes.paper }}
onClose={handleClose}
anchorOrigin={{ vertical: "bottom", horizontal: "left" }}
transformOrigin={{ vertical: "top", horizontal: "left" }}
>
<IconButton className={classes.closeButton} onClick={handleClose}>
<CloseIcon />
</IconButton>
<div className={classes.content}>
{/* <Grid
container
alignItems="center"
spacing={2}
className={classes.topRow}
>
<Grid item>
<Typography component="span">Results match</Typography>
</Grid>
<Grid item>
<TextField
select
variant="filled"
id="demo-simple-select-filled"
value={combineType}
hiddenLabel
// disabled
// onChange={handleChange}
>
<MenuItem value="all">all</MenuItem>
<MenuItem value="any">any</MenuItem>
</TextField>
</Grid>
<Grid item>
<Typography component="span">of the filter criteria.</Typography>
</Grid>
</Grid> */}
<Grid container spacing={2}>
<Grid item xs={4}>
<Typography variant="overline">Column</Typography>
</Grid>
<Grid item xs={4}>
<Typography variant="overline">Condition</Typography>
</Grid>
<Grid item xs={4}>
<Typography variant="overline">Value</Typography>
</Grid>
</Grid>
<Grid container spacing={2}>
<Grid item xs={4}>
<TextField
select
variant="filled"
hiddenLabel
fullWidth
value={selectedColumn?.key ?? ""}
onChange={handleChangeColumn}
SelectProps={{ displayEmpty: true }}
>
<MenuItem disabled value="" style={{ display: "none" }}>
Select Column
</MenuItem>
{filterColumns.map((c) => (
<MenuItem key={c.key} value={c.key}>
{c.label}
</MenuItem>
))}
</TextField>
</Grid>
<Grid item xs={4}>
<TextField
select
variant="filled"
hiddenLabel
fullWidth
value={query.operator}
disabled={!query.key || operators?.length === 0}
onChange={(e) => {
setQuery((query) => ({
...query,
operator: e.target.value as string,
}));
}}
SelectProps={{ displayEmpty: true }}
>
<MenuItem disabled value="" style={{ display: "none" }}>
Select Condition
</MenuItem>
{operators.map((operator) => (
<MenuItem key={operator.value} value={operator.value}>
{operator.label}
</MenuItem>
))}
</TextField>
</Grid>
<Grid item xs={4}>
{query.operator &&
renderInputField(selectedColumn, query.operator)}
</Grid>
</Grid>
<Grid
container
className={classes.bottomButtons}
justify="space-between"
>
{/* <Button color="primary">+ ADD FILTER</Button> */}
<Button
disabled={query.key === ""}
onClick={() => {
handleUpdateFilters([]);
setQuery({
key: "",
operator: "",
value: "",
});
setSelectedColumn(null);
//handleClose();
}}
>
Clear
</Button>
<Button
disabled={
query.value !== true &&
query.value !== false &&
_isEmpty(query.value) &&
typeof query.value !== "number"
}
color="primary"
onClick={() => {
handleUpdateFilters([query]);
handleClose();
}}
>
Apply
</Button>
</Grid>
</div>
</Popover>
</>
);
};
export default Filters; | the_stack |
import assert = require('assert');
import {} from 'mocha';
import * as path from 'path';
import {LabelResolver} from '../src/labelresolver';
import {OrchestratorBaseModel} from '../src/basemodel';
import {OrchestratorHelper} from '../src/orchestratorhelper';
import {Utility} from '../src/utility';
import {LabelType, Utility as UtilityDispatcher} from '@microsoft/bf-dispatcher';
import {Example} from '@microsoft/bf-dispatcher';
import {UnitTestHelper} from './utility.test';
describe('Test Suite - LabelResolver', () => {
it('Test.0000 LabelResolver.scoreBatch()', async function (): Promise<void> {
const ignore: boolean = UnitTestHelper.getIgnoreFlag();
if (ignore) {
return;
}
Utility.resetFlagToPrintDebuggingLogToConsole(UnitTestHelper.getDefaultUnitTestDebuggingLogFlag());
this.timeout(UnitTestHelper.getDefaultFunctionalTestTimeout());
const baseModelPath: string = path.resolve('./resources/model/model_dte_bert_3l');
Utility.debuggingLog('Test.0000 LabelResolver.scoreBatch(): downloading a base nerual network language model for unit test');
await UnitTestHelper.downloadModelFileForTest(
baseModelPath,
OrchestratorBaseModel.defaultHandler,
OrchestratorBaseModel.defaultHandler);
const modelConfig: string = Utility.loadFile(path.resolve(baseModelPath, 'config.json'));
Utility.debuggingLog(`Test.0000 LabelResolver.scoreBatch(): modelConfig=${modelConfig}`);
Utility.debuggingLog(`Test.0000 LabelResolver.scoreBatch(): process.cwd()=${process.cwd()}`);
const inputPath: string = './resources/data/Columnar/Email_bert.blu';
// -----------------------------------------------------------------------
// ---- NOTE ---- create a LabelResolver object and load the snapshot set.
Utility.debuggingLog('Test.0000 LabelResolver.scoreBatch(), ready to call LabelResolver.createAsync()');
await LabelResolver.createAsync(baseModelPath, '');
Utility.debuggingLog('Test.0000 LabelResolver.scoreBatch(), after calling LabelResolver.createAsync()');
// Utility.debuggingLog('LabelResolver.scoreBatch(), ready to call UtilityLabelResolver.resetLabelResolverSettingUseCompactEmbeddings()');
// UtilityLabelResolver.resetLabelResolverSettingUseCompactEmbeddings(fullEmbeddings);
// Utility.debuggingLog('LabelResolver.scoreBatch(), after calling UtilityLabelResolver.resetLabelResolverSettingUseCompactEmbeddings()');
Utility.debuggingLog('Test.0000 LabelResolver.scoreBatch(), ready to call OrchestratorHelper.getSnapshotFromFile()');
const snapshot: Uint8Array = OrchestratorHelper.getSnapshotFromFile(inputPath);
Utility.debuggingLog(`Test.0000 LabelResolver.scoreBatch(): typeof(snapshot)=${typeof snapshot}`);
Utility.debuggingLog(`Test.0000 LabelResolver.scoreBatch(): snapshot.byteLength=${snapshot.byteLength}`);
Utility.debuggingLog('Test.0000 LabelResolver.scoreBatch(), after calling OrchestratorHelper.getSnapshotFromFile()');
Utility.debuggingLog('Test.0000 LabelResolver.scoreBatch(), ready to call LabelResolver.addSnapshot()');
await LabelResolver.addSnapshot(snapshot);
Utility.debuggingLog('Test.0000 LabelResolver.scoreBatch(), after calling LabelResolver.addSnapshot()');
// -----------------------------------------------------------------------
const utterances: string[] = [
'add a flag to it',
'add some more info',
];
// -----------------------------------------------------------------------
const results: any = LabelResolver.scoreBatch(utterances, LabelType.Intent);
UtilityDispatcher.debuggingNamedLog1('Test.0000 LabelResolver.scoreBatch(utterances, LabelType.Intent)', results, 'results');
// -----------------------------------------------------------------------
UtilityDispatcher.debuggingLog('THE END - Test.0000 LabelResolver.scoreBatch()');
});
it('Test.0001 LabelResolver.addExample()', async function (): Promise<void> {
const ignore: boolean = UnitTestHelper.getIgnoreFlag();
if (ignore) {
return;
}
Utility.resetFlagToPrintDebuggingLogToConsole(UnitTestHelper.getDefaultUnitTestDebuggingLogFlag());
this.timeout(UnitTestHelper.getDefaultFunctionalTestTimeout());
const baseModelPath: string = path.resolve('./resources/model/model_dte_bert_3l');
Utility.debuggingLog('Test.0001 LabelResolver.addExample(): downloading a base nerual network language model for unit test');
await UnitTestHelper.downloadModelFileForTest(
baseModelPath,
OrchestratorBaseModel.defaultHandler,
OrchestratorBaseModel.defaultHandler,
'pretrained.20200924.microsoft.dte.00.06.en.onnx');
const modelConfig: string = Utility.loadFile(path.resolve(baseModelPath, 'config.json'));
Utility.debuggingLog(`Test.0001 LabelResolver.addExample(): modelConfig=${modelConfig}`);
Utility.debuggingLog(`Test.0001 LabelResolver.addExample(): process.cwd()=${process.cwd()}`);
// -----------------------------------------------------------------------
// ---- NOTE ---- create a LabelResolver object and load the snapshot set.
Utility.debuggingLog('Test.0001 LabelResolver.addExample(), ready to call LabelResolver.createAsync()');
await LabelResolver.createAsync(baseModelPath, '');
Utility.debuggingLog('Test.0001 LabelResolver.addExample(), after calling LabelResolver.createAsync()');
// Utility.debuggingLog('LabelResolver.addExample(), ready to call UtilityLabelResolver.resetLabelResolverSettingUseCompactEmbeddings()');
// UtilityLabelResolver.resetLabelResolverSettingUseCompactEmbeddings(fullEmbeddings);
// Utility.debuggingLog('LabelResolver.addExample(), after calling UtilityLabelResolver.resetLabelResolverSettingUseCompactEmbeddings()');
const example: Example = Example.newIntentExample(
'where is the news on agility',
['Keyword']);
const exampleObject: any = example.toAlternateObject();
Utility.debuggingLog(`Test.0001 LabelResolver.addExample(): exampleObject=${Utility.jsonStringify(exampleObject)}`);
const rvAddExample: any = LabelResolver.addExample(exampleObject);
Utility.debuggingLog(`Test.0001 LabelResolver.addExample(): rv=${rvAddExample}`);
const snapshot: any = LabelResolver.createSnapshot();
Utility.debuggingLog(`Test.0001 LabelResolver.addExample(): snapshot=${snapshot}`);
Utility.debuggingLog(`Test.0001 LabelResolver.addExample(): snapshot.byteLength=${snapshot.byteLength}`);
const snapshotInString: string = new TextDecoder().decode(snapshot);
Utility.debuggingLog(`Test.0001 LabelResolver.addExample(): snapshotInString=${snapshotInString}`);
// -----------------------------------------------------------------------
UtilityDispatcher.debuggingLog('THE END - Test.0001 LabelResolver.addExample()');
});
it('Test.0002 LabelResolver.removeExample()', async function (): Promise<void> {
const ignore: boolean = UnitTestHelper.getIgnoreFlag();
if (ignore) {
return;
}
Utility.resetFlagToPrintDebuggingLogToConsole(UnitTestHelper.getDefaultUnitTestDebuggingLogFlag());
this.timeout(UnitTestHelper.getDefaultFunctionalTestTimeout());
const baseModelPath: string = path.resolve('./resources/model/model_dte_bert_3l');
Utility.debuggingLog('Test.0002 LabelResolver.addExample(): downloading a base nerual network language model for unit test');
await UnitTestHelper.downloadModelFileForTest(
baseModelPath,
OrchestratorBaseModel.defaultHandler,
OrchestratorBaseModel.defaultHandler,
'pretrained.20200924.microsoft.dte.00.06.en.onnx');
const modelConfig: string = Utility.loadFile(path.resolve(baseModelPath, 'config.json'));
Utility.debuggingLog(`Test.0002 LabelResolver.addExample(): modelConfig=${modelConfig}`);
Utility.debuggingLog(`Test.0002 LabelResolver.addExample(): process.cwd()=${process.cwd()}`);
// -----------------------------------------------------------------------
// ---- NOTE ---- create a LabelResolver object and load the snapshot set.
Utility.debuggingLog('Test.0002 LabelResolver.addExample(), ready to call LabelResolver.createAsync()');
await LabelResolver.createAsync(baseModelPath, '');
Utility.debuggingLog('Test.0002 LabelResolver.addExample(), after calling LabelResolver.createAsync()');
// Utility.debuggingLog('LabelResolver.addExample(), ready to call UtilityLabelResolver.resetLabelResolverSettingUseCompactEmbeddings()');
// UtilityLabelResolver.resetLabelResolverSettingUseCompactEmbeddings(fullEmbeddings);
// Utility.debuggingLog('LabelResolver.addExample(), after calling UtilityLabelResolver.resetLabelResolverSettingUseCompactEmbeddings()');
const example: Example = Example.newIntentExample(
'where is the news on agility',
['Keyword']);
const exampleObject: any = example.toAlternateObject();
Utility.debuggingLog(`Test.0002 LabelResolver.addExample(): exampleObject=${Utility.jsonStringify(exampleObject)}`);
const rvAddExample: any = LabelResolver.addExample(exampleObject);
Utility.debuggingLog(`Test.0002 LabelResolver.addExample(): rv=${rvAddExample}`);
const snapshot: any = LabelResolver.createSnapshot();
Utility.debuggingLog(`Test.0002 LabelResolver.addExample(): snapshot=${snapshot}`);
Utility.debuggingLog(`Test.0002 LabelResolver.addExample(): snapshot.byteLength=${snapshot.byteLength}`);
const snapshotInString: string = new TextDecoder().decode(snapshot);
Utility.debuggingLog(`Test.0002 LabelResolver.addExample(): snapshotInString=${snapshotInString}`);
// -----------------------------------------------------------------------
const examples: any = LabelResolver.getExamples();
assert.strictEqual(examples.length, 1);
// -----------------------------------------------------------------------
const rvRemoveExample: any = LabelResolver.removeExample(exampleObject);
Utility.debuggingLog(`Test.0002 LabelResolver.removeExample(): rv=${rvRemoveExample}`);
// -----------------------------------------------------------------------
const examplesAfterRemoveExample: any = LabelResolver.getExamples();
assert.strictEqual(examplesAfterRemoveExample.length, 0);
// -----------------------------------------------------------------------
UtilityDispatcher.debuggingLog('THE END - Test.0002 LabelResolver.addExample()');
});
}); | the_stack |
import { ReactWrapper, ShallowWrapper } from "enzyme"
import React from "react"
import { FileError } from "react-dropzone"
import { mount, shallow } from "src/lib/test_util"
import {
FileUploader as FileUploaderProto,
FileUploaderState as FileUploaderStateProto,
UploadedFileInfo as UploadedFileInfoProto,
} from "src/autogen/proto"
import { WidgetStateManager } from "src/lib/WidgetStateManager"
import { notUndefined } from "src/lib/utils"
import FileDropzone from "./FileDropzone"
import FileUploader, { Props } from "./FileUploader"
import { ErrorStatus, UploadFileInfo, UploadingStatus } from "./UploadFileInfo"
const createFile = (): File => {
return new File(["Text in a file!"], "filename.txt", {
type: "text/plain",
lastModified: 0,
})
}
const buildFileUploaderStateProto = (
maxFileId: number,
uploadedFileIds: number[]
): FileUploaderStateProto =>
new FileUploaderStateProto({
maxFileId,
uploadedFileInfo: uploadedFileIds.map(
fileId =>
new UploadedFileInfoProto({
id: fileId,
name: "filename.txt",
size: 15,
})
),
})
const INVALID_TYPE_ERROR: FileError = {
message: "error message",
code: "file-invalid-type",
}
const TOO_MANY_FILES: FileError = {
message: "error message",
code: "too-many-files",
}
const FILE_TOO_LARGE: FileError = {
message: "error message",
code: "file-too-large",
}
const INITIAL_SERVER_FILE_ID = 1
const getProps = (elementProps: Partial<FileUploaderProto> = {}): Props => {
let mockServerFileIdCounter = INITIAL_SERVER_FILE_ID
return {
element: FileUploaderProto.create({
id: "id",
type: [],
maxUploadSizeMb: 50,
...elementProps,
}),
width: 0,
disabled: false,
widgetMgr: new WidgetStateManager({
sendRerunBackMsg: jest.fn(),
formsDataChanged: jest.fn(),
}),
mockServerFileIdCounter: 1,
// @ts-ignore
uploadClient: {
uploadFile: jest.fn().mockImplementation(() => {
// Mock UploadClient to return an incremented ID for each upload.
return Promise.resolve(mockServerFileIdCounter++)
}),
},
}
}
/** Return a strongly-typed wrapper.state("files") */
function getFiles(
wrapper: ShallowWrapper<FileUploader> | ReactWrapper<FileUploader>,
statusType?: string
): UploadFileInfo[] {
const result = wrapper.state<UploadFileInfo[]>("files")
return statusType != null
? result.filter(f => f.status.type === statusType)
: result
}
function getServerFileId(file: UploadFileInfo): number | undefined {
if (file.status.type === "uploaded") {
return file.status.serverFileId
}
return undefined
}
function getServerFileIds(files: UploadFileInfo[]): number[] {
return files.map(getServerFileId).filter(notUndefined)
}
describe("FileUploader widget", () => {
it("renders without crashing", () => {
const props = getProps()
const wrapper = shallow(<FileUploader {...props} />)
const instance = wrapper.instance() as FileUploader
expect(wrapper).toBeDefined()
expect(instance.status).toBe("ready")
})
it("sets initial value properly if non-empty", () => {
const props = getProps()
const { element, widgetMgr } = props
widgetMgr.setFileUploaderStateValue(
element,
buildFileUploaderStateProto(INITIAL_SERVER_FILE_ID, [
INITIAL_SERVER_FILE_ID,
]),
{ fromUi: false }
)
const wrapper = shallow(<FileUploader {...props} />)
expect(wrapper.state()).toEqual({
files: [
{
name: "filename.txt",
size: 15,
status: { type: "uploaded", serverFileId: 1 },
id: 1,
},
],
newestServerFileId: 1,
})
})
it("shows a label", () => {
const props = getProps({ label: "Test label" })
const wrapper = mount(<FileUploader {...props} />)
expect(wrapper.find("StyledWidgetLabel").text()).toBe(props.element.label)
})
it("uploads a single selected file", async () => {
const props = getProps()
jest.spyOn(props.widgetMgr, "setFileUploaderStateValue")
const wrapper = shallow(<FileUploader {...props} />)
const instance = wrapper.instance() as FileUploader
const fileDropzone = wrapper.find(FileDropzone)
fileDropzone.props().onDrop([createFile()], [])
// We should have 1 file in the uploading state
expect(props.uploadClient.uploadFile).toHaveBeenCalledTimes(1)
expect(getFiles(wrapper).length).toBe(1)
expect(getFiles(wrapper)[0].status.type).toBe("uploading")
expect(instance.status).toBe("updating")
// WidgetStateManager should not have been called yet
expect(props.widgetMgr.setFileUploaderStateValue).not.toHaveBeenCalled()
await process.nextTick
// The server will have assigned us a new ID. This will also be
// our "newestServerFileId".
const serverFileId = getServerFileId(getFiles(wrapper)[0]) as number
const newestServerFileId = serverFileId
// After upload completes, our file should be "uploaded" and our status
// should be "ready". The file should also have a new ID, returned by our
// uploadFile endpoint.
expect(getFiles(wrapper).length).toBe(1)
expect(getFiles(wrapper)[0].status.type).toBe("uploaded")
expect(serverFileId).toBeDefined()
expect(instance.status).toBe("ready")
// And WidgetStateManager should have been called with the file's ID
expect(props.widgetMgr.setFileUploaderStateValue).toHaveBeenCalledWith(
props.element,
buildFileUploaderStateProto(newestServerFileId, [serverFileId]),
{
fromUi: true,
}
)
})
it("uploads a single file even if too many files are selected", async () => {
const props = getProps({ multipleFiles: false })
jest.spyOn(props.widgetMgr, "setFileUploaderStateValue")
const wrapper = shallow(<FileUploader {...props} />)
const instance = wrapper.instance() as FileUploader
const fileDropzone = wrapper.find(FileDropzone)
fileDropzone.props().onDrop(
[],
[
{
file: createFile(),
errors: [INVALID_TYPE_ERROR, TOO_MANY_FILES],
},
{ file: createFile(), errors: [TOO_MANY_FILES] },
{ file: createFile(), errors: [TOO_MANY_FILES] },
]
)
expect(props.uploadClient.uploadFile).toHaveBeenCalledTimes(1)
// We should have 3 files. One will be uploading, the other two will
// be in the error state.
expect(getFiles(wrapper).length).toBe(3)
expect(getFiles(wrapper, "uploading").length).toBe(1)
expect(getFiles(wrapper, "error").length).toBe(2)
expect(instance.status).toBe("updating")
await process.nextTick
// Our upload has completed, our file should now be "uploaded", and
// our status should now be "ready".
expect(getFiles(wrapper).length).toBe(3)
expect(getFiles(wrapper, "uploaded").length).toBe(1)
expect(getFiles(wrapper, "error").length).toBe(2)
expect(instance.status).toBe("ready")
const fileId = getServerFileId(getFiles(wrapper)[0]) as number
const newestServerFileId = fileId
// WidgetStateManager should have been called with the file's ID
expect(props.widgetMgr.setFileUploaderStateValue).toHaveBeenCalledWith(
props.element,
buildFileUploaderStateProto(newestServerFileId, [fileId]),
{
fromUi: true,
}
)
})
it("replaces file on single file uploader", async () => {
const props = getProps({ multipleFiles: false })
const wrapper = mount(<FileUploader {...props} />)
const instance = wrapper.instance() as FileUploader
const fileDropzone = wrapper.find(FileDropzone)
// Upload the first file
fileDropzone.props().onDrop([createFile()], [])
const origFile = getFiles(wrapper)[0]
expect(props.uploadClient.uploadFile).toBeCalledTimes(1)
expect(getFiles(wrapper).length).toBe(1)
expect(getFiles(wrapper, "uploading").length).toBe(1)
await process.nextTick
expect(getFiles(wrapper, "uploaded").length).toBe(1)
expect(instance.status).toBe("ready")
// Upload a replacement file
fileDropzone.props().onDrop([createFile()], [])
const replacementFile = getFiles(wrapper)[0]
expect(props.uploadClient.uploadFile).toBeCalledTimes(2)
expect(getFiles(wrapper).length).toBe(1)
expect(getFiles(wrapper, "uploading").length).toBe(1)
// Ensure that our new UploadFileInfo has a different ID than the first
// file's.
expect(replacementFile.id).not.toBe(origFile.id)
await process.nextTick
// Ensure that our final status is as expected.
expect(getFiles(wrapper, "uploaded").length).toBe(1)
expect(instance.status).toBe("ready")
})
it("uploads multiple files, even if some have errors", async () => {
const props = getProps({ multipleFiles: true })
jest.spyOn(props.widgetMgr, "setFileUploaderStateValue")
const wrapper = shallow(<FileUploader {...props} />)
const instance = wrapper.instance() as FileUploader
const fileDropzone = wrapper.find(FileDropzone)
// Drop two valid files, and 3 invalid ones.
fileDropzone.props().onDrop(
[createFile(), createFile()],
[
{ file: createFile(), errors: [INVALID_TYPE_ERROR] },
{ file: createFile(), errors: [INVALID_TYPE_ERROR] },
{ file: createFile(), errors: [INVALID_TYPE_ERROR] },
]
)
expect(props.uploadClient.uploadFile).toHaveBeenCalledTimes(2)
// We should have two files uploading, and 3 showing an error.
expect(getFiles(wrapper).length).toBe(5)
expect(getFiles(wrapper, "uploading").length).toBe(2)
expect(getFiles(wrapper, "error").length).toBe(3)
expect(instance.status).toBe("updating")
await process.nextTick
// When our upload completes, our uploading files should now be uploaded
expect(getFiles(wrapper).length).toBe(5)
expect(getFiles(wrapper, "uploaded").length).toBe(2)
expect(getFiles(wrapper, "error").length).toBe(3)
expect(instance.status).toBe("ready")
// WidgetStateManager should have been called with the server IDs
// of the uploaded files.
const uploadedFiles = getFiles(wrapper, "uploaded")
const uploadedFileIds = getServerFileIds(uploadedFiles)
const newestServerId = Math.max(...uploadedFileIds)
expect(props.widgetMgr.setFileUploaderStateValue).toHaveBeenCalledWith(
props.element,
buildFileUploaderStateProto(newestServerId, uploadedFileIds),
{
fromUi: true,
}
)
})
it("can delete completed upload", async () => {
const props = getProps({ multipleFiles: true })
jest.spyOn(props.widgetMgr, "setFileUploaderStateValue")
const wrapper = mount(<FileUploader {...props} />)
const instance = wrapper.instance() as FileUploader
// Upload two files
instance.uploadFile(createFile())
instance.uploadFile(createFile())
await process.nextTick
const initialFiles = getFiles(wrapper)
expect(initialFiles.length).toBe(2)
expect(getFiles(wrapper, "uploaded").length).toBe(2)
expect(instance.status).toBe("ready")
// WidgetStateManager should have been called with our two file IDs
expect(props.widgetMgr.setFileUploaderStateValue).toHaveBeenCalledTimes(1)
const initialFileIds = getServerFileIds(initialFiles)
const newestServerId = Math.max(...initialFileIds)
expect(props.widgetMgr.setFileUploaderStateValue).toHaveBeenLastCalledWith(
props.element,
buildFileUploaderStateProto(newestServerId, initialFileIds),
{
fromUi: true,
}
)
// Delete the first file
// @ts-ignore
instance.deleteFile(initialFiles[0].id)
await process.nextTick
// We should only have a single file - the second file from the original
// upload.
expect(getFiles(wrapper).length).toBe(1)
expect(getFiles(wrapper)[0]).toBe(initialFiles[1])
expect(instance.status).toBe("ready")
// WidgetStateManager should have been called with the file ID
// of the remaining file. This should be the second time WidgetStateManager
// has been updated.
expect(props.widgetMgr.setFileUploaderStateValue).toHaveBeenCalledTimes(2)
const newWidgetValue = [initialFileIds[1]]
expect(props.widgetMgr.setFileUploaderStateValue).toHaveBeenLastCalledWith(
props.element,
buildFileUploaderStateProto(newestServerId, newWidgetValue),
{
fromUi: true,
}
)
})
it("can delete in-progress upload", async () => {
const props = getProps({ multipleFiles: true })
jest.spyOn(props.widgetMgr, "setFileUploaderStateValue")
const wrapper = mount(<FileUploader {...props} />)
const instance = wrapper.instance() as FileUploader
// Upload a file...
instance.uploadFile(createFile())
expect(getFiles(wrapper, "uploading").length).toBe(1)
expect(instance.status).toBe("updating")
const fileId = getFiles(wrapper)[0].id
// and then immediately delete it before upload "completes"
instance.deleteFile(fileId)
// Wait for the update
await process.nextTick
expect(getFiles(wrapper).length).toBe(0)
expect(instance.status).toBe("ready")
// WidgetStateManager will still have been called once, with a single
// value - the id that was last returned from the server.
expect(props.widgetMgr.setFileUploaderStateValue).toHaveBeenCalledTimes(1)
expect(props.widgetMgr.setFileUploaderStateValue).toHaveBeenCalledWith(
props.element,
buildFileUploaderStateProto(INITIAL_SERVER_FILE_ID, []),
{
fromUi: true,
}
)
})
it("can delete file with ErrorStatus", () => {
const props = getProps()
jest.spyOn(props.widgetMgr, "setFileUploaderStateValue")
const wrapper = shallow(<FileUploader {...props} />)
const instance = wrapper.instance() as FileUploader
const fileDropzone = wrapper.find(FileDropzone)
// Drop a file with an error status
fileDropzone
.props()
.onDrop([], [{ file: createFile(), errors: [INVALID_TYPE_ERROR] }])
expect(getFiles(wrapper, "error").length).toBe(1)
// Delete the file
instance.deleteFile(getFiles(wrapper)[0].id)
// File should be gone
expect(getFiles(wrapper).length).toBe(0)
// WidgetStateManager should not have been called - no uploads happened.
expect(props.widgetMgr.setFileUploaderStateValue).not.toHaveBeenCalled()
})
it("handles upload error", async () => {
const props = getProps()
const wrapper = shallow(<FileUploader {...props} />)
const instance = wrapper.instance() as FileUploader
// Upload a file that will be rejected by the server
props.uploadClient.uploadFile = jest
.fn()
.mockRejectedValue(new Error("random upload error!"))
instance.uploadFile(createFile())
expect(getFiles(wrapper)[0].status.type).toBe("uploading")
// Wait one tick for the upload to be rejected
await process.nextTick
// And another for the uploader to be re-rendered
await process.nextTick
// Our file should have an error status, and our uploader should still be
// "ready"
expect(getFiles(wrapper)[0].status.type).toBe("error")
expect(
(getFiles(wrapper)[0].status as ErrorStatus).errorMessage
).toContain("random upload error!")
expect(instance.status).toBe("ready")
})
it("changes status + adds file attributes when dropping a File", () => {
const props = getProps()
const wrapper = shallow(<FileUploader {...props} />)
const fileDropzone = wrapper.find(FileDropzone)
fileDropzone.props().onDrop([createFile()], [])
const files = getFiles(wrapper)
expect(files[0].status.type).toBe("uploading")
expect((files[0].status as UploadingStatus).cancelToken).toBeDefined()
expect(files[0].id).toBeDefined()
})
it("shows an ErrorStatus when File extension is not allowed", () => {
const props = getProps({ type: ["png"] })
const wrapper = shallow(<FileUploader {...props} />)
const instance = wrapper.instance() as FileUploader
const fileDropzone = wrapper.find(FileDropzone)
fileDropzone
.props()
.onDrop([], [{ file: createFile(), errors: [INVALID_TYPE_ERROR] }])
expect(getFiles(wrapper)[0].status.type).toBe("error")
expect((getFiles(wrapper)[0].status as ErrorStatus).errorMessage).toBe(
"text/plain files are not allowed."
)
// If a file has an error, the FileUploader still has a valid status
expect(instance.status).toBe("ready")
})
it("shows an ErrorStatus when maxUploadSizeMb = 0", () => {
const props = getProps({ maxUploadSizeMb: 0 })
const wrapper = shallow(<FileUploader {...props} />)
const instance = wrapper.instance() as FileUploader
const fileDropzone = wrapper.find(FileDropzone)
fileDropzone
.props()
.onDrop([], [{ file: createFile(), errors: [FILE_TOO_LARGE] }])
const files: UploadFileInfo[] = wrapper.state("files")
expect(files[0].status.type).toBe("error")
expect((files[0].status as ErrorStatus).errorMessage).toBe(
"File must be 0.0B or smaller."
)
// If a file has an error, the FileUploader still has a valid status
expect(instance.status).toBe("ready")
})
it("resets on disconnect", () => {
const props = getProps()
const wrapper = shallow(<FileUploader {...props} />)
// @ts-ignore
const resetSpy = jest.spyOn(wrapper.instance(), "reset")
wrapper.setProps({ disabled: true })
expect(resetSpy).toBeCalled()
})
it("resets its value when form is cleared", async () => {
// Create a widget in a clearOnSubmit form
const props = getProps({ formId: "form" })
jest.spyOn(props.widgetMgr, "setFileUploaderStateValue")
props.widgetMgr.setFormClearOnSubmit("form", true)
jest.spyOn(props.widgetMgr, "setIntValue")
const wrapper = shallow(<FileUploader {...props} />)
// Upload a single file
const fileDropzone = wrapper.find(FileDropzone)
fileDropzone.props().onDrop([createFile()], [])
await process.nextTick
const serverFileId = getServerFileId(getFiles(wrapper)[0]) as number
expect(wrapper.state("files")).toHaveLength(1)
expect(props.widgetMgr.setFileUploaderStateValue).toHaveBeenCalledWith(
props.element,
buildFileUploaderStateProto(serverFileId, [serverFileId]),
{
fromUi: true,
}
)
// "Submit" the form
props.widgetMgr.submitForm({ id: "submitFormButtonId", formId: "form" })
wrapper.update()
// Our widget should be reset, and the widgetMgr should be updated
expect(wrapper.state("files")).toHaveLength(0)
expect(props.widgetMgr.setFileUploaderStateValue).toHaveBeenCalledWith(
props.element,
buildFileUploaderStateProto(serverFileId, []),
{
fromUi: true,
}
)
})
}) | the_stack |
import { BaseResource } from 'ms-rest-azure';
import { CloudError } from 'ms-rest-azure';
import * as moment from 'moment';
export { BaseResource } from 'ms-rest-azure';
export { CloudError } from 'ms-rest-azure';
/**
* @class
* Initializes a new instance of the Resource class.
* @constructor
* Resource Manager Resource Information.
*
* @member {string} [id] Resource Manager Resource ID.
* @member {string} [type] Resource Manager Resource Type.
* @member {string} [name] Resource Manager Resource Name.
* @member {string} [location] Resource Manager Resource Location.
* @member {object} [tags] Resource Manager Resource Tags.
* @member {string} [etag]
*/
export interface Resource extends BaseResource {
readonly id?: string;
readonly type?: string;
readonly name?: string;
readonly location?: string;
tags?: { [propertyName: string]: string };
etag?: string;
}
/**
* @class
* Initializes a new instance of the EncryptionJwkResource class.
* @constructor
* The public key of the gateway.
*
* @member {string} [kty]
* @member {string} [alg]
* @member {string} [e]
* @member {string} [n]
*/
export interface EncryptionJwkResource {
kty?: string;
alg?: string;
e?: string;
n?: string;
}
/**
* @class
* Initializes a new instance of the GatewayStatus class.
* @constructor
* Expanded gateway status information.
*
* @member {number} [availableMemoryMByte] The available memory on the gateway
* host machine in megabytes.
* @member {number} [gatewayCpuUtilizationPercent] The CPU utilization of the
* gateway process (numeric value between 0 and 100).
* @member {number} [totalCpuUtilizationPercent] CPU Utilization of the whole
* system.
* @member {string} [gatewayVersion] The version of the gateway that is
* installed on the system.
* @member {string} [friendlyOsName] The Plaintext description of the OS on the
* gateway.
* @member {date} [installedDate] The date the gateway was installed.
* @member {number} [logicalProcessorCount] Number of logical processors in the
* gateway system.
* @member {string} [name] The computer name of the gateway system.
* @member {string} [gatewayId] The gateway resource ID.
* @member {number} [gatewayWorkingSetMByte] The working set size of the
* gateway process in megabytes.
* @member {date} [statusUpdated] UTC date and time when gateway status was
* last updated.
* @member {string} [groupPolicyError] The group policy error.
* @member {boolean} [allowGatewayGroupPolicyStatus] Status of the
* allowGatewayGroupPolicy setting.
* @member {boolean} [requireMfaGroupPolicyStatus] Status of the
* requireMfaGroupPolicy setting.
* @member {string} [encryptionCertificateThumbprint] Thumbprint of the
* encryption certificate.
* @member {string} [secondaryEncryptionCertificateThumbprint] Secondary
* thumbprint of the encryption certificate.
* @member {object} [encryptionJwk] The encryption certificate key.
* @member {string} [encryptionJwk.kty]
* @member {string} [encryptionJwk.alg]
* @member {string} [encryptionJwk.e]
* @member {string} [encryptionJwk.n]
* @member {object} [secondaryEncryptionJwk] The secondary encryption
* certificate key.
* @member {string} [secondaryEncryptionJwk.kty]
* @member {string} [secondaryEncryptionJwk.alg]
* @member {string} [secondaryEncryptionJwk.e]
* @member {string} [secondaryEncryptionJwk.n]
* @member {number} [activeMessageCount] Active message count.
* @member {string} [latestPublishedMsiVersion] Latest published version of the
* gateway install MSI.
* @member {date} [publishedTimeUtc] Gateway install MSI published time.
*/
export interface GatewayStatus {
availableMemoryMByte?: number;
gatewayCpuUtilizationPercent?: number;
totalCpuUtilizationPercent?: number;
gatewayVersion?: string;
friendlyOsName?: string;
installedDate?: Date;
logicalProcessorCount?: number;
name?: string;
gatewayId?: string;
gatewayWorkingSetMByte?: number;
statusUpdated?: Date;
groupPolicyError?: string;
allowGatewayGroupPolicyStatus?: boolean;
requireMfaGroupPolicyStatus?: boolean;
encryptionCertificateThumbprint?: string;
secondaryEncryptionCertificateThumbprint?: string;
encryptionJwk?: EncryptionJwkResource;
secondaryEncryptionJwk?: EncryptionJwkResource;
activeMessageCount?: number;
latestPublishedMsiVersion?: string;
publishedTimeUtc?: Date;
}
/**
* @class
* Initializes a new instance of the GatewayResource class.
* @constructor
* Data model for an arm gateway resource.
*
* @member {date} [created] UTC date and time when gateway was first added to
* management service.
* @member {date} [updated] UTC date and time when node was last updated.
* @member {string} [upgradeMode] The upgradeMode property gives the
* flexibility to gateway to auto upgrade itself. If properties value not
* specified, then we assume upgradeMode = Automatic. Possible values include:
* 'Manual', 'Automatic'
* @member {string} [desiredVersion] Latest available MSI version.
* @member {array} [instances] Names of the nodes in the gateway.
* @member {number} [activeMessageCount] Number of active messages.
* @member {string} [latestPublishedMsiVersion] Last published MSI version.
* @member {date} [publishedTimeUtc] The date/time of the last published
* gateway.
* @member {string} [installerDownload] Installer download uri.
* @member {string} [minimumVersion] Minimum gateway version.
*/
export interface GatewayResource extends Resource {
created?: Date;
updated?: Date;
upgradeMode?: string;
desiredVersion?: string;
instances?: GatewayStatus[];
activeMessageCount?: number;
latestPublishedMsiVersion?: string;
publishedTimeUtc?: Date;
readonly installerDownload?: string;
readonly minimumVersion?: string;
}
/**
* @class
* Initializes a new instance of the GatewayProfile class.
* @constructor
* JSON properties that the gateway service uses know how to communicate with
* the resource.
*
* @member {string} [dataPlaneServiceBaseAddress] The Dataplane connection URL.
* @member {string} [gatewayId] The ID of the gateway.
* @member {string} [environment] The environment for the gateway (DEV,
* DogFood, or Production).
* @member {string} [upgradeManifestUrl] Gateway upgrade manifest URL.
* @member {string} [messagingNamespace] Messaging namespace.
* @member {string} [messagingAccount] Messaging Account.
* @member {string} [messagingKey] Messaging Key.
* @member {string} [requestQueue] Request queue name.
* @member {string} [responseTopic] Response topic name.
* @member {string} [statusBlobSignature] The gateway status blob SAS URL.
*/
export interface GatewayProfile {
dataPlaneServiceBaseAddress?: string;
gatewayId?: string;
environment?: string;
upgradeManifestUrl?: string;
messagingNamespace?: string;
messagingAccount?: string;
messagingKey?: string;
requestQueue?: string;
responseTopic?: string;
statusBlobSignature?: string;
}
/**
* @class
* Initializes a new instance of the GatewayParameters class.
* @constructor
* Collection of parameters for operations on a gateway resource.
*
* @member {string} [location] Location of the resource.
* @member {object} [tags] Resource tags.
* @member {string} [upgradeMode] The upgradeMode property gives the
* flexibility to gateway to auto upgrade itself. If properties value not
* specified, then we assume upgradeMode = Automatic. Possible values include:
* 'Manual', 'Automatic'
*/
export interface GatewayParameters {
location?: string;
tags?: any;
upgradeMode?: string;
}
/**
* @class
* Initializes a new instance of the NodeResource class.
* @constructor
* A Node Resource.
*
* @member {string} [gatewayId] ID of the gateway.
* @member {string} [connectionName] myhost.domain.com
* @member {date} [created] UTC date and time when node was first added to
* management service.
* @member {date} [updated] UTC date and time when node was last updated.
*/
export interface NodeResource extends Resource {
gatewayId?: string;
connectionName?: string;
created?: Date;
updated?: Date;
}
/**
* @class
* Initializes a new instance of the NodeParameters class.
* @constructor
* Parameter collection for operations on arm node resource.
*
* @member {string} [location] Location of the resource.
* @member {object} [tags] Resource tags.
* @member {string} [gatewayId] Gateway ID which will manage this node.
* @member {string} [connectionName] myhost.domain.com
* @member {string} [userName] User name to be used to connect to node.
* @member {string} [password] Password associated with user name.
*/
export interface NodeParameters {
location?: string;
tags?: any;
gatewayId?: string;
connectionName?: string;
userName?: string;
password?: string;
}
/**
* @class
* Initializes a new instance of the SessionResource class.
* @constructor
* The session object.
*
* @member {string} [userName] The username connecting to the session.
* @member {date} [created] UTC date and time when node was first added to
* management service.
* @member {date} [updated] UTC date and time when node was last updated.
*/
export interface SessionResource extends Resource {
userName?: string;
created?: Date;
updated?: Date;
}
/**
* @class
* Initializes a new instance of the SessionParameters class.
* @constructor
* Parameter collection for creation and other operations on sessions.
*
* @member {string} [userName] Encrypted User name to be used to connect to
* node.
* @member {string} [password] Encrypted Password associated with user name.
* @member {string} [retentionPeriod] Session retention period. Possible values
* include: 'Session', 'Persistent'
* @member {string} [credentialDataFormat] Credential data format. Possible
* values include: 'RsaEncrypted'
* @member {string} [encryptionCertificateThumbprint] Encryption certificate
* thumbprint.
*/
export interface SessionParameters {
userName?: string;
password?: string;
retentionPeriod?: string;
credentialDataFormat?: string;
encryptionCertificateThumbprint?: string;
}
/**
* @class
* Initializes a new instance of the Version class.
* @constructor
* A multipart-numeric version number.
*
* @member {number} [major] The leftmost number of the version.
* @member {number} [minor] The second leftmost number of the version.
* @member {number} [build] The third number of the version.
* @member {number} [revision] The fourth number of the version.
* @member {number} [majorRevision] The MSW of the fourth part.
* @member {number} [minorRevision] The LSW of the fourth part.
*/
export interface Version {
major?: number;
minor?: number;
build?: number;
revision?: number;
majorRevision?: number;
minorRevision?: number;
}
/**
* @class
* Initializes a new instance of the PowerShellSessionResource class.
* @constructor
* A PowerShell session resource (practically equivalent to a runspace
* instance).
*
* @member {string} [sessionId] The PowerShell Session ID.
* @member {string} [state] The runspace state.
* @member {string} [runspaceAvailability] The availability of the runspace.
* @member {date} [disconnectedOn] Timestamp of last time the service
* disconnected from the runspace.
* @member {date} [expiresOn] Timestamp when the runspace expires.
* @member {object} [version]
* @member {number} [version.major] The leftmost number of the version.
* @member {number} [version.minor] The second leftmost number of the version.
* @member {number} [version.build] The third number of the version.
* @member {number} [version.revision] The fourth number of the version.
* @member {number} [version.majorRevision] The MSW of the fourth part.
* @member {number} [version.minorRevision] The LSW of the fourth part.
* @member {string} [powerShellSessionResourceName] Name of the runspace.
*/
export interface PowerShellSessionResource extends Resource {
sessionId?: string;
state?: string;
runspaceAvailability?: string;
disconnectedOn?: Date;
expiresOn?: Date;
version?: Version;
powerShellSessionResourceName?: string;
}
/**
* @class
* Initializes a new instance of the PromptFieldDescription class.
* @constructor
* Field description for the implementation of PSHostUserInterface.Prompt
*
* @member {string} [name] The name of the prompt.
* @member {string} [label] The label text of the prompt.
* @member {string} [helpMessage] The help message of the prompt.
* @member {boolean} [promptFieldTypeIsList] When set to 'true' the prompt
* field type is a list of values.
* @member {string} [promptFieldType] Possible values include: 'String',
* 'SecureString', 'Credential'
*/
export interface PromptFieldDescription {
name?: string;
label?: string;
helpMessage?: string;
promptFieldTypeIsList?: boolean;
promptFieldType?: string;
}
/**
* @class
* Initializes a new instance of the PowerShellCommandResult class.
* @constructor
* Results from invoking a PowerShell command.
*
* @member {number} [messageType] The type of message.
* @member {string} [foregroundColor] The HTML color string representing the
* foreground color.
* @member {string} [backgroundColor] The HTML color string representing the
* background color.
* @member {string} [value] Actual result text from the PowerShell Command.
* @member {string} [prompt] The interactive prompt message.
* @member {number} [exitCode] The exit code from a executable that was called
* from PowerShell.
* @member {number} [id] ID of the prompt message.
* @member {string} [caption] Text that precedes the prompt.
* @member {string} [message] Text of the prompt.
* @member {array} [descriptions] Collection of PromptFieldDescription objects
* that contains the user input.
*/
export interface PowerShellCommandResult {
messageType?: number;
foregroundColor?: string;
backgroundColor?: string;
value?: string;
prompt?: string;
exitCode?: number;
id?: number;
caption?: string;
message?: string;
descriptions?: PromptFieldDescription[];
}
/**
* @class
* Initializes a new instance of the PowerShellCommandResults class.
* @constructor
* A collection of results from a PowerShell command.
*
* @member {array} [results]
* @member {string} [pssession]
* @member {string} [command]
* @member {boolean} [completed]
*/
export interface PowerShellCommandResults {
results?: PowerShellCommandResult[];
pssession?: string;
command?: string;
completed?: boolean;
}
/**
* @class
* Initializes a new instance of the PowerShellCommandStatus class.
* @constructor
* Result status from invoking a PowerShell command.
*
* @member {array} [results]
* @member {string} [pssession]
* @member {string} [command]
* @member {boolean} [completed]
*/
export interface PowerShellCommandStatus extends Resource {
results?: PowerShellCommandResult[];
pssession?: string;
command?: string;
completed?: boolean;
}
/**
* @class
* Initializes a new instance of the PowerShellSessionResources class.
* @constructor
* A collection of PowerShell session resources
*
* @member {array} [value] Collection of PowerShell session resources.
* @member {string} [nextLink] The URL to the next set of resources.
*/
export interface PowerShellSessionResources {
value?: PowerShellSessionResource[];
nextLink?: string;
}
/**
* @class
* Initializes a new instance of the PowerShellCommandParameters class.
* @constructor
* The parameters to a PowerShell script execution command.
*
* @member {string} [command] Script to execute.
*/
export interface PowerShellCommandParameters {
command?: string;
}
/**
* @class
* Initializes a new instance of the PromptMessageResponse class.
* @constructor
* The response to a prompt message.
*
* @member {array} [response] The list of responses a cmdlet expects.
*/
export interface PromptMessageResponse {
response?: string[];
}
/**
* @class
* Initializes a new instance of the PowerShellTabCompletionParameters class.
* @constructor
* Collection of parameters for PowerShell tab completion.
*
* @member {string} [command] Command to get tab completion for.
*/
export interface PowerShellTabCompletionParameters {
command?: string;
}
/**
* @class
* Initializes a new instance of the PowerShellTabCompletionResults class.
* @constructor
* An array of strings representing the different values that can be selected
* through.
*
* @member {array} [results]
*/
export interface PowerShellTabCompletionResults {
results?: string[];
}
/**
* @class
* Initializes a new instance of the ErrorModel class.
* @constructor
* Error message.
*
* @member {number} [code]
* @member {string} [message]
* @member {string} [fields]
*/
export interface ErrorModel {
code?: number;
message?: string;
fields?: string;
}
/**
* @class
* Initializes a new instance of the GatewayResources class.
* @constructor
* Collection of Gateway Resources.
*
* @member {string} [nextLink] The URL to the next set of resources.
*/
export interface GatewayResources extends Array<GatewayResource> {
nextLink?: string;
}
/**
* @class
* Initializes a new instance of the NodeResources class.
* @constructor
* A collection of node resource objects.
*
* @member {string} [nextLink] The URL to the next set of resources.
*/
export interface NodeResources extends Array<NodeResource> {
nextLink?: string;
} | the_stack |
import * as _ from "underscore";
import {HttpClient} from "@angular/common/http";
import {StateService} from "@uirouter/angular";
import {Component, EventEmitter, Injector, Input, OnInit, Output} from "@angular/core";
import {DomSanitizer} from "@angular/platform-browser";
import {SelectionService, SingleSelectionPolicy} from "../../api/services/selection.service";
import {DataSource} from "../../api/models/datasource";
import {Node} from '../../api/models/node';
import {MatDialog} from "@angular/material/dialog";
import {SatusDialogComponent} from "../../dialog/status-dialog.component";
import 'rxjs/add/observable/of';
import {MatDialogRef} from "@angular/material/dialog/typings/dialog-ref";
import {ITdDataTableSortChangeEvent, TdDataTableService, TdDataTableSortingOrder} from '@covalent/core/data-table';
import {PreviewUploadDataSet} from "./model/preview-upload-data-set";
import {SchemaParseSettingsDialog} from "./schema-parse-settings-dialog.component";
import {SimpleChanges} from "@angular/core/src/metadata/lifecycle_hooks";
import {TableColumn} from "./model/table-view-model"
import {FileMetadataTransformService} from "./service/file-metadata-transform.service";
import {FileMetadataTransformResponse} from "./model/file-metadata-transform-response";
import {PreviewSchemaService} from "./service/preview-schema.service";
import {PreviewRawService} from "./service/preview-raw.service";
import {PreviewDataSetRequest} from "./model/preview-data-set-request";
import {DatasetCollectionStatus, PreviewDataSet} from "./model/preview-data-set";
import {PreviewJdbcDataSet} from "./model/preview-jdbc-data-set";
import {PreviewFileDataSet} from "./model/preview-file-data-set";
import {PreviewDatasetCollectionService} from "../../api/services/preview-dataset-collection.service";
import {Common} from '../../../../../lib/common/CommonTypes';
//NOT USED NOW!!!
@Component({
selector: "preview-schema",
template: "<div></div>"
})
export class PreviewSchemaComponent implements OnInit {
/**
* The datasource to use to connect and preview
*/
@Input()
public datasource: DataSource;
/**
* Optional set of incoming paths to be used to create datasets to preview.
* This will be if a user is viewing a feed or dataset that has already been saved.
* If not specified the component will attempt to get the paths from the selection-service.
* This will be in the case of coming directly from the catalog
*/
@Input()
public paths?:string[];
/**
* Flag to allow for edit actions
*/
@Input()
public editable:boolean;
/**
* if true it will collect the first dataset (if not already collected) and add it to the preivew-dataset-collection service
*/
@Input()
public autoCollect:boolean;
@Input()
public addToCollectionButtonName:string = "Add"
@Input()
public removeFromCollectionButtonName:string = "Remove";
/**
* a custom event allowing users to override what happens when a user removes a dataset from the collection service.
* NOTE the user of this needs to include the logic to do the removal of the dataset from the collection service
* @type {EventEmitter<PreviewDataSet>}
*/
@Output()
public customDatasetRemoval:EventEmitter<PreviewDataSet> = new EventEmitter<PreviewDataSet>();
/**
* a custom event allowing users to override what happens when a user adds a dataset to the collection service.
* NOTE: the user of this needs to include the logic to add the dataset to the collectoin service.
* @type {EventEmitter<PreviewDataSet>}
*/
@Output()
public customDatasetAddition:EventEmitter<PreviewDataSet> = new EventEmitter<PreviewDataSet>();
statusDialogRef: MatDialogRef<SatusDialogComponent>;
/**
* A Object<string,PreviewDataSet> where the key is the dataset.key
*/
datasetMap:Common.Map<PreviewDataSet>;
/**
* the dataset.key array
*/
datasetKeys :string[]
/**
* The array of datasets to be previewed
*/
datasets:PreviewDataSet[];
/**
* The selected dataset
*/
selectedDataSet:PreviewDataSet | PreviewFileDataSet
/**
* Flag to indicate we are allowed to view raw or preview
*/
selectedDataSetViewRaw:boolean;
/**
* optional error message populated after a dataset is previewed
*/
message:string
/**
* is it set to only allow 1 node selection
* @type {boolean}
*/
singleNodeSelection:boolean = false;
/**
* Shared service with the Visual Query to store the datasets
*/
previewDatasetCollectionService : PreviewDatasetCollectionService
/**
* Query engine for the data model
*/
// engine: QueryEngine<any> ;
constructor(private http: HttpClient, private sanitizer: DomSanitizer, private selectionService: SelectionService, private dialog: MatDialog, private fileMetadataTransformService: FileMetadataTransformService, private previewRawService :PreviewRawService, private previewSchemaService :PreviewSchemaService, private $$angularInjector: Injector, private stateService: StateService) {
this.previewDatasetCollectionService = $$angularInjector.get("PreviewDatasetCollectionService");
this.singleNodeSelection = this.selectionService.hasPolicy(SingleSelectionPolicy);
}
public ngOnInit(): void {
// this.engine = this.sparkQueryEngine;
//this.engine = this.queryEngineFactory.getEngine('spark')
//this.previewDatasetCollectionService.reset();
this.createDataSets();
}
public showAddToCollectionButton(dataSet:PreviewDataSet){
let collectedSize = this.previewDatasetCollectionService.datasetCount();
return this.editable && !dataSet.isCollected() && !dataSet.isLoading();
}
public showRemoveFromCollectionButton(dataSet:PreviewDataSet){
let collectedSize = this.previewDatasetCollectionService.datasetCount();
return this.editable && dataSet.isCollected() && (!this.singleNodeSelection || (this.singleNodeSelection && this.datasets && this.datasets.length >1));
}
private addCollectedDatasets(){
this.previewDatasetCollectionService.datasets.forEach(dataset => {
let key = dataset.key;
if(this.datasetKeys.indexOf(key) <0){
this.datasetKeys.push(key)
this.datasetMap[key] = dataset;
this.datasets.push(dataset)
}
else {
}
})
}
openSchemaParseSettingsDialog(): void {
let dialogRef = this.dialog.open(SchemaParseSettingsDialog, {
width: '500px',
data: { schemaParser: (<PreviewFileDataSet>this.selectedDataSet).schemaParser,
sparkScript: (<PreviewFileDataSet>this.selectedDataSet).sparkScript
}
});
dialogRef.afterClosed().subscribe(result => {
///update it
});
}
private openStatusDialog(title: string, message: string, showProgress:boolean,renderActionButtons?: boolean): void {
this.closeStatusDialog();
if (renderActionButtons == undefined) {
renderActionButtons = false;
}
this.statusDialogRef = this.dialog.open(SatusDialogComponent, {
data: {
renderActionButtons: renderActionButtons,
title: title,
message: message,
showProgress:showProgress
}
});
}
private closeStatusDialog(): void {
if (this.statusDialogRef) {
this.statusDialogRef.close();
}
}
/**
* Switch between raw view and data preview
*/
onToggleRaw(){
this.selectedDataSetViewRaw = !this.selectedDataSetViewRaw
if(this.selectedDataSetViewRaw){
//view raw
this.loadRawData();
}
}
/**
* make the request to load in the raw view. *
*/
loadRawData(){
this.selectedDataSetViewRaw = true;
if(this.selectedDataSet.raw == undefined) {
this.previewRawService.preview((<PreviewFileDataSet>this.selectedDataSet)).subscribe((data: PreviewDataSet) => {
this.selectedDataSetViewRaw = true;
}, (error1:any) => {
console.log("Error loading Raw data",error1)
})
}
}
/**
* When a user selects a dataset it will attempt to load in the preview data.
* if that has an error
* @param {string} datasetKey
*/
onDatasetSelected(datasetKey: string){
this.selectedDataSet = this.datasetMap[datasetKey];
//toggle the raw flag back to preview
this.selectedDataSetViewRaw =false;
this.preview();
}
preview(){
if (!this.selectedDataSet.hasPreview()) {
let previewRequest = new PreviewDataSetRequest()
previewRequest.dataSource = this.datasource;
this.selectedDataSet.applyPreviewRequestProperties(previewRequest);
let isNew = !this.selectedDataSet.hasPreview();
this.selectedDataSet.dataSource = this.datasource;
//add in other properties
this.previewSchemaService.preview(this.selectedDataSet, previewRequest,false).subscribe((data: PreviewDataSet) => {
this.selectedDataSetViewRaw = false;
//auto collect the first one if there is only 1 dataset and its editable
if(this.autoCollect && this.editable){ //this.datasetKeys.length == 1 &&
this.addToCollection(this.selectedDataSet);
}
}, (error1:any) => {
console.error("unable to preview dataset ",error1);
this.selectedDataSet.previewError("unable to preview dataset ");
if(this.selectedDataSet.allowsRawView) {
this.loadRawData();
}
})
}
}
/**
* add the dataset
* @param {PreviewDataSet} dataset
*/
addToCollection(dataset: PreviewDataSet){
if(this.customDatasetAddition.observers.length >0) {
this.customDatasetAddition.emit(dataset);
}
else {
this.previewDatasetCollectionService.addDataSet(dataset);
}
}
/**
* remove the dataset
* @param {PreviewDataSet} dataset
*/
removeFromCollection(dataset:PreviewDataSet){
if(this.customDatasetRemoval.observers.length >0) {
this.customDatasetRemoval.emit(dataset);
}
else {
this.previewDatasetCollectionService.remove(dataset);
}
}
/**
* Go to the visual query populating with the selected datasets
*/
visualQuery(){
this.stateService.go("visual-query");
}
/**
* Create the datasets for the selected nodes
*/
createDataSets(){
let paths = this.paths;
if(paths == undefined){
//attempt to get the paths from the selectionService and selected node
//this is if the paths are not explicitly passed in. it will pull them from the catalog selection
let node: Node = <Node> this.selectionService.get(this.datasource.id);
if(node) {
paths = this.fileMetadataTransformService.getSelectedItems(node, this.datasource);
}
}
if(paths) {
//TODO Move to Factory
this.openStatusDialog("Examining file metadata", "Validating file metadata",true,false)
if (!this.datasource.connector.template.format) {
this.createFileBasedDataSets(paths);
}
else if (this.datasource.connector.template.format == "jdbc") {
let datasets = {}
paths.forEach(path => {
let dataSet = new PreviewJdbcDataSet();
dataSet.items = [path];
dataSet.displayKey = path;
dataSet.key = path;
dataSet.allowsRawView = false;
dataSet.updateDisplayKey();
datasets[dataSet.key] = dataSet;
//add in any cached preview responses
this.previewSchemaService.updateDataSetsWithCachedPreview([dataSet])
//update the CollectionStatus
if(this.previewDatasetCollectionService.exists(dataSet) && !dataSet.isCollected()){
dataSet.collectionStatus = DatasetCollectionStatus.COLLECTED;
}
if(this.autoCollect && this.editable){
this.addToCollection(dataSet);
}
});
this.setAndSelectFirstDataSet(datasets);
}
} else if ((this.datasource as any).$uploadDataSet) {
this.openStatusDialog("Examining file metadata", "Validating file metadata",true,false);
const dataSet = (this.datasource as any).$uploadDataSet;
this.fileMetadataTransformService.detectFormatForPaths(dataSet.paths, this.datasource).subscribe((response: FileMetadataTransformResponse) => {
if (response.results) {
this.message = response.message;
//add in any cached preview responses
const resultDataSet: PreviewDataSet = (Object as any).values(response.results.datasets as any)[0];
const previewDataSet = new PreviewUploadDataSet(resultDataSet, dataSet);
this.previewSchemaService.updateDataSetsWithCachedPreview([previewDataSet])
if(this.autoCollect && this.editable){
this.addToCollection(previewDataSet);
}
if(this.previewDatasetCollectionService.exists(previewDataSet) && !previewDataSet.isCollected()){
previewDataSet.collectionStatus = DatasetCollectionStatus.COLLECTED;
}
//select and transform the first dataset
const map = {};
map[previewDataSet.key] = previewDataSet;
this.setAndSelectFirstDataSet(map);
this.closeStatusDialog();
}
else {
this.openStatusDialog("Error. Cant process", "No results found ", false,true);
}
},error1 => (response:FileMetadataTransformResponse) => {
this.openStatusDialog("Error","Error",false,true);
});
// const dataSets = {};
// dataSets[uploadDataSet.id] = new PreviewSparkDataSet(uploadDataSet);
// this.setAndSelectFirstDataSet(daat);
} else {
this.openStatusDialog("No path has been supplied. ","Please select an item to preview from the catalog",false,true);
}
}
/**
* set the datasets array and select the first one
* @param {Common.Map<PreviewDataSet>} datasetMap
*/
setAndSelectFirstDataSet(datasetMap:Common.Map<PreviewDataSet>){
this.datasetMap = datasetMap;
this.datasetKeys = Object.keys(this.datasetMap);
this.datasets =this.datasetKeys.map(key=>this.datasetMap[key])
let firstKey = this.datasetKeys[0];
this.onDatasetSelected(firstKey);
//add in any existing datasets that are already in the collection
this.addCollectedDatasets()
}
/**
* Attempt to detect the file formats and mimetypes if the datasource used is a file based datasource
*/
createFileBasedDataSets(paths:string[]): void {
if(paths && paths.length >0) {
this.fileMetadataTransformService.detectFormatForPaths(paths,this.datasource).subscribe((response:FileMetadataTransformResponse)=> {
if (response.results ) {
this.message = response.message;
//add in any cached preview responses
_.each(response.results.datasets,(dataset:PreviewDataSet,key:string)=> {
this.previewSchemaService.updateDataSetsWithCachedPreview([dataset])
if(this.autoCollect && this.editable){
this.addToCollection(dataset);
}
if(this.previewDatasetCollectionService.exists(dataset) && !dataset.isCollected()){
dataset.collectionStatus = DatasetCollectionStatus.COLLECTED;
}
});
//select and transform the first dataset
this.setAndSelectFirstDataSet(response.results.datasets);
this.closeStatusDialog();
}
else {
this.openStatusDialog("Error. Cant process", "No results found ", false,true);
}
},error1 => (response:FileMetadataTransformResponse) => {
this.openStatusDialog("Error","Error",false,true);
});
}
}
}
@Component({
selector: 'dataset-simple-table-X',
styleUrls:["./dataset-simple-table.component.scss"],
template:`
<div class="dataset-simple-table">
<table td-data-table >
<thead>
<tr td-data-table-column-row>
<th td-data-table-column
*ngFor="let column of columns"
[name]="column.name"
[sortable]="false"
[numeric]="column.numeric"
(sortChange)="sort($event)"
[sortOrder]="sortOrder">
{{column.label}} <br/>
({{column.dataType}})
</th>
</tr>
</thead>
<tbody>
<tr td-data-table-row *ngFor="let row of filteredData">
<td td-data-table-cell *ngFor="let column of columns"
[numeric]="column.numeric">
{{row[column.name]}}
</td>
</tr>
</tbody>
</table>
</div>
<!--
<td-data-table
[data]="filteredData"
[columns]="columns"
[selectable]="false"
[clickable]="true"
[multiple]="multiple"
[sortable]="false"
[sortBy]="sortBy"
[(ngModel)]="selected"
[sortOrder]="sortOrder"
(rowClick)="rowSelected($event)"
(sortChange)="sort($event)"
[style.height.px]="325" class="dataset-simple-table">
</td-data-table>
-->
<div *ngIf="filteredData.length !== 0" fxLayout="row" fxLayoutAlign="center center">
<h3>No results to display.</h3>
</div>`
})
export class SimpleTableComponent {
@Input()
rows:any[];
@Input()
columns:TableColumn[] = [];
constructor( private _dataTableService: TdDataTableService){
}
/**
* All the data
* @type {any[]}
*/
data:any[] = [];
/**
* sorted/filtered data displayed in the ui
* @type {any[]}
*/
filteredData:any[] = [];
sortBy: string = '';
sortOrder: TdDataTableSortingOrder = TdDataTableSortingOrder.Descending;
sort(sortEvent: ITdDataTableSortChangeEvent): void {
this.sortBy = sortEvent.name;
this.sortOrder = sortEvent.order === TdDataTableSortingOrder.Descending ? TdDataTableSortingOrder.Ascending : TdDataTableSortingOrder.Descending;
this.filter();
}
filter(){
let newData:any[] = this.data;
newData = this._dataTableService.sortData(newData, this.sortBy, this.sortOrder);
this.filteredData = newData;
}
ngOnInit(){
this.initTable();
}
ngOnChanges(changes: SimpleChanges) {
if(changes && (!changes.rows.firstChange || !changes.columns.firstChange)){
this.initTable();
}
}
initTable(){
if(this.columns) {
this.sortBy = this.columns[0].name;
}
else {
this.columns = [];
}
// Add table data
this.data = this.rows;
this.filter();
}
}
@Component({
selector:'dataset-schema-definition-X',
template:`
<dataset-simple-table [class.small]="smallView" [rows]="columns" [columns]="schemaColumns"></dataset-simple-table>
`
})
export class SchemaDefinitionComponent implements OnInit {
@Input()
columns:TableColumn[]
@Input()
smallView:boolean = true;
schemaColumns:TableColumn[]
constructor() {
}
private toDataTable(){
let schemaColumns :TableColumn[] = []
schemaColumns.push({"name":"name","label":"Column Name","dataType":"string","sortable":true})
schemaColumns.push({"name":"dataType","label":"Data Type","dataType":"string","sortable":true})
this.schemaColumns = schemaColumns;
}
ngOnInit(){
if(this.columns == undefined){
this.columns = [];
}
this.toDataTable();
}
} | the_stack |
// Borrowed from https://github.com/kelseasy/web-ext-types
// Last updated at 7-4-2018 to commit daae1085685b97efdb98c59668cbdfd91c5c874c
// This Source Code Form is subject to the terms of the Mozilla Public
// license, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
interface CRMBrowserEvListener<T extends Function> {
addListener: BrowserReturnValue<void>;
removeListener: BrowserReturnValue<void>
hasListener: BrowserReturnValue<boolean>;
}
/**
* Data about a chrome request
*/
interface BrowserReturnRequest {
/**
* The API it's using
*/
api: string,
/**
* Arguments passed to the request
*/
chromeAPIArguments: {
/**
* The type of argument
*/
type: 'fn'|'arg'|'return';
/**
* The value of the argument
*/
val: any;
}[],
/**
* The type of this chrome request (if a special one
* that can not be made by the user themselves)
*/
type?: 'GM_download'|'GM_notification';
}
interface BrowserReturnValue<T> extends Function {
/**
* A regular call with given arguments (functions can only be called once
* unless you use .persistent)
*/
(...params: any[]): BrowserReturnValue<T>;
/**
* A regular call with given arguments (functions can only be called once
* unless you use .persistent)
*/
args: (...params: any[]) => BrowserReturnValue<T>;
/**
* A regular call with given arguments (functions can only be called once
* unless you use .persistent)
*/
a: (...params: any[]) => BrowserReturnValue<T>;
/**
* A persistent callback (that can be called multiple times)
*/
persistent: (...functions: Function[]) => BrowserReturnValue<T>;
/**
* A persistent callback (that can be called multiple times)
*/
p: (...functions: Function[]) => BrowserReturnValue<T>;
/**
* Sends the function and returns a promise that resolves with its result
*/
send: () => Promise<T>;
/**
* Sends the function and returns a promise that resolves with its result
*/
s: () => Promise<T>;
/**
* Info about the request itself
*/
request: BrowserReturnRequest;
}
type CRMBrowserListener<T> = CRMBrowserEvListener<(arg: T) => void>;
declare namespace crmbrowser.alarms {
type Alarm = {
name: string,
scheduledTime: number,
periodInMinutes?: number,
};
type When = {
when?: number,
periodInMinutes?: number,
};
type DelayInMinutes = {
delayInMinutes?: number,
periodInMinutes?: number,
};
function create(name?: string, alarmInfo?: When | DelayInMinutes): BrowserReturnValue<void>;
function get(name?: string): BrowserReturnValue<Alarm|undefined>;
function getAll(): BrowserReturnValue<Alarm[]>;
function clear(name?: string): BrowserReturnValue<boolean>;
function clearAll(): BrowserReturnValue<boolean>;
const onAlarm: CRMBrowserListener<Alarm>;
}
declare namespace crmbrowser.bookmarks {
type BookmarkTreeNodeUnmodifiable = "managed";
type BookmarkTreeNodeType = "bookmark"|"folder"|"separator";
type BookmarkTreeNode = {
id: string,
parentId?: string,
index?: number,
url?: string,
title: string,
dateAdded?: number,
dateGroupModified?: number,
unmodifiable?: BookmarkTreeNodeUnmodifiable,
children?: BookmarkTreeNode[],
type?: BookmarkTreeNodeType,
};
type CreateDetails = {
parentId?: string,
index?: number,
title?: string,
url?: string,
};
function create(bookmark: CreateDetails): BrowserReturnValue<BookmarkTreeNode>;
function get(idOrIdList: string|string[]): BrowserReturnValue<BookmarkTreeNode[]>;
function getChildren(id: string): BrowserReturnValue<BookmarkTreeNode[]>;
function getRecent(numberOfItems: number): BrowserReturnValue<BookmarkTreeNode[]>;
function getSubTree(id: string): BrowserReturnValue<[BookmarkTreeNode]>;
function getTree(): BrowserReturnValue<[BookmarkTreeNode]>;
type Destination = {
parentId: string,
index?: number,
} | {
index: number,
parentId?: string,
};
function move(id: string, destination: Destination): BrowserReturnValue<BookmarkTreeNode>;
function remove(id: string): BrowserReturnValue<void>;
function removeTree(id: string): BrowserReturnValue<void>;
function search(query: string|{
query?: string,
url?: string,
title?: string,
}): BrowserReturnValue<BookmarkTreeNode[]>;
function update(id: string, changes: { title: string, url: string }): BrowserReturnValue<BookmarkTreeNode>;
const onCreated: CRMBrowserEvListener<(id: string, bookmark: BookmarkTreeNode) => void>;
const onRemoved: CRMBrowserEvListener<(id: string, removeInfo: {
parentId: string,
index: number,
node: BookmarkTreeNode,
}) => void>;
const onChanged: CRMBrowserEvListener<(id: string, changeInfo: {
title: string,
url?: string,
}) => void>;
const onMoved: CRMBrowserEvListener<(id: string, moveInfo: {
parentId: string,
index: number,
oldParentId: string,
oldIndex: number,
}) => void>;
}
declare namespace crmbrowser.browserAction {
type ColorArray = [number, number, number, number];
type ImageDataType = ImageData;
function setTitle(details: { title: string, tabId?: number }): BrowserReturnValue<void>;
function getTitle(details: { tabId?: number }): BrowserReturnValue<string>;
type IconViaPath = {
path: string | object,
tabId?: number,
};
type IconViaImageData = {
imageData: ImageDataType,
tabId?: number,
};
function setIcon(details: IconViaPath | IconViaImageData): BrowserReturnValue<void>;
function setPopup(details: { popup: string, tabId?: number }): BrowserReturnValue<void>;
function getPopup(details: { tabId?: number }): BrowserReturnValue<string>;
function openPopup(): BrowserReturnValue<void>;
function setBadgeText(details: { text: string, tabId?: number }): BrowserReturnValue<void>;
function getBadgeText(details: { tabId?: number }): BrowserReturnValue<string>;
function setBadgeBackgroundColor(details: { color: string|ColorArray, tabId?: number }): BrowserReturnValue<void>;
function getBadgeBackgroundColor(details: { tabId?: number }): BrowserReturnValue<ColorArray>;
function enable(tabId?: number): BrowserReturnValue<void>;
function disable(tabId?: number): BrowserReturnValue<void>;
const onClicked: CRMBrowserListener<crmbrowser.tabs.Tab>;
}
declare namespace crmbrowser.browsingData {
type DataTypeSet = {
cache?: boolean,
cookies?: boolean,
downloads?: boolean,
fileSystems?: boolean,
formData?: boolean,
history?: boolean,
indexedDB?: boolean,
localStorage?: boolean,
passwords?: boolean,
pluginData?: boolean,
serverBoundCertificates?: boolean,
serviceWorkers?: boolean,
};
type DataRemovalOptions = {
since?: number,
originTypes?: { unprotectedWeb: boolean },
};
function remove(removalOptions: DataRemovalOptions, dataTypes: DataTypeSet): BrowserReturnValue<void>;
function removeCache(removalOptions?: DataRemovalOptions): BrowserReturnValue<void>;
function removeCookies(removalOptions: DataRemovalOptions): BrowserReturnValue<void>;
function removeDownloads(removalOptions: DataRemovalOptions): BrowserReturnValue<void>;
function removeFormData(removalOptions: DataRemovalOptions): BrowserReturnValue<void>;
function removeHistory(removalOptions: DataRemovalOptions): BrowserReturnValue<void>;
function removePasswords(removalOptions: DataRemovalOptions): BrowserReturnValue<void>;
function removePluginData(removalOptions: DataRemovalOptions): BrowserReturnValue<void>;
function settings(): BrowserReturnValue<{
options: DataRemovalOptions,
dataToRemove: DataTypeSet,
dataRemovalPermitted: DataTypeSet,
}>;
}
declare namespace crmbrowser.commands {
type Command = {
name?: string,
description?: string,
shortcut?: string,
};
function getAll(): BrowserReturnValue<Command[]>;
const onCommand: CRMBrowserListener<string>;
}
declare namespace crmbrowser.contextMenus {
type ContextType = "all" | "page" | "frame" | "page" | "link" | "editable" | "image" | "selection"
| "video" | "audio" | "launcher" | "browser_action" | "page_action" | "password" | "tab";
type ItemType = "normal" | "checkbox" | "radio" | "separator";
type OnClickData = {
menuItemId: number|string,
modifiers: string[],
editable: boolean,
parentMenuItemId?: number|string,
mediaType?: string,
linkUrl?: string,
srcUrl?: string,
pageUrl?: string,
frameUrl?: string,
selectionText?: string,
wasChecked?: boolean,
checked?: boolean,
};
const ACTION_MENU_TOP_LEVEL_LIMIT: number;
function create(createProperties: {
type?: ItemType,
id?: string,
title?: string,
checked?: boolean,
command?: "_execute_crmbrowser_action" | "_execute_page_action" | "_execute_sidebar_action",
contexts?: ContextType[],
onclick?: (info: OnClickData, tab: crmbrowser.tabs.Tab) => void,
parentId?: number|string,
documentUrlPatterns?: string[],
targetUrlPatterns?: string[],
enabled?: boolean,
}, callback?: () => void): BrowserReturnValue<number|string>;
function update(id: number|string, updateProperties: {
type?: ItemType,
title?: string,
checked?: boolean,
contexts?: ContextType[],
onclick?: (info: OnClickData, tab: crmbrowser.tabs.Tab) => void,
parentId?: number|string,
documentUrlPatterns?: string[],
targetUrlPatterns?: string[],
enabled?: boolean,
}): BrowserReturnValue<void>;
function remove(menuItemId: number|string): BrowserReturnValue<void>;
function removeAll(): BrowserReturnValue<void>;
const onClicked: CRMBrowserEvListener<(info: OnClickData, tab: crmbrowser.tabs.Tab) => void>;
}
declare namespace crmbrowser.contextualIdentities {
type IdentityColor = "blue" | "turquoise" | "green" | "yellow" | "orange" | "red" | "pink" | "purple";
type IdentityIcon = "fingerprint" | "briefcase" | "dollar" | "cart" | "circle";
type ContextualIdentity = {
cookieStoreId: string,
color: IdentityColor,
icon: IdentityIcon,
name: string,
};
function create(details: {
name: string,
color: IdentityColor,
icon: IdentityIcon,
}): BrowserReturnValue<ContextualIdentity>;
function get(cookieStoreId: string): BrowserReturnValue<ContextualIdentity|null>;
function query(details: { name?: string }): BrowserReturnValue<ContextualIdentity[]>;
function update(cookieStoreId: string, details: {
name: string,
color: IdentityColor,
icon: IdentityIcon,
}): BrowserReturnValue<ContextualIdentity>;
function remove(cookieStoreId: string): BrowserReturnValue<ContextualIdentity|null>;
}
declare namespace crmbrowser.cookies {
type Cookie = {
name: string,
value: string,
domain: string,
hostOnly: boolean,
path: string,
secure: boolean,
httpOnly: boolean,
session: boolean,
expirationDate?: number,
storeId: string,
};
type CookieStore = {
id: string,
tabIds: number[],
};
type OnChangedCause = "evicted" | "expired" | "explicit" | "expired_overwrite"| "overwrite";
function get(details: { url: string, name: string, storeId?: string }): BrowserReturnValue<Cookie|null>;
function getAll(details: {
url?: string,
name?: string,
domain?: string,
path?: string,
secure?: boolean,
session?: boolean,
storeId?: string,
}): BrowserReturnValue<Cookie[]>;
function set(details: {
url: string,
name?: string,
domain?: string,
path?: string,
secure?: boolean,
httpOnly?: boolean,
expirationDate?: number,
storeId?: string,
}): BrowserReturnValue<Cookie>;
function remove(details: { url: string, name: string, storeId?: string }): BrowserReturnValue<Cookie|null>;
function getAllCookieStores(): BrowserReturnValue<CookieStore[]>;
const onChanged: CRMBrowserListener<{ removed: boolean, cookie: Cookie, cause: OnChangedCause }>;
}
declare namespace crmbrowser.devtools.inspectedWindow {
const tabId: number;
function eval(expression: string): BrowserReturnValue<[
any,
{ isException: boolean, value: string } | { isError: boolean, code: string }
]>;
function reload(reloadOptions?: {
ignoreCache?: boolean,
userAgent?: string,
injectedScript?: string,
}): BrowserReturnValue<void>;
}
declare namespace crmbrowser.devtools.network {
const onNavigated: CRMBrowserListener<string>;
}
declare namespace crmbrowser.devtools.panels {
type ExtensionPanel = {
onShown: CRMBrowserListener<Window>,
onHidden: CRMBrowserListener<void>,
};
function create(title: string, iconPath: string, pagePath: string): BrowserReturnValue<ExtensionPanel>;
}
declare namespace crmbrowser.downloads {
type FilenameConflictAction = "uniquify" | "overwrite" | "prompt";
type InterruptReason = "FILE_FAILED" | "FILE_ACCESS_DENIED" | "FILE_NO_SPACE"
| "FILE_NAME_TOO_LONG" | "FILE_TOO_LARGE" | "FILE_VIRUS_INFECTED"
| "FILE_TRANSIENT_ERROR" | "FILE_BLOCKED" | "FILE_SECURITY_CHECK_FAILED"
| "FILE_TOO_SHORT"
| "NETWORK_FAILED" | "NETWORK_TIMEOUT" | "NETWORK_DISCONNECTED"
| "NETWORK_SERVER_DOWN" | "NETWORK_INVALID_REQUEST"
| "SERVER_FAILED" | "SERVER_NO_RANGE" | "SERVER_BAD_CONTENT"
| "SERVER_UNAUTHORIZED" | "SERVER_CERT_PROBLEM" | "SERVER_FORBIDDEN"
| "USER_CANCELED" | "USER_SHUTDOWN" | "CRASH";
type DangerType = "file" | "url" | "content" | "uncommon" | "host" | "unwanted" | "safe"
| "accepted";
type State = "in_progress" | "interrupted" | "complete";
type DownloadItem = {
id: number,
url: string,
referrer: string,
filename: string,
incognito: boolean,
danger: string,
mime: string,
startTime: string,
endTime?: string,
estimatedEndTime?: string,
state: string,
paused: boolean,
canResume: boolean,
error?: string,
bytesReceived: number,
totalBytes: number,
fileSize: number,
exists: boolean,
byExtensionId?: string,
byExtensionName?: string,
};
type Delta<T> = {
current?: T,
previous?: T,
};
type StringDelta = Delta<string>;
type DoubleDelta = Delta<number>;
type BooleanDelta = Delta<boolean>;
type DownloadTime = Date|string|number;
type DownloadQuery = {
query?: string[],
startedBefore?: DownloadTime,
startedAfter?: DownloadTime,
endedBefore?: DownloadTime,
endedAfter?: DownloadTime,
totalBytesGreater?: number,
totalBytesLess?: number,
filenameRegex?: string,
urlRegex?: string,
limit?: number,
orderBy?: string,
id?: number,
url?: string,
filename?: string,
danger?: DangerType,
mime?: string,
startTime?: string,
endTime?: string,
state?: State,
paused?: boolean,
error?: InterruptReason,
bytesReceived?: number,
totalBytes?: number,
fileSize?: number,
exists?: boolean,
};
function download(options: {
url: string,
filename?: string,
conflictAction?: string,
saveAs?: boolean,
method?: string,
headers?: { [key: string]: string },
body?: string,
}): BrowserReturnValue<number>;
function search(query: DownloadQuery): BrowserReturnValue<DownloadItem[]>;
function pause(downloadId: number): BrowserReturnValue<void>;
function resume(downloadId: number): BrowserReturnValue<void>;
function cancel(downloadId: number): BrowserReturnValue<void>;
// unsupported: function getFileIcon(downloadId: number, options?: { size?: number }):
// BrowserReturnValue<string>;
function open(downloadId: number): BrowserReturnValue<void>;
function show(downloadId: number): BrowserReturnValue<void>;
function showDefaultFolder(): BrowserReturnValue<void>;
function erase(query: DownloadQuery): BrowserReturnValue<number[]>;
function removeFile(downloadId: number): BrowserReturnValue<void>;
// unsupported: function acceptDanger(downloadId: number): BrowserReturnValue<void>;
// unsupported: function drag(downloadId: number): BrowserReturnValue<void>;
// unsupported: function setShelfEnabled(enabled: boolean): BrowserReturnValue<void>;
const onCreated: CRMBrowserListener<DownloadItem>;
const onErased: CRMBrowserListener<number>;
const onChanged: CRMBrowserListener<{
id: number,
url?: StringDelta,
filename?: StringDelta,
danger?: StringDelta,
mime?: StringDelta,
startTime?: StringDelta,
endTime?: StringDelta,
state?: StringDelta,
canResume?: BooleanDelta,
paused?: BooleanDelta,
error?: StringDelta,
totalBytes?: DoubleDelta,
fileSize?: DoubleDelta,
exists?: BooleanDelta,
}>;
}
declare namespace crmbrowser.events {
type UrlFilter = {
hostContains?: string,
hostEquals?: string,
hostPrefix?: string,
hostSuffix?: string,
pathContains?: string,
pathEquals?: string,
pathPrefix?: string,
pathSuffix?: string,
queryContains?: string,
queryEquals?: string,
queryPrefix?: string,
querySuffix?: string,
urlContains?: string,
urlEquals?: string,
urlMatches?: string,
originAndPathMatches?: string,
urlPrefix?: string,
urlSuffix?: string,
schemes?: string[],
ports?: Array<number|number[]>,
};
}
declare namespace crmbrowser.extension {
type ViewType = "tab" | "notification" | "popup";
const lastError: string|null;
const inIncognitoContext: boolean;
function getURL(path: string): string;
function getViews(fetchProperties?: { type?: ViewType, windowId?: number }): Window[];
function getBackgroundPage(): Window;
function isAllowedIncognitoAccess(): BrowserReturnValue<boolean>;
function isAllowedFileSchemeAccess(): BrowserReturnValue<boolean>;
// unsupported: events as they are deprecated
}
declare namespace crmbrowser.extensionTypes {
type ImageFormat = "jpeg" | "png";
type ImageDetails = {
format: ImageFormat,
quality: number,
};
type RunAt = "document_start" | "document_end" | "document_idle";
type InjectDetails = {
allFrames?: boolean,
code?: string,
file?: string,
frameId?: number,
matchAboutBlank?: boolean,
runAt?: RunAt,
};
type InjectDetailsCSS = InjectDetails & { cssOrigin?: "user" | "author" };
}
declare namespace crmbrowser.history {
type TransitionType = "link" | "typed" | "auto_bookmark" | "auto_subframe" | "manual_subframe"
| "generated" | "auto_toplevel" | "form_submit" | "reload" | "keyword"
| "keyword_generated";
type HistoryItem = {
id: string,
url?: string,
title?: string,
lastVisitTime?: number,
visitCount?: number,
typedCount?: number,
};
type VisitItem = {
id: string,
visitId: string,
VisitTime?: number,
refferingVisitId: string,
transition: TransitionType,
};
function search(query: {
text: string,
startTime?: number|string|Date,
endTime?: number|string|Date,
maxResults?: number,
}): BrowserReturnValue<HistoryItem[]>;
function getVisits(details: { url: string }): BrowserReturnValue<VisitItem[]>;
function addUrl(details: {
url: string,
title?: string,
transition?: TransitionType,
visitTime?: number|string|Date,
}): BrowserReturnValue<void>;
function deleteUrl(details: { url: string }): BrowserReturnValue<void>;
function deleteRange(range: {
startTime: number|string|Date,
endTime: number|string|Date,
}): BrowserReturnValue<void>;
function deleteAll(): BrowserReturnValue<void>;
const onVisited: CRMBrowserListener<HistoryItem>;
// TODO: Ensure that urls is not `urls: [string]` instead
const onVisitRemoved: CRMBrowserListener<{ allHistory: boolean, urls: string[] }>;
}
declare namespace crmbrowser.i18n {
type LanguageCode = string;
function getAcceptLanguages(): BrowserReturnValue<LanguageCode[]>;
function getMessage(messageName: string, substitutions?: string|string[]): string;
function getUILanguage(): LanguageCode;
function detectLanguage(text: string): BrowserReturnValue<{
isReliable: boolean,
languages: { language: LanguageCode, percentage: number }[],
}>;
}
declare namespace crmbrowser.identity {
function getRedirectURL(): string;
function launchWebAuthFlow(details: { url: string, interactive: boolean }): BrowserReturnValue<string>;
}
declare namespace crmbrowser.idle {
type IdleState = "active" | "idle" /* unsupported: | "locked" */;
function queryState(detectionIntervalInSeconds: number): BrowserReturnValue<IdleState>;
function setDetectionInterval(intervalInSeconds: number): BrowserReturnValue<void>;
const onStateChanged: CRMBrowserListener<IdleState>;
}
declare namespace crmbrowser.management {
type ExtensionInfo = {
description: string,
// unsupported: disabledReason: string,
enabled: boolean,
homepageUrl: string,
hostPermissions: string[],
icons: { size: number, url: string }[],
id: string,
installType: "admin" | "development" | "normal" | "sideload" | "other";
mayDisable: boolean,
name: string,
// unsupported: offlineEnabled: boolean,
optionsUrl: string,
permissions: string[],
shortName: string,
// unsupported: type: string,
updateUrl: string,
version: string,
// unsupported: versionName: string,
};
function getSelf(): BrowserReturnValue<ExtensionInfo>;
function uninstallSelf(options: { showConfirmDialog: boolean, dialogMessage: string }): BrowserReturnValue<void>;
}
declare namespace crmbrowser.notifications {
type TemplateType = "basic" /* | "image" | "list" | "progress" */;
type NotificationOptions = {
type: TemplateType,
message: string,
title: string,
iconUrl?: string,
};
function create(id: string|null, options: NotificationOptions): BrowserReturnValue<string>;
function clear(id: string): BrowserReturnValue<boolean>;
function getAll(): BrowserReturnValue<{ [key: string]: NotificationOptions }>;
const onClosed: CRMBrowserListener<string>;
const onClicked: CRMBrowserListener<string>;
}
declare namespace crmbrowser.omnibox {
type OnInputEnteredDisposition = "currentTab" | "newForegroundTab" | "newBackgroundTab";
type SuggestResult = {
content: string,
description: string,
};
function setDefaultSuggestion(suggestion: { description: string }): BrowserReturnValue<void>;
const onInputStarted: CRMBrowserListener<void>;
const onInputChanged:
CRMBrowserEvListener<(text: string, suggest: (arg: SuggestResult[]) => void) => void>;
const onInputEntered:
CRMBrowserEvListener<(text: string, disposition: OnInputEnteredDisposition) => void>;
const onInputCancelled: CRMBrowserListener<void>;
}
declare namespace crmbrowser.pageAction {
type ImageDataType = ImageData;
function show(tabId: number): BrowserReturnValue<void>;
function hide(tabId: number): BrowserReturnValue<void>;
function setTitle(details: { tabId: number, title: string }): BrowserReturnValue<void>;
function getTitle(details: { tabId: number }): BrowserReturnValue<string>;
function setIcon(details: {
tabId: number,
path?: string|object,
imageData?: ImageDataType,
}): BrowserReturnValue<void>;
function setPopup(details: { tabId: number, popup: string }): BrowserReturnValue<void>;
function getPopup(details: { tabId: number }): BrowserReturnValue<string>;
const onClicked: CRMBrowserListener<crmbrowser.tabs.Tab>;
}
declare namespace crmbrowser.permissions {
type Permission = "activeTab" | "alarms" |
"bookmarks" | "browsingData" | "browserSettings" |
"contextMenus" | "contextualIdentities" | "cookies" |
"downloads" | "downloads.open" |
"find" | "geolocation" | "history" |
"identity" | "idle" |
"management" | "menus" |
"nativeMessaging" | "notifications" |
"pkcs11" | "privacy" | "proxy" |
"sessions" | "storage" |
"tabs" | "theme" | "topSites" |
"webNavigation" | "webRequest" | "webRequestBlocking";
type Permissions = {
origins?: string[],
permissions?: Permission[]
};
function contains(permissions: Permissions): BrowserReturnValue<boolean>;
function getAll(): BrowserReturnValue<Permissions>;
function remove(permissions: Permissions): BrowserReturnValue<boolean>;
function request(permissions: Permissions): BrowserReturnValue<boolean>;
// Not yet support in Edge and Firefox:
// const onAdded: CRMBrowserListener<Permissions>;
// const onRemoved: CRMBrowserListener<Permissions>;
}
declare namespace crmbrowser.runtime {
const lastError: string | null;
const id: string;
type Port = {
name: string,
disconnect(): BrowserReturnValue<void>,
error: object,
onDisconnect: {
addListener(cb: (port: Port) => void): BrowserReturnValue<void>,
removeListener(): BrowserReturnValue<void>,
},
onMessage: {
addListener(cb: (message: object) => void): BrowserReturnValue<void>,
removeListener(): BrowserReturnValue<void>,
},
postMessage(message: object): BrowserReturnValue<void>,
sender?: runtime.MessageSender,
};
type MessageSender = {
tab?: crmbrowser.tabs.Tab,
frameId?: number,
id?: string,
url?: string,
tlsChannelId?: string,
};
type PlatformOs = "mac" | "win" | "android" | "cros" | "linux" | "openbsd";
type PlatformArch = "arm" | "x86-32" | "x86-64";
type PlatformNaclArch = "arm" | "x86-32" | "x86-64";
type PlatformInfo = {
os: PlatformOs,
arch: PlatformArch,
};
// type RequestUpdateCheckStatus = "throttled" | "no_update" | "update_available";
type OnInstalledReason = "install" | "update" | "chrome_update" | "shared_module_update";
type OnRestartRequiredReason = "app_update" | "os_update" | "periodic";
function getBackgroundPage(): BrowserReturnValue<Window>;
function openOptionsPage(): BrowserReturnValue<void>;
// TODO: Explicitly expose every property of the manifest
function getManifest(): BrowserReturnValue<object>;
function getURL(path: string): BrowserReturnValue<string>;
function setUninstallURL(url: string): BrowserReturnValue<void>;
function reload(): BrowserReturnValue<void>;
// Will not exist: https://bugzilla.mozilla.org/show_bug.cgi?id=1314922
// function RequestUpdateCheck(): BrowserReturnValue<RequestUpdateCheckStatus>;
function connect(
extensionId?: string,
connectInfo?: { name?: string, includeTlsChannelId?: boolean }
): BrowserReturnValue<Port>;
function connectNative(application: string): Port;
function sendMessage<T = any, U = any>(
message: T
): BrowserReturnValue<U>;
function sendMessage<T = any, U = any>(
message: T,
options: { includeTlsChannelId?: boolean, toProxyScript?: boolean }
): BrowserReturnValue<U>;
function sendMessage<T = any, U = any>(
extensionId: string,
message: T,
): BrowserReturnValue<U>;
function sendMessage<T = any, U = any>(
extensionId: string,
message: T,
options?: { includeTlsChannelId?: boolean, toProxyScript?: boolean }
): BrowserReturnValue<U>;
function sendNativeMessage(
application: string,
message: object
): BrowserReturnValue<object|void>;
function getPlatformInfo(): BrowserReturnValue<PlatformInfo>;
function getBrowserInfo(): BrowserReturnValue<{
name: string,
vendor: string,
version: string,
buildID: string,
}>;
// Unsupported: https://bugzilla.mozilla.org/show_bug.cgi?id=1339407
// function getPackageDirectoryEntry(): BrowserReturnValue<any>;
const onStartup: CRMBrowserListener<void>;
const onInstalled: CRMBrowserListener<{
reason: OnInstalledReason,
previousVersion?: string,
id?: string,
}>;
// Unsupported
// const onSuspend: CRMBrowserListener<void>;
// const onSuspendCanceled: CRMBrowserListener<void>;
// const onBrowserUpdateAvailable: CRMBrowserListener<void>;
// const onRestartRequired: CRMBrowserListener<OnRestartRequiredReason>;
const onUpdateAvailable: CRMBrowserListener<{ version: string }>;
const onConnect: CRMBrowserListener<Port>;
const onConnectExternal: CRMBrowserListener<Port>;
type onMessagePromise = (
message: object,
sender: MessageSender,
sendResponse: (response: object) => boolean
) => BrowserReturnValue<void>;
type onMessageBool = (
message: object,
sender: MessageSender,
sendResponse: (response: object) => BrowserReturnValue<void>
) => boolean;
type onMessageVoid = (
message: object,
sender: MessageSender,
sendResponse: (response: object) => BrowserReturnValue<void>
) => void;
type onMessageEvent = onMessagePromise | onMessageBool | onMessageVoid;
const onMessage: CRMBrowserEvListener<onMessageEvent>;
const onMessageExternal: CRMBrowserEvListener<onMessageEvent>;
}
declare namespace crmbrowser.sessions{
type Filter = { maxResults?: number }
type Session = {
lastModified: number,
tab: crmbrowser.tabs.Tab,
window: crmbrowser.windows.Window
}
const MAX_SESSION_RESULTS: number
function getRecentlyClosed(filter?: Filter): BrowserReturnValue<Session[]>
function restore(sessionId: string): BrowserReturnValue<Session>
function setTabValue(tabId: number, key: string, value: string|object): BrowserReturnValue<void>
function getTabValue(tabId: number, key: string): BrowserReturnValue<void|string|object>
function removeTabValue(tabId: number, key: string): BrowserReturnValue<void>
function setWindowValue(windowId: number, key: string, value: string|object): BrowserReturnValue<void>
function getWindowValue(windowId: number, key: string): BrowserReturnValue<void|string|object>
function removeWindowValue(windowId: number, key: string): BrowserReturnValue<void>
const onChanged: CRMBrowserEvListener<()=>void>
}
declare namespace crmbrowser.sidebarAction {
type ImageDataType = ImageData;
function setPanel(details: { panel: string, tabId?: number }): BrowserReturnValue<void>;
function getPanel(details: { tabId?: number }): BrowserReturnValue<string>;
function setTitle(details: { title: string, tabId?: number }): BrowserReturnValue<void>;
function getTitle(details: { tabId?: number }): BrowserReturnValue<string>;
type IconViaPath = {
path: string | { [index: number]: string },
tabId?: number,
};
type IconViaImageData = {
imageData: ImageDataType | { [index: number]: ImageDataType },
tabId?: number,
};
function setIcon(details: IconViaPath | IconViaImageData): BrowserReturnValue<void>;
function open(): BrowserReturnValue<void>;
function close(): BrowserReturnValue<void>;
}
declare namespace crmbrowser.storage {
// Non-firefox implementations don't accept all these types
type StorageValue =
string |
number |
boolean |
null |
undefined |
RegExp |
ArrayBuffer |
Uint8ClampedArray |
Uint8Array |
Uint16Array |
Uint32Array |
Int8Array |
Int16Array |
Int32Array |
Float32Array |
Float64Array |
DataView |
StorageArray |
StorageMap |
StorageSet |
StorageObject;
// The Index signature makes casting to/from classes or interfaces a pain.
// Custom types are OK.
interface StorageObject {
[key: string]: StorageValue;
}
// These have to be interfaces rather than types to avoid a circular
// definition of StorageValue
interface StorageArray extends Array<StorageValue> {}
interface StorageMap extends Map<StorageValue,StorageValue> {}
interface StorageSet extends Set<StorageValue> {}
interface Get {
<T extends StorageObject>(keys?: string|string[]|null): Promise<T>;
/* <T extends StorageObject>(keys: T): BrowserReturnValue<{[K in keyof T]: T[K]}>; */
<T extends StorageObject>(keys: T): BrowserReturnValue<T>;
}
type StorageArea = {
get: Get,
// unsupported: getBytesInUse: (keys: string|string[]|null) => BrowserReturnValue<number>,
set: (keys: StorageObject) => BrowserReturnValue<void>,
remove: (keys: string|string[]) => BrowserReturnValue<void>,
clear: () => BrowserReturnValue<void>,
};
type StorageChange = {
oldValue?: any,
newValue?: any,
};
const sync: StorageArea;
const local: StorageArea;
// unsupported: const managed: StorageArea;
type ChangeDict = { [field: string]: StorageChange };
type StorageName = "sync"|"local" /* |"managed" */;
const onChanged: CRMBrowserEvListener<(changes: ChangeDict, areaName: StorageName) => void>;
}
declare namespace crmbrowser.tabs {
type MutedInfoReason = "capture" | "extension" | "user";
type MutedInfo = {
muted: boolean,
extensionId?: string,
reason: MutedInfoReason,
};
// TODO: Specify PageSettings properly.
type PageSettings = object;
type Tab = {
active: boolean,
audible?: boolean,
autoDiscardable?: boolean,
cookieStoreId?: string,
discarded?: boolean,
favIconUrl?: string,
height?: number,
highlighted: boolean,
id?: number,
incognito: boolean,
index: number,
isArticle: boolean,
isInReaderMode: boolean,
lastAccessed: number,
mutedInfo?: MutedInfo,
openerTabId?: number,
pinned: boolean,
selected: boolean,
sessionId?: string,
status?: string,
title?: string,
url?: string,
width?: number,
windowId: number,
};
type TabStatus = "loading" | "complete";
type WindowType = "normal" | "popup" | "panel" | "devtools";
type ZoomSettingsMode = "automatic" | "disabled" | "manual";
type ZoomSettingsScope = "per-origin" | "per-tab";
type ZoomSettings = {
defaultZoomFactor?: number,
mode?: ZoomSettingsMode,
scope?: ZoomSettingsScope,
};
const TAB_ID_NONE: number;
function connect(tabId: number, connectInfo?: { name?: string, frameId?: number }): crmbrowser.runtime.Port;
function create(createProperties: {
active?: boolean,
cookieStoreId?: string,
index?: number,
openerTabId?: number,
pinned?: boolean,
// deprecated: selected: boolean,
url?: string,
windowId?: number,
}): BrowserReturnValue<Tab>;
function captureVisibleTab(
windowId?: number,
options?: crmbrowser.extensionTypes.ImageDetails
): BrowserReturnValue<string>;
function captureVisibleTab(
options?: crmbrowser.extensionTypes.ImageDetails
): BrowserReturnValue<string>;
function detectLanguage(tabId?: number): BrowserReturnValue<string>;
function duplicate(tabId: number): BrowserReturnValue<Tab>;
function executeScript(
tabId: number|undefined,
details: crmbrowser.extensionTypes.InjectDetails
): BrowserReturnValue<object[]>;
function get(tabId: number): BrowserReturnValue<Tab>;
// deprecated: function getAllInWindow(): x;
function getCurrent(): BrowserReturnValue<Tab>;
// deprecated: function getSelected(windowId?: number): BrowserReturnValue<browser.tabs.Tab>;
function getZoom(tabId?: number): BrowserReturnValue<number>;
function getZoomSettings(tabId?: number): BrowserReturnValue<ZoomSettings>;
// unsupported: function highlight(highlightInfo: {
// windowId?: number,
// tabs: number[]|number,
// }): BrowserReturnValue<browser.windows.Window>;
function insertCSS(tabId: number|undefined, details: crmbrowser.extensionTypes.InjectDetailsCSS): BrowserReturnValue<void>;
function removeCSS(tabId: number|undefined, details: crmbrowser.extensionTypes.InjectDetails): BrowserReturnValue<void>;
function move(tabIds: number|number[], moveProperties: {
windowId?: number,
index: number,
}): BrowserReturnValue<Tab|Tab[]>;
function print(): BrowserReturnValue<void>;
function printPreview(): BrowserReturnValue<void>;
function query(queryInfo: {
active?: boolean,
audible?: boolean,
// unsupported: autoDiscardable?: boolean,
cookieStoreId?: string,
currentWindow?: boolean,
discarded?: boolean,
highlighted?: boolean,
index?: number,
muted?: boolean,
lastFocusedWindow?: boolean,
pinned?: boolean,
status?: TabStatus,
title?: string,
url?: string|string[],
windowId?: number,
windowType?: WindowType,
}): BrowserReturnValue<Tab[]>;
function reload(tabId?: number, reloadProperties?: { bypassCache?: boolean }): BrowserReturnValue<void>;
function remove(tabIds: number|number[]): BrowserReturnValue<void>;
function saveAsPDF(pageSettings: PageSettings): BrowserReturnValue<
'saved' |
'replaced' |
'canceled' |
'not_saved' |
'not_replaced'
>;
function sendMessage<T = any, U = object>(tabId: number, message: T, options?: { frameId?: number }): BrowserReturnValue<U|void>;
// deprecated: function sendRequest(): x;
function setZoom(tabId: number|undefined, zoomFactor: number): BrowserReturnValue<void>;
function setZoomSettings(tabId: number|undefined, zoomSettings: ZoomSettings): BrowserReturnValue<void>;
function update(tabId: number|undefined, updateProperties: {
active?: boolean,
// unsupported: autoDiscardable?: boolean,
// unsupported: highlighted?: boolean,
loadReplace?: boolean,
muted?: boolean,
openerTabId?: number,
pinned?: boolean,
// deprecated: selected?: boolean,
url?: string,
}): BrowserReturnValue<Tab>;
function update(updateProperties: {
active?: boolean,
// unsupported: autoDiscardable?: boolean,
// unsupported: highlighted?: boolean,
loadReplace?: boolean,
muted?: boolean,
openerTabId?: number,
pinned?: boolean,
// deprecated: selected?: boolean,
url?: string,
}): BrowserReturnValue<Tab>;
const onActivated: CRMBrowserListener<{ tabId: number, windowId: number }>;
const onAttached: CRMBrowserEvListener<(tabId: number, attachInfo: {
newWindowId: number,
newPosition: number,
}) => void>;
const onCreated: CRMBrowserListener<Tab>;
const onDetached: CRMBrowserEvListener<(tabId: number, detachInfo: {
oldWindowId: number,
oldPosition: number,
}) => void>;
const onHighlighted: CRMBrowserListener<{ windowId: number, tabIds: number[] }>;
const onMoved: CRMBrowserEvListener<(tabId: number, moveInfo: {
windowId: number,
fromIndex: number,
toIndex: number,
}) => void>;
const onRemoved: CRMBrowserEvListener<(tabId: number, removeInfo: {
windowId: number,
isWindowClosing: boolean,
}) => void>;
const onReplaced: CRMBrowserEvListener<(addedTabId: number, removedTabId: number) => void>;
const onUpdated: CRMBrowserEvListener<(tabId: number, changeInfo: {
audible?: boolean,
discarded?: boolean,
favIconUrl?: string,
mutedInfo?: MutedInfo,
pinned?: boolean,
status?: string,
title?: string,
url?: string,
}, tab: Tab) => void>;
const onZoomChanged: CRMBrowserListener<{
tabId: number,
oldZoomFactor: number,
newZoomFactor: number,
zoomSettings: ZoomSettings,
}>;
}
declare namespace crmbrowser.topSites {
type MostVisitedURL = {
title: string,
url: string,
};
function get(): BrowserReturnValue<MostVisitedURL[]>;
}
declare namespace crmbrowser.webNavigation {
type TransitionType = "link" | "auto_subframe" | "form_submit" | "reload";
// unsupported: | "typed" | "auto_bookmark" | "manual_subframe"
// | "generated" | "start_page" | "keyword"
// | "keyword_generated";
type TransitionQualifier = "client_redirect" | "server_redirect" | "forward_back";
// unsupported: "from_address_bar";
function getFrame(details: {
tabId: number,
processId: number,
frameId: number,
}): BrowserReturnValue<{ errorOccured: boolean, url: string, parentFrameId: number }>;
function getAllFrames(details: { tabId: number }): BrowserReturnValue<{
errorOccured: boolean,
processId: number,
frameId: number,
parentFrameId: number,
url: string,
}[]>;
interface NavListener<T> {
addListener: (callback: (arg: T) => void, filter?: {
url: crmbrowser.events.UrlFilter[],
}) => void;
removeListener: (callback: (arg: T) => void) => void;
hasListener: (callback: (arg: T) => void) => boolean;
}
type DefaultNavListener = NavListener<{
tabId: number,
url: string,
processId: number,
frameId: number,
timeStamp: number,
}>;
type TransitionNavListener = NavListener<{
tabId: number,
url: string,
processId: number,
frameId: number,
timeStamp: number,
transitionType: TransitionType,
transitionQualifiers: TransitionQualifier[],
}>;
const onBeforeNavigate: NavListener<{
tabId: number,
url: string,
processId: number,
frameId: number,
parentFrameId: number,
timeStamp: number,
}>;
const onCommitted: TransitionNavListener;
const onCreatedNavigationTarget: NavListener<{
sourceFrameId: number,
// Unsupported: sourceProcessId: number,
sourceTabId: number,
tabId: number,
timeStamp: number,
url: string,
windowId: number,
}>;
const onDOMContentLoaded: DefaultNavListener;
const onCompleted: DefaultNavListener;
const onErrorOccurred: DefaultNavListener; // error field unsupported
const onReferenceFragmentUpdated: TransitionNavListener;
const onHistoryStateUpdated: TransitionNavListener;
}
declare namespace crmbrowser.webRequest {
type ResourceType = "main_frame" | "sub_frame" | "stylesheet" | "script" | "image" | "object"
| "xmlhttprequest" | "xbl" | "xslt" | "ping" | "beacon" | "xml_dtd" | "font"
| "media" | "websocket" | "csp_report" | "imageset" | "web_manifest"
| "other";
type RequestFilter = {
urls: string[],
types?: ResourceType[],
tabId?: number,
windowId?: number,
};
type StreamFilter = {
onstart: (event: any) => void;
ondata: (event: { data: ArrayBuffer }) => void;
onstop: (event: any) => void;
onerror: (event: any) => void;
close(): BrowserReturnValue<void>;
disconnect(): BrowserReturnValue<void>;
resume(): BrowserReturnValue<void>;
suspend(): BrowserReturnValue<void>;
write(data: Uint8Array | ArrayBuffer): BrowserReturnValue<void>;
error: string;
status: "uninitialized" | "transferringdata" | "finishedtransferringdata" | "suspended" | "closed" | "disconnected" | "failed";
}
type HttpHeaders = ({ name: string, binaryValue: number[], value?: string }
| { name: string, value: string, binaryValue?: number[] })[];
type BlockingResponse = {
cancel?: boolean,
redirectUrl?: string,
requestHeaders?: HttpHeaders,
responseHeaders?: HttpHeaders,
// unsupported: authCredentials?: { username: string, password: string },
};
type UploadData = {
bytes?: ArrayBuffer,
file?: string,
};
const MAX_HANDLER_BEHAVIOR_CHANGED_CALLS_PER_10_MINUTES: number;
function handlerBehaviorChanged(): BrowserReturnValue<void>;
// TODO: Enforce the return result of the addListener call in the contract
// Use an intersection type for all the default properties
interface ReqListener<T, U> {
addListener: BrowserReturnValue<void>;
removeListener: BrowserReturnValue<void>
hasListener: BrowserReturnValue<void>;
}
const onBeforeRequest: ReqListener<{
requestId: string,
url: string,
method: string,
frameId: number,
parentFrameId: number,
requestBody?: {
error?: string,
formData?: { [key: string]: string[] },
raw?: UploadData[],
},
tabId: number,
type: ResourceType,
timeStamp: number,
originUrl: string,
}, "blocking"|"requestBody">;
const onBeforeSendHeaders: ReqListener<{
requestId: string,
url: string,
method: string,
frameId: number,
parentFrameId: number,
tabId: number,
type: ResourceType,
timeStamp: number,
originUrl: string,
requestHeaders?: HttpHeaders,
}, "blocking"|"requestHeaders">;
const onSendHeaders: ReqListener<{
requestId: string,
url: string,
method: string,
frameId: number,
parentFrameId: number,
tabId: number,
type: ResourceType,
timeStamp: number,
originUrl: string,
requestHeaders?: HttpHeaders,
}, "requestHeaders">;
const onHeadersReceived: ReqListener<{
requestId: string,
url: string,
method: string,
frameId: number,
parentFrameId: number,
tabId: number,
type: ResourceType,
timeStamp: number,
originUrl: string,
statusLine: string,
responseHeaders?: HttpHeaders,
statusCode: number,
}, "blocking"|"responseHeaders">;
const onAuthRequired: ReqListener<{
requestId: string,
url: string,
method: string,
frameId: number,
parentFrameId: number,
tabId: number,
type: ResourceType,
timeStamp: number,
scheme: string,
realm?: string,
challenger: { host: string, port: number },
isProxy: boolean,
responseHeaders?: HttpHeaders,
statusLine: string,
statusCode: number,
}, "blocking"|"responseHeaders">;
const onResponseStarted: ReqListener<{
requestId: string,
url: string,
method: string,
frameId: number,
parentFrameId: number,
tabId: number,
type: ResourceType,
timeStamp: number,
originUrl: string,
ip?: string,
fromCache: boolean,
statusLine: string,
responseHeaders?: HttpHeaders,
statusCode: number,
}, "responseHeaders">;
const onBeforeRedirect: ReqListener<{
requestId: string,
url: string,
method: string,
frameId: number,
parentFrameId: number,
tabId: number,
type: ResourceType,
timeStamp: number,
originUrl: string,
ip?: string,
fromCache: boolean,
statusCode: number,
redirectUrl: string,
statusLine: string,
responseHeaders?: HttpHeaders,
}, "responseHeaders">;
const onCompleted: ReqListener<{
requestId: string,
url: string,
method: string,
frameId: number,
parentFrameId: number,
tabId: number,
type: ResourceType,
timeStamp: number,
originUrl: string,
ip?: string,
fromCache: boolean,
statusCode: number,
statusLine: string,
responseHeaders?: HttpHeaders,
}, "responseHeaders">;
const onErrorOccurred: ReqListener<{
requestId: string,
url: string,
method: string,
frameId: number,
parentFrameId: number,
tabId: number,
type: ResourceType,
timeStamp: number,
originUrl: string,
ip?: string,
fromCache: boolean,
error: string,
}, void>;
function filterResponseData(requestId: string): StreamFilter;
}
declare namespace crmbrowser.windows {
type WindowType = "normal" | "popup" | "panel" | "devtools";
type WindowState = "normal" | "minimized" | "maximized" | "fullscreen" | "docked";
type Window = {
id?: number,
focused: boolean,
top?: number,
left?: number,
width?: number,
height?: number,
tabs?: crmbrowser.tabs.Tab[],
incognito: boolean,
type?: WindowType,
state?: WindowState,
alwaysOnTop: boolean,
sessionId?: string,
};
type CreateType = "normal" | "popup" | "panel" | "detached_panel";
const WINDOW_ID_NONE: number;
const WINDOW_ID_CURRENT: number;
function get(windowId: number, getInfo?: {
populate?: boolean,
windowTypes?: WindowType[],
}): BrowserReturnValue<crmbrowser.windows.Window>;
function getCurrent(getInfo?: {
populate?: boolean,
windowTypes?: WindowType[],
}): BrowserReturnValue<crmbrowser.windows.Window>;
function getLastFocused(getInfo?: {
populate?: boolean,
windowTypes?: WindowType[],
}): BrowserReturnValue<crmbrowser.windows.Window>;
function getAll(getInfo?: {
populate?: boolean,
windowTypes?: WindowType[],
}): BrowserReturnValue<crmbrowser.windows.Window[]>;
// TODO: url and tabId should be exclusive
function create(createData?: {
url?: string|string[],
tabId?: number,
left?: number,
top?: number,
width?: number,
height?: number,
// unsupported: focused?: boolean,
incognito?: boolean,
type?: CreateType,
state?: WindowState,
}): BrowserReturnValue<crmbrowser.windows.Window>;
function update(windowId: number, updateInfo: {
left?: number,
top?: number,
width?: number,
height?: number,
focused?: boolean,
drawAttention?: boolean,
state?: WindowState,
}): BrowserReturnValue<crmbrowser.windows.Window>;
function remove(windowId: number): BrowserReturnValue<void>;
const onCreated: CRMBrowserListener<crmbrowser.windows.Window>;
const onRemoved: CRMBrowserListener<number>;
const onFocusChanged: CRMBrowserListener<number>;
}
declare namespace crmbrowser.theme {
type Theme = {
images: ThemeImages,
colors: ThemeColors,
properties?: ThemeProperties,
};
type ThemeImages = {
headerURL: string,
theme_frame?: string,
additional_backgrounds?: string[],
};
type ThemeColors = {
accentcolor: string,
textcolor: string,
frame?: [number, number, number],
tab_text?: [number, number, number],
toolbar?: string,
toolbar_text?: string,
toolbar_field?: string,
toolbar_field_text?: string,
};
type ThemeProperties = {
additional_backgrounds_alignment: Alignment[],
additional_backgrounds_tiling: Tiling[],
}
type Alignment =
| 'bottom' | 'center' | 'left' | 'right' | 'top'
| 'center bottom' | 'center center' | 'center top'
| 'left bottom' | 'left center' | 'left top'
| 'right bottom' | 'right center' | 'right top';
type Tiling = 'no-repeat' | 'repeat' | 'repeat-x' | 'repeat-y';
function getCurrent(): BrowserReturnValue<Theme>;
function getCurrent(windowId: number): BrowserReturnValue<Theme>;
function update(theme: Theme): BrowserReturnValue<void>;
function update(windowId: number, theme: Theme): BrowserReturnValue<void>;
function reset(): BrowserReturnValue<void>;
function reset(windowId: number): BrowserReturnValue<void>;
} | the_stack |
import { BaseResource, CloudError } from "ms-rest-azure";
import * as moment from "moment";
export {
BaseResource,
CloudError
};
/**
* Properties of a weekly schedule.
*/
export interface WeekDetails {
/**
* The days of the week for which the schedule is set (e.g. Sunday, Monday, Tuesday, etc.).
*/
weekdays?: string[];
/**
* The time of the day the schedule will occur.
*/
time?: string;
}
/**
* Properties of a daily schedule.
*/
export interface DayDetails {
/**
* The time of day the schedule will occur.
*/
time?: string;
}
/**
* Properties of an hourly schedule.
*/
export interface HourDetails {
/**
* Minutes of the hour the schedule will run.
*/
minute?: number;
}
/**
* Notification settings for a schedule.
*/
export interface NotificationSettings {
/**
* If notifications are enabled for this schedule (i.e. Enabled, Disabled). Possible values
* include: 'Enabled', 'Disabled'
*/
status?: string;
/**
* Time in minutes before event at which notification will be sent.
*/
timeInMinutes?: number;
/**
* The webhook URL to which the notification will be sent.
*/
webhookUrl?: string;
/**
* The email recipient to send notifications to (can be a list of semi-colon separated email
* addresses).
*/
emailRecipient?: string;
/**
* The locale to use when sending a notification (fallback for unsupported languages is EN).
*/
notificationLocale?: string;
}
/**
* An Azure resource.
*/
export interface Resource extends BaseResource {
/**
* The identifier of the resource.
*/
readonly id?: string;
/**
* The name of the resource.
*/
readonly name?: string;
/**
* The type of the resource.
*/
readonly type?: string;
/**
* The location of the resource.
*/
location?: string;
/**
* The tags of the resource.
*/
tags?: { [propertyName: string]: string };
}
/**
* A schedule.
*/
export interface Schedule extends Resource {
/**
* The status of the schedule (i.e. Enabled, Disabled). Possible values include: 'Enabled',
* 'Disabled'
*/
status?: string;
/**
* The task type of the schedule (e.g. LabVmsShutdownTask, LabVmAutoStart).
*/
taskType?: string;
/**
* If the schedule will occur only some days of the week, specify the weekly recurrence.
*/
weeklyRecurrence?: WeekDetails;
/**
* If the schedule will occur once each day of the week, specify the daily recurrence.
*/
dailyRecurrence?: DayDetails;
/**
* If the schedule will occur multiple times a day, specify the hourly recurrence.
*/
hourlyRecurrence?: HourDetails;
/**
* The time zone ID (e.g. Pacific Standard time).
*/
timeZoneId?: string;
/**
* Notification settings.
*/
notificationSettings?: NotificationSettings;
/**
* The creation date of the schedule.
*/
readonly createdDate?: Date;
/**
* The resource ID to which the schedule belongs
*/
targetResourceId?: string;
/**
* The provisioning status of the resource.
*/
readonly provisioningState?: string;
/**
* The unique immutable identifier of a resource (Guid).
*/
readonly uniqueIdentifier?: string;
}
/**
* Schedules applicable to a virtual machine. The schedules may have been defined on a VM or on lab
* level.
*/
export interface ApplicableSchedule extends Resource {
/**
* The auto-shutdown schedule, if one has been set at the lab or lab resource level.
*/
labVmsShutdown?: Schedule;
/**
* The auto-startup schedule, if one has been set at the lab or lab resource level.
*/
labVmsStartup?: Schedule;
}
/**
* Properties of a weekly schedule.
*/
export interface WeekDetailsFragment {
/**
* The days of the week for which the schedule is set (e.g. Sunday, Monday, Tuesday, etc.).
*/
weekdays?: string[];
/**
* The time of the day the schedule will occur.
*/
time?: string;
}
/**
* Properties of a daily schedule.
*/
export interface DayDetailsFragment {
/**
* The time of day the schedule will occur.
*/
time?: string;
}
/**
* Properties of an hourly schedule.
*/
export interface HourDetailsFragment {
/**
* Minutes of the hour the schedule will run.
*/
minute?: number;
}
/**
* Notification settings for a schedule.
*/
export interface NotificationSettingsFragment {
/**
* If notifications are enabled for this schedule (i.e. Enabled, Disabled). Possible values
* include: 'Enabled', 'Disabled'
*/
status?: string;
/**
* Time in minutes before event at which notification will be sent.
*/
timeInMinutes?: number;
/**
* The webhook URL to which the notification will be sent.
*/
webhookUrl?: string;
/**
* The email recipient to send notifications to (can be a list of semi-colon separated email
* addresses).
*/
emailRecipient?: string;
/**
* The locale to use when sending a notification (fallback for unsupported languages is EN).
*/
notificationLocale?: string;
}
/**
* Represents an update resource
*/
export interface UpdateResource {
/**
* The tags of the resource.
*/
tags?: { [propertyName: string]: string };
}
/**
* A schedule.
*/
export interface ScheduleFragment extends UpdateResource {
/**
* The status of the schedule (i.e. Enabled, Disabled). Possible values include: 'Enabled',
* 'Disabled'
*/
status?: string;
/**
* The task type of the schedule (e.g. LabVmsShutdownTask, LabVmAutoStart).
*/
taskType?: string;
/**
* If the schedule will occur only some days of the week, specify the weekly recurrence.
*/
weeklyRecurrence?: WeekDetailsFragment;
/**
* If the schedule will occur once each day of the week, specify the daily recurrence.
*/
dailyRecurrence?: DayDetailsFragment;
/**
* If the schedule will occur multiple times a day, specify the hourly recurrence.
*/
hourlyRecurrence?: HourDetailsFragment;
/**
* The time zone ID (e.g. Pacific Standard time).
*/
timeZoneId?: string;
/**
* Notification settings.
*/
notificationSettings?: NotificationSettingsFragment;
/**
* The resource ID to which the schedule belongs
*/
targetResourceId?: string;
}
/**
* Schedules applicable to a virtual machine. The schedules may have been defined on a VM or on lab
* level.
*/
export interface ApplicableScheduleFragment extends UpdateResource {
/**
* The auto-shutdown schedule, if one has been set at the lab or lab resource level.
*/
labVmsShutdown?: ScheduleFragment;
/**
* The auto-startup schedule, if one has been set at the lab or lab resource level.
*/
labVmsStartup?: ScheduleFragment;
}
/**
* Properties of an artifact parameter.
*/
export interface ArtifactParameterProperties {
/**
* The name of the artifact parameter.
*/
name?: string;
/**
* The value of the artifact parameter.
*/
value?: string;
}
/**
* Properties of an artifact.
*/
export interface ArtifactInstallProperties {
/**
* The artifact's identifier.
*/
artifactId?: string;
/**
* The artifact's title.
*/
artifactTitle?: string;
/**
* The parameters of the artifact.
*/
parameters?: ArtifactParameterProperties[];
/**
* The status of the artifact.
*/
status?: string;
/**
* The status message from the deployment.
*/
deploymentStatusMessage?: string;
/**
* The status message from the virtual machine extension.
*/
vmExtensionStatusMessage?: string;
/**
* The time that the artifact starts to install on the virtual machine.
*/
installTime?: Date;
}
/**
* Request body for applying artifacts to a virtual machine.
*/
export interface ApplyArtifactsRequest {
/**
* The list of artifacts to apply.
*/
artifacts?: ArtifactInstallProperties[];
}
/**
* A file containing a set of parameter values for an ARM template.
*/
export interface ParametersValueFileInfo {
/**
* File name.
*/
fileName?: string;
/**
* Contents of the file.
*/
parametersValueInfo?: any;
}
/**
* An Azure Resource Manager template.
*/
export interface ArmTemplate extends Resource {
/**
* The display name of the ARM template.
*/
readonly displayName?: string;
/**
* The description of the ARM template.
*/
readonly description?: string;
/**
* The publisher of the ARM template.
*/
readonly publisher?: string;
/**
* The URI to the icon of the ARM template.
*/
readonly icon?: string;
/**
* The contents of the ARM template.
*/
readonly contents?: any;
/**
* The creation date of the armTemplate.
*/
readonly createdDate?: Date;
/**
* File name and parameter values information from all azuredeploy.*.parameters.json for the ARM
* template.
*/
readonly parametersValueFilesInfo?: ParametersValueFileInfo[];
/**
* Whether or not ARM template is enabled for use by lab user.
*/
readonly enabled?: boolean;
}
/**
* Information about a generated ARM template.
*/
export interface ArmTemplateInfo {
/**
* The template's contents.
*/
template?: any;
/**
* The parameters of the ARM template.
*/
parameters?: any;
}
/**
* Properties of an Azure Resource Manager template parameter.
*/
export interface ArmTemplateParameterProperties {
/**
* The name of the template parameter.
*/
name?: string;
/**
* The value of the template parameter.
*/
value?: string;
}
/**
* Properties of an Azure Resource Manager template parameter.
*/
export interface ArmTemplateParameterPropertiesFragment {
/**
* The name of the template parameter.
*/
name?: string;
/**
* The value of the template parameter.
*/
value?: string;
}
/**
* An artifact.
*/
export interface Artifact extends Resource {
/**
* The artifact's title.
*/
readonly title?: string;
/**
* The artifact's description.
*/
readonly description?: string;
/**
* The artifact's publisher.
*/
readonly publisher?: string;
/**
* The file path to the artifact.
*/
readonly filePath?: string;
/**
* The URI to the artifact icon.
*/
readonly icon?: string;
/**
* The artifact's target OS.
*/
readonly targetOsType?: string;
/**
* The artifact's parameters.
*/
readonly parameters?: any;
/**
* The artifact's creation date.
*/
readonly createdDate?: Date;
}
/**
* Properties of an artifact deployment.
*/
export interface ArtifactDeploymentStatusProperties {
/**
* The deployment status of the artifact.
*/
deploymentStatus?: string;
/**
* The total count of the artifacts that were successfully applied.
*/
artifactsApplied?: number;
/**
* The total count of the artifacts that were tentatively applied.
*/
totalArtifacts?: number;
}
/**
* Properties of an artifact deployment.
*/
export interface ArtifactDeploymentStatusPropertiesFragment {
/**
* The deployment status of the artifact.
*/
deploymentStatus?: string;
/**
* The total count of the artifacts that were successfully applied.
*/
artifactsApplied?: number;
/**
* The total count of the artifacts that were tentatively applied.
*/
totalArtifacts?: number;
}
/**
* Properties of an artifact parameter.
*/
export interface ArtifactParameterPropertiesFragment {
/**
* The name of the artifact parameter.
*/
name?: string;
/**
* The value of the artifact parameter.
*/
value?: string;
}
/**
* Properties of an artifact.
*/
export interface ArtifactInstallPropertiesFragment {
/**
* The artifact's identifier.
*/
artifactId?: string;
/**
* The artifact's title.
*/
artifactTitle?: string;
/**
* The parameters of the artifact.
*/
parameters?: ArtifactParameterPropertiesFragment[];
/**
* The status of the artifact.
*/
status?: string;
/**
* The status message from the deployment.
*/
deploymentStatusMessage?: string;
/**
* The status message from the virtual machine extension.
*/
vmExtensionStatusMessage?: string;
/**
* The time that the artifact starts to install on the virtual machine.
*/
installTime?: Date;
}
/**
* Properties of an artifact source.
*/
export interface ArtifactSource extends Resource {
/**
* The artifact source's display name.
*/
displayName?: string;
/**
* The artifact source's URI.
*/
uri?: string;
/**
* The artifact source's type. Possible values include: 'VsoGit', 'GitHub'
*/
sourceType?: string;
/**
* The folder containing artifacts.
*/
folderPath?: string;
/**
* The folder containing Azure Resource Manager templates.
*/
armTemplateFolderPath?: string;
/**
* The artifact source's branch reference.
*/
branchRef?: string;
/**
* The security token to authenticate to the artifact source.
*/
securityToken?: string;
/**
* Indicates if the artifact source is enabled (values: Enabled, Disabled). Possible values
* include: 'Enabled', 'Disabled'
*/
status?: string;
/**
* The artifact source's creation date.
*/
readonly createdDate?: Date;
/**
* The provisioning status of the resource.
*/
readonly provisioningState?: string;
/**
* The unique immutable identifier of a resource (Guid).
*/
readonly uniqueIdentifier?: string;
}
/**
* Properties of an artifact source.
*/
export interface ArtifactSourceFragment extends UpdateResource {
/**
* The artifact source's display name.
*/
displayName?: string;
/**
* The artifact source's URI.
*/
uri?: string;
/**
* The artifact source's type. Possible values include: 'VsoGit', 'GitHub'
*/
sourceType?: string;
/**
* The folder containing artifacts.
*/
folderPath?: string;
/**
* The folder containing Azure Resource Manager templates.
*/
armTemplateFolderPath?: string;
/**
* The artifact source's branch reference.
*/
branchRef?: string;
/**
* The security token to authenticate to the artifact source.
*/
securityToken?: string;
/**
* Indicates if the artifact source is enabled (values: Enabled, Disabled). Possible values
* include: 'Enabled', 'Disabled'
*/
status?: string;
}
/**
* Properties of the disk to attach.
*/
export interface AttachDiskProperties {
/**
* The resource ID of the Lab virtual machine to which the disk is attached.
*/
leasedByLabVmId?: string;
}
/**
* Properties to attach new disk to the Virtual Machine.
*/
export interface AttachNewDataDiskOptions {
/**
* Size of the disk to be attached in Gibibytes.
*/
diskSizeGiB?: number;
/**
* The name of the disk to be attached.
*/
diskName?: string;
/**
* The storage type for the disk (i.e. Standard, Premium). Possible values include: 'Standard',
* 'Premium'
*/
diskType?: string;
}
/**
* Properties to attach new disk to the Virtual Machine.
*/
export interface AttachNewDataDiskOptionsFragment {
/**
* Size of the disk to be attached in Gibibytes.
*/
diskSizeGiB?: number;
/**
* The name of the disk to be attached.
*/
diskName?: string;
/**
* The storage type for the disk (i.e. Standard, Premium). Possible values include: 'Standard',
* 'Premium'
*/
diskType?: string;
}
/**
* Parameters for creating multiple virtual machines as a single action.
*/
export interface BulkCreationParameters {
/**
* The number of virtual machine instances to create.
*/
instanceCount?: number;
}
/**
* Parameters for creating multiple virtual machines as a single action.
*/
export interface BulkCreationParametersFragment {
/**
* The number of virtual machine instances to create.
*/
instanceCount?: number;
}
/**
* A data disks attached to a virtual machine.
*/
export interface ComputeDataDisk {
/**
* Gets data disk name.
*/
name?: string;
/**
* When backed by a blob, the URI of underlying blob.
*/
diskUri?: string;
/**
* When backed by managed disk, this is the ID of the compute disk resource.
*/
managedDiskId?: string;
/**
* Gets data disk size in GiB.
*/
diskSizeGiB?: number;
}
/**
* A data disks attached to a virtual machine.
*/
export interface ComputeDataDiskFragment {
/**
* Gets data disk name.
*/
name?: string;
/**
* When backed by a blob, the URI of underlying blob.
*/
diskUri?: string;
/**
* When backed by managed disk, this is the ID of the compute disk resource.
*/
managedDiskId?: string;
/**
* Gets data disk size in GiB.
*/
diskSizeGiB?: number;
}
/**
* Status information about a virtual machine.
*/
export interface ComputeVmInstanceViewStatus {
/**
* Gets the status Code.
*/
code?: string;
/**
* Gets the short localizable label for the status.
*/
displayStatus?: string;
/**
* Gets the message associated with the status.
*/
message?: string;
}
/**
* Status information about a virtual machine.
*/
export interface ComputeVmInstanceViewStatusFragment {
/**
* Gets the status Code.
*/
code?: string;
/**
* Gets the short localizable label for the status.
*/
displayStatus?: string;
/**
* Gets the message associated with the status.
*/
message?: string;
}
/**
* Properties of a virtual machine returned by the Microsoft.Compute API.
*/
export interface ComputeVmProperties {
/**
* Gets the statuses of the virtual machine.
*/
statuses?: ComputeVmInstanceViewStatus[];
/**
* Gets the OS type of the virtual machine.
*/
osType?: string;
/**
* Gets the size of the virtual machine.
*/
vmSize?: string;
/**
* Gets the network interface ID of the virtual machine.
*/
networkInterfaceId?: string;
/**
* Gets OS disk blob uri for the virtual machine.
*/
osDiskId?: string;
/**
* Gets data disks blob uri for the virtual machine.
*/
dataDiskIds?: string[];
/**
* Gets all data disks attached to the virtual machine.
*/
dataDisks?: ComputeDataDisk[];
}
/**
* Properties of a virtual machine returned by the Microsoft.Compute API.
*/
export interface ComputeVmPropertiesFragment {
/**
* Gets the statuses of the virtual machine.
*/
statuses?: ComputeVmInstanceViewStatusFragment[];
/**
* Gets the OS type of the virtual machine.
*/
osType?: string;
/**
* Gets the size of the virtual machine.
*/
vmSize?: string;
/**
* Gets the network interface ID of the virtual machine.
*/
networkInterfaceId?: string;
/**
* Gets OS disk blob uri for the virtual machine.
*/
osDiskId?: string;
/**
* Gets data disks blob uri for the virtual machine.
*/
dataDiskIds?: string[];
/**
* Gets all data disks attached to the virtual machine.
*/
dataDisks?: ComputeDataDiskFragment[];
}
/**
* Properties of a percentage cost threshold.
*/
export interface PercentageCostThresholdProperties {
/**
* The cost threshold value.
*/
thresholdValue?: number;
}
/**
* Properties of a cost threshold item.
*/
export interface CostThresholdProperties {
/**
* The ID of the cost threshold item.
*/
thresholdId?: string;
/**
* The value of the percentage cost threshold.
*/
percentageThreshold?: PercentageCostThresholdProperties;
/**
* Indicates whether this threshold will be displayed on cost charts. Possible values include:
* 'Enabled', 'Disabled'
*/
displayOnChart?: string;
/**
* Indicates whether notifications will be sent when this threshold is exceeded. Possible values
* include: 'Enabled', 'Disabled'
*/
sendNotificationWhenExceeded?: string;
/**
* Indicates the datetime when notifications were last sent for this threshold.
*/
notificationSent?: string;
}
/**
* Information about a Windows OS.
*/
export interface WindowsOsInfo {
/**
* The state of the Windows OS (i.e. NonSysprepped, SysprepRequested, SysprepApplied). Possible
* values include: 'NonSysprepped', 'SysprepRequested', 'SysprepApplied'
*/
windowsOsState?: string;
}
/**
* Information about a Linux OS.
*/
export interface LinuxOsInfo {
/**
* The state of the Linux OS (i.e. NonDeprovisioned, DeprovisionRequested, DeprovisionApplied).
* Possible values include: 'NonDeprovisioned', 'DeprovisionRequested', 'DeprovisionApplied'
*/
linuxOsState?: string;
}
/**
* Properties for creating a custom image from a virtual machine.
*/
export interface CustomImagePropertiesFromVm {
/**
* The source vm identifier.
*/
sourceVmId?: string;
/**
* The Windows OS information of the VM.
*/
windowsOsInfo?: WindowsOsInfo;
/**
* The Linux OS information of the VM.
*/
linuxOsInfo?: LinuxOsInfo;
}
/**
* Properties for creating a custom image from a VHD.
*/
export interface CustomImagePropertiesCustom {
/**
* The image name.
*/
imageName?: string;
/**
* Indicates whether sysprep has been run on the VHD.
*/
sysPrep?: boolean;
/**
* The OS type of the custom image (i.e. Windows, Linux). Possible values include: 'Windows',
* 'Linux', 'None'
*/
osType: string;
}
/**
* Storage information about the data disks present in the custom image
*/
export interface DataDiskStorageTypeInfo {
/**
* Disk Lun
*/
lun?: string;
/**
* Disk Storage Type. Possible values include: 'Standard', 'Premium'
*/
storageType?: string;
}
/**
* Properties for plan on a custom image.
*/
export interface CustomImagePropertiesFromPlan {
/**
* The id of the plan, equivalent to name of the plan
*/
id?: string;
/**
* The publisher for the plan from the marketplace image the custom image is derived from
*/
publisher?: string;
/**
* The offer for the plan from the marketplace image the custom image is derived from
*/
offer?: string;
}
/**
* A custom image.
*/
export interface CustomImage extends Resource {
/**
* The virtual machine from which the image is to be created.
*/
vm?: CustomImagePropertiesFromVm;
/**
* The VHD from which the image is to be created.
*/
vhd?: CustomImagePropertiesCustom;
/**
* The description of the custom image.
*/
description?: string;
/**
* The author of the custom image.
*/
author?: string;
/**
* The creation date of the custom image.
*/
readonly creationDate?: Date;
/**
* The Managed Image Id backing the custom image.
*/
managedImageId?: string;
/**
* The Managed Snapshot Id backing the custom image.
*/
managedSnapshotId?: string;
/**
* Storage information about the data disks present in the custom image
*/
dataDiskStorageInfo?: DataDiskStorageTypeInfo[];
/**
* Storage information about the plan related to this custom image
*/
customImagePlan?: CustomImagePropertiesFromPlan;
/**
* Whether or not the custom images underlying offer/plan has been enabled for programmatic
* deployment
*/
isPlanAuthorized?: boolean;
/**
* The provisioning status of the resource.
*/
readonly provisioningState?: string;
/**
* The unique immutable identifier of a resource (Guid).
*/
readonly uniqueIdentifier?: string;
}
/**
* Information about a Windows OS.
*/
export interface WindowsOsInfoFragment {
/**
* The state of the Windows OS (i.e. NonSysprepped, SysprepRequested, SysprepApplied). Possible
* values include: 'NonSysprepped', 'SysprepRequested', 'SysprepApplied'
*/
windowsOsState?: string;
}
/**
* Information about a Linux OS.
*/
export interface LinuxOsInfoFragment {
/**
* The state of the Linux OS (i.e. NonDeprovisioned, DeprovisionRequested, DeprovisionApplied).
* Possible values include: 'NonDeprovisioned', 'DeprovisionRequested', 'DeprovisionApplied'
*/
linuxOsState?: string;
}
/**
* Properties for creating a custom image from a virtual machine.
*/
export interface CustomImagePropertiesFromVmFragment {
/**
* The source vm identifier.
*/
sourceVmId?: string;
/**
* The Windows OS information of the VM.
*/
windowsOsInfo?: WindowsOsInfoFragment;
/**
* The Linux OS information of the VM.
*/
linuxOsInfo?: LinuxOsInfoFragment;
}
/**
* Properties for creating a custom image from a VHD.
*/
export interface CustomImagePropertiesCustomFragment {
/**
* The image name.
*/
imageName?: string;
/**
* Indicates whether sysprep has been run on the VHD.
*/
sysPrep?: boolean;
/**
* The OS type of the custom image (i.e. Windows, Linux). Possible values include: 'Windows',
* 'Linux', 'None'
*/
osType?: string;
}
/**
* Storage information about the data disks present in the custom image
*/
export interface DataDiskStorageTypeInfoFragment {
/**
* Disk Lun
*/
lun?: string;
/**
* Disk Storage Type. Possible values include: 'Standard', 'Premium'
*/
storageType?: string;
}
/**
* Properties for plan on a custom image.
*/
export interface CustomImagePropertiesFromPlanFragment {
/**
* The id of the plan, equivalent to name of the plan
*/
id?: string;
/**
* The publisher for the plan from the marketplace image the custom image is derived from
*/
publisher?: string;
/**
* The offer for the plan from the marketplace image the custom image is derived from
*/
offer?: string;
}
/**
* A custom image.
*/
export interface CustomImageFragment extends UpdateResource {
/**
* The virtual machine from which the image is to be created.
*/
vm?: CustomImagePropertiesFromVmFragment;
/**
* The VHD from which the image is to be created.
*/
vhd?: CustomImagePropertiesCustomFragment;
/**
* The description of the custom image.
*/
description?: string;
/**
* The author of the custom image.
*/
author?: string;
/**
* The Managed Image Id backing the custom image.
*/
managedImageId?: string;
/**
* The Managed Snapshot Id backing the custom image.
*/
managedSnapshotId?: string;
/**
* Storage information about the data disks present in the custom image
*/
dataDiskStorageInfo?: DataDiskStorageTypeInfoFragment[];
/**
* Storage information about the plan related to this custom image
*/
customImagePlan?: CustomImagePropertiesFromPlanFragment;
/**
* Whether or not the custom images underlying offer/plan has been enabled for programmatic
* deployment
*/
isPlanAuthorized?: boolean;
}
/**
* Request body for adding a new or existing data disk to a virtual machine.
*/
export interface DataDiskProperties {
/**
* Specifies options to attach a new disk to the virtual machine.
*/
attachNewDataDiskOptions?: AttachNewDataDiskOptions;
/**
* Specifies the existing lab disk id to attach to virtual machine.
*/
existingLabDiskId?: string;
/**
* Caching option for a data disk (i.e. None, ReadOnly, ReadWrite). Possible values include:
* 'None', 'ReadOnly', 'ReadWrite'
*/
hostCaching?: string;
}
/**
* Request body for adding a new or existing data disk to a virtual machine.
*/
export interface DataDiskPropertiesFragment {
/**
* Specifies options to attach a new disk to the virtual machine.
*/
attachNewDataDiskOptions?: AttachNewDataDiskOptionsFragment;
/**
* Specifies the existing lab disk id to attach to virtual machine.
*/
existingLabDiskId?: string;
/**
* Caching option for a data disk (i.e. None, ReadOnly, ReadWrite). Possible values include:
* 'None', 'ReadOnly', 'ReadWrite'
*/
hostCaching?: string;
}
/**
* Request body for detaching data disk from a virtual machine.
*/
export interface DetachDataDiskProperties {
/**
* Specifies the disk resource ID to detach from virtual machine.
*/
existingLabDiskId?: string;
}
/**
* Properties of the disk to detach.
*/
export interface DetachDiskProperties {
/**
* The resource ID of the Lab VM to which the disk is attached.
*/
leasedByLabVmId?: string;
}
/**
* A Disk.
*/
export interface Disk extends Resource {
/**
* The storage type for the disk (i.e. Standard, Premium). Possible values include: 'Standard',
* 'Premium'
*/
diskType?: string;
/**
* The size of the disk in Gibibytes.
*/
diskSizeGiB?: number;
/**
* The resource ID of the VM to which this disk is leased.
*/
leasedByLabVmId?: string;
/**
* When backed by a blob, the name of the VHD blob without extension.
*/
diskBlobName?: string;
/**
* When backed by a blob, the URI of underlying blob.
*/
diskUri?: string;
/**
* The creation date of the disk.
*/
readonly createdDate?: Date;
/**
* The host caching policy of the disk (i.e. None, ReadOnly, ReadWrite).
*/
hostCaching?: string;
/**
* When backed by managed disk, this is the ID of the compute disk resource.
*/
managedDiskId?: string;
/**
* The provisioning status of the resource.
*/
readonly provisioningState?: string;
/**
* The unique immutable identifier of a resource (Guid).
*/
readonly uniqueIdentifier?: string;
}
/**
* A Disk.
*/
export interface DiskFragment extends UpdateResource {
/**
* The storage type for the disk (i.e. Standard, Premium). Possible values include: 'Standard',
* 'Premium'
*/
diskType?: string;
/**
* The size of the disk in Gibibytes.
*/
diskSizeGiB?: number;
/**
* The resource ID of the VM to which this disk is leased.
*/
leasedByLabVmId?: string;
/**
* When backed by a blob, the name of the VHD blob without extension.
*/
diskBlobName?: string;
/**
* When backed by a blob, the URI of underlying blob.
*/
diskUri?: string;
/**
* The host caching policy of the disk (i.e. None, ReadOnly, ReadWrite).
*/
hostCaching?: string;
/**
* When backed by managed disk, this is the ID of the compute disk resource.
*/
managedDiskId?: string;
}
/**
* Properties of an environment deployment.
*/
export interface EnvironmentDeploymentProperties {
/**
* The Azure Resource Manager template's identifier.
*/
armTemplateId?: string;
/**
* The parameters of the Azure Resource Manager template.
*/
parameters?: ArmTemplateParameterProperties[];
}
/**
* An environment, which is essentially an ARM template deployment.
*/
export interface DtlEnvironment extends Resource {
/**
* The deployment properties of the environment.
*/
deploymentProperties?: EnvironmentDeploymentProperties;
/**
* The display name of the Azure Resource Manager template that produced the environment.
*/
armTemplateDisplayName?: string;
/**
* The identifier of the resource group containing the environment's resources.
*/
readonly resourceGroupId?: string;
/**
* The creator of the environment.
*/
readonly createdByUser?: string;
/**
* The provisioning status of the resource.
*/
readonly provisioningState?: string;
/**
* The unique immutable identifier of a resource (Guid).
*/
readonly uniqueIdentifier?: string;
}
/**
* Properties of an environment deployment.
*/
export interface EnvironmentDeploymentPropertiesFragment {
/**
* The Azure Resource Manager template's identifier.
*/
armTemplateId?: string;
/**
* The parameters of the Azure Resource Manager template.
*/
parameters?: ArmTemplateParameterPropertiesFragment[];
}
/**
* An environment, which is essentially an ARM template deployment.
*/
export interface DtlEnvironmentFragment extends UpdateResource {
/**
* The deployment properties of the environment.
*/
deploymentProperties?: EnvironmentDeploymentPropertiesFragment;
/**
* The display name of the Azure Resource Manager template that produced the environment.
*/
armTemplateDisplayName?: string;
}
/**
* Properties for evaluating a policy set.
*/
export interface EvaluatePoliciesProperties {
/**
* The fact name.
*/
factName?: string;
/**
* The fact data.
*/
factData?: string;
/**
* The value offset.
*/
valueOffset?: string;
/**
* The user for which policies will be evaluated
*/
userObjectId?: string;
}
/**
* Request body for evaluating a policy set.
*/
export interface EvaluatePoliciesRequest {
/**
* Policies to evaluate.
*/
policies?: EvaluatePoliciesProperties[];
}
/**
* Policy violation.
*/
export interface PolicyViolation {
/**
* The code of the policy violation.
*/
code?: string;
/**
* The message of the policy violation.
*/
message?: string;
}
/**
* Result of a policy set evaluation.
*/
export interface PolicySetResult {
/**
* A value indicating whether this policy set evaluation has discovered violations.
*/
hasError?: boolean;
/**
* The list of policy violations.
*/
policyViolations?: PolicyViolation[];
}
/**
* Response body for evaluating a policy set.
*/
export interface EvaluatePoliciesResponse {
/**
* Results of evaluating a policy set.
*/
results?: PolicySetResult[];
}
/**
* An event to be notified for.
*/
export interface Event {
/**
* The event type for which this notification is enabled (i.e. AutoShutdown, Cost). Possible
* values include: 'AutoShutdown', 'Cost'
*/
eventName?: string;
}
/**
* An event to be notified for.
*/
export interface EventFragment {
/**
* The event type for which this notification is enabled (i.e. AutoShutdown, Cost). Possible
* values include: 'AutoShutdown', 'Cost'
*/
eventName?: string;
}
/**
* The parameters of the export operation.
*/
export interface ExportResourceUsageParameters {
/**
* The blob storage absolute sas uri with write permission to the container which the usage data
* needs to be uploaded to.
*/
blobStorageAbsoluteSasUri?: string;
/**
* The start time of the usage. If not provided, usage will be reported since the beginning of
* data collection.
*/
usageStartDate?: Date;
}
/**
* Subnet information as returned by the Microsoft.Network API.
*/
export interface ExternalSubnet {
/**
* Gets or sets the identifier.
*/
id?: string;
/**
* Gets or sets the name.
*/
name?: string;
}
/**
* Subnet information as returned by the Microsoft.Network API.
*/
export interface ExternalSubnetFragment {
/**
* Gets or sets the identifier.
*/
id?: string;
/**
* Gets or sets the name.
*/
name?: string;
}
/**
* The reference information for an Azure Marketplace image.
*/
export interface GalleryImageReference {
/**
* The offer of the gallery image.
*/
offer?: string;
/**
* The publisher of the gallery image.
*/
publisher?: string;
/**
* The SKU of the gallery image.
*/
sku?: string;
/**
* The OS type of the gallery image.
*/
osType?: string;
/**
* The version of the gallery image.
*/
version?: string;
}
/**
* A rule for NAT - exposing a VM's port (backendPort) on the public IP address using a load
* balancer.
*/
export interface InboundNatRule {
/**
* The transport protocol for the endpoint. Possible values include: 'Tcp', 'Udp'
*/
transportProtocol?: string;
/**
* The external endpoint port of the inbound connection. Possible values range between 1 and
* 65535, inclusive. If unspecified, a value will be allocated automatically.
*/
frontendPort?: number;
/**
* The port to which the external traffic will be redirected.
*/
backendPort?: number;
}
/**
* Properties of a virtual machine that determine how it is connected to a load balancer.
*/
export interface SharedPublicIpAddressConfiguration {
/**
* The incoming NAT rules
*/
inboundNatRules?: InboundNatRule[];
}
/**
* Properties of a network interface.
*/
export interface NetworkInterfaceProperties {
/**
* The resource ID of the virtual network.
*/
virtualNetworkId?: string;
/**
* The resource ID of the sub net.
*/
subnetId?: string;
/**
* The resource ID of the public IP address.
*/
publicIpAddressId?: string;
/**
* The public IP address.
*/
publicIpAddress?: string;
/**
* The private IP address.
*/
privateIpAddress?: string;
/**
* The DNS name.
*/
dnsName?: string;
/**
* The RdpAuthority property is a server DNS host name or IP address followed by the service port
* number for RDP (Remote Desktop Protocol).
*/
rdpAuthority?: string;
/**
* The SshAuthority property is a server DNS host name or IP address followed by the service port
* number for SSH.
*/
sshAuthority?: string;
/**
* The configuration for sharing a public IP address across multiple virtual machines.
*/
sharedPublicIpAddressConfiguration?: SharedPublicIpAddressConfiguration;
}
/**
* Properties for creating a schedule.
*/
export interface ScheduleCreationParameter {
/**
* The status of the schedule (i.e. Enabled, Disabled). Possible values include: 'Enabled',
* 'Disabled'
*/
status?: string;
/**
* The task type of the schedule (e.g. LabVmsShutdownTask, LabVmAutoStart).
*/
taskType?: string;
/**
* If the schedule will occur only some days of the week, specify the weekly recurrence.
*/
weeklyRecurrence?: WeekDetails;
/**
* If the schedule will occur once each day of the week, specify the daily recurrence.
*/
dailyRecurrence?: DayDetails;
/**
* If the schedule will occur multiple times a day, specify the hourly recurrence.
*/
hourlyRecurrence?: HourDetails;
/**
* The time zone ID (e.g. Pacific Standard time).
*/
timeZoneId?: string;
/**
* Notification settings.
*/
notificationSettings?: NotificationSettings;
/**
* The resource ID to which the schedule belongs
*/
targetResourceId?: string;
/**
* The name of the virtual machine or environment
*/
name?: string;
/**
* The location of the new virtual machine or environment
*/
location?: string;
/**
* The tags of the resource.
*/
tags?: { [propertyName: string]: string };
}
/**
* Properties for creating a virtual machine.
*/
export interface LabVirtualMachineCreationParameter {
/**
* The number of virtual machine instances to create.
*/
bulkCreationParameters?: BulkCreationParameters;
/**
* The notes of the virtual machine.
*/
notes?: string;
/**
* The object identifier of the owner of the virtual machine.
*/
ownerObjectId?: string;
/**
* The user principal name of the virtual machine owner.
*/
ownerUserPrincipalName?: string;
/**
* The object identifier of the creator of the virtual machine.
*/
createdByUserId?: string;
/**
* The email address of creator of the virtual machine.
*/
createdByUser?: string;
/**
* The creation date of the virtual machine.
*/
createdDate?: Date;
/**
* The resource identifier (Microsoft.Compute) of the virtual machine.
*/
computeId?: string;
/**
* The custom image identifier of the virtual machine.
*/
customImageId?: string;
/**
* The OS type of the virtual machine.
*/
osType?: string;
/**
* The size of the virtual machine.
*/
size?: string;
/**
* The user name of the virtual machine.
*/
userName?: string;
/**
* The password of the virtual machine administrator.
*/
password?: string;
/**
* The SSH key of the virtual machine administrator.
*/
sshKey?: string;
/**
* Indicates whether this virtual machine uses an SSH key for authentication.
*/
isAuthenticationWithSshKey?: boolean;
/**
* The fully-qualified domain name of the virtual machine.
*/
fqdn?: string;
/**
* The lab subnet name of the virtual machine.
*/
labSubnetName?: string;
/**
* The lab virtual network identifier of the virtual machine.
*/
labVirtualNetworkId?: string;
/**
* Indicates whether the virtual machine is to be created without a public IP address.
*/
disallowPublicIpAddress?: boolean;
/**
* The artifacts to be installed on the virtual machine.
*/
artifacts?: ArtifactInstallProperties[];
/**
* The artifact deployment status for the virtual machine.
*/
artifactDeploymentStatus?: ArtifactDeploymentStatusProperties;
/**
* The Microsoft Azure Marketplace image reference of the virtual machine.
*/
galleryImageReference?: GalleryImageReference;
/**
* The id of the plan associated with the virtual machine image
*/
planId?: string;
/**
* The network interface properties.
*/
networkInterface?: NetworkInterfaceProperties;
/**
* The expiration date for VM.
*/
expirationDate?: Date;
/**
* Indicates whether another user can take ownership of the virtual machine
*/
allowClaim?: boolean;
/**
* Storage type to use for virtual machine (i.e. Standard, Premium).
*/
storageType?: string;
/**
* Tells source of creation of lab virtual machine. Output property only. Possible values
* include: 'FromCustomImage', 'FromGalleryImage'
*/
virtualMachineCreationSource?: string;
/**
* The resource ID of the environment that contains this virtual machine, if any.
*/
environmentId?: string;
/**
* New or existing data disks to attach to the virtual machine after creation
*/
dataDiskParameters?: DataDiskProperties[];
/**
* Virtual Machine schedules to be created
*/
scheduleParameters?: ScheduleCreationParameter[];
/**
* Last known compute power state captured in DTL
*/
lastKnownPowerState?: string;
/**
* The name of the virtual machine or environment
*/
name?: string;
/**
* The location of the new virtual machine or environment
*/
location?: string;
/**
* The tags of the resource.
*/
tags?: { [propertyName: string]: string };
}
/**
* Information about a VM from which a formula is to be created.
*/
export interface FormulaPropertiesFromVm {
/**
* The identifier of the VM from which a formula is to be created.
*/
labVmId?: string;
}
/**
* A formula for creating a VM, specifying an image base and other parameters
*/
export interface Formula extends Resource {
/**
* The description of the formula.
*/
description?: string;
/**
* The author of the formula.
*/
author?: string;
/**
* The OS type of the formula.
*/
osType?: string;
/**
* The creation date of the formula.
*/
readonly creationDate?: Date;
/**
* The content of the formula.
*/
formulaContent?: LabVirtualMachineCreationParameter;
/**
* Information about a VM from which a formula is to be created.
*/
vm?: FormulaPropertiesFromVm;
/**
* The provisioning status of the resource.
*/
readonly provisioningState?: string;
/**
* The unique immutable identifier of a resource (Guid).
*/
readonly uniqueIdentifier?: string;
}
/**
* The reference information for an Azure Marketplace image.
*/
export interface GalleryImageReferenceFragment {
/**
* The offer of the gallery image.
*/
offer?: string;
/**
* The publisher of the gallery image.
*/
publisher?: string;
/**
* The SKU of the gallery image.
*/
sku?: string;
/**
* The OS type of the gallery image.
*/
osType?: string;
/**
* The version of the gallery image.
*/
version?: string;
}
/**
* A rule for NAT - exposing a VM's port (backendPort) on the public IP address using a load
* balancer.
*/
export interface InboundNatRuleFragment {
/**
* The transport protocol for the endpoint. Possible values include: 'Tcp', 'Udp'
*/
transportProtocol?: string;
/**
* The external endpoint port of the inbound connection. Possible values range between 1 and
* 65535, inclusive. If unspecified, a value will be allocated automatically.
*/
frontendPort?: number;
/**
* The port to which the external traffic will be redirected.
*/
backendPort?: number;
}
/**
* Properties of a virtual machine that determine how it is connected to a load balancer.
*/
export interface SharedPublicIpAddressConfigurationFragment {
/**
* The incoming NAT rules
*/
inboundNatRules?: InboundNatRuleFragment[];
}
/**
* Properties of a network interface.
*/
export interface NetworkInterfacePropertiesFragment {
/**
* The resource ID of the virtual network.
*/
virtualNetworkId?: string;
/**
* The resource ID of the sub net.
*/
subnetId?: string;
/**
* The resource ID of the public IP address.
*/
publicIpAddressId?: string;
/**
* The public IP address.
*/
publicIpAddress?: string;
/**
* The private IP address.
*/
privateIpAddress?: string;
/**
* The DNS name.
*/
dnsName?: string;
/**
* The RdpAuthority property is a server DNS host name or IP address followed by the service port
* number for RDP (Remote Desktop Protocol).
*/
rdpAuthority?: string;
/**
* The SshAuthority property is a server DNS host name or IP address followed by the service port
* number for SSH.
*/
sshAuthority?: string;
/**
* The configuration for sharing a public IP address across multiple virtual machines.
*/
sharedPublicIpAddressConfiguration?: SharedPublicIpAddressConfigurationFragment;
}
/**
* Properties for creating a schedule.
*/
export interface ScheduleCreationParameterFragment {
/**
* The status of the schedule (i.e. Enabled, Disabled). Possible values include: 'Enabled',
* 'Disabled'
*/
status?: string;
/**
* The task type of the schedule (e.g. LabVmsShutdownTask, LabVmAutoStart).
*/
taskType?: string;
/**
* If the schedule will occur only some days of the week, specify the weekly recurrence.
*/
weeklyRecurrence?: WeekDetailsFragment;
/**
* If the schedule will occur once each day of the week, specify the daily recurrence.
*/
dailyRecurrence?: DayDetailsFragment;
/**
* If the schedule will occur multiple times a day, specify the hourly recurrence.
*/
hourlyRecurrence?: HourDetailsFragment;
/**
* The time zone ID (e.g. Pacific Standard time).
*/
timeZoneId?: string;
/**
* Notification settings.
*/
notificationSettings?: NotificationSettingsFragment;
/**
* The resource ID to which the schedule belongs
*/
targetResourceId?: string;
/**
* The name of the virtual machine or environment
*/
name?: string;
/**
* The location of the new virtual machine or environment
*/
location?: string;
/**
* The tags of the resource.
*/
tags?: { [propertyName: string]: string };
}
/**
* Properties for creating a virtual machine.
*/
export interface LabVirtualMachineCreationParameterFragment {
/**
* The number of virtual machine instances to create.
*/
bulkCreationParameters?: BulkCreationParametersFragment;
/**
* The notes of the virtual machine.
*/
notes?: string;
/**
* The object identifier of the owner of the virtual machine.
*/
ownerObjectId?: string;
/**
* The user principal name of the virtual machine owner.
*/
ownerUserPrincipalName?: string;
/**
* The object identifier of the creator of the virtual machine.
*/
createdByUserId?: string;
/**
* The email address of creator of the virtual machine.
*/
createdByUser?: string;
/**
* The creation date of the virtual machine.
*/
createdDate?: Date;
/**
* The resource identifier (Microsoft.Compute) of the virtual machine.
*/
computeId?: string;
/**
* The custom image identifier of the virtual machine.
*/
customImageId?: string;
/**
* The OS type of the virtual machine.
*/
osType?: string;
/**
* The size of the virtual machine.
*/
size?: string;
/**
* The user name of the virtual machine.
*/
userName?: string;
/**
* The password of the virtual machine administrator.
*/
password?: string;
/**
* The SSH key of the virtual machine administrator.
*/
sshKey?: string;
/**
* Indicates whether this virtual machine uses an SSH key for authentication.
*/
isAuthenticationWithSshKey?: boolean;
/**
* The fully-qualified domain name of the virtual machine.
*/
fqdn?: string;
/**
* The lab subnet name of the virtual machine.
*/
labSubnetName?: string;
/**
* The lab virtual network identifier of the virtual machine.
*/
labVirtualNetworkId?: string;
/**
* Indicates whether the virtual machine is to be created without a public IP address.
*/
disallowPublicIpAddress?: boolean;
/**
* The artifacts to be installed on the virtual machine.
*/
artifacts?: ArtifactInstallPropertiesFragment[];
/**
* The artifact deployment status for the virtual machine.
*/
artifactDeploymentStatus?: ArtifactDeploymentStatusPropertiesFragment;
/**
* The Microsoft Azure Marketplace image reference of the virtual machine.
*/
galleryImageReference?: GalleryImageReferenceFragment;
/**
* The id of the plan associated with the virtual machine image
*/
planId?: string;
/**
* The network interface properties.
*/
networkInterface?: NetworkInterfacePropertiesFragment;
/**
* The expiration date for VM.
*/
expirationDate?: Date;
/**
* Indicates whether another user can take ownership of the virtual machine
*/
allowClaim?: boolean;
/**
* Storage type to use for virtual machine (i.e. Standard, Premium).
*/
storageType?: string;
/**
* Tells source of creation of lab virtual machine. Output property only. Possible values
* include: 'FromCustomImage', 'FromGalleryImage'
*/
virtualMachineCreationSource?: string;
/**
* The resource ID of the environment that contains this virtual machine, if any.
*/
environmentId?: string;
/**
* New or existing data disks to attach to the virtual machine after creation
*/
dataDiskParameters?: DataDiskPropertiesFragment[];
/**
* Virtual Machine schedules to be created
*/
scheduleParameters?: ScheduleCreationParameterFragment[];
/**
* Last known compute power state captured in DTL
*/
lastKnownPowerState?: string;
/**
* The name of the virtual machine or environment
*/
name?: string;
/**
* The location of the new virtual machine or environment
*/
location?: string;
/**
* The tags of the resource.
*/
tags?: { [propertyName: string]: string };
}
/**
* Information about a VM from which a formula is to be created.
*/
export interface FormulaPropertiesFromVmFragment {
/**
* The identifier of the VM from which a formula is to be created.
*/
labVmId?: string;
}
/**
* A formula for creating a VM, specifying an image base and other parameters
*/
export interface FormulaFragment extends UpdateResource {
/**
* The description of the formula.
*/
description?: string;
/**
* The author of the formula.
*/
author?: string;
/**
* The OS type of the formula.
*/
osType?: string;
/**
* The content of the formula.
*/
formulaContent?: LabVirtualMachineCreationParameterFragment;
/**
* Information about a VM from which a formula is to be created.
*/
vm?: FormulaPropertiesFromVmFragment;
}
/**
* A gallery image.
*/
export interface GalleryImage extends Resource {
/**
* The author of the gallery image.
*/
author?: string;
/**
* The creation date of the gallery image.
*/
readonly createdDate?: Date;
/**
* The description of the gallery image.
*/
description?: string;
/**
* The image reference of the gallery image.
*/
imageReference?: GalleryImageReference;
/**
* The icon of the gallery image.
*/
icon?: string;
/**
* Indicates whether this gallery image is enabled.
*/
enabled?: boolean;
/**
* The third party plan that applies to this image
*/
planId?: string;
/**
* Indicates if the plan has been authorized for programmatic deployment.
*/
isPlanAuthorized?: boolean;
}
/**
* Information about an artifact's parameter.
*/
export interface ParameterInfo {
/**
* The name of the artifact parameter.
*/
name?: string;
/**
* The value of the artifact parameter.
*/
value?: string;
}
/**
* Parameters for generating an ARM template for deploying artifacts.
*/
export interface GenerateArmTemplateRequest {
/**
* The resource name of the virtual machine.
*/
virtualMachineName?: string;
/**
* The parameters of the ARM template.
*/
parameters?: ParameterInfo[];
/**
* The location of the virtual machine.
*/
location?: string;
/**
* Options for uploading the files for the artifact. UploadFilesAndGenerateSasTokens is the
* default value. Possible values include: 'UploadFilesAndGenerateSasTokens', 'None'
*/
fileUploadOptions?: string;
}
/**
* Properties for generating an upload URI.
*/
export interface GenerateUploadUriParameter {
/**
* The blob name of the upload URI.
*/
blobName?: string;
}
/**
* Response body for generating an upload URI.
*/
export interface GenerateUploadUriResponse {
/**
* The upload URI for the VHD.
*/
uploadUri?: string;
}
/**
* Properties of a managed identity
*/
export interface IdentityProperties {
/**
* Managed identity.
*/
type?: string;
/**
* The principal id of resource identity.
*/
principalId?: string;
/**
* The tenant identifier of resource.
*/
tenantId?: string;
/**
* The client secret URL of the identity.
*/
clientSecretUrl?: string;
}
/**
* This represents the payload required to import a virtual machine from a different lab into the
* current one
*/
export interface ImportLabVirtualMachineRequest {
/**
* The full resource ID of the virtual machine to be imported.
*/
sourceVirtualMachineResourceId?: string;
/**
* The name of the virtual machine in the destination lab
*/
destinationVirtualMachineName?: string;
}
/**
* Properties of a lab's announcement banner
*/
export interface LabAnnouncementProperties {
/**
* The plain text title for the lab announcement
*/
title?: string;
/**
* The markdown text (if any) that this lab displays in the UI. If left empty/null, nothing will
* be shown.
*/
markdown?: string;
/**
* Is the lab announcement active/enabled at this time?. Possible values include: 'Enabled',
* 'Disabled'
*/
enabled?: string;
/**
* The time at which the announcement expires (null for never)
*/
expirationDate?: Date;
/**
* Has this announcement expired?
*/
expired?: boolean;
/**
* The provisioning status of the resource.
*/
readonly provisioningState?: string;
/**
* The unique immutable identifier of a resource (Guid).
*/
readonly uniqueIdentifier?: string;
}
/**
* Properties of a lab's support banner
*/
export interface LabSupportProperties {
/**
* Is the lab support banner active/enabled at this time?. Possible values include: 'Enabled',
* 'Disabled'
*/
enabled?: string;
/**
* The markdown text (if any) that this lab displays in the UI. If left empty/null, nothing will
* be shown.
*/
markdown?: string;
}
/**
* A lab.
*/
export interface Lab extends Resource {
/**
* The lab's default storage account.
*/
readonly defaultStorageAccount?: string;
/**
* The lab's default premium storage account.
*/
readonly defaultPremiumStorageAccount?: string;
/**
* The lab's artifact storage account.
*/
readonly artifactsStorageAccount?: string;
/**
* The lab's premium data disk storage account.
*/
readonly premiumDataDiskStorageAccount?: string;
/**
* The lab's Key vault.
*/
readonly vaultName?: string;
/**
* Type of storage used by the lab. It can be either Premium or Standard. Default is Premium.
* Possible values include: 'Standard', 'Premium'
*/
labStorageType?: string;
/**
* The ordered list of artifact resource IDs that should be applied on all Linux VM creations by
* default, prior to the artifacts specified by the user.
*/
mandatoryArtifactsResourceIdsLinux?: string[];
/**
* The ordered list of artifact resource IDs that should be applied on all Windows VM creations
* by default, prior to the artifacts specified by the user.
*/
mandatoryArtifactsResourceIdsWindows?: string[];
/**
* The creation date of the lab.
*/
readonly createdDate?: Date;
/**
* The setting to enable usage of premium data disks.
* When its value is 'Enabled', creation of standard or premium data disks is allowed.
* When its value is 'Disabled', only creation of standard data disks is allowed. Possible values
* include: 'Disabled', 'Enabled'
*/
premiumDataDisks?: string;
/**
* The access rights to be granted to the user when provisioning an environment. Possible values
* include: 'Reader', 'Contributor'
*/
environmentPermission?: string;
/**
* The properties of any lab announcement associated with this lab
*/
announcement?: LabAnnouncementProperties;
/**
* The properties of any lab support message associated with this lab
*/
support?: LabSupportProperties;
/**
* The resource group in which lab virtual machines will be created in.
*/
readonly vmCreationResourceGroup?: string;
/**
* The public IP address for the lab's load balancer.
*/
readonly publicIpId?: string;
/**
* The load balancer used to for lab VMs that use shared IP address.
*/
readonly loadBalancerId?: string;
/**
* The Network Security Group attached to the lab VMs Network interfaces to restrict open ports.
*/
readonly networkSecurityGroupId?: string;
/**
* Extended properties of the lab used for experimental features
*/
extendedProperties?: { [propertyName: string]: string };
/**
* The provisioning status of the resource.
*/
readonly provisioningState?: string;
/**
* The unique immutable identifier of a resource (Guid).
*/
readonly uniqueIdentifier?: string;
}
/**
* Properties of a lab's announcement banner
*/
export interface LabAnnouncementPropertiesFragment {
/**
* The plain text title for the lab announcement
*/
title?: string;
/**
* The markdown text (if any) that this lab displays in the UI. If left empty/null, nothing will
* be shown.
*/
markdown?: string;
/**
* Is the lab announcement active/enabled at this time?. Possible values include: 'Enabled',
* 'Disabled'
*/
enabled?: string;
/**
* The time at which the announcement expires (null for never)
*/
expirationDate?: Date;
/**
* Has this announcement expired?
*/
expired?: boolean;
}
/**
* Properties of a cost target.
*/
export interface TargetCostProperties {
/**
* Target cost status. Possible values include: 'Enabled', 'Disabled'
*/
status?: string;
/**
* Lab target cost
*/
target?: number;
/**
* Cost thresholds.
*/
costThresholds?: CostThresholdProperties[];
/**
* Reporting cycle start date.
*/
cycleStartDateTime?: Date;
/**
* Reporting cycle end date.
*/
cycleEndDateTime?: Date;
/**
* Reporting cycle type. Possible values include: 'CalendarMonth', 'Custom'
*/
cycleType?: string;
}
/**
* The properties of the cost summary.
*/
export interface LabCostSummaryProperties {
/**
* The cost component of the cost item.
*/
estimatedLabCost?: number;
}
/**
* The properties of a lab cost item.
*/
export interface LabCostDetailsProperties {
/**
* The date of the cost item.
*/
date?: Date;
/**
* The cost component of the cost item.
*/
cost?: number;
/**
* The type of the cost. Possible values include: 'Unavailable', 'Reported', 'Projected'
*/
costType?: string;
}
/**
* The properties of a resource cost item.
*/
export interface LabResourceCostProperties {
/**
* The name of the resource.
*/
resourcename?: string;
/**
* The unique identifier of the resource.
*/
resourceUId?: string;
/**
* The cost component of the resource cost item.
*/
resourceCost?: number;
/**
* The logical resource type (ex. virtualmachine, storageaccount)
*/
resourceType?: string;
/**
* The owner of the resource (ex. janedoe@microsoft.com)
*/
resourceOwner?: string;
/**
* The category of the resource (ex. Premium_LRS, Standard_DS1)
*/
resourcePricingTier?: string;
/**
* The status of the resource (ex. Active)
*/
resourceStatus?: string;
/**
* The ID of the resource
*/
resourceId?: string;
/**
* The ID of the external resource
*/
externalResourceId?: string;
}
/**
* A cost item.
*/
export interface LabCost extends Resource {
/**
* The target cost properties
*/
targetCost?: TargetCostProperties;
/**
* The lab cost summary component of the cost data.
*/
readonly labCostSummary?: LabCostSummaryProperties;
/**
* The lab cost details component of the cost data.
*/
readonly labCostDetails?: LabCostDetailsProperties[];
/**
* The resource cost component of the cost data.
*/
readonly resourceCosts?: LabResourceCostProperties[];
/**
* The currency code of the cost.
*/
currencyCode?: string;
/**
* The start time of the cost data.
*/
startDateTime?: Date;
/**
* The end time of the cost data.
*/
endDateTime?: Date;
/**
* The creation date of the cost.
*/
createdDate?: Date;
/**
* The provisioning status of the resource.
*/
readonly provisioningState?: string;
/**
* The unique immutable identifier of a resource (Guid).
*/
readonly uniqueIdentifier?: string;
}
/**
* Properties of a lab's support banner
*/
export interface LabSupportPropertiesFragment {
/**
* Is the lab support banner active/enabled at this time?. Possible values include: 'Enabled',
* 'Disabled'
*/
enabled?: string;
/**
* The markdown text (if any) that this lab displays in the UI. If left empty/null, nothing will
* be shown.
*/
markdown?: string;
}
/**
* A lab.
*/
export interface LabFragment extends UpdateResource {
/**
* Type of storage used by the lab. It can be either Premium or Standard. Default is Premium.
* Possible values include: 'Standard', 'Premium'
*/
labStorageType?: string;
/**
* The ordered list of artifact resource IDs that should be applied on all Linux VM creations by
* default, prior to the artifacts specified by the user.
*/
mandatoryArtifactsResourceIdsLinux?: string[];
/**
* The ordered list of artifact resource IDs that should be applied on all Windows VM creations
* by default, prior to the artifacts specified by the user.
*/
mandatoryArtifactsResourceIdsWindows?: string[];
/**
* The setting to enable usage of premium data disks.
* When its value is 'Enabled', creation of standard or premium data disks is allowed.
* When its value is 'Disabled', only creation of standard data disks is allowed. Possible values
* include: 'Disabled', 'Enabled'
*/
premiumDataDisks?: string;
/**
* The access rights to be granted to the user when provisioning an environment. Possible values
* include: 'Reader', 'Contributor'
*/
environmentPermission?: string;
/**
* The properties of any lab announcement associated with this lab
*/
announcement?: LabAnnouncementPropertiesFragment;
/**
* The properties of any lab support message associated with this lab
*/
support?: LabSupportPropertiesFragment;
/**
* Extended properties of the lab used for experimental features
*/
extendedProperties?: { [propertyName: string]: string };
}
/**
* Properties of a VHD in the lab.
*/
export interface LabVhd {
/**
* The URI to the VHD.
*/
id?: string;
}
/**
* A virtual machine.
*/
export interface LabVirtualMachine extends Resource {
/**
* The notes of the virtual machine.
*/
notes?: string;
/**
* The object identifier of the owner of the virtual machine.
*/
ownerObjectId?: string;
/**
* The user principal name of the virtual machine owner.
*/
ownerUserPrincipalName?: string;
/**
* The object identifier of the creator of the virtual machine.
*/
createdByUserId?: string;
/**
* The email address of creator of the virtual machine.
*/
createdByUser?: string;
/**
* The creation date of the virtual machine.
*/
createdDate?: Date;
/**
* The resource identifier (Microsoft.Compute) of the virtual machine.
*/
computeId?: string;
/**
* The custom image identifier of the virtual machine.
*/
customImageId?: string;
/**
* The OS type of the virtual machine.
*/
osType?: string;
/**
* The size of the virtual machine.
*/
size?: string;
/**
* The user name of the virtual machine.
*/
userName?: string;
/**
* The password of the virtual machine administrator.
*/
password?: string;
/**
* The SSH key of the virtual machine administrator.
*/
sshKey?: string;
/**
* Indicates whether this virtual machine uses an SSH key for authentication.
*/
isAuthenticationWithSshKey?: boolean;
/**
* The fully-qualified domain name of the virtual machine.
*/
fqdn?: string;
/**
* The lab subnet name of the virtual machine.
*/
labSubnetName?: string;
/**
* The lab virtual network identifier of the virtual machine.
*/
labVirtualNetworkId?: string;
/**
* Indicates whether the virtual machine is to be created without a public IP address.
*/
disallowPublicIpAddress?: boolean;
/**
* The artifacts to be installed on the virtual machine.
*/
artifacts?: ArtifactInstallProperties[];
/**
* The artifact deployment status for the virtual machine.
*/
artifactDeploymentStatus?: ArtifactDeploymentStatusProperties;
/**
* The Microsoft Azure Marketplace image reference of the virtual machine.
*/
galleryImageReference?: GalleryImageReference;
/**
* The id of the plan associated with the virtual machine image
*/
planId?: string;
/**
* The compute virtual machine properties.
*/
readonly computeVm?: ComputeVmProperties;
/**
* The network interface properties.
*/
networkInterface?: NetworkInterfaceProperties;
/**
* The applicable schedule for the virtual machine.
*/
readonly applicableSchedule?: ApplicableSchedule;
/**
* The expiration date for VM.
*/
expirationDate?: Date;
/**
* Indicates whether another user can take ownership of the virtual machine
*/
allowClaim?: boolean;
/**
* Storage type to use for virtual machine (i.e. Standard, Premium).
*/
storageType?: string;
/**
* Tells source of creation of lab virtual machine. Output property only. Possible values
* include: 'FromCustomImage', 'FromGalleryImage'
*/
virtualMachineCreationSource?: string;
/**
* The resource ID of the environment that contains this virtual machine, if any.
*/
environmentId?: string;
/**
* New or existing data disks to attach to the virtual machine after creation
*/
dataDiskParameters?: DataDiskProperties[];
/**
* Virtual Machine schedules to be created
*/
scheduleParameters?: ScheduleCreationParameter[];
/**
* Last known compute power state captured in DTL
*/
lastKnownPowerState?: string;
/**
* The provisioning status of the resource.
*/
readonly provisioningState?: string;
/**
* The unique immutable identifier of a resource (Guid).
*/
readonly uniqueIdentifier?: string;
}
/**
* A virtual machine.
*/
export interface LabVirtualMachineFragment extends UpdateResource {
/**
* The notes of the virtual machine.
*/
notes?: string;
/**
* The object identifier of the owner of the virtual machine.
*/
ownerObjectId?: string;
/**
* The user principal name of the virtual machine owner.
*/
ownerUserPrincipalName?: string;
/**
* The object identifier of the creator of the virtual machine.
*/
createdByUserId?: string;
/**
* The email address of creator of the virtual machine.
*/
createdByUser?: string;
/**
* The creation date of the virtual machine.
*/
createdDate?: Date;
/**
* The resource identifier (Microsoft.Compute) of the virtual machine.
*/
computeId?: string;
/**
* The custom image identifier of the virtual machine.
*/
customImageId?: string;
/**
* The OS type of the virtual machine.
*/
osType?: string;
/**
* The size of the virtual machine.
*/
size?: string;
/**
* The user name of the virtual machine.
*/
userName?: string;
/**
* The password of the virtual machine administrator.
*/
password?: string;
/**
* The SSH key of the virtual machine administrator.
*/
sshKey?: string;
/**
* Indicates whether this virtual machine uses an SSH key for authentication.
*/
isAuthenticationWithSshKey?: boolean;
/**
* The fully-qualified domain name of the virtual machine.
*/
fqdn?: string;
/**
* The lab subnet name of the virtual machine.
*/
labSubnetName?: string;
/**
* The lab virtual network identifier of the virtual machine.
*/
labVirtualNetworkId?: string;
/**
* Indicates whether the virtual machine is to be created without a public IP address.
*/
disallowPublicIpAddress?: boolean;
/**
* The artifacts to be installed on the virtual machine.
*/
artifacts?: ArtifactInstallPropertiesFragment[];
/**
* The artifact deployment status for the virtual machine.
*/
artifactDeploymentStatus?: ArtifactDeploymentStatusPropertiesFragment;
/**
* The Microsoft Azure Marketplace image reference of the virtual machine.
*/
galleryImageReference?: GalleryImageReferenceFragment;
/**
* The id of the plan associated with the virtual machine image
*/
planId?: string;
/**
* The network interface properties.
*/
networkInterface?: NetworkInterfacePropertiesFragment;
/**
* The expiration date for VM.
*/
expirationDate?: Date;
/**
* Indicates whether another user can take ownership of the virtual machine
*/
allowClaim?: boolean;
/**
* Storage type to use for virtual machine (i.e. Standard, Premium).
*/
storageType?: string;
/**
* Tells source of creation of lab virtual machine. Output property only. Possible values
* include: 'FromCustomImage', 'FromGalleryImage'
*/
virtualMachineCreationSource?: string;
/**
* The resource ID of the environment that contains this virtual machine, if any.
*/
environmentId?: string;
/**
* New or existing data disks to attach to the virtual machine after creation
*/
dataDiskParameters?: DataDiskPropertiesFragment[];
/**
* Virtual Machine schedules to be created
*/
scheduleParameters?: ScheduleCreationParameterFragment[];
/**
* Last known compute power state captured in DTL
*/
lastKnownPowerState?: string;
}
/**
* A notification.
*/
export interface NotificationChannel extends Resource {
/**
* The webhook URL to send notifications to.
*/
webHookUrl?: string;
/**
* The email recipient to send notifications to (can be a list of semi-colon separated email
* addresses).
*/
emailRecipient?: string;
/**
* The locale to use when sending a notification (fallback for unsupported languages is EN).
*/
notificationLocale?: string;
/**
* Description of notification.
*/
description?: string;
/**
* The list of event for which this notification is enabled.
*/
events?: Event[];
/**
* The creation date of the notification channel.
*/
readonly createdDate?: Date;
/**
* The provisioning status of the resource.
*/
readonly provisioningState?: string;
/**
* The unique immutable identifier of a resource (Guid).
*/
readonly uniqueIdentifier?: string;
}
/**
* A notification.
*/
export interface NotificationChannelFragment extends UpdateResource {
/**
* The webhook URL to send notifications to.
*/
webHookUrl?: string;
/**
* The email recipient to send notifications to (can be a list of semi-colon separated email
* addresses).
*/
emailRecipient?: string;
/**
* The locale to use when sending a notification (fallback for unsupported languages is EN).
*/
notificationLocale?: string;
/**
* Description of notification.
*/
description?: string;
/**
* The list of event for which this notification is enabled.
*/
events?: EventFragment[];
}
/**
* Properties for generating a Notification.
*/
export interface NotifyParameters {
/**
* The type of event (i.e. AutoShutdown, Cost). Possible values include: 'AutoShutdown', 'Cost'
*/
eventName?: string;
/**
* Properties for the notification in json format.
*/
jsonPayload?: string;
}
/**
* Error details for the operation in case of a failure.
*/
export interface OperationError {
/**
* The error code of the operation error.
*/
code?: string;
/**
* The error message of the operation error.
*/
message?: string;
}
/**
* The object that describes the operations
*/
export interface OperationMetadataDisplay {
/**
* Friendly name of the resource provider
*/
provider?: string;
/**
* Resource type on which the operation is performed.
*/
resource?: string;
/**
* Operation type: read, write, delete, listKeys/action, etc.
*/
operation?: string;
/**
* Friendly name of the operation
*/
description?: string;
}
/**
* The REST API operation supported by DevTestLab ResourceProvider.
*/
export interface OperationMetadata {
/**
* Operation name: {provider}/{resource}/{operation}
*/
name?: string;
/**
* The object that describes the operations
*/
display?: OperationMetadataDisplay;
}
/**
* An Operation Result
*/
export interface OperationResult {
/**
* The operation status.
*/
status?: string;
/**
* The status code for the operation. Possible values include: 'Continue', 'SwitchingProtocols',
* 'OK', 'Created', 'Accepted', 'NonAuthoritativeInformation', 'NoContent', 'ResetContent',
* 'PartialContent', 'MultipleChoices', 'MovedPermanently', 'Redirect', 'SeeOther',
* 'NotModified', 'UseProxy', 'Unused', 'TemporaryRedirect', 'BadRequest', 'Unauthorized',
* 'PaymentRequired', 'Forbidden', 'NotFound', 'MethodNotAllowed', 'NotAcceptable',
* 'ProxyAuthenticationRequired', 'RequestTimeout', 'Conflict', 'Gone', 'LengthRequired',
* 'PreconditionFailed', 'RequestEntityTooLarge', 'RequestUriTooLong', 'UnsupportedMediaType',
* 'RequestedRangeNotSatisfiable', 'ExpectationFailed', 'UpgradeRequired', 'InternalServerError',
* 'NotImplemented', 'BadGateway', 'ServiceUnavailable', 'GatewayTimeout',
* 'HttpVersionNotSupported'
*/
statusCode?: string;
/**
* Error details for the operation in case of a failure.
*/
error?: OperationError;
}
/**
* A Policy.
*/
export interface Policy extends Resource {
/**
* The description of the policy.
*/
description?: string;
/**
* The status of the policy. Possible values include: 'Enabled', 'Disabled'
*/
status?: string;
/**
* The fact name of the policy (e.g. LabVmCount, LabVmSize, MaxVmsAllowedPerLab, etc. Possible
* values include: 'UserOwnedLabVmCount', 'UserOwnedLabPremiumVmCount', 'LabVmCount',
* 'LabPremiumVmCount', 'LabVmSize', 'GalleryImage', 'UserOwnedLabVmCountInSubnet',
* 'LabTargetCost', 'EnvironmentTemplate', 'ScheduleEditPermission'
*/
factName?: string;
/**
* The fact data of the policy.
*/
factData?: string;
/**
* The threshold of the policy (i.e. a number for MaxValuePolicy, and a JSON array of values for
* AllowedValuesPolicy).
*/
threshold?: string;
/**
* The evaluator type of the policy (i.e. AllowedValuesPolicy, MaxValuePolicy). Possible values
* include: 'AllowedValuesPolicy', 'MaxValuePolicy'
*/
evaluatorType?: string;
/**
* The creation date of the policy.
*/
readonly createdDate?: Date;
/**
* The provisioning status of the resource.
*/
readonly provisioningState?: string;
/**
* The unique immutable identifier of a resource (Guid).
*/
readonly uniqueIdentifier?: string;
}
/**
* A Policy.
*/
export interface PolicyFragment extends UpdateResource {
/**
* The description of the policy.
*/
description?: string;
/**
* The status of the policy. Possible values include: 'Enabled', 'Disabled'
*/
status?: string;
/**
* The fact name of the policy (e.g. LabVmCount, LabVmSize, MaxVmsAllowedPerLab, etc. Possible
* values include: 'UserOwnedLabVmCount', 'UserOwnedLabPremiumVmCount', 'LabVmCount',
* 'LabPremiumVmCount', 'LabVmSize', 'GalleryImage', 'UserOwnedLabVmCountInSubnet',
* 'LabTargetCost', 'EnvironmentTemplate', 'ScheduleEditPermission'
*/
factName?: string;
/**
* The fact data of the policy.
*/
factData?: string;
/**
* The threshold of the policy (i.e. a number for MaxValuePolicy, and a JSON array of values for
* AllowedValuesPolicy).
*/
threshold?: string;
/**
* The evaluator type of the policy (i.e. AllowedValuesPolicy, MaxValuePolicy). Possible values
* include: 'AllowedValuesPolicy', 'MaxValuePolicy'
*/
evaluatorType?: string;
}
/**
* Properties of a network port.
*/
export interface Port {
/**
* Protocol type of the port. Possible values include: 'Tcp', 'Udp'
*/
transportProtocol?: string;
/**
* Backend port of the target virtual machine.
*/
backendPort?: number;
}
/**
* Properties of a network port.
*/
export interface PortFragment {
/**
* Protocol type of the port. Possible values include: 'Tcp', 'Udp'
*/
transportProtocol?: string;
/**
* Backend port of the target virtual machine.
*/
backendPort?: number;
}
/**
* Represents a .rdp file
*/
export interface RdpConnection {
/**
* The contents of the .rdp file
*/
contents?: string;
}
/**
* Request body for resizing a virtual machine.
*/
export interface ResizeLabVirtualMachineProperties {
/**
* Specifies the size of the virtual machine.
*/
size?: string;
}
/**
* Properties for retargeting a virtual machine schedule.
*/
export interface RetargetScheduleProperties {
/**
* The resource Id of the virtual machine on which the schedule operates
*/
currentResourceId?: string;
/**
* The resource Id of the virtual machine that the schedule should be retargeted to
*/
targetResourceId?: string;
}
/**
* A secret.
*/
export interface Secret extends Resource {
/**
* The value of the secret for secret creation.
*/
value?: string;
/**
* The provisioning status of the resource.
*/
readonly provisioningState?: string;
/**
* The unique immutable identifier of a resource (Guid).
*/
readonly uniqueIdentifier?: string;
}
/**
* A secret.
*/
export interface SecretFragment extends UpdateResource {
/**
* The value of the secret for secret creation.
*/
value?: string;
}
/**
* A Service Fabric.
*/
export interface ServiceFabric extends Resource {
/**
* The backing service fabric resource's id
*/
externalServiceFabricId?: string;
/**
* The resource id of the environment under which the service fabric resource is present
*/
environmentId?: string;
/**
* The applicable schedule for the virtual machine.
*/
readonly applicableSchedule?: ApplicableSchedule;
/**
* The provisioning status of the resource.
*/
readonly provisioningState?: string;
/**
* The unique immutable identifier of a resource (Guid).
*/
readonly uniqueIdentifier?: string;
}
/**
* A Service Fabric.
*/
export interface ServiceFabricFragment extends UpdateResource {
/**
* The backing service fabric resource's id
*/
externalServiceFabricId?: string;
/**
* The resource id of the environment under which the service fabric resource is present
*/
environmentId?: string;
}
/**
* A container for a managed identity to execute DevTest lab services.
*/
export interface ServiceRunner extends Resource {
/**
* The identity of the resource.
*/
identity?: IdentityProperties;
}
/**
* The contents of a shutdown notification. Webhooks can use this type to deserialize the request
* body when they get notified of an imminent shutdown.
*/
export interface ShutdownNotificationContent {
/**
* The URL to skip auto-shutdown.
*/
skipUrl?: string;
/**
* The URL to delay shutdown by 60 minutes.
*/
delayUrl60?: string;
/**
* The URL to delay shutdown by 2 hours.
*/
delayUrl120?: string;
/**
* The virtual machine to be shut down.
*/
vmName?: string;
/**
* The GUID for the virtual machine to be shut down.
*/
guid?: string;
/**
* The owner of the virtual machine.
*/
owner?: string;
/**
* The URL of the virtual machine.
*/
vmUrl?: string;
/**
* Minutes remaining until shutdown
*/
minutesUntilShutdown?: string;
/**
* The event for which a notification will be sent.
*/
eventType?: string;
/**
* The text for the notification.
*/
text?: string;
/**
* The subscription ID for the schedule.
*/
subscriptionId?: string;
/**
* The resource group name for the schedule.
*/
resourceGroupName?: string;
/**
* The lab for the schedule.
*/
labName?: string;
}
/**
* Subnet information.
*/
export interface Subnet {
/**
* The resource ID of the subnet.
*/
resourceId?: string;
/**
* The name of the subnet as seen in the lab.
*/
labSubnetName?: string;
/**
* The permission policy of the subnet for allowing public IP addresses (i.e. Allow, Deny)).
* Possible values include: 'Default', 'Deny', 'Allow'
*/
allowPublicIp?: string;
}
/**
* Subnet information.
*/
export interface SubnetFragment {
/**
* The resource ID of the subnet.
*/
resourceId?: string;
/**
* The name of the subnet as seen in the lab.
*/
labSubnetName?: string;
/**
* The permission policy of the subnet for allowing public IP addresses (i.e. Allow, Deny)).
* Possible values include: 'Default', 'Deny', 'Allow'
*/
allowPublicIp?: string;
}
/**
* Configuration for public IP address sharing.
*/
export interface SubnetSharedPublicIpAddressConfiguration {
/**
* Backend ports that virtual machines on this subnet are allowed to expose
*/
allowedPorts?: Port[];
}
/**
* Property overrides on a subnet of a virtual network.
*/
export interface SubnetOverride {
/**
* The resource ID of the subnet.
*/
resourceId?: string;
/**
* The name given to the subnet within the lab.
*/
labSubnetName?: string;
/**
* Indicates whether this subnet can be used during virtual machine creation (i.e. Allow, Deny).
* Possible values include: 'Default', 'Deny', 'Allow'
*/
useInVmCreationPermission?: string;
/**
* Indicates whether public IP addresses can be assigned to virtual machines on this subnet (i.e.
* Allow, Deny). Possible values include: 'Default', 'Deny', 'Allow'
*/
usePublicIpAddressPermission?: string;
/**
* Properties that virtual machines on this subnet will share.
*/
sharedPublicIpAddressConfiguration?: SubnetSharedPublicIpAddressConfiguration;
/**
* The virtual network pool associated with this subnet.
*/
virtualNetworkPoolName?: string;
}
/**
* Configuration for public IP address sharing.
*/
export interface SubnetSharedPublicIpAddressConfigurationFragment {
/**
* Backend ports that virtual machines on this subnet are allowed to expose
*/
allowedPorts?: PortFragment[];
}
/**
* Property overrides on a subnet of a virtual network.
*/
export interface SubnetOverrideFragment {
/**
* The resource ID of the subnet.
*/
resourceId?: string;
/**
* The name given to the subnet within the lab.
*/
labSubnetName?: string;
/**
* Indicates whether this subnet can be used during virtual machine creation (i.e. Allow, Deny).
* Possible values include: 'Default', 'Deny', 'Allow'
*/
useInVmCreationPermission?: string;
/**
* Indicates whether public IP addresses can be assigned to virtual machines on this subnet (i.e.
* Allow, Deny). Possible values include: 'Default', 'Deny', 'Allow'
*/
usePublicIpAddressPermission?: string;
/**
* Properties that virtual machines on this subnet will share.
*/
sharedPublicIpAddressConfiguration?: SubnetSharedPublicIpAddressConfigurationFragment;
/**
* The virtual network pool associated with this subnet.
*/
virtualNetworkPoolName?: string;
}
/**
* Identity attributes of a lab user.
*/
export interface UserIdentity {
/**
* Set to the principal name / UPN of the client JWT making the request.
*/
principalName?: string;
/**
* Set to the principal Id of the client JWT making the request. Service principal will not have
* the principal Id.
*/
principalId?: string;
/**
* Set to the tenant ID of the client JWT making the request.
*/
tenantId?: string;
/**
* Set to the object Id of the client JWT making the request. Not all users have object Id. For
* CSP (reseller) scenarios for example, object Id is not available.
*/
objectId?: string;
/**
* Set to the app Id of the client JWT making the request.
*/
appId?: string;
}
/**
* Properties of a user's secret store.
*/
export interface UserSecretStore {
/**
* The URI of the user's Key vault.
*/
keyVaultUri?: string;
/**
* The ID of the user's Key vault.
*/
keyVaultId?: string;
}
/**
* Profile of a lab user.
*/
export interface User extends Resource {
/**
* The identity of the user.
*/
identity?: UserIdentity;
/**
* The secret store of the user.
*/
secretStore?: UserSecretStore;
/**
* The creation date of the user profile.
*/
readonly createdDate?: Date;
/**
* The provisioning status of the resource.
*/
readonly provisioningState?: string;
/**
* The unique immutable identifier of a resource (Guid).
*/
readonly uniqueIdentifier?: string;
}
/**
* Identity attributes of a lab user.
*/
export interface UserIdentityFragment {
/**
* Set to the principal name / UPN of the client JWT making the request.
*/
principalName?: string;
/**
* Set to the principal Id of the client JWT making the request. Service principal will not have
* the principal Id.
*/
principalId?: string;
/**
* Set to the tenant ID of the client JWT making the request.
*/
tenantId?: string;
/**
* Set to the object Id of the client JWT making the request. Not all users have object Id. For
* CSP (reseller) scenarios for example, object Id is not available.
*/
objectId?: string;
/**
* Set to the app Id of the client JWT making the request.
*/
appId?: string;
}
/**
* Properties of a user's secret store.
*/
export interface UserSecretStoreFragment {
/**
* The URI of the user's Key vault.
*/
keyVaultUri?: string;
/**
* The ID of the user's Key vault.
*/
keyVaultId?: string;
}
/**
* Profile of a lab user.
*/
export interface UserFragment extends UpdateResource {
/**
* The identity of the user.
*/
identity?: UserIdentityFragment;
/**
* The secret store of the user.
*/
secretStore?: UserSecretStoreFragment;
}
/**
* A virtual network.
*/
export interface VirtualNetwork extends Resource {
/**
* The allowed subnets of the virtual network.
*/
allowedSubnets?: Subnet[];
/**
* The description of the virtual network.
*/
description?: string;
/**
* The Microsoft.Network resource identifier of the virtual network.
*/
externalProviderResourceId?: string;
/**
* The external subnet properties.
*/
readonly externalSubnets?: ExternalSubnet[];
/**
* The subnet overrides of the virtual network.
*/
subnetOverrides?: SubnetOverride[];
/**
* The creation date of the virtual network.
*/
readonly createdDate?: Date;
/**
* The provisioning status of the resource.
*/
readonly provisioningState?: string;
/**
* The unique immutable identifier of a resource (Guid).
*/
readonly uniqueIdentifier?: string;
}
/**
* A virtual network.
*/
export interface VirtualNetworkFragment extends UpdateResource {
/**
* The allowed subnets of the virtual network.
*/
allowedSubnets?: SubnetFragment[];
/**
* The description of the virtual network.
*/
description?: string;
/**
* The Microsoft.Network resource identifier of the virtual network.
*/
externalProviderResourceId?: string;
/**
* The subnet overrides of the virtual network.
*/
subnetOverrides?: SubnetOverrideFragment[];
}
/**
* Result of the request to list REST API operations
*/
export interface ProviderOperationResult extends Array<OperationMetadata> {
/**
* URL to get the next set of operation list results if there are any.
*/
readonly nextLink?: string;
}
/**
* The response of a list operation.
*/
export interface LabList extends Array<Lab> {
/**
* Link for next set of results.
*/
nextLink?: string;
}
/**
* The response of a list operation.
*/
export interface LabVhdList extends Array<LabVhd> {
/**
* Link for next set of results.
*/
nextLink?: string;
}
/**
* The response of a list operation.
*/
export interface ScheduleList extends Array<Schedule> {
/**
* Link for next set of results.
*/
nextLink?: string;
}
/**
* The response of a list operation.
*/
export interface ArtifactSourceList extends Array<ArtifactSource> {
/**
* Link for next set of results.
*/
nextLink?: string;
}
/**
* The response of a list operation.
*/
export interface ArmTemplateList extends Array<ArmTemplate> {
/**
* Link for next set of results.
*/
nextLink?: string;
}
/**
* The response of a list operation.
*/
export interface ArtifactList extends Array<Artifact> {
/**
* Link for next set of results.
*/
nextLink?: string;
}
/**
* The response of a list operation.
*/
export interface CustomImageList extends Array<CustomImage> {
/**
* Link for next set of results.
*/
nextLink?: string;
}
/**
* The response of a list operation.
*/
export interface FormulaList extends Array<Formula> {
/**
* Link for next set of results.
*/
nextLink?: string;
}
/**
* The response of a list operation.
*/
export interface GalleryImageList extends Array<GalleryImage> {
/**
* Link for next set of results.
*/
nextLink?: string;
}
/**
* The response of a list operation.
*/
export interface NotificationChannelList extends Array<NotificationChannel> {
/**
* Link for next set of results.
*/
nextLink?: string;
}
/**
* The response of a list operation.
*/
export interface PolicyList extends Array<Policy> {
/**
* Link for next set of results.
*/
nextLink?: string;
}
/**
* The response of a list operation.
*/
export interface ServiceRunnerList extends Array<ServiceRunner> {
/**
* Link for next set of results.
*/
nextLink?: string;
}
/**
* The response of a list operation.
*/
export interface UserList extends Array<User> {
/**
* Link for next set of results.
*/
nextLink?: string;
}
/**
* The response of a list operation.
*/
export interface DiskList extends Array<Disk> {
/**
* Link for next set of results.
*/
nextLink?: string;
}
/**
* The response of a list operation.
*/
export interface DtlEnvironmentList extends Array<DtlEnvironment> {
/**
* Link for next set of results.
*/
nextLink?: string;
}
/**
* The response of a list operation.
*/
export interface SecretList extends Array<Secret> {
/**
* Link for next set of results.
*/
nextLink?: string;
}
/**
* The response of a list operation.
*/
export interface ServiceFabricList extends Array<ServiceFabric> {
/**
* Link for next set of results.
*/
nextLink?: string;
}
/**
* The response of a list operation.
*/
export interface LabVirtualMachineList extends Array<LabVirtualMachine> {
/**
* Link for next set of results.
*/
nextLink?: string;
}
/**
* The response of a list operation.
*/
export interface VirtualNetworkList extends Array<VirtualNetwork> {
/**
* Link for next set of results.
*/
nextLink?: string;
} | the_stack |
import { XYZ, AxisMap, EulerRotation } from "../Types";
import { PI, TWO_PI } from "./../constants";
/** Vector Math class. */
export default class Vector {
public x: number;
public y: number;
public z: number;
constructor(a?: number[] | XYZ | number | Vector | EulerRotation, b?: number, c?: number) {
if (Array.isArray(a)) {
this.x = a[0] ?? 0;
this.y = a[1] ?? 0;
this.z = a[2] ?? 0;
return;
}
if (!!a && typeof a === "object") {
this.x = a.x ?? 0;
this.y = a.y ?? 0;
this.z = a.z ?? 0;
return;
}
this.x = a ?? 0;
this.y = b ?? 0;
this.z = c ?? 0;
}
// Methods //
/**
* Returns the negative of this vector.
*/
negative() {
return new Vector(-this.x, -this.y, -this.z);
}
/**
* Add a vector or number to this vector.
* @param {Vector | number} a: Vector or number to add
* @returns {Vector} New vector
*/
add(v: Vector | number) {
if (v instanceof Vector) return new Vector(this.x + v.x, this.y + v.y, this.z + v.z);
else return new Vector(this.x + v, this.y + v, this.z + v);
}
/**
* Substracts a vector or number from this vector.
* @param {Vector | number} a: Vector or number to subtract
* @returns {Vector} New vector
*/
subtract(v: Vector | number) {
if (v instanceof Vector) return new Vector(this.x - v.x, this.y - v.y, this.z - v.z);
else return new Vector(this.x - v, this.y - v, this.z - v);
}
/**
* Multiplies a vector or a number to a vector.
* @param {Vector | number} a: Vector or number to multiply
* @param {Vector} b: Vector to multiply
*/
multiply(v: Vector | number) {
if (v instanceof Vector) return new Vector(this.x * v.x, this.y * v.y, this.z * v.z);
else return new Vector(this.x * v, this.y * v, this.z * v);
}
/**
* Divide this vector by a vector or a number.
* @param {Vector | number} a: Vector or number to divide
* @returns {Vector} New vector
*/
divide(v: Vector | number) {
if (v instanceof Vector) return new Vector(this.x / v.x, this.y / v.y, this.z / v.z);
else return new Vector(this.x / v, this.y / v, this.z / v);
}
/**
* Check if the given vector is equal to this vector.
* @param {Vector} v: Vector to compare
* @returns {boolean} True if equal
*/
equals(v: Vector) {
return this.x == v.x && this.y == v.y && this.z == v.z;
}
/**
* Returns the dot product of this vector and another vector.
* @param {Vector} v: Vector to dot
* @returns {number} Dot product
*/
dot(v: Vector) {
return this.x * v.x + this.y * v.y + this.z * v.z;
}
/**
* Cross product of two vectors.
* @param {Vector} a: Vector to cross
* @param {Vector} b: Vector to cross
*/
cross(v: Vector) {
return new Vector(this.y * v.z - this.z * v.y, this.z * v.x - this.x * v.z, this.x * v.y - this.y * v.x);
}
/**
* Get the length of the Vector
* @returns {number} Length
*/
length() {
return Math.sqrt(this.dot(this));
}
/**
* Find the distance between this and another vector.
* @param {Vector} v: Vector to find distance to
* @param {2 | 3} d: 2D or 3D distance
* @returns {number} Distance
*/
distance(v: Vector, d: 2 | 3 = 3) {
//2D distance
if (d === 2) return Math.sqrt(Math.pow(this.x - v.x, 2) + Math.pow(this.y - v.y, 2));
//3D distance
else return Math.sqrt(Math.pow(this.x - v.x, 2) + Math.pow(this.y - v.y, 2) + Math.pow(this.z - v.z, 2));
}
/**
* Lerp between this vector and another vector.
* @param {Vector} v: Vector to lerp to
* @param {number} fraction: Fraction to lerp
* @returns {Vector}
*/
lerp(v: Vector, fraction: number) {
return v.subtract(this).multiply(fraction).add(this);
}
/**
* Returns the unit vector of this vector.
* @returns {Vector} Unit vector
*/
unit() {
return this.divide(this.length());
}
min() {
return Math.min(Math.min(this.x, this.y), this.z);
}
max() {
return Math.max(Math.max(this.x, this.y), this.z);
}
/**
* To Angles
* @param {AxisMap} [axisMap = {x: "x", y: "y", z: "z"}]
* @returns {{ theta: number, phi: number }}
*/
toSphericalCoords(axisMap: AxisMap = { x: "x", y: "y", z: "z" }) {
return {
theta: Math.atan2(this[axisMap.y], this[axisMap.x]),
phi: Math.acos(this[axisMap.z] / this.length()),
};
}
/**
* Returns the angle between this vector and vector a in radians.
* @param {Vector} a: Vector
* @returns {number}
*/
angleTo(a: Vector) {
return Math.acos(this.dot(a) / (this.length() * a.length()));
}
/**
* Array representation of the vector.
* @param {number} n: Array length
* @returns {number[]} Array
* @example
* new Vector(1, 2, 3).toArray(); // [1, 2, 3]
*/
toArray(n: number) {
return [this.x, this.y, this.z].slice(0, n || 3);
}
/**
* Clone the vector.
* @returns {Vector} New vector
*/
clone() {
return new Vector(this.x, this.y, this.z);
}
/**
* Init this Vector with explicit values
* @param {number} x: X value
* @param {number} y: Y value
* @param {number} z: Z value
*/
init(x: number, y: number, z: number) {
this.x = x;
this.y = y;
this.z = z;
return this;
}
// static methods //
static negative(a: Vector, b: Vector = new Vector()) {
b.x = -a.x;
b.y = -a.y;
b.z = -a.z;
return b;
}
static add(a: Vector, b: Vector | number, c: Vector = new Vector()) {
if (b instanceof Vector) {
c.x = a.x + b.x;
c.y = a.y + b.y;
c.z = a.z + b.z;
} else {
c.x = a.x + b;
c.y = a.y + b;
c.z = a.z + b;
}
return c;
}
static subtract(a: Vector, b: Vector | number, c: Vector = new Vector()) {
if (b instanceof Vector) {
c.x = a.x - b.x;
c.y = a.y - b.y;
c.z = a.z - b.z;
} else {
c.x = a.x - b;
c.y = a.y - b;
c.z = a.z - b;
}
return c;
}
static multiply(a: Vector, b: Vector | number, c: Vector = new Vector()) {
if (b instanceof Vector) {
c.x = a.x * b.x;
c.y = a.y * b.y;
c.z = a.z * b.z;
} else {
c.x = a.x * b;
c.y = a.y * b;
c.z = a.z * b;
}
return c;
}
static divide(a: Vector, b: Vector | number, c: Vector = new Vector()) {
if (b instanceof Vector) {
c.x = a.x / b.x;
c.y = a.y / b.y;
c.z = a.z / b.z;
} else {
c.x = a.x / b;
c.y = a.y / b;
c.z = a.z / b;
}
return c;
}
static cross(a: Vector, b: Vector, c: Vector = new Vector()) {
c.x = a.y * b.z - a.z * b.y;
c.y = a.z * b.x - a.x * b.z;
c.z = a.x * b.y - a.y * b.x;
return c;
}
static unit(a: Vector, b: Vector) {
const length = a.length();
b.x = a.x / length;
b.y = a.y / length;
b.z = a.z / length;
return b;
}
/**
* Create new vector from angles
* @param {number} theta: Theta angle
* @param {number} phi: Phi angle
* @returns {Vector} New vector
*/
static fromAngles(theta: number, phi: number) {
return new Vector(Math.cos(theta) * Math.cos(phi), Math.sin(phi), Math.sin(theta) * Math.cos(phi));
}
static randomDirection() {
return Vector.fromAngles(Math.random() * TWO_PI, Math.asin(Math.random() * 2 - 1));
}
static min(a: Vector, b: Vector) {
return new Vector(Math.min(a.x, b.x), Math.min(a.y, b.y), Math.min(a.z, b.z));
}
static max(a: Vector, b: Vector) {
return new Vector(Math.max(a.x, b.x), Math.max(a.y, b.y), Math.max(a.z, b.z));
}
/**
* Lerp between two vectors
* @param {Vector} a: Vector a
* @param {Vector} b: Vector b
* @param {number} fraction: Fraction
*/
static lerp<T extends number | Vector>(a: T, b: T, fraction: number): T {
if (b instanceof Vector) {
return b.subtract(a).multiply(fraction).add(a) as unknown as T;
} else {
return (((b as number) - (a as number)) * fraction + (a as unknown as number)) as unknown as T;
}
}
/**
* Create a new vector from an Array
* @param {number[]} array: Array
* @returns {Vector} New vector
*/
static fromArray(a: Array<number> | XYZ) {
if (Array.isArray(a)) {
return new Vector(a[0], a[1], a[2]);
}
return new Vector(a.x, a.y, a.z);
}
/**
* Angle between two vectors
* @param {Vector} a: Vector a
* @param {Vector} b: Vector b
* @returns
*/
static angleBetween(a: Vector, b: Vector) {
return a.angleTo(b);
}
static distance(a: Vector, b: Vector, d: number) {
if (d === 2) return Math.sqrt(Math.pow(a.x - b.x, 2) + Math.pow(a.y - b.y, 2));
else return Math.sqrt(Math.pow(a.x - b.x, 2) + Math.pow(a.y - b.y, 2) + Math.pow(a.z - b.z, 2));
}
static toDegrees(a: number) {
return a * (180 / PI);
}
static normalizeAngle(radians: number) {
let angle = radians % TWO_PI;
angle = angle > PI ? angle - TWO_PI : angle < -PI ? TWO_PI + angle : angle;
//returns normalized values to -1,1
return angle / PI;
}
static normalizeRadians(radians: number) {
if (radians >= PI / 2) {
radians -= TWO_PI;
}
if (radians <= -PI / 2) {
radians += TWO_PI;
radians = PI - radians;
}
//returns normalized values to -1,1
return radians / PI;
}
static find2DAngle(cx: number, cy: number, ex: number, ey: number) {
const dy = ey - cy;
const dx = ex - cx;
const theta = Math.atan2(dy, dx);
return theta;
}
/**
* Find 3D rotation between two vectors
* @param {Vector} a: First vector
* @param {Vector} b: Second vector
* @param {boolean} normalize: Normalize the result
*/
static findRotation(a: Vector | XYZ, b: Vector | XYZ, normalize = true) {
if (normalize) {
return new Vector(
Vector.normalizeRadians(Vector.find2DAngle(a.z, a.x, b.z, b.x)),
Vector.normalizeRadians(Vector.find2DAngle(a.z, a.y, b.z, b.y)),
Vector.normalizeRadians(Vector.find2DAngle(a.x, a.y, b.x, b.y))
);
} else {
return new Vector(
Vector.find2DAngle(a.z, a.x, b.z, b.x),
Vector.find2DAngle(a.z, a.y, b.z, b.y),
Vector.find2DAngle(a.x, a.y, b.x, b.y)
);
}
}
/**
* Find roll pitch yaw of plane formed by 3 points
* @param {Vector} a: Vector
* @param {Vector} b: Vector
* @param {Vector} c: Vector
*/
static rollPitchYaw(a: Vector | XYZ, b: Vector | XYZ, c?: Vector) {
if (!c) {
return new Vector(
Vector.normalizeAngle(Vector.find2DAngle(a.z, a.y, b.z, b.y)),
Vector.normalizeAngle(Vector.find2DAngle(a.z, a.x, b.z, b.x)),
Vector.normalizeAngle(Vector.find2DAngle(a.x, a.y, b.x, b.y))
);
}
const qb = (b as Vector).subtract(a as Vector);
const qc = c.subtract(a as Vector);
const n = qb.cross(qc);
const unitZ = n.unit();
const unitX = qb.unit();
const unitY = unitZ.cross(unitX);
const beta = Math.asin(unitZ.x) || 0;
const alpha = Math.atan2(-unitZ.y, unitZ.z) || 0;
const gamma = Math.atan2(-unitY.x, unitX.x) || 0;
return new Vector(Vector.normalizeAngle(alpha), Vector.normalizeAngle(beta), Vector.normalizeAngle(gamma));
}
/**
* Find angle between 3D Coordinates
* @param {Vector | number} a: Vector or Number
* @param {Vector | number} b: Vector or Number
* @param {Vector | number} c: Vector or Number
*/
static angleBetween3DCoords(a: Vector | XYZ, b: Vector | XYZ, c: Vector | XYZ) {
if (!(a instanceof Vector)) {
a = new Vector(a);
b = new Vector(b);
c = new Vector(c);
}
// Calculate vector between points 1 and 2
const v1 = (a as Vector).subtract(b as Vector);
// Calculate vector between points 2 and 3
const v2 = (c as Vector).subtract(b as Vector);
// The dot product of vectors v1 & v2 is a function of the cosine of the
// angle between them (it's scaled by the product of their magnitudes).
const v1norm = v1.unit();
const v2norm = v2.unit();
// Calculate the dot products of vectors v1 and v2
const dotProducts = v1norm.dot(v2norm);
// Extract the angle from the dot products
const angle = Math.acos(dotProducts);
// return single angle Normalized to 1
return Vector.normalizeRadians(angle);
}
/**
* Get normalized, spherical coordinates for the vector bc, relative to vector ab
* @param {Vector | number} a: Vector or Number
* @param {Vector | number} b: Vector or Number
* @param {Vector | number} c: Vector or Number
* @param {AxisMap} axisMap: Mapped axis to get the right spherical coords
*/
static getRelativeSphericalCoords(a: Vector | XYZ, b: Vector | XYZ, c: Vector | XYZ, axisMap: AxisMap) {
if (!(a instanceof Vector)) {
a = new Vector(a);
b = new Vector(b);
c = new Vector(c);
}
// Calculate vector between points 1 and 2
const v1 = (b as Vector).subtract(a as Vector);
// Calculate vector between points 2 and 3
const v2 = (c as Vector).subtract(b as Vector);
const v1norm = v1.unit();
const v2norm = v2.unit();
const { theta: theta1, phi: phi1 } = v1norm.toSphericalCoords(axisMap);
const { theta: theta2, phi: phi2 } = v2norm.toSphericalCoords(axisMap);
const theta = theta1 - theta2;
const phi = phi1 - phi2;
return {
theta: Vector.normalizeAngle(theta),
phi: Vector.normalizeAngle(phi),
};
}
/**
* Get normalized, spherical coordinates for the vector bc
* @param {Vector | number} a: Vector or Number
* @param {Vector | number} b: Vector or Number
* @param {AxisMap} axisMap: Mapped axis to get the right spherical coords
*/
static getSphericalCoords(a: Vector | XYZ, b: Vector | XYZ, axisMap: AxisMap = { x: "x", y: "y", z: "z" }) {
if (!(a instanceof Vector)) {
a = new Vector(a);
b = new Vector(b);
}
// Calculate vector between points 1 and 2
const v1 = (b as Vector).subtract(a as Vector);
const v1norm = v1.unit();
const { theta, phi } = v1norm.toSphericalCoords(axisMap);
return {
theta: Vector.normalizeAngle(-theta),
phi: Vector.normalizeAngle(PI / 2 - phi),
};
}
} | the_stack |
/////////////////////////////
/// Worker Iterable APIs
/////////////////////////////
interface Cache {
addAll(requests: Iterable<RequestInfo>): Promise<void>;
}
interface DOMStringList {
[Symbol.iterator](): IterableIterator<string>;
}
interface FileList {
[Symbol.iterator](): IterableIterator<File>;
}
interface FontFaceSet extends Set<FontFace> {
}
interface FormData {
[Symbol.iterator](): IterableIterator<[string, FormDataEntryValue]>;
/**
* Returns an array of key, value pairs for every entry in the list.
*/
entries(): IterableIterator<[string, FormDataEntryValue]>;
/**
* Returns a list of keys in the list.
*/
keys(): IterableIterator<string>;
/**
* Returns a list of values in the list.
*/
values(): IterableIterator<FormDataEntryValue>;
}
interface Headers {
[Symbol.iterator](): IterableIterator<[string, string]>;
/**
* Returns an iterator allowing to go through all key/value pairs contained in this object.
*/
entries(): IterableIterator<[string, string]>;
/**
* Returns an iterator allowing to go through all keys of the key/value pairs contained in this object.
*/
keys(): IterableIterator<string>;
/**
* Returns an iterator allowing to go through all values of the key/value pairs contained in this object.
*/
values(): IterableIterator<string>;
}
interface IDBDatabase {
/**
* Returns a new transaction with the given mode ("readonly" or "readwrite") and scope which can be a single object store name or an array of names.
*/
transaction(storeNames: string | Iterable<string>, mode?: IDBTransactionMode): IDBTransaction;
}
interface IDBObjectStore {
/**
* Creates a new index in store with the given name, keyPath and options and returns a new IDBIndex. If the keyPath and options define constraints that cannot be satisfied with the data already in store the upgrade transaction will abort with a "ConstraintError" DOMException.
*
* Throws an "InvalidStateError" DOMException if not called within an upgrade transaction.
*/
createIndex(name: string, keyPath: string | Iterable<string>, options?: IDBIndexParameters): IDBIndex;
}
interface MessageEvent<T = any> {
/** @deprecated */
initMessageEvent(type: string, bubbles?: boolean, cancelable?: boolean, data?: any, origin?: string, lastEventId?: string, source?: MessageEventSource | null, ports?: Iterable<MessagePort>): void;
}
interface ReadableStream<R = any> {
[Symbol.iterator](): IterableIterator<any>;
entries(): IterableIterator<[number, any]>;
keys(): IterableIterator<number>;
values(): IterableIterator<any>;
}
interface SubtleCrypto {
deriveKey(algorithm: AlgorithmIdentifier | EcdhKeyDeriveParams | HkdfParams | Pbkdf2Params, baseKey: CryptoKey, derivedKeyType: AlgorithmIdentifier | AesDerivedKeyParams | HmacImportParams | HkdfParams | Pbkdf2Params, extractable: boolean, keyUsages: Iterable<KeyUsage>): Promise<CryptoKey>;
generateKey(algorithm: RsaHashedKeyGenParams | EcKeyGenParams, extractable: boolean, keyUsages: KeyUsage[]): Promise<CryptoKeyPair>;
generateKey(algorithm: AesKeyGenParams | HmacKeyGenParams | Pbkdf2Params, extractable: boolean, keyUsages: KeyUsage[]): Promise<CryptoKey>;
generateKey(algorithm: AlgorithmIdentifier, extractable: boolean, keyUsages: Iterable<KeyUsage>): Promise<CryptoKeyPair | CryptoKey>;
importKey(format: "jwk", keyData: JsonWebKey, algorithm: AlgorithmIdentifier | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | AesKeyAlgorithm, extractable: boolean, keyUsages: KeyUsage[]): Promise<CryptoKey>;
importKey(format: Exclude<KeyFormat, "jwk">, keyData: BufferSource, algorithm: AlgorithmIdentifier | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | AesKeyAlgorithm, extractable: boolean, keyUsages: Iterable<KeyUsage>): Promise<CryptoKey>;
unwrapKey(format: KeyFormat, wrappedKey: BufferSource, unwrappingKey: CryptoKey, unwrapAlgorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AesGcmParams, unwrappedKeyAlgorithm: AlgorithmIdentifier | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | AesKeyAlgorithm, extractable: boolean, keyUsages: Iterable<KeyUsage>): Promise<CryptoKey>;
}
interface URLSearchParams {
[Symbol.iterator](): IterableIterator<[string, string]>;
/**
* Returns an array of key, value pairs for every entry in the search params.
*/
entries(): IterableIterator<[string, string]>;
/**
* Returns a list of keys in the search params.
*/
keys(): IterableIterator<string>;
/**
* Returns a list of values in the search params.
*/
values(): IterableIterator<string>;
}
interface WEBGL_draw_buffers {
drawBuffersWEBGL(buffers: Iterable<GLenum>): void;
}
interface WebGL2RenderingContextBase {
clearBufferfv(buffer: GLenum, drawbuffer: GLint, values: Iterable<GLfloat>, srcOffset?: GLuint): void;
clearBufferiv(buffer: GLenum, drawbuffer: GLint, values: Iterable<GLint>, srcOffset?: GLuint): void;
clearBufferuiv(buffer: GLenum, drawbuffer: GLint, values: Iterable<GLuint>, srcOffset?: GLuint): void;
drawBuffers(buffers: Iterable<GLenum>): void;
getActiveUniforms(program: WebGLProgram, uniformIndices: Iterable<GLuint>, pname: GLenum): any;
getUniformIndices(program: WebGLProgram, uniformNames: Iterable<string>): Iterable<GLuint> | null;
invalidateFramebuffer(target: GLenum, attachments: Iterable<GLenum>): void;
invalidateSubFramebuffer(target: GLenum, attachments: Iterable<GLenum>, x: GLint, y: GLint, width: GLsizei, height: GLsizei): void;
transformFeedbackVaryings(program: WebGLProgram, varyings: Iterable<string>, bufferMode: GLenum): void;
uniform1uiv(location: WebGLUniformLocation | null, data: Iterable<GLuint>, srcOffset?: GLuint, srcLength?: GLuint): void;
uniform2uiv(location: WebGLUniformLocation | null, data: Iterable<GLuint>, srcOffset?: GLuint, srcLength?: GLuint): void;
uniform3uiv(location: WebGLUniformLocation | null, data: Iterable<GLuint>, srcOffset?: GLuint, srcLength?: GLuint): void;
uniform4uiv(location: WebGLUniformLocation | null, data: Iterable<GLuint>, srcOffset?: GLuint, srcLength?: GLuint): void;
uniformMatrix2x3fv(location: WebGLUniformLocation | null, transpose: GLboolean, data: Iterable<GLfloat>, srcOffset?: GLuint, srcLength?: GLuint): void;
uniformMatrix2x4fv(location: WebGLUniformLocation | null, transpose: GLboolean, data: Iterable<GLfloat>, srcOffset?: GLuint, srcLength?: GLuint): void;
uniformMatrix3x2fv(location: WebGLUniformLocation | null, transpose: GLboolean, data: Iterable<GLfloat>, srcOffset?: GLuint, srcLength?: GLuint): void;
uniformMatrix3x4fv(location: WebGLUniformLocation | null, transpose: GLboolean, data: Iterable<GLfloat>, srcOffset?: GLuint, srcLength?: GLuint): void;
uniformMatrix4x2fv(location: WebGLUniformLocation | null, transpose: GLboolean, data: Iterable<GLfloat>, srcOffset?: GLuint, srcLength?: GLuint): void;
uniformMatrix4x3fv(location: WebGLUniformLocation | null, transpose: GLboolean, data: Iterable<GLfloat>, srcOffset?: GLuint, srcLength?: GLuint): void;
vertexAttribI4iv(index: GLuint, values: Iterable<GLint>): void;
vertexAttribI4uiv(index: GLuint, values: Iterable<GLuint>): void;
}
interface WebGL2RenderingContextOverloads {
uniform1fv(location: WebGLUniformLocation | null, data: Iterable<GLfloat>, srcOffset?: GLuint, srcLength?: GLuint): void;
uniform1iv(location: WebGLUniformLocation | null, data: Iterable<GLint>, srcOffset?: GLuint, srcLength?: GLuint): void;
uniform2fv(location: WebGLUniformLocation | null, data: Iterable<GLfloat>, srcOffset?: GLuint, srcLength?: GLuint): void;
uniform2iv(location: WebGLUniformLocation | null, data: Iterable<GLint>, srcOffset?: GLuint, srcLength?: GLuint): void;
uniform3fv(location: WebGLUniformLocation | null, data: Iterable<GLfloat>, srcOffset?: GLuint, srcLength?: GLuint): void;
uniform3iv(location: WebGLUniformLocation | null, data: Iterable<GLint>, srcOffset?: GLuint, srcLength?: GLuint): void;
uniform4fv(location: WebGLUniformLocation | null, data: Iterable<GLfloat>, srcOffset?: GLuint, srcLength?: GLuint): void;
uniform4iv(location: WebGLUniformLocation | null, data: Iterable<GLint>, srcOffset?: GLuint, srcLength?: GLuint): void;
uniformMatrix2fv(location: WebGLUniformLocation | null, transpose: GLboolean, data: Iterable<GLfloat>, srcOffset?: GLuint, srcLength?: GLuint): void;
uniformMatrix3fv(location: WebGLUniformLocation | null, transpose: GLboolean, data: Iterable<GLfloat>, srcOffset?: GLuint, srcLength?: GLuint): void;
uniformMatrix4fv(location: WebGLUniformLocation | null, transpose: GLboolean, data: Iterable<GLfloat>, srcOffset?: GLuint, srcLength?: GLuint): void;
}
interface WebGLRenderingContextBase {
vertexAttrib1fv(index: GLuint, values: Iterable<GLfloat>): void;
vertexAttrib2fv(index: GLuint, values: Iterable<GLfloat>): void;
vertexAttrib3fv(index: GLuint, values: Iterable<GLfloat>): void;
vertexAttrib4fv(index: GLuint, values: Iterable<GLfloat>): void;
}
interface WebGLRenderingContextOverloads {
uniform1fv(location: WebGLUniformLocation | null, v: Iterable<GLfloat>): void;
uniform1iv(location: WebGLUniformLocation | null, v: Iterable<GLint>): void;
uniform2fv(location: WebGLUniformLocation | null, v: Iterable<GLfloat>): void;
uniform2iv(location: WebGLUniformLocation | null, v: Iterable<GLint>): void;
uniform3fv(location: WebGLUniformLocation | null, v: Iterable<GLfloat>): void;
uniform3iv(location: WebGLUniformLocation | null, v: Iterable<GLint>): void;
uniform4fv(location: WebGLUniformLocation | null, v: Iterable<GLfloat>): void;
uniform4iv(location: WebGLUniformLocation | null, v: Iterable<GLint>): void;
uniformMatrix2fv(location: WebGLUniformLocation | null, transpose: GLboolean, value: Iterable<GLfloat>): void;
uniformMatrix3fv(location: WebGLUniformLocation | null, transpose: GLboolean, value: Iterable<GLfloat>): void;
uniformMatrix4fv(location: WebGLUniformLocation | null, transpose: GLboolean, value: Iterable<GLfloat>): void;
} | the_stack |
const serverRequire = require;
let THREE: typeof SupEngine.THREE;
// NOTE: It is important that we require THREE through SupEngine
// so that we inherit any settings, like the global Euler order
// (or, alternatively, we could duplicate those settings...)
if ((<any>global).window == null) THREE = serverRequire("../../../../SupEngine").THREE;
else if ((<any>window).SupEngine != null) THREE = SupEngine.THREE;
import * as path from "path";
import * as fs from "fs";
import * as async from "async";
import * as _ from "lodash";
import CubicModelNodes, { XYZ, Node, Shape, getShapeTextureSize, getShapeTextureFaceSize } from "./CubicModelNodes";
type AddNodeCallback = SupCore.Data.Base.ErrorCallback & ((err: string, nodeId: string, node: Node, parentId: string, index: number) => void);
type SetNodePropertyCallback = SupCore.Data.Base.ErrorCallback & ((err: string, ack: any, id: string, path: string, value: any) => void);
type MoveNodePivotCallback = SupCore.Data.Base.ErrorCallback & ((err: string, ack: any, id: string, value: { x: number; y: number; z: number; }) => void);
type MoveNodeCallback = SupCore.Data.Base.ErrorCallback & ((err: string, ack: any, id: string, parentId: string, index: number) => void);
type DuplicateNodeCallback = SupCore.Data.Base.ErrorCallback & ((err: string, nodeId: string, rootNode: Node, newNodes: DuplicatedNode[]) => void);
type RemoveNodeCallback = SupCore.Data.Base.ErrorCallback & ((err: string, ack: any, id: string) => void);
type MoveNodeTextureOffsetCallback = SupCore.Data.Base.ErrorCallback & ((err: string, ack: any, nodeIds: string[], offset: { x: number; y: number }) => void);
type ChangeTextureWidthCallback = SupCore.Data.Base.ErrorCallback & ((err: string, ack: any, newWidth: number) => void);
type ChangeTextureHeightCallback = SupCore.Data.Base.ErrorCallback & ((err: string, ack: any, newHeight: number) => void);
type EditTextureCallback = SupCore.Data.Base.ErrorCallback & ((err: string, ack: any, name: string, edits: TextureEdit[]) => void);
export interface CubicModelAssetPub {
pixelsPerUnit: number;
nodes: Node[];
textureWidth: number;
textureHeight: number;
textures?: { [name: string]: THREE.Texture; };
maps: { [name: string]: ArrayBuffer; };
mapSlots: { [name: string]: string; };
}
export interface DuplicatedNode {
node: Node;
parentId: string;
index: number;
}
export interface TextureEdit {
x: number; y: number;
value: { r: number; g: number; b: number; a: number; };
}
export default class CubicModelAsset extends SupCore.Data.Base.Asset {
static schema: SupCore.Data.Schema = {
pixelsPerUnit: { type: "integer", min: 1, mutable: true },
nodes: { type: "array" },
textureWidth: { type: "number" },
textureHeight: { type: "number" },
maps: { type: "hash", values: { type: "buffer?" } },
mapSlots: {
type: "hash",
properties: {
map: { type: "string?", mutable: true },
light: { type: "string?", mutable: true },
specular: { type: "string?", mutable: true },
alpha: { type: "string?", mutable: true },
normal: { type: "string?", mutable: true }
}
}
};
static validTextureSizes = [32, 64, 128, 256, 512, 1024, 2048];
pub: CubicModelAssetPub;
nodes: CubicModelNodes;
textureDatas: { [name: string]: Uint8ClampedArray; };
// Only used on client-side
clientTextureDatas: { [name: string]: { imageData: ImageData; ctx: CanvasRenderingContext2D; } } = {};
constructor(id: string, pub: any, server: ProjectServer) {
super(id, pub, CubicModelAsset.schema, server);
}
init(options: any, callback: Function) {
this.server.data.resources.acquire("cubicModelSettings", null, (err: Error, cubicModelSettings: any) => {
this.server.data.resources.release("cubicModelSettings", null);
const pixelsPerUnit: number = cubicModelSettings.pub.pixelsPerUnit;
const initialTextureSize = 256;
this.pub = {
pixelsPerUnit,
nodes: [],
textureWidth: initialTextureSize,
textureHeight: initialTextureSize,
maps: { map: new ArrayBuffer(initialTextureSize * initialTextureSize * 4) },
mapSlots: {
map: "map",
light: null,
specular: null,
alpha: null,
normal: null
}
};
const data = new Uint8ClampedArray(this.pub.maps["map"]);
for (let i = 0; i < data.length; i++) data[i] = 255;
super.init(options, callback);
});
}
setup() {
this.nodes = new CubicModelNodes(this);
this.textureDatas = {};
for (const mapName in this.pub.maps) {
this.textureDatas[mapName] = new Uint8ClampedArray(this.pub.maps[mapName]);
}
}
load(assetPath: string) {
fs.readFile(path.join(assetPath, "cubicModel.json"), { encoding: "utf8" }, (err, json) => {
const pub: CubicModelAssetPub = JSON.parse(json);
const mapNames = (pub as any).maps as string[];
pub.maps = {};
async.each(mapNames, (mapName, cb) => {
// TODO: Replace this with a PNG disk format
fs.readFile(path.join(assetPath, `map-${mapName}.dat`), (err, data) => {
if (err) { cb(err); return; }
pub.maps[mapName] = new Uint8ClampedArray(data).buffer;
cb();
});
}, (err) => {
if (err) throw err;
this._onLoaded(assetPath, pub);
});
});
}
client_load() { this.loadTextures(); }
client_unload() { this.unloadTextures(); }
save(outputPath: string, callback: (err: Error) => void) {
this.write(fs.writeFile, outputPath, (err) => {
if (err != null) { callback(err); return; }
// Clean up old maps from disk
async.each(Object.keys(this.pub.maps), (mapName, cb) => {
if (this.pub.maps[mapName] != null) { cb(); return; }
fs.unlink(path.join(outputPath, `map-${mapName}.dat`), (err) => {
if (err != null && err.code !== "ENOENT") { cb(err); return; }
cb();
});
}, callback);
});
}
clientExport(outputPath: string, callback: (err: Error) => void) {
this.write(SupApp.writeFile, outputPath, callback);
}
private write(writeFile: Function, outputPath: string, writeCallback: (err: Error) => void) {
const maps = this.pub.maps;
(this.pub as any).maps = [];
for (const key in maps) {
if (maps[key] != null) (this.pub as any).maps.push(key);
}
const textures = this.pub.textures;
delete this.pub.textures;
const json = JSON.stringify(this.pub, null, 2);
this.pub.maps = maps;
this.pub.textures = textures;
writeFile(path.join(outputPath, "cubicModel.json"), json, { encoding: "utf8" }, (err: Error) => {
if (err != null) { writeCallback(err); return; }
async.each(Object.keys(maps), (mapName, cb) => {
const value = maps[mapName];
if (value == null) { cb(); return; }
writeFile(path.join(outputPath, `map-${mapName}.dat`), new Buffer(value), cb);
}, writeCallback);
});
}
private unloadTextures() {
for (const textureName in this.pub.textures) this.pub.textures[textureName].dispose();
}
private loadTextures() {
this.unloadTextures();
this.pub.textures = {};
this.clientTextureDatas = {};
// Texturing
// NOTE: This is the unoptimized variant for editing
// There should be an option you can pass to setModel to ask for editable version vs (default) optimized
for (const mapName in this.pub.maps) {
const canvas = document.createElement("canvas");
canvas.width = this.pub.textureWidth;
canvas.height = this.pub.textureHeight;
const ctx = canvas.getContext("2d");
const texture = this.pub.textures[mapName] = new THREE.Texture(canvas);
texture.needsUpdate = true;
texture.magFilter = THREE.NearestFilter;
texture.minFilter = THREE.NearestFilter;
const imageData = new ImageData(this.textureDatas[mapName], this.pub.textureWidth, this.pub.textureHeight);
ctx.putImageData(imageData, 0, 0);
this.clientTextureDatas[mapName] = { imageData, ctx };
}
}
// Nodes
server_addNode(client: SupCore.RemoteClient, name: string, options: any, callback: AddNodeCallback) {
const parentId = (options != null) ? options.parentId : null;
const node: Node = {
id: null, name: name, children: [],
position: (options != null && options.transform != null && options.transform.position != null) ? options.transform.position : { x: 0, y: 0, z: 0 },
orientation: (options != null && options.transform != null && options.transform.orientation != null) ? options.transform.orientation : { x: 0, y: 0, z: 0, w: 1 },
shape: (options != null && options.shape != null) ? options.shape : { type: "none", offset: { x: 0, y: 0, z: 0 }, textureOffset: {}, settings: null }
};
node.shape.textureLayoutCustom = false;
if (node.shape.type !== "none") {
const origin = { x: 0, y: 0 };
let placed = false;
const size = getShapeTextureSize(node.shape);
for (let j = 0; j < this.pub.textureHeight - size.height; j++) {
for (let i = 0; i < this.pub.textureWidth; i++) {
let pushed: boolean;
do {
pushed = false;
for (const otherNodeId in this.nodes.byId) {
const otherNode = this.nodes.byId[otherNodeId];
if (otherNode.shape.type === "none") continue;
// + 1 and - 1 because we need a one-pixel border
// to avoid filtering issues
for (const faceName in otherNode.shape.textureLayout) {
const faceOffset = otherNode.shape.textureLayout[faceName].offset;
const otherSize = getShapeTextureFaceSize(otherNode.shape, faceName);
if ((i + size.width >= faceOffset.x - 1) && (j + size.height >= faceOffset.y - 1) &&
(i <= faceOffset.x + otherSize.width + 1) && (j <= faceOffset.y + otherSize.height + 1)) {
i = faceOffset.x + otherSize.width + 2;
pushed = true;
break;
}
}
if (pushed) break;
}
} while (pushed);
if (i < this.pub.textureWidth && i + size.width < this.pub.textureWidth) {
origin.x = i;
origin.y = j;
placed = true;
break;
}
}
if (placed) break;
}
if (!placed)
console.log("Could not find any room for the node's texture. Texture needs to be expanded and all blocks should be re-laid out from bigger to smaller!");
switch (node.shape.type) {
case "box":
const size = node.shape.settings.size as { x: number; y: number; z: number; };
node.shape.textureLayout = {
"top": {
offset: { x: origin.x + size.z, y: origin.y },
mirror: { x: false, y: false },
angle: 0
},
"bottom": {
offset: { x: origin.x + size.z + size.x, y: origin.y },
mirror: { x: false, y: false },
angle: 0
},
"front": {
offset: { x: origin.x + size.z, y: origin.y + size.z },
mirror: { x: false, y: false },
angle: 0
},
"back": {
offset: { x: origin.x + 2 * size.z + size.x, y: origin.y + size.z },
mirror: { x: false, y: false },
angle: 0
},
"left": {
offset: { x: origin.x, y: origin.y + size.z },
mirror: { x: false, y: false },
angle: 0
},
"right": {
offset: { x: origin.x + size.z + size.x, y: origin.y + size.z },
mirror: { x: false, y: false },
angle: 0
}
};
break;
case "none":
node.shape.textureLayout = {};
break;
}
}
const index = (options != null) ? options.index : null;
this.nodes.add(node, parentId, index, (err, actualIndex) => {
if (err != null) { callback(err); return; }
callback(null, node.id, node, parentId, actualIndex);
this.emit("change");
});
}
client_addNode(node: Node, parentId: string, index: number) {
this.nodes.client_add(node, parentId, index);
}
server_setNodeProperty(client: SupCore.RemoteClient, id: string, path: string, value: any, callback: SetNodePropertyCallback) {
const oldSize = this.nodes.byId[id].shape.settings.size;
this.nodes.setProperty(id, path, value, (err, actualValue) => {
if (err != null) { callback(err); return; }
if (path === "shape.settings.size") this._updateNodeUvFromSize(oldSize, this.nodes.byId[id].shape);
callback(null, null, id, path, actualValue);
this.emit("change");
});
}
client_setNodeProperty(id: string, path: string, value: any) {
const oldSize = this.nodes.byId[id].shape.settings.size;
this.nodes.client_setProperty(id, path, value);
if (path === "shape.settings.size") this._updateNodeUvFromSize(oldSize, this.nodes.byId[id].shape);
}
_updateNodeUvFromSize(oldSize: XYZ, shape: Shape) {
if (shape.textureLayoutCustom) return;
switch (shape.type) {
case "box":
const newSize: XYZ = shape.settings.size;
const x = newSize.x - oldSize.x;
const z = newSize.z - oldSize.z;
shape.textureLayout["top"].offset.x += z;
shape.textureLayout["bottom"].offset.x += x + z;
shape.textureLayout["front"].offset.x += z;
shape.textureLayout["right"].offset.x += x + z;
shape.textureLayout["back"].offset.x += x + 2 * z;
shape.textureLayout["front"].offset.y += z;
shape.textureLayout["back"].offset.y += z;
shape.textureLayout["left"].offset.y += z;
shape.textureLayout["right"].offset.y += z;
break;
}
}
server_moveNodePivot(client: SupCore.RemoteClient, id: string, value: { x: number; y: number; z: number; }, callback: MoveNodePivotCallback) {
const node = this.nodes.byId[id];
const oldMatrix = (node != null) ? this.computeGlobalMatrix(node) : null;
this.nodes.setProperty(id, "position", value, (err, actualValue) => {
if (err != null) { callback(err); return; }
const newInverseMatrix = this.computeGlobalMatrix(node);
newInverseMatrix.getInverse(newInverseMatrix);
const offset = new THREE.Vector3(node.shape.offset.x, node.shape.offset.y, node.shape.offset.z);
offset.applyMatrix4(oldMatrix).applyMatrix4(newInverseMatrix);
node.shape.offset.x = offset.x;
node.shape.offset.y = offset.y;
node.shape.offset.z = offset.z;
callback(null, null, id, actualValue);
this.emit("change");
});
}
client_moveNodePivot(id: string, value: { x: number; y: number; z: number; }) {
const node = this.nodes.byId[id];
const oldMatrix = (node != null) ? this.computeGlobalMatrix(node) : null;
this.nodes.client_setProperty(id, "position", value);
const newInverseMatrix = this.computeGlobalMatrix(node);
newInverseMatrix.getInverse(newInverseMatrix);
const offset = new THREE.Vector3(node.shape.offset.x, node.shape.offset.y, node.shape.offset.z);
offset.applyMatrix4(oldMatrix).applyMatrix4(newInverseMatrix);
node.shape.offset.x = offset.x;
node.shape.offset.y = offset.y;
node.shape.offset.z = offset.z;
}
server_moveNode(client: SupCore.RemoteClient, id: string, parentId: string, index: number, callback: MoveNodeCallback) {
const node = this.nodes.byId[id];
if (node == null) { callback(`Invalid node id: ${id}`); return; }
const globalMatrix = this.computeGlobalMatrix(node);
this.nodes.move(id, parentId, index, (err, actualIndex) => {
if (err != null) { callback(err); return; }
this.applyGlobalMatrix(node, globalMatrix);
callback(null, null, id, parentId, actualIndex);
this.emit("change");
});
}
computeGlobalMatrix(node: Node, includeShapeOffset = false) {
const defaultScale = new THREE.Vector3(1, 1, 1);
const matrix = new THREE.Matrix4().compose(<THREE.Vector3>node.position, <THREE.Quaternion>node.orientation, defaultScale);
let parentNode = this.nodes.parentNodesById[node.id];
const parentMatrix = new THREE.Matrix4();
const parentPosition = new THREE.Vector3();
const parentOffset = new THREE.Vector3();
while (parentNode != null) {
parentPosition.set(parentNode.position.x, parentNode.position.y, parentNode.position.z);
parentOffset.set(parentNode.shape.offset.x, parentNode.shape.offset.y, parentNode.shape.offset.z);
parentOffset.applyQuaternion(<THREE.Quaternion>parentNode.orientation);
parentPosition.add(parentOffset);
parentMatrix.identity().compose(parentPosition, <THREE.Quaternion>parentNode.orientation, defaultScale);
matrix.multiplyMatrices(parentMatrix, matrix);
parentNode = this.nodes.parentNodesById[parentNode.id];
}
return matrix;
}
applyGlobalMatrix(node: Node, matrix: THREE.Matrix4) {
const parentGlobalMatrix = new THREE.Matrix4();
let parentNode = this.nodes.parentNodesById[node.id];
const parentMatrix = new THREE.Matrix4();
const defaultScale = new THREE.Vector3(1, 1, 1);
const parentPosition = new THREE.Vector3();
const parentOffset = new THREE.Vector3();
while (parentNode != null) {
parentPosition.set(parentNode.position.x, parentNode.position.y, parentNode.position.z);
parentOffset.set(parentNode.shape.offset.x, parentNode.shape.offset.y, parentNode.shape.offset.z);
parentOffset.applyQuaternion(<THREE.Quaternion>parentNode.orientation);
parentPosition.add(parentOffset);
parentMatrix.identity().compose(parentPosition, <THREE.Quaternion>parentNode.orientation, defaultScale);
parentGlobalMatrix.multiplyMatrices(parentMatrix, parentGlobalMatrix);
parentNode = this.nodes.parentNodesById[parentNode.id];
}
matrix.multiplyMatrices(parentGlobalMatrix.getInverse(parentGlobalMatrix), matrix);
const position = new THREE.Vector3();
const orientation = new THREE.Quaternion();
matrix.decompose(position, orientation, defaultScale);
node.position.x = position.x;
node.position.y = position.y;
node.position.z = position.z;
node.orientation.x = orientation.x;
node.orientation.y = orientation.y;
node.orientation.z = orientation.z;
node.orientation.w = orientation.w;
}
client_moveNode(id: string, parentId: string, index: number) {
const node = this.nodes.byId[id];
const globalMatrix = this.computeGlobalMatrix(node);
this.nodes.client_move(id, parentId, index);
this.applyGlobalMatrix(node, globalMatrix);
}
server_duplicateNode(client: SupCore.RemoteClient, newName: string, id: string, index: number, callback: DuplicateNodeCallback) {
const referenceNode = this.nodes.byId[id];
if (referenceNode == null) { callback(`Invalid node id: ${id}`); return; }
const newNodes: DuplicatedNode[] = [];
let totalNodeCount = 0;
const walk = (node: Node) => {
totalNodeCount += 1;
for (const childNode of node.children) walk(childNode);
};
walk(referenceNode);
const rootNode: Node = {
id: null, name: newName, children: [],
position: _.cloneDeep(referenceNode.position),
orientation: _.cloneDeep(referenceNode.orientation),
shape: _.cloneDeep(referenceNode.shape)
};
const parentId = (this.nodes.parentNodesById[id] != null) ? this.nodes.parentNodesById[id].id : null;
const addNode = (newNode: Node, parentId: string, index: number, children: Node[]) => {
this.nodes.add(newNode, parentId, index, (err, actualIndex) => {
if (err != null) { callback(err); return; }
// TODO: Copy shape
newNodes.push({ node: newNode, parentId, index: actualIndex });
if (newNodes.length === totalNodeCount) {
callback(null, rootNode.id, rootNode, newNodes);
this.emit("change");
}
for (let childIndex = 0; childIndex < children.length; childIndex++) {
const childNode = children[childIndex];
const node: Node = {
id: null, name: childNode.name, children: [],
position: _.cloneDeep(childNode.position),
orientation: _.cloneDeep(childNode.orientation),
shape: _.cloneDeep(childNode.shape)
};
addNode(node, newNode.id, childIndex, childNode.children);
}
});
};
addNode(rootNode, parentId, index, referenceNode.children);
}
client_duplicateNode(rootNode: Node, newNodes: DuplicatedNode[]) {
for (const newNode of newNodes) {
newNode.node.children.length = 0;
this.nodes.client_add(newNode.node, newNode.parentId, newNode.index);
}
}
server_removeNode(client: SupCore.RemoteClient, id: string, callback: RemoveNodeCallback) {
this.nodes.remove(id, (err) => {
if (err != null) { callback(err); return; }
callback(null, null, id);
this.emit("change");
});
}
client_removeNode(id: string) {
this.nodes.client_remove(id);
}
server_moveNodeTextureOffset(client: SupCore.RemoteClient, nodeIds: string[], offset: { x: number; y: number }, callback: MoveNodeTextureOffsetCallback) {
// TODO: add checks
this.client_moveNodeTextureOffset(nodeIds, offset);
callback(null, null, nodeIds, offset);
this.emit("change");
}
client_moveNodeTextureOffset(nodeIds: string[], offset: { x: number; y: number }) {
for (const id of nodeIds) {
const node = this.nodes.byId[id];
for (const faceName in node.shape.textureLayout) {
const faceOffset = node.shape.textureLayout[faceName].offset;
faceOffset.x += offset.x;
faceOffset.y += offset.y;
}
}
}
// Texture
server_changeTextureWidth(client: SupCore.RemoteClient, newWidth: number, callback: ChangeTextureWidthCallback) {
if (CubicModelAsset.validTextureSizes.indexOf(newWidth) === -1) { callback(`Invalid new texture width: ${newWidth}`); return; }
this._changeTextureWidth(newWidth);
callback(null, null, newWidth);
this.emit("change");
}
client_changeTextureWidth(newWidth: number) {
this._changeTextureWidth(newWidth);
this.loadTextures();
}
_changeTextureWidth(newWidth: number) {
for (const mapName in this.pub.maps) {
const oldMapData = this.textureDatas[mapName];
const newMapBuffer = new ArrayBuffer(newWidth * this.pub.textureHeight * 4);
const newMapData = new Uint8ClampedArray(newMapBuffer);
for (let y = 0; y < this.pub.textureHeight; y++) {
let x = 0;
while (x < Math.max(this.pub.textureWidth, newWidth)) {
const oldIndex = (y * this.pub.textureWidth + x) * 4;
const newIndex = (y * newWidth + x) * 4;
for (let i = 0; i < 4; i++) {
const value = x >= this.pub.textureWidth ? 255 : oldMapData[oldIndex + i];
newMapData[newIndex + i] = value;
}
x++;
}
}
this.pub.maps[mapName] = newMapBuffer;
this.textureDatas[mapName] = newMapData;
}
this.pub.textureWidth = newWidth;
}
server_changeTextureHeight(client: SupCore.RemoteClient, newHeight: number, callback: ChangeTextureHeightCallback) {
if (CubicModelAsset.validTextureSizes.indexOf(newHeight) === -1) { callback(`Invalid new texture height: ${newHeight}`); return; }
this._changeTextureHeight(newHeight);
callback(null, null, newHeight);
this.emit("change");
}
client_changeTextureHeight(newHeight: number) {
this._changeTextureHeight(newHeight);
this.loadTextures();
}
_changeTextureHeight(newHeight: number) {
for (const mapName in this.pub.maps) {
const oldMapData = this.textureDatas[mapName];
const newMapBuffer = new ArrayBuffer(this.pub.textureWidth * newHeight * 4);
const newMapData = new Uint8ClampedArray(newMapBuffer);
for (let y = 0; y < Math.max(this.pub.textureHeight, newHeight); y++) {
for (let x = 0; x < this.pub.textureWidth; x++) {
let index = (y * this.pub.textureWidth + x) * 4;
for (let i = 0; i < 4; i++) {
let value = y >= this.pub.textureHeight ? 255 : oldMapData[index + i];
newMapData[index + i] = value;
}
}
}
this.pub.maps[mapName] = newMapBuffer;
this.textureDatas[mapName] = newMapData;
}
this.pub.textureHeight = newHeight;
}
server_editTexture(client: SupCore.RemoteClient, name: string, edits: TextureEdit[], callback: EditTextureCallback) {
if (this.pub.maps[name] == null) { callback(`Invalid map name: ${name}`); return; }
for (const edit of edits) {
if (edit.x == null || edit.x < 0 || edit.x >= this.pub.textureWidth) { callback(`Invalid edit x: ${edit.x}`); return; }
if (edit.y == null || edit.y < 0 || edit.y >= this.pub.textureHeight) { callback(`Invalid edit y: ${edit.y}`); return; }
if (edit.value.r == null || edit.value.r < 0 || edit.value.r > 255) { callback(`Invalid edit value r: ${edit.value.r}`); return; }
if (edit.value.g == null || edit.value.g < 0 || edit.value.g > 255) { callback(`Invalid edit value g: ${edit.value.g}`); return; }
if (edit.value.b == null || edit.value.b < 0 || edit.value.b > 255) { callback(`Invalid edit value b: ${edit.value.b}`); return; }
if (edit.value.a == null || edit.value.a < 0 || edit.value.a > 255) { callback(`Invalid edit value a: ${edit.value.a}`); return; }
}
this._editTextureData(name, edits);
callback(null, null, name, edits);
this.emit("change");
}
client_editTexture(name: string, edits: TextureEdit[]) {
this._editTextureData(name, edits);
const imageData = this.clientTextureDatas[name].imageData;
this.clientTextureDatas[name].ctx.putImageData(imageData, 0, 0);
this.pub.textures[name].needsUpdate = true;
}
_editTextureData(name: string, edits: TextureEdit[]) {
const array = this.textureDatas[name];
for (const edit of edits) {
const index = (edit.y * this.pub.textureWidth + edit.x) * 4;
array[index + 0] = edit.value.r;
array[index + 1] = edit.value.g;
array[index + 2] = edit.value.b;
array[index + 3] = edit.value.a;
}
}
} | the_stack |
import { Col, Row, Form, Input, Button } from 'antd'
import React, { useEffect, useRef } from 'react'
import './Signup.scss'
import { Link } from 'lib/components/Link'
import { SocialLoginButtons } from 'lib/components/SocialLoginButton'
import { PasswordInput } from './PasswordInput'
import { useActions, useValues } from 'kea'
import { preflightLogic } from 'scenes/PreflightCheck/logic'
import { signupLogic } from './signupLogic'
import { Rule } from 'rc-field-form/lib/interface'
import { ExclamationCircleFilled } from '@ant-design/icons'
import { userLogic } from '../userLogic'
import { WelcomeLogo } from './WelcomeLogo'
import hedgehogMain from 'public/hedgehog-bridge-page.png'
import { ErrorMessage } from 'lib/components/ErrorMessage/ErrorMessage'
import { SceneExport } from 'scenes/sceneTypes'
export const scene: SceneExport = {
component: Signup,
logic: signupLogic,
}
const UTM_TAGS = 'utm_campaign=in-product&utm_tag=signup-header'
const requiredRule = (message: string): Rule[] | undefined => {
return [
{
required: true,
message: (
<>
<ExclamationCircleFilled style={{ marginLeft: 4 }} /> {message}
</>
),
},
]
}
export function Signup(): JSX.Element | null {
const [form] = Form.useForm()
const { preflight } = useValues(preflightLogic)
const { user } = useValues(userLogic)
const { signupResponse, signupResponseLoading, initialEmail, formSubmitted } = useValues(signupLogic)
const { signup, setFormSubmitted } = useActions(signupLogic)
const emailInputRef = useRef<Input | null>(null)
const passwordInputRef = useRef<Input | null>(null)
useEffect(() => {
if (initialEmail) {
passwordInputRef?.current?.focus()
} else {
emailInputRef?.current?.focus()
}
}, [initialEmail])
const handleFormSubmit = async (values: Record<string, string>): Promise<void> => {
setFormSubmitted(true)
if (await form.validateFields(['email', 'password', 'first_name', 'organization_name'])) {
signup(values)
}
}
const footerHighlights = {
cloud: ['Hosted & managed by PostHog', 'Pay per event, cancel anytime', 'Community, Slack & email support'],
selfHosted: [
'Fully featured product, unlimited events',
'Data in your own infrastructure',
'Community, Slack & email support',
],
}
return !user ? (
<div className="bridge-page signup">
<Row>
<Col span={24} className="auth-main-content">
<img src={hedgehogMain} alt="" className="main-art" />
<div className="inner-wrapper">
<WelcomeLogo view="signup" />
<div className="inner">
<h2 className="subtitle" style={{ justifyContent: 'center' }}>
Get started
</h2>
{(preflight?.cloud || preflight?.initiated) && ( // For now, if you're not on Cloud, you wouldn't see
// this page, but future-proofing this (with `preflight.initiated`) in case this changes.
<div className="text-center" style={{ marginBottom: 32 }}>
Already have an account?{' '}
<Link to="/login" data-attr="signup-login-link">
Log in
</Link>
</div>
)}
{!signupResponseLoading &&
signupResponse?.errorCode &&
!['email', 'password'].includes(signupResponse?.errorAttribute || '') && (
<ErrorMessage style={{ marginBottom: 16 }}>
{signupResponse?.errorDetail ||
'Could not complete your signup. Please try again.'}
</ErrorMessage>
)}
<Form
layout="vertical"
form={form}
onFinish={handleFormSubmit}
requiredMark={false}
initialValues={{ email: initialEmail }}
noValidate
>
<Form.Item
name="email"
label="Email"
rules={
formSubmitted
? [
...(requiredRule('Please enter your email to continue') || []),
{
type: 'email',
message: (
<>
<ExclamationCircleFilled style={{ marginLeft: 4 }} />{' '}
Please enter a valid email
</>
),
},
]
: undefined
}
validateStatus={signupResponse?.errorAttribute === 'email' ? 'error' : undefined}
help={
signupResponse?.errorAttribute === 'email'
? signupResponse.errorDetail
: undefined
}
>
<Input
className="ph-ignore-input"
autoFocus
data-attr="signup-email"
placeholder="email@yourcompany.com"
type="email"
ref={emailInputRef}
disabled={signupResponseLoading}
/>
</Form.Item>
<PasswordInput
ref={passwordInputRef}
showStrengthIndicator
validateStatus={signupResponse?.errorAttribute === 'password' ? 'error' : undefined}
help={
signupResponse?.errorAttribute === 'password' ? (
signupResponse.errorDetail
) : (
<span style={{ paddingBottom: 16 }}>
<ExclamationCircleFilled style={{ marginRight: 4 }} />
Passwords must be at least 8 characters
</span>
)
}
validateMinLength
validationDisabled={!formSubmitted}
disabled={signupResponseLoading}
/>
<Form.Item
name="first_name"
label="Your full name"
rules={formSubmitted ? requiredRule('Please enter your first name') : undefined}
>
<Input
className="ph-ignore-input"
autoFocus
data-attr="signup-first-name"
placeholder="Jane Doe"
disabled={signupResponseLoading}
/>
</Form.Item>
<Form.Item
name="organization_name"
label="Organization name"
rules={
formSubmitted
? requiredRule('Please enter the name of your organization')
: undefined
}
>
<Input
className="ph-ignore-input"
data-attr="signup-organization-name"
placeholder="Hogflix Movies"
disabled={signupResponseLoading}
/>
</Form.Item>
<Form.Item className="text-center" style={{ marginTop: 32 }}>
By creating an account, you agree to our{' '}
<a href={`https://posthog.com/terms?${UTM_TAGS}`} target="_blank" rel="noopener">
Terms of Service
</a>{' '}
and{' '}
<a href={`https://posthog.com/privacy?${UTM_TAGS}`} target="_blank" rel="noopener">
Privacy Policy
</a>
.
</Form.Item>
<Form.Item>
<Button
className="btn-bridge"
htmlType="submit"
data-attr="signup-submit"
block
loading={signupResponseLoading}
>
Create account
</Button>
</Form.Item>
</Form>
<div>
<SocialLoginButtons caption="Or sign up with" />
</div>
</div>
</div>
</Col>
</Row>
<footer>
<div className="footer-inner">
{footerHighlights[preflight?.cloud ? 'cloud' : 'selfHosted'].map((val, idx) => (
<span key={idx}>{val}</span>
))}
</div>
</footer>
</div>
) : null
} | the_stack |
import {
concat as observableConcat,
defer as observableDefer,
EMPTY,
filter,
finalize,
map,
merge as observableMerge,
mergeMap,
Observable,
of as observableOf,
ReplaySubject,
share,
switchMap,
take,
} from "rxjs";
import { ICustomError } from "../../../errors";
import log from "../../../log";
import Manifest, {
Adaptation,
ISegment,
Period,
Representation,
} from "../../../manifest";
import {
ISegmentParserParsedInitSegment,
ISegmentParserParsedSegment,
} from "../../../transports";
import assert from "../../../utils/assert";
import assertUnreachable from "../../../utils/assert_unreachable";
import objectAssign from "../../../utils/object_assign";
import { IReadOnlySharedReference } from "../../../utils/reference";
import {
IPrioritizedSegmentFetcher,
IPrioritizedSegmentFetcherEvent,
} from "../../fetchers";
import {
IQueuedSegment,
} from "../types";
/**
* Class scheduling segment downloads for a single Representation.
* @class DownloadingQueue
*/
export default class DownloadingQueue<T> {
/** Context of the Representation that will be loaded through this DownloadingQueue. */
private _content : IDownloadingQueueContext;
/**
* Observable doing segment requests and emitting related events.
* We only can have maximum one at a time.
* `null` when `start` has never been called.
*/
private _currentObs$ : Observable<IDownloadingQueueEvent<T>> | null;
/**
* Current queue of segments scheduled for download.
*
* Segments whose request are still pending are still in that queue. Segments
* are only removed from it once their request has succeeded.
*/
private _downloadQueue : IReadOnlySharedReference<IDownloadQueueItem>;
/**
* Pending request for the initialization segment.
* `null` if no request is pending for it.
*/
private _initSegmentRequest : ISegmentRequestObject<T>|null;
/**
* Pending request for a media (i.e. non-initialization) segment.
* `null` if no request is pending for it.
*/
private _mediaSegmentRequest : ISegmentRequestObject<T>|null;
/** Interface used to load segments. */
private _segmentFetcher : IPrioritizedSegmentFetcher<T>;
/** Emit the timescale anounced in the initialization segment once parsed. */
private _initSegmentMetadata$ : ReplaySubject<number | undefined>;
/**
* Some media segments might have been loaded and are only awaiting for the
* initialization segment to be parsed before being parsed themselves.
* This `Set` will contain the `id` property of all segments that are
* currently awaiting this event.
*/
private _mediaSegmentsAwaitingInitMetadata : Set<string>;
/**
* Create a new `DownloadingQueue`.
*
* @param {Object} content - The context of the Representation you want to
* load segments for.
* @param {Object} downloadQueue - Queue of segments you want to load.
* @param {Object} segmentFetcher - Interface to facilitate the download of
* segments.
* @param {boolean} hasInitSegment - Declare that an initialization segment
* will need to be downloaded.
*
* A `DownloadingQueue` ALWAYS wait for the initialization segment to be
* loaded and parsed before parsing a media segment.
*
* In cases where no initialization segment exist, this would lead to the
* `DownloadingQueue` waiting indefinitely for it.
*
* By setting that value to `false`, you anounce to the `DownloadingQueue`
* that it should not wait for an initialization segment before parsing a
* media segment.
*/
constructor(
content: IDownloadingQueueContext,
downloadQueue : IReadOnlySharedReference<IDownloadQueueItem>,
segmentFetcher : IPrioritizedSegmentFetcher<T>,
hasInitSegment : boolean
) {
this._content = content;
this._currentObs$ = null;
this._downloadQueue = downloadQueue;
this._initSegmentRequest = null;
this._mediaSegmentRequest = null;
this._segmentFetcher = segmentFetcher;
this._initSegmentMetadata$ = new ReplaySubject<number|undefined>(1);
this._mediaSegmentsAwaitingInitMetadata = new Set();
if (!hasInitSegment) {
this._initSegmentMetadata$.next(undefined);
}
}
/**
* Returns the initialization segment currently being requested.
* Returns `null` if no initialization segment request is pending.
* @returns {Object}
*/
public getRequestedInitSegment() : ISegment | null {
return this._initSegmentRequest === null ? null :
this._initSegmentRequest.segment;
}
/**
* Returns the media segment currently being requested.
* Returns `null` if no media segment request is pending.
* @returns {Object}
*/
public getRequestedMediaSegment() : ISegment | null {
return this._mediaSegmentRequest === null ? null :
this._mediaSegmentRequest.segment;
}
/**
* Start the current downloading queue, emitting events as it loads and parses
* initialization and media segments.
*
* If it was already started, returns the same - shared - Observable.
* @returns {Observable}
*/
public start() : Observable<IDownloadingQueueEvent<T>> {
if (this._currentObs$ !== null) {
return this._currentObs$;
}
const obs = observableDefer(() => {
const mediaQueue$ = this._downloadQueue.asObservable().pipe(
filter(({ segmentQueue }) => {
// First, the first elements of the segmentQueue might be already
// loaded but awaiting the initialization segment to be parsed.
// Filter those out.
let nextSegmentToLoadIdx = 0;
for (; nextSegmentToLoadIdx < segmentQueue.length; nextSegmentToLoadIdx++) {
const nextSegment = segmentQueue[nextSegmentToLoadIdx].segment;
if (!this._mediaSegmentsAwaitingInitMetadata.has(nextSegment.id)) {
break;
}
}
const currentSegmentRequest = this._mediaSegmentRequest;
if (nextSegmentToLoadIdx >= segmentQueue.length) {
return currentSegmentRequest !== null;
} else if (currentSegmentRequest === null) {
return true;
}
const nextItem = segmentQueue[nextSegmentToLoadIdx];
if (currentSegmentRequest.segment.id !== nextItem.segment.id) {
return true;
}
if (currentSegmentRequest.priority !== nextItem.priority) {
this._segmentFetcher.updatePriority(currentSegmentRequest.request$,
nextItem.priority);
}
return false;
}),
switchMap(({ segmentQueue }) =>
segmentQueue.length > 0 ? this._requestMediaSegments() :
EMPTY));
const initSegmentPush$ = this._downloadQueue.asObservable().pipe(
filter((next) => {
const initSegmentRequest = this._initSegmentRequest;
if (next.initSegment !== null && initSegmentRequest !== null) {
if (next.initSegment.priority !== initSegmentRequest.priority) {
this._segmentFetcher.updatePriority(initSegmentRequest.request$,
next.initSegment.priority);
}
return false;
} else {
return next.initSegment === null || initSegmentRequest === null;
}
}),
switchMap((nextQueue) => {
if (nextQueue.initSegment === null) {
return EMPTY;
}
return this._requestInitSegment(nextQueue.initSegment);
}));
return observableMerge(initSegmentPush$, mediaQueue$);
}).pipe(share());
this._currentObs$ = obs;
return obs;
}
/**
* Internal logic performing media segment requests.
* @returns {Observable}
*/
private _requestMediaSegments(
) : Observable<ILoaderRetryEvent |
IEndOfQueueEvent |
IParsedSegmentEvent<T> |
IEndOfSegmentEvent> {
const { segmentQueue } = this._downloadQueue.getValue();
const currentNeededSegment = segmentQueue[0];
const recursivelyRequestSegments = (
startingSegment : IQueuedSegment | undefined
) : Observable<ILoaderRetryEvent |
IEndOfQueueEvent |
IParsedSegmentEvent<T> |
IEndOfSegmentEvent
> => {
if (startingSegment === undefined) {
return observableOf({ type : "end-of-queue",
value : null });
}
const { segment, priority } = startingSegment;
const context = objectAssign({ segment }, this._content);
const request$ = this._segmentFetcher.createRequest(context, priority);
this._mediaSegmentRequest = { segment, priority, request$ };
return request$
.pipe(mergeMap((evt) => {
switch (evt.type) {
case "warning":
return observableOf({ type: "retry" as const,
value: { segment, error: evt.value } });
case "interrupted":
log.info("Stream: segment request interrupted temporarly.", segment);
return EMPTY;
case "ended":
this._mediaSegmentRequest = null;
const lastQueue = this._downloadQueue.getValue().segmentQueue;
if (lastQueue.length === 0) {
return observableOf({ type : "end-of-queue" as const,
value : null });
} else if (lastQueue[0].segment.id === segment.id) {
lastQueue.shift();
}
return recursivelyRequestSegments(lastQueue[0]);
case "chunk":
case "chunk-complete":
this._mediaSegmentsAwaitingInitMetadata.add(segment.id);
return this._initSegmentMetadata$.pipe(
take(1),
map((initTimescale) => {
if (evt.type === "chunk-complete") {
return { type: "end-of-segment" as const,
value: { segment } };
}
const parsed = evt.parse(initTimescale);
assert(parsed.segmentType === "media",
"Should have loaded a media segment.");
return objectAssign({},
parsed,
{ type: "parsed-media" as const,
segment });
}),
finalize(() => {
this._mediaSegmentsAwaitingInitMetadata.delete(segment.id);
}));
default:
assertUnreachable(evt);
}
}));
};
return observableDefer(() =>
recursivelyRequestSegments(currentNeededSegment)
).pipe(finalize(() => { this._mediaSegmentRequest = null; }));
}
/**
* Internal logic performing initialization segment requests.
* @param {Object} queuedInitSegment
* @returns {Observable}
*/
private _requestInitSegment(
queuedInitSegment : IQueuedSegment | null
) : Observable<ILoaderRetryEvent |
IParsedInitSegmentEvent<T> |
IEndOfSegmentEvent> {
if (queuedInitSegment === null) {
this._initSegmentRequest = null;
return EMPTY;
}
const { segment, priority } = queuedInitSegment;
const context = objectAssign({ segment }, this._content);
const request$ = this._segmentFetcher.createRequest(context, priority);
this._initSegmentRequest = { segment, priority, request$ };
return request$
.pipe(mergeMap((evt) : Observable<ILoaderRetryEvent |
IParsedInitSegmentEvent<T> |
IEndOfSegmentEvent> =>
{
switch (evt.type) {
case "warning":
return observableOf({ type: "retry" as const,
value: { segment, error: evt.value } });
case "interrupted":
log.info("Stream: init segment request interrupted temporarly.", segment);
return EMPTY;
case "chunk":
const parsed = evt.parse(undefined);
assert(parsed.segmentType === "init",
"Should have loaded an init segment.");
return observableConcat(
observableOf(objectAssign({},
parsed,
{ type: "parsed-init" as const,
segment })),
// We want to emit parsing information strictly AFTER the
// initialization segment is emitted. Hence why we perform this
// side-effect a posteriori in a concat operator
observableDefer(() => {
if (parsed.segmentType === "init") {
this._initSegmentMetadata$.next(parsed.initTimescale);
}
return EMPTY;
}));
case "chunk-complete":
return observableOf({ type: "end-of-segment" as const,
value: { segment } });
case "ended":
return EMPTY; // Do nothing, just here to check every case
default:
assertUnreachable(evt);
}
})).pipe(finalize(() => { this._initSegmentRequest = null; }));
}
}
/** Event sent by the DownloadingQueue. */
export type IDownloadingQueueEvent<T> = IParsedInitSegmentEvent<T> |
IParsedSegmentEvent<T> |
IEndOfSegmentEvent |
ILoaderRetryEvent |
IEndOfQueueEvent;
/**
* Notify that the initialization segment has been fully loaded and parsed.
*
* You can now push that segment to its corresponding buffer and use its parsed
* metadata.
*
* Only sent if an initialization segment exists (when the `DownloadingQueue`'s
* `hasInitSegment` constructor option has been set to `true`).
* In that case, an `IParsedInitSegmentEvent` will always be sent before any
* `IParsedSegmentEvent` event is sent.
*/
export type IParsedInitSegmentEvent<T> = ISegmentParserParsedInitSegment<T> &
{ segment : ISegment;
type : "parsed-init"; };
/**
* Notify that a media chunk (decodable sub-part of a media segment) has been
* loaded and parsed.
*
* If an initialization segment exists (when the `DownloadingQueue`'s
* `hasInitSegment` constructor option has been set to `true`), an
* `IParsedSegmentEvent` will always be sent AFTER the `IParsedInitSegmentEvent`
* event.
*
* It can now be pushed to its corresponding buffer. Note that there might be
* multiple `IParsedSegmentEvent` for a single segment, if that segment is
* divided into multiple decodable chunks.
* You will know that all `IParsedSegmentEvent` have been loaded for a given
* segment once you received the `IEndOfSegmentEvent` for that segment.
*/
export type IParsedSegmentEvent<T> = ISegmentParserParsedSegment<T> &
{ segment : ISegment;
type : "parsed-media"; };
/** Notify that a media or initialization segment has been fully-loaded. */
export interface IEndOfSegmentEvent { type : "end-of-segment";
value: { segment : ISegment }; }
/**
* Notify that a media or initialization segment request is retried.
* This happened most likely because of an HTTP error.
*/
export interface ILoaderRetryEvent { type : "retry";
value : { segment : ISegment;
error : ICustomError; }; }
/**
* Notify that the media segment queue is now empty.
* This can be used to re-check if any segment are now needed.
*/
export interface IEndOfQueueEvent { type : "end-of-queue"; value : null }
/**
* Structure of the object that has to be emitted through the `downloadQueue`
* Observable, to signal which segments are currently needed.
*/
export interface IDownloadQueueItem {
/**
* A potential initialization segment that needs to be loaded and parsed.
* It will generally be requested in parralel of the first media segments.
*
* Can be set to `null` if you don't need to load the initialization segment
* for now.
*
* If the `DownloadingQueue`'s `hasInitSegment` constructor option has been
* set to `true`, no media segment will be parsed before the initialization
* segment has been loaded and parsed.
*/
initSegment : IQueuedSegment | null;
/**
* The queue of media segments currently needed for download.
*
* Those will be loaded from the first element in that queue to the last
* element in it.
*
* Note that any media segments in the segment queue will only be parsed once
* either of these is true:
* - An initialization segment has been loaded and parsed by this
* `DownloadingQueue` instance.
* - The `DownloadingQueue`'s `hasInitSegment` constructor option has been
* set to `false`.
*/
segmentQueue : IQueuedSegment[];
}
/** Object describing a pending Segment request. */
interface ISegmentRequestObject<T> {
/** The segment the request is for. */
segment : ISegment;
/** The request Observable itself. Can be used to update its priority. */
request$ : Observable<IPrioritizedSegmentFetcherEvent<T>>;
/** Last set priority of the segment request (lower number = higher priority). */
priority : number;
}
/** Context for segments downloaded through the DownloadingQueue. */
export interface IDownloadingQueueContext {
/** Adaptation linked to the segments you want to load. */
adaptation : Adaptation;
/** Manifest linked to the segments you want to load. */
manifest : Manifest;
/** Period linked to the segments you want to load. */
period : Period;
/** Representation linked to the segments you want to load. */
representation : Representation;
}
/** Object describing a pending Segment request. */
interface ISegmentRequestObject<T> {
/** The segment the request is for. */
segment : ISegment;
/** The request Observable itself. Can be used to update its priority. */
request$ : Observable<IPrioritizedSegmentFetcherEvent<T>>;
/** Last set priority of the segment request (lower number = higher priority). */
priority : number;
} | the_stack |
import * as iam from '@aws-cdk/aws-iam';
import * as cdk from '@aws-cdk/core';
import { Alarm, ComparisonOperator, TreatMissingData } from './alarm';
import { IMetric, MetricAlarmConfig, MetricConfig, MetricGraphConfig, Unit } from './metric-types';
export declare type DimensionHash = {
[dim: string]: any;
};
/**
* Options shared by most methods accepting metric options.
*/
export interface CommonMetricOptions {
/**
* The period over which the specified statistic is applied.
*
* @default Duration.minutes(5)
*/
readonly period?: cdk.Duration;
/**
* What function to use for aggregating.
*
* Can be one of the following:
*
* - "Minimum" | "min"
* - "Maximum" | "max"
* - "Average" | "avg"
* - "Sum" | "sum"
* - "SampleCount | "n"
* - "pNN.NN"
*
* @default Average
*/
readonly statistic?: string;
/**
* Dimensions of the metric.
*
* @default - No dimensions.
*/
readonly dimensions?: DimensionHash;
/**
* Unit used to filter the metric stream.
*
* Only refer to datums emitted to the metric stream with the given unit and
* ignore all others. Only useful when datums are being emitted to the same
* metric stream under different units.
*
* The default is to use all matric datums in the stream, regardless of unit,
* which is recommended in nearly all cases.
*
* CloudWatch does not honor this property for graphs.
*
* @default - All metric datums in the given metric stream
*/
readonly unit?: Unit;
/**
* Label for this metric when added to a Graph in a Dashboard.
*
* @default - No label
*/
readonly label?: string;
/**
* The hex color code, prefixed with '#' (e.g. '#00ff00'), to use when this metric is rendered on a graph. The `Color` class has a set of standard colors that can be used here.
*
* @default - Automatic color
*/
readonly color?: string;
/**
* Account which this metric comes from.
*
* @default - Deployment account.
*/
readonly account?: string;
/**
* Region which this metric comes from.
*
* @default - Deployment region.
*/
readonly region?: string;
}
/**
* Properties for a metric.
*/
export interface MetricProps extends CommonMetricOptions {
/**
* Namespace of the metric.
*/
readonly namespace: string;
/**
* Name of the metric.
*/
readonly metricName: string;
}
/**
* Properties of a metric that can be changed.
*/
export interface MetricOptions extends CommonMetricOptions {
}
/**
* Configurable options for MathExpressions.
*/
export interface MathExpressionOptions {
/**
* Label for this metric when added to a Graph in a Dashboard.
*
* @default - Expression value is used as label
*/
readonly label?: string;
/**
* Color for this metric when added to a Graph in a Dashboard.
*
* @default - Automatic color
*/
readonly color?: string;
/**
* The period over which the expression's statistics are applied.
*
* This period overrides all periods in the metrics used in this
* math expression.
*
* @default Duration.minutes(5)
*/
readonly period?: cdk.Duration;
}
/**
* Properties for a MathExpression.
*/
export interface MathExpressionProps extends MathExpressionOptions {
/**
* The expression defining the metric.
*/
readonly expression: string;
/**
* The metrics used in the expression, in a map.
*
* The key is the identifier that represents the given metric in the
* expression, and the value is the actual Metric object.
*/
readonly usingMetrics: Record<string, IMetric>;
}
/**
* A metric emitted by a service.
*
* The metric is a combination of a metric identifier (namespace, name and dimensions)
* and an aggregation function (statistic, period and unit).
*
* It also contains metadata which is used only in graphs, such as color and label.
* It makes sense to embed this in here, so that compound constructs can attach
* that metadata to metrics they expose.
*
* This class does not represent a resource, so hence is not a construct. Instead,
* Metric is an abstraction that makes it easy to specify metrics for use in both
* alarms and graphs.
*/
export declare class Metric implements IMetric {
/**
* Grant permissions to the given identity to write metrics.
*
* @param grantee The IAM identity to give permissions to.
*/
static grantPutMetricData(grantee: iam.IGrantable): iam.Grant;
/**
* Dimensions of this metric.
*/
readonly dimensions?: DimensionHash;
/**
* Namespace of this metric.
*/
readonly namespace: string;
/**
* Name of this metric.
*/
readonly metricName: string;
/**
* Period of this metric.
*/
readonly period: cdk.Duration;
/**
* Statistic of this metric.
*/
readonly statistic: string;
/**
* Label for this metric when added to a Graph in a Dashboard.
*/
readonly label?: string;
/**
* The hex color code used when this metric is rendered on a graph.
*/
readonly color?: string;
/**
* Unit of the metric.
*/
readonly unit?: Unit;
/**
* Account which this metric comes from.
*/
readonly account?: string;
/**
* Region which this metric comes from.
*/
readonly region?: string;
/**
*
*/
constructor(props: MetricProps);
/**
* Return a copy of Metric `with` properties changed.
*
* All properties except namespace and metricName can be changed.
*
* @param props The set of properties to change.
*/
with(props: MetricOptions): Metric;
/**
* Attach the metric object to the given construct scope.
*
* Returns a Metric object that uses the account and region from the Stack
* the given construct is defined in. If the metric is subsequently used
* in a Dashboard or Alarm in a different Stack defined in a different
* account or region, the appropriate 'region' and 'account' fields
* will be added to it.
*
* If the scope we attach to is in an environment-agnostic stack,
* nothing is done and the same Metric object is returned.
*/
attachTo(scope: cdk.Construct): Metric;
/**
* Inspect the details of the metric object.
*/
toMetricConfig(): MetricConfig;
/**
* Turn this metric object into an alarm configuration.
*/
toAlarmConfig(): MetricAlarmConfig;
/**
* Turn this metric object into a graph configuration.
*/
toGraphConfig(): MetricGraphConfig;
/**
* Make a new Alarm for this metric.
*
* Combines both properties that may adjust the metric (aggregation) as well
* as alarm properties.
*/
createAlarm(scope: cdk.Construct, id: string, props: CreateAlarmOptions): Alarm;
/**
* Returns a string representation of an object.
*/
toString(): string;
/**
* Return the dimensions of this Metric as a list of Dimension.
*/
private dimensionsAsList;
}
/**
* A math expression built with metric(s) emitted by a service.
*
* The math expression is a combination of an expression (x+y) and metrics to apply expression on.
* It also contains metadata which is used only in graphs, such as color and label.
* It makes sense to embed this in here, so that compound constructs can attach
* that metadata to metrics they expose.
*
* This class does not represent a resource, so hence is not a construct. Instead,
* MathExpression is an abstraction that makes it easy to specify metrics for use in both
* alarms and graphs.
*/
export declare class MathExpression implements IMetric {
/**
* The expression defining the metric.
*/
readonly expression: string;
/**
* The metrics used in the expression as KeyValuePair <id, metric>.
*/
readonly usingMetrics: Record<string, IMetric>;
/**
* Label for this metric when added to a Graph.
*/
readonly label?: string;
/**
* The hex color code, prefixed with '#' (e.g. '#00ff00'), to use when this metric is rendered on a graph. The `Color` class has a set of standard colors that can be used here.
*/
readonly color?: string;
/**
* Aggregation period of this metric.
*/
readonly period: cdk.Duration;
/**
*
*/
constructor(props: MathExpressionProps);
/**
* Return a copy of Metric with properties changed.
*
* All properties except namespace and metricName can be changed.
*
* @param props The set of properties to change.
*/
with(props: MathExpressionOptions): MathExpression;
/**
* Turn this metric object into an alarm configuration.
*/
toAlarmConfig(): MetricAlarmConfig;
/**
* Turn this metric object into a graph configuration.
*/
toGraphConfig(): MetricGraphConfig;
/**
* Inspect the details of the metric object.
*/
toMetricConfig(): MetricConfig;
/**
* Make a new Alarm for this metric.
*
* Combines both properties that may adjust the metric (aggregation) as well
* as alarm properties.
*/
createAlarm(scope: cdk.Construct, id: string, props: CreateAlarmOptions): Alarm;
/**
* Returns a string representation of an object.
*/
toString(): string;
private validateNoIdConflicts;
}
/**
* Properties needed to make an alarm from a metric.
*/
export interface CreateAlarmOptions {
/**
* (deprecated) The period over which the specified statistic is applied.
*
* Cannot be used with `MathExpression` objects.
*
* @default - The period from the metric
* @deprecated Use `metric.with({ period: ... })` to encode the period into the Metric object
*/
readonly period?: cdk.Duration;
/**
* (deprecated) What function to use for aggregating.
*
* Can be one of the following:
*
* - "Minimum" | "min"
* - "Maximum" | "max"
* - "Average" | "avg"
* - "Sum" | "sum"
* - "SampleCount | "n"
* - "pNN.NN"
*
* Cannot be used with `MathExpression` objects.
*
* @default - The statistic from the metric
* @deprecated Use `metric.with({ statistic: ... })` to encode the period into the Metric object
*/
readonly statistic?: string;
/**
* Name of the alarm.
*
* @default Automatically generated name
*/
readonly alarmName?: string;
/**
* Description for the alarm.
*
* @default No description
*/
readonly alarmDescription?: string;
/**
* Comparison to use to check if metric is breaching.
*
* @default GreaterThanOrEqualToThreshold
*/
readonly comparisonOperator?: ComparisonOperator;
/**
* The value against which the specified statistic is compared.
*/
readonly threshold: number;
/**
* The number of periods over which data is compared to the specified threshold.
*/
readonly evaluationPeriods: number;
/**
* Specifies whether to evaluate the data and potentially change the alarm state if there are too few data points to be statistically significant.
*
* Used only for alarms that are based on percentiles.
*
* @default - Not configured.
*/
readonly evaluateLowSampleCountPercentile?: string;
/**
* Sets how this alarm is to handle missing data points.
*
* @default TreatMissingData.Missing
*/
readonly treatMissingData?: TreatMissingData;
/**
* Whether the actions for this alarm are enabled.
*
* @default true
*/
readonly actionsEnabled?: boolean;
/**
* The number of datapoints that must be breaching to trigger the alarm.
*
* This is used only if you are setting an "M
* out of N" alarm. In that case, this value is the M. For more information, see Evaluating an Alarm in the Amazon
* CloudWatch User Guide.
*
* @default ``evaluationPeriods``
* @see https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/AlarmThatSendsEmail.html#alarm-evaluation
*/
readonly datapointsToAlarm?: number;
} | the_stack |
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*
* Modifications Copyright OpenSearch Contributors. See
* GitHub history for details.
*/
import { i18n } from '@osd/i18n';
export const createNodeAgentInstructions = (apmServerUrl = '', secretToken = '') => [
{
title: i18n.translate('apmOss.tutorial.nodeClient.install.title', {
defaultMessage: 'Install the APM agent',
}),
textPre: i18n.translate('apmOss.tutorial.nodeClient.install.textPre', {
defaultMessage: 'Install the APM agent for Node.js as a dependency to your application.',
}),
commands: ['npm install elastic-apm-node --save'],
},
{
title: i18n.translate('apmOss.tutorial.nodeClient.configure.title', {
defaultMessage: 'Configure the agent',
}),
textPre: i18n.translate('apmOss.tutorial.nodeClient.configure.textPre', {
defaultMessage:
'Agents are libraries that run inside of your application process. \
APM services are created programmatically based on the `serviceName`. \
This agent supports a variety of frameworks but can also be used with your custom stack.',
}),
commands: `// ${i18n.translate(
'apmOss.tutorial.nodeClient.configure.commands.addThisToTheFileTopComment',
{
defaultMessage: 'Add this to the VERY top of the first file loaded in your app',
}
)}
var apm = require('elastic-apm-node').start({curlyOpen}
// ${i18n.translate(
'apmOss.tutorial.nodeClient.configure.commands.setRequiredServiceNameComment',
{
defaultMessage: 'Override service name from package.json',
}
)}
// ${i18n.translate('apmOss.tutorial.nodeClient.configure.commands.allowedCharactersComment', {
defaultMessage: 'Allowed characters: a-z, A-Z, 0-9, -, _, and space',
})}
serviceName: '',
// ${i18n.translate(
'apmOss.tutorial.nodeClient.configure.commands.useIfApmRequiresTokenComment',
{
defaultMessage: 'Use if APM Server requires a token',
}
)}
secretToken: '${secretToken}',
// ${i18n.translate(
'apmOss.tutorial.nodeClient.configure.commands.setCustomApmServerUrlComment',
{
defaultMessage: 'Set custom APM Server URL (default: {defaultApmServerUrl})',
values: { defaultApmServerUrl: 'http://localhost:8200' },
}
)}
serverUrl: '${apmServerUrl}'
{curlyClose})`.split('\n'),
textPost: i18n.translate('apmOss.tutorial.nodeClient.configure.textPost', {
defaultMessage:
'See [the documentation]({documentationLink}) for advanced usage, including how to use with \
[Babel/ES Modules]({babelEsModulesLink}).',
values: {
documentationLink: '{config.docs.base_url}guide/en/apm/agent/nodejs/current/index.html',
babelEsModulesLink:
'{config.docs.base_url}guide/en/apm/agent/nodejs/current/advanced-setup.html#es-modules',
},
}),
},
];
export const createDjangoAgentInstructions = (apmServerUrl = '', secretToken = '') => [
{
title: i18n.translate('apmOss.tutorial.djangoClient.install.title', {
defaultMessage: 'Install the APM agent',
}),
textPre: i18n.translate('apmOss.tutorial.djangoClient.install.textPre', {
defaultMessage: 'Install the APM agent for Python as a dependency.',
}),
commands: ['$ pip install elastic-apm'],
},
{
title: i18n.translate('apmOss.tutorial.djangoClient.configure.title', {
defaultMessage: 'Configure the agent',
}),
textPre: i18n.translate('apmOss.tutorial.djangoClient.configure.textPre', {
defaultMessage:
'Agents are libraries that run inside of your application process. \
APM services are created programmatically based on the `SERVICE_NAME`.',
}),
commands: `# ${i18n.translate(
'apmOss.tutorial.djangoClient.configure.commands.addAgentComment',
{
defaultMessage: 'Add the agent to the installed apps',
}
)}
INSTALLED_APPS = (
'elasticapm.contrib.django',
# ...
)
ELASTIC_APM = {curlyOpen}
# ${i18n.translate(
'apmOss.tutorial.djangoClient.configure.commands.setRequiredServiceNameComment',
{
defaultMessage: 'Set required service name. Allowed characters:',
}
)}
# ${i18n.translate('apmOss.tutorial.djangoClient.configure.commands.allowedCharactersComment', {
defaultMessage: 'a-z, A-Z, 0-9, -, _, and space',
})}
'SERVICE_NAME': '',
# ${i18n.translate(
'apmOss.tutorial.djangoClient.configure.commands.useIfApmServerRequiresTokenComment',
{
defaultMessage: 'Use if APM Server requires a token',
}
)}
'SECRET_TOKEN': '${secretToken}',
# ${i18n.translate(
'apmOss.tutorial.djangoClient.configure.commands.setCustomApmServerUrlComment',
{
defaultMessage: 'Set custom APM Server URL (default: {defaultApmServerUrl})',
values: { defaultApmServerUrl: 'http://localhost:8200' },
}
)}
'SERVER_URL': '${apmServerUrl}',
{curlyClose}
# ${i18n.translate('apmOss.tutorial.djangoClient.configure.commands.addTracingMiddlewareComment', {
defaultMessage: 'To send performance metrics, add our tracing middleware:',
})}
MIDDLEWARE = (
'elasticapm.contrib.django.middleware.TracingMiddleware',
#...
)`.split('\n'),
textPost: i18n.translate('apmOss.tutorial.djangoClient.configure.textPost', {
defaultMessage: 'See the [documentation]({documentationLink}) for advanced usage.',
values: {
documentationLink:
'{config.docs.base_url}guide/en/apm/agent/python/current/django-support.html',
},
}),
},
];
export const createFlaskAgentInstructions = (apmServerUrl = '', secretToken = '') => [
{
title: i18n.translate('apmOss.tutorial.flaskClient.install.title', {
defaultMessage: 'Install the APM agent',
}),
textPre: i18n.translate('apmOss.tutorial.flaskClient.install.textPre', {
defaultMessage: 'Install the APM agent for Python as a dependency.',
}),
commands: ['$ pip install elastic-apm[flask]'],
},
{
title: i18n.translate('apmOss.tutorial.flaskClient.configure.title', {
defaultMessage: 'Configure the agent',
}),
textPre: i18n.translate('apmOss.tutorial.flaskClient.configure.textPre', {
defaultMessage:
'Agents are libraries that run inside of your application process. \
APM services are created programmatically based on the `SERVICE_NAME`.',
}),
commands: `# ${i18n.translate(
'apmOss.tutorial.flaskClient.configure.commands.initializeUsingEnvironmentVariablesComment',
{
defaultMessage: 'initialize using environment variables',
}
)}
from elasticapm.contrib.flask import ElasticAPM
app = Flask(__name__)
apm = ElasticAPM(app)
# ${i18n.translate('apmOss.tutorial.flaskClient.configure.commands.configureElasticApmComment', {
defaultMessage: "or configure to use ELASTIC_APM in your application's settings",
})}
from elasticapm.contrib.flask import ElasticAPM
app.config['ELASTIC_APM'] = {curlyOpen}
# ${i18n.translate(
'apmOss.tutorial.flaskClient.configure.commands.setRequiredServiceNameComment',
{
defaultMessage: 'Set required service name. Allowed characters:',
}
)}
# ${i18n.translate('apmOss.tutorial.flaskClient.configure.commands.allowedCharactersComment', {
defaultMessage: 'a-z, A-Z, 0-9, -, _, and space',
})}
'SERVICE_NAME': '',
# ${i18n.translate(
'apmOss.tutorial.flaskClient.configure.commands.useIfApmServerRequiresTokenComment',
{
defaultMessage: 'Use if APM Server requires a token',
}
)}
'SECRET_TOKEN': '${secretToken}',
# ${i18n.translate(
'apmOss.tutorial.flaskClient.configure.commands.setCustomApmServerUrlComment',
{
defaultMessage: 'Set custom APM Server URL (default: {defaultApmServerUrl})',
values: { defaultApmServerUrl: 'http://localhost:8200' },
}
)}
'SERVER_URL': '${apmServerUrl}',
{curlyClose}
apm = ElasticAPM(app)`.split('\n'),
textPost: i18n.translate('apmOss.tutorial.flaskClient.configure.textPost', {
defaultMessage: 'See the [documentation]({documentationLink}) for advanced usage.',
values: {
documentationLink:
'{config.docs.base_url}guide/en/apm/agent/python/current/flask-support.html',
},
}),
},
];
export const createRailsAgentInstructions = (apmServerUrl = '', secretToken = '') => [
{
title: i18n.translate('apmOss.tutorial.railsClient.install.title', {
defaultMessage: 'Install the APM agent',
}),
textPre: i18n.translate('apmOss.tutorial.railsClient.install.textPre', {
defaultMessage: 'Add the agent to your Gemfile.',
}),
commands: [`gem 'elastic-apm'`],
},
{
title: i18n.translate('apmOss.tutorial.railsClient.configure.title', {
defaultMessage: 'Configure the agent',
}),
textPre: i18n.translate('apmOss.tutorial.railsClient.configure.textPre', {
defaultMessage:
'APM is automatically started when your app boots. Configure the agent, by creating the config file {configFile}',
values: { configFile: '`config/elastic_apm.yml`' },
}),
commands: `# config/elastic_apm.yml:
# Set service name - allowed characters: a-z, A-Z, 0-9, -, _ and space
# Defaults to the name of your Rails app
# service_name: 'my-service'
# Use if APM Server requires a token
# secret_token: '${secretToken}'
# Set custom APM Server URL (default: http://localhost:8200)
# server_url: '${apmServerUrl || 'http://localhost:8200'}'`.split('\n'),
textPost: i18n.translate('apmOss.tutorial.railsClient.configure.textPost', {
defaultMessage:
'See the [documentation]({documentationLink}) for configuration options and advanced usage.\n\n',
values: {
documentationLink: '{config.docs.base_url}guide/en/apm/agent/ruby/current/index.html',
},
}),
},
];
export const createRackAgentInstructions = (apmServerUrl = '', secretToken = '') => [
{
title: i18n.translate('apmOss.tutorial.rackClient.install.title', {
defaultMessage: 'Install the APM agent',
}),
textPre: i18n.translate('apmOss.tutorial.rackClient.install.textPre', {
defaultMessage: 'Add the agent to your Gemfile.',
}),
commands: [`gem 'elastic-apm'`],
},
{
title: i18n.translate('apmOss.tutorial.rackClient.configure.title', {
defaultMessage: 'Configure the agent',
}),
textPre: i18n.translate('apmOss.tutorial.rackClient.configure.textPre', {
defaultMessage:
'For Rack or a compatible framework (e.g. Sinatra), include the middleware in your app and start the agent.',
}),
commands: `# config.ru
require 'sinatra/base'
class MySinatraApp < Sinatra::Base
use ElasticAPM::Middleware
# ...
end
ElasticAPM.start(
app: MySinatraApp, # ${i18n.translate(
'apmOss.tutorial.rackClient.configure.commands.requiredComment',
{
defaultMessage: 'required',
}
)}
config_file: '' # ${i18n.translate(
'apmOss.tutorial.rackClient.configure.commands.optionalComment',
{
defaultMessage: 'optional, defaults to config/elastic_apm.yml',
}
)}
)
run MySinatraApp
at_exit {curlyOpen} ElasticAPM.stop {curlyClose}`.split('\n'),
},
{
title: i18n.translate('apmOss.tutorial.rackClient.createConfig.title', {
defaultMessage: 'Create config file',
}),
textPre: i18n.translate('apmOss.tutorial.rackClient.createConfig.textPre', {
defaultMessage: 'Create a config file {configFile}:',
values: { configFile: '`config/elastic_apm.yml`' },
}),
commands: `# config/elastic_apm.yml:
# ${i18n.translate('apmOss.tutorial.rackClient.createConfig.commands.setServiceNameComment', {
defaultMessage: 'Set service name - allowed characters: a-z, A-Z, 0-9, -, _ and space',
})}
# ${i18n.translate(
'apmOss.tutorial.rackClient.createConfig.commands.defaultsToTheNameOfRackAppClassComment',
{
defaultMessage: "Defaults to the name of your Rack app's class.",
}
)}
# service_name: 'my-service'
# ${i18n.translate(
'apmOss.tutorial.rackClient.createConfig.commands.useIfApmServerRequiresTokenComment',
{
defaultMessage: 'Use if APM Server requires a token',
}
)}
# secret_token: '${secretToken}'
# ${i18n.translate('apmOss.tutorial.rackClient.createConfig.commands.setCustomApmServerComment', {
defaultMessage: 'Set custom APM Server URL (default: {defaultServerUrl})',
values: { defaultServerUrl: 'http://localhost:8200' },
})}
# server_url: '${apmServerUrl || 'http://localhost:8200'}'`.split('\n'),
textPost: i18n.translate('apmOss.tutorial.rackClient.createConfig.textPost', {
defaultMessage:
'See the [documentation]({documentationLink}) for configuration options and advanced usage.\n\n',
values: {
documentationLink: '{config.docs.base_url}guide/en/apm/agent/ruby/current/index.html',
},
}),
},
];
export const createJsAgentInstructions = (apmServerUrl = '') => [
{
title: i18n.translate('apmOss.tutorial.jsClient.enableRealUserMonitoring.title', {
defaultMessage: 'Enable Real User Monitoring support in APM Server',
}),
textPre: i18n.translate('apmOss.tutorial.jsClient.enableRealUserMonitoring.textPre', {
defaultMessage:
'APM Server disables RUM support by default. See the [documentation]({documentationLink}) \
for details on how to enable RUM support.',
values: {
documentationLink:
'{config.docs.base_url}guide/en/apm/server/{config.docs.version}/configuration-rum.html',
},
}),
},
{
title: i18n.translate('apmOss.tutorial.jsClient.installDependency.title', {
defaultMessage: 'Set up the Agent as a dependency',
}),
textPre: i18n.translate('apmOss.tutorial.jsClient.installDependency.textPre', {
defaultMessage:
'You can install the Agent as a dependency to your application with \
`npm install @elastic/apm-rum --save`.\n\n\
The Agent can then be initialized and configured in your application like this:',
}),
commands: `import {curlyOpen} init as initApm {curlyClose} from '@elastic/apm-rum'
var apm = initApm({curlyOpen}
// ${i18n.translate(
'apmOss.tutorial.jsClient.installDependency.commands.setRequiredServiceNameComment',
{
defaultMessage:
'Set required service name (allowed characters: a-z, A-Z, 0-9, -, _, and space)',
}
)}
serviceName: '',
// ${i18n.translate(
'apmOss.tutorial.jsClient.installDependency.commands.setCustomApmServerUrlComment',
{
defaultMessage: 'Set custom APM Server URL (default: {defaultApmServerUrl})',
values: { defaultApmServerUrl: 'http://localhost:8200' },
}
)}
serverUrl: '${apmServerUrl}',
// ${i18n.translate(
'apmOss.tutorial.jsClient.installDependency.commands.setServiceVersionComment',
{
defaultMessage: 'Set service version (required for source map feature)',
}
)}
serviceVersion: ''
{curlyClose})`.split('\n'),
textPost: i18n.translate('apmOss.tutorial.jsClient.installDependency.textPost', {
defaultMessage:
'Framework integrations, like React or Angular, have custom dependencies. \
See the [integration documentation]({docLink}) for more information.',
values: {
docLink:
'{config.docs.base_url}guide/en/apm/agent/rum-js/current/framework-integrations.html',
},
}),
},
{
title: i18n.translate('apmOss.tutorial.jsClient.scriptTags.title', {
defaultMessage: 'Set up the Agent with Script Tags',
}),
textPre: i18n.translate('apmOss.tutorial.jsClient.scriptTags.textPre', {
defaultMessage:
"Alternatively, you can use Script tags to set up and configure the Agent. \
Add a `<script>` tag to the HTML page and use the `elasticApm` global object to load and initialize the agent. \
Don't forget to download the latest version of the RUM Agent from [GitHub]({GitHubLink}) or [UNPKG]({UnpkgLink}), \
and host the file on your Server/CDN before deploying to production.",
values: {
GitHubLink: 'https://github.com/elastic/apm-agent-rum-js/releases/latest',
UnpkgLink: 'https://unpkg.com/@elastic/apm-rum/dist/bundles/elastic-apm-rum.umd.min.js',
},
}),
commands: `\
<script src="https://your-cdn-host.com/path/to/elastic-apm-rum.umd.min.js" crossorigin></script>
<script>
elasticApm.init({curlyOpen}
serviceName: 'your-app-name',
serverUrl: 'http://localhost:8200',
{curlyClose})
</script>
`.split('\n'),
},
];
export const createGoAgentInstructions = (apmServerUrl = '', secretToken = '') => [
{
title: i18n.translate('apmOss.tutorial.goClient.install.title', {
defaultMessage: 'Install the APM agent',
}),
textPre: i18n.translate('apmOss.tutorial.goClient.install.textPre', {
defaultMessage: 'Install the APM agent packages for Go.',
}),
commands: ['go get go.opensearch.org/apm'],
},
{
title: i18n.translate('apmOss.tutorial.goClient.configure.title', {
defaultMessage: 'Configure the agent',
}),
textPre: i18n.translate('apmOss.tutorial.goClient.configure.textPre', {
defaultMessage:
'Agents are libraries that run inside of your application process. \
APM services are created programmatically based on the executable \
file name, or the `ELASTIC_APM_SERVICE_NAME` environment variable.',
}),
commands: `# ${i18n.translate(
'apmOss.tutorial.goClient.configure.commands.initializeUsingEnvironmentVariablesComment',
{
defaultMessage: 'Initialize using environment variables:',
}
)}
# ${i18n.translate('apmOss.tutorial.goClient.configure.commands.setServiceNameComment', {
defaultMessage: 'Set the service name. Allowed characters: # a-z, A-Z, 0-9, -, _, and space.',
})}
# ${i18n.translate('apmOss.tutorial.goClient.configure.commands.usedExecutableNameComment', {
defaultMessage:
'If ELASTIC_APM_SERVICE_NAME is not specified, the executable name will be used.',
})}
export ELASTIC_APM_SERVICE_NAME=
# ${i18n.translate('apmOss.tutorial.goClient.configure.commands.setCustomApmServerUrlComment', {
defaultMessage: 'Set custom APM Server URL (default: {defaultApmServerUrl})',
values: { defaultApmServerUrl: 'http://localhost:8200' },
})}
export ELASTIC_APM_SERVER_URL=${apmServerUrl}
# ${i18n.translate('apmOss.tutorial.goClient.configure.commands.useIfApmRequiresTokenComment', {
defaultMessage: 'Use if APM Server requires a token',
})}
export ELASTIC_APM_SECRET_TOKEN=${secretToken}
`.split('\n'),
textPost: i18n.translate('apmOss.tutorial.goClient.configure.textPost', {
defaultMessage: 'See the [documentation]({documentationLink}) for advanced configuration.',
values: {
documentationLink: '{config.docs.base_url}guide/en/apm/agent/go/current/configuration.html',
},
}),
},
{
title: i18n.translate('apmOss.tutorial.goClient.instrument.title', {
defaultMessage: 'Instrument your application',
}),
textPre: i18n.translate('apmOss.tutorial.goClient.instrument.textPre', {
defaultMessage:
'Instrument your Go application by using one of the provided instrumentation modules or \
by using the tracer API directly.',
}),
commands: `\
import (
"net/http"
"go.opensearch.org/apm/module/apmhttp"
)
func main() {curlyOpen}
mux := http.NewServeMux()
...
http.ListenAndServe(":8080", apmhttp.Wrap(mux))
{curlyClose}
`.split('\n'),
textPost: i18n.translate('apmOss.tutorial.goClient.instrument.textPost', {
defaultMessage:
'See the [documentation]({documentationLink}) for a detailed \
guide to instrumenting Go source code.',
values: {
documentationLink:
'{config.docs.base_url}guide/en/apm/agent/go/current/instrumenting-source.html',
},
}),
},
];
export const createJavaAgentInstructions = (apmServerUrl = '', secretToken = '') => [
{
title: i18n.translate('apmOss.tutorial.javaClient.download.title', {
defaultMessage: 'Download the APM agent',
}),
textPre: i18n.translate('apmOss.tutorial.javaClient.download.textPre', {
defaultMessage:
'Download the agent jar from [Maven Central]({mavenCentralLink}). \
Do **not** add the agent as a dependency to your application.',
values: {
mavenCentralLink: 'http://search.maven.org/#search%7Cga%7C1%7Ca%3Aelastic-apm-agent',
},
}),
},
{
title: i18n.translate('apmOss.tutorial.javaClient.startApplication.title', {
defaultMessage: 'Start your application with the javaagent flag',
}),
textPre: i18n.translate('apmOss.tutorial.javaClient.startApplication.textPre', {
defaultMessage:
'Add the `-javaagent` flag and configure the agent with system properties.\n\n \
* Set required service name (allowed characters: a-z, A-Z, 0-9, -, _, and space)\n \
* Set custom APM Server URL (default: {customApmServerUrl})\n \
* Set the base package of your application',
values: { customApmServerUrl: 'http://localhost:8200' },
}),
commands: `java -javaagent:/path/to/elastic-apm-agent-<version>.jar \\
-Delastic.apm.service_name=my-application \\
-Delastic.apm.server_urls=${apmServerUrl || 'http://localhost:8200'} \\
-Delastic.apm.secret_token=${secretToken} \\
-Delastic.apm.application_packages=org.example \\
-jar my-application.jar`.split('\n'),
textPost: i18n.translate('apmOss.tutorial.javaClient.startApplication.textPost', {
defaultMessage:
'See the [documentation]({documentationLink}) for configuration options and advanced \
usage.',
values: {
documentationLink: '{config.docs.base_url}guide/en/apm/agent/java/current/index.html',
},
}),
},
];
export const createDotNetAgentInstructions = (apmServerUrl = '', secretToken = '') => [
{
title: i18n.translate('apmOss.tutorial.dotNetClient.download.title', {
defaultMessage: 'Download the APM agent',
}),
textPre: i18n.translate('apmOss.tutorial.dotNetClient.download.textPre', {
defaultMessage:
'Add the the agent package(s) from [NuGet]({allNuGetPackagesLink}) to your .NET application. There are multiple \
NuGet packages available for different use cases. \n\nFor an ASP.NET Core application with Entity Framework \
Core download the [Elastic.Apm.NetCoreAll]({netCoreAllApmPackageLink}) package. This package will automatically add every \
agent component to your application. \n\n In case you would like to to minimize the dependencies, you can use the \
[Elastic.Apm.AspNetCore]({aspNetCorePackageLink}) package for just \
ASP.NET Core monitoring or the [Elastic.Apm.EfCore]({efCorePackageLink}) package for just Entity Framework Core monitoring. \n\n \
In case you only want to use the public Agent API for manual instrumentation use the [Elastic.Apm]({elasticApmPackageLink}) package.',
values: {
allNuGetPackagesLink: 'https://www.nuget.org/packages?q=Elastic.apm',
netCoreAllApmPackageLink: 'https://www.nuget.org/packages/Elastic.Apm.NetCoreAll',
aspNetCorePackageLink: 'https://www.nuget.org/packages/Elastic.Apm.AspNetCore',
efCorePackageLink: 'https://www.nuget.org/packages/Elastic.Apm.EntityFrameworkCore',
elasticApmPackageLink: 'https://www.nuget.org/packages/Elastic.Apm',
},
}),
},
{
title: i18n.translate('apmOss.tutorial.dotNetClient.configureApplication.title', {
defaultMessage: 'Add the agent to the application',
}),
textPre: i18n.translate('apmOss.tutorial.dotNetClient.configureApplication.textPre', {
defaultMessage:
'In case of ASP.NET Core with the `Elastic.Apm.NetCoreAll` package, call the `UseAllElasticApm` \
method in the `Configure` method within the `Startup.cs` file.',
}),
commands: `public class Startup
{curlyOpen}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{curlyOpen}
app.UseAllElasticApm(Configuration);
//…rest of the method
{curlyClose}
//…rest of the class
{curlyClose}`.split('\n'),
textPost: i18n.translate('apmOss.tutorial.dotNetClient.configureApplication.textPost', {
defaultMessage:
'Passing an `IConfiguration` instance is optional and by doing so, the agent will read config settings through this \
`IConfiguration` instance (e.g. from the `appsettings.json` file).',
}),
},
{
title: i18n.translate('apmOss.tutorial.dotNetClient.configureAgent.title', {
defaultMessage: 'Sample appsettings.json file:',
}),
commands: `{curlyOpen}
"ElasticApm": {curlyOpen}
"SecretToken": "${secretToken}",
"ServerUrls": "${
apmServerUrl || 'http://localhost:8200'
}", //Set custom APM Server URL (default: http://localhost:8200)
"ServiceName" : "MyApp", //allowed characters: a-z, A-Z, 0-9, -, _, and space. Default is the entry assembly of the application
{curlyClose}
{curlyClose}`.split('\n'),
textPost: i18n.translate('apmOss.tutorial.dotNetClient.configureAgent.textPost', {
defaultMessage:
'In case you don’t pass an `IConfiguration` instance to the agent (e.g. in case of non ASP.NET Core applications) \
you can also configure the agent through environment variables. \n \
See [the documentation]({documentationLink}) for advanced usage.',
values: {
documentationLink:
'{config.docs.base_url}guide/en/apm/agent/dotnet/current/configuration.html',
},
}),
},
]; | the_stack |
import { Component, Input, OnInit, EventEmitter, Output, ViewChild, ElementRef } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';
import { LoggerService } from '../../../../chat21-core/providers/abstract/logger.service';
import { LoggerInstance } from '../../../../chat21-core/providers/logger/loggerInstance';
import { MIN_WIDTH_IMAGES } from '../../../utils/constants';
@Component({
selector: 'chat-conversation-attachment-preview',
templateUrl: './conversation-preview.component.html',
styleUrls: ['./conversation-preview.component.scss']
})
export class ConversationPreviewComponent implements OnInit {
@ViewChild('divPreview') public scrollMe: ElementRef;
@Input() textInputTextArea: string;
@Input() attachments: [{ file: Array<any>, metadata: {}}];
@Input() baseLocation: string;
@Input() translationMap: Map< string, string>;
@Input() stylesMap: Map<string, string>;
@Output() onSendAttachment = new EventEmitter<any>();
@Output() onCloseModalPreview = new EventEmitter();
public hideHeaderCloseButton: Boolean = false;
public arrayFiles = [];
public fileSelected: any;
public file_extension: string;
/**TEXT AREA PARAMETER */
// public textInputTextArea: string = '';
public isFilePendingToLoad: boolean = false;
public HEIGHT_DEFAULT = '20px';
public currentHeight: number = 0;
// ========= begin:: gestione scroll view messaggi ======= //
startScroll = true; // indica lo stato dello scroll: true/false -> è in movimento/ è fermo
idDivScroll = 'c21-contentScroll-preview'; // id div da scrollare
isScrolling = false;
isIE = /msie\s|trident\//i.test(window.navigator.userAgent);
firstScroll = true;
// ========= end:: gestione scroll view messaggi ======= //
private logger: LoggerService = LoggerInstance.getInstance()
constructor(private sanitizer: DomSanitizer) { }
ngOnInit() {
this.logger.log('[LOADER-PREVIEW-PAGE] Hello!', this.textInputTextArea);
this.setFocusOnId('chat21-main-message-context-preview')
// tslint:disable-next-line: prefer-for-of
// this.selectedFiles = this.files;
for (let i = 0; i < this.attachments.length; i++) {
this.logger.log('[LOADER-PREVIEW-PAGE] ngOnInit', this.attachments[i])
this.readAsDataURL(this.attachments[i]); //GABBBBBBB
//this.fileChange(this.files[i]);
}
}
/**
*
* @param metadata
* @return width, height
*/
getMetadataSize(metadata): {width, height} {
const MAX_WIDTH_IMAGES_PREVIEW = 230
const MAX_HEIGHT_IMAGES_PREIEW = 150
if(metadata.width === undefined){
metadata.width= MAX_WIDTH_IMAGES_PREVIEW
}
if(metadata.height === undefined){
metadata.height = MAX_WIDTH_IMAGES_PREVIEW
}
// const MAX_WIDTH_IMAGES = 300;
const sizeImage = {
width: metadata.width,
height: metadata.height
};
// SCALE IN WIDTH --> for horizontal images
if (metadata.width && metadata.width > MAX_WIDTH_IMAGES_PREVIEW) {
const ratio = (metadata['width'] / metadata['height']);
sizeImage.width = metadata.width = MAX_WIDTH_IMAGES_PREVIEW;
sizeImage.height = metadata.height = MAX_WIDTH_IMAGES_PREVIEW / ratio;
} else if(metadata.width && metadata.width <= 55){
const ratio = (metadata['width'] / metadata['height']);
sizeImage.width = MIN_WIDTH_IMAGES;
sizeImage.height = MIN_WIDTH_IMAGES / ratio;
}
// SCALE IN HEIGHT --> for vertical images
if(metadata.height && metadata.height > MAX_HEIGHT_IMAGES_PREIEW){
const ratio = (metadata['height'] / metadata['width']);
sizeImage.width = MAX_HEIGHT_IMAGES_PREIEW / ratio;
sizeImage.height = MAX_HEIGHT_IMAGES_PREIEW ;
}
return sizeImage; // h.toString();
}
readAsDataURL(attachment: any) {
this.logger.log('[LOADER-PREVIEW-PAGE] readAsDataURL file', attachment);
if((attachment.file.type.startsWith("image")) && (!attachment.file.type.includes("svg"))){
// ---------------------------------------------------------------------
// USE CASE IMAGE
// ---------------------------------------------------------------------
this.logger.log('[LOADER-PREVIEW-PAGE] - readAsDataURL - USE CASE IMAGE - IMAGE ', attachment);
if(!this.fileSelected){
this.fileSelected = this.attachments[0]
// const sizeImage = this.getMetadataSize(this.fileSelected.metadata)
// console.log('attachmenttttt', attachment, this.attachments[0])
// this.fileSelected.metadata.width = sizeImage.width
// this.fileSelected.metadata.height = sizeImage.height
}
} else if ((attachment.file.type.startsWith("image")) && (attachment.file.type.includes("svg"))){
// ---------------------------------------------------------------------
// USE CASE SVG
// ---------------------------------------------------------------------
this.logger.log('[LOADER-PREVIEW-PAGE] - readAsDataURL - USE CASE SVG - SVG ', attachment);
attachment.metadata.src = this.sanitizer.bypassSecurityTrustUrl(attachment.metadata.src)
if(!this.fileSelected){
this.fileSelected = this.attachments[0]
// const sizeImage = this.getMetadataSize(this.fileSelected.metadata)
// this.fileSelected.metadata.width = sizeImage.width
// this.fileSelected.metadata.height = sizeImage.height
}
}else if(!attachment.file.type.startsWith("image")){
// ---------------------------------------------------------------------
// USE CASE FILE
// ---------------------------------------------------------------------
this.logger.log('[LOADER-PREVIEW-PAGE] - readAsDataURL - USE CASE FILE - FILE ', attachment);
this.logger.log('[LOADER-PREVIEW-PAGE] - readAsDataURL - USE CASE FILE - FILE TYPE', attachment.file.type);
this.file_extension = attachment.file.name.substring(attachment.file.name.lastIndexOf('.') + 1, attachment.file.name.length) || attachment.file.name;
this.createFile(attachment);
}
}
async createFile(attachment) {
const that = this
let response = await fetch( that.baseLocation + '/assets/images/file-alt-solid.png');
let data = await response.blob();
let file_temp = new File([data], attachment.file.name);
this.logger.log('[LOADER-PREVIEW-PAGE] - createFile file - file', file_temp);
const reader = new FileReader();
reader.onloadend = () => {
const imageXLoad = new Image;
this.logger.debug('[LOADER-PREVIEW-PAGE] onload ', imageXLoad);
imageXLoad.src = reader.result.toString();
imageXLoad.title = attachment.file.name;
imageXLoad.onload = function () {
const metadata = {
'name': imageXLoad.title,
'src': that.sanitizer.bypassSecurityTrustUrl(imageXLoad.src),
'width': 80,
'height': 106,
'type': attachment.metadata.type,
'uid': attachment.metadata.uid
};
that.logger.debug('[LOADER-PREVIEW-PAGE] OK: ', metadata);
that.arrayFiles.push({metadata});
if (!that.fileSelected) {
that.fileSelected = {metadata};
}
};
}
reader.readAsDataURL(file_temp);
}
/** -------- TEXT AREA METHODS: BEGIN ----------- */
onTextAreaChange(){
this.resizeInputField();
this.resizeModalHeight()
// this.setWritingMessages(this.textInputTextArea)
}
setFocusOnId(id) {
setTimeout(function () {
const textarea = document.getElementById(id);
if (textarea) {
// that.logger.debug('[CONV-FOOTER] 1--------> FOCUSSSSSS : ', textarea);
textarea.setAttribute('value', ' ');
textarea.focus();
}
}, 500);
}
resizeInputField() {
try {
const target = document.getElementById('chat21-main-message-context-preview') as HTMLInputElement;
// that.logger.debug('[CONV-FOOTER] H:: this.textInputTextArea', (document.getElementById('chat21-main-message-context') as HTMLInputElement).value , target.style.height, target.scrollHeight, target.offsetHeight, target.clientHeight);
target.style.height = '100%';
if (target.value === '\n') {
target.value = '';
target.style.height = this.HEIGHT_DEFAULT;
} else if (target.scrollHeight > target.offsetHeight) {
target.style.height = target.scrollHeight + 2 + 'px';
target.style.minHeight = this.HEIGHT_DEFAULT;
} else {
// that.logger.debug('[CONV-FOOTER] PASSO 3');
target.style.height = this.HEIGHT_DEFAULT;
// segno sto scrivendo
// target.offsetHeight - 15 + 'px';
}
//this.setWritingMessages(target.value);
// this.onChangeTextArea.emit({textAreaEl: target, minHeightDefault: this.HEIGHT_DEFAULT})
} catch (e) {
this.logger.error('[LOADER-PREVIEW-PAGE] > Error :' + e);
}
// tslint:disable-next-line:max-line-length
// that.logger.debug('[CONV-FOOTER] H:: this.textInputTextArea', this.textInputTextArea, target.style.height, target.scrollHeight, target.offsetHeight, target.clientHeight);
}
resizeModalHeight(){
try{
const textarea = document.getElementById('chat21-main-message-context-preview') as HTMLInputElement;
const height = +textarea.style.height.substring(0, textarea.style.height.length - 2);
if(height > 20 && height < 110){
this.scrollMe.nativeElement.style.height = 'calc(39% + ' + (height - 20)+'px'
// document.getElementById('chat21-button-send-preview').style.right = '18px'
// this.scrollToBottom()
} else if(height <= 20) {
this.scrollMe.nativeElement.style.height = '39%'
} else if(height > 110){
// document.getElementById('chat21-button-send-preview').style.right = '18px'
}
} catch (e) {
this.logger.error('[LOADER-PREVIEW-PAGE] > Error :' + e);
}
}
private restoreTextArea() {
// that.logger.debug('[CONV-FOOTER] AppComponent:restoreTextArea::restoreTextArea');
this.resizeInputField();
const textArea = (<HTMLInputElement>document.getElementById('chat21-main-message-context-preview'));
this.textInputTextArea = ''; // clear the textarea
if (textArea) {
textArea.value = ''; // clear the textarea
textArea.placeholder = this.translationMap.get('LABEL_PLACEHOLDER'); // restore the placholder
this.logger.debug('[LOADER-PREVIEW-PAGE] AppComponent:restoreTextArea::restoreTextArea::textArea:', 'restored');
} else {
this.logger.error('[LOADER-PREVIEW-PAGE] restoreTextArea::textArea:', 'not restored');
}
this.setFocusOnId('chat21-main-message-context-preview');
}
/*
* @param event
*/
onkeypress(event) {
const keyCode = event.which || event.keyCode;
this.textInputTextArea = ((document.getElementById('chat21-main-message-context-preview') as HTMLInputElement).value);
// this.logger.debug('[CONV-FOOTER] onkeypress **************', this.textInputTextArea, keyCode]);
if (keyCode === 13) {
if (this.textInputTextArea && this.textInputTextArea.trim() !== '') {
// that.logger.debug('[CONV-FOOTER] sendMessage -> ', this.textInputTextArea);
// this.resizeInputField();
// this.messagingService.sendMessage(msg, TYPE_MSG_TEXT);
// this.setDepartment();
// this.textInputTextArea = replaceBr(this.textInputTextArea);
this.onSendAttachment.emit(this.textInputTextArea);
this.restoreTextArea();
}
} else if (keyCode === 9) {
// console.log('TAB pressedddd')
event.preventDefault();
}
}
onPaste(event){
this.resizeInputField();
this.logger.debug('[LOADER-PREVIEW] onPaste', event)
}
onClickClose(){
this.logger.debug('[LOADER-PREVIEW] onCLose')
this.onCloseModalPreview.emit()
}
onSendPressed(event){
this.logger.debug('[LOADER-PREVIEW] onSendPressed', event)
this.onSendAttachment.emit(this.textInputTextArea)
}
// =========== BEGIN: event emitter function ====== //
onImageRenderedFN(){
this.isFilePendingToLoad = false
}
// =========== END: event emitter function ====== //
} | the_stack |
import * as sdk from "../microsoft.cognitiveservices.speech.sdk";
import {
ConsoleLoggingListener,
WebsocketMessageAdapter,
} from "../src/common.browser/Exports";
import { ServiceRecognizerBase } from "../src/common.speech/Exports";
import {
Events,
EventType
} from "../src/common/Exports";
import { ByteBufferAudioFile } from "./ByteBufferAudioFile";
import { Settings } from "./Settings";
import { validateTelemetry } from "./TelemetryUtil";
import {
closeAsyncObjects,
WaitForCondition
} from "./Utilities";
import { WaveFileAudioInput } from "./WaveFileAudioInputStream";
import { AudioStreamFormatImpl } from "../src/sdk/Audio/AudioStreamFormat";
let objsToClose: any[];
beforeAll(() => {
// Override inputs, if necessary
Settings.LoadSettings();
Events.instance.attachListener(new ConsoleLoggingListener(EventType.Debug));
});
beforeEach(() => {
objsToClose = [];
// tslint:disable-next-line:no-console
console.info("------------------Starting test case: " + expect.getState().currentTestName + "-------------------------");
// tslint:disable-next-line:no-console
console.info("Sart Time: " + new Date(Date.now()).toLocaleString());
});
afterEach(async (done: jest.DoneCallback) => {
// tslint:disable-next-line:no-console
console.info("End Time: " + new Date(Date.now()).toLocaleString());
await closeAsyncObjects(objsToClose);
done();
});
const BuildRecognizerFromWaveFile: (speechConfig?: sdk.SpeechTranslationConfig, fileName?: string) => sdk.TranslationRecognizer = (speechConfig?: sdk.SpeechTranslationConfig, fileName?: string): sdk.TranslationRecognizer => {
let s: sdk.SpeechTranslationConfig = speechConfig;
if (s === undefined) {
s = BuildSpeechConfig();
// Since we're not going to return it, mark it for closure.
objsToClose.push(s);
}
const config: sdk.AudioConfig = WaveFileAudioInput.getAudioConfigFromFile(fileName === undefined ? Settings.WaveFile : fileName);
const language: string = Settings.WaveFileLanguage;
if (s.getProperty(sdk.PropertyId[sdk.PropertyId.SpeechServiceConnection_RecoLanguage]) === undefined) {
s.speechRecognitionLanguage = language;
}
s.addTargetLanguage("de-DE");
const r: sdk.TranslationRecognizer = new sdk.TranslationRecognizer(s, config);
expect(r).not.toBeUndefined();
return r;
};
const BuildSpeechConfig: () => sdk.SpeechTranslationConfig = (): sdk.SpeechTranslationConfig => {
const s: sdk.SpeechTranslationConfig = sdk.SpeechTranslationConfig.fromSubscription(Settings.SpeechSubscriptionKey, Settings.SpeechRegion);
expect(s).not.toBeUndefined();
return s;
};
const FIRST_EVENT_ID: number = 1;
const Recognizing: string = "Recognizing";
const Recognized: string = "Recognized";
const Canceled: string = "Canceled";
test("GetTargetLanguages", () => {
// tslint:disable-next-line:no-console
console.info("Name: GetTargetLanguages");
const r: sdk.TranslationRecognizer = BuildRecognizerFromWaveFile();
objsToClose.push(r);
expect(r.targetLanguages).not.toBeUndefined();
expect(r.targetLanguages).not.toBeNull();
expect(r.targetLanguages.length).toEqual(1);
expect(r.targetLanguages[0]).toEqual(r.properties.getProperty(sdk.PropertyId[sdk.PropertyId.SpeechServiceConnection_TranslationToLanguages]));
});
test.skip("GetOutputVoiceNameNoSetting", () => {
// tslint:disable-next-line:no-console
console.info("Name: GetOutputVoiceNameNoSetting");
const r: sdk.TranslationRecognizer = BuildRecognizerFromWaveFile();
objsToClose.push(r);
expect(r.voiceName).not.toBeUndefined();
});
test("GetParameters", () => {
// tslint:disable-next-line:no-console
console.info("Name: GetParameters");
const r: sdk.TranslationRecognizer = BuildRecognizerFromWaveFile();
objsToClose.push(r);
expect(r.properties).not.toBeUndefined();
expect(r.speechRecognitionLanguage).toEqual(r.properties.getProperty(sdk.PropertyId.SpeechServiceConnection_RecoLanguage, ""));
// TODO this cannot be true, right? comparing an array with a string parameter???
expect(r.targetLanguages.length).toEqual(1);
expect(r.targetLanguages[0]).toEqual(r.properties.getProperty(sdk.PropertyId.SpeechServiceConnection_TranslationToLanguages));
});
describe.each([false])("Service based tests", (forceNodeWebSocket: boolean) => {
beforeEach(() => {
// tslint:disable-next-line:no-console
console.info("forceNodeWebSocket: " + forceNodeWebSocket);
WebsocketMessageAdapter.forceNpmWebSocket = forceNodeWebSocket;
});
afterAll(() => {
WebsocketMessageAdapter.forceNpmWebSocket = false;
});
test("Translate Multiple Targets", (done: jest.DoneCallback) => {
// tslint:disable-next-line:no-console
console.info("Name: Translate Multiple Targets");
const s: sdk.SpeechTranslationConfig = BuildSpeechConfig();
objsToClose.push(s);
s.addTargetLanguage("en-US");
const r: sdk.TranslationRecognizer = BuildRecognizerFromWaveFile(s);
objsToClose.push(r);
r.canceled = (o: sdk.Recognizer, e: sdk.TranslationRecognitionCanceledEventArgs): void => {
try {
expect(e.errorDetails).toBeUndefined();
} catch (error) {
done.fail(error);
}
};
r.recognizeOnceAsync(
(res: sdk.TranslationRecognitionResult) => {
expect(res).not.toBeUndefined();
expect(res.errorDetails).toBeUndefined();
expect(sdk.ResultReason[res.reason]).toEqual(sdk.ResultReason[sdk.ResultReason.TranslatedSpeech]);
expect("Wie ist das Wetter?").toEqual(res.translations.get("de", ""));
expect("What's the weather like?").toEqual(res.translations.get("en", ""));
expect(res.translations.languages).toEqual(["en", "de"]);
expect(r.targetLanguages.length).toEqual(res.translations.languages.length);
r.removeTargetLanguage("de-DE");
expect(r.targetLanguages.includes("de-DE")).toBeFalsy();
r.addTargetLanguage("es-MX");
expect(r.targetLanguages.includes("es-MX")).toBeTruthy();
r.recognizeOnceAsync(
(secondRes: sdk.TranslationRecognitionResult) => {
expect(secondRes).not.toBeUndefined();
expect(secondRes.errorDetails).toBeUndefined();
expect(sdk.ResultReason[secondRes.reason]).toEqual(sdk.ResultReason[sdk.ResultReason.TranslatedSpeech]);
expect("What's the weather like?").toEqual(secondRes.translations.get("en", ""));
expect(secondRes.translations.languages.includes("es")).toBeTruthy();
expect(secondRes.translations.languages.includes("en")).toBeTruthy();
expect(secondRes.translations.languages.includes("de")).toBeFalsy();
expect("¿Cómo es el clima?").toEqual(secondRes.translations.get("es", ""));
done();
},
(error: string) => {
done.fail(error);
});
},
(error: string) => {
done.fail(error);
});
}, 15000);
test("Translate Bad Language", (done: jest.DoneCallback) => {
// tslint:disable-next-line:no-console
console.info("Name: Translate Bad Language");
const s: sdk.SpeechTranslationConfig = BuildSpeechConfig();
objsToClose.push(s);
s.addTargetLanguage("zz");
const r: sdk.TranslationRecognizer = BuildRecognizerFromWaveFile(s);
objsToClose.push(r);
expect(r).not.toBeUndefined();
expect(r instanceof sdk.Recognizer).toEqual(true);
r.synthesizing = ((o: sdk.Recognizer, e: sdk.TranslationSynthesisEventArgs) => {
try {
if (e.result.reason === sdk.ResultReason.Canceled) {
done.fail(sdk.ResultReason[e.result.reason]);
}
} catch (error) {
done.fail(error);
}
});
r.recognizeOnceAsync(
(res: sdk.TranslationRecognitionResult) => {
expect(res).not.toBeUndefined();
expect(res.errorDetails).not.toBeUndefined();
expect(sdk.ResultReason[res.reason]).toEqual(sdk.ResultReason[sdk.ResultReason.RecognizedSpeech]);
expect(res.translations).toBeUndefined();
expect(res.text).toEqual("What's the weather like?");
done();
},
(error: string) => {
done.fail(error);
});
});
test("RecognizeOnce Bad Language", (done: jest.DoneCallback) => {
// tslint:disable-next-line:no-console
console.info("Name: RecognizeOnce Bad Language");
const s: sdk.SpeechTranslationConfig = BuildSpeechConfig();
objsToClose.push(s);
s.speechRecognitionLanguage = "BadLanguage";
s.addTargetLanguage("en-US");
const r: sdk.TranslationRecognizer = BuildRecognizerFromWaveFile(s);
objsToClose.push(r);
let doneCount: number = 0;
r.canceled = (o: sdk.Recognizer, e: sdk.TranslationRecognitionCanceledEventArgs) => {
try {
expect(sdk.CancellationReason[e.reason]).toEqual(sdk.CancellationReason[sdk.CancellationReason.Error]);
expect(sdk.CancellationErrorCode[e.errorCode]).toEqual(sdk.CancellationErrorCode[sdk.CancellationErrorCode.ConnectionFailure]);
expect(e.errorDetails).toContain("1006");
doneCount++;
} catch (error) {
done.fail(error);
}
};
r.recognizeOnceAsync((result: sdk.TranslationRecognitionResult) => {
try {
const e: sdk.CancellationDetails = sdk.CancellationDetails.fromResult(result);
expect(sdk.CancellationReason[e.reason]).toEqual(sdk.CancellationReason[sdk.CancellationReason.Error]);
expect(sdk.CancellationErrorCode[e.ErrorCode]).toEqual(sdk.CancellationErrorCode[sdk.CancellationErrorCode.ConnectionFailure]);
expect(e.errorDetails).toContain("1006");
doneCount++;
} catch (error) {
done.fail(error);
}
});
WaitForCondition(() => (doneCount === 2), done);
});
test("fromEndPoint with Subscription key", (done: jest.DoneCallback) => {
// tslint:disable-next-line:no-console
console.info("Name: fromEndPoint with Subscription key");
const endpoint = "wss://" + Settings.SpeechRegion + ".s2s.speech.microsoft.com/speech/translation/cognitiveservices/v1";
const s: sdk.SpeechTranslationConfig = sdk.SpeechTranslationConfig.fromEndpoint(new URL(endpoint), Settings.SpeechSubscriptionKey);
objsToClose.push(s);
s.addTargetLanguage("de-DE");
s.speechRecognitionLanguage = "en-US";
const r: sdk.TranslationRecognizer = BuildRecognizerFromWaveFile(s);
objsToClose.push(r);
r.canceled = (o: sdk.TranslationRecognizer, e: sdk.TranslationRecognitionCanceledEventArgs): void => {
try {
expect(e.errorDetails).toBeUndefined();
} catch (error) {
done.fail(error);
}
};
r.recognizeOnceAsync(
(res: sdk.TranslationRecognitionResult) => {
expect(res).not.toBeUndefined();
expect(res.errorDetails).toBeUndefined();
expect(sdk.ResultReason[res.reason]).toEqual(sdk.ResultReason[sdk.ResultReason.TranslatedSpeech]);
expect(res.translations.get("de", undefined) !== undefined).toEqual(true);
expect("Wie ist das Wetter?").toEqual(res.translations.get("de", ""));
expect(res.text).toEqual("What's the weather like?");
done();
},
(error: string) => {
done.fail(error);
});
}, 12000);
test("fromV2EndPoint with Subscription key", (done: jest.DoneCallback) => {
// tslint:disable-next-line:no-console
console.info("Name: fromV2EndPoint with Subscription key");
const endpoint = "wss://" + Settings.SpeechRegion + ".stt.speech.microsoft.com/speech/universal/v2?SpeechContext-translation.targetLanguages=[\"de-de\"]";
const s: sdk.SpeechTranslationConfig = sdk.SpeechTranslationConfig.fromEndpoint(new URL(endpoint), Settings.SpeechSubscriptionKey);
objsToClose.push(s);
s.addTargetLanguage("de-DE");
s.speechRecognitionLanguage = "en-US";
s.setServiceProperty("language", "en-US", sdk.ServicePropertyChannel.UriQueryParameter);
s.setServiceProperty("SpeechContext-phraseDetection.interimResults", "true", sdk.ServicePropertyChannel.UriQueryParameter);
s.setServiceProperty("SpeechContext-phraseDetection.onInterim.action", "Translate", sdk.ServicePropertyChannel.UriQueryParameter);
s.setServiceProperty("SpeechContext-phraseDetection.onSuccess.action", "Translate", sdk.ServicePropertyChannel.UriQueryParameter);
s.setServiceProperty("SpeechContext-phraseOutput.interimResults.resultType", "Hypothesis", sdk.ServicePropertyChannel.UriQueryParameter);
s.setServiceProperty("SpeechContext-translation.onSuccess.action", "None", sdk.ServicePropertyChannel.UriQueryParameter);
s.setServiceProperty("SpeechContext-translation.output.includePassThroughResults", "true", sdk.ServicePropertyChannel.UriQueryParameter);
s.setServiceProperty("SpeechContext-translation.output.interimResults.mode", "Always", sdk.ServicePropertyChannel.UriQueryParameter);
const r: sdk.TranslationRecognizer = BuildRecognizerFromWaveFile(s);
objsToClose.push(r);
r.canceled = (o: sdk.TranslationRecognizer, e: sdk.TranslationRecognitionCanceledEventArgs): void => {
try {
expect(e.errorDetails).toBeUndefined();
} catch (error) {
done.fail(error);
}
};
r.recognizeOnceAsync(
(res: sdk.TranslationRecognitionResult) => {
expect(res).not.toBeUndefined();
expect(res.errorDetails).toBeUndefined();
expect(sdk.ResultReason[res.reason]).toEqual(sdk.ResultReason[sdk.ResultReason.TranslatedSpeech]);
expect(res.translations.get("de-de", undefined) !== undefined).toEqual(true);
expect("Wie ist das Wetter?").toEqual(res.translations.get("de-de", ""));
expect(res.text).toEqual("What's the weather like?");
done();
},
(error: string) => {
done.fail(error);
});
}, 12000);
}); | the_stack |
import { expect } from "chai";
import * as sinon from "sinon";
import * as React from "react";
import { fireEvent, render } from "@testing-library/react";
import { MultiValueFilter } from "../../../../components-react/table/columnfiltering/multi-value-filter/MultiValueFilter";
import { ReactDataGridColumn, TableColumn } from "../../../../components-react/table/component/TableColumn";
import { FilterableColumn, TableDistinctValue } from "../../../../components-react/table/columnfiltering/ColumnFiltering";
import { ColumnDescription } from "../../../../components-react/table/TableDataProvider";
import { TestFilterableTable } from "../../../TestUtils";
// cSpell:ignore columnfiltering
describe("MultiValueFilter", () => {
let fakeTimers: sinon.SinonFakeTimers;
const columnDescriptions: ColumnDescription[] = [
{
key: "multi-value1",
label: "Multi-Value1",
showDistinctValueFilters: true,
showFieldFilters: true,
filterCaseSensitive: false,
},
{
key: "multi-value2",
label: "Multi-Value2",
showDistinctValueFilters: true,
showFieldFilters: true,
filterCaseSensitive: true,
},
];
const reactDataGridColumns: ReactDataGridColumn[] = [
{
key: columnDescriptions[0].key,
name: columnDescriptions[0].label,
filterRenderer: MultiValueFilter,
filterable: true,
},
{
key: columnDescriptions[1].key,
name: columnDescriptions[1].label,
filterRenderer: MultiValueFilter,
filterable: true,
},
];
const testTable = new TestFilterableTable(columnDescriptions);
const filterableColumn0: FilterableColumn = new TableColumn(testTable, columnDescriptions[0], reactDataGridColumns[0]);
reactDataGridColumns[0].filterableColumn = filterableColumn0;
const filterableColumn1: FilterableColumn = new TableColumn(testTable, columnDescriptions[1], reactDataGridColumns[1]);
reactDataGridColumns[1].filterableColumn = filterableColumn1;
reactDataGridColumns[1].filterableColumn.columnFilterDescriptor.distinctFilter.addDistinctValue("multi-value 1");
const filterValueCount = 15;
const getValidFilterValues = (_columnKey: string): any[] => {
const values: TableDistinctValue[] = [];
for (let index = 0; index < filterValueCount; index++) {
values.push({ value: `multi-value ${index + 1}`, label: `Multi-Value ${index + 1}` });
}
return values;
};
const testChecked = (cbs: HTMLInputElement[], testResult: number): void => {
let checked = 0;
cbs.forEach((cb) => { if (cb.checked) checked++; });
expect(checked).to.eq(testResult);
};
beforeEach(() => {
fakeTimers = sinon.useFakeTimers();
});
afterEach(() => {
fakeTimers.restore();
});
it("renders filter Ui", () => {
const spy = sinon.spy();
const component = render(<MultiValueFilter onChange={spy} column={reactDataGridColumns[0]} getValidFilterValues={getValidFilterValues} />);
expect(component.getByTestId("components-multi-value-filter")).to.exist;
});
it("clicking opens popup", () => {
const spy = sinon.spy();
const component = render(<MultiValueFilter onChange={spy} column={reactDataGridColumns[0]} getValidFilterValues={getValidFilterValues} />);
expect(component.getByTestId("components-multi-value-filter")).to.exist;
const button = component.container.querySelector(".components-popup-button");
expect(button).to.exist;
fireEvent.click(button!);
expect(component.queryAllByTestId("core-chk-listboxitem-checkbox").length).to.eq(filterValueCount);
});
it("entering Search text limits values shown", async () => {
const spy = sinon.spy();
const component = render(<MultiValueFilter onChange={spy} column={reactDataGridColumns[0]} getValidFilterValues={getValidFilterValues} />);
expect(component.getByTestId("components-multi-value-filter")).to.exist;
const button = component.container.querySelector(".components-popup-button");
expect(button).to.exist;
fireEvent.click(button!);
const searchBox = component.queryByTestId("core-searchbox-input") as HTMLInputElement;
expect(searchBox).to.exist;
let searchText = "6";
fireEvent.change(searchBox, { target: { value: searchText } });
expect(searchBox.value).to.be.equal(searchText);
await fakeTimers.tickAsync(500);
expect(component.queryAllByTestId("core-chk-listboxitem-checkbox").length).to.eq(1);
searchText = "multi-value";
fireEvent.change(searchBox, { target: { value: searchText } });
expect(searchBox.value).to.be.equal(searchText);
await fakeTimers.tickAsync(500);
expect(component.queryAllByTestId("core-chk-listboxitem-checkbox").length).to.eq(filterValueCount);
});
it("entering Search text limits values shown for caseSensitive", async () => {
const spy = sinon.spy();
const component = render(<MultiValueFilter onChange={spy} column={reactDataGridColumns[1]} getValidFilterValues={getValidFilterValues} />);
expect(component.getByTestId("components-multi-value-filter")).to.exist;
const button = component.container.querySelector(".components-popup-button");
expect(button).to.exist;
fireEvent.click(button!);
const checkboxes = component.queryAllByTestId("core-chk-listboxitem-checkbox") as HTMLInputElement[];
expect(checkboxes.length).to.eq(filterValueCount);
testChecked(checkboxes, 1); // Because we populated the distinctFilter with one entry for reactDataGridColumns[1]
const searchBox = component.queryByTestId("core-searchbox-input") as HTMLInputElement;
expect(searchBox).to.exist;
let searchText = "multi-value";
fireEvent.change(searchBox, { target: { value: searchText } });
expect(searchBox.value).to.be.equal(searchText);
await fakeTimers.tickAsync(500);
expect(component.queryAllByTestId("core-chk-listboxitem-checkbox").length).to.eq(0);
searchText = "Multi-Value";
fireEvent.change(searchBox, { target: { value: searchText } });
expect(searchBox.value).to.be.equal(searchText);
await fakeTimers.tickAsync(500);
expect(component.queryAllByTestId("core-chk-listboxitem-checkbox").length).to.eq(filterValueCount);
});
it("checking a value then pressing Filter will filter results", async () => {
const spy = sinon.spy();
const component = render(<MultiValueFilter onChange={spy} column={reactDataGridColumns[0]} getValidFilterValues={getValidFilterValues} />);
expect(component.getByTestId("components-multi-value-filter")).to.exist;
const button = component.container.querySelector(".components-popup-button");
expect(button).to.exist;
fireEvent.click(button!);
const checkboxes = component.queryAllByTestId("core-chk-listboxitem-checkbox");
expect(checkboxes.length).to.eq(filterValueCount);
fireEvent.click(checkboxes[0]);
const filterButton = component.getByTestId("components-multi-value-button-filter");
fireEvent.click(filterButton);
spy.calledOnce.should.true;
});
it("checking multiple values then pressing Filter will filter results", async () => {
const spy = sinon.spy();
const component = render(<MultiValueFilter onChange={spy} column={reactDataGridColumns[0]} getValidFilterValues={getValidFilterValues} />);
expect(component.getByTestId("components-multi-value-filter")).to.exist;
const button = component.container.querySelector(".components-popup-button");
expect(button).to.exist;
fireEvent.click(button!);
const checkboxes = component.queryAllByTestId("core-chk-listboxitem-checkbox");
expect(checkboxes.length).to.eq(filterValueCount);
// Test with less than 10
const testCount = 4;
for (let index = 0; index < testCount; index++) {
fireEvent.click(checkboxes[index]);
}
const filterButton = component.getByTestId("components-multi-value-button-filter");
fireEvent.click(filterButton);
spy.calledOnce.should.true;
});
it("checking multiple values then pressing Filter will filter results", async () => {
const spy = sinon.spy();
const component = render(<MultiValueFilter onChange={spy} column={reactDataGridColumns[0]} getValidFilterValues={getValidFilterValues} />);
expect(component.getByTestId("components-multi-value-filter")).to.exist;
const button = component.container.querySelector(".components-popup-button");
expect(button).to.exist;
fireEvent.click(button!);
const checkboxes = component.queryAllByTestId("core-chk-listboxitem-checkbox");
expect(checkboxes.length).to.eq(filterValueCount);
// Test with more than 10
const testCount = 12;
for (let index = 0; index < testCount; index++) {
fireEvent.click(checkboxes[index]);
}
const filterButton = component.getByTestId("components-multi-value-button-filter");
fireEvent.click(filterButton);
spy.calledOnce.should.true;
});
it("checking a value then pressing Clear will uncheck all", async () => {
const spy = sinon.spy();
const component = render(<MultiValueFilter onChange={spy} column={reactDataGridColumns[0]} getValidFilterValues={getValidFilterValues} />);
expect(component.getByTestId("components-multi-value-filter")).to.exist;
const button = component.container.querySelector(".components-popup-button");
expect(button).to.exist;
fireEvent.click(button!);
const checkboxes = component.queryAllByTestId("core-chk-listboxitem-checkbox") as HTMLInputElement[];
expect(checkboxes.length).to.eq(filterValueCount);
testChecked(checkboxes, 0);
fireEvent.click(checkboxes[0]);
fireEvent.click(checkboxes[1]);
testChecked(checkboxes, 2);
fireEvent.click(checkboxes[1]);
testChecked(checkboxes, 1);
const clearButton = component.getByTestId("components-multi-value-button-clear");
fireEvent.click(clearButton);
testChecked(checkboxes, 0);
const filterButton = component.getByTestId("components-multi-value-button-filter");
fireEvent.click(filterButton);
spy.calledOnce.should.true;
});
it("pressing Cancel will not filter results", async () => {
const spy = sinon.spy();
const component = render(<MultiValueFilter onChange={spy} column={reactDataGridColumns[0]} getValidFilterValues={getValidFilterValues} />);
expect(component.getByTestId("components-multi-value-filter")).to.exist;
const button = component.container.querySelector(".components-popup-button");
expect(button).to.exist;
fireEvent.click(button!);
const cancelButton = component.getByTestId("components-multi-value-button-cancel");
fireEvent.click(cancelButton);
spy.calledOnce.should.false;
});
it("clicking SelectAll will select all checkboxes", async () => {
const spy = sinon.spy();
const component = render(<MultiValueFilter onChange={spy} column={reactDataGridColumns[0]} getValidFilterValues={getValidFilterValues} />);
expect(component.getByTestId("components-multi-value-filter")).to.exist;
const button = component.container.querySelector(".components-popup-button");
expect(button).to.exist;
fireEvent.click(button!);
const checkboxes = component.queryAllByTestId("core-chk-listboxitem-checkbox") as HTMLInputElement[];
expect(checkboxes.length).to.eq(filterValueCount);
testChecked(checkboxes, 0);
const selectAllButton = component.getByTestId("components-multi-value-filter-selectAll");
fireEvent.click(selectAllButton);
testChecked(checkboxes, filterValueCount);
fireEvent.click(checkboxes[0]);
testChecked(checkboxes, filterValueCount - 1);
fireEvent.click(selectAllButton);
testChecked(checkboxes, filterValueCount);
fireEvent.click(checkboxes[0]);
testChecked(checkboxes, filterValueCount - 1);
fireEvent.click(checkboxes[0]);
testChecked(checkboxes, filterValueCount);
fireEvent.click(selectAllButton);
testChecked(checkboxes, 0);
fireEvent.click(checkboxes[0]);
testChecked(checkboxes, 1);
fireEvent.click(checkboxes[0]);
testChecked(checkboxes, 0);
});
}); | the_stack |
import { ServiceClientOptions } from "@azure/ms-rest-js";
import * as msRest from "@azure/ms-rest-js";
/**
* @interface
* An interface representing MetricsPostBodySchemaParameters.
* The parameters for a single metrics query
*
*/
export interface MetricsPostBodySchemaParameters {
/**
* @member {MetricId} metricId Possible values include: 'requests/count',
* 'requests/duration', 'requests/failed', 'users/count',
* 'users/authenticated', 'pageViews/count', 'pageViews/duration',
* 'client/processingDuration', 'client/receiveDuration',
* 'client/networkDuration', 'client/sendDuration', 'client/totalDuration',
* 'dependencies/count', 'dependencies/failed', 'dependencies/duration',
* 'exceptions/count', 'exceptions/browser', 'exceptions/server',
* 'sessions/count', 'performanceCounters/requestExecutionTime',
* 'performanceCounters/requestsPerSecond',
* 'performanceCounters/requestsInQueue',
* 'performanceCounters/memoryAvailableBytes',
* 'performanceCounters/exceptionsPerSecond',
* 'performanceCounters/processCpuPercentage',
* 'performanceCounters/processIOBytesPerSecond',
* 'performanceCounters/processPrivateBytes',
* 'performanceCounters/processorCpuPercentage',
* 'availabilityResults/availabilityPercentage',
* 'availabilityResults/duration', 'billing/telemetryCount',
* 'customEvents/count'
*/
metricId: MetricId;
/**
* @member {string} [timespan]
*/
timespan?: string;
/**
* @member {MetricsAggregation[]} [aggregation]
*/
aggregation?: MetricsAggregation[];
/**
* @member {string} [interval]
*/
interval?: string;
/**
* @member {MetricsSegment[]} [segment]
*/
segment?: MetricsSegment[];
/**
* @member {number} [top]
*/
top?: number;
/**
* @member {string} [orderby]
*/
orderby?: string;
/**
* @member {string} [filter]
*/
filter?: string;
}
/**
* @interface
* An interface representing MetricsPostBodySchema.
* A metric request
*
*/
export interface MetricsPostBodySchema {
/**
* @member {string} id An identifier for this query. Must be unique within
* the post body of the request. This identifier will be the 'id' property
* of the response object representing this query.
*/
id: string;
/**
* @member {MetricsPostBodySchemaParameters} parameters The parameters for a
* single metrics query
*/
parameters: MetricsPostBodySchemaParameters;
}
/**
* @interface
* An interface representing MetricsSegmentInfo.
* A metric segment
*
*/
export interface MetricsSegmentInfo {
/**
* @member {Date} [start] Start time of the metric segment (only when an
* interval was specified).
*/
start?: Date;
/**
* @member {Date} [end] Start time of the metric segment (only when an
* interval was specified).
*/
end?: Date;
/**
* @member {MetricsSegmentInfo[]} [segments] Segmented metric data (if
* further segmented).
*/
segments?: MetricsSegmentInfo[];
/**
* @property Describes unknown properties. The value of an unknown property
* can be of "any" type.
*/
[property: string]: any;
}
/**
* @interface
* An interface representing MetricsResultInfo.
* A metric result data.
*
*/
export interface MetricsResultInfo {
/**
* @member {Date} [start] Start time of the metric.
*/
start?: Date;
/**
* @member {Date} [end] Start time of the metric.
*/
end?: Date;
/**
* @member {string} [interval] The interval used to segment the metric data.
*/
interval?: string;
/**
* @member {MetricsSegmentInfo[]} [segments] Segmented metric data (if
* segmented).
*/
segments?: MetricsSegmentInfo[];
/**
* @property Describes unknown properties. The value of an unknown property
* can be of "any" type.
*/
[property: string]: any;
}
/**
* @interface
* An interface representing MetricsResult.
* A metric result.
*
*/
export interface MetricsResult {
/**
* @member {MetricsResultInfo} [value]
*/
value?: MetricsResultInfo;
}
/**
* @interface
* An interface representing MetricsResultsItem.
*/
export interface MetricsResultsItem {
/**
* @member {string} id The specified ID for this metric.
*/
id: string;
/**
* @member {number} status The HTTP status code of this metric query.
*/
status: number;
/**
* @member {MetricsResult} body The results of this metric query.
*/
body: MetricsResult;
}
/**
* @interface
* An interface representing ErrorDetail.
* @summary Error details.
*
*/
export interface ErrorDetail {
/**
* @member {string} code The error's code.
*/
code: string;
/**
* @member {string} message A human readable error message.
*/
message: string;
/**
* @member {string} [target] Indicates which property in the request is
* responsible for the error.
*/
target?: string;
/**
* @member {string} [value] Indicates which value in 'target' is responsible
* for the error.
*/
value?: string;
/**
* @member {string[]} [resources] Indicates resources which were responsible
* for the error.
*/
resources?: string[];
/**
* @member {any} [additionalProperties]
*/
additionalProperties?: any;
}
/**
* @interface
* An interface representing ErrorInfo.
* @summary The code and message for an error.
*
*/
export interface ErrorInfo {
/**
* @member {string} code A machine readable error code.
*/
code: string;
/**
* @member {string} message A human readable error message.
*/
message: string;
/**
* @member {ErrorDetail[]} [details] error details.
*/
details?: ErrorDetail[];
/**
* @member {ErrorInfo} [innererror] Inner error details if they exist.
*/
innererror?: ErrorInfo;
/**
* @member {any} [additionalProperties]
*/
additionalProperties?: any;
}
/**
* @interface
* An interface representing EventsResultDataCustomDimensions.
* Custom dimensions of the event
*
*/
export interface EventsResultDataCustomDimensions {
/**
* @member {any} [additionalProperties]
*/
additionalProperties?: any;
}
/**
* @interface
* An interface representing EventsResultDataCustomMeasurements.
* Custom measurements of the event
*
*/
export interface EventsResultDataCustomMeasurements {
/**
* @member {any} [additionalProperties]
*/
additionalProperties?: any;
}
/**
* @interface
* An interface representing EventsOperationInfo.
* Operation info for an event result
*
*/
export interface EventsOperationInfo {
/**
* @member {string} [name] Name of the operation
*/
name?: string;
/**
* @member {string} [id] ID of the operation
*/
id?: string;
/**
* @member {string} [parentId] Parent ID of the operation
*/
parentId?: string;
/**
* @member {string} [syntheticSource] Synthetic source of the operation
*/
syntheticSource?: string;
}
/**
* @interface
* An interface representing EventsSessionInfo.
* Session info for an event result
*
*/
export interface EventsSessionInfo {
/**
* @member {string} [id] ID of the session
*/
id?: string;
}
/**
* @interface
* An interface representing EventsUserInfo.
* User info for an event result
*
*/
export interface EventsUserInfo {
/**
* @member {string} [id] ID of the user
*/
id?: string;
/**
* @member {string} [accountId] Account ID of the user
*/
accountId?: string;
/**
* @member {string} [authenticatedId] Authenticated ID of the user
*/
authenticatedId?: string;
}
/**
* @interface
* An interface representing EventsCloudInfo.
* Cloud info for an event result
*
*/
export interface EventsCloudInfo {
/**
* @member {string} [roleName] Role name of the cloud
*/
roleName?: string;
/**
* @member {string} [roleInstance] Role instance of the cloud
*/
roleInstance?: string;
}
/**
* @interface
* An interface representing EventsAiInfo.
* AI related application info for an event result
*
*/
export interface EventsAiInfo {
/**
* @member {string} [iKey] iKey of the app
*/
iKey?: string;
/**
* @member {string} [appName] Name of the application
*/
appName?: string;
/**
* @member {string} [appId] ID of the application
*/
appId?: string;
/**
* @member {string} [sdkVersion] SDK version of the application
*/
sdkVersion?: string;
}
/**
* @interface
* An interface representing EventsApplicationInfo.
* Application info for an event result
*
*/
export interface EventsApplicationInfo {
/**
* @member {string} [version] Version of the application
*/
version?: string;
}
/**
* @interface
* An interface representing EventsClientInfo.
* Client info for an event result
*
*/
export interface EventsClientInfo {
/**
* @member {string} [model] Model of the client
*/
model?: string;
/**
* @member {string} [os] Operating system of the client
*/
os?: string;
/**
* @member {string} [type] Type of the client
*/
type?: string;
/**
* @member {string} [browser] Browser of the client
*/
browser?: string;
/**
* @member {string} [ip] IP address of the client
*/
ip?: string;
/**
* @member {string} [city] City of the client
*/
city?: string;
/**
* @member {string} [stateOrProvince] State or province of the client
*/
stateOrProvince?: string;
/**
* @member {string} [countryOrRegion] Country or region of the client
*/
countryOrRegion?: string;
}
/**
* Contains the possible cases for EventsResultData.
*/
export type EventsResultDataUnion = EventsResultData | EventsTraceResult | EventsCustomEventResult | EventsPageViewResult | EventsBrowserTimingResult | EventsRequestResult | EventsDependencyResult | EventsExceptionResult | EventsAvailabilityResultResult | EventsPerformanceCounterResult | EventsCustomMetricResult;
/**
* @interface
* An interface representing EventsResultData.
* Events query result data.
*
*/
export interface EventsResultData {
/**
* @member {string} type Polymorphic Discriminator
*/
type: "eventsResultData";
/**
* @member {string} [id] The unique ID for this event.
*/
id?: string;
/**
* @member {number} [count] Count of the event
*/
count?: number;
/**
* @member {Date} [timestamp] Timestamp of the event
*/
timestamp?: Date;
/**
* @member {EventsResultDataCustomDimensions} [customDimensions] Custom
* dimensions of the event
*/
customDimensions?: EventsResultDataCustomDimensions;
/**
* @member {EventsResultDataCustomMeasurements} [customMeasurements] Custom
* measurements of the event
*/
customMeasurements?: EventsResultDataCustomMeasurements;
/**
* @member {EventsOperationInfo} [operation] Operation info of the event
*/
operation?: EventsOperationInfo;
/**
* @member {EventsSessionInfo} [session] Session info of the event
*/
session?: EventsSessionInfo;
/**
* @member {EventsUserInfo} [user] User info of the event
*/
user?: EventsUserInfo;
/**
* @member {EventsCloudInfo} [cloud] Cloud info of the event
*/
cloud?: EventsCloudInfo;
/**
* @member {EventsAiInfo} [ai] AI info of the event
*/
ai?: EventsAiInfo;
/**
* @member {EventsApplicationInfo} [application] Application info of the
* event
*/
application?: EventsApplicationInfo;
/**
* @member {EventsClientInfo} [client] Client info of the event
*/
client?: EventsClientInfo;
}
/**
* @interface
* An interface representing EventsResults.
* An events query result.
*
*/
export interface EventsResults {
/**
* @member {string} [odatacontext] OData context metadata endpoint for this
* response
*/
odatacontext?: string;
/**
* @member {ErrorInfo[]} [aimessages] OData messages for this response.
*/
aimessages?: ErrorInfo[];
/**
* @member {EventsResultDataUnion[]} [value] Contents of the events query
* result.
*/
value?: EventsResultDataUnion[];
}
/**
* @interface
* An interface representing EventsResult.
* An event query result.
*
*/
export interface EventsResult {
/**
* @member {ErrorInfo[]} [aimessages] OData messages for this response.
*/
aimessages?: ErrorInfo[];
/**
* @member {EventsResultDataUnion} [value]
*/
value?: EventsResultDataUnion;
}
/**
* @interface
* An interface representing EventsTraceInfo.
* The trace information
*
*/
export interface EventsTraceInfo {
/**
* @member {string} [message] The trace message
*/
message?: string;
/**
* @member {number} [severityLevel] The trace severity level
*/
severityLevel?: number;
}
/**
* @interface
* An interface representing EventsTraceResult.
* A trace result
*
*/
export interface EventsTraceResult {
/**
* @member {string} type Polymorphic Discriminator
*/
type: "trace";
/**
* @member {string} [id] The unique ID for this event.
*/
id?: string;
/**
* @member {number} [count] Count of the event
*/
count?: number;
/**
* @member {Date} [timestamp] Timestamp of the event
*/
timestamp?: Date;
/**
* @member {EventsResultDataCustomDimensions} [customDimensions] Custom
* dimensions of the event
*/
customDimensions?: EventsResultDataCustomDimensions;
/**
* @member {EventsResultDataCustomMeasurements} [customMeasurements] Custom
* measurements of the event
*/
customMeasurements?: EventsResultDataCustomMeasurements;
/**
* @member {EventsOperationInfo} [operation] Operation info of the event
*/
operation?: EventsOperationInfo;
/**
* @member {EventsSessionInfo} [session] Session info of the event
*/
session?: EventsSessionInfo;
/**
* @member {EventsUserInfo} [user] User info of the event
*/
user?: EventsUserInfo;
/**
* @member {EventsCloudInfo} [cloud] Cloud info of the event
*/
cloud?: EventsCloudInfo;
/**
* @member {EventsAiInfo} [ai] AI info of the event
*/
ai?: EventsAiInfo;
/**
* @member {EventsApplicationInfo} [application] Application info of the
* event
*/
application?: EventsApplicationInfo;
/**
* @member {EventsClientInfo} [client] Client info of the event
*/
client?: EventsClientInfo;
/**
* @member {EventsTraceInfo} [trace]
*/
trace?: EventsTraceInfo;
}
/**
* @interface
* An interface representing EventsCustomEventInfo.
* The custom event information
*
*/
export interface EventsCustomEventInfo {
/**
* @member {string} [name] The name of the custom event
*/
name?: string;
}
/**
* @interface
* An interface representing EventsCustomEventResult.
* A custom event result
*
*/
export interface EventsCustomEventResult {
/**
* @member {string} type Polymorphic Discriminator
*/
type: "customEvent";
/**
* @member {string} [id] The unique ID for this event.
*/
id?: string;
/**
* @member {number} [count] Count of the event
*/
count?: number;
/**
* @member {Date} [timestamp] Timestamp of the event
*/
timestamp?: Date;
/**
* @member {EventsResultDataCustomDimensions} [customDimensions] Custom
* dimensions of the event
*/
customDimensions?: EventsResultDataCustomDimensions;
/**
* @member {EventsResultDataCustomMeasurements} [customMeasurements] Custom
* measurements of the event
*/
customMeasurements?: EventsResultDataCustomMeasurements;
/**
* @member {EventsOperationInfo} [operation] Operation info of the event
*/
operation?: EventsOperationInfo;
/**
* @member {EventsSessionInfo} [session] Session info of the event
*/
session?: EventsSessionInfo;
/**
* @member {EventsUserInfo} [user] User info of the event
*/
user?: EventsUserInfo;
/**
* @member {EventsCloudInfo} [cloud] Cloud info of the event
*/
cloud?: EventsCloudInfo;
/**
* @member {EventsAiInfo} [ai] AI info of the event
*/
ai?: EventsAiInfo;
/**
* @member {EventsApplicationInfo} [application] Application info of the
* event
*/
application?: EventsApplicationInfo;
/**
* @member {EventsClientInfo} [client] Client info of the event
*/
client?: EventsClientInfo;
/**
* @member {EventsCustomEventInfo} [customEvent]
*/
customEvent?: EventsCustomEventInfo;
}
/**
* @interface
* An interface representing EventsPageViewInfo.
* The page view information
*
*/
export interface EventsPageViewInfo {
/**
* @member {string} [name] The name of the page
*/
name?: string;
/**
* @member {string} [url] The URL of the page
*/
url?: string;
/**
* @member {string} [duration] The duration of the page view
*/
duration?: string;
/**
* @member {string} [performanceBucket] The performance bucket of the page
* view
*/
performanceBucket?: string;
}
/**
* @interface
* An interface representing EventsPageViewResult.
* A page view result
*
*/
export interface EventsPageViewResult {
/**
* @member {string} type Polymorphic Discriminator
*/
type: "pageView";
/**
* @member {string} [id] The unique ID for this event.
*/
id?: string;
/**
* @member {number} [count] Count of the event
*/
count?: number;
/**
* @member {Date} [timestamp] Timestamp of the event
*/
timestamp?: Date;
/**
* @member {EventsResultDataCustomDimensions} [customDimensions] Custom
* dimensions of the event
*/
customDimensions?: EventsResultDataCustomDimensions;
/**
* @member {EventsResultDataCustomMeasurements} [customMeasurements] Custom
* measurements of the event
*/
customMeasurements?: EventsResultDataCustomMeasurements;
/**
* @member {EventsOperationInfo} [operation] Operation info of the event
*/
operation?: EventsOperationInfo;
/**
* @member {EventsSessionInfo} [session] Session info of the event
*/
session?: EventsSessionInfo;
/**
* @member {EventsUserInfo} [user] User info of the event
*/
user?: EventsUserInfo;
/**
* @member {EventsCloudInfo} [cloud] Cloud info of the event
*/
cloud?: EventsCloudInfo;
/**
* @member {EventsAiInfo} [ai] AI info of the event
*/
ai?: EventsAiInfo;
/**
* @member {EventsApplicationInfo} [application] Application info of the
* event
*/
application?: EventsApplicationInfo;
/**
* @member {EventsClientInfo} [client] Client info of the event
*/
client?: EventsClientInfo;
/**
* @member {EventsPageViewInfo} [pageView]
*/
pageView?: EventsPageViewInfo;
}
/**
* @interface
* An interface representing EventsBrowserTimingInfo.
* The browser timing information
*
*/
export interface EventsBrowserTimingInfo {
/**
* @member {string} [urlPath] The path of the URL
*/
urlPath?: string;
/**
* @member {string} [urlHost] The host of the URL
*/
urlHost?: string;
/**
* @member {string} [name] The name of the page
*/
name?: string;
/**
* @member {string} [url] The url of the page
*/
url?: string;
/**
* @member {number} [totalDuration] The total duration of the load
*/
totalDuration?: number;
/**
* @member {string} [performanceBucket] The performance bucket of the load
*/
performanceBucket?: string;
/**
* @member {number} [networkDuration] The network duration of the load
*/
networkDuration?: number;
/**
* @member {number} [sendDuration] The send duration of the load
*/
sendDuration?: number;
/**
* @member {number} [receiveDuration] The receive duration of the load
*/
receiveDuration?: number;
/**
* @member {number} [processingDuration] The processing duration of the load
*/
processingDuration?: number;
}
/**
* @interface
* An interface representing EventsClientPerformanceInfo.
* Client performance information
*
*/
export interface EventsClientPerformanceInfo {
/**
* @member {string} [name] The name of the client performance
*/
name?: string;
}
/**
* @interface
* An interface representing EventsBrowserTimingResult.
* A browser timing result
*
*/
export interface EventsBrowserTimingResult {
/**
* @member {string} type Polymorphic Discriminator
*/
type: "browserTiming";
/**
* @member {string} [id] The unique ID for this event.
*/
id?: string;
/**
* @member {number} [count] Count of the event
*/
count?: number;
/**
* @member {Date} [timestamp] Timestamp of the event
*/
timestamp?: Date;
/**
* @member {EventsResultDataCustomDimensions} [customDimensions] Custom
* dimensions of the event
*/
customDimensions?: EventsResultDataCustomDimensions;
/**
* @member {EventsResultDataCustomMeasurements} [customMeasurements] Custom
* measurements of the event
*/
customMeasurements?: EventsResultDataCustomMeasurements;
/**
* @member {EventsOperationInfo} [operation] Operation info of the event
*/
operation?: EventsOperationInfo;
/**
* @member {EventsSessionInfo} [session] Session info of the event
*/
session?: EventsSessionInfo;
/**
* @member {EventsUserInfo} [user] User info of the event
*/
user?: EventsUserInfo;
/**
* @member {EventsCloudInfo} [cloud] Cloud info of the event
*/
cloud?: EventsCloudInfo;
/**
* @member {EventsAiInfo} [ai] AI info of the event
*/
ai?: EventsAiInfo;
/**
* @member {EventsApplicationInfo} [application] Application info of the
* event
*/
application?: EventsApplicationInfo;
/**
* @member {EventsClientInfo} [client] Client info of the event
*/
client?: EventsClientInfo;
/**
* @member {EventsBrowserTimingInfo} [browserTiming]
*/
browserTiming?: EventsBrowserTimingInfo;
/**
* @member {EventsClientPerformanceInfo} [clientPerformance]
*/
clientPerformance?: EventsClientPerformanceInfo;
}
/**
* @interface
* An interface representing EventsRequestInfo.
* The request info
*
*/
export interface EventsRequestInfo {
/**
* @member {string} [name] The name of the request
*/
name?: string;
/**
* @member {string} [url] The URL of the request
*/
url?: string;
/**
* @member {string} [success] Indicates if the request was successful
*/
success?: string;
/**
* @member {number} [duration] The duration of the request
*/
duration?: number;
/**
* @member {string} [performanceBucket] The performance bucket of the request
*/
performanceBucket?: string;
/**
* @member {string} [resultCode] The result code of the request
*/
resultCode?: string;
/**
* @member {string} [source] The source of the request
*/
source?: string;
/**
* @member {string} [id] The ID of the request
*/
id?: string;
}
/**
* @interface
* An interface representing EventsRequestResult.
* A request result
*
*/
export interface EventsRequestResult {
/**
* @member {string} type Polymorphic Discriminator
*/
type: "request";
/**
* @member {string} [id] The unique ID for this event.
*/
id?: string;
/**
* @member {number} [count] Count of the event
*/
count?: number;
/**
* @member {Date} [timestamp] Timestamp of the event
*/
timestamp?: Date;
/**
* @member {EventsResultDataCustomDimensions} [customDimensions] Custom
* dimensions of the event
*/
customDimensions?: EventsResultDataCustomDimensions;
/**
* @member {EventsResultDataCustomMeasurements} [customMeasurements] Custom
* measurements of the event
*/
customMeasurements?: EventsResultDataCustomMeasurements;
/**
* @member {EventsOperationInfo} [operation] Operation info of the event
*/
operation?: EventsOperationInfo;
/**
* @member {EventsSessionInfo} [session] Session info of the event
*/
session?: EventsSessionInfo;
/**
* @member {EventsUserInfo} [user] User info of the event
*/
user?: EventsUserInfo;
/**
* @member {EventsCloudInfo} [cloud] Cloud info of the event
*/
cloud?: EventsCloudInfo;
/**
* @member {EventsAiInfo} [ai] AI info of the event
*/
ai?: EventsAiInfo;
/**
* @member {EventsApplicationInfo} [application] Application info of the
* event
*/
application?: EventsApplicationInfo;
/**
* @member {EventsClientInfo} [client] Client info of the event
*/
client?: EventsClientInfo;
/**
* @member {EventsRequestInfo} [request]
*/
request?: EventsRequestInfo;
}
/**
* @interface
* An interface representing EventsDependencyInfo.
* The dependency info
*
*/
export interface EventsDependencyInfo {
/**
* @member {string} [target] The target of the dependency
*/
target?: string;
/**
* @member {string} [data] The data of the dependency
*/
data?: string;
/**
* @member {string} [success] Indicates if the dependency was successful
*/
success?: string;
/**
* @member {number} [duration] The duration of the dependency
*/
duration?: number;
/**
* @member {string} [performanceBucket] The performance bucket of the
* dependency
*/
performanceBucket?: string;
/**
* @member {string} [resultCode] The result code of the dependency
*/
resultCode?: string;
/**
* @member {string} [type] The type of the dependency
*/
type?: string;
/**
* @member {string} [name] The name of the dependency
*/
name?: string;
/**
* @member {string} [id] The ID of the dependency
*/
id?: string;
}
/**
* @interface
* An interface representing EventsDependencyResult.
* A dependency result
*
*/
export interface EventsDependencyResult {
/**
* @member {string} type Polymorphic Discriminator
*/
type: "dependency";
/**
* @member {string} [id] The unique ID for this event.
*/
id?: string;
/**
* @member {number} [count] Count of the event
*/
count?: number;
/**
* @member {Date} [timestamp] Timestamp of the event
*/
timestamp?: Date;
/**
* @member {EventsResultDataCustomDimensions} [customDimensions] Custom
* dimensions of the event
*/
customDimensions?: EventsResultDataCustomDimensions;
/**
* @member {EventsResultDataCustomMeasurements} [customMeasurements] Custom
* measurements of the event
*/
customMeasurements?: EventsResultDataCustomMeasurements;
/**
* @member {EventsOperationInfo} [operation] Operation info of the event
*/
operation?: EventsOperationInfo;
/**
* @member {EventsSessionInfo} [session] Session info of the event
*/
session?: EventsSessionInfo;
/**
* @member {EventsUserInfo} [user] User info of the event
*/
user?: EventsUserInfo;
/**
* @member {EventsCloudInfo} [cloud] Cloud info of the event
*/
cloud?: EventsCloudInfo;
/**
* @member {EventsAiInfo} [ai] AI info of the event
*/
ai?: EventsAiInfo;
/**
* @member {EventsApplicationInfo} [application] Application info of the
* event
*/
application?: EventsApplicationInfo;
/**
* @member {EventsClientInfo} [client] Client info of the event
*/
client?: EventsClientInfo;
/**
* @member {EventsDependencyInfo} [dependency]
*/
dependency?: EventsDependencyInfo;
}
/**
* @interface
* An interface representing EventsExceptionDetailsParsedStack.
* A parsed stack entry
*
*/
export interface EventsExceptionDetailsParsedStack {
/**
* @member {string} [assembly] The assembly of the stack entry
*/
assembly?: string;
/**
* @member {string} [method] The method of the stack entry
*/
method?: string;
/**
* @member {number} [level] The level of the stack entry
*/
level?: number;
/**
* @member {number} [line] The line of the stack entry
*/
line?: number;
}
/**
* @interface
* An interface representing EventsExceptionDetail.
* Exception details
*
*/
export interface EventsExceptionDetail {
/**
* @member {string} [severityLevel] The severity level of the exception
* detail
*/
severityLevel?: string;
/**
* @member {string} [outerId] The outer ID of the exception detail
*/
outerId?: string;
/**
* @member {string} [message] The message of the exception detail
*/
message?: string;
/**
* @member {string} [type] The type of the exception detail
*/
type?: string;
/**
* @member {string} [id] The ID of the exception detail
*/
id?: string;
/**
* @member {EventsExceptionDetailsParsedStack[]} [parsedStack] The parsed
* stack
*/
parsedStack?: EventsExceptionDetailsParsedStack[];
}
/**
* @interface
* An interface representing EventsExceptionInfo.
* The exception info
*
*/
export interface EventsExceptionInfo {
/**
* @member {number} [severityLevel] The severity level of the exception
*/
severityLevel?: number;
/**
* @member {string} [problemId] The problem ID of the exception
*/
problemId?: string;
/**
* @member {string} [handledAt] Indicates where the exception was handled at
*/
handledAt?: string;
/**
* @member {string} [assembly] The assembly which threw the exception
*/
assembly?: string;
/**
* @member {string} [method] The method that threw the exception
*/
method?: string;
/**
* @member {string} [message] The message of the exception
*/
message?: string;
/**
* @member {string} [type] The type of the exception
*/
type?: string;
/**
* @member {string} [outerType] The outer type of the exception
*/
outerType?: string;
/**
* @member {string} [outerMethod] The outer method of the exception
*/
outerMethod?: string;
/**
* @member {string} [outerAssembly] The outer assmebly of the exception
*/
outerAssembly?: string;
/**
* @member {string} [outerMessage] The outer message of the exception
*/
outerMessage?: string;
/**
* @member {string} [innermostType] The inner most type of the exception
*/
innermostType?: string;
/**
* @member {string} [innermostMessage] The inner most message of the
* exception
*/
innermostMessage?: string;
/**
* @member {string} [innermostMethod] The inner most method of the exception
*/
innermostMethod?: string;
/**
* @member {string} [innermostAssembly] The inner most assembly of the
* exception
*/
innermostAssembly?: string;
/**
* @member {EventsExceptionDetail[]} [details] The details of the exception
*/
details?: EventsExceptionDetail[];
}
/**
* @interface
* An interface representing EventsExceptionResult.
* An exception result
*
*/
export interface EventsExceptionResult {
/**
* @member {string} type Polymorphic Discriminator
*/
type: "exception";
/**
* @member {string} [id] The unique ID for this event.
*/
id?: string;
/**
* @member {number} [count] Count of the event
*/
count?: number;
/**
* @member {Date} [timestamp] Timestamp of the event
*/
timestamp?: Date;
/**
* @member {EventsResultDataCustomDimensions} [customDimensions] Custom
* dimensions of the event
*/
customDimensions?: EventsResultDataCustomDimensions;
/**
* @member {EventsResultDataCustomMeasurements} [customMeasurements] Custom
* measurements of the event
*/
customMeasurements?: EventsResultDataCustomMeasurements;
/**
* @member {EventsOperationInfo} [operation] Operation info of the event
*/
operation?: EventsOperationInfo;
/**
* @member {EventsSessionInfo} [session] Session info of the event
*/
session?: EventsSessionInfo;
/**
* @member {EventsUserInfo} [user] User info of the event
*/
user?: EventsUserInfo;
/**
* @member {EventsCloudInfo} [cloud] Cloud info of the event
*/
cloud?: EventsCloudInfo;
/**
* @member {EventsAiInfo} [ai] AI info of the event
*/
ai?: EventsAiInfo;
/**
* @member {EventsApplicationInfo} [application] Application info of the
* event
*/
application?: EventsApplicationInfo;
/**
* @member {EventsClientInfo} [client] Client info of the event
*/
client?: EventsClientInfo;
/**
* @member {EventsExceptionInfo} [exception]
*/
exception?: EventsExceptionInfo;
}
/**
* @interface
* An interface representing EventsAvailabilityResultInfo.
* The availability result info
*
*/
export interface EventsAvailabilityResultInfo {
/**
* @member {string} [name] The name of the availability result
*/
name?: string;
/**
* @member {string} [success] Indicates if the availability result was
* successful
*/
success?: string;
/**
* @member {number} [duration] The duration of the availability result
*/
duration?: number;
/**
* @member {string} [performanceBucket] The performance bucket of the
* availability result
*/
performanceBucket?: string;
/**
* @member {string} [message] The message of the availability result
*/
message?: string;
/**
* @member {string} [location] The location of the availability result
*/
location?: string;
/**
* @member {string} [id] The ID of the availability result
*/
id?: string;
/**
* @member {string} [size] The size of the availability result
*/
size?: string;
}
/**
* @interface
* An interface representing EventsAvailabilityResultResult.
* An availability result result
*
*/
export interface EventsAvailabilityResultResult {
/**
* @member {string} type Polymorphic Discriminator
*/
type: "availabilityResult";
/**
* @member {string} [id] The unique ID for this event.
*/
id?: string;
/**
* @member {number} [count] Count of the event
*/
count?: number;
/**
* @member {Date} [timestamp] Timestamp of the event
*/
timestamp?: Date;
/**
* @member {EventsResultDataCustomDimensions} [customDimensions] Custom
* dimensions of the event
*/
customDimensions?: EventsResultDataCustomDimensions;
/**
* @member {EventsResultDataCustomMeasurements} [customMeasurements] Custom
* measurements of the event
*/
customMeasurements?: EventsResultDataCustomMeasurements;
/**
* @member {EventsOperationInfo} [operation] Operation info of the event
*/
operation?: EventsOperationInfo;
/**
* @member {EventsSessionInfo} [session] Session info of the event
*/
session?: EventsSessionInfo;
/**
* @member {EventsUserInfo} [user] User info of the event
*/
user?: EventsUserInfo;
/**
* @member {EventsCloudInfo} [cloud] Cloud info of the event
*/
cloud?: EventsCloudInfo;
/**
* @member {EventsAiInfo} [ai] AI info of the event
*/
ai?: EventsAiInfo;
/**
* @member {EventsApplicationInfo} [application] Application info of the
* event
*/
application?: EventsApplicationInfo;
/**
* @member {EventsClientInfo} [client] Client info of the event
*/
client?: EventsClientInfo;
/**
* @member {EventsAvailabilityResultInfo} [availabilityResult]
*/
availabilityResult?: EventsAvailabilityResultInfo;
}
/**
* @interface
* An interface representing EventsPerformanceCounterInfo.
* The performance counter info
*
*/
export interface EventsPerformanceCounterInfo {
/**
* @member {number} [value] The value of the performance counter
*/
value?: number;
/**
* @member {string} [name] The name of the performance counter
*/
name?: string;
/**
* @member {string} [category] The category of the performance counter
*/
category?: string;
/**
* @member {string} [counter] The counter of the performance counter
*/
counter?: string;
/**
* @member {string} [instanceName] The instance name of the performance
* counter
*/
instanceName?: string;
/**
* @member {string} [instance] The instance of the performance counter
*/
instance?: string;
}
/**
* @interface
* An interface representing EventsPerformanceCounterResult.
* A performance counter result
*
*/
export interface EventsPerformanceCounterResult {
/**
* @member {string} type Polymorphic Discriminator
*/
type: "performanceCounter";
/**
* @member {string} [id] The unique ID for this event.
*/
id?: string;
/**
* @member {number} [count] Count of the event
*/
count?: number;
/**
* @member {Date} [timestamp] Timestamp of the event
*/
timestamp?: Date;
/**
* @member {EventsResultDataCustomDimensions} [customDimensions] Custom
* dimensions of the event
*/
customDimensions?: EventsResultDataCustomDimensions;
/**
* @member {EventsResultDataCustomMeasurements} [customMeasurements] Custom
* measurements of the event
*/
customMeasurements?: EventsResultDataCustomMeasurements;
/**
* @member {EventsOperationInfo} [operation] Operation info of the event
*/
operation?: EventsOperationInfo;
/**
* @member {EventsSessionInfo} [session] Session info of the event
*/
session?: EventsSessionInfo;
/**
* @member {EventsUserInfo} [user] User info of the event
*/
user?: EventsUserInfo;
/**
* @member {EventsCloudInfo} [cloud] Cloud info of the event
*/
cloud?: EventsCloudInfo;
/**
* @member {EventsAiInfo} [ai] AI info of the event
*/
ai?: EventsAiInfo;
/**
* @member {EventsApplicationInfo} [application] Application info of the
* event
*/
application?: EventsApplicationInfo;
/**
* @member {EventsClientInfo} [client] Client info of the event
*/
client?: EventsClientInfo;
/**
* @member {EventsPerformanceCounterInfo} [performanceCounter]
*/
performanceCounter?: EventsPerformanceCounterInfo;
}
/**
* @interface
* An interface representing EventsCustomMetricInfo.
* The custom metric info
*
*/
export interface EventsCustomMetricInfo {
/**
* @member {string} [name] The name of the custom metric
*/
name?: string;
/**
* @member {number} [value] The value of the custom metric
*/
value?: number;
/**
* @member {number} [valueSum] The sum of the custom metric
*/
valueSum?: number;
/**
* @member {number} [valueCount] The count of the custom metric
*/
valueCount?: number;
/**
* @member {number} [valueMin] The minimum value of the custom metric
*/
valueMin?: number;
/**
* @member {number} [valueMax] The maximum value of the custom metric
*/
valueMax?: number;
/**
* @member {number} [valueStdDev] The standard deviation of the custom metric
*/
valueStdDev?: number;
}
/**
* @interface
* An interface representing EventsCustomMetricResult.
* A custom metric result
*
*/
export interface EventsCustomMetricResult {
/**
* @member {string} type Polymorphic Discriminator
*/
type: "customMetric";
/**
* @member {string} [id] The unique ID for this event.
*/
id?: string;
/**
* @member {number} [count] Count of the event
*/
count?: number;
/**
* @member {Date} [timestamp] Timestamp of the event
*/
timestamp?: Date;
/**
* @member {EventsResultDataCustomDimensions} [customDimensions] Custom
* dimensions of the event
*/
customDimensions?: EventsResultDataCustomDimensions;
/**
* @member {EventsResultDataCustomMeasurements} [customMeasurements] Custom
* measurements of the event
*/
customMeasurements?: EventsResultDataCustomMeasurements;
/**
* @member {EventsOperationInfo} [operation] Operation info of the event
*/
operation?: EventsOperationInfo;
/**
* @member {EventsSessionInfo} [session] Session info of the event
*/
session?: EventsSessionInfo;
/**
* @member {EventsUserInfo} [user] User info of the event
*/
user?: EventsUserInfo;
/**
* @member {EventsCloudInfo} [cloud] Cloud info of the event
*/
cloud?: EventsCloudInfo;
/**
* @member {EventsAiInfo} [ai] AI info of the event
*/
ai?: EventsAiInfo;
/**
* @member {EventsApplicationInfo} [application] Application info of the
* event
*/
application?: EventsApplicationInfo;
/**
* @member {EventsClientInfo} [client] Client info of the event
*/
client?: EventsClientInfo;
/**
* @member {EventsCustomMetricInfo} [customMetric]
*/
customMetric?: EventsCustomMetricInfo;
}
/**
* @interface
* An interface representing QueryBody.
* The Analytics query. Learn more about the [Analytics query
* syntax](https://azure.microsoft.com/documentation/articles/app-insights-analytics-reference/)
*
*/
export interface QueryBody {
/**
* @member {string} query The query to execute.
*/
query: string;
/**
* @member {string} [timespan] Optional. The timespan over which to query
* data. This is an ISO8601 time period value. This timespan is applied in
* addition to any that are specified in the query expression.
*/
timespan?: string;
/**
* @member {string[]} [applications] A list of Application IDs for
* cross-application queries.
*/
applications?: string[];
}
/**
* @interface
* An interface representing Column.
* @summary A table column.
*
* A column in a table.
*
*/
export interface Column {
/**
* @member {string} [name] The name of this column.
*/
name?: string;
/**
* @member {string} [type] The data type of this column.
*/
type?: string;
}
/**
* @interface
* An interface representing Table.
* @summary A query response table.
*
* Contains the columns and rows for one table in a query response.
*
*/
export interface Table {
/**
* @member {string} name The name of the table.
*/
name: string;
/**
* @member {Column[]} columns The list of columns in this table.
*/
columns: Column[];
/**
* @member {any[][]} rows The resulting rows from this query.
*/
rows: any[][];
}
/**
* @interface
* An interface representing QueryResults.
* @summary A query response.
*
* Contains the tables, columns & rows resulting from a query.
*
*/
export interface QueryResults {
/**
* @member {Table[]} tables The list of tables, columns and rows.
*/
tables: Table[];
}
/**
* @interface
* An interface representing ErrorResponse.
* @summary Error details.
*
* Contains details when the response code indicates an error.
*
*/
export interface ErrorResponse {
/**
* @member {ErrorInfo} error The error details.
*/
error: ErrorInfo;
}
/**
* @interface
* An interface representing ApplicationInsightsDataClientOptions.
* @extends ServiceClientOptions
*/
export interface ApplicationInsightsDataClientOptions extends ServiceClientOptions {
/**
* @member {string} [baseUri]
*/
baseUri?: string;
}
/**
* @interface
* An interface representing MetricsGetOptionalParams.
* Optional Parameters.
*
* @extends RequestOptionsBase
*/
export interface MetricsGetOptionalParams extends msRest.RequestOptionsBase {
/**
* @member {string} [timespan] The timespan over which to retrieve metric
* values. This is an ISO8601 time period value. If timespan is omitted, a
* default time range of `PT12H` ("last 12 hours") is used. The actual
* timespan that is queried may be adjusted by the server based. In all
* cases, the actual time span used for the query is included in the
* response.
*/
timespan?: string;
/**
* @member {string} [interval] The time interval to use when retrieving
* metric values. This is an ISO8601 duration. If interval is omitted, the
* metric value is aggregated across the entire timespan. If interval is
* supplied, the server may adjust the interval to a more appropriate size
* based on the timespan used for the query. In all cases, the actual
* interval used for the query is included in the response.
*/
interval?: string;
/**
* @member {MetricsAggregation[]} [aggregation] The aggregation to use when
* computing the metric values. To retrieve more than one aggregation at a
* time, separate them with a comma. If no aggregation is specified, then the
* default aggregation for the metric is used.
*/
aggregation?: MetricsAggregation[];
/**
* @member {MetricsSegment[]} [segment] The name of the dimension to segment
* the metric values by. This dimension must be applicable to the metric you
* are retrieving. To segment by more than one dimension at a time, separate
* them with a comma (,). In this case, the metric data will be segmented in
* the order the dimensions are listed in the parameter.
*/
segment?: MetricsSegment[];
/**
* @member {number} [top] The number of segments to return. This value is
* only valid when segment is specified.
*/
top?: number;
/**
* @member {string} [orderby] The aggregation function and direction to sort
* the segments by. This value is only valid when segment is specified.
*/
orderby?: string;
/**
* @member {string} [filter] An expression used to filter the results. This
* value should be a valid OData filter expression where the keys of each
* clause should be applicable dimensions for the metric you are retrieving.
*/
filter?: string;
}
/**
* @interface
* An interface representing EventsGetByTypeOptionalParams.
* Optional Parameters.
*
* @extends RequestOptionsBase
*/
export interface EventsGetByTypeOptionalParams extends msRest.RequestOptionsBase {
/**
* @member {string} [timespan] Optional. The timespan over which to retrieve
* events. This is an ISO8601 time period value. This timespan is applied in
* addition to any that are specified in the Odata expression.
*/
timespan?: string;
/**
* @member {string} [filter] An expression used to filter the returned events
*/
filter?: string;
/**
* @member {string} [search] A free-text search expression to match for
* whether a particular event should be returned
*/
search?: string;
/**
* @member {string} [orderby] A comma-separated list of properties with
* \"asc\" (the default) or \"desc\" to control the order of returned events
*/
orderby?: string;
/**
* @member {string} [select] Limits the properties to just those requested on
* each returned event
*/
select?: string;
/**
* @member {number} [skip] The number of items to skip over before returning
* events
*/
skip?: number;
/**
* @member {number} [top] The number of events to return
*/
top?: number;
/**
* @member {string} [format] Format for the returned events
*/
format?: string;
/**
* @member {boolean} [count] Request a count of matching items included with
* the returned events
*/
count?: boolean;
/**
* @member {string} [apply] An expression used for aggregation over returned
* events
*/
apply?: string;
}
/**
* @interface
* An interface representing EventsGetOptionalParams.
* Optional Parameters.
*
* @extends RequestOptionsBase
*/
export interface EventsGetOptionalParams extends msRest.RequestOptionsBase {
/**
* @member {string} [timespan] Optional. The timespan over which to retrieve
* events. This is an ISO8601 time period value. This timespan is applied in
* addition to any that are specified in the Odata expression.
*/
timespan?: string;
}
/**
* Defines values for MetricId.
* Possible values include: 'requests/count', 'requests/duration', 'requests/failed',
* 'users/count', 'users/authenticated', 'pageViews/count', 'pageViews/duration',
* 'client/processingDuration', 'client/receiveDuration', 'client/networkDuration',
* 'client/sendDuration', 'client/totalDuration', 'dependencies/count', 'dependencies/failed',
* 'dependencies/duration', 'exceptions/count', 'exceptions/browser', 'exceptions/server',
* 'sessions/count', 'performanceCounters/requestExecutionTime',
* 'performanceCounters/requestsPerSecond', 'performanceCounters/requestsInQueue',
* 'performanceCounters/memoryAvailableBytes', 'performanceCounters/exceptionsPerSecond',
* 'performanceCounters/processCpuPercentage', 'performanceCounters/processIOBytesPerSecond',
* 'performanceCounters/processPrivateBytes', 'performanceCounters/processorCpuPercentage',
* 'availabilityResults/availabilityPercentage', 'availabilityResults/duration',
* 'billing/telemetryCount', 'customEvents/count'
* @readonly
* @enum {string}
*/
export type MetricId = 'requests/count' | 'requests/duration' | 'requests/failed' | 'users/count' | 'users/authenticated' | 'pageViews/count' | 'pageViews/duration' | 'client/processingDuration' | 'client/receiveDuration' | 'client/networkDuration' | 'client/sendDuration' | 'client/totalDuration' | 'dependencies/count' | 'dependencies/failed' | 'dependencies/duration' | 'exceptions/count' | 'exceptions/browser' | 'exceptions/server' | 'sessions/count' | 'performanceCounters/requestExecutionTime' | 'performanceCounters/requestsPerSecond' | 'performanceCounters/requestsInQueue' | 'performanceCounters/memoryAvailableBytes' | 'performanceCounters/exceptionsPerSecond' | 'performanceCounters/processCpuPercentage' | 'performanceCounters/processIOBytesPerSecond' | 'performanceCounters/processPrivateBytes' | 'performanceCounters/processorCpuPercentage' | 'availabilityResults/availabilityPercentage' | 'availabilityResults/duration' | 'billing/telemetryCount' | 'customEvents/count';
/**
* Defines values for MetricsAggregation.
* Possible values include: 'min', 'max', 'avg', 'sum', 'count', 'unique'
* @readonly
* @enum {string}
*/
export type MetricsAggregation = 'min' | 'max' | 'avg' | 'sum' | 'count' | 'unique';
/**
* Defines values for MetricsSegment.
* Possible values include: 'applicationBuild', 'applicationVersion',
* 'authenticatedOrAnonymousTraffic', 'browser', 'browserVersion', 'city', 'cloudRoleName',
* 'cloudServiceName', 'continent', 'countryOrRegion', 'deploymentId', 'deploymentUnit',
* 'deviceType', 'environment', 'hostingLocation', 'instanceName'
* @readonly
* @enum {string}
*/
export type MetricsSegment = 'applicationBuild' | 'applicationVersion' | 'authenticatedOrAnonymousTraffic' | 'browser' | 'browserVersion' | 'city' | 'cloudRoleName' | 'cloudServiceName' | 'continent' | 'countryOrRegion' | 'deploymentId' | 'deploymentUnit' | 'deviceType' | 'environment' | 'hostingLocation' | 'instanceName';
/**
* Defines values for EventType.
* Possible values include: '$all', 'traces', 'customEvents', 'pageViews', 'browserTimings',
* 'requests', 'dependencies', 'exceptions', 'availabilityResults', 'performanceCounters',
* 'customMetrics'
* @readonly
* @enum {string}
*/
export type EventType = '$all' | 'traces' | 'customEvents' | 'pageViews' | 'browserTimings' | 'requests' | 'dependencies' | 'exceptions' | 'availabilityResults' | 'performanceCounters' | 'customMetrics';
/**
* Contains response data for the get operation.
*/
export type MetricsGetResponse = MetricsResult & {
/**
* 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: MetricsResult;
};
};
/**
* Contains response data for the getMultiple operation.
*/
export type MetricsGetMultipleResponse = Array<MetricsResultsItem> & {
/**
* 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: MetricsResultsItem[];
};
};
/**
* Contains response data for the getMetadata operation.
*/
export type MetricsGetMetadataResponse = {
/**
* 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 getByType operation.
*/
export type EventsGetByTypeResponse = EventsResults & {
/**
* 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: EventsResults;
};
};
/**
* Contains response data for the get operation.
*/
export type EventsGetResponse = EventsResults & {
/**
* 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: EventsResults;
};
};
/**
* Contains response data for the execute operation.
*/
export type QueryExecuteResponse = QueryResults & {
/**
* 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: QueryResults;
};
}; | the_stack |
import * as coreClient from "@azure/core-client";
/** The result of the request to list REST API operations. It contains a list of operations and a URL to get the next set of results. */
export interface OperationListResult {
/**
* The list of operations supported by the resource provider.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly value?: Operation[];
/**
* The URL to get the next set of operation list results, if any.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly nextLink?: string;
}
/** Describes a REST API operation. */
export interface Operation {
/**
* The name of the operation. This name is of the form {provider}/{resource}/{operation}.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly name?: string;
/**
* The object that describes the operation.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly display?: OperationDisplay;
}
/** The object that describes the operation. */
export interface OperationDisplay {
/**
* The friendly name of the resource provider.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly provider?: string;
/**
* The operation type: read, write, delete, listKeys/action, etc.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly operation?: string;
/**
* The resource type on which the operation is performed.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly resource?: string;
/**
* The friendly name of the operation.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly description?: string;
}
/** Contains information about an API error. */
export interface CloudError {
/** Describes a particular API error with an error code and a message. */
error?: CloudErrorBody;
}
/** Describes a particular API error with an error code and a message. */
export interface CloudErrorBody {
/** An error code that describes the error condition more precisely than an HTTP status code. Can be used to programmatically handle specific error cases. */
code?: string;
/** A message that describes the error in detail and provides debugging information. */
message?: string;
/** The target of the particular error (for example, the name of the property in error). */
target?: string;
/** Contains nested errors that are related to this error. */
details?: CloudErrorBody[];
}
/** Response containing the primary and secondary admin API keys for a given Azure Cognitive Search service. */
export interface AdminKeyResult {
/**
* The primary admin API key of the search service.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly primaryKey?: string;
/**
* The secondary admin API key of the search service.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly secondaryKey?: string;
}
/** Describes an API key for a given Azure Cognitive Search service that has permissions for query operations only. */
export interface QueryKey {
/**
* The name of the query API key; may be empty.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly name?: string;
/**
* The value of the query API key.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly key?: string;
}
/** Response containing the query API keys for a given Azure Cognitive Search service. */
export interface ListQueryKeysResult {
/**
* The query keys for the Azure Cognitive Search service.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly value?: QueryKey[];
/**
* Request URL that can be used to query next page of query keys. Returned when the total number of requested query keys exceed maximum page size.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly nextLink?: string;
}
/** Network specific rules that determine how the Azure Cognitive Search service may be reached. */
export interface NetworkRuleSet {
/** A list of IP restriction rules that defines the inbound network(s) with allowing access to the search service endpoint. At the meantime, all other public IP networks are blocked by the firewall. These restriction rules are applied only when the 'publicNetworkAccess' of the search service is 'enabled'; otherwise, traffic over public interface is not allowed even with any public IP rules, and private endpoint connections would be the exclusive access method. */
ipRules?: IpRule[];
}
/** The IP restriction rule of the Azure Cognitive Search service. */
export interface IpRule {
/** Value corresponding to a single IPv4 address (eg., 123.1.2.3) or an IP range in CIDR format (eg., 123.1.2.3/24) to be allowed. */
value?: string;
}
/** Describes the properties of an existing Private Endpoint connection to the Azure Cognitive Search service. */
export interface PrivateEndpointConnectionProperties {
/** The private endpoint resource from Microsoft.Network provider. */
privateEndpoint?: PrivateEndpointConnectionPropertiesPrivateEndpoint;
/** Describes the current state of an existing Private Link Service connection to the Azure Private Endpoint. */
privateLinkServiceConnectionState?: PrivateEndpointConnectionPropertiesPrivateLinkServiceConnectionState;
}
/** The private endpoint resource from Microsoft.Network provider. */
export interface PrivateEndpointConnectionPropertiesPrivateEndpoint {
/** The resource id of the private endpoint resource from Microsoft.Network provider. */
id?: string;
}
/** Describes the current state of an existing Private Link Service connection to the Azure Private Endpoint. */
export interface PrivateEndpointConnectionPropertiesPrivateLinkServiceConnectionState {
/** Status of the the private link service connection. Can be Pending, Approved, Rejected, or Disconnected. */
status?: PrivateLinkServiceConnectionStatus;
/** The description for the private link service connection state. */
description?: string;
/** A description of any extra actions that may be required. */
actionsRequired?: string;
}
/** Common fields that are returned in the response for all Azure Resource Manager resources */
export interface Resource {
/**
* 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. E.g. "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;
}
/** Describes the properties of an existing Shared Private Link Resource managed by the Azure Cognitive Search service. */
export interface SharedPrivateLinkResourceProperties {
/** The resource id of the resource the shared private link resource is for. */
privateLinkResourceId?: string;
/** The group id from the provider of resource the shared private link resource is for. */
groupId?: string;
/** The request message for requesting approval of the shared private link resource. */
requestMessage?: string;
/** Optional. Can be used to specify the Azure Resource Manager location of the resource to which a shared private link is to be created. This is only required for those resources whose DNS configuration are regional (such as Azure Kubernetes Service). */
resourceRegion?: string;
/** Status of the shared private link resource. Can be Pending, Approved, Rejected or Disconnected. */
status?: SharedPrivateLinkResourceStatus;
/** The provisioning state of the shared private link resource. Can be Updating, Deleting, Failed, Succeeded or Incomplete. */
provisioningState?: SharedPrivateLinkResourceProvisioningState;
}
/** Defines the SKU of an Azure Cognitive Search Service, which determines price tier and capacity limits. */
export interface Sku {
/** The SKU of the search service. Valid values include: 'free': Shared service. 'basic': Dedicated service with up to 3 replicas. 'standard': Dedicated service with up to 12 partitions and 12 replicas. 'standard2': Similar to standard, but with more capacity per search unit. 'standard3': The largest Standard offering with up to 12 partitions and 12 replicas (or up to 3 partitions with more indexes if you also set the hostingMode property to 'highDensity'). 'storage_optimized_l1': Supports 1TB per partition, up to 12 partitions. 'storage_optimized_l2': Supports 2TB per partition, up to 12 partitions.' */
name?: SkuName;
}
/** Identity for the resource. */
export interface Identity {
/**
* The principal ID of resource identity.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly principalId?: string;
/**
* The tenant ID of resource.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly tenantId?: string;
/** The identity type. */
type: IdentityType;
}
/** Response containing a list of Azure Cognitive Search services. */
export interface SearchServiceListResult {
/**
* The list of search services.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly value?: SearchService[];
/**
* Request URL that can be used to query next page of search services. Returned when the total number of requested search services exceed maximum page size.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly nextLink?: string;
}
/** Response containing a list of supported Private Link Resources. */
export interface PrivateLinkResourcesResult {
/**
* The list of supported Private Link Resources.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly value?: PrivateLinkResource[];
}
/** Describes the properties of a supported private link resource for the Azure Cognitive Search service. For a given API version, this represents the 'supported' groupIds when creating a shared private link resource. */
export interface PrivateLinkResourceProperties {
/**
* The group ID of the private link resource.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly groupId?: string;
/**
* The list of required members of the private link resource.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly requiredMembers?: string[];
/**
* The list of required DNS zone names of the private link resource.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly requiredZoneNames?: string[];
/**
* The list of resources that are onboarded to private link service, that are supported by Azure Cognitive Search.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly shareablePrivateLinkResourceTypes?: ShareablePrivateLinkResourceType[];
}
/** Describes an resource type that has been onboarded to private link service, supported by Azure Cognitive Search. */
export interface ShareablePrivateLinkResourceType {
/**
* The name of the resource type that has been onboarded to private link service, supported by Azure Cognitive Search.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly name?: string;
/**
* Describes the properties of a resource type that has been onboarded to private link service, supported by Azure Cognitive Search.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly properties?: ShareablePrivateLinkResourceProperties;
}
/** Describes the properties of a resource type that has been onboarded to private link service, supported by Azure Cognitive Search. */
export interface ShareablePrivateLinkResourceProperties {
/**
* The resource provider type for the resource that has been onboarded to private link service, supported by Azure Cognitive Search.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly type?: string;
/**
* The resource provider group id for the resource that has been onboarded to private link service, supported by Azure Cognitive Search.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly groupId?: string;
/**
* The description of the resource type that has been onboarded to private link service, supported by Azure Cognitive Search.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly description?: string;
}
/** Response containing a list of Private Endpoint connections. */
export interface PrivateEndpointConnectionListResult {
/**
* The list of Private Endpoint connections.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly value?: PrivateEndpointConnection[];
/**
* Request URL that can be used to query next page of private endpoint connections. Returned when the total number of requested private endpoint connections exceed maximum page size.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly nextLink?: string;
}
/** Response containing a list of Shared Private Link Resources. */
export interface SharedPrivateLinkResourceListResult {
/**
* The list of Shared Private Link Resources.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly value?: SharedPrivateLinkResource[];
/** The URL to get the next set of shared private link resources, if there are any. */
nextLink?: string;
}
/** Input of check name availability API. */
export interface CheckNameAvailabilityInput {
/** The search service name to validate. Search service names must only contain lowercase letters, digits or dashes, cannot use dash as the first two or last one characters, cannot contain consecutive dashes, and must be between 2 and 60 characters in length. */
name: string;
/** The type of the resource whose name is to be validated. This value must always be 'searchServices'. */
type: "searchServices";
}
/** Output of check name availability API. */
export interface CheckNameAvailabilityOutput {
/**
* A value indicating whether the name is available.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly isNameAvailable?: boolean;
/**
* The reason why the name is not available. 'Invalid' indicates the name provided does not match the naming requirements (incorrect length, unsupported characters, etc.). 'AlreadyExists' indicates that the name is already in use and is therefore unavailable.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly reason?: UnavailableNameReason;
/**
* A message that explains why the name is invalid and provides resource naming requirements. Available only if 'Invalid' is returned in the 'reason' property.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly message?: string;
}
/** The details of a long running asynchronous shared private link resource operation */
export interface AsyncOperationResult {
/** The current status of the long running asynchronous shared private link resource operation. */
status?: SharedPrivateLinkResourceAsyncOperationResult;
}
/** Describes an existing Private Endpoint connection to the Azure Cognitive Search service. */
export type PrivateEndpointConnection = Resource & {
/** Describes the properties of an existing Private Endpoint connection to the Azure Cognitive Search service. */
properties?: PrivateEndpointConnectionProperties;
};
/** Describes a Shared Private Link Resource managed by the Azure Cognitive Search service. */
export type SharedPrivateLinkResource = Resource & {
/** Describes the properties of a Shared Private Link Resource managed by the Azure Cognitive Search service. */
properties?: SharedPrivateLinkResourceProperties;
};
/** The resource model definition for an Azure Resource Manager tracked top level resource which has 'tags' and a 'location' */
export type TrackedResource = Resource & {
/** Resource tags. */
tags?: { [propertyName: string]: string };
/** The geo-location where the resource lives */
location: string;
};
/** The parameters used to update an Azure Cognitive Search service. */
export type SearchServiceUpdate = Resource & {
/** The SKU of the Search Service, which determines price tier and capacity limits. This property is required when creating a new Search Service. */
sku?: Sku;
/** The geographic location of the resource. This must be one of the supported and registered Azure Geo Regions (for example, West US, East US, Southeast Asia, and so forth). This property is required when creating a new resource. */
location?: string;
/** Tags to help categorize the resource in the Azure portal. */
tags?: { [propertyName: string]: string };
/** The identity of the resource. */
identity?: Identity;
/** The number of replicas in the search service. If specified, it must be a value between 1 and 12 inclusive for standard SKUs or between 1 and 3 inclusive for basic SKU. */
replicaCount?: number;
/** The number of partitions in the search service; if specified, it can be 1, 2, 3, 4, 6, or 12. Values greater than 1 are only valid for standard SKUs. For 'standard3' services with hostingMode set to 'highDensity', the allowed values are between 1 and 3. */
partitionCount?: number;
/** Applicable only for the standard3 SKU. You can set this property to enable up to 3 high density partitions that allow up to 1000 indexes, which is much higher than the maximum indexes allowed for any other SKU. For the standard3 SKU, the value is either 'default' or 'highDensity'. For all other SKUs, this value must be 'default'. */
hostingMode?: HostingMode;
/** This value can be set to 'enabled' to avoid breaking changes on existing customer resources and templates. If set to 'disabled', traffic over public interface is not allowed, and private endpoint connections would be the exclusive access method. */
publicNetworkAccess?: PublicNetworkAccess;
/**
* The status of the search service. Possible values include: 'running': The search service is running and no provisioning operations are underway. 'provisioning': The search service is being provisioned or scaled up or down. 'deleting': The search service is being deleted. 'degraded': The search service is degraded. This can occur when the underlying search units are not healthy. The search service is most likely operational, but performance might be slow and some requests might be dropped. 'disabled': The search service is disabled. In this state, the service will reject all API requests. 'error': The search service is in an error state. If your service is in the degraded, disabled, or error states, it means the Azure Cognitive Search team is actively investigating the underlying issue. Dedicated services in these states are still chargeable based on the number of search units provisioned.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly status?: SearchServiceStatus;
/**
* The details of the search service status.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly statusDetails?: string;
/**
* The state of the last provisioning operation performed on the search service. Provisioning is an intermediate state that occurs while service capacity is being established. After capacity is set up, provisioningState changes to either 'succeeded' or 'failed'. Client applications can poll provisioning status (the recommended polling interval is from 30 seconds to one minute) by using the Get Search Service operation to see when an operation is completed. If you are using the free service, this value tends to come back as 'succeeded' directly in the call to Create search service. This is because the free service uses capacity that is already set up.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly provisioningState?: ProvisioningState;
/** Network specific rules that determine how the Azure Cognitive Search service may be reached. */
networkRuleSet?: NetworkRuleSet;
/**
* The list of private endpoint connections to the Azure Cognitive Search service.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly privateEndpointConnections?: PrivateEndpointConnection[];
/**
* The list of shared private link resources managed by the Azure Cognitive Search service.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly sharedPrivateLinkResources?: SharedPrivateLinkResource[];
};
/** Describes a supported private link resource for the Azure Cognitive Search service. */
export type PrivateLinkResource = Resource & {
/**
* Describes the properties of a supported private link resource for the Azure Cognitive Search service.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly properties?: PrivateLinkResourceProperties;
};
/** Describes an Azure Cognitive Search service and its current state. */
export type SearchService = TrackedResource & {
/** The SKU of the Search Service, which determines price tier and capacity limits. This property is required when creating a new Search Service. */
sku?: Sku;
/** The identity of the resource. */
identity?: Identity;
/** The number of replicas in the search service. If specified, it must be a value between 1 and 12 inclusive for standard SKUs or between 1 and 3 inclusive for basic SKU. */
replicaCount?: number;
/** The number of partitions in the search service; if specified, it can be 1, 2, 3, 4, 6, or 12. Values greater than 1 are only valid for standard SKUs. For 'standard3' services with hostingMode set to 'highDensity', the allowed values are between 1 and 3. */
partitionCount?: number;
/** Applicable only for the standard3 SKU. You can set this property to enable up to 3 high density partitions that allow up to 1000 indexes, which is much higher than the maximum indexes allowed for any other SKU. For the standard3 SKU, the value is either 'default' or 'highDensity'. For all other SKUs, this value must be 'default'. */
hostingMode?: HostingMode;
/** This value can be set to 'enabled' to avoid breaking changes on existing customer resources and templates. If set to 'disabled', traffic over public interface is not allowed, and private endpoint connections would be the exclusive access method. */
publicNetworkAccess?: PublicNetworkAccess;
/**
* The status of the search service. Possible values include: 'running': The search service is running and no provisioning operations are underway. 'provisioning': The search service is being provisioned or scaled up or down. 'deleting': The search service is being deleted. 'degraded': The search service is degraded. This can occur when the underlying search units are not healthy. The search service is most likely operational, but performance might be slow and some requests might be dropped. 'disabled': The search service is disabled. In this state, the service will reject all API requests. 'error': The search service is in an error state. If your service is in the degraded, disabled, or error states, it means the Azure Cognitive Search team is actively investigating the underlying issue. Dedicated services in these states are still chargeable based on the number of search units provisioned.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly status?: SearchServiceStatus;
/**
* The details of the search service status.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly statusDetails?: string;
/**
* The state of the last provisioning operation performed on the search service. Provisioning is an intermediate state that occurs while service capacity is being established. After capacity is set up, provisioningState changes to either 'succeeded' or 'failed'. Client applications can poll provisioning status (the recommended polling interval is from 30 seconds to one minute) by using the Get Search Service operation to see when an operation is completed. If you are using the free service, this value tends to come back as 'succeeded' directly in the call to Create search service. This is because the free service uses capacity that is already set up.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly provisioningState?: ProvisioningState;
/** Network specific rules that determine how the Azure Cognitive Search service may be reached. */
networkRuleSet?: NetworkRuleSet;
/**
* The list of private endpoint connections to the Azure Cognitive Search service.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly privateEndpointConnections?: PrivateEndpointConnection[];
/**
* The list of shared private link resources managed by the Azure Cognitive Search service.
* NOTE: This property will not be serialized. It can only be populated by the server.
*/
readonly sharedPrivateLinkResources?: SharedPrivateLinkResource[];
};
/** Parameter group */
export interface SearchManagementRequestOptions {
/** A client-generated GUID value that identifies this request. If specified, this will be included in response information as a way to track the request. */
clientRequestId?: string;
}
/** Known values of {@link UnavailableNameReason} that the service accepts. */
export enum KnownUnavailableNameReason {
Invalid = "Invalid",
AlreadyExists = "AlreadyExists"
}
/**
* Defines values for UnavailableNameReason. \
* {@link KnownUnavailableNameReason} can be used interchangeably with UnavailableNameReason,
* this enum contains the known values that the service supports.
* ### Known values supported by the service
* **Invalid** \
* **AlreadyExists**
*/
export type UnavailableNameReason = string;
/** Known values of {@link SharedPrivateLinkResourceAsyncOperationResult} that the service accepts. */
export enum KnownSharedPrivateLinkResourceAsyncOperationResult {
Running = "Running",
Succeeded = "Succeeded",
Failed = "Failed"
}
/**
* Defines values for SharedPrivateLinkResourceAsyncOperationResult. \
* {@link KnownSharedPrivateLinkResourceAsyncOperationResult} can be used interchangeably with SharedPrivateLinkResourceAsyncOperationResult,
* this enum contains the known values that the service supports.
* ### Known values supported by the service
* **Running** \
* **Succeeded** \
* **Failed**
*/
export type SharedPrivateLinkResourceAsyncOperationResult = string;
/** Defines values for AdminKeyKind. */
export type AdminKeyKind = "primary" | "secondary";
/** Defines values for HostingMode. */
export type HostingMode = "default" | "highDensity";
/** Defines values for PublicNetworkAccess. */
export type PublicNetworkAccess = "enabled" | "disabled";
/** Defines values for SearchServiceStatus. */
export type SearchServiceStatus =
| "running"
| "provisioning"
| "deleting"
| "degraded"
| "disabled"
| "error";
/** Defines values for ProvisioningState. */
export type ProvisioningState = "succeeded" | "provisioning" | "failed";
/** Defines values for PrivateLinkServiceConnectionStatus. */
export type PrivateLinkServiceConnectionStatus =
| "Pending"
| "Approved"
| "Rejected"
| "Disconnected";
/** Defines values for SharedPrivateLinkResourceStatus. */
export type SharedPrivateLinkResourceStatus =
| "Pending"
| "Approved"
| "Rejected"
| "Disconnected";
/** Defines values for SharedPrivateLinkResourceProvisioningState. */
export type SharedPrivateLinkResourceProvisioningState =
| "Updating"
| "Deleting"
| "Failed"
| "Succeeded"
| "Incomplete";
/** Defines values for SkuName. */
export type SkuName =
| "free"
| "basic"
| "standard"
| "standard2"
| "standard3"
| "storage_optimized_l1"
| "storage_optimized_l2";
/** Defines values for IdentityType. */
export type IdentityType = "None" | "SystemAssigned";
/** Optional parameters. */
export interface OperationsListOptionalParams
extends coreClient.OperationOptions {}
/** Contains response data for the list operation. */
export type OperationsListResponse = OperationListResult;
/** Optional parameters. */
export interface AdminKeysGetOptionalParams
extends coreClient.OperationOptions {
/** Parameter group */
searchManagementRequestOptions?: SearchManagementRequestOptions;
}
/** Contains response data for the get operation. */
export type AdminKeysGetResponse = AdminKeyResult;
/** Optional parameters. */
export interface AdminKeysRegenerateOptionalParams
extends coreClient.OperationOptions {
/** Parameter group */
searchManagementRequestOptions?: SearchManagementRequestOptions;
}
/** Contains response data for the regenerate operation. */
export type AdminKeysRegenerateResponse = AdminKeyResult;
/** Optional parameters. */
export interface QueryKeysCreateOptionalParams
extends coreClient.OperationOptions {
/** Parameter group */
searchManagementRequestOptions?: SearchManagementRequestOptions;
}
/** Contains response data for the create operation. */
export type QueryKeysCreateResponse = QueryKey;
/** Optional parameters. */
export interface QueryKeysListBySearchServiceOptionalParams
extends coreClient.OperationOptions {
/** Parameter group */
searchManagementRequestOptions?: SearchManagementRequestOptions;
}
/** Contains response data for the listBySearchService operation. */
export type QueryKeysListBySearchServiceResponse = ListQueryKeysResult;
/** Optional parameters. */
export interface QueryKeysDeleteOptionalParams
extends coreClient.OperationOptions {
/** Parameter group */
searchManagementRequestOptions?: SearchManagementRequestOptions;
}
/** Optional parameters. */
export interface QueryKeysListBySearchServiceNextOptionalParams
extends coreClient.OperationOptions {
/** Parameter group */
searchManagementRequestOptions?: SearchManagementRequestOptions;
}
/** Contains response data for the listBySearchServiceNext operation. */
export type QueryKeysListBySearchServiceNextResponse = ListQueryKeysResult;
/** Optional parameters. */
export interface ServicesCreateOrUpdateOptionalParams
extends coreClient.OperationOptions {
/** Parameter group */
searchManagementRequestOptions?: SearchManagementRequestOptions;
/** Delay to wait until next poll, in milliseconds. */
updateIntervalInMs?: number;
/** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */
resumeFrom?: string;
}
/** Contains response data for the createOrUpdate operation. */
export type ServicesCreateOrUpdateResponse = SearchService;
/** Optional parameters. */
export interface ServicesUpdateOptionalParams
extends coreClient.OperationOptions {
/** Parameter group */
searchManagementRequestOptions?: SearchManagementRequestOptions;
}
/** Contains response data for the update operation. */
export type ServicesUpdateResponse = SearchService;
/** Optional parameters. */
export interface ServicesGetOptionalParams extends coreClient.OperationOptions {
/** Parameter group */
searchManagementRequestOptions?: SearchManagementRequestOptions;
}
/** Contains response data for the get operation. */
export type ServicesGetResponse = SearchService;
/** Optional parameters. */
export interface ServicesDeleteOptionalParams
extends coreClient.OperationOptions {
/** Parameter group */
searchManagementRequestOptions?: SearchManagementRequestOptions;
}
/** Optional parameters. */
export interface ServicesListByResourceGroupOptionalParams
extends coreClient.OperationOptions {
/** Parameter group */
searchManagementRequestOptions?: SearchManagementRequestOptions;
}
/** Contains response data for the listByResourceGroup operation. */
export type ServicesListByResourceGroupResponse = SearchServiceListResult;
/** Optional parameters. */
export interface ServicesListBySubscriptionOptionalParams
extends coreClient.OperationOptions {
/** Parameter group */
searchManagementRequestOptions?: SearchManagementRequestOptions;
}
/** Contains response data for the listBySubscription operation. */
export type ServicesListBySubscriptionResponse = SearchServiceListResult;
/** Optional parameters. */
export interface ServicesCheckNameAvailabilityOptionalParams
extends coreClient.OperationOptions {
/** Parameter group */
searchManagementRequestOptions?: SearchManagementRequestOptions;
}
/** Contains response data for the checkNameAvailability operation. */
export type ServicesCheckNameAvailabilityResponse = CheckNameAvailabilityOutput;
/** Optional parameters. */
export interface ServicesListByResourceGroupNextOptionalParams
extends coreClient.OperationOptions {
/** Parameter group */
searchManagementRequestOptions?: SearchManagementRequestOptions;
}
/** Contains response data for the listByResourceGroupNext operation. */
export type ServicesListByResourceGroupNextResponse = SearchServiceListResult;
/** Optional parameters. */
export interface ServicesListBySubscriptionNextOptionalParams
extends coreClient.OperationOptions {
/** Parameter group */
searchManagementRequestOptions?: SearchManagementRequestOptions;
}
/** Contains response data for the listBySubscriptionNext operation. */
export type ServicesListBySubscriptionNextResponse = SearchServiceListResult;
/** Optional parameters. */
export interface PrivateLinkResourcesListSupportedOptionalParams
extends coreClient.OperationOptions {
/** Parameter group */
searchManagementRequestOptions?: SearchManagementRequestOptions;
}
/** Contains response data for the listSupported operation. */
export type PrivateLinkResourcesListSupportedResponse = PrivateLinkResourcesResult;
/** Optional parameters. */
export interface PrivateEndpointConnectionsUpdateOptionalParams
extends coreClient.OperationOptions {
/** Parameter group */
searchManagementRequestOptions?: SearchManagementRequestOptions;
}
/** Contains response data for the update operation. */
export type PrivateEndpointConnectionsUpdateResponse = PrivateEndpointConnection;
/** Optional parameters. */
export interface PrivateEndpointConnectionsGetOptionalParams
extends coreClient.OperationOptions {
/** Parameter group */
searchManagementRequestOptions?: SearchManagementRequestOptions;
}
/** Contains response data for the get operation. */
export type PrivateEndpointConnectionsGetResponse = PrivateEndpointConnection;
/** Optional parameters. */
export interface PrivateEndpointConnectionsDeleteOptionalParams
extends coreClient.OperationOptions {
/** Parameter group */
searchManagementRequestOptions?: SearchManagementRequestOptions;
}
/** Contains response data for the delete operation. */
export type PrivateEndpointConnectionsDeleteResponse = PrivateEndpointConnection;
/** Optional parameters. */
export interface PrivateEndpointConnectionsListByServiceOptionalParams
extends coreClient.OperationOptions {
/** Parameter group */
searchManagementRequestOptions?: SearchManagementRequestOptions;
}
/** Contains response data for the listByService operation. */
export type PrivateEndpointConnectionsListByServiceResponse = PrivateEndpointConnectionListResult;
/** Optional parameters. */
export interface PrivateEndpointConnectionsListByServiceNextOptionalParams
extends coreClient.OperationOptions {
/** Parameter group */
searchManagementRequestOptions?: SearchManagementRequestOptions;
}
/** Contains response data for the listByServiceNext operation. */
export type PrivateEndpointConnectionsListByServiceNextResponse = PrivateEndpointConnectionListResult;
/** Optional parameters. */
export interface SharedPrivateLinkResourcesCreateOrUpdateOptionalParams
extends coreClient.OperationOptions {
/** Parameter group */
searchManagementRequestOptions?: SearchManagementRequestOptions;
/** Delay to wait until next poll, in milliseconds. */
updateIntervalInMs?: number;
/** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */
resumeFrom?: string;
}
/** Contains response data for the createOrUpdate operation. */
export type SharedPrivateLinkResourcesCreateOrUpdateResponse = SharedPrivateLinkResource;
/** Optional parameters. */
export interface SharedPrivateLinkResourcesGetOptionalParams
extends coreClient.OperationOptions {
/** Parameter group */
searchManagementRequestOptions?: SearchManagementRequestOptions;
}
/** Contains response data for the get operation. */
export type SharedPrivateLinkResourcesGetResponse = SharedPrivateLinkResource;
/** Optional parameters. */
export interface SharedPrivateLinkResourcesDeleteOptionalParams
extends coreClient.OperationOptions {
/** Parameter group */
searchManagementRequestOptions?: SearchManagementRequestOptions;
/** Delay to wait until next poll, in milliseconds. */
updateIntervalInMs?: number;
/** A serialized poller which can be used to resume an existing paused Long-Running-Operation. */
resumeFrom?: string;
}
/** Optional parameters. */
export interface SharedPrivateLinkResourcesListByServiceOptionalParams
extends coreClient.OperationOptions {
/** Parameter group */
searchManagementRequestOptions?: SearchManagementRequestOptions;
}
/** Contains response data for the listByService operation. */
export type SharedPrivateLinkResourcesListByServiceResponse = SharedPrivateLinkResourceListResult;
/** Optional parameters. */
export interface SharedPrivateLinkResourcesListByServiceNextOptionalParams
extends coreClient.OperationOptions {
/** Parameter group */
searchManagementRequestOptions?: SearchManagementRequestOptions;
}
/** Contains response data for the listByServiceNext operation. */
export type SharedPrivateLinkResourcesListByServiceNextResponse = SharedPrivateLinkResourceListResult;
/** Optional parameters. */
export interface SearchManagementClientOptionalParams
extends coreClient.ServiceClientOptions {
/** server parameter */
$host?: string;
/** Api Version */
apiVersion?: string;
/** Overrides client endpoint. */
endpoint?: string;
} | the_stack |
import { CommandData } from "../module.base";
import { ReJSONGetParameters } from "./rejson.types";
export class RejsonCommander {
/**
* Deleting a JSON key
* @param key The name of the key
* @param path The path of the key defaults to root if not provided. Non-existing keys and paths are ignored. Deleting an object's root is equivalent to deleting the key from Redis.
* @returns The number of paths deleted (0 or 1).
*/
del(key: string, path?: string): CommandData {
const parameters = [key];
if(path !== undefined) parameters.push(path)
return {
command: 'JSON.DEL',
args: parameters
}
}
/**
* Clearing a JSON key
* @param key The name of the key
* @param path The path of the key defaults to root if not provided. Non-existing keys and paths are ignored. Deleting an object's root is equivalent to deleting the key from Redis.
* @returns The number of paths deleted (0 or 1).
*/
clear(key: string, path?: string): CommandData {
const parameters = [key];
if(path !== undefined) parameters.push(path);
return {
command: 'JSON.CLEAR',
args: parameters
}
}
/**
* Toggling a JSON key
* @param key The name of the key
* @param path The path of the key defaults to root if not provided. Non-existing keys and paths are ignored. Deleting an object's root is equivalent to deleting the key from Redis.
* @returns The value of the path after the toggle.
*/
toggle(key: string, path?: string): CommandData {
const parameters = [key];
if(path !== undefined) parameters.push(path);
return {
command: 'JSON.TOGGLE',
args: parameters
}
}
/**
* Setting a new JSON key
* @param key The name of the key
* @param path The path of the key
* @param json The JSON string of the key i.e. '{"x": 4}'
* @param condition Optional. The condition to set the JSON in.
* @returns Simple String OK if executed correctly, or Null Bulk if the specified NX or XX conditions were not met.
*/
set(key: string, path: string, json: string, condition?: 'NX' | 'XX'): CommandData {
const args = [key, path, json]
if(condition){
args.push(condition)
}
return {
command: 'JSON.SET',
args: args
}
}
/**
* Retrieving a JSON key
* @param key The name of the key
* @param path The path of the key
* @param parameters Additional parameters to arrange the returned values
* @returns The value at path in JSON serialized form.
*/
get(key: string, path?: string, parameters?: ReJSONGetParameters): CommandData{
const args = [key];
for(const parameter in parameters) {
const name = parameter.toUpperCase();
const value = parameters[parameter];
args.push(name);
if(typeof value !== 'boolean')
args.push(value);
}
if(path !== undefined) args.push(path);
return {
command: 'JSON.GET',
args: args
}
}
/**
* Retrieving values from multiple keys
* @param keys A list of keys
* @param path The path of the keys
* @returns The values at path from multiple key's. Non-existing keys and non-existing paths are reported as null.
*/
mget(keys: string[], path?: string): CommandData {
const args = keys;
if(path !== undefined) args.push(path);
return {
command: 'JSON.MGET',
args: args
}
}
/**
* Retrieving the type of a JSON key
* @param key The name of the key
* @param path The path of the key
* @returns Simple String, specifically the type of value.
*/
type(key: string, path?: string): CommandData {
const args = [key];
if(path !== undefined) args.push(path);
return {
command: 'JSON.TYPE',
args: args
}
}
/**
* Increasing JSON key value by number
* @param key The name of the key
* @param number The number to increase by
* @param path The path of the key
* @returns Bulk String, specifically the stringified new value.
*/
numincrby(key: string, number: number, path?: string): CommandData {
const args = [key];
if(path !== undefined) args.push(path);
args.push(`${number}`);
return {
command: 'JSON.NUMINCRBY',
args: args
}
}
/**
* Multiplying JSON key value by number
* @param key The name of the key
* @param number The number to multiply by
* @param path The path of the key
* @returns Bulk String, specifically the stringified new value.
*/
nummultby(key: string, number: number, path?: string): CommandData {
const args = [key];
if(path !== undefined) args.push(path);
args.push(`${number}`);
return {
command: 'JSON.NUMMULTBY',
args: args
}
}
/**
* Appending string to JSON key string value
* @param key The name of the key
* @param string The string to append to key value
* @param path The path of the key
* @returns Integer, specifically the string's new length.
*/
strappend(key: string, string: string, path?: string): CommandData {
const args = [key];
if(path !== undefined) args.push(path);
return {
command: 'JSON.STRAPPEND',
args: args.concat(string)
};
}
/**
* Retrieving the length of a JSON key value
* @param key The name of the key
* @param path The path of the key
* @returns Integer, specifically the string's length.
*/
strlen(key: string, path?: string): CommandData {
const args = [key];
if(path !== undefined) args.push(path);
return {
command: 'JSON.STRLEN',
args: args
}
}
/**
* Appending string to JSON key array value
* @param key The name of the key
* @param items The items to append to an existing JSON array
* @param path The path of the key
* @returns Integer, specifically the array's new size.
*/
arrappend(key: string, items: string[], path?: string): CommandData {
const args = [key];
if(path !== undefined) args.push(path);
return {
command: 'JSON.ARRAPPEND',
args: args.concat(items)
}
}
/**
* Retrieving JSON key array item by index
* @param key The name of the key
* @param scalar The scalar to filter out a JSON key
* @param path The path of the key
* @returns Integer, specifically the position of the scalar value in the array, or -1 if unfound.
*/
arrindex(key: string, scalar: string, path?: string): CommandData {
const args = [key];
if(path !== undefined) args.push(path);
args.push(scalar);
return {
command: 'JSON.ARRINDEX',
args: args
}
}
/**
* Inserting item into JSON key array
* @param key The name of the key
* @param index The index to insert the JSON into the array
* @param json The JSON string to insert into the array
* @param path The path of the key
* @returns Integer, specifically the array's new size.
*/
arrinsert(key: string, index: number, json: string, path?: string): CommandData {
let args = [key];
if(path !== undefined) args.push(path);
args = args.concat([`${index}`, `${json}`])
return {
command: 'JSON.ARRINSERT',
args: args
}
}
/**
* Retrieving the length of a JSON key array
* @param key The name of the key
* @param path The path of the key
* @returns Integer, specifically the array's length.
*/
arrlen(key: string, path?: string): CommandData {
const args = [key];
if(path !== undefined) args.push(path);
return {
command: 'JSON.ARRLEN',
args: args
}
}
/**
* Poping an array item by index
* @param key The name of the key
* @param index The index of the array item to pop
* @param path The path of the key
* @returns Bulk String, specifically the popped JSON value.
*/
arrpop(key: string, index: number, path?: string): CommandData {
const args = [key];
if(path !== undefined) args.push(path);
args.push(`${index}`);
return {
command: 'JSON.ARRPOP',
args: args
}
}
/**
* Triming an array by index range
* @param key The name of the key
* @param start The starting index of the trim
* @param end The ending index of the trim
* @param path The path of the key
* @returns Integer, specifically the array's new size.
*/
arrtrim(key: string, start: number, end: number, path?: string): CommandData {
let args = [key];
if(path !== undefined) args.push(path);
args = args.concat([`${start}`, `${end}`]);
return {
command: 'JSON.ARRTRIM',
args: args
}
}
/**
* Retrieving an array of JSON keys
* @param key The name of the key
* @param path The path of the key
* @returns Array, specifically the key names in the object as Bulk Strings.
*/
objkeys(key: string, path?: string): CommandData {
const args = [key];
if(path !== undefined) args.push(path);
return {
command: 'JSON.OBJKEYS',
args: args
}
}
/**
* Retrieving the length of a JSON
* @param key The name of the key
* @param path The path of the key
* @returns Integer, specifically the number of keys in the object.
*/
objlen(key: string, path?: string): CommandData {
const args = [key];
if(path !== undefined) args.push(path);
return {
command: 'JSON.OBJLEN',
args: args
}
}
/**
* Executing debug command
* @param subcommand The subcommand of the debug command
* @param key The name of the key
* @param path The path of the key
* @returns
MEMORY returns an integer, specifically the size in bytes of the value
HELP returns an array, specifically with the help message
*/
debug(subcommand: 'MEMORY' | 'HELP', key?: string, path?: string): CommandData {
const args: string[] = [subcommand];
if(subcommand === 'MEMORY') {
if(key !== undefined) args.push(key);
if(path !== undefined) args.push(path);
}
return {
command: 'JSON.DEBUG',
args: args
}
}
/**
* An alias of delCommand
* @param key The name of the key
* @param path The path of the key
* @returns The number of paths deleted (0 or 1).
*/
forget(key: string, path?: string): CommandData {
const parameters = [key];
if(path !== undefined) parameters.push(path)
return {
command: 'JSON.FORGET',
args: parameters
}
}
/**
* Retrieving a JSON key value in RESP protocol
* @param key The name of the key
* @param path The path of the key
* @returns Array, specifically the JSON's RESP form as detailed.
*/
resp(key: string, path?: string): CommandData {
const parameters = [key];
if(path !== undefined) parameters.push(path)
return {
command: 'JSON.RESP',
args: parameters
}
}
} | the_stack |
import { HttpOperationResponse } from '@azure/ms-rest-js';
import { AzExtRequestPrepareOptions, sendRequestWithTimeout } from '@microsoft/vscode-azext-azureutils';
import { IActionContext, UserCancelledError } from '@microsoft/vscode-azext-utils';
import * as unixPsTree from 'ps-tree';
import * as vscode from 'vscode';
import { hostStartTaskName } from '../constants';
import { IPreDebugValidateResult, preDebugValidate } from '../debug/validatePreDebug';
import { ext } from '../extensionVariables';
import { getFuncPortFromTaskOrProject, IRunningFuncTask, isFuncHostTask, runningFuncTaskMap, stopFuncTaskIfRunning } from '../funcCoreTools/funcHostTask';
import { localize } from '../localize';
import { delay } from '../utils/delay';
import { requestUtils } from '../utils/requestUtils';
import { taskUtils } from '../utils/taskUtils';
import { getWindowsProcessTree, IProcessInfo, IWindowsProcessTree, ProcessDataFlag } from '../utils/windowsProcessTree';
import { getWorkspaceSetting } from '../vsCodeConfig/settings';
const funcTaskReadyEmitter = new vscode.EventEmitter<vscode.WorkspaceFolder>();
export const onDotnetFuncTaskReady = funcTaskReadyEmitter.event;
export async function pickFuncProcess(context: IActionContext, debugConfig: vscode.DebugConfiguration): Promise<string | undefined> {
const result: IPreDebugValidateResult = await preDebugValidate(context, debugConfig);
if (!result.shouldContinue) {
throw new UserCancelledError('preDebugValidate');
}
await waitForPrevFuncTaskToStop(result.workspace);
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const preLaunchTaskName: string | undefined = debugConfig.preLaunchTask;
const tasks: vscode.Task[] = await vscode.tasks.fetchTasks();
const funcTask: vscode.Task | undefined = tasks.find(t => {
return t.scope === result.workspace && (preLaunchTaskName ? t.name === preLaunchTaskName : isFuncHostTask(t));
});
if (!funcTask) {
throw new Error(localize('noFuncTask', 'Failed to find "{0}" task.', preLaunchTaskName || hostStartTaskName));
}
const taskInfo = await startFuncTask(context, result.workspace, funcTask);
return await pickChildProcess(taskInfo);
}
async function waitForPrevFuncTaskToStop(workspaceFolder: vscode.WorkspaceFolder): Promise<void> {
stopFuncTaskIfRunning(workspaceFolder);
const timeoutInSeconds: number = 30;
const maxTime: number = Date.now() + timeoutInSeconds * 1000;
while (Date.now() < maxTime) {
if (!runningFuncTaskMap.has(workspaceFolder)) {
return;
}
await delay(1000);
}
throw new Error(localize('failedToFindFuncHost', 'Failed to stop previous running Functions host within "{0}" seconds. Make sure the task has stopped before you debug again.', timeoutInSeconds));
}
async function startFuncTask(context: IActionContext, workspaceFolder: vscode.WorkspaceFolder, funcTask: vscode.Task): Promise<IRunningFuncTask> {
const settingKey: string = 'pickProcessTimeout';
const settingValue: number | undefined = getWorkspaceSetting<number>(settingKey);
const timeoutInSeconds: number = Number(settingValue);
if (isNaN(timeoutInSeconds)) {
throw new Error(localize('invalidSettingValue', 'The setting "{0}" must be a number, but instead found "{1}".', settingKey, settingValue));
}
context.telemetry.properties.timeoutInSeconds = timeoutInSeconds.toString();
let taskError: Error | undefined;
const errorListener: vscode.Disposable = vscode.tasks.onDidEndTaskProcess((e: vscode.TaskProcessEndEvent) => {
if (e.execution.task.scope === workspaceFolder && e.exitCode !== 0) {
context.errorHandling.suppressReportIssue = true;
// Throw if _any_ task fails, not just funcTask (since funcTask often depends on build/clean tasks)
taskError = new Error(localize('taskFailed', 'Error exists after running preLaunchTask "{0}". View task output for more information.', e.execution.task.name, e.exitCode));
errorListener.dispose();
}
});
try {
// The "IfNotActive" part helps when the user starts, stops and restarts debugging quickly in succession. We want to use the already-active task to avoid two func tasks causing a port conflict error
// The most common case we hit this is if the "clean" or "build" task is running when we get here. It's unlikely the "func host start" task is active, since we would've stopped it in `waitForPrevFuncTaskToStop` above
await taskUtils.executeIfNotActive(funcTask);
const intervalMs: number = 500;
const funcPort: string = await getFuncPortFromTaskOrProject(context, funcTask, workspaceFolder);
let statusRequestTimeout: number = intervalMs;
const maxTime: number = Date.now() + timeoutInSeconds * 1000;
while (Date.now() < maxTime) {
if (taskError !== undefined) {
throw taskError;
}
const taskInfo: IRunningFuncTask | undefined = runningFuncTaskMap.get(workspaceFolder);
if (taskInfo) {
for (const scheme of ['http', 'https']) {
const statusRequest: AzExtRequestPrepareOptions = { url: `${scheme}://localhost:${funcPort}/admin/host/status`, method: 'GET' };
if (scheme === 'https') {
statusRequest.rejectUnauthorized = false;
}
try {
// wait for status url to indicate functions host is running
const response: HttpOperationResponse = await sendRequestWithTimeout(context, statusRequest, statusRequestTimeout, undefined);
// eslint-disable-next-line @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-member-access
if (response.parsedBody.state.toLowerCase() === 'running') {
funcTaskReadyEmitter.fire(workspaceFolder);
return taskInfo;
}
} catch (error) {
if (requestUtils.isTimeoutError(error)) {
// Timeout likely means localhost isn't ready yet, but we'll increase the timeout each time it fails just in case it's a slow computer that can't handle a request that fast
statusRequestTimeout *= 2;
context.telemetry.measurements.maxStatusTimeout = statusRequestTimeout;
} else {
// ignore
}
}
}
}
await delay(intervalMs);
}
throw new Error(localize('failedToFindFuncHost', 'Failed to detect running Functions host within "{0}" seconds. You may want to adjust the "{1}" setting.', timeoutInSeconds, `${ext.prefix}.${settingKey}`));
} finally {
errorListener.dispose();
}
}
type OSAgnosticProcess = { command: string | undefined; pid: number | string };
/**
* Picks the child process that we want to use. Scenarios to keep in mind:
* 1. On Windows, the rootPid is almost always the parent PowerShell process
* 2. On Unix, the rootPid may be a wrapper around the main func exe if installed with npm
* 3. Starting with the .NET 5 worker, Windows sometimes has an inner process we _don't_ want like 'conhost.exe'
* The only processes we should want to attach to are the "func" process itself or a "dotnet" process running a dll, so we will pick the innermost one of those
*/
async function pickChildProcess(taskInfo: IRunningFuncTask): Promise<string> {
// Workaround for https://github.com/microsoft/vscode-azurefunctions/issues/2656
if (!isRunning(taskInfo.processId) && vscode.window.activeTerminal) {
const terminalPid = await vscode.window.activeTerminal.processId
if (terminalPid) {
// NOTE: Intentionally updating the object so that `runningFuncTaskMap` is affected, too
taskInfo.processId = terminalPid;
}
}
const children: OSAgnosticProcess[] = process.platform === 'win32' ? await getWindowsChildren(taskInfo.processId) : await getUnixChildren(taskInfo.processId);
const child: OSAgnosticProcess | undefined = children.reverse().find(c => /(dotnet|func)(\.exe|)$/i.test(c.command || ''));
return child ? child.pid.toString() : String(taskInfo.processId);
}
// Looks like this bug was fixed, but never merged:
// https://github.com/indexzero/ps-tree/issues/18
type ActualUnixPS = unixPsTree.PS & { COMM?: string };
async function getUnixChildren(pid: number): Promise<OSAgnosticProcess[]> {
const processes: ActualUnixPS[] = await new Promise((resolve, reject): void => {
unixPsTree(pid, (error: Error | null, result: unixPsTree.PS[]) => {
if (error) {
reject(error);
} else {
resolve(result);
}
});
});
return processes.map(c => { return { command: c.COMMAND || c.COMM, pid: c.PID }; });
}
async function getWindowsChildren(pid: number): Promise<OSAgnosticProcess[]> {
const windowsProcessTree: IWindowsProcessTree = getWindowsProcessTree();
const processes: (IProcessInfo[] | undefined) = await new Promise((resolve): void => {
windowsProcessTree.getProcessList(pid, resolve, ProcessDataFlag.None);
});
return (processes || []).map(c => { return { command: c.name, pid: c.pid }; });
}
function isRunning(pid: number): boolean {
try {
// https://nodejs.org/api/process.html#process_process_kill_pid_signal
// This method will throw an error if the target pid does not exist. As a special case, a signal of 0 can be used to test for the existence of a process.
// Even though the name of this function is process.kill(), it is really just a signal sender, like the kill system call.
process.kill(pid, 0);
return true;
} catch {
return false;
}
} | the_stack |
import Cell from '../cell/Cell';
import CellArray from '../cell/CellArray';
import { mixInto } from '../../util/Utils';
import { removeDuplicates } from '../../util/arrayUtils';
import { findNearestSegment } from '../../util/mathUtils';
import Geometry from '../geometry/Geometry';
import EventObject from '../event/EventObject';
import InternalEvent from '../event/InternalEvent';
import Dictionary from '../../util/Dictionary';
import { Graph } from '../Graph';
import Point from '../geometry/Point';
declare module '../Graph' {
interface Graph {
resetEdgesOnResize: boolean;
resetEdgesOnMove: false;
resetEdgesOnConnect: boolean;
connectableEdges: boolean;
allowDanglingEdges: boolean;
cloneInvalidEdges: boolean;
alternateEdgeStyle: string | null;
edgeLabelsMovable: boolean;
isResetEdgesOnMove: () => boolean;
isResetEdgesOnConnect: () => boolean;
isResetEdgesOnResize: () => boolean;
isEdgeLabelsMovable: () => boolean;
setEdgeLabelsMovable: (value: boolean) => void;
setAllowDanglingEdges: (value: boolean) => void;
isAllowDanglingEdges: () => boolean;
setConnectableEdges: (value: boolean) => void;
isConnectableEdges: () => boolean;
setCloneInvalidEdges: (value: boolean) => void;
isCloneInvalidEdges: () => boolean;
flipEdge: (edge: Cell) => Cell;
splitEdge: (
edge: Cell,
cells: CellArray,
newEdge: Cell | null,
dx?: number,
dy?: number,
x?: number,
y?: number,
parent?: Cell | null
) => Cell;
insertEdge: (...args: any[]) => Cell;
createEdge: (
parent: Cell | null,
id: string,
value: any,
source: Cell | null,
target: Cell | null,
style: any
) => Cell;
addEdge: (
edge: Cell,
parent: Cell | null,
source: Cell | null,
target: Cell | null,
index?: number | null
) => Cell;
addAllEdges: (cells: CellArray) => CellArray;
getAllEdges: (cells: CellArray | null) => CellArray;
getIncomingEdges: (cell: Cell, parent: Cell | null) => CellArray;
getOutgoingEdges: (cell: Cell, parent: Cell | null) => CellArray;
getEdges: (
cell: Cell,
parent?: Cell | null,
incoming?: boolean,
outgoing?: boolean,
includeLoops?: boolean,
recurse?: boolean
) => CellArray;
getChildEdges: (parent: Cell) => CellArray;
getEdgesBetween: (source: Cell, target: Cell, directed?: boolean) => CellArray;
resetEdges: (cells: CellArray) => void;
resetEdge: (edge: Cell) => Cell;
}
}
type PartialGraph = Pick<
Graph,
| 'batchUpdate'
| 'fireEvent'
| 'getDataModel'
| 'getView'
| 'getChildCells'
| 'isValidAncestor'
| 'cellsAdded'
| 'cellsMoved'
| 'cloneCell'
| 'addCell'
| 'cellConnected'
>;
type PartialEdge = Pick<
Graph,
| 'resetEdgesOnResize'
| 'resetEdgesOnMove'
| 'resetEdgesOnConnect'
| 'connectableEdges'
| 'allowDanglingEdges'
| 'cloneInvalidEdges'
| 'alternateEdgeStyle'
| 'edgeLabelsMovable'
| 'isResetEdgesOnMove'
| 'isResetEdgesOnConnect'
| 'isResetEdgesOnResize'
| 'isEdgeLabelsMovable'
| 'setEdgeLabelsMovable'
| 'setAllowDanglingEdges'
| 'isAllowDanglingEdges'
| 'setConnectableEdges'
| 'isConnectableEdges'
| 'setCloneInvalidEdges'
| 'isCloneInvalidEdges'
| 'flipEdge'
| 'splitEdge'
| 'insertEdge'
| 'createEdge'
| 'addEdge'
| 'addAllEdges'
| 'getAllEdges'
| 'getIncomingEdges'
| 'getOutgoingEdges'
| 'getEdges'
| 'getChildEdges'
| 'getEdgesBetween'
| 'resetEdges'
| 'resetEdge'
>;
type PartialType = PartialGraph & PartialEdge;
// @ts-expect-error The properties of PartialGraph are defined elsewhere.
const EdgeMixin: PartialType = {
/**
* Specifies if edge control points should be reset after the resize of a
* connected cell.
* @default false
*/
resetEdgesOnResize: false,
isResetEdgesOnResize() {
return this.resetEdgesOnResize;
},
/**
* Specifies if edge control points should be reset after the move of a
* connected cell.
* @default false
*/
resetEdgesOnMove: false,
isResetEdgesOnMove() {
return this.resetEdgesOnMove;
},
/**
* Specifies if edge control points should be reset after the the edge has been
* reconnected.
* @default true
*/
resetEdgesOnConnect: true,
isResetEdgesOnConnect() {
return this.resetEdgesOnConnect;
},
/**
* Specifies if edges are connectable. This overrides the connectable field in edges.
* @default false
*/
connectableEdges: false,
/**
* Specifies if edges with disconnected terminals are allowed in the graph.
* @default true
*/
allowDanglingEdges: true,
/**
* Specifies if edges that are cloned should be validated and only inserted
* if they are valid.
* @default true
*/
cloneInvalidEdges: false,
/**
* Specifies the alternate edge style to be used if the main control point
* on an edge is being double clicked.
* @default null
*/
alternateEdgeStyle: null,
/**
* Specifies the return value for edges in {@link isLabelMovable}.
* @default true
*/
edgeLabelsMovable: true,
/*****************************************************************************
* Group: Graph Behaviour
*****************************************************************************/
/**
* Returns {@link edgeLabelsMovable}.
*/
isEdgeLabelsMovable() {
return this.edgeLabelsMovable;
},
/**
* Sets {@link edgeLabelsMovable}.
*/
setEdgeLabelsMovable(value) {
this.edgeLabelsMovable = value;
},
/**
* Specifies if dangling edges are allowed, that is, if edges are allowed
* that do not have a source and/or target terminal defined.
*
* @param value Boolean indicating if dangling edges are allowed.
*/
setAllowDanglingEdges(value) {
this.allowDanglingEdges = value;
},
/**
* Returns {@link allowDanglingEdges} as a boolean.
*/
isAllowDanglingEdges() {
return this.allowDanglingEdges;
},
/**
* Specifies if edges should be connectable.
*
* @param value Boolean indicating if edges should be connectable.
*/
setConnectableEdges(value) {
this.connectableEdges = value;
},
/**
* Returns {@link connectableEdges} as a boolean.
*/
isConnectableEdges() {
return this.connectableEdges;
},
/**
* Specifies if edges should be inserted when cloned but not valid wrt.
* {@link getEdgeValidationError}. If false such edges will be silently ignored.
*
* @param value Boolean indicating if cloned invalid edges should be
* inserted into the graph or ignored.
*/
setCloneInvalidEdges(value) {
this.cloneInvalidEdges = value;
},
/**
* Returns {@link cloneInvalidEdges} as a boolean.
*/
isCloneInvalidEdges() {
return this.cloneInvalidEdges;
},
/*****************************************************************************
* Group: Cell alignment and orientation
*****************************************************************************/
/**
* Toggles the style of the given edge between null (or empty) and
* {@link alternateEdgeStyle}. This method fires {@link InternalEvent.FLIP_EDGE} while the
* transaction is in progress. Returns the edge that was flipped.
*
* Here is an example that overrides this implementation to invert the
* value of {@link 'elbow'} without removing any existing styles.
*
* ```javascript
* graph.flipEdge = function(edge)
* {
* if (edge != null)
* {
* var style = this.getCurrentCellStyle(edge);
* var elbow = mxUtils.getValue(style, 'elbow',
* mxConstants.ELBOW_HORIZONTAL);
* var value = (elbow == mxConstants.ELBOW_HORIZONTAL) ?
* mxConstants.ELBOW_VERTICAL : mxConstants.ELBOW_HORIZONTAL;
* this.setCellStyles('elbow', value, [edge]);
* }
* };
* ```
*
* @param edge {@link mxCell} whose style should be changed.
*/
flipEdge(edge) {
if (this.alternateEdgeStyle) {
this.batchUpdate(() => {
const style = edge.getStyle();
if (!style || style.length === 0) {
this.getDataModel().setStyle(edge, this.alternateEdgeStyle);
} else {
this.getDataModel().setStyle(edge, null);
}
// Removes all existing control points
this.resetEdge(edge);
this.fireEvent(new EventObject(InternalEvent.FLIP_EDGE, { edge }));
});
}
return edge;
},
/**
* Splits the given edge by adding the newEdge between the previous source
* and the given cell and reconnecting the source of the given edge to the
* given cell. This method fires {@link Event#SPLIT_EDGE} while the transaction
* is in progress. Returns the new edge that was inserted.
*
* @param edge <Cell> that represents the edge to be splitted.
* @param cells {@link Cells} that represents the cells to insert into the edge.
* @param newEdge <Cell> that represents the edge to be inserted.
* @param dx Optional integer that specifies the vector to move the cells.
* @param dy Optional integer that specifies the vector to move the cells.
* @param x Integer that specifies the x-coordinate of the drop location.
* @param y Integer that specifies the y-coordinate of the drop location.
* @param parent Optional parent to insert the cell. If null the parent of
* the edge is used.
*/
splitEdge(edge, cells, newEdge, dx = 0, dy = 0, x, y, parent = null) {
parent = parent ?? edge.getParent();
const source = edge.getTerminal(true);
this.batchUpdate(() => {
if (!newEdge) {
newEdge = this.cloneCell(edge);
// Removes waypoints before/after new cell
const state = this.getView().getState(edge);
let geo: Geometry | null = newEdge.getGeometry();
if (geo && state) {
const t = this.getView().translate;
const s = this.getView().scale;
const idx = findNearestSegment(state, (dx + t.x) * s, (dy + t.y) * s);
geo.points = (<Point[]>geo.points).slice(0, idx);
geo = edge.getGeometry();
if (geo) {
geo = geo.clone();
geo.points = (<Point[]>geo.points).slice(idx);
this.getDataModel().setGeometry(edge, geo);
}
}
}
this.cellsMoved(cells, dx, dy, false, false);
this.cellsAdded(
cells,
parent as Cell,
parent ? parent.getChildCount() : 0,
null,
null,
true
);
this.cellsAdded(
new CellArray(newEdge),
parent as Cell,
parent ? parent.getChildCount() : 0,
source,
cells[0],
false
);
this.cellConnected(edge, cells[0], true);
this.fireEvent(
new EventObject(InternalEvent.SPLIT_EDGE, { edge, cells, newEdge, dx, dy })
);
});
return newEdge as Cell;
},
/**
* Adds a new edge into the given parent {@link Cell} using value as the user
* object and the given source and target as the terminals of the new edge.
* The id and style are used for the respective properties of the new
* {@link Cell}, which is returned.
*
* @param parent {@link mxCell} that specifies the parent of the new edge.
* @param id Optional string that defines the Id of the new edge.
* @param value JavaScript object to be used as the user object.
* @param source {@link mxCell} that defines the source of the edge.
* @param target {@link mxCell} that defines the target of the edge.
* @param style Optional string that defines the cell style.
*/
insertEdge(...args) {
let parent: Cell;
let id: string = '';
let value: any; // note me - can be a string or a class instance!!!
let source: Cell;
let target: Cell;
let style: string = ''; // TODO: Also allow for an object or class instance??
if (args.length === 1) {
// If only a single parameter, treat as an object
// This syntax can be more readable
const params = args[0];
parent = params.parent;
id = params.id || '';
value = params.value || '';
source = params.source;
target = params.target;
style = params.style;
} else {
// otherwise treat as individual arguments
[parent, id, value, source, target, style] = args;
}
const edge = this.createEdge(parent, id, value, source, target, style);
return this.addEdge(edge, parent, source, target);
},
/**
* Hook method that creates the new edge for {@link insertEdge}. This
* implementation does not set the source and target of the edge, these
* are set when the edge is added to the model.
*
*/
createEdge(parent = null, id, value, source = null, target = null, style) {
// Creates the edge
const edge = new Cell(value, new Geometry(), style);
edge.setId(id);
edge.setEdge(true);
(<Geometry>edge.geometry).relative = true;
return edge;
},
/**
* Adds the edge to the parent and connects it to the given source and
* target terminals. This is a shortcut method. Returns the edge that was
* added.
*
* @param edge {@link mxCell} to be inserted into the given parent.
* @param parent {@link mxCell} that represents the new parent. If no parent is
* given then the default parent is used.
* @param source Optional {@link Cell} that represents the source terminal.
* @param target Optional {@link Cell} that represents the target terminal.
* @param index Optional index to insert the cells at. Default is 'to append'.
*/
addEdge(edge, parent = null, source = null, target = null, index = null) {
return this.addCell(edge, parent, index, source, target);
},
/*****************************************************************************
* Group: Folding
*****************************************************************************/
/**
* Returns an array with the given cells and all edges that are connected
* to a cell or one of its descendants.
*/
addAllEdges(cells) {
const allCells = cells.slice();
return new CellArray(...removeDuplicates(allCells.concat(this.getAllEdges(cells))));
},
/**
* Returns all edges connected to the given cells or its descendants.
*/
getAllEdges(cells) {
let edges: CellArray = new CellArray();
if (cells) {
for (let i = 0; i < cells.length; i += 1) {
const edgeCount = cells[i].getEdgeCount();
for (let j = 0; j < edgeCount; j++) {
edges.push(cells[i].getEdgeAt(j));
}
// Recurses
const children = cells[i].getChildren();
edges = edges.concat(this.getAllEdges(children));
}
}
return edges;
},
/**
* Returns the visible incoming edges for the given cell. If the optional
* parent argument is specified, then only child edges of the given parent
* are returned.
*
* @param cell {@link mxCell} whose incoming edges should be returned.
* @param parent Optional parent of the opposite end for an edge to be
* returned.
*/
getIncomingEdges(cell, parent = null) {
return this.getEdges(cell, parent, true, false, false);
},
/**
* Returns the visible outgoing edges for the given cell. If the optional
* parent argument is specified, then only child edges of the given parent
* are returned.
*
* @param cell {@link mxCell} whose outgoing edges should be returned.
* @param parent Optional parent of the opposite end for an edge to be
* returned.
*/
getOutgoingEdges(cell, parent = null) {
return this.getEdges(cell, parent, false, true, false);
},
/**
* Returns the incoming and/or outgoing edges for the given cell.
* If the optional parent argument is specified, then only edges are returned
* where the opposite is in the given parent cell. If at least one of incoming
* or outgoing is true, then loops are ignored, if both are false, then all
* edges connected to the given cell are returned including loops.
*
* @param cell <Cell> whose edges should be returned.
* @param parent Optional parent of the opposite end for an edge to be
* returned.
* @param incoming Optional boolean that specifies if incoming edges should
* be included in the result. Default is true.
* @param outgoing Optional boolean that specifies if outgoing edges should
* be included in the result. Default is true.
* @param includeLoops Optional boolean that specifies if loops should be
* included in the result. Default is true.
* @param recurse Optional boolean the specifies if the parent specified only
* need be an ancestral parent, true, or the direct parent, false.
* Default is false
*/
getEdges(
cell,
parent = null,
incoming = true,
outgoing = true,
includeLoops = true,
recurse = false
) {
let edges: CellArray = new CellArray();
const isCollapsed = cell.isCollapsed();
const childCount = cell.getChildCount();
for (let i = 0; i < childCount; i += 1) {
const child = cell.getChildAt(i);
if (isCollapsed || !child.isVisible()) {
edges = edges.concat(child.getEdges(incoming, outgoing));
}
}
edges = edges.concat(cell.getEdges(incoming, outgoing));
const result = new CellArray();
for (let i = 0; i < edges.length; i += 1) {
const state = this.getView().getState(edges[i]);
const source = state
? state.getVisibleTerminal(true)
: this.getView().getVisibleTerminal(edges[i], true);
const target = state
? state.getVisibleTerminal(false)
: this.getView().getVisibleTerminal(edges[i], false);
if (
(includeLoops && source === target) ||
(source !== target &&
((incoming &&
target === cell &&
(!parent || this.isValidAncestor(<Cell>source, parent, recurse))) ||
(outgoing &&
source === cell &&
(!parent || this.isValidAncestor(<Cell>target, parent, recurse)))))
) {
result.push(edges[i]);
}
}
return result;
},
/*****************************************************************************
* Group: Cell retrieval
*****************************************************************************/
/**
* Returns the visible child edges of the given parent.
*
* @param parent {@link mxCell} whose child vertices should be returned.
*/
getChildEdges(parent) {
return this.getChildCells(parent, false, true);
},
/**
* Returns the edges between the given source and target. This takes into
* account collapsed and invisible cells and returns the connected edges
* as displayed on the screen.
*
* source -
* target -
* directed -
*/
getEdgesBetween(source, target, directed = false) {
const edges = this.getEdges(source);
const result = new CellArray();
// Checks if the edge is connected to the correct
// cell and returns the first match
for (let i = 0; i < edges.length; i += 1) {
const state = this.getView().getState(edges[i]);
const src = state
? state.getVisibleTerminal(true)
: this.getView().getVisibleTerminal(edges[i], true);
const trg = state
? state.getVisibleTerminal(false)
: this.getView().getVisibleTerminal(edges[i], false);
if (
(src === source && trg === target) ||
(!directed && src === target && trg === source)
) {
result.push(edges[i]);
}
}
return result;
},
/*****************************************************************************
* Group: Cell moving
*****************************************************************************/
/**
* Resets the control points of the edges that are connected to the given
* cells if not both ends of the edge are in the given cells array.
*
* @param cells Array of {@link Cell} for which the connected edges should be
* reset.
*/
resetEdges(cells) {
// Prepares faster cells lookup
const dict = new Dictionary();
for (let i = 0; i < cells.length; i += 1) {
dict.put(cells[i], true);
}
this.batchUpdate(() => {
for (let i = 0; i < cells.length; i += 1) {
const edges = cells[i].getEdges();
for (let j = 0; j < edges.length; j++) {
const state = this.getView().getState(edges[j]);
const source = state
? state.getVisibleTerminal(true)
: this.getView().getVisibleTerminal(edges[j], true);
const target = state
? state.getVisibleTerminal(false)
: this.getView().getVisibleTerminal(edges[j], false);
// Checks if one of the terminals is not in the given array
if (!dict.get(source) || !dict.get(target)) {
this.resetEdge(edges[j]);
}
}
this.resetEdges(cells[i].getChildren());
}
});
},
/**
* Resets the control points of the given edge.
*
* @param edge {@link mxCell} whose points should be reset.
*/
resetEdge(edge) {
let geo = edge.getGeometry();
// Resets the control points
if (geo && geo.points && (<Point[]>geo.points).length > 0) {
geo = geo.clone();
geo.points = [];
this.getDataModel().setGeometry(edge, geo);
}
return edge;
},
};
mixInto(Graph)(EdgeMixin); | the_stack |
import * as React from 'react';
import { Button, Expandable, Modal, Tab, Tabs } from '@patternfly/react-core';
import { WorkloadOverview } from '../../types/ServiceInfo';
import * as API from '../../services/Api';
import { Response } from '../../services/Api';
import * as AlertUtils from '../../utils/AlertUtils';
import RequestRouting from './RequestRouting';
import TrafficShifting, { WorkloadWeight } from './TrafficShifting';
import TrafficPolicyContainer, {
ConsistentHashType,
TrafficPolicyState,
UNSET
} from '../../components/IstioWizards/TrafficPolicy';
import { ROUND_ROBIN } from './TrafficPolicy';
import FaultInjection, { FaultInjectionRoute } from './FaultInjection';
import { Rule } from './RequestRouting/Rules';
import {
buildIstioConfig,
fqdnServiceName,
getInitGateway,
getInitHosts,
getInitLoadBalancer,
getInitPeerAuthentication,
getInitRules,
getInitTlsMode,
getInitWeights,
hasGateway,
WIZARD_REQUEST_ROUTING,
WIZARD_FAULT_INJECTION,
WIZARD_TITLES,
WIZARD_TRAFFIC_SHIFTING,
ServiceWizardProps,
ServiceWizardState,
getInitFaultInjectionRoute,
WIZARD_REQUEST_TIMEOUTS,
getInitTimeoutRetryRoute,
getInitConnectionPool,
getInitOutlierDetection,
WIZARD_TCP_TRAFFIC_SHIFTING
} from './WizardActions';
import { MessageType } from '../../types/MessageCenter';
import GatewaySelector, { GatewaySelectorState } from './GatewaySelector';
import VirtualServiceHosts from './VirtualServiceHosts';
import { DestinationRule, PeerAuthentication, PeerAuthenticationMutualTLSMode } from '../../types/IstioObjects';
import { style } from 'typestyle';
import RequestTimeouts, { TimeoutRetryRoute } from './RequestTimeouts';
import CircuitBreaker, { CircuitBreakerState } from './CircuitBreaker';
import _ from 'lodash';
const emptyServiceWizardState = (fqdnServiceName: string): ServiceWizardState => {
return {
showWizard: false,
showAdvanced: false,
advancedTabKey: 0,
workloads: [],
rules: [],
faultInjectionRoute: {
workloads: [],
delayed: false,
delay: {
percentage: {
value: 100
},
fixedDelay: '5s'
},
isValidDelay: true,
aborted: false,
abort: {
percentage: {
value: 100
},
httpStatus: 503
},
isValidAbort: true
},
timeoutRetryRoute: {
workloads: [],
isTimeout: false,
timeout: '2s',
isValidTimeout: true,
isRetry: false,
retries: {
attempts: 3,
perTryTimeout: '2s',
retryOn: 'gateway-error,connect-failure,refused-stream'
},
isValidRetry: true
},
valid: {
mainWizard: true,
vsHosts: true,
tls: true,
lb: true,
gateway: true,
cp: true,
od: true
},
advancedOptionsValid: true,
vsHosts: [fqdnServiceName],
trafficPolicy: {
tlsModified: false,
mtlsMode: UNSET,
clientCertificate: '',
privateKey: '',
caCertificates: '',
addLoadBalancer: false,
simpleLB: false,
consistentHashType: ConsistentHashType.HTTP_HEADER_NAME,
loadBalancer: {
simple: ROUND_ROBIN
},
peerAuthnSelector: {
addPeerAuthentication: false,
addPeerAuthnModified: false,
mode: PeerAuthenticationMutualTLSMode.UNSET
},
addConnectionPool: false,
connectionPool: {},
addOutlierDetection: false,
outlierDetection: {}
},
gateway: undefined
};
};
const advancedOptionsStyle = style({
marginTop: 10
});
class ServiceWizard extends React.Component<ServiceWizardProps, ServiceWizardState> {
constructor(props: ServiceWizardProps) {
super(props);
this.state = emptyServiceWizardState(fqdnServiceName(props.serviceName, props.namespace));
}
componentDidUpdate(prevProps: ServiceWizardProps) {
if (prevProps.show !== this.props.show || !this.compareWorkloads(prevProps.workloads, this.props.workloads)) {
let isMainWizardValid: boolean;
switch (this.props.type) {
// By default the rule of Weighted routing should be valid
case WIZARD_TRAFFIC_SHIFTING:
isMainWizardValid = true;
break;
// By default no rules is a no valid scenario
case WIZARD_REQUEST_ROUTING:
isMainWizardValid = false;
break;
case WIZARD_FAULT_INJECTION:
case WIZARD_REQUEST_TIMEOUTS:
default:
isMainWizardValid = true;
break;
}
const initVsHosts = getInitHosts(this.props.virtualServices);
const [initMtlsMode, initClientCertificate, initPrivateKey, initCaCertificates] = getInitTlsMode(
this.props.destinationRules
);
const initLoadBalancer = getInitLoadBalancer(this.props.destinationRules);
let initConsistentHashType = ConsistentHashType.HTTP_HEADER_NAME;
if (initLoadBalancer && initLoadBalancer.consistentHash) {
if (initLoadBalancer.consistentHash.httpHeaderName) {
initConsistentHashType = ConsistentHashType.HTTP_HEADER_NAME;
} else if (initLoadBalancer.consistentHash.httpCookie) {
initConsistentHashType = ConsistentHashType.HTTP_COOKIE;
} else if (initLoadBalancer.consistentHash.useSourceIp) {
initConsistentHashType = ConsistentHashType.USE_SOURCE_IP;
}
}
const initPeerAuthentication = getInitPeerAuthentication(
this.props.destinationRules,
this.props.peerAuthentications
);
const initConnetionPool = getInitConnectionPool(this.props.destinationRules);
const initOutlierDetection = getInitOutlierDetection(this.props.destinationRules);
const trafficPolicy: TrafficPolicyState = {
tlsModified: initMtlsMode !== '',
mtlsMode: initMtlsMode !== '' ? initMtlsMode : UNSET,
clientCertificate: initClientCertificate,
privateKey: initPrivateKey,
caCertificates: initCaCertificates,
addLoadBalancer: initLoadBalancer !== undefined,
simpleLB: initLoadBalancer !== undefined && initLoadBalancer.simple !== undefined,
consistentHashType: initConsistentHashType,
loadBalancer: initLoadBalancer
? initLoadBalancer
: {
simple: ROUND_ROBIN
},
peerAuthnSelector: {
addPeerAuthentication: initPeerAuthentication !== undefined,
addPeerAuthnModified: false,
mode: initPeerAuthentication || PeerAuthenticationMutualTLSMode.UNSET
},
addConnectionPool: initConnetionPool ? true : false,
connectionPool: initConnetionPool
? initConnetionPool
: {
tcp: {
maxConnections: 1
},
http: {
http1MaxPendingRequests: 1
}
},
addOutlierDetection: initOutlierDetection ? true : false,
outlierDetection: initOutlierDetection
? initOutlierDetection
: {
consecutiveErrors: 1
}
};
const gateway: GatewaySelectorState = {
addGateway: false,
gwHosts: '',
gwHostsValid: false,
newGateway: false,
selectedGateway: '',
addMesh: false,
port: 80
};
if (hasGateway(this.props.virtualServices)) {
const [gatewaySelected, isMesh] = getInitGateway(this.props.virtualServices);
gateway.addGateway = true;
gateway.selectedGateway = gatewaySelected;
gateway.addMesh = isMesh;
}
this.setState({
showWizard: this.props.show,
workloads: [],
rules: [],
valid: {
mainWizard: isMainWizardValid,
vsHosts: true,
tls: true,
lb: true,
gateway: true,
cp: true,
od: true
},
vsHosts:
initVsHosts.length > 1 || (initVsHosts.length === 1 && initVsHosts[0].length > 0)
? initVsHosts
: [fqdnServiceName(this.props.serviceName, this.props.namespace)],
trafficPolicy: trafficPolicy,
gateway: gateway
});
}
}
compareWorkloads = (prev: WorkloadOverview[], current: WorkloadOverview[]): boolean => {
if (prev.length !== current.length) {
return false;
}
for (let i = 0; i < prev.length; i++) {
if (!current.some(w => _.isEqual(w, prev[i]))) {
return false;
}
}
return true;
};
onClose = (changed: boolean) => {
this.setState(emptyServiceWizardState(fqdnServiceName(this.props.serviceName, this.props.namespace)));
this.props.onClose(changed);
};
onCreateUpdate = () => {
const promises: Promise<Response<string>>[] = [];
switch (this.props.type) {
case WIZARD_TRAFFIC_SHIFTING:
case WIZARD_TCP_TRAFFIC_SHIFTING:
case WIZARD_REQUEST_ROUTING:
case WIZARD_FAULT_INJECTION:
case WIZARD_REQUEST_TIMEOUTS:
const [dr, vs, gw, pa] = buildIstioConfig(this.props, this.state);
// Gateway is only created when user has explicit selected this option
if (gw) {
promises.push(API.createIstioConfigDetail(this.props.namespace, 'gateways', JSON.stringify(gw)));
}
if (this.props.update) {
promises.push(
API.updateIstioConfigDetail(this.props.namespace, 'destinationrules', dr.metadata.name, JSON.stringify(dr))
);
promises.push(
API.updateIstioConfigDetail(this.props.namespace, 'virtualservices', vs.metadata.name, JSON.stringify(vs))
);
this.handlePeerAuthnUpdate(pa, dr, promises);
// Note that Gateways are not updated from the Wizard, only the VS hosts/gateways sections are updated
} else {
promises.push(API.createIstioConfigDetail(this.props.namespace, 'destinationrules', JSON.stringify(dr)));
promises.push(API.createIstioConfigDetail(this.props.namespace, 'virtualservices', JSON.stringify(vs)));
if (pa) {
promises.push(API.createIstioConfigDetail(this.props.namespace, 'peerauthentications', JSON.stringify(pa)));
}
}
break;
default:
}
// Disable button before promise is completed. Then Wizard is closed.
this.setState(prevState => {
prevState.valid.mainWizard = false;
return {
valid: prevState.valid
};
});
Promise.all(promises)
.then(results => {
if (results.length > 0) {
AlertUtils.add(
'Istio Config ' +
(this.props.update ? 'updated' : 'created') +
' for ' +
this.props.serviceName +
' service.',
'default',
MessageType.SUCCESS
);
}
this.onClose(true);
})
.catch(error => {
AlertUtils.addError('Could not ' + (this.props.update ? 'update' : 'create') + ' Istio config objects.', error);
this.onClose(true);
});
};
handlePeerAuthnUpdate = (
pa: PeerAuthentication | undefined,
dr: DestinationRule,
promises: Promise<Response<string>>[]
): void => {
if (pa) {
if (this.state.trafficPolicy.peerAuthnSelector.addPeerAuthnModified) {
promises.push(API.createIstioConfigDetail(this.props.namespace, 'peerauthentications', JSON.stringify(pa)));
} else {
promises.push(
API.updateIstioConfigDetail(this.props.namespace, 'peerauthentications', dr.metadata.name, JSON.stringify(pa))
);
}
} else if (this.state.trafficPolicy.peerAuthnSelector.addPeerAuthnModified) {
promises.push(API.deleteIstioConfigDetail(this.props.namespace, 'peerauthentications', dr.metadata.name));
}
};
onVsHosts = (valid: boolean, vsHosts: string[]) => {
this.setState(prevState => {
prevState.valid.vsHosts = valid;
if (prevState.gateway && prevState.gateway.addGateway && prevState.gateway.newGateway) {
prevState.gateway.gwHosts = vsHosts.join(',');
}
// Check if Gateway is valid after a VsHosts check
if (valid && !prevState.valid.gateway) {
const hasVsWildcard = vsHosts.some(h => h === '*');
if (hasVsWildcard) {
if (prevState.gateway && !prevState.gateway.addMesh) {
prevState.valid.gateway = true;
}
} else {
// If no wildcard Gateway should be ok
prevState.valid.gateway = true;
}
}
return {
valid: prevState.valid,
vsHosts: vsHosts
};
});
};
onTrafficPolicy = (valid: boolean, trafficPolicy: TrafficPolicyState) => {
this.setState(prevState => {
// At the moment this callback only updates the valid of the loadbalancer
// tls is always true, but I maintain it on the structure for consistency
prevState.valid.tls = valid;
prevState.valid.lb = valid;
return {
valid: prevState.valid,
trafficPolicy: trafficPolicy
};
});
};
onCircuitBreaker = (circuitBreaker: CircuitBreakerState) => {
this.setState(prevState => {
prevState.valid.cp = circuitBreaker.isValidConnectionPool;
prevState.valid.od = circuitBreaker.isValidOutlierDetection;
prevState.trafficPolicy.addConnectionPool = circuitBreaker.addConnectionPool;
prevState.trafficPolicy.connectionPool = circuitBreaker.connectionPool;
prevState.trafficPolicy.addOutlierDetection = circuitBreaker.addOutlierDetection;
prevState.trafficPolicy.outlierDetection = circuitBreaker.outlierDetection;
return {
valid: prevState.valid,
trafficPolicy: prevState.trafficPolicy
};
});
};
onGateway = (valid: boolean, gateway: GatewaySelectorState) => {
this.setState(prevState => {
prevState.valid.gateway = valid;
return {
valid: prevState.valid,
gateway: gateway,
vsHosts:
gateway.addGateway && gateway.newGateway && gateway.gwHosts.length > 0
? gateway.gwHosts.split(',')
: prevState.vsHosts
};
});
};
onWeightsChange = (valid: boolean, workloads: WorkloadWeight[]) => {
this.setState(prevState => {
prevState.valid.mainWizard = valid;
return {
valid: prevState.valid,
workloads: workloads
};
});
};
onRulesChange = (valid: boolean, rules: Rule[]) => {
this.setState(prevState => {
prevState.valid.mainWizard = valid;
return {
valid: prevState.valid,
rules: rules
};
});
};
onFaultInjectionRouteChange = (valid: boolean, faultInjectionRoute: FaultInjectionRoute) => {
this.setState(prevState => {
prevState.valid.mainWizard = valid;
return {
valid: prevState.valid,
faultInjectionRoute: faultInjectionRoute
};
});
};
onTimeoutRetryRouteChange = (valid: boolean, timeoutRetryRoute: TimeoutRetryRoute) => {
this.setState(prevState => {
prevState.valid.mainWizard = valid;
return {
valid: prevState.valid,
timeoutRetryRoute: timeoutRetryRoute
};
});
};
isValid = (state: ServiceWizardState): boolean => {
return (
state.valid.mainWizard &&
state.valid.vsHosts &&
state.valid.tls &&
state.valid.lb &&
state.valid.gateway &&
state.valid.cp &&
state.valid.od
);
};
advancedHandleTabClick = (_event, tabIndex) => {
this.setState({
advancedTabKey: tabIndex
});
};
render() {
const [gatewaySelected, isMesh] = getInitGateway(this.props.virtualServices);
return (
<Modal
width={'75%'}
title={
this.props.type.length > 0
? this.props.update
? 'Update ' + WIZARD_TITLES[this.props.type]
: 'Create ' + WIZARD_TITLES[this.props.type]
: ''
}
isOpen={this.state.showWizard}
onClose={() => this.onClose(false)}
onKeyPress={e => {
if (e.key === 'Enter' && this.isValid(this.state)) {
this.onCreateUpdate();
}
}}
actions={[
<Button key="cancel" variant="secondary" onClick={() => this.onClose(false)}>
Cancel
</Button>,
<Button isDisabled={!this.isValid(this.state)} key="confirm" variant="primary" onClick={this.onCreateUpdate}>
{this.props.update ? 'Update' : 'Create'}
</Button>
]}
>
{this.props.type === WIZARD_REQUEST_ROUTING && (
<RequestRouting
serviceName={this.props.serviceName}
workloads={this.props.workloads}
initRules={getInitRules(this.props.workloads, this.props.virtualServices, this.props.destinationRules)}
onChange={this.onRulesChange}
/>
)}
{this.props.type === WIZARD_FAULT_INJECTION && (
<FaultInjection
initFaultInjectionRoute={getInitFaultInjectionRoute(
this.props.workloads,
this.props.virtualServices,
this.props.destinationRules
)}
onChange={this.onFaultInjectionRouteChange}
/>
)}
{(this.props.type === WIZARD_TRAFFIC_SHIFTING || this.props.type === WIZARD_TCP_TRAFFIC_SHIFTING) && (
<TrafficShifting
showValid={true}
workloads={this.props.workloads}
initWeights={getInitWeights(this.props.workloads, this.props.virtualServices, this.props.destinationRules)}
showMirror={this.props.type === WIZARD_TRAFFIC_SHIFTING}
onChange={this.onWeightsChange}
/>
)}
{this.props.type === WIZARD_REQUEST_TIMEOUTS && (
<RequestTimeouts
initTimeoutRetry={getInitTimeoutRetryRoute(
this.props.workloads,
this.props.virtualServices,
this.props.destinationRules
)}
onChange={this.onTimeoutRetryRouteChange}
/>
)}
{(this.props.type === WIZARD_REQUEST_ROUTING ||
this.props.type === WIZARD_FAULT_INJECTION ||
this.props.type === WIZARD_TRAFFIC_SHIFTING ||
this.props.type === WIZARD_TCP_TRAFFIC_SHIFTING ||
this.props.type === WIZARD_REQUEST_TIMEOUTS) && (
<Expandable
className={advancedOptionsStyle}
isExpanded={this.state.showAdvanced}
toggleText={(this.state.showAdvanced ? 'Hide' : 'Show') + ' Advanced Options'}
onToggle={() => {
this.setState({
showAdvanced: !this.state.showAdvanced
});
}}
>
<Tabs isFilled={true} activeKey={this.state.advancedTabKey} onSelect={this.advancedHandleTabClick}>
<Tab eventKey={0} title={'Destination Hosts'}>
<div style={{ marginTop: '20px' }}>
<VirtualServiceHosts
vsHosts={this.state.vsHosts}
gateway={this.state.gateway}
onVsHostsChange={this.onVsHosts}
/>
</div>
</Tab>
<Tab eventKey={1} title={'Gateways'}>
<div style={{ marginTop: '20px', marginBottom: '10px' }}>
<GatewaySelector
serviceName={this.props.serviceName}
hasGateway={hasGateway(this.props.virtualServices)}
gateway={gatewaySelected}
isMesh={isMesh}
gateways={this.props.gateways}
vsHosts={this.state.vsHosts}
onGatewayChange={this.onGateway}
/>
</div>
</Tab>
<Tab eventKey={2} title={'Traffic Policy'}>
<div style={{ marginTop: '20px', marginBottom: '10px' }}>
<TrafficPolicyContainer
mtlsMode={this.state.trafficPolicy.mtlsMode}
clientCertificate={this.state.trafficPolicy.clientCertificate}
privateKey={this.state.trafficPolicy.privateKey}
caCertificates={this.state.trafficPolicy.caCertificates}
hasLoadBalancer={this.state.trafficPolicy.addLoadBalancer}
loadBalancer={this.state.trafficPolicy.loadBalancer}
nsWideStatus={this.props.tlsStatus}
hasPeerAuthentication={this.state.trafficPolicy.peerAuthnSelector.addPeerAuthentication}
peerAuthenticationMode={this.state.trafficPolicy.peerAuthnSelector.mode}
addConnectionPool={this.state.trafficPolicy.addConnectionPool}
connectionPool={this.state.trafficPolicy.connectionPool}
addOutlierDetection={this.state.trafficPolicy.addOutlierDetection}
outlierDetection={this.state.trafficPolicy.outlierDetection}
onTrafficPolicyChange={this.onTrafficPolicy}
/>
</div>
</Tab>
{this.props.type !== WIZARD_TCP_TRAFFIC_SHIFTING && (
<Tab eventKey={3} title={'Circuit Breaker'}>
<div style={{ marginTop: '20px', marginBottom: '10px' }}>
<CircuitBreaker
hasConnectionPool={this.state.trafficPolicy.addConnectionPool}
connectionPool={this.state.trafficPolicy.connectionPool}
hasOutlierDetection={this.state.trafficPolicy.addOutlierDetection}
outlierDetection={this.state.trafficPolicy.outlierDetection}
onCircuitBreakerChange={this.onCircuitBreaker}
/>
</div>
</Tab>
)}
</Tabs>
</Expandable>
)}
</Modal>
);
}
}
export default ServiceWizard; | the_stack |
import { browser, Bookmarks } from "webextension-polyfill-ts";
import BookmarkService from '../../utils/services'
import { Setting } from '../../utils/setting'
import iconLogo from '../../icons/icon128.png'
import { OperType, BookmarkInfo, SyncDataInfo, RootBookmarksType, BrowserType } from '../../utils/models'
let curOperType = OperType.NONE;
let curBrowserType = BrowserType.CHROME;
browser.runtime.onMessage.addListener(async (msg, sender) => {
if (msg.name === 'upload') {
curOperType = OperType.SYNC
await uploadBookmarks();
curOperType = OperType.NONE
browser.browserAction.setBadgeText({ text: "" });
refreshLocalCount();
}
if (msg.name === 'download') {
curOperType = OperType.SYNC
await downloadBookmarks();
curOperType = OperType.NONE
browser.browserAction.setBadgeText({ text: "" });
refreshLocalCount();
}
if (msg.name === 'removeAll') {
curOperType = OperType.REMOVE
await clearBookmarkTree();
curOperType = OperType.NONE
browser.browserAction.setBadgeText({ text: "" });
refreshLocalCount();
}
if (msg.name === 'setting') {
await browser.runtime.openOptionsPage();
}
return true;
});
browser.bookmarks.onCreated.addListener((id, info) => {
if (curOperType === OperType.NONE) {
// console.log("onCreated", id, info)
browser.browserAction.setBadgeText({ text: "!" });
browser.browserAction.setBadgeBackgroundColor({ color: "#F00" });
refreshLocalCount();
}
});
browser.bookmarks.onChanged.addListener((id, info) => {
if (curOperType === OperType.NONE) {
// console.log("onChanged", id, info)
browser.browserAction.setBadgeText({ text: "!" });
browser.browserAction.setBadgeBackgroundColor({ color: "#F00" });
}
})
browser.bookmarks.onMoved.addListener((id, info) => {
if (curOperType === OperType.NONE) {
// console.log("onMoved", id, info)
browser.browserAction.setBadgeText({ text: "!" });
browser.browserAction.setBadgeBackgroundColor({ color: "#F00" });
}
})
browser.bookmarks.onRemoved.addListener((id, info) => {
if (curOperType === OperType.NONE) {
// console.log("onRemoved", id, info)
browser.browserAction.setBadgeText({ text: "!" });
browser.browserAction.setBadgeBackgroundColor({ color: "#F00" });
refreshLocalCount();
}
})
async function uploadBookmarks() {
try {
let setting = await Setting.build()
if (setting.githubToken == '') {
throw new Error("Gist Token Not Found");
}
if (setting.gistID == '') {
throw new Error("Gist ID Not Found");
}
if (setting.gistFileName == '') {
throw new Error("Gist File Not Found");
}
let bookmarks = await getBookmarks();
let syncdata = new SyncDataInfo();
syncdata.version = browser.runtime.getManifest().version;
syncdata.createDate = Date.now();
syncdata.bookmarks = formatBookmarks(bookmarks);
syncdata.browser = navigator.userAgent;
await BookmarkService.update(JSON.stringify({
files: {
[setting.gistFileName]: {
content: JSON.stringify(syncdata)
}
},
description: setting.gistFileName
}));
const count = getBookmarkCount(syncdata.bookmarks);
await browser.storage.local.set({ remoteCount: count });
if (setting.enableNotify) {
await browser.notifications.create({
type: "basic",
iconUrl: iconLogo,
title: browser.i18n.getMessage('uploadBookmarks'),
message: browser.i18n.getMessage('success')
});
}
}
catch (error) {
await browser.notifications.create({
type: "basic",
iconUrl: iconLogo,
title: browser.i18n.getMessage('uploadBookmarks'),
message: `${browser.i18n.getMessage('error')}:${error.message}`
});
}
}
async function downloadBookmarks() {
try {
let gist = await BookmarkService.get();
let setting = await Setting.build()
if (gist) {
let syncdata: SyncDataInfo = JSON.parse(gist);
if (syncdata.bookmarks == undefined || syncdata.bookmarks.length == 0) {
if (setting.enableNotify) {
await browser.notifications.create({
type: "basic",
iconUrl: iconLogo,
title: browser.i18n.getMessage('downloadBookmarks'),
message: `${browser.i18n.getMessage('error')}:Gist File ${setting.gistFileName} is NULL`
});
}
return;
}
await clearBookmarkTree();
await createBookmarkTree(syncdata.bookmarks);
const count = getBookmarkCount(syncdata.bookmarks);
await browser.storage.local.set({ remoteCount: count });
if (setting.enableNotify) {
await browser.notifications.create({
type: "basic",
iconUrl: iconLogo,
title: browser.i18n.getMessage('downloadBookmarks'),
message: browser.i18n.getMessage('success')
});
}
}
else {
await browser.notifications.create({
type: "basic",
iconUrl: iconLogo,
title: browser.i18n.getMessage('downloadBookmarks'),
message: `${browser.i18n.getMessage('error')}:Gist File ${setting.gistFileName} Not Found`
});
}
}
catch (error) {
await browser.notifications.create({
type: "basic",
iconUrl: iconLogo,
title: browser.i18n.getMessage('downloadBookmarks'),
message: `${browser.i18n.getMessage('error')}:${error.message}`
});
}
}
async function getBookmarks() {
let bookmarkTree: BookmarkInfo[] = await browser.bookmarks.getTree();
if (bookmarkTree && bookmarkTree[0].id === "root________") {
curBrowserType = BrowserType.FIREFOX;
}
else {
curBrowserType = BrowserType.CHROME;
}
return bookmarkTree;
}
async function clearBookmarkTree() {
try {
let setting = await Setting.build()
if (setting.githubToken == '') {
throw new Error("Gist Token Not Found");
}
if (setting.gistID == '') {
throw new Error("Gist ID Not Found");
}
if (setting.gistFileName == '') {
throw new Error("Gist File Not Found");
}
let bookmarks = await getBookmarks();
let tempNodes: BookmarkInfo[] = [];
bookmarks[0].children?.forEach(c => {
c.children?.forEach(d => {
tempNodes.push(d)
})
});
if (tempNodes.length > 0) {
for (let node of tempNodes) {
if (node.id) {
await browser.bookmarks.removeTree(node.id)
}
}
}
if (curOperType === OperType.REMOVE && setting.enableNotify) {
await browser.notifications.create({
type: "basic",
iconUrl: iconLogo,
title: browser.i18n.getMessage('removeAllBookmarks'),
message: browser.i18n.getMessage('success')
});
}
}
catch (error) {
await browser.notifications.create({
type: "basic",
iconUrl: iconLogo,
title: browser.i18n.getMessage('removeAllBookmarks'),
message: `${browser.i18n.getMessage('error')}:${error.message}`
});
}
}
async function createBookmarkTree(bookmarkList: BookmarkInfo[] | undefined) {
if (bookmarkList == null) {
return;
}
for (let i = 0; i < bookmarkList.length; i++) {
let node = bookmarkList[i];
if (node.title == RootBookmarksType.MenuFolder
|| node.title == RootBookmarksType.MobileFolder
|| node.title == RootBookmarksType.ToolbarFolder
|| node.title == RootBookmarksType.UnfiledFolder) {
if (curBrowserType == BrowserType.FIREFOX) {
switch (node.title) {
case RootBookmarksType.MenuFolder:
node.children?.forEach(c => c.parentId = "menu________");
break;
case RootBookmarksType.MobileFolder:
node.children?.forEach(c => c.parentId = "mobile______");
break;
case RootBookmarksType.ToolbarFolder:
node.children?.forEach(c => c.parentId = "toolbar_____");
break;
case RootBookmarksType.UnfiledFolder:
node.children?.forEach(c => c.parentId = "unfiled_____");
break;
default:
node.children?.forEach(c => c.parentId = "unfiled_____");
break;
}
} else {
switch (node.title) {
case RootBookmarksType.MobileFolder:
node.children?.forEach(c => c.parentId = "3");
break;
case RootBookmarksType.ToolbarFolder:
node.children?.forEach(c => c.parentId = "1");
break;
case RootBookmarksType.UnfiledFolder:
case RootBookmarksType.MenuFolder:
node.children?.forEach(c => c.parentId = "2");
break;
default:
node.children?.forEach(c => c.parentId = "2");
break;
}
}
await createBookmarkTree(node.children);
continue;
}
let res: Bookmarks.BookmarkTreeNode = { id: '', title: '' };
try {
/* 处理firefox中创建 chrome://chrome-urls/ 格式的书签会报错的问题 */
res = await browser.bookmarks.create({
parentId: node.parentId,
title: node.title,
url: node.url
});
} catch (err) {
console.error(res, err);
}
if (res.id && node.children && node.children.length > 0) {
node.children.forEach(c => c.parentId = res.id);
await createBookmarkTree(node.children);
}
}
}
function getBookmarkCount(bookmarkList: BookmarkInfo[] | undefined) {
let count = 0;
if (bookmarkList) {
bookmarkList.forEach(c => {
if (c.url) {
count = count + 1;
}
else {
count = count + getBookmarkCount(c.children);
}
});
}
return count;
}
async function refreshLocalCount() {
let bookmarkList = await getBookmarks();
const count = getBookmarkCount(bookmarkList);
await browser.storage.local.set({ localCount: count });
}
function formatBookmarks(bookmarks: BookmarkInfo[]): BookmarkInfo[] | undefined {
if (bookmarks[0].children) {
for (let a of bookmarks[0].children) {
switch (a.id) {
case "1":
case "toolbar_____":
a.title = RootBookmarksType.ToolbarFolder;
break;
case "menu________":
a.title = RootBookmarksType.MenuFolder;
break;
case "2":
case "unfiled_____":
a.title = RootBookmarksType.UnfiledFolder;
break;
case "3":
case "mobile______":
a.title = RootBookmarksType.MobileFolder;
break;
}
}
}
let a = format(bookmarks[0]);
return a.children;
}
function format(b: BookmarkInfo): BookmarkInfo {
b.dateAdded = undefined;
b.dateGroupModified = undefined;
b.id = undefined;
b.index = undefined;
b.parentId = undefined;
b.type = undefined;
b.unmodifiable = undefined;
if (b.children && b.children.length > 0) {
b.children?.map(c => format(c))
}
return b;
}
///暂时不启用自动备份
async function backupToLocalStorage(bookmarks: BookmarkInfo[]) {
try {
let syncdata = new SyncDataInfo();
syncdata.version = browser.runtime.getManifest().version;
syncdata.createDate = Date.now();
syncdata.bookmarks = formatBookmarks(bookmarks);
syncdata.browser = navigator.userAgent;
const keyname = 'BookmarkHub_backup_' + Date.now().toString();
await browser.storage.local.set({ [keyname]: JSON.stringify(syncdata) });
}
catch (error) {
console.error(error)
}
} | the_stack |
import Micromerge, { OperationPath, Patch } from "./micromerge"
import { EditorState, TextSelection, Transaction } from "prosemirror-state"
import { EditorView } from "prosemirror-view"
import { Schema, Slice, Node, Fragment, Mark } from "prosemirror-model"
import { baseKeymap, Command, Keymap, toggleMark } from "prosemirror-commands"
import { keymap } from "prosemirror-keymap"
import { ALL_MARKS, isMarkType, MarkType, schemaSpec } from "./schema"
import { ReplaceStep, AddMarkStep, RemoveMarkStep } from "prosemirror-transform"
import { ChangeQueue } from "./changeQueue"
import type { DocSchema } from "./schema"
import type { Publisher } from "./pubsub"
import type { ActorId, Char, Change, Operation as InternalOperation, InputOperation } from "./micromerge"
import { MarkMap, FormatSpanWithText, MarkValue } from "./peritext"
import type { Comment, CommentId } from "./comment"
import { v4 as uuid } from "uuid"
import { clamp } from "lodash"
export const schema = new Schema(schemaSpec)
export type RootDoc = {
text: Array<Char>
comments: Record<CommentId, Comment>
}
// This is a factory which returns a Prosemirror command.
// The Prosemirror command adds a mark to the document.
// The mark takes on the position of the current selection,
// and has the given type and attributes.
// (The structure/usage of this is similar to the toggleMark command factory
// built in to prosemirror)
function addMark<M extends MarkType>(args: { markType: M; makeAttrs: () => Omit<MarkValue[M], "opId" | "active"> }) {
const { markType, makeAttrs } = args
const command: Command<DocSchema> = (
state: EditorState,
dispatch: ((t: Transaction<DocSchema>) => void) | undefined,
) => {
const tr = state.tr
const { $from, $to } = state.selection.ranges[0]
const from = $from.pos,
to = $to.pos
tr.addMark(from, to, schema.marks[markType].create(makeAttrs()))
if (dispatch !== undefined) {
dispatch(tr)
}
return true
}
return command
}
const richTextKeymap: Keymap<DocSchema> = {
...baseKeymap,
"Mod-b": toggleMark(schema.marks.strong),
"Mod-i": toggleMark(schema.marks.em),
"Mod-e": addMark({
markType: "comment",
makeAttrs: () => ({ id: uuid() }),
}),
"Mod-k": addMark({
markType: "link",
makeAttrs: () => ({
url: `https://www.google.com/search?q=${uuid()}`,
}),
}),
}
export type Editor = {
doc: Micromerge
view: EditorView
queue: ChangeQueue
outputDebugForChange: (change: Change) => void
}
const describeMarkType = (markType: string): string => {
switch (markType) {
case "em":
return "italic"
case "strong":
return "bold"
default:
return markType
}
}
// Returns a natural language description of an op in our CRDT.
// Just for demo / debug purposes, doesn't cover all cases
function describeOp(op: InternalOperation): string {
if (op.action === "set" && op.elemId !== undefined) {
return `${op.value}`
} else if (op.action === "del" && op.elemId !== undefined) {
return `❌ <strong>${String(op.elemId)}</strong>`
} else if (op.action === "addMark") {
return `🖌 format <strong>${describeMarkType(op.markType)}</strong>`
} else if (op.action === "removeMark") {
return `🖌 unformat <strong>${op.markType}</strong>`
} else if (op.action === "makeList") {
return `🗑 reset`
} else {
return op.action
}
}
/** Initialize multiple Micromerge docs to all have same base editor state.
* The key is that all docs get initialized with a single change that originates
* on one of the docs; this avoids weird issues where each doc independently
* tries to initialize the basic structure of the document.
*/
export const initializeDocs = (docs: Micromerge[], initialInputOps?: InputOperation[]): void => {
const inputOps: InputOperation[] = [{ path: [], action: "makeList", key: Micromerge.contentKey }]
if (initialInputOps) {
inputOps.push(...initialInputOps)
}
const { change: initialChange } = docs[0].change(inputOps)
for (const doc of docs.slice(1)) {
doc.applyChange(initialChange)
}
}
/** Extends a Prosemirror Transaction with new steps incorporating
* the effects of a Micromerge Patch.
*
* @param transaction - the original transaction to extend
* @param patch - the Micromerge Patch to incorporate
* @returns
* transaction: a Transaction that includes additional steps representing the patch
* startPos: the Prosemirror position where the patch's effects start
* endPos: the Prosemirror position where the patch's effects end
* */
export const extendProsemirrorTransactionWithMicromergePatch = (
transaction: Transaction,
patch: Patch,
): { transaction: Transaction; startPos: number; endPos: number } => {
// console.log("applying patch", patch)
switch (patch.action) {
case "insert": {
const index = prosemirrorPosFromContentPos(patch.index)
return {
transaction: transaction.replace(
index,
index,
new Slice(
Fragment.from(schema.text(patch.values[0], getProsemirrorMarksForMarkMap(patch.marks))),
0,
0,
),
),
startPos: index,
endPos: index + 1,
}
}
case "delete": {
const index = prosemirrorPosFromContentPos(patch.index)
return {
transaction: transaction.replace(index, index + patch.count, Slice.empty),
startPos: index,
endPos: index,
}
}
case "addMark": {
return {
transaction: transaction.addMark(
prosemirrorPosFromContentPos(patch.startIndex),
prosemirrorPosFromContentPos(patch.endIndex),
schema.mark(patch.markType, patch.attrs),
),
startPos: prosemirrorPosFromContentPos(patch.startIndex),
endPos: prosemirrorPosFromContentPos(patch.endIndex),
}
}
case "removeMark": {
return {
transaction: transaction.removeMark(
prosemirrorPosFromContentPos(patch.startIndex),
prosemirrorPosFromContentPos(patch.endIndex),
schema.mark(patch.markType, patch.attrs),
),
startPos: prosemirrorPosFromContentPos(patch.startIndex),
endPos: prosemirrorPosFromContentPos(patch.endIndex),
}
}
case "makeList": {
return {
transaction: transaction.delete(0, transaction.doc.content.size),
startPos: 0,
endPos: 0,
}
}
}
unreachable(patch)
}
/** Construct a Prosemirror editor instance on a DOM node, and bind it to a Micromerge doc */
export function createEditor(args: {
actorId: ActorId
editorNode: Element
changesNode: Element
doc: Micromerge
publisher: Publisher<Array<Change>>
editable: boolean
handleClickOn?: (
this: unknown,
view: EditorView<Schema>,
pos: number,
node: Node<Schema>,
nodePos: number,
event: MouseEvent,
direct: boolean,
) => boolean
onRemotePatchApplied?: (args: {
transaction: Transaction
view: EditorView
startPos: number
endPos: number
}) => Transaction
}): Editor {
const { actorId, editorNode, changesNode, doc, publisher, handleClickOn, onRemotePatchApplied, editable } = args
const queue = new ChangeQueue({
handleFlush: (changes: Array<Change>) => {
publisher.publish(actorId, changes)
},
})
queue.start()
const outputDebugForChange = (change: Change) => {
const opsDivs = change.ops.map((op: InternalOperation) => `<div class="op">${describeOp(op)}</div>`)
for (const divHtml of opsDivs) {
changesNode.insertAdjacentHTML("beforeend", divHtml)
}
changesNode.scrollTop = changesNode.scrollHeight
}
publisher.subscribe(actorId, incomingChanges => {
if (incomingChanges.length === 0) {
return
}
let state = view.state
// For each incoming change, we:
// - retrieve Patches from Micromerge describing the effect of applying the change
// - construct a Prosemirror Transaction representing those effecst
// - apply that Prosemirror Transaction to the document
for (const change of incomingChanges) {
// Create a transaction that will accumulate the effects of our patches
let transaction = state.tr
const patches = doc.applyChange(change)
for (const patch of patches) {
// Get a new Prosemirror transaction containing the effects of the Micromerge patch
const result = extendProsemirrorTransactionWithMicromergePatch(transaction, patch)
let { transaction: newTransaction } = result
const { startPos, endPos } = result
// If this editor has a callback function defined for handling a remote patch being applied,
// apply that callback and give it the chance to extend the transaction.
// (e.g. this can be used to visualize changes by adding new marks.)
if (onRemotePatchApplied) {
newTransaction = onRemotePatchApplied({
transaction: newTransaction,
view,
startPos,
endPos,
})
}
// Assign the newly modified transaction
transaction = newTransaction
}
state = state.apply(transaction)
}
view.updateState(state)
})
// Generate an empty document conforming to the schema,
// and a default selection at the start of the document.
const state = EditorState.create({
schema,
plugins: [keymap(richTextKeymap)],
doc: prosemirrorDocFromCRDT({
schema,
spans: doc.getTextWithFormatting([Micromerge.contentKey]),
}),
})
// Create a view for the state and generate transactions when the user types.
const view = new EditorView(editorNode, {
// state.doc is a read-only data structure using a node hierarchy
// A node contains a fragment with zero or more child nodes.
// Text is modeled as a flat sequence of tokens.
// Each document has a unique valid representation.
// Order of marks specified by schema.
state,
handleClickOn,
editable: () => editable,
// We intercept local Prosemirror transactions and derive Micromerge changes from them
dispatchTransaction: (txn: Transaction) => {
let state = view.state
// Apply a corresponding change to the Micromerge document.
// We observe a Micromerge Patch from applying the change, and
// apply its effects to our local Prosemirror doc.
const { change, patches } = applyProsemirrorTransactionToMicromergeDoc({ doc, txn })
if (change) {
let transaction = state.tr
for (const patch of patches) {
const { transaction: newTxn } = extendProsemirrorTransactionWithMicromergePatch(transaction, patch)
transaction = newTxn
}
state = state.apply(transaction)
outputDebugForChange(change)
// Broadcast the change to remote peers
queue.enqueue(change)
}
// If this transaction updated the local selection, we need to
// make sure that's reflected in the editor state.
// (Roundtripping through Micromerge won't do that for us, since
// selection state is not part of the document state.)
if (txn.selectionSet) {
state = state.apply(
state.tr.setSelection(
new TextSelection(
state.doc.resolve(txn.selection.anchor),
state.doc.resolve(txn.selection.head),
),
),
)
}
view.updateState(state)
console.groupEnd()
},
})
return { doc, view, queue, outputDebugForChange }
}
/**
* Converts a position in the Prosemirror doc to an offset in the CRDT content string.
* For now we only have a single node so this is relatively trivial.
* In the future when things get more complicated with multiple block nodes,
* we can probably take advantage
* of the additional metadata that Prosemirror can provide by "resolving" the position.
* @param position : an unresolved Prosemirror position in the doc;
* @param doc : the Prosemirror document containing the position
*/
function contentPosFromProsemirrorPos(position: number, doc: Node<DocSchema>): number {
// The -1 accounts for the extra character at the beginning of the PM doc
// containing the beginning of the paragraph.
// In some rare cases we can end up with incoming positions outside of the single
// paragraph node (e.g., when the user does cmd-A to select all),
// so we need to be sure to clamp the resulting position to inside the paragraph node.
return clamp(position - 1, 0, doc.textContent.length)
}
/** Given an index in the text CRDT, convert to an index in the Prosemirror editor.
* The Prosemirror editor has a paragraph node which we ignore because we only handle inline;
* the beginning of the paragraph takes up one position in the Prosemirror indexing scheme.
* This means we have to add 1 to CRDT indexes to get correct Prosemirror indexes.
*/
function prosemirrorPosFromContentPos(position: number) {
return position + 1
}
function getProsemirrorMarksForMarkMap<T extends MarkMap>(markMap: T): Mark[] {
const marks = []
for (const markType of ALL_MARKS) {
const markValue = markMap[markType]
if (markValue === undefined) {
continue
}
if (Array.isArray(markValue)) {
for (const value of markValue) {
marks.push(schema.mark(markType, value))
}
} else {
if (markValue) {
marks.push(schema.mark(markType, markValue))
}
}
}
return marks
}
// Given a micromerge doc representation, produce a prosemirror doc.
export function prosemirrorDocFromCRDT(args: { schema: DocSchema; spans: FormatSpanWithText[] }): Node {
const { schema, spans } = args
// Prosemirror doesn't allow for empty text nodes;
// if our doc is empty, we short-circuit and don't add any text nodes.
if (spans.length === 1 && spans[0].text === "") {
return schema.node("doc", undefined, [schema.node("paragraph", [])])
}
const result = schema.node("doc", undefined, [
schema.node(
"paragraph",
undefined,
spans.map(span => {
return schema.text(span.text, getProsemirrorMarksForMarkMap(span.marks))
}),
),
])
return result
}
// Given a CRDT Doc and a Prosemirror Transaction, update the micromerge doc.
export function applyProsemirrorTransactionToMicromergeDoc(args: { doc: Micromerge; txn: Transaction<DocSchema> }): {
change: Change | null
patches: Patch[]
} {
const { doc, txn } = args
const operations: Array<InputOperation> = []
for (const step of txn.steps) {
if (step instanceof ReplaceStep) {
if (step.slice) {
// handle insertion
if (step.from !== step.to) {
operations.push({
path: [Micromerge.contentKey],
action: "delete",
index: contentPosFromProsemirrorPos(step.from, txn.before),
count:
contentPosFromProsemirrorPos(step.to, txn.before) -
contentPosFromProsemirrorPos(step.from, txn.before),
})
}
const insertedContent = step.slice.content.textBetween(0, step.slice.content.size)
operations.push({
path: [Micromerge.contentKey],
action: "insert",
index: contentPosFromProsemirrorPos(step.from, txn.before),
values: insertedContent.split(""),
})
} else {
// handle deletion
operations.push({
path: [Micromerge.contentKey],
action: "delete",
index: contentPosFromProsemirrorPos(step.from, txn.before),
count:
contentPosFromProsemirrorPos(step.to, txn.before) -
contentPosFromProsemirrorPos(step.from, txn.before),
})
}
} else if (step instanceof AddMarkStep) {
if (!isMarkType(step.mark.type.name)) {
throw new Error(`Invalid mark type: ${step.mark.type.name}`)
}
const partialOp: {
action: "addMark"
path: OperationPath
startIndex: number
endIndex: number
} = {
action: "addMark",
path: [Micromerge.contentKey],
startIndex: contentPosFromProsemirrorPos(step.from, txn.before),
endIndex: contentPosFromProsemirrorPos(step.to, txn.before),
}
if (step.mark.type.name === "comment") {
if (!step.mark.attrs || typeof step.mark.attrs.id !== "string") {
throw new Error("Expected comment mark to have id attrs")
}
operations.push({
...partialOp,
markType: step.mark.type.name,
attrs: step.mark.attrs as { id: string },
})
} else if (step.mark.type.name === "link") {
if (!step.mark.attrs || typeof step.mark.attrs.url !== "string") {
throw new Error("Expected link mark to have url attrs")
}
operations.push({
...partialOp,
markType: step.mark.type.name,
attrs: step.mark.attrs as { url: string },
})
} else {
operations.push({
...partialOp,
markType: step.mark.type.name,
})
}
} else if (step instanceof RemoveMarkStep) {
if (!isMarkType(step.mark.type.name)) {
throw new Error(`Invalid mark type: ${step.mark.type.name}`)
}
const partialOp: {
action: "removeMark"
path: OperationPath
startIndex: number
endIndex: number
} = {
action: "removeMark",
path: [Micromerge.contentKey],
startIndex: contentPosFromProsemirrorPos(step.from, txn.before),
endIndex: contentPosFromProsemirrorPos(step.to, txn.before),
}
if (step.mark.type.name === "comment") {
if (!step.mark.attrs || typeof step.mark.attrs.id !== "string") {
throw new Error("Expected comment mark to have id attrs")
}
operations.push({
...partialOp,
markType: step.mark.type.name,
attrs: step.mark.attrs as { id: string },
})
} else {
operations.push({
...partialOp,
markType: step.mark.type.name,
})
}
}
}
if (operations.length > 0) {
return doc.change(operations)
} else {
return { change: null, patches: [] }
}
} | the_stack |
* numeral.js
* version : 2.0.6
* author : Adam Draper
* license : MIT
* http://adamwdraper.github.com/Numeral-js/
*/
/************************************
Variables
************************************/
var numeral,
_,
VERSION = '2.0.6',
formats = {},
locales = {},
defaults = {
currentLocale: 'en',
zeroFormat: null,
nullFormat: null,
defaultFormat: '0,0',
scalePercentBy100: true
},
options = {
currentLocale: defaults.currentLocale,
zeroFormat: defaults.zeroFormat,
nullFormat: defaults.nullFormat,
defaultFormat: defaults.defaultFormat,
scalePercentBy100: defaults.scalePercentBy100
};
/************************************
Constructors
************************************/
// Numeral prototype object
function Numeral(input, number) {
this._input = input;
this._value = number;
}
numeral = function(input) {
var value, kind, unformatFunction, regexp;
if (numeral.isNumeral(input)) {
value = input.value();
} else if (input === 0 || typeof input === 'undefined') {
value = 0;
} else if (input === null || _.isNaN(input)) {
value = null;
} else if (typeof input === 'string') {
if (options.zeroFormat && input === options.zeroFormat) {
value = 0;
} else if ((options.nullFormat && input === options.nullFormat) || !input.replace(/[^0-9]+/g, '').length) {
value = null;
} else {
for (kind in formats) {
regexp =
typeof formats[kind].regexps.unformat === 'function'
? formats[kind].regexps.unformat()
: formats[kind].regexps.unformat;
if (regexp && input.match(regexp)) {
unformatFunction = formats[kind].unformat;
break;
}
}
unformatFunction = unformatFunction || numeral._.stringToNumber;
value = unformatFunction(input);
}
} else {
value = Number(input) || null;
}
return new Numeral(input, value);
};
// version number
numeral.version = VERSION;
// compare numeral object
numeral.isNumeral = function(obj) {
return obj instanceof Numeral;
};
// helper functions
numeral._ = _ = {
// formats numbers separators, decimals places, signs, abbreviations
numberToFormat: function(value, format, roundingFunction) {
var locale = locales[numeral.options.currentLocale],
negP = false,
optDec = false,
leadingCount = 0,
abbr = '',
trillion = 1000000000000,
billion = 1000000000,
million = 1000000,
thousand = 1000,
decimal = '',
neg = false,
abbrForce, // force abbreviation
abs,
min,
max,
power,
int,
precision,
signed,
thousands,
output;
// make sure we never format a null value
value = value || 0;
abs = Math.abs(value);
// see if we should use parentheses for negative number or if we should prefix with a sign
// if both are present we default to parentheses
if (numeral._.includes(format, '(')) {
negP = true;
format = format.replace(/[\(|\)]/g, '');
} else if (numeral._.includes(format, '+') || numeral._.includes(format, '-')) {
signed = numeral._.includes(format, '+') ? format.indexOf('+') : value < 0 ? format.indexOf('-') : -1;
format = format.replace(/[\+|\-]/g, '');
}
// see if abbreviation is wanted
if (numeral._.includes(format, 'a')) {
abbrForce = format.match(/a(k|m|b|t)?/);
abbrForce = abbrForce ? abbrForce[1] : false;
// check for space before abbreviation
if (numeral._.includes(format, ' a')) {
abbr = ' ';
}
format = format.replace(new RegExp(abbr + 'a[kmbt]?'), '');
if ((abs >= trillion && !abbrForce) || abbrForce === 't') {
// trillion
abbr += locale.abbreviations.trillion;
value = value / trillion;
} else if ((abs < trillion && abs >= billion && !abbrForce) || abbrForce === 'b') {
// billion
abbr += locale.abbreviations.billion;
value = value / billion;
} else if ((abs < billion && abs >= million && !abbrForce) || abbrForce === 'm') {
// million
abbr += locale.abbreviations.million;
value = value / million;
} else if ((abs < million && abs >= thousand && !abbrForce) || abbrForce === 'k') {
// thousand
abbr += locale.abbreviations.thousand;
value = value / thousand;
}
}
// check for optional decimals
if (numeral._.includes(format, '[.]')) {
optDec = true;
format = format.replace('[.]', '.');
}
// break number and format
int = value.toString().split('.')[0];
precision = format.split('.')[1];
thousands = format.indexOf(',');
leadingCount = (
format
.split('.')[0]
.split(',')[0]
.match(/0/g) || []
).length;
if (precision) {
if (numeral._.includes(precision, '[')) {
precision = precision.replace(']', '');
precision = precision.split('[');
decimal = numeral._.toFixed(
value,
precision[0].length + precision[1].length,
roundingFunction,
precision[1].length
);
} else {
decimal = numeral._.toFixed(value, precision.length, roundingFunction);
}
int = decimal.split('.')[0];
if (numeral._.includes(decimal, '.')) {
decimal = locale.delimiters.decimal + decimal.split('.')[1];
} else {
decimal = '';
}
if (optDec && Number(decimal.slice(1)) === 0) {
decimal = '';
}
} else {
int = numeral._.toFixed(value, 0, roundingFunction);
}
// check abbreviation again after rounding
if (abbr && !abbrForce && Number(int) >= 1000 && abbr !== locale.abbreviations.trillion) {
int = String(Number(int) / 1000);
switch (abbr) {
case locale.abbreviations.thousand:
abbr = locale.abbreviations.million;
break;
case locale.abbreviations.million:
abbr = locale.abbreviations.billion;
break;
case locale.abbreviations.billion:
abbr = locale.abbreviations.trillion;
break;
}
}
// format number
if (numeral._.includes(int, '-')) {
int = int.slice(1);
neg = true;
}
if (int.length < leadingCount) {
for (var i = leadingCount - int.length; i > 0; i--) {
int = '0' + int;
}
}
if (thousands > -1) {
int = int.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1' + locale.delimiters.thousands);
}
if (format.indexOf('.') === 0) {
int = '';
}
output = int + decimal + (abbr ? abbr : '');
if (negP) {
output = (negP && neg ? '(' : '') + output + (negP && neg ? ')' : '');
} else {
if (signed >= 0) {
output = signed === 0 ? (neg ? '-' : '+') + output : output + (neg ? '-' : '+');
} else if (neg) {
output = '-' + output;
}
}
return output;
},
// unformats numbers separators, decimals places, signs, abbreviations
stringToNumber: function(string) {
var locale = locales[options.currentLocale],
stringOriginal = string,
abbreviations = {
thousand: 3,
million: 6,
billion: 9,
trillion: 12
},
abbreviation,
value,
i,
regexp;
if (options.zeroFormat && string === options.zeroFormat) {
value = 0;
} else if ((options.nullFormat && string === options.nullFormat) || !string.replace(/[^0-9]+/g, '').length) {
value = null;
} else {
value = 1;
if (locale.delimiters.decimal !== '.') {
string = string.replace(/\./g, '').replace(locale.delimiters.decimal, '.');
}
for (abbreviation in abbreviations) {
regexp = new RegExp(
'[^a-zA-Z]' + locale.abbreviations[abbreviation] + '(?:\\)|(\\' + locale.currency.symbol + ')?(?:\\))?)?$'
);
if (stringOriginal.match(regexp)) {
value *= Math.pow(10, abbreviations[abbreviation]);
break;
}
}
// check for negative number
value *=
(string.split('-').length + Math.min(string.split('(').length - 1, string.split(')').length - 1)) % 2 ? 1 : -1;
// remove non numbers
string = string.replace(/[^0-9\.]+/g, '');
value *= Number(string);
}
return value;
},
isNaN: function(value) {
return typeof value === 'number' && isNaN(value);
},
includes: function(string, search) {
return string.indexOf(search) !== -1;
},
insert: function(string, subString, start) {
return string.slice(0, start) + subString + string.slice(start);
},
reduce: function(array, callback /*, initialValue*/) {
if (this === null) {
throw new TypeError('Array.prototype.reduce called on null or undefined');
}
if (typeof callback !== 'function') {
throw new TypeError(callback + ' is not a function');
}
var t = Object(array),
len = t.length >>> 0,
k = 0,
value;
if (arguments.length === 3) {
value = arguments[2];
} else {
while (k < len && !(k in t)) {
k++;
}
if (k >= len) {
throw new TypeError('Reduce of empty array with no initial value');
}
value = t[k++];
}
for (; k < len; k++) {
if (k in t) {
value = callback(value, t[k], k, t);
}
}
return value;
},
/**
* Computes the multiplier necessary to make x >= 1,
* effectively eliminating miscalculations caused by
* finite precision.
*/
multiplier: function(x) {
var parts = x.toString().split('.');
return parts.length < 2 ? 1 : Math.pow(10, parts[1].length);
},
/**
* Given a variable number of arguments, returns the maximum
* multiplier that must be used to normalize an operation involving
* all of them.
*/
correctionFactor: function() {
var args = Array.prototype.slice.call(arguments);
return args.reduce(function(accum, next) {
var mn = _.multiplier(next);
return accum > mn ? accum : mn;
}, 1);
},
/**
* Implementation of toFixed() that treats floats more like decimals
*
* Fixes binary rounding issues (eg. (0.615).toFixed(2) === '0.61') that present
* problems for accounting- and finance-related software.
*/
toFixed: function(value, maxDecimals, roundingFunction, optionals) {
var splitValue = value.toString().split('.'),
minDecimals = maxDecimals - (optionals || 0),
boundedPrecision,
optionalsRegExp,
power,
output;
// Use the smallest precision value possible to avoid errors from floating point representation
if (splitValue.length === 2) {
boundedPrecision = Math.min(Math.max(splitValue[1].length, minDecimals), maxDecimals);
} else {
boundedPrecision = minDecimals;
}
power = Math.pow(10, boundedPrecision);
// Multiply up by precision, round accurately, then divide and use native toFixed():
output = (roundingFunction(value + 'e+' + boundedPrecision) / power).toFixed(boundedPrecision);
if (optionals > maxDecimals - boundedPrecision) {
optionalsRegExp = new RegExp('\\.?0{1,' + (optionals - (maxDecimals - boundedPrecision)) + '}$');
output = output.replace(optionalsRegExp, '');
}
return output;
}
};
// avaliable options
numeral.options = options;
// avaliable formats
numeral.formats = formats;
// avaliable formats
numeral.locales = locales;
// This function sets the current locale. If
// no arguments are passed in, it will simply return the current global
// locale key.
numeral.locale = function(key) {
if (key) {
options.currentLocale = key.toLowerCase();
}
return options.currentLocale;
};
// This function provides access to the loaded locale data. If
// no arguments are passed in, it will simply return the current
// global locale object.
numeral.localeData = function(key) {
if (!key) {
return locales[options.currentLocale];
}
key = key.toLowerCase();
if (!locales[key]) {
throw new Error('Unknown locale : ' + key);
}
return locales[key];
};
numeral.reset = function() {
for (var property in defaults) {
options[property] = defaults[property];
}
};
numeral.zeroFormat = function(format) {
options.zeroFormat = typeof format === 'string' ? format : null;
};
numeral.nullFormat = function(format) {
options.nullFormat = typeof format === 'string' ? format : null;
};
numeral.defaultFormat = function(format) {
options.defaultFormat = typeof format === 'string' ? format : '0.0';
};
numeral.register = function(type, name, format) {
name = name.toLowerCase();
if (this[type + 's'][name]) {
throw new TypeError(name + ' ' + type + ' already registered.');
}
this[type + 's'][name] = format;
return format;
};
numeral.validate = function(val, culture) {
var _decimalSep, _thousandSep, _currSymbol, _valArray, _abbrObj, _thousandRegEx, localeData, temp;
//coerce val to string
if (typeof val !== 'string') {
val += '';
if (console.warn) {
console.warn('Numeral.js: Value is not string. It has been co-erced to: ', val);
}
}
//trim whitespaces from either sides
val = val.trim();
//if val is just digits return true
if (!!val.match(/^\d+$/)) {
return true;
}
//if val is empty return false
if (val === '') {
return false;
}
//get the decimal and thousands separator from numeral.localeData
try {
//check if the culture is understood by numeral. if not, default it to current locale
localeData = numeral.localeData(culture);
} catch (e) {
localeData = numeral.localeData(numeral.locale());
}
//setup the delimiters and currency symbol based on culture/locale
_currSymbol = localeData.currency.symbol;
_abbrObj = localeData.abbreviations;
_decimalSep = localeData.delimiters.decimal;
if (localeData.delimiters.thousands === '.') {
_thousandSep = '\\.';
} else {
_thousandSep = localeData.delimiters.thousands;
}
// validating currency symbol
temp = val.match(/^[^\d]+/);
if (temp !== null) {
val = val.substr(1);
if (temp[0] !== _currSymbol) {
return false;
}
}
//validating abbreviation symbol
temp = val.match(/[^\d]+$/);
if (temp !== null) {
val = val.slice(0, -1);
if (
temp[0] !== _abbrObj.thousand &&
temp[0] !== _abbrObj.million &&
temp[0] !== _abbrObj.billion &&
temp[0] !== _abbrObj.trillion
) {
return false;
}
}
_thousandRegEx = new RegExp(_thousandSep + '{2}');
if (!val.match(/[^\d.,]/g)) {
_valArray = val.split(_decimalSep);
if (_valArray.length > 2) {
return false;
} else {
if (_valArray.length < 2) {
return !!_valArray[0].match(/^\d+.*\d$/) && !_valArray[0].match(_thousandRegEx);
} else {
if (_valArray[0].length === 1) {
return !!_valArray[0].match(/^\d+$/) && !_valArray[0].match(_thousandRegEx) && !!_valArray[1].match(/^\d+$/);
} else {
return (
!!_valArray[0].match(/^\d+.*\d$/) && !_valArray[0].match(_thousandRegEx) && !!_valArray[1].match(/^\d+$/)
);
}
}
}
}
return false;
};
/************************************
Numeral Prototype
************************************/
numeral.fn = Numeral.prototype = {
clone: function() {
return numeral(this);
},
format: function(inputString, roundingFunction) {
var value = this._value,
format = inputString || options.defaultFormat,
kind,
output,
formatFunction;
// make sure we have a roundingFunction
roundingFunction = roundingFunction || Math.round;
// format based on value
if (value === 0 && options.zeroFormat !== null) {
output = options.zeroFormat;
} else if (value === null && options.nullFormat !== null) {
output = options.nullFormat;
} else {
for (kind in formats) {
if (format.match(formats[kind].regexps.format)) {
formatFunction = formats[kind].format;
break;
}
}
formatFunction = formatFunction || numeral._.numberToFormat;
output = formatFunction(value, format, roundingFunction);
}
return output;
},
value: function() {
return this._value;
},
input: function() {
return this._input;
},
set: function(value) {
this._value = Number(value);
return this;
},
add: function(value) {
var corrFactor = _.correctionFactor.call(null, this._value, value);
function cback(accum, curr, currI, O) {
return accum + Math.round(corrFactor * curr);
}
this._value = _.reduce([this._value, value], cback, 0) / corrFactor;
return this;
},
subtract: function(value) {
var corrFactor = _.correctionFactor.call(null, this._value, value);
function cback(accum, curr, currI, O) {
return accum - Math.round(corrFactor * curr);
}
this._value = _.reduce([value], cback, Math.round(this._value * corrFactor)) / corrFactor;
return this;
},
multiply: function(value) {
function cback(accum, curr, currI, O) {
var corrFactor = _.correctionFactor(accum, curr);
return (Math.round(accum * corrFactor) * Math.round(curr * corrFactor)) / Math.round(corrFactor * corrFactor);
}
this._value = _.reduce([this._value, value], cback, 1);
return this;
},
divide: function(value) {
function cback(accum, curr, currI, O) {
var corrFactor = _.correctionFactor(accum, curr);
return Math.round(accum * corrFactor) / Math.round(curr * corrFactor);
}
this._value = _.reduce([this._value, value], cback);
return this;
},
difference: function(value) {
return Math.abs(
numeral(this._value)
.subtract(value)
.value()
);
}
};
/************************************
Default Locale && Format
************************************/
numeral.register('locale', 'en', {
delimiters: {
thousands: ',',
decimal: '.'
},
abbreviations: {
thousand: 'k',
million: 'm',
billion: 'b',
trillion: 't'
},
ordinal: function(number) {
var b = number % 10;
return ~~((number % 100) / 10) === 1 ? 'th' : b === 1 ? 'st' : b === 2 ? 'nd' : b === 3 ? 'rd' : 'th';
},
currency: {
symbol: '$'
}
});
(function() {
numeral.register('format', 'bps', {
regexps: {
format: /(BPS)/,
unformat: /(BPS)/
},
format: function(value, format, roundingFunction) {
var space = numeral._.includes(format, ' BPS') ? ' ' : '',
output;
value = value * 10000;
// check for space before BPS
format = format.replace(/\s?BPS/, '');
output = numeral._.numberToFormat(value, format, roundingFunction);
if (numeral._.includes(output, ')')) {
output = output.split('');
output.splice(-1, 0, space + 'BPS');
output = output.join('');
} else {
output = output + space + 'BPS';
}
return output;
},
unformat: function(string) {
return +(numeral._.stringToNumber(string) * 0.0001).toFixed(15);
}
});
})();
(function() {
var decimal = {
base: 1000,
suffixes: ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
},
binary = {
base: 1024,
suffixes: ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB']
};
var allSuffixes = decimal.suffixes.concat(
binary.suffixes.filter(function(item) {
return decimal.suffixes.indexOf(item) < 0;
})
);
var unformatRegex = allSuffixes.join('|');
// Allow support for BPS (http://www.investopedia.com/terms/b/basispoint.asp)
unformatRegex = '(' + unformatRegex.replace('B', 'B(?!PS)') + ')';
numeral.register('format', 'bytes', {
regexps: {
format: /([0\s]i?b)/,
unformat: new RegExp(unformatRegex)
},
format: function(value, format, roundingFunction) {
var output,
bytes = numeral._.includes(format, 'ib') ? binary : decimal,
suffix = numeral._.includes(format, ' b') || numeral._.includes(format, ' ib') ? ' ' : '',
power,
min,
max;
// check for space before
format = format.replace(/\s?i?b/, '');
for (power = 0; power <= bytes.suffixes.length; power++) {
min = Math.pow(bytes.base, power);
max = Math.pow(bytes.base, power + 1);
if (value === null || value === 0 || (value >= min && value < max)) {
suffix += bytes.suffixes[power];
if (min > 0) {
value = value / min;
}
break;
}
}
output = numeral._.numberToFormat(value, format, roundingFunction);
return output + suffix;
},
unformat: function(string) {
var value = numeral._.stringToNumber(string),
power,
bytesMultiplier;
if (value) {
for (power = decimal.suffixes.length - 1; power >= 0; power--) {
if (numeral._.includes(string, decimal.suffixes[power])) {
bytesMultiplier = Math.pow(decimal.base, power);
break;
}
if (numeral._.includes(string, binary.suffixes[power])) {
bytesMultiplier = Math.pow(binary.base, power);
break;
}
}
value *= bytesMultiplier || 1;
}
return value;
}
});
})();
(function() {
numeral.register('format', 'currency', {
regexps: {
format: /(\$)/
},
format: function(value, format, roundingFunction) {
var locale = numeral.locales[numeral.options.currentLocale],
symbols = {
before: format.match(/^([\+|\-|\(|\s|\$]*)/)[0],
after: format.match(/([\+|\-|\)|\s|\$]*)$/)[0]
},
output,
symbol,
i;
// strip format of spaces and $
format = format.replace(/\s?\$\s?/, '');
// format the number
output = numeral._.numberToFormat(value, format, roundingFunction);
// update the before and after based on value
if (value >= 0) {
symbols.before = symbols.before.replace(/[\-\(]/, '');
symbols.after = symbols.after.replace(/[\-\)]/, '');
} else if (value < 0 && (!numeral._.includes(symbols.before, '-') && !numeral._.includes(symbols.before, '('))) {
symbols.before = '-' + symbols.before;
}
// loop through each before symbol
for (i = 0; i < symbols.before.length; i++) {
symbol = symbols.before[i];
switch (symbol) {
case '$':
output = numeral._.insert(output, locale.currency.symbol, i);
break;
case ' ':
output = numeral._.insert(output, ' ', i + locale.currency.symbol.length - 1);
break;
}
}
// loop through each after symbol
for (i = symbols.after.length - 1; i >= 0; i--) {
symbol = symbols.after[i];
switch (symbol) {
case '$':
output =
i === symbols.after.length - 1
? output + locale.currency.symbol
: numeral._.insert(output, locale.currency.symbol, -(symbols.after.length - (1 + i)));
break;
case ' ':
output =
i === symbols.after.length - 1
? output + ' '
: numeral._.insert(output, ' ', -(symbols.after.length - (1 + i) + locale.currency.symbol.length - 1));
break;
}
}
return output;
}
});
})();
(function() {
numeral.register('format', 'exponential', {
regexps: {
format: /(e\+|e-)/,
unformat: /(e\+|e-)/
},
format: function(value, format, roundingFunction) {
var output,
exponential = typeof value === 'number' && !numeral._.isNaN(value) ? value.toExponential() : '0e+0',
parts = exponential.split('e');
format = format.replace(/e[\+|\-]{1}0/, '');
output = numeral._.numberToFormat(Number(parts[0]), format, roundingFunction);
return output + 'e' + parts[1];
},
unformat: function(string) {
var parts = numeral._.includes(string, 'e+') ? string.split('e+') : string.split('e-'),
value = Number(parts[0]),
power = Number(parts[1]);
power = numeral._.includes(string, 'e-') ? (power *= -1) : power;
function cback(accum, curr, currI, O) {
var corrFactor = numeral._.correctionFactor(accum, curr),
num = (accum * corrFactor * (curr * corrFactor)) / (corrFactor * corrFactor);
return num;
}
return numeral._.reduce([value, Math.pow(10, power)], cback, 1);
}
});
})();
(function() {
numeral.register('format', 'ordinal', {
regexps: {
format: /(o)/
},
format: function(value, format, roundingFunction) {
var locale = numeral.locales[numeral.options.currentLocale],
output,
ordinal = numeral._.includes(format, ' o') ? ' ' : '';
// check for space before
format = format.replace(/\s?o/, '');
ordinal += locale.ordinal(value);
output = numeral._.numberToFormat(value, format, roundingFunction);
return output + ordinal;
}
});
})();
(function() {
numeral.register('format', 'percentage', {
regexps: {
format: /(%)/,
unformat: /(%)/
},
format: function(value, format, roundingFunction) {
var space = numeral._.includes(format, ' %') ? ' ' : '',
output;
if (numeral.options.scalePercentBy100) {
value = value * 100;
}
// check for space before %
format = format.replace(/\s?\%/, '');
output = numeral._.numberToFormat(value, format, roundingFunction);
if (numeral._.includes(output, ')')) {
output = output.split('');
output.splice(-1, 0, space + '%');
output = output.join('');
} else {
output = output + space + '%';
}
return output;
},
unformat: function(string) {
var number = numeral._.stringToNumber(string);
if (numeral.options.scalePercentBy100) {
return number * 0.01;
}
return number;
}
});
})();
(function() {
numeral.register('format', 'time', {
regexps: {
format: /(:)/,
unformat: /(:)/
},
format: function(value, format, roundingFunction) {
var hours = Math.floor(value / 60 / 60),
minutes = Math.floor((value - hours * 60 * 60) / 60),
seconds = Math.round(value - hours * 60 * 60 - minutes * 60);
return hours + ':' + (minutes < 10 ? '0' + minutes : minutes) + ':' + (seconds < 10 ? '0' + seconds : seconds);
},
unformat: function(string) {
var timeArray = string.split(':'),
seconds = 0;
// turn hours and minutes into seconds and add them all up
if (timeArray.length === 3) {
// hours
seconds = seconds + Number(timeArray[0]) * 60 * 60;
// minutes
seconds = seconds + Number(timeArray[1]) * 60;
// seconds
seconds = seconds + Number(timeArray[2]);
} else if (timeArray.length === 2) {
// minutes
seconds = seconds + Number(timeArray[0]) * 60;
// seconds
seconds = seconds + Number(timeArray[1]);
}
return Number(seconds);
}
});
})();
export default numeral; | the_stack |
declare type Observable<T> = any;
declare type Subject<T> = any;
declare module ngMetadataPlatform{
// type AppRoot = string | Element | Document;
// function bootstrap(angular1Module: string, {element, strictDi}?: {
// element?: AppRoot;
// strictDi?: boolean;
// }): void;
const platformBrowserDynamic: () => {
bootstrapModule: Function;
};
/**
* A service that can be used to get and set the title of a current HTML document.
*
* Since an Angular 2 application can't be bootstrapped on the entire HTML document (`<html>` tag)
* it is not possible to bind to the `text` property of the `HTMLTitleElement` elements
* (representing the `<title>` tag). Instead, this service can be used to set and get the current
* title value.
*/
class Title {
private $document;
constructor($document: ng.IDocumentService);
/**
* Get the title of the current HTML document.
* @returns {string}
*/
getTitle(): string;
/**
* Set the title of the current HTML document.
* @param newTitle
*/
setTitle(newTitle: string): void;
}
}
declare module ngMetadataCore{
export interface Type extends Function {}
export class OpaqueToken {
private _desc;
constructor(_desc: string);
desc: string;
toString(): string;
}
/**
* A `changes` object whose keys are property names and
* values are instances of {@link SimpleChange}. See {@link OnChanges}
*/
export interface SimpleChanges {
[propName: string]: SimpleChange;
}
/**
* Represents a basic change from a previous to a new value.
*/
export class SimpleChange {
previousValue: any;
currentValue: any;
constructor(previousValue: any, currentValue: any);
/**
* Check whether the new value is the first value assigned.
*/
isFirstChange(): boolean;
}
export class ChangeDetectorRef {
private $scope;
static create($scope: ng.IScope): ChangeDetectorRef;
constructor($scope: ng.IScope);
/**
* Marks all {@link ChangeDetectionStrategy#OnPush} ancestors as to be checked.
*
* <!-- TODO: Add a link to a chapter on OnPush components -->
*
* ### Example ([live demo](http://plnkr.co/edit/GC512b?p=preview))
*
* ```typescript
* @Component({
* selector: 'cmp',
* changeDetection: ChangeDetectionStrategy.OnPush,
* template: `Number of ticks: {{numberOfTicks}}`
* })
* class Cmp {
* numberOfTicks = 0;
*
* constructor(ref: ChangeDetectorRef) {
* setInterval(() => {
* this.numberOfTicks ++
* // the following is required, otherwise the view will not be updated
* this.ref.markForCheck();
* }, 1000);
* }
* }
*
* @Component({
* selector: 'app',
* changeDetection: ChangeDetectionStrategy.OnPush,
* template: `
* <cmp><cmp>
* `,
* directives: [Cmp]
* })
* class App {
* }
*
* bootstrap(App);
* ```
*/
markForCheck(): void;
/**
* Detaches the change detector from the change detector tree.
*
* The detached change detector will not be checked until it is reattached.
*
* This can also be used in combination with {@link ChangeDetectorRef#detectChanges} to implement
* local change
* detection checks.
*
* <!-- TODO: Add a link to a chapter on detach/reattach/local digest -->
* <!-- TODO: Add a live demo once ref.detectChanges is merged into master -->
*
* ### Example
*
* The following example defines a component with a large list of readonly data.
* Imagine the data changes constantly, many times per second. For performance reasons,
* we want to check and update the list every five seconds. We can do that by detaching
* the component's change detector and doing a local check every five seconds.
*
* ```typescript
* class DataProvider {
* // in a real application the returned data will be different every time
* get data() {
* return [1,2,3,4,5];
* }
* }
*
* @Component({
* selector: 'giant-list',
* template: `
* <li *ngFor="let d of dataProvider.data">Data {{d}}</lig>
* `,
* directives: [NgFor]
* })
* class GiantList {
* constructor(private ref: ChangeDetectorRef, private dataProvider:DataProvider) {
* ref.detach();
* setInterval(() => {
* this.ref.detectChanges();
* }, 5000);
* }
* }
*
* @Component({
* selector: 'app',
* providers: [DataProvider],
* template: `
* <giant-list><giant-list>
* `,
* directives: [GiantList]
* })
* class App {
* }
*
* bootstrap(App);
* ```
*/
detach(): void;
/**
* Checks the change detector and its children.
*
* This can also be used in combination with {@link ChangeDetectorRef#detach} to implement local
* change detection
* checks.
*
* <!-- TODO: Add a link to a chapter on detach/reattach/local digest -->
* <!-- TODO: Add a live demo once ref.detectChanges is merged into master -->
*
* ### Example
*
* The following example defines a component with a large list of readonly data.
* Imagine, the data changes constantly, many times per second. For performance reasons,
* we want to check and update the list every five seconds.
*
* We can do that by detaching the component's change detector and doing a local change detection
* check
* every five seconds.
*
* See {@link ChangeDetectorRef#detach} for more information.
*/
detectChanges(): void;
/**
* Checks the change detector and its children, and throws if any changes are detected.
*
* This is used in development mode to verify that running change detection doesn't introduce
* other changes.
*/
checkNoChanges(): void;
/**
* Reattach the change detector to the change detector tree.
*
* This also marks OnPush ancestors as to be checked. This reattached change detector will be
* checked during the next change detection run.
*
* <!-- TODO: Add a link to a chapter on detach/reattach/local digest -->
*
* ### Example ([live demo](http://plnkr.co/edit/aUhZha?p=preview))
*
* The following example creates a component displaying `live` data. The component will detach
* its change detector from the main change detector tree when the component's live property
* is set to false.
*
* ```typescript
* class DataProvider {
* data = 1;
*
* constructor() {
* setInterval(() => {
* this.data = this.data * 2;
* }, 500);
* }
* }
*
* @Component({
* selector: 'live-data',
* inputs: ['live'],
* template: `Data: {{dataProvider.data}}`
* })
* class LiveData {
* constructor(private ref: ChangeDetectorRef, private dataProvider:DataProvider) {}
*
* set live(value) {
* if (value)
* this.ref.reattach();
* else
* this.ref.detach();
* }
* }
*
* @Component({
* selector: 'app',
* providers: [DataProvider],
* template: `
* Live Update: <input type="checkbox" [(ngModel)]="live">
* <live-data [live]="live"><live-data>
* `,
* directives: [LiveData, FORM_DIRECTIVES]
* })
* class App {
* live = true;
* }
*
* bootstrap(App);
* ```
*/
reattach(): void;
}
/**
* Describes within the change detector which strategy will be used the next time change
* detection is triggered.
*/
export const enum ChangeDetectionStrategy {
/**
* `CheckedOnce` means that after calling detectChanges the mode of the change detector
* will become `Checked`.
*/
/**
* `Checked` means that the change detector should be skipped until its mode changes to
* `CheckOnce`.
*/
/**
* `CheckAlways` means that after calling detectChanges the mode of the change detector
* will remain `CheckAlways`.
*/
/**
* `Detached` means that the change detector sub tree is not a part of the main tree and
* should be skipped.
*/
/**
* `OnPush` means that the change detector's mode will be set to `CheckOnce` during hydration.
*/
OnPush = 0,
/**
* `Default` means that the change detector's mode will be set to `CheckAlways` during hydration.
*/
Default = 1,
}
export type ProviderType = Type | string | OpaqueToken;
/**
* should extract the string token from provided Type and add $inject angular 1 annotation to constructor if @Inject
* was used
* @param type
* @returns {string}
*/
export function provide(type: ProviderType, {useClass, useValue, useFactory, deps}?: {
useClass?: Type,
useValue?: any,
useFactory?: Function,
deps?: Object[]
}): [string, Type];
function Directive({selector, legacy}: {
selector: string;
legacy?: ng.IDirective;
inputs?: string[],
outputs?: string[],
providers?: Function[],
}): ClassDecorator;
function Component({selector, template, templateUrl, inputs, attrs, outputs, legacy, changeDetection, directives, moduleId}: {
selector: string;
template?: string;
templateUrl?: string;
inputs?: string[];
outputs?: string[];
attrs?: string[];
legacy?: ng.IDirective;
changeDetection?: ChangeDetectionStrategy;
directives?: Function[],
providers?: Function[],
viewProviders?: Function[],
pipes?: Function[],
moduleId?: string
}): ClassDecorator;
function Output(bindingPropertyName?: string): PropertyDecorator;
function Input(bindingPropertyName?: string): PropertyDecorator;
function Attr(bindingPropertyName?: string): PropertyDecorator;
/**
* Interface for creating NgModuleMetadata
*/
interface NgModuleMetadataType {
providers?: any[];
declarations?: Array<Type | Type[]>;
imports?: Array<Type | string>;
exports?: Array<Type | any[]>;
entryComponents?: Array<Type | any[]>;
bootstrap?: Array<Type | any[]>;
schemas?: Array<any[]>;
}
class NgModuleMetadata implements NgModuleMetadataType {
providers: any[];
private _providers;
declarations: Array<Type | Type[]>;
imports: Array<Type | string>;
constructor(options?: NgModuleMetadataType);
}
export interface TypeDecorator {
/**
* Invoke as ES7 decorator.
*/
<T extends Type>(type: T): T;
(target: Object, propertyKey?: string | symbol, parameterIndex?: number): void;
}
/**
* Interface for the {@link NgModuleMetadata} decorator function.
*
* See {@link NgModuleMetadataFactory}.
*
* @stable
*/
export interface NgModuleDecorator extends TypeDecorator {
}
/**
* {@link NgModuleMetadata} factory for creating annotations, decorators or DSL.
*
* @experimental
*/
export interface NgModuleMetadataFactory {
(obj?: NgModuleMetadataType): NgModuleDecorator;
new (obj?: NgModuleMetadataType): NgModuleMetadata;
}
/**
* Declares an ng module.
* @experimental
* @Annotation
*/
export const NgModule: NgModuleMetadataFactory;
function Pipe({name, pure}?: {
name?: string;
pure?: boolean;
}): ClassDecorator;
export function Optional(): ParameterDecorator;
export function Host(): ParameterDecorator;
export function Parent(): ParameterDecorator;
export function Self(): ParameterDecorator;
export function SkipSelf(): ParameterDecorator;
export function HostListener(eventName: string, args?: string[]): MethodDecorator;
/**
* Factory for {@link ContentChildren}.
*/
export interface ContentChildrenFactory {
(selector: Type | string, {descendants}?: {
descendants?: boolean;
}): any;
new (selector: Type | string, {descendants}?: {
descendants?: boolean;
}): any;
}
/**
* Factory for {@link ContentChild}.
*/
export interface ContentChildFactory {
(selector: Type | string): any;
new (selector: Type | string): any;
}
/**
* Factory for {@link ViewChildren}.
*/
export interface ViewChildrenFactory {
(selector: Type | string): any;
new (selector: Type | string): any;
}
/**
* Factory for {@link ViewChild}.
*/
export interface ViewChildFactory {
(selector: Type | string): any;
new (selector: Type | string): ViewChildFactory;
}
export const ContentChildren: ContentChildrenFactory;
export const ContentChild: ContentChildFactory;
export const ViewChildren: ViewChildrenFactory;
export const ViewChild: ViewChildFactory;
interface InjectableServiceConfigStatic {
_name?: string
}
/**
* Injectable type used for @Inject(Injectable) decorator
*/
type InjectableToken = string | Function | InjectableServiceConfigStatic;
function Inject(injectable: InjectableToken): ParameterDecorator;
function Injectable(name?: string): ClassDecorator;
export interface ForwardRefFn {
(): any;
__forward_ref__?: Type;
toString?(): string;
}
/**
* Allows to refer to references which are not yet defined.
*
* For instance, `forwardRef` is used when the `token` which we need to refer to for the purposes of
* DI is declared,
* but not yet defined. It is also used when the `token` which we use when creating a query is not
* yet defined.
*
* ### Example
* {@example core/di/ts/forward_ref/forward_ref.ts region='forward_ref'}
*/
export function forwardRef(forwardRefFn: ForwardRefFn): Type;
export enum LifecycleHooks {
OnInit = 0,
OnDestroy = 1,
AfterContentInit = 2,
AfterContentChecked = 3,
AfterViewInit = 4,
AfterViewChecked = 5,
OnChildrenChanged = 6,
}
/**
* @internal
*/
export var LIFECYCLE_HOOKS_VALUES: LifecycleHooks[];
/**
* Lifecycle hooks are guaranteed to be called in the following order:
* - `OnChanges` (if any bindings have changed),
* - `OnInit` (after the first check only),
* - `AfterContentInit`,
* - `AfterContentChecked`,
* - `AfterViewInit`,
* - `AfterViewChecked`,
* - `OnDestroy` (at the very end before destruction)
*/
/**
* Implement this interface to get notified when any data-bound property of your directive changes.
*
* `ngOnChanges` is called right after the data-bound properties have been checked and before view
* and content children are checked if at least one of them has changed.
*
* The `changes` parameter contains an entry for each of the changed data-bound property. The key is
* the property name and the value is an instance of {@link SimpleChange}.
*
* ### Example ([live example](http://plnkr.co/edit/AHrB6opLqHDBPkt4KpdT?p=preview)):
*
* ```typescript
* @Component({
* selector: 'my-cmp',
* template: `<p>myProp = {{myProp}}</p>`
* })
* class MyComponent implements OnChanges {
* @Input() myProp: any;
*
* ngOnChanges(changes: {[propName: string]: SimpleChange}) {
* console.log('ngOnChanges - myProp = ' + changes['myProp'].currentValue);
* }
* }
*
* @Component({
* selector: 'app',
* template: `
* <button (click)="value = value + 1">Change MyComponent</button>
* <my-cmp [my-prop]="value"></my-cmp>`,
* directives: [MyComponent]
* })
* export class App {
* value = 0;
* }
*
* bootstrap(App).catch(err => console.error(err));
* ```
*/
export interface OnChanges {
ngOnChanges(changes: SimpleChanges): any;
}
/**
* Implement this interface to execute custom initialization logic after your directive's
* data-bound properties have been initialized.
*
* `ngOnInit` is called right after the directive's data-bound properties have been checked for the
* first time, and before any of its children have been checked. It is invoked only once when the
* directive is instantiated.
*
* ### Example ([live example](http://plnkr.co/edit/1MBypRryXd64v4pV03Yn?p=preview))
*
* ```typescript
* @Component({
* selector: 'my-cmp',
* template: `<p>my-component</p>`
* })
* class MyComponent implements OnInit, OnDestroy {
* ngOnInit() {
* console.log('ngOnInit');
* }
*
* ngOnDestroy() {
* console.log('ngOnDestroy');
* }
* }
*
* @Component({
* selector: 'app',
* template: `
* <button (click)="hasChild = !hasChild">
* {{hasChild ? 'Destroy' : 'Create'}} MyComponent
* </button>
* <my-cmp *ngIf="hasChild"></my-cmp>`,
* directives: [MyComponent, NgIf]
* })
* export class App {
* hasChild = true;
* }
*
* bootstrap(App).catch(err => console.error(err));
* ```
*/
export interface OnInit {
ngOnInit(): any;
}
/**
* Implement this interface to override the default change detection algorithm for your directive.
*
* `ngDoCheck` gets called to check the changes in the directives instead of the default algorithm.
*
* The default change detection algorithm looks for differences by comparing bound-property values
* by reference across change detection runs. When `DoCheck` is implemented, the default algorithm
* is disabled and `ngDoCheck` is responsible for checking for changes.
*
* Implementing this interface allows improving performance by using insights about the component,
* its implementation and data types of its properties.
*
* Note that a directive should not implement both `DoCheck` and {@link OnChanges} at the same time.
* `ngOnChanges` would not be called when a directive implements `DoCheck`. Reaction to the changes
* have to be handled from within the `ngDoCheck` callback.
*
* Use {@link KeyValueDiffers} and {@link IterableDiffers} to add your custom check mechanisms.
*
* ### Example ([live demo](http://plnkr.co/edit/QpnIlF0CR2i5bcYbHEUJ?p=preview))
*
* In the following example `ngDoCheck` uses an {@link IterableDiffers} to detect the updates to the
* array `list`:
*
* ```typescript
* @Component({
* selector: 'custom-check',
* template: `
* <p>Changes:</p>
* <ul>
* <li *ngFor="let line of logs">{{line}}</li>
* </ul>`,
* directives: [NgFor]
* })
* class CustomCheckComponent implements DoCheck {
* @Input() list: any[];
* differ: any;
* logs = [];
*
* constructor(differs: IterableDiffers) {
* this.differ = differs.find([]).create(null);
* }
*
* ngDoCheck() {
* var changes = this.differ.diff(this.list);
*
* if (changes) {
* changes.forEachAddedItem(r => this.logs.push('added ' + r.item));
* changes.forEachRemovedItem(r => this.logs.push('removed ' + r.item))
* }
* }
* }
*
* @Component({
* selector: 'app',
* template: `
* <button (click)="list.push(list.length)">Push</button>
* <button (click)="list.pop()">Pop</button>
* <custom-check [list]="list"></custom-check>`,
* directives: [CustomCheckComponent]
* })
* export class App {
* list = [];
* }
* ```
*/
export interface DoCheck {
ngDoCheck(): any;
}
/**
* Implement this interface to get notified when your directive is destroyed.
*
* `ngOnDestroy` callback is typically used for any custom cleanup that needs to occur when the
* instance is destroyed
*
* ### Example ([live example](http://plnkr.co/edit/1MBypRryXd64v4pV03Yn?p=preview))
*
* ```typesript
* @Component({
* selector: 'my-cmp',
* template: `<p>my-component</p>`
* })
* class MyComponent implements OnInit, OnDestroy {
* ngOnInit() {
* console.log('ngOnInit');
* }
*
* ngOnDestroy() {
* console.log('ngOnDestroy');
* }
* }
*
* @Component({
* selector: 'app',
* template: `
* <button (click)="hasChild = !hasChild">
* {{hasChild ? 'Destroy' : 'Create'}} MyComponent
* </button>
* <my-cmp *ngIf="hasChild"></my-cmp>`,
* directives: [MyComponent, NgIf]
* })
* export class App {
* hasChild = true;
* }
*
* bootstrap(App).catch(err => console.error(err));
* ```
*
*
* To create a stateful Pipe, you should implement this interface and set the `pure`
* parameter to `false` in the {@link PipeMetadata}.
*
* A stateful pipe may produce different output, given the same input. It is
* likely that a stateful pipe may contain state that should be cleaned up when
* a binding is destroyed. For example, a subscription to a stream of data may need to
* be disposed, or an interval may need to be cleared.
*
* ### Example ([live demo](http://plnkr.co/edit/i8pm5brO4sPaLxBx56MR?p=preview))
*
* In this example, a pipe is created to countdown its input value, updating it every
* 50ms. Because it maintains an internal interval, it automatically clears
* the interval when the binding is destroyed or the countdown completes.
*
* ```
* import {OnDestroy, Pipe, PipeTransform} from 'angular2/core'
* @Pipe({name: 'countdown', pure: false})
* class CountDown implements PipeTransform, OnDestroy {
* remainingTime:Number;
* interval:SetInterval;
* ngOnDestroy() {
* if (this.interval) {
* clearInterval(this.interval);
* }
* }
* transform(value: any, args: any[] = []) {
* if (!parseInt(value, 10)) return null;
* if (typeof this.remainingTime !== 'number') {
* this.remainingTime = parseInt(value, 10);
* }
* if (!this.interval) {
* this.interval = setInterval(() => {
* this.remainingTime-=50;
* if (this.remainingTime <= 0) {
* this.remainingTime = 0;
* clearInterval(this.interval);
* delete this.interval;
* }
* }, 50);
* }
* return this.remainingTime;
* }
* }
* ```
*
* Invoking `{{ 10000 | countdown }}` would cause the value to be decremented by 50,
* every 50ms, until it reaches 0.
*
*/
export interface OnDestroy {
ngOnDestroy(): any;
}
/**
* Implement this interface to get notified when your directive's content has been fully
* initialized.
*
* ### Example ([live demo](http://plnkr.co/edit/plamXUpsLQbIXpViZhUO?p=preview))
*
* ```typescript
* @Component({
* selector: 'child-cmp',
* template: `{{where}} child`
* })
* class ChildComponent {
* @Input() where: string;
* }
*
* @Component({
* selector: 'parent-cmp',
* template: `<ng-content></ng-content>`
* })
* class ParentComponent implements AfterContentInit {
* @ContentChild(ChildComponent) contentChild: ChildComponent;
*
* constructor() {
* // contentChild is not initialized yet
* console.log(this.getMessage(this.contentChild));
* }
*
* ngAfterContentInit() {
* // contentChild is updated after the content has been checked
* console.log('AfterContentInit: ' + this.getMessage(this.contentChild));
* }
*
* private getMessage(cmp: ChildComponent): string {
* return cmp ? cmp.where + ' child' : 'no child';
* }
* }
*
* @Component({
* selector: 'app',
* template: `
* <parent-cmp>
* <child-cmp where="content"></child-cmp>
* </parent-cmp>`,
* directives: [ParentComponent, ChildComponent]
* })
* export class App {
* }
*
* bootstrap(App).catch(err => console.error(err));
* ```
*/
export interface AfterContentInit {
ngAfterContentInit(): any;
}
/**
* Implement this interface to get notified after every check of your directive's content.
*
* ### Example ([live demo](http://plnkr.co/edit/tGdrytNEKQnecIPkD7NU?p=preview))
*
* ```typescript
* @Component({selector: 'child-cmp', template: `{{where}} child`})
* class ChildComponent {
* @Input() where: string;
* }
*
* @Component({selector: 'parent-cmp', template: `<ng-content></ng-content>`})
* class ParentComponent implements AfterContentChecked {
* @ContentChild(ChildComponent) contentChild: ChildComponent;
*
* constructor() {
* // contentChild is not initialized yet
* console.log(this.getMessage(this.contentChild));
* }
*
* ngAfterContentChecked() {
* // contentChild is updated after the content has been checked
* console.log('AfterContentChecked: ' + this.getMessage(this.contentChild));
* }
*
* private getMessage(cmp: ChildComponent): string {
* return cmp ? cmp.where + ' child' : 'no child';
* }
* }
*
* @Component({
* selector: 'app',
* template: `
* <parent-cmp>
* <button (click)="hasContent = !hasContent">Toggle content child</button>
* <child-cmp *ngIf="hasContent" where="content"></child-cmp>
* </parent-cmp>`,
* directives: [NgIf, ParentComponent, ChildComponent]
* })
* export class App {
* hasContent = true;
* }
*
* bootstrap(App).catch(err => console.error(err));
* ```
*/
export interface AfterContentChecked {
ngAfterContentChecked(): any;
}
/**
* Implement this interface to get notified when your component's view has been fully initialized.
*
* ### Example ([live demo](http://plnkr.co/edit/LhTKVMEM0fkJgyp4CI1W?p=preview))
*
* ```typescript
* @Component({selector: 'child-cmp', template: `{{where}} child`})
* class ChildComponent {
* @Input() where: string;
* }
*
* @Component({
* selector: 'parent-cmp',
* template: `<child-cmp where="view"></child-cmp>`,
* directives: [ChildComponent]
* })
* class ParentComponent implements AfterViewInit {
* @ViewChild(ChildComponent) viewChild: ChildComponent;
*
* constructor() {
* // viewChild is not initialized yet
* console.log(this.getMessage(this.viewChild));
* }
*
* ngAfterViewInit() {
* // viewChild is updated after the view has been initialized
* console.log('ngAfterViewInit: ' + this.getMessage(this.viewChild));
* }
*
* private getMessage(cmp: ChildComponent): string {
* return cmp ? cmp.where + ' child' : 'no child';
* }
* }
*
* @Component({
* selector: 'app',
* template: `<parent-cmp></parent-cmp>`,
* directives: [ParentComponent]
* })
* export class App {
* }
*
* bootstrap(App).catch(err => console.error(err));
* ```
*/
export interface AfterViewInit {
ngAfterViewInit(): any;
}
/**
* Implement this interface to get notified after every check of your component's view.
*
* ### Example ([live demo](http://plnkr.co/edit/0qDGHcPQkc25CXhTNzKU?p=preview))
*
* ```typescript
* @Component({selector: 'child-cmp', template: `{{where}} child`})
* class ChildComponent {
* @Input() where: string;
* }
*
* @Component({
* selector: 'parent-cmp',
* template: `
* <button (click)="showView = !showView">Toggle view child</button>
* <child-cmp *ngIf="showView" where="view"></child-cmp>`,
* directives: [NgIf, ChildComponent]
* })
* class ParentComponent implements AfterViewChecked {
* @ViewChild(ChildComponent) viewChild: ChildComponent;
* showView = true;
*
* constructor() {
* // viewChild is not initialized yet
* console.log(this.getMessage(this.viewChild));
* }
*
* ngAfterViewChecked() {
* // viewChild is updated after the view has been checked
* console.log('AfterViewChecked: ' + this.getMessage(this.viewChild));
* }
*
* private getMessage(cmp: ChildComponent): string {
* return cmp ? cmp.where + ' child' : 'no child';
* }
* }
*
* @Component({
* selector: 'app',
* template: `<parent-cmp></parent-cmp>`,
* directives: [ParentComponent]
* })
* export class App {
* }
*
* bootstrap(App).catch(err => console.error(err));
* ```
*/
export interface AfterViewChecked {
ngAfterViewChecked(): any;
}
/**
* this is a private interface which method is called from within postLink Fn or
* from children which are queryied via one of `@Query*` decorators
* @private
*/
export interface OnChildrenChanged {
_ngOnChildrenChanged?(): any;
}
export interface OnChanges {
ngOnChanges(changes: {[key: string]: {
previousValue: any,
currentValue: any,
isFirstChange(): boolean
}});
}
/**
* Disable Angular's development mode, which turns off assertions and other
* checks within the framework.
*
* One important assertion this disables verifies that a change detection pass
* does not result in additional changes to any bindings (also known as
* unidirectional data flow).
*/
export function enableProdMode(): void;
export class EventEmitter<T> {
private __isAsync;
/** @internal */
private _ngExpressionBindingCb;
/**
* Creates an instance of [EventEmitter], which depending on [isAsync],
* delivers events synchronously or asynchronously.
*/
constructor(isAsync?: boolean);
/** @internal */
wrapNgExpBindingToEmitter(cb: Function): void;
emit(value: T): void;
subscribe(generatorOrNext?: any, error?: any, complete?: any): {unsubscribe():void};
}
export interface EventHandler<T> {
($event: T):void;
}
}
declare module ngMetadataCommon {
export const CORE_DIRECTIVES: Type[]
export abstract class NgModel implements ng.INgModelController {
$viewValue: any;
$modelValue: any;
$parsers: ng.IModelParser[];
$formatters: ng.IModelFormatter[];
$viewChangeListeners: ng.IModelViewChangeListener[];
$error: any;
$name: string;
$touched: boolean;
$untouched: boolean;
$validators: ng.IModelValidators;
$asyncValidators: ng.IAsyncModelValidators;
$pending: any;
$pristine: boolean;
$dirty: boolean;
$valid: boolean;
$invalid: boolean;
$render(): void;
$setValidity(validationErrorKey: string, isValid: boolean): void;
$setViewValue(value: any, trigger?: string): void;
$setPristine(): void;
$setDirty(): void;
$validate(): void;
$setTouched(): void;
$setUntouched(): void;
$rollbackViewValue(): void;
$commitViewValue(): void;
$isEmpty(value: any): boolean;
}
export abstract class NgForm implements ng.IFormController {
$name: string;
$pristine: boolean;
$dirty: boolean;
$valid: boolean;
$invalid: boolean;
$submitted: boolean;
$error: any;
$pending: any;
$addControl(control: ng.INgModelController): void;
$removeControl(control: ng.INgModelController): void;
$setValidity(validationErrorKey: string, isValid: boolean, control: ng.INgModelController): void;
$setDirty(): void;
$setPristine(): void;
$commitViewValue(): void;
$rollbackViewValue(): void;
$setSubmitted(): void;
$setUntouched(): void;
}
export abstract class NgSelect {
ngModelCtrl: ng.INgModelController;
unknownOption: ng.IAugmentedJQuery;
renderUnknownOption(val: string): void;
removeUnknownOption(): void;
abstract readValue(): string;
writeValue(value: string): void;
addOption(value: string, element: ng.IAugmentedJQuery): void;
removeOption(value: any): void;
abstract hasOption(value: any): boolean;
registerOption(optionScope: ng.IScope, optionElement: ng.IAugmentedJQuery, optionAttrs: ng.IAttributes, interpolateValueFn?: Function, interpolateTextFn?: Function): void;
}
export class AsyncPipe {
private static nextObjectID;
private static values;
private static subscriptions;
private static TRACK_PROP_NAME;
private static objectId(obj);
private static isPromiseOrObservable(obj);
private static getSubscriptionStrategy(input);
private static dispose(inputId);
transform(input: Observable<any> | ng.IPromise<any> | ng.IHttpPromise<any>, scope?: ng.IScope): any;
}
}
declare module "ng-metadata/core" {
export = ngMetadataCore;
}
declare module "ng-metadata/platform-browser-dynamic" {
export = ngMetadataPlatform;
}
declare module "ng-metadata/common" {
export = ngMetadataCommon
}
declare type Type = Function; | the_stack |
import {LanguageService} from '../../src/language_service';
import {APP_COMPONENT, MockService, setup} from './mock_host';
import {HumanizedDefinitionInfo, humanizeDefinitionInfo} from './test_utils';
describe('type definitions', () => {
let service: MockService;
let ngLS: LanguageService;
beforeAll(() => {
const {project, service: _service, tsLS} = setup();
service = _service;
ngLS = new LanguageService(project, tsLS, {});
});
const possibleArrayDefFiles = new Set([
'lib.es5.d.ts', 'lib.es2015.core.d.ts', 'lib.es2015.iterable.d.ts',
'lib.es2015.symbol.wellknown.d.ts', 'lib.es2016.array.include.d.ts'
]);
beforeEach(() => {
service.reset();
});
describe('elements', () => {
it('should work for native elements', () => {
const defs = getTypeDefinitions({
templateOverride: `<butt¦on></button>`,
});
expect(defs.length).toEqual(2);
expect(defs[0].fileName).toContain('lib.dom.d.ts');
expect(defs[0].contextSpan).toContain('interface HTMLButtonElement extends HTMLElement');
expect(defs[1].contextSpan).toContain('declare var HTMLButtonElement');
});
it('should return directives which match the element tag', () => {
const defs = getTypeDefinitions({
templateOverride: `<butt¦on compound custom-button></button>`,
});
expect(defs.length).toEqual(3);
expect(defs[0].contextSpan).toContain('export class CompoundCustomButtonDirective');
expect(defs[1].contextSpan).toContain('interface HTMLButtonElement extends HTMLElement');
expect(defs[2].contextSpan).toContain('declare var HTMLButtonElement');
});
});
describe('templates', () => {
it('should return no definitions for ng-templates', () => {
const {position} =
service.overwriteInlineTemplate(APP_COMPONENT, `<ng-templ¦ate></ng-template>`);
const defs = ngLS.getTypeDefinitionAtPosition(APP_COMPONENT, position);
expect(defs).toEqual([]);
});
});
describe('directives', () => {
it('should work for directives', () => {
const definitions = getTypeDefinitions({
templateOverride: `<div string-model¦></div>`,
});
expect(definitions.length).toEqual(1);
expect(definitions[0].fileName).toContain('parsing-cases.ts');
expect(definitions[0].textSpan).toEqual('StringModel');
expect(definitions[0].contextSpan).toContain('@Directive');
});
it('should work for components', () => {
const definitions = getTypeDefinitions({
templateOverride: `<t¦est-comp></test-comp>`,
});
expect(definitions.length).toEqual(1);
expect(definitions[0].textSpan).toEqual('TestComponent');
expect(definitions[0].contextSpan).toContain('@Component');
});
it('should work for structural directives', () => {
const definitions = getTypeDefinitions({
templateOverride: `<div *¦ngFor="let item of heroes"></div>`,
});
expect(definitions.length).toEqual(1);
expect(definitions[0].fileName).toContain('ng_for_of.d.ts');
expect(definitions[0].textSpan).toEqual('NgForOf');
expect(definitions[0].contextSpan)
.toContain(
'export declare class NgForOf<T, U extends NgIterable<T> = NgIterable<T>> implements DoCheck');
});
it('should work for directives with compound selectors', () => {
let defs = getTypeDefinitions({
templateOverride: `<button com¦pound custom-button></button>`,
});
expect(defs.length).toEqual(1);
expect(defs[0].contextSpan).toContain('export class CompoundCustomButtonDirective');
defs = getTypeDefinitions({
templateOverride: `<button compound cu¦stom-button></button>`,
});
expect(defs.length).toEqual(1);
expect(defs[0].contextSpan).toContain('export class CompoundCustomButtonDirective');
});
});
describe('bindings', () => {
describe('inputs', () => {
it('should return something for input providers with non-primitive types', () => {
const defs = getTypeDefinitions({
templateOverride: `<button compound custom-button [config¦]="{}"></button>`,
});
expect(defs.length).toEqual(1);
expect(defs[0].textSpan).toEqual('{color?: string}');
});
it('should work for structural directive inputs ngForTrackBy', () => {
const definitions = getTypeDefinitions({
templateOverride: `<div *ngFor="let item of heroes; tr¦ackBy: test;"></div>`,
});
expect(definitions!.length).toEqual(1);
const [def] = definitions;
expect(def.textSpan).toEqual('TrackByFunction');
expect(def.contextSpan).toContain('export interface TrackByFunction<T>');
});
it('should work for structural directive inputs ngForOf', () => {
const definitions = getTypeDefinitions({
templateOverride: `<div *ngFor="let item o¦f heroes"></div>`,
});
// In addition to all the array defs, this will also return the NgForOf def because the
// input is part of the selector ([ngFor][ngForOf]).
expectAllDefinitions(
definitions, new Set(['Array', 'NgForOf']),
new Set([...possibleArrayDefFiles, 'ng_for_of.d.ts']));
});
it('should return nothing for two-way binding providers', () => {
const definitions = getTypeDefinitions({
templateOverride: `<test-comp string-model [(mo¦del)]="title"></test-comp>`,
});
// TODO(atscott): This should actually return EventEmitter type but we only match the input
// at the moment.
expect(definitions).toEqual([]);
});
});
describe('outputs', () => {
it('should work for event providers', () => {
const definitions = getTypeDefinitions({
templateOverride: `<test-comp (te¦st)="myClick($event)"></test-comp>`,
});
expect(definitions!.length).toEqual(2);
const [emitterInterface, emitterConst] = definitions;
expect(emitterInterface.textSpan).toEqual('EventEmitter');
expect(emitterInterface.contextSpan)
.toContain('export interface EventEmitter<T> extends Subject<T>');
expect(emitterInterface.fileName).toContain('event_emitter.d.ts');
expect(emitterConst.textSpan).toEqual('EventEmitter');
expect(emitterConst.contextSpan).toContain('export declare const EventEmitter');
expect(emitterConst.fileName).toContain('event_emitter.d.ts');
});
it('should return the directive when the event is part of the selector', () => {
const definitions = getTypeDefinitions({
templateOverride: `<div (eventSelect¦or)="title = ''"></div>`,
});
expect(definitions!.length).toEqual(3);
// EventEmitter tested in previous test
const directiveDef = definitions[2];
expect(directiveDef.contextSpan).toContain('export class EventSelectorDirective');
});
it('should work for native event outputs', () => {
const definitions = getTypeDefinitions({
templateOverride: `<div (cl¦ick)="myClick($event)"></div>`,
});
expect(definitions!.length).toEqual(1);
expect(definitions[0].textSpan).toEqual('addEventListener');
expect(definitions[0].contextSpan)
.toEqual(
'addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;');
expect(definitions[0].fileName).toContain('lib.dom.d.ts');
});
});
});
describe('references', () => {
it('should work for element references', () => {
const defs = getTypeDefinitions({
templateOverride: `<div #chart></div>{{char¦t}}`,
});
expect(defs.length).toEqual(2);
expect(defs[0].contextSpan).toContain('interface HTMLDivElement extends HTMLElement');
expect(defs[1].contextSpan).toContain('declare var HTMLDivElement');
});
it('should work for directive references', () => {
const defs = getTypeDefinitions({
templateOverride: `<div #mod¦el="stringModel" string-model></div>`,
});
expect(defs.length).toEqual(1);
expect(defs[0].contextSpan).toContain('@Directive');
expect(defs[0].contextSpan).toContain('export class StringModel');
});
});
describe('variables', () => {
it('should work for array members', () => {
const definitions = getTypeDefinitions({
templateOverride: `<div *ngFor="let hero of heroes">{{her¦o}}</div>`,
});
expect(definitions!.length).toEqual(1);
expect(definitions[0].textSpan).toEqual('Hero');
expect(definitions[0].contextSpan).toContain('export interface Hero');
});
});
describe('pipes', () => {
it('should work for pipes', () => {
const templateOverride = `<p>The hero's birthday is {{birthday | da¦te: "MM/dd/yy"}}</p>`;
const definitions = getTypeDefinitions({
templateOverride,
});
expect(definitions!.length).toEqual(1);
const [def] = definitions;
expect(def.textSpan).toEqual('transform');
expect(def.contextSpan).toContain('transform(value: Date');
});
});
describe('expressions', () => {
it('should return nothing for primitives', () => {
const definitions = getTypeDefinitions({
templateOverride: `<div>{{ tit¦le }}</div>`,
});
expect(definitions!.length).toEqual(0);
});
// TODO(atscott): Investigate why this returns nothing in the test environment. This actually
// works in the extension.
xit('should work for functions on primitives', () => {
const definitions = getTypeDefinitions({
templateOverride: `<div>{{ title.toLower¦case() }}</div>`,
});
expect(definitions!.length).toEqual(1);
expect(definitions[0].textSpan).toEqual('toLowerCase');
expect(definitions[0].fileName).toContain('lib.es5.d.ts');
});
it('should work for accessed property reads', () => {
const definitions = getTypeDefinitions({
templateOverride: `<div>{{heroes[0].addre¦ss}}</div>`,
});
expect(definitions!.length).toEqual(1);
const [def] = definitions;
expect(def.textSpan).toEqual('Address');
expect(def.contextSpan).toContain('export interface Address');
});
it('should work for $event', () => {
const definitions = getTypeDefinitions({
templateOverride: `<button (click)="title=$ev¦ent"></button>`,
});
expect(definitions!.length).toEqual(2);
const [def1, def2] = definitions;
expect(def1.textSpan).toEqual('MouseEvent');
expect(def1.contextSpan).toContain(`interface MouseEvent extends UIEvent`);
expect(def2.textSpan).toEqual('MouseEvent');
expect(def2.contextSpan).toContain(`declare var MouseEvent:`);
});
it('should work for method calls', () => {
const definitions = getTypeDefinitions({
templateOverride: `<div (click)="setT¦itle('title')"></div>`,
});
expect(definitions!.length).toEqual(1);
const [def] = definitions;
expect(def.textSpan).toEqual('setTitle');
expect(def.contextSpan).toContain('setTitle(newTitle: string)');
});
it('should work for accessed properties in writes', () => {
const definitions = getTypeDefinitions({
templateOverride: `<div (click)="hero.add¦ress = undefined"></div>`,
});
expect(definitions!.length).toEqual(1);
const [def] = definitions;
expect(def.textSpan).toEqual('Address');
expect(def.contextSpan).toContain('export interface Address');
});
it('should work for variables in structural directives', () => {
const definitions = getTypeDefinitions({
templateOverride: `<div *ngFor="let item of heroes as her¦oes2; trackBy: test;"></div>`,
});
expectAllDefinitions(definitions, new Set(['Array']), possibleArrayDefFiles);
});
it('should work for uses of members in structural directives', () => {
const definitions = getTypeDefinitions({
templateOverride: `<div *ngFor="let item of heroes as heroes2">{{her¦oes2}}</div>`,
});
expectAllDefinitions(definitions, new Set(['Array']), possibleArrayDefFiles);
});
it('should work for members in structural directives', () => {
const definitions = getTypeDefinitions({
templateOverride: `<div *ngFor="let item of her¦oes; trackBy: test;"></div>`,
});
expectAllDefinitions(definitions, new Set(['Array']), possibleArrayDefFiles);
});
it('should return nothing for the $any() cast function', () => {
const {position} =
service.overwriteInlineTemplate(APP_COMPONENT, `<div>{{$an¦y(title)}}</div>`);
const definitionAndBoundSpan = ngLS.getTypeDefinitionAtPosition(APP_COMPONENT, position);
expect(definitionAndBoundSpan).toBeUndefined();
});
});
function getTypeDefinitions({templateOverride}: {templateOverride: string}):
HumanizedDefinitionInfo[] {
const {position} = service.overwriteInlineTemplate(APP_COMPONENT, templateOverride);
const defs = ngLS.getTypeDefinitionAtPosition(APP_COMPONENT, position);
expect(defs).toBeTruthy();
return defs!.map(d => humanizeDefinitionInfo(d, service));
}
function expectAllDefinitions(
definitions: HumanizedDefinitionInfo[], textSpans: Set<string>,
possibleFileNames: Set<string>) {
expect(definitions!.length).toBeGreaterThan(0);
const actualTextSpans = new Set(definitions.map(d => d.textSpan));
expect(actualTextSpans).toEqual(textSpans);
for (const def of definitions) {
const fileName = def.fileName.split('/').slice(-1)[0];
expect(possibleFileNames)
.toContain(fileName, `Expected ${fileName} to be one of: ${possibleFileNames}`);
}
}
}); | the_stack |
import { connect, ConnectRequest, Emitter, EmitterMessage } from "emitter-io";
import LatLon from "geodesy/latlon-spherical.js";
import { Hangar } from "./hangar";
import { Delivery, Warehouse } from "./warehouse";
import { Weather } from "./weather";
const MAX_PAYLOAD_BATT_DRAIN: number = .005; // max batt drain (%/s) at max payload
const BASE_BATT_DRAIN: number = .00005; // max batt drain (%/s) at max payload
const LOW_BATT_LEVEL: number = .25;
interface Channel {
name: "drone-position" | "event";
key: string;
}
interface Location {
lat: number;
lon: number;
}
interface EventData {
message: string;
batteryConsumed?: number;
packagePayload?: number;
}
interface ControlEvent {
type: "pause" | "resume" | "cancel" | "set_altitude";
filter: {
name?: string[];
warehouse?: string[];
hangar?: string[];
};
data: {
message?: string;
altitude?: number;
};
}
// Assumptions:
// Drone experiences constant accelleration
// Power/Payload impact acceleration
// Top speed capped at 10x power
export class Drone {
public id: string;
public name: string;
private hangar: Hangar;
private power: number; // size of drone, impacts speed/accel
private client: Emitter | null;
private active: boolean; // deployed in air
private status: "charging" | "traveling" | "loading" | "unloading";
private location: LatLon; // current location
private bearing: number; // degrees from north
private speed: number; // m/s
private accel: number; // m/s^2
private altitude: number; // m
private battery: number; // percent
private temperature: number; // degree C
private dest: LatLon; // current destination
private warehouse: Warehouse | null; // warehouse drone is deployed to
private jobs: Delivery[]; // package deliveries
private completed: Delivery[]; // complete package deliveries
private ctlPause: boolean; // flag indicating the drone is paused
private ctlCancel: boolean; // flag indicating the drone operation is cancelled
private ctlAltitude: number; // the desired altitude for operation
private weather: Weather;
private badBattery: boolean;
constructor(id: string, name: string, hangar: Hangar, power: number, weather: Weather, badBattery=false) {
this.id = id;
this.name = name;
this.hangar = hangar;
this.power = power;
this.client = null;
this.active = false; // deployed
this.status = "charging";
this.location = hangar.location;
this.bearing = 0;
this.speed = 0;
this.accel = 0;
this.altitude = 0;
this.battery = 1; // 0 - 1, percent capacity
this.temperature = 23;
this.dest = hangar.location;
this.warehouse = null;
this.jobs = [];
this.completed = [];
this.ctlPause = false;
this.ctlCancel = false;
this.ctlAltitude = 300;
this.weather = weather;
this.badBattery = badBattery;
}
// take off an begin delivering packages from warehouse
public async deploy(warehouse: Warehouse, broker: ConnectRequest) {
// takeoff (assume it takes 5 secs)
this.goTo(warehouse.location);
this.altitude = this.ctlAltitude;
this.battery = 1;
this.warehouse = warehouse;
this.speed = 0;
this.accel = 0;
if (!process.env.CHANNEL_KEY_DRONE_POSITION
|| !process.env.CHANNEL_KEY_DRONE_EVENT
|| !process.env.CHANNEL_KEY_CONTROL_EVENT) {
console.log("Can't connect to ATC - missing channel key(s). Drone grounded...");
return;
}
this.client = connect(broker, () => {
console.log("%s lifting off with ", this.name, this.badBattery ? "weak battery" : "good battery");
// tslint:disable-next-line: no-unused-expression
this.client && this.client.subscribe({
channel: "control-event",
key: process.env.CHANNEL_KEY_CONTROL_EVENT || "",
});
// tslint:disable-next-line: no-unused-expression
this.client && this.client.on("message", (msg: EmitterMessage) => {
const message: ControlEvent = msg.asObject();
if ((message.filter.name && message.filter.name.includes(this.name))
|| (message.filter.warehouse && message.filter.warehouse.includes(
this.warehouse && this.warehouse.name || ""))
|| (message.filter.hangar && message.filter.hangar.includes(this.hangar.name))
) {
console.log(message);
console.log("%s received control event %s", this.name, message.type);
this.sendEvent("control_event_rx", {
message: message.data.message || "Control Event received",
});
} else {
return;
}
if (message.type === "pause") {
this.ctlPause = true;
}
if (message.type === "resume") {
this.ctlPause = false;
}
if (message.type === "cancel") {
this.ctlCancel = true;
}
if (message.type === "set_altitude") {
this.ctlAltitude = message.data.altitude || this.ctlAltitude;
console.log("%s adjusting altitude to %d", this.name, this.ctlAltitude);
}
});
this.sendEvent("drone_deployed", {
message: "Drone now active",
});
this.active = true;
this.run();
});
}
private goTo(dest: LatLon) {
this.status = "traveling";
this.dest = dest;
}
private touchDown(decendedCallback: any, ascendedCallback: any) {
const decendTimer = setInterval(() => {
// console.log("decending....");
this.altitude = 3 * (this.altitude / 4);
if (this.altitude < 20) {
clearInterval(decendTimer);
decendedCallback();
const ascendTimer = setInterval(() => {
// console.log("ascending....");
this.altitude = this.altitude * (3 / 2);
if (this.altitude >= this.ctlAltitude) {
this.altitude = this.ctlAltitude;
clearInterval(ascendTimer);
ascendedCallback();
}
}, 1000);
}
}, 1000);
}
private dropPackage() {
this.touchDown(() => {
console.log("%s delivered package...", this.name);
const delivery = this.jobs.shift();
if (delivery) {
delivery.batteryConsumed = delivery.batteryConsumed - this.battery;
this.completed.push(delivery);
this.sendEvent("package_delivered", {
batteryConsumed: Math.floor(delivery.batteryConsumed * 100),
message: "Package has been delivered",
packagePayload: Math.floor(delivery.payload * 100),
});
}
}, () => {
this.goTo(
this.jobs.length && this.jobs[0].dest ||
this.warehouse && this.warehouse.location ||
this.hangar.location);
});
}
private reLoad() {
this.touchDown(() => {
console.log("%s picked up package...", this.name);
this.jobs = this.warehouse && this.warehouse.pickup() || [];
this.jobs.forEach((element) => {
// save the starting battery level, we'll calculate consumption once we drop
element.batteryConsumed = this.battery;
this.sendEvent("package_loaded", {
message: "Package has been loaded",
packagePayload: Math.floor(element.payload * 100),
});
});
}, () => {
this.goTo(
this.jobs.length && this.jobs[0].dest ||
this.warehouse && this.warehouse.location ||
this.hangar.location,
);
});
}
private async sendEvent(eventType: string, eventData: EventData) {
// tslint:disable-next-line: no-unused-expression
this.client && this.client.publish({
channel: "drone-event",
key: process.env.CHANNEL_KEY_DRONE_EVENT || "",
message: JSON.stringify({
data: {
batteryConsumed: eventData.batteryConsumed || 0,
batteryPercent: Math.floor(this.battery * 100),
hangar: this.hangar.name,
location: {
lat: this.location.lat,
lon: this.location.lon,
},
message: eventData.message,
name: this.name,
packagePayload: eventData.packagePayload || 0,
payload: Math.floor(this.jobs.reduce((sum, job) => sum + job.payload, 0) * 100),
warehouse: this.warehouse && this.warehouse.name || "unassigned",
},
type: eventType,
}),
});
}
private processDest(dest: LatLon) {
// take action based on where we are
if (this.status === "traveling") {
if (this.warehouse && this.warehouse.location === dest) {
this.status = "loading";
this.reLoad();
} else if (this.jobs.length && this.jobs[0].dest === dest) {
this.status = "unloading";
this.dropPackage();
} else if (this.hangar.location === dest) {
this.status = "charging";
this.active = false;
} else {
console.log("unhandled destination......");
}
}
}
private processState() {
// calculate the new state based on our last state
let battDrain = 1;
if (this.weather.isWindy(this.location, this.altitude)) {
// send event and drain battery hard
console.log("%s Flying in windy area", this.name);
battDrain = 3;
this.sendEvent("system_warning", {
message: "High Wind Warning",
});
}
if (this.badBattery) {
// cause some random accelerated drainage
battDrain = battDrain + Math.random() * 2;
}
const payload = this.jobs.reduce((sum, job) => sum + job.payload, 0);
const batteryConsumed = (MAX_PAYLOAD_BATT_DRAIN * payload * battDrain) - BASE_BATT_DRAIN;
this.battery = Math.max(this.battery - batteryConsumed, .01);
this.location = this.location.destinationPoint(this.calcDistanceTraveled(1), this.bearing);
this.bearing = this.location.initialBearingTo(this.dest) || 0;
this.speed = Math.min(this.power * 10, Math.max(this.speed + this.accel, 0));
const calcStatus = this.ctlPause && "pausing" || this.ctlCancel && "cancelling" || this.status;
console.log("%s %s at location: %s, bearing: %d, alt %s, speed %d, accel %d, batt %d",
this.name, calcStatus, this.location.toString(), this.bearing, this.altitude,
this.speed, this.accel, this.battery);
// tslint:disable-next-line: no-unused-expression
this.client && this.client.publish({
channel: "drone-position",
key: process.env.CHANNEL_KEY_DRONE_POSITION || "",
message: JSON.stringify({
altitude: this.altitude,
batteryDrain: batteryConsumed,
batteryPercent: Math.floor(this.battery * 100),
bearing: this.bearing,
destination: {
lat: this.dest.lat,
lon: this.dest.lon,
},
location: {
lat: this.location.lat,
lon: this.location.lon,
},
name: this.name,
payloadPercent: Math.floor(payload * 100),
speed: this.speed,
status: calcStatus,
tempCelsius: this.temperature + (this.altitude / 100) + (2 * Math.random()),
}),
});
// calculate trajectory corrections
if (this.ctlCancel && this.status === "traveling") {
// force cancel as soon as possible
this.goTo(this.hangar.location);
}
if (this.battery < LOW_BATT_LEVEL &&
0 === this.jobs.length &&
this.status === "traveling" &&
this.dest !== this.hangar.location) {
// divert to hangar if battery gets low while returning to warehouse
this.sendEvent("low_battery", {
message: "Battery is low, returning to charge",
});
console.log("%s has low battery, diverting to hangar...", this.name);
this.goTo(this.hangar.location);
}
const distToDest = this.location.distanceTo(this.dest); // meters
const stopDist = this.calcStopDistance();
// console.log("%d meters to dest, %d needed to stop", distToDest, stopDist);
// adjust altitude when traveling
if (this.status === "traveling") {
this.altitude = (this.ctlAltitude > this.altitude)
? this.altitude + this.power : this.altitude - this.power;
if (Math.abs(this.ctlAltitude - this.altitude) < this.power) {
// add a little randomness
this.altitude = this.ctlAltitude + (10 * Math.random()) - 5;
}
}
if (this.ctlPause) {
console.log ("pausing");
this.accel = -this.power;
if (Math.abs(this.speed) < this.power) {
this.speed = 0;
this.accel = 0;
}
} else if (distToDest < this.power) {
// console.log("stopping");
this.location = this.dest;
this.speed = 0;
this.accel = 0;
this.processDest(this.dest);
} else if (distToDest < (stopDist + (2 * this.speed))) {
// console.log("slowing down");
this.accel = -this.power;
} else {
// console.log("full speed ahead");
this.accel = this.power;
}
}
private processErrors() {
// calculate random error and warning events
if (Math.random() > .999) {
// .1% chance of high wind
this.sendEvent("system_warning", {
message: "High Wind Warning",
});
}
if (Math.random() > .999) {
// .1% chance of battery overheating
this.sendEvent("system_warning", {
message: "High Battery Temperature",
});
}
if (Math.random() > .99995) {
// .005% chance of motor running inefficient
this.sendEvent("system_error", {
message: "Motor Overcurrent",
});
}
if (Math.random() > .9999) {
// .01% chance of gps sensor malfunction
this.sendEvent("system_error", {
message: "GPS Sensor Malfunction",
});
}
if (Math.random() > .9999) {
// .01% chance of gyro sensor malfunction
this.sendEvent("system_error", {
message: "Gyro Sensor Malfunction",
});
}
}
private async run() {
while (this.active) {
this.processState();
this.processErrors();
// console.log(this);
await new Promise((resolve) => setTimeout(resolve, 1000));
}
await this.sendEvent("drone_grounded", {
message: "Drone returned to hangar",
});
console.log("%s returned to hangar...", this.name);
// tslint:disable-next-line: no-unused-expression
this.client && this.client.disconnect();
this.client = null;
// console.log(this);
}
private calcDistanceTraveled(time: number) {
const Vi = this.speed;
const a = this.accel;
return (Vi * time) + (.5 * a * time * time);
}
private calcStopDistance() {
const Vi = this.speed;
const a = this.power;
const t = (Vi / a); // time required to stop
return (Vi * t) - (.5 * a * t * t);
}
} | the_stack |
import * as pdfMake from 'pdfmake/build/pdfmake';
import * as pdfFonts from 'pdfmake/build/vfs_fonts';
const definitions = [
{
content: [
'First paragraph',
'Another paragraph, this time a little bit longer to make sure, this line will be divided into at least two lines'
]
},
{
content: [
{
text: 'This is a header, using header style',
style: 'header'
},
'Lorem ipsum dolor sit amet, consectetur adipisicing elit. \n\n',
{
text: 'Subheader 1 - using subheader style',
style: 'subheader'
},
'Lorem ipsum dolor sit amet, consectetur adipisicing elit. ',
'Lorem ipsum dolor sit amet, consectetur adipisicing elit. ',
'Lorem ipsum dolor sit amet, consectetur adipisicing elit. \n\n',
{
text: 'Subheader 2 - using subheader style',
style: 'subheader'
},
'Lorem ipsum dolor sit amet, consectetur adipisicing elit. ',
'Lorem ipsum dolor sit amet, consectetur adipisicing elit. \n\n',
{
text: 'It is possible to apply multiple styles, ',
style: ['quote', 'small']
}
],
styles: {
header: {
fontSize: 18,
bold: true
},
subheader: {
fontSize: 15,
bold: true
},
quote: {
italics: true
},
small: {
fontSize: 8
}
}
},
{
content: [
{
text: 'This is a header (whole paragraph uses the same header style)\n\n',
style: 'header'
},
{
text: [
'It is however possible to provide an array of texts ',
'to the paragraph (instead of a single string) and have ',
{ text: 'a better ', fontSize: 15, bold: true },
'control over it. \nEach inline can be ',
{ text: 'styled ', fontSize: 20 },
{ text: 'independently ', italics: true, fontSize: 40 },
'then.\n\n'
]
},
{ text: 'Mixing named styles and style-overrides', style: 'header' },
{
style: 'bigger',
italics: false,
text: [
'We can also mix named-styles and style-overrides at both paragraph and inline level. ',
'For example, this paragraph uses the "bigger" style, which changes fontSize to 15 and sets italics to true. ',
'Texts are not italics though. It\'s because we\'ve overriden italics back to false at ',
'the paragraph level. \n\n',
'We can also change the style of a single inline. Let\'s use a named style called header: ',
{ text: 'like here.\n', style: 'header' },
'It got bigger and bold.\n\n',
'OK, now we\'re going to mix named styles and style-overrides at the inline level. ',
'We\'ll use header style (it makes texts bigger and bold), but we\'ll override ',
'bold back to false: ',
{ text: 'wow! it works!', style: 'header', bold: false },
'\n\nMake sure to take a look into the sources to understand what\'s going on here.'
]
}
],
styles: {
header: {
fontSize: 18,
bold: true
},
bigger: {
fontSize: 15,
italics: true
}
}
},
{
content: [
{
text: 'This paragraph uses header style and extends the alignment property',
style: 'header',
alignment: 'center'
},
{
text: [
'This paragraph uses header style and overrides bold value setting it back to false.\n',
'Header style in this example sets alignment to justify, so this paragraph should be rendered \n',
'Lorem ipsum dolor sit amet, consectetur adipisicing elit. Malit profecta versatur nomine ocurreret '
],
style: 'header',
bold: false
}
],
styles: {
header: {
fontSize: 18,
bold: true,
alignment: 'justify'
}
}
},
{
content: [
'By default paragraphs are stacked one on top of (or actually - below) another. ',
'It\'s possible however to split any paragraph (or even the whole document) into columns.\n\n',
'Here we go with 2 star-sized columns, with justified text and gap set to 20:\n\n',
{
alignment: 'justify',
columns: [
{
text: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit.'
},
{
text: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit.'
}
]
},
'\nStar-sized columns have always equal widths, so if we define 3 of those, ',
'it\'ll look like this (make sure to scroll to the next page, as we have a couple of more examples):\n\n',
{
columns: [
{
text: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit.'
},
{
text: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit.'
},
{
text: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit.'
}
]
},
'\nYou can also specify accurate widths for some (or all columns)',
{
columns: [
{
width: 90,
text: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit.'
},
{
width: '*',
text: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit.'
},
{
width: '*',
text: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit.'
},
{
width: 90,
text: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit.'
}
]
},
'\nWe also support auto columns. They set their widths based on the content:\n\n',
{
columns: [
{
width: 'auto',
text: 'auto column'
},
{
width: '*',
text: 'This is a star-sized column. It should get the remaining'
+ ' space divided by the number of all star-sized columns.'
},
{
width: 50,
text: 'this one has specific width set to 50'
},
{
width: 'auto',
text: 'another auto column'
},
{
width: '*',
text: 'This is a star-sized column. It should get the remaining space '
+ 'divided by the number of all star-sized columns.'
},
]
},
'\nIf all auto columns fit within available width, the table does not occupy whole space:\n\n',
{
columns: [
{
width: 'auto',
text: 'val1'
},
{
width: 'auto',
text: 'val2'
},
{
width: 'auto',
text: 'value3'
},
{
width: 'auto',
text: 'value 4'
},
]
},
'\nAnother cool feature of pdfmake is the ability to have nested elements.',
{
columns: [
{
width: 100,
fontSize: 9,
text: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit. '
},
[
'As you can see in the document definition - this column is not defined with ',
'an object, but an array, which means it\'s treated as an array of paragraphs rendered one below another.',
'Just like on the top-level of the document. Let\'s try to divide the remaing space into 3 star-sized columns:\n\n',
{
columns: [
{ text: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit.' },
{ text: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit.' },
{ text: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit.' },
]
}
]
]
},
'\n\nOh, don\'t forget, we can use everything from styling examples (named styles, custom overrides) here as well.\n\n',
'For instance - our next paragraph will use the \'bigger\' style (with fontSize set to 15 and italics - true).',
' We\'ll split it into three columns and make sure they inherit the style:\n\n',
{
style: 'bigger',
columns: [
'First column (BTW - it\'s defined as a single string value. pdfmake will turn it into appropriate structure ',
'automatically and make sure it inherits the styles',
{
fontSize: 20,
text: 'In this column, we\'ve overriden fontSize to 20. It means the content should have italics=true'
+ ' (inherited from the style) and be a little bit bigger'
},
{
style: 'header',
text: 'Last column does not override any styling properties, but applies a new style (header) to itself.'
+ ' Eventually - texts here have italics=true (from bigger) and derive fontSize from the style.'
+ ' OK, but which one? Both styles define it. As we already know from our styling examples, multiple'
+ ' styles can be applied to the element and their order is important. Because \'header\' style has been'
+ ' set after \'bigger\' its fontSize takes precedence over the fontSize from \'bigger\'. This is how it works. '
+ 'You will find more examples in the unit tests.'
}
]
},
'\n\nWow, you\'ve read the whole document! Congratulations :D'
],
styles: {
header: {
fontSize: 18,
bold: true
},
bigger: {
fontSize: 15,
italics: true
}
},
defaultStyle: {
columnGap: 20
}
},
{
content: [
{ text: 'Tables', style: 'header' },
'Official documentation is in progress, this document is just',
' a glimpse of what is possible with pdfmake and its layout engine.',
{ text: 'A simple table (no headers, no width specified, no spans, no styling)',
style: 'subheader' },
'The following table has nothing more than a body array',
{
style: 'tableExample',
table: {
body: [
['Column 1', 'Column 2', 'Column 3'],
['One value goes here', 'Another one here', 'OK?']
]
}
},
{ text: 'A simple table with nested elements', style: 'subheader' },
'It is of course possible to nest any other type of nodes available in ',
'pdfmake inside table cells',
{
style: 'tableExample',
table: {
body: [
['Column 1', 'Column 2', 'Column 3'],
[
{
stack: [
'Let\'s try an unordered list',
{
ul: [
'item 1',
'item 2'
]
}
]
},
[
'or a nested table',
{
table: {
body: [
['Col1', 'Col2', 'Col3'],
['1', '2', '3'],
['1', '2', '3']
]
},
}
],
{
text: [
'Inlines can be ',
{ text: 'styled\n', italics: true },
{ text: 'easily as everywhere else', fontSize: 10 }]
}
]
]
}
},
{ text: 'Defining column widths', style: 'subheader' },
'Tables support the same width definitions as standard columns:',
{
bold: true,
ul: [
'auto',
'star',
'fixed value'
]
},
{
style: 'tableExample',
table: {
widths: [100, '*', 200, '*'],
body: [
['width=100', 'star-sized', 'width=200', 'star-sized'],
['fixed-width cells have exactly the specified width',
{ text: 'nothing interesting here', italics: true, color: 'gray' },
{ text: 'nothing interesting here', italics: true, color: 'gray' },
{ text: 'nothing interesting here', italics: true, color: 'gray' }]
]
}
},
{
style: 'tableExample',
table: {
widths: ['*', 'auto'],
body: [
['This is a star-sized column. The next column over, an auto-sized column, will wrap to accomodate all the text in this cell.', 'I am auto sized.'],
]
}
},
{
style: 'tableExample',
table: {
widths: ['*', 'auto'],
body: [
['This is a star-sized column. The next column over, an auto-sized column',
{ text: 'I am auto sized.', noWrap: true }],
]
}
},
{ text: 'Defining row heights', style: 'subheader' },
{
style: 'tableExample',
table: {
heights: [20, 50, 70],
body: [
['row 1 with height 20', 'column B'],
['row 2 with height 50', 'column B'],
['row 3 with height 70', 'column B']
]
}
},
'With same height:',
{
style: 'tableExample',
table: {
heights: 40,
body: [
['row 1', 'column B'],
['row 2', 'column B'],
['row 3', 'column B']
]
}
},
'With height from function:',
{
style: 'tableExample',
table: {
heights: (row: number) => {
return (row + 1) * 25;
},
body: [
['row 1', 'column B'],
['row 2', 'column B'],
['row 3', 'column B']
]
}
},
{ text: 'Column/row spans', pageBreak: 'before', style: 'subheader' },
'Each cell-element can set a rowSpan or colSpan',
{
style: 'tableExample',
color: '#444',
table: {
widths: [200, 'auto', 'auto'],
headerRows: 2,
// keepWithHeaderRows: 1,
body: [
[{ text: 'Header with Colspan = 2', style: 'tableHeader', colSpan: 2, alignment: 'center' },
{}, { text: 'Header 3', style: 'tableHeader', alignment: 'center' }],
[{ text: 'Header 1', style: 'tableHeader', alignment: 'center' },
{ text: 'Header 2', style: 'tableHeader', alignment: 'center' },
{ text: 'Header 3', style: 'tableHeader', alignment: 'center' }],
['Sample value 1', 'Sample value 2', 'Sample value 3'],
[{ rowSpan: 3, text: 'rowSpan set to 3\nLorem ipsum dolor sit amet' },
'Sample value 2', 'Sample value 3'],
['', 'Sample value 2', 'Sample value 3'],
['Sample value 1', 'Sample value 2', 'Sample value 3'],
['Sample value 1', { colSpan: 2, rowSpan: 2, text: 'Both:\nrowSpan and colSpan\ncan be defined at the same time' }, ''],
['Sample value 1', '', ''],
]
}
},
{ text: 'Headers', pageBreak: 'before', style: 'subheader' },
'You can declare how many rows should be treated as a header. Headers are',
' automatically repeated on the following pages',
{ text: ['It is also possible to set keepWithHeaderRows to make sure there will be no page-break'
+ 'between the header and these rows. Take a look at the document-definition and play with it. '
+ 'If you set it to one, the following table will automatically start on the next page, '
+ 'since there\'s not enough space for the first row to be rendered here'], color: 'gray', italics: true },
{
style: 'tableExample',
table: {
headerRows: 1,
// dontBreakRows: true,
// keepWithHeaderRows: 1,
body: [
[{ text: 'Header 1', style: 'tableHeader' }, { text: 'Header 2', style: 'tableHeader' },
{ text: 'Header 3', style: 'tableHeader' }],
[
'Lorem ipsum dolor sit amet, ',
'Lorem ipsum dolor sit amet, ',
'Lorem ipsum dolor sit amet, ',
]
]
}
},
{ text: 'Styling tables', style: 'subheader' },
'You can provide a custom styler for the table. Currently it supports:',
{
ul: [
'line widths',
'line colors',
'cell paddings',
]
},
'with more options coming soon...\n\npdfmake currently has a few predefined styles (see them on the next page)',
{ text: 'noBorders:', fontSize: 14, bold: true, pageBreak: 'before', margin: [0, 0, 0, 8] },
{
style: 'tableExample',
table: {
headerRows: 1,
body: [
[{ text: 'Header 1', style: 'tableHeader' }, { text: 'Header 2', style: 'tableHeader' },
{ text: 'Header 3', style: 'tableHeader' }],
['Sample value 1', 'Sample value 2', 'Sample value 3'],
['Sample value 1', 'Sample value 2', 'Sample value 3'],
['Sample value 1', 'Sample value 2', 'Sample value 3'],
['Sample value 1', 'Sample value 2', 'Sample value 3'],
['Sample value 1', 'Sample value 2', 'Sample value 3'],
]
},
layout: 'noBorders'
},
{ text: 'headerLineOnly:', fontSize: 14, bold: true, margin: [0, 20, 0, 8] },
{
style: 'tableExample',
table: {
headerRows: 1,
body: [
[{ text: 'Header 1', style: 'tableHeader' }, { text: 'Header 2', style: 'tableHeader' },
{ text: 'Header 3', style: 'tableHeader' }],
['Sample value 1', 'Sample value 2', 'Sample value 3'],
['Sample value 1', 'Sample value 2', 'Sample value 3'],
['Sample value 1', 'Sample value 2', 'Sample value 3'],
['Sample value 1', 'Sample value 2', 'Sample value 3'],
['Sample value 1', 'Sample value 2', 'Sample value 3'],
]
},
layout: 'headerLineOnly'
},
{ text: 'lightHorizontalLines:', fontSize: 14, bold: true, margin: [0, 20, 0, 8] },
{
style: 'tableExample',
table: {
headerRows: 1,
body: [
[{ text: 'Header 1', style: 'tableHeader' }, { text: 'Header 2', style: 'tableHeader' }, { text: 'Header 3', style: 'tableHeader' }],
['Sample value 1', 'Sample value 2', 'Sample value 3'],
['Sample value 1', 'Sample value 2', 'Sample value 3'],
['Sample value 1', 'Sample value 2', 'Sample value 3'],
['Sample value 1', 'Sample value 2', 'Sample value 3'],
['Sample value 1', 'Sample value 2', 'Sample value 3'],
]
},
layout: 'lightHorizontalLines'
},
{ text: 'but you can provide a custom styler as well', margin: [0, 20, 0, 8] },
{
style: 'tableExample',
table: {
headerRows: 1,
body: [
[{ text: 'Header 1', style: 'tableHeader' }, { text: 'Header 2', style: 'tableHeader' }, { text: 'Header 3', style: 'tableHeader' }],
['Sample value 1', 'Sample value 2', 'Sample value 3'],
['Sample value 1', 'Sample value 2', 'Sample value 3'],
['Sample value 1', 'Sample value 2', 'Sample value 3'],
['Sample value 1', 'Sample value 2', 'Sample value 3'],
['Sample value 1', 'Sample value 2', 'Sample value 3'],
]
},
layout: {
hLineWidth: (i: number, node: any) => {
return (i === 0 || i === node.table.body.length) ? 2 : 1;
},
vLineWidth: (i: number, node: any) => {
return (i === 0 || i === node.table.widths.length) ? 2 : 1;
},
hLineColor: (i: number, node: any) => {
return (i === 0 || i === node.table.body.length) ? 'black' : 'gray';
},
vLineColor: (i: number, node: any) => {
return (i === 0 || i === node.table.widths.length) ? 'black' : 'gray';
},
// paddingLeft: function(i, node) { return 4; },
// paddingRight: function(i, node) { return 4; },
// paddingTop: function(i, node) { return 2; },
// paddingBottom: function(i, node) { return 2; },
// fillColor: (i: number, node: any) => { return null; }
}
},
{ text: 'zebra style', margin: [0, 20, 0, 8] },
{
style: 'tableExample',
table: {
body: [
['Sample value 1', 'Sample value 2', 'Sample value 3'],
['Sample value 1', 'Sample value 2', 'Sample value 3'],
['Sample value 1', 'Sample value 2', 'Sample value 3'],
['Sample value 1', 'Sample value 2', 'Sample value 3'],
['Sample value 1', 'Sample value 2', 'Sample value 3'],
]
},
layout: {
fillColor: (i: number, node: any) => {
return (i % 2 === 0) ? '#CCCCCC' : null;
}
}
},
{ text: 'Optional border', fontSize: 14, bold: true, pageBreak: 'before', margin: [0, 0, 0, 8] },
'Each cell contains an optional border property: an array of 4 booleans for left border, top border, right border, bottom border.',
{
style: 'tableExample',
table: {
body: [
[
{
border: [false, true, false, false],
fillColor: '#eeeeee',
text: 'border:\n[false, true, false, false]'
},
{
border: [false, false, false, false],
fillColor: '#dddddd',
text: 'border:\n[false, false, false, false]'
},
{
border: [true, true, true, true],
fillColor: '#eeeeee',
text: 'border:\n[true, true, true, true]'
}
],
[
{
rowSpan: 3,
border: [true, true, true, true],
fillColor: '#eeeeff',
text: 'rowSpan: 3\n\nborder:\n[true, true, true, true]'
},
{
border: undefined,
fillColor: '#eeeeee',
text: 'border:\nundefined'
},
{
border: [true, false, false, false],
fillColor: '#dddddd',
text: 'border:\n[true, false, false, false]'
}
],
[
'',
{
colSpan: 2,
border: [true, true, true, true],
fillColor: '#eeffee',
text: 'colSpan: 2\n\nborder:\n[true, true, true, true]'
},
''
],
[
'',
{
border: undefined,
fillColor: '#eeeeee',
text: 'border:\nundefined'
},
{
border: [false, false, true, true],
fillColor: '#dddddd',
text: 'border:\n[false, false, true, true]'
}
]
]
},
layout: {
defaultBorder: false,
}
},
'For every cell without a border property, whether it has all borders or not is determined by ',
'layout.defaultBorder, which is false in the table above and true (by default) in the table below.',
{
style: 'tableExample',
table: {
body: [
[
{
border: [false, false, false, false],
fillColor: '#eeeeee',
text: 'border:\n[false, false, false, false]'
},
{
fillColor: '#dddddd',
text: 'border:\nundefined'
},
{
fillColor: '#eeeeee',
text: 'border:\nundefined'
},
],
[
{
fillColor: '#dddddd',
text: 'border:\nundefined'
},
{
fillColor: '#eeeeee',
text: 'border:\nundefined'
},
{
border: [true, true, false, false],
fillColor: '#dddddd',
text: 'border:\n[true, true, false, false]'
},
]
]
}
},
'And some other examples with rowSpan/colSpan...',
{
style: 'tableExample',
table: {
body: [
[
'',
'column 1',
'column 2',
'column 3'
],
[
'row 1',
{
rowSpan: 3,
colSpan: 3,
border: [true, true, true, true],
fillColor: '#cccccc',
text: 'rowSpan: 3\ncolSpan: 3\n\nborder:\n[true, true, true, true]'
},
'',
''
],
[
'row 2',
'',
'',
''
],
[
'row 3',
'',
'',
''
]
]
},
layout: {
defaultBorder: false,
}
},
{
style: 'tableExample',
table: {
body: [
[
{
colSpan: 3,
text: 'colSpan: 3\n\nborder:\n[false, false, false, false]',
fillColor: '#eeeeee',
border: [false, false, false, false]
},
'',
''
],
[
'border:\nundefined',
'border:\nundefined',
'border:\nundefined'
]
]
}
},
{
style: 'tableExample',
table: {
body: [
[
{ rowSpan: 3, text: 'rowSpan: 3\n\nborder:\n[false, false, false, false]', fillColor: '#eeeeee', border: [false, false, false, false] },
'border:\nundefined',
'border:\nundefined'
],
[
'',
'border:\nundefined',
'border:\nundefined'
],
[
'',
'border:\nundefined',
'border:\nundefined'
]
]
}
}
],
styles: {
header: {
fontSize: 18,
bold: true,
margin: [0, 0, 0, 10]
},
subheader: {
fontSize: 16,
bold: true,
margin: [0, 10, 0, 5]
},
tableExample: {
margin: [0, 5, 0, 15]
},
tableHeader: {
bold: true,
fontSize: 13,
color: 'black'
}
},
defaultStyle: {
// alignment: 'justify'
}
},
{
content: [
{ text: 'Unordered list', style: 'header' },
{
ul: [
'item 1',
'item 2',
'item 3'
]
},
{ text: '\n\nUnordered list with longer lines', style: 'header' },
{
ul: [
'item 1',
'Lorem ipsum dolor sit amet, consectetur adipisicing elit.',
'item 3'
]
},
{ text: '\n\nOrdered list', style: 'header' },
{
ol: [
'item 1',
'item 2',
'item 3'
]
},
{ text: '\n\nOrdered list with longer lines', style: 'header' },
{
ol: [
'item 1',
'Lorem ipsum dolor sit amet, consectetur adipisicing elit.',
'item 3'
]
},
{ text: '\n\nOrdered list should be descending', style: 'header' },
{
reversed: true,
ol: [
'item 1',
'item 2',
'item 3'
]
},
{ text: '\n\nOrdered list with start value', style: 'header' },
{
start: 50,
ol: [
'item 1',
'item 2',
'item 3'
]
},
{ text: '\n\nOrdered list with own values', style: 'header' },
{
ol: [
{ text: 'item 1', counter: 10 },
{ text: 'item 2', counter: 20 },
{ text: 'item 3', counter: 30 },
{ text: 'item 4 without own value' }
]
},
{ text: '\n\nNested lists (ordered)', style: 'header' },
{
ol: [
'item 1',
[
'Lorem ipsum dolor sit amet, consectetur adipisicing elit.',
{
ol: [
'subitem 1',
'subitem 2',
'subitem 3 - Lorem ipsum dolor sit amet',
'subitem 3 - Lorem ipsum dolor sit amet',
'subitem 3 - Lorem ipsum dolor sit amet',
{
text: [
'subitem 3 - Lorem ipsum dolor sit amet',
'subitem 3 - Lorem ipsum dolor sit amet',
'subitem 3 - Lorem ipsum dolor sit amet',
'subitem 3 - Lorem ipsum dolor sit amet',
'subitem 3 - Lorem ipsum dolor sit amet',
'subitem 3 - Lorem ipsum dolor sit amet',
'subitem 3 - Lorem ipsum dolor sit amet',
'subitem 3 - Lorem ipsum dolor sit amet',
]
},
'subitem 3 - Lorem ipsum dolor sit amet',
'subitem 3 - Lorem ipsum dolor sit amet',
'subitem 3 - Lorem ipsum dolor sit amet',
'subitem 3 - Lorem ipsum dolor sit amet',
'subitem 4',
'subitem 5',
]
}
],
'item 3\nsecond line of item3'
]
},
{ text: '\n\nNested lists (unordered)', style: 'header' },
{
ol: [
'item 1',
'Lorem ipsum dolor sit amet',
{
ul: [
'subitem 1',
'subitem 2',
'subitem 3 - Lorem ipsum dolor sit amet',
'subitem 3 - Lorem ipsum dolor sit amet',
'subitem 3 - Lorem ipsum dolor sit amet',
{
text: [
'subitem 3 - Lorem ipsum dolor sit amet',
'subitem 3 - Lorem ipsum dolor sit amet',
'subitem 3 - Lorem ipsum dolor sit amet',
'subitem 3 - Lorem ipsum dolor sit amet',
'subitem 3 - Lorem ipsum dolor sit amet',
'subitem 3 - Lorem ipsum dolor sit amet',
'subitem 3 - Lorem ipsum dolor sit amet',
'subitem 3 - Lorem ipsum dolor sit amet',
]
},
'subitem 3 - Lorem ipsum dolor sit amet',
'subitem 3 - Lorem ipsum dolor sit amet',
'subitem 3 - Lorem ipsum dolor sit amet',
'subitem 3 - Lorem ipsum dolor sit amet',
'subitem 4',
'subitem 5',
]
},
'item 3\nsecond line of item3',
]
},
{ text: '\n\nUnordered lists inside columns', style: 'header' },
{
columns: [
{
ul: [
'item 1',
'Lorem ipsum dolor sit amet',
]
},
{
ul: [
'item 1',
'Lorem ipsum dolor sit amet',
]
}
]
},
{ text: '\n\nOrdered lists inside columns', style: 'header' },
{
columns: [
{
ol: [
'item 1',
'Lorem ipsum dolor sit amet',
]
},
{
ol: [
'item 1',
'Lorem ipsum dolor sit amet',
]
}
]
},
{ text: '\n\nNested lists width columns', style: 'header' },
{
ul: [
'item 1',
'Lorem ipsum dolor sit amet',
{
ol: [
[
{
columns: [
'column 1',
{
stack: [
'column 2',
{
ul: [
'item 1',
'item 2',
{
ul: [
'item',
'item',
'item',
]
},
'item 4',
]
}
]
},
'column 3',
'column 4',
]
},
'subitem 1 in a vertical container',
'subitem 2 in a vertical container',
],
'subitem 2',
'subitem 3 - Lorem ipsum dolor sit amet',
'subitem 3 - Lorem ipsum dolor sit amet',
'subitem 3 - Lorem ipsum dolor sit amet',
{
text: [
'subitem 3 - Lorem ipsum dolor sit amet',
'subitem 3 - Lorem ipsum dolor sit amet',
'subitem 3 - Lorem ipsum dolor sit amet',
'subitem 3 - Lorem ipsum dolor sit amet',
'subitem 3 - Lorem ipsum dolor sit amet',
'subitem 3 - Lorem ipsum dolor sit amet',
'subitem 3 - Lorem ipsum dolor sit amet',
'subitem 3 - Lorem ipsum dolor sit amet',
]
},
'subitem 3 - Lorem ipsum dolor sit amet',
'subitem 3 - Lorem ipsum dolor sit amet',
'subitem 3 - Lorem ipsum dolor sit amet',
'subitem 3 - Lorem ipsum dolor sit amet',
'subitem 4',
'subitem 5',
]
},
'item 3\nsecond line of item3',
]
},
{ text: '\n\nUnordered list with square marker type', style: 'header' },
{
type: 'square',
ul: [
'item 1',
'item 2',
'item 3'
]
},
{ text: '\n\nUnordered list with circle marker type', style: 'header' },
{
type: 'circle',
ul: [
'item 1',
'item 2',
'item 3'
]
},
{ text: '\n\nColored unordered list', style: 'header' },
{
color: 'blue',
ul: [
'item 1',
'item 2',
'item 3'
]
},
{ text: '\n\nColored unordered list with own marker color', style: 'header' },
{
color: 'blue',
markerColor: 'red',
ul: [
'item 1',
'item 2',
'item 3'
]
},
{ text: '\n\nColored ordered list', style: 'header' },
{
color: 'blue',
ol: [
'item 1',
'item 2',
'item 3'
]
},
{ text: '\n\nColored ordered list with own marker color', style: 'header' },
{
color: 'blue',
markerColor: 'red',
ol: [
'item 1',
'item 2',
'item 3'
]
},
{ text: '\n\nOrdered list - type: lower-alpha', style: 'header' },
{
type: 'lower-alpha',
ol: [
'item 1',
'item 2',
'item 3'
]
},
{ text: '\n\nOrdered list - type: upper-alpha', style: 'header' },
{
type: 'upper-alpha',
ol: [
'item 1',
'item 2',
'item 3'
]
},
{ text: '\n\nOrdered list - type: upper-roman', style: 'header' },
{
type: 'upper-roman',
ol: [
'item 1',
'item 2',
'item 3',
'item 4',
'item 5'
]
},
{ text: '\n\nOrdered list - type: lower-roman', style: 'header' },
{
type: 'lower-roman',
ol: [
'item 1',
'item 2',
'item 3',
'item 4',
'item 5'
]
},
{ text: '\n\nOrdered list - type: none', style: 'header' },
{
type: 'none',
ol: [
'item 1',
'item 2',
'item 3'
]
},
{ text: '\n\nUnordered list - type: none', style: 'header' },
{
type: 'none',
ul: [
'item 1',
'item 2',
'item 3'
]
},
{ text: '\n\nOrdered list with own separator', style: 'header' },
{
separator: ')',
ol: [
'item 1',
'item 2',
'item 3'
]
},
{ text: '\n\nOrdered list with own complex separator', style: 'header' },
{
separator: ['(', ')'],
ol: [
'item 1',
'item 2',
'item 3'
]
},
{ text: '\n\nOrdered list with own items type', style: 'header' },
{
ol: [
'item 1',
{ text: 'item 2', listType: 'none' },
{ text: 'item 3', listType: 'upper-roman' }
]
},
{ text: '\n\nUnordered list with own items type', style: 'header' },
{
ul: [
'item 1',
{ text: 'item 2', listType: 'none' },
{ text: 'item 3', listType: 'circle' }
]
},
],
styles: {
header: {
bold: true,
fontSize: 15
}
},
defaultStyle: {
fontSize: 12
}
},
{
content: [
{
stack: [
'This header has both top and bottom margins defined',
{ text: 'This is a subheader', style: 'subheader' },
],
style: 'header'
},
{
text: [
'Margins have slightly different behavior than other layout properties. ',
'They are not inherited, unlike anything else. They\'re applied only to those nodes which explicitly ',
'set margin or style property.\n',
]
},
{
text: 'This paragraph (consisting of a single line) directly sets top and bottom margin to 20',
margin: [0, 20],
},
{
stack: [
{
text: [
'This line begins a stack of paragraphs. The whole stack uses a ',
{ text: 'superMargin', italics: true },
' style (with margin and fontSize properties).',
]
},
{ text: ['When you look at the', { text: ' document definition', italics: true },
', you will notice that fontSize is inherited by all paragraphs inside the stack.'] },
'Margin however is only applied once (to the whole stack).'
],
style: 'superMargin'
},
{
stack: [
'I\'m not sure yet if this is the desired behavior. I find it a better approach however.',
' One thing to be considered in the future is an explicit layout property called inheritMargin which could opt-in the inheritance.\n\n',
{
fontSize: 15,
text: [
'Currently margins for ',
/* the following margin definition doesn't change anything */
{ text: 'inlines', margin: 20 },
' are ignored\n\n'
],
},
'Lorem ipsum dolor sit amet, consectetur adipisicing elit.\n',
'Lorem ipsum dolor sit amet, consectetur adipisicing elit.\n',
'Lorem ipsum dolor sit amet, consectetur adipisicing elit.\n',
'Lorem ipsum dolor sit amet, consectetur adipisicing elit.\n',
'Lorem ipsum dolor sit amet, consectetur adipisicing elit.\n',
'Lorem ipsum dolor sit amet, consectetur adipisicing elit.\n',
'Lorem ipsum dolor sit amet, consectetur adipisicing elit.\n',
],
margin: [0, 20, 0, 0],
alignment: 'justify'
}
],
styles: {
header: {
fontSize: 18,
bold: true,
alignment: 'right',
margin: [0, 190, 0, 80]
},
subheader: {
fontSize: 14
},
superMargin: {
margin: [20, 0, 40, 0],
fontSize: 15
}
}
},
{
content: [
'pdfmake (since it\'s based on pdfkit) supports JPEG and PNG format',
'If no width/height/fit is provided, image original size will be used',
{
image: 'sampleImage.jpg',
},
'If you specify width, image will scale proportionally',
{
image: 'sampleImage.jpg',
width: 150
},
'If you specify both width and height - image will be stretched',
{
image: 'sampleImage.jpg',
width: 150,
height: 150,
},
'You can also fit the image inside a rectangle',
{
image: 'sampleImage.jpg',
fit: [100, 100],
pageBreak: 'after'
},
// Warning! Make sure to copy this definition and paste it to an
// external text editor, as the online AceEditor has some troubles
// with long dataUrl lines and the following image values look like
// they're empty.
'Images can be also provided in dataURL format...',
{
image: 'data:image/gif;base64,...',
width: 200
},
'or be declared in an "images" dictionary and referenced by name',
{
image: 'building',
width: 200
},
],
images: {
building: 'data:image/gif;base64,...'
}
},
{
compress: false,
content: ['This document does not use compression']
}
];
const createPdf = () => {
const pdf = pdfMake;
pdf.vfs = pdfFonts.pdfMake.vfs;
for (const definition of definitions) {
const typedDefinition: pdfMake.TDocumentDefinitions = definition;
pdfMake.createPdf(typedDefinition).download();
}
}; | the_stack |
import { createNanoEvents, Emitter as EventEmitter } from 'nanoevents'
import { Bsp } from './Bsp'
import { Sound } from './Sound'
import { extname } from './Util'
import { Config } from './Config'
import { Tga } from './Parsers/Tga'
import { Wad } from './Parsers/Wad'
import { Replay } from './Replay/Replay'
import { Sprite } from './Parsers/Sprite'
import { ProgressCallback, xhr } from './Xhr'
import { BspParser } from './Parsers/BspParser'
enum LoadItemStatus {
Loading = 1,
Skipped = 2,
Error = 3,
Done = 4
}
class LoadItemBase<T> {
name: string
progress: number
status: LoadItemStatus
data: T | null
constructor(name: string) {
this.name = name
this.progress = 0
this.status = LoadItemStatus.Loading
this.data = null
}
isLoading() {
return this.status === LoadItemStatus.Loading
}
skip() {
this.status = LoadItemStatus.Skipped
}
isSkipped() {
return this.status === LoadItemStatus.Skipped
}
// TODO: Add error reason
error() {
this.status = LoadItemStatus.Error
}
isError() {
return this.status === LoadItemStatus.Error
}
done(data: T) {
this.status = LoadItemStatus.Done
this.data = data
}
isDone() {
return this.status === LoadItemStatus.Done
}
}
class LoadItemReplay extends LoadItemBase<any> {
type: 'replay' = 'replay'
}
class LoadItemBsp extends LoadItemBase<Bsp> {
type: 'bsp' = 'bsp'
}
class LoadItemSky extends LoadItemBase<Tga> {
type: 'sky' = 'sky'
}
class LoadItemWad extends LoadItemBase<Wad> {
type: 'wad' = 'wad'
}
class LoadItemSound extends LoadItemBase<Sound> {
type: 'sound' = 'sound'
}
class LoadItemSprite extends LoadItemBase<Sprite> {
type: 'sprite' = 'sprite'
}
export type LoadItem =
| LoadItemReplay
| LoadItemBsp
| LoadItemSky
| LoadItemWad
| LoadItemSound
| LoadItemSprite
export class Loader {
config: Config
replay?: LoadItemReplay
map?: LoadItemBsp
skies: LoadItemSky[]
wads: LoadItemWad[]
sounds: LoadItemSound[]
sprites: { [name: string]: LoadItemSprite } = {}
events: EventEmitter
constructor(config: Config) {
this.config = config
this.replay = undefined
this.map = undefined
this.skies = []
this.wads = []
this.sounds = []
this.events = createNanoEvents()
this.events.on('error', (err: any) => {
console.error(err)
})
}
clear() {
this.replay = undefined
this.map = undefined
this.skies.length = 0
this.wads.length = 0
this.sounds.length = 0
this.sprites = {}
}
checkStatus() {
if (this.replay && !this.replay.isDone()) {
return
}
if (this.map && !this.map.isDone()) {
return
}
for (let i = 0; i < this.skies.length; ++i) {
if (this.skies[i].isLoading()) {
return
}
}
for (let i = 0; i < this.wads.length; ++i) {
if (this.wads[i].isLoading()) {
return
}
}
for (let i = 0; i < this.sounds.length; ++i) {
if (this.sounds[i].isLoading()) {
return
}
}
const sprites = Object.entries(this.sprites)
for (let i = 0; i < sprites.length; ++i) {
if (sprites[i][1].isLoading()) {
return
}
}
this.events.emit('loadall', this)
}
load(name: string) {
const extension = extname(name)
if (extension === '.dem') {
this.loadReplay(name)
} else if (extension === '.bsp') {
this.loadMap(name)
} else {
this.events.emit('error', 'Invalid file extension', name)
}
}
async loadReplay(name: string) {
this.replay = new LoadItemReplay(name)
this.events.emit('loadstart', this.replay)
const progressCallback: ProgressCallback = (_1, progress) => {
if (this.replay) {
this.replay.progress = progress
}
this.events.emit('progress', this.replay)
}
const replayPath = this.config.getReplaysPath()
const buffer = await xhr(`${replayPath}/${name}`, {
method: 'GET',
isBinary: true,
progressCallback
}).catch((err: any) => {
if (this.replay) {
this.replay.error()
}
this.events.emit('error', err, this.replay)
})
if (this.replay.isError()) {
return
}
const replay = await Replay.parseIntoChunks(buffer)
this.replay.done(replay)
this.loadMap(replay.maps[0].name + '.bsp')
const sounds = replay.maps[0].resources.sounds
sounds.forEach((sound: any) => {
if (sound.used) {
this.loadSound(sound.name, sound.index)
}
})
this.events.emit('load', this.replay)
this.checkStatus()
}
async loadMap(name: string) {
this.map = new LoadItemBsp(name)
this.events.emit('loadstart', this.map)
const progressCallback: ProgressCallback = (_1, progress) => {
if (this.map) {
this.map.progress = progress
}
this.events.emit('progress', this.map)
}
const mapsPath = this.config.getMapsPath()
const buffer = await xhr(`${mapsPath}/${name}`, {
method: 'GET',
isBinary: true,
progressCallback
}).catch(err => {
if (this.map) {
this.map.error()
}
this.events.emit('error', err, this.map)
})
if (this.map.isError()) {
return
}
const map = await BspParser.parse(name, buffer)
this.map.done(map)
map.entities
.map((e: any) => {
if (typeof e.model === 'string' && e.model.indexOf('.spr') > -1) {
return e.model as string
}
return undefined
})
.filter(
(a: string | undefined, pos: number, arr: (string | undefined)[]) =>
a && arr.indexOf(a) === pos
)
.forEach(a => a && this.loadSprite(a))
const skyname = map.entities[0].skyname
if (skyname) {
const sides = ['bk', 'dn', 'ft', 'lf', 'rt', 'up']
sides.map(a => `${skyname}${a}`).forEach(a => this.loadSky(a))
}
// check if there is at least one missing texture
// if yes then load wad files (textures should be there)
if (map.textures.find(a => a.isExternal)) {
const wads = map.entities[0].wad
const wadPromises = wads.map((w: string) => this.loadWad(w))
await Promise.all(wadPromises)
}
this.events.emit('load', this.map)
this.checkStatus()
}
async loadSprite(name: string) {
const item = new LoadItemSprite(name)
this.sprites[name] = item
this.events.emit('loadstart', item)
const progressCallback: ProgressCallback = (_1, progress) => {
item.progress = progress
this.events.emit('progress', item)
}
const buffer = await xhr(`${this.config.getBasePath()}/${name}`, {
method: 'GET',
isBinary: true,
progressCallback
}).catch((err: any) => {
item.error()
this.events.emit('error', err, item)
this.checkStatus()
})
if (item.isError()) {
return
}
const sprite = Sprite.parse(buffer)
item.done(sprite)
this.events.emit('load', item)
this.checkStatus()
}
async loadSky(name: string) {
const item = new LoadItemSky(name)
this.skies.push(item)
this.events.emit('loadstart', item)
const progressCallback: ProgressCallback = (_1, progress) => {
item.progress = progress
this.events.emit('progress', item)
}
const skiesPath = this.config.getSkiesPath()
const buffer = await xhr(`${skiesPath}/${name}.tga`, {
method: 'GET',
isBinary: true,
progressCallback
}).catch((err: any) => {
item.error()
this.events.emit('error', err, item)
this.checkStatus()
})
if (item.isError()) {
return
}
const skyImage = Tga.parse(buffer, name)
item.done(skyImage)
this.events.emit('load', item)
this.checkStatus()
}
async loadWad(name: string) {
const wadItem = new LoadItemWad(name)
this.wads.push(wadItem)
this.events.emit('loadstart', wadItem)
const progressCallback: ProgressCallback = (_1, progress) => {
wadItem.progress = progress
this.events.emit('progress', wadItem)
}
const wadsPath = this.config.getWadsPath()
const buffer = await xhr(`${wadsPath}/${name}`, {
method: 'GET',
isBinary: true,
progressCallback
}).catch((err: any) => {
wadItem.error()
this.events.emit('error', err, wadItem)
this.checkStatus()
})
if (wadItem.isError()) {
return
}
const wad = await Wad.parse(buffer)
wadItem.done(wad)
if (!this.map || !this.map.data) {
return
}
const map = this.map.data
const cmp = (a: any, b: any) => a.toLowerCase() === b.toLowerCase()
wad.entries.forEach(entry => {
if (entry.type !== 'texture') {
return
}
map.textures.forEach(texture => {
if (cmp(entry.name, texture.name)) {
texture.width = entry.width
texture.height = entry.height
texture.data = entry.data
}
})
})
this.events.emit('load', wadItem)
this.checkStatus()
}
async loadSound(name: string, index: number) {
const sound = new LoadItemSound(name)
this.sounds.push(sound)
this.events.emit('loadstart', sound)
const progressCallback: ProgressCallback = (_1, progress) => {
sound.progress = progress
this.events.emit('progress', sound)
}
const soundsPath = this.config.getSoundsPath()
const buffer = await xhr(`${soundsPath}/${name}`, {
method: 'GET',
isBinary: true,
progressCallback
}).catch((err: any) => {
sound.error()
this.events.emit('error', err, sound)
this.checkStatus()
})
if (sound.isError()) {
return
}
const data = await Sound.create(buffer).catch((err: any) => {
sound.error()
this.events.emit('error', err, sound)
this.checkStatus()
})
if (!data || sound.isError()) {
return
}
data.index = index
data.name = name
sound.done(data)
this.events.emit('load', sound)
this.checkStatus()
}
} | the_stack |
import chai, { expect } from 'chai';
import Helper from '../../src/e2e-helper/e2e-helper';
import { ExportMissingVersions } from '../../src/scope/exceptions/export-missing-versions';
import ServerIsBusy from '../../src/scope/exceptions/server-is-busy';
chai.use(require('chai-fs'));
describe('export functionality on Harmony', function () {
this.timeout(0);
let helper: Helper;
before(() => {
helper = new Helper();
});
after(() => {
helper.scopeHelper.destroy();
});
describe('export, re-init the remote scope, tag and export', () => {
before(() => {
helper.scopeHelper.setNewLocalAndRemoteScopesHarmony();
helper.bitJsonc.setupDefault();
helper.fixtures.populateComponents(1);
helper.command.tagAllWithoutBuild();
helper.command.export();
helper.scopeHelper.reInitRemoteScope();
helper.fixtures.populateComponents(1, undefined, '-v2');
helper.command.tagAllWithoutBuild();
});
it('should throw ExportMissingVersions error on export', () => {
const err = new ExportMissingVersions(`${helper.scopes.remote}/comp1`, ['0.0.1']);
const cmd = () => helper.command.export();
helper.general.expectToThrow(cmd, err);
});
it('should enable exporting with --all-versions flag', () => {
expect(() => helper.command.export('--all-versions')).not.to.throw();
});
});
describe('export, tag and export', () => {
before(() => {
helper.scopeHelper.setNewLocalAndRemoteScopesHarmony();
helper.bitJsonc.setupDefault();
helper.fixtures.populateComponents(1);
helper.command.tagAllWithoutBuild();
helper.command.export();
helper.fixtures.populateComponents(1, undefined, '-v2');
helper.command.tagAllWithoutBuild();
helper.command.export();
});
it('should not delete the first version', () => {
expect(() => helper.command.catComponent('comp1@0.0.1')).not.to.throw();
});
it('should enable un-tagging after a new tag', () => {
// before it used to throw VersionNotFound
helper.fixtures.populateComponents(1, undefined, '-v3');
helper.command.tagAllWithoutBuild();
expect(() => helper.command.untag('comp1')).not.to.throw();
});
});
describe.skip('export to multiple scope with circular between the scopes', () => {
let anotherRemote;
let exportOutput;
before(() => {
helper.scopeHelper.setNewLocalAndRemoteScopesHarmony();
helper.bitJsonc.setupDefault();
const { scopeName, scopePath } = helper.scopeHelper.getNewBareScope();
anotherRemote = scopeName;
helper.scopeHelper.addRemoteScope(scopePath);
helper.scopeHelper.addRemoteScope(scopePath, helper.scopes.remotePath);
helper.scopeHelper.addRemoteScope(helper.scopes.remotePath, scopePath);
helper.fs.outputFile('bar1/foo1.js', `require('@${anotherRemote}/bar2');`);
helper.fs.outputFile('bar2/foo2.js', `require('@${helper.scopes.remote}/bar1');`);
helper.command.addComponent('bar1');
helper.command.addComponent('bar2');
helper.bitJsonc.addToVariant('bar2', 'defaultScope', anotherRemote);
helper.command.linkAndRewire();
helper.command.compile();
helper.command.tagAllComponents();
exportOutput = helper.command.export();
});
it('should export them successfully with no errors', () => {
expect(exportOutput).to.have.string('exported the following 2 component');
const scope1 = helper.command.listRemoteScopeParsed();
expect(scope1).to.have.lengthOf(1);
const scope2 = helper.command.listRemoteScopeParsed(anotherRemote);
expect(scope2).to.have.lengthOf(1);
});
it('bit status should be clean', () => {
helper.command.expectStatusToBeClean();
});
});
/**
* there is no good option to make the remote scope fails at the persist step. normally, if there
* is any error, it stops at the validation step.
* to be able to test these scenarios, we ran the previous test "(export to multiple scope with
* circular between the scopes)", manually threw an error during the persist phase, and then tar
* the remote scopes (tar -czf mjtjb8oh-remote2-bar2.tgz pending-objects/1611930408860).
* this way, we could create tests using the extracted remote-scopes with the pending-objects
* directories.
*/
describe.skip('recover from persist-error during export', () => {
let remote1Name: string;
let remote2Name: string;
let remote1Path: string;
let remote2Path: string;
let remote1Clone: string;
let remote2Clone: string;
let exportId: string;
// extract the pending-objects to the two remotes
before(() => {
remote1Name = 'ovio1b1s-remote';
remote2Name = 'mjtjb8oh-remote2';
exportId = '1611930408860';
remote1Path = helper.scopeHelper.getNewBareScopeWithSpecificName(remote1Name);
remote2Path = helper.scopeHelper.getNewBareScopeWithSpecificName(remote2Name);
helper.fixtures.extractCompressedFixture('objects/ovio1b1s-remote-bar1.tgz', remote1Path);
helper.fixtures.extractCompressedFixture('objects/mjtjb8oh-remote2-bar2.tgz', remote2Path);
helper.scopeHelper.addRemoteScope(remote1Path, remote2Path);
helper.scopeHelper.addRemoteScope(remote2Path, remote1Path);
remote1Clone = helper.scopeHelper.cloneScope(remote1Path);
remote2Clone = helper.scopeHelper.cloneScope(remote2Path);
});
it('as an intermediate step, make sure the remotes scopes are empty', () => {
const scope1 = helper.command.catScope(true, remote1Path);
const scope2 = helper.command.catScope(true, remote2Path);
expect(scope1).to.have.lengthOf(0);
expect(scope2).to.have.lengthOf(0);
});
function expectRemotesToHaveTheComponents() {
it('the remotes should now have the components', () => {
const scope1 = helper.command.catScope(true, remote1Path);
const scope2 = helper.command.catScope(true, remote2Path);
expect(scope1).to.have.lengthOf.least(1); // can be two if fetched-missing-deps completed.
expect(scope2).to.have.lengthOf.least(1);
});
}
describe('when the failure happened on the same workspace', () => {
let beforeExportClone;
before(() => {
// simulate the same workspace the persist failed.
helper.scopeHelper.reInitLocalScopeHarmony();
helper.scopeHelper.addRemoteScope(remote1Path);
helper.scopeHelper.addRemoteScope(remote2Path);
helper.fs.outputFile('bar1/foo1.js', `require('@${remote2Name}/bar2');`);
helper.fs.outputFile('bar2/foo2.js', `require('@${remote1Name}/bar1');`);
helper.command.addComponent('bar1');
helper.command.addComponent('bar2');
helper.bitJsonc.addToVariant('bar1', 'defaultScope', remote1Name);
helper.bitJsonc.addToVariant('bar2', 'defaultScope', remote2Name);
helper.command.linkAndRewire();
helper.command.compile();
helper.command.tagAllWithoutBuild();
beforeExportClone = helper.scopeHelper.cloneLocalScope();
});
describe('running bit export --resume <export-id>', () => {
let exportOutput: string;
before(() => {
exportOutput = helper.command.export(`--resume ${exportId}`);
});
it('should resume the export and complete it successfully', () => {
expect(exportOutput).to.have.string('exported the following 2 component(s)');
expect(exportOutput).to.have.string('ovio1b1s-remote/bar1');
expect(exportOutput).to.have.string('mjtjb8oh-remote2/bar2');
});
it('bit status should be clean', () => {
helper.command.expectStatusToBeClean();
});
expectRemotesToHaveTheComponents();
});
describe('running bit export without resume', () => {
before(() => {
helper.scopeHelper.getClonedScope(remote1Clone, remote1Path);
helper.scopeHelper.getClonedScope(remote2Clone, remote2Path);
helper.scopeHelper.getClonedLocalScope(beforeExportClone);
});
it('should throw ServerIsBusy error', () => {
const err = new ServerIsBusy(2, exportId);
const cmd = () => helper.command.export();
helper.general.expectToThrow(cmd, err);
});
});
describe('when one remote succeeded and one failed', () => {
let exportOutput;
before(() => {
helper.scopeHelper.getClonedScope(remote1Clone, remote1Path);
helper.scopeHelper.getClonedScope(remote2Clone, remote2Path);
helper.scopeHelper.getClonedLocalScope(beforeExportClone);
helper.command.resumeExport(exportId, [remote1Name]);
exportOutput = helper.command.export(`--resume ${exportId}`);
});
it('should still be able to run export --resume to persist to other scopes', () => {
expect(exportOutput).to.have.string('exported the following 1 component(s)');
expect(exportOutput).to.have.string('mjtjb8oh-remote2/bar2');
});
});
});
describe('from different workspace, by running bit resume-export <export-id> <remotes...>', () => {
before(() => {
helper.scopeHelper.reInitLocalScopeHarmony();
helper.scopeHelper.getClonedScope(remote1Clone, remote1Path);
helper.scopeHelper.getClonedScope(remote2Clone, remote2Path);
helper.scopeHelper.addRemoteScope(remote1Path);
helper.scopeHelper.addRemoteScope(remote2Path);
});
describe('running it with the correct export-id and all the remotes', () => {
let resumeExportOutput: string;
before(() => {
resumeExportOutput = helper.command.resumeExport(exportId, [remote1Name, remote2Name]);
});
it('should complete the export successfully', () => {
expect(resumeExportOutput).to.have.string('the following components were persisted successfully');
expect(resumeExportOutput).to.have.string('ovio1b1s-remote/bar1');
expect(resumeExportOutput).to.have.string('mjtjb8oh-remote2/bar2');
});
expectRemotesToHaveTheComponents();
});
describe('running it with the correct export-id and only one remote', () => {
let resumeExportOutput: string;
before(() => {
helper.scopeHelper.getClonedScope(remote1Clone, remote1Path);
helper.scopeHelper.getClonedScope(remote2Clone, remote2Path);
resumeExportOutput = helper.command.resumeExport(exportId, [remote1Name]);
});
it('should complete the export for that remote only', () => {
expect(resumeExportOutput).to.have.string('the following components were persisted successfully');
expect(resumeExportOutput).to.have.string('ovio1b1s-remote/bar1');
expect(resumeExportOutput).to.not.have.string('mjtjb8oh-remote2/bar2');
});
it('only the first remote should have the component', () => {
const scope1 = helper.command.catScope(true, remote1Path);
const scope2 = helper.command.catScope(true, remote2Path);
expect(scope1).to.have.lengthOf(1);
expect(scope2).to.have.lengthOf(0);
});
});
describe('running it with a non-exist export-id', () => {
it('should indicate that no components were persisted', () => {
const output = helper.command.resumeExport('1234', [remote1Name]);
expect(output).to.have.string('no components were left to persist for this export-id');
});
});
});
});
}); | the_stack |
import { BundlerConfigType } from '@umijs/types';
import { chalk, createDebug, mkdirp } from '@umijs/utils';
import assert from 'assert';
import { existsSync, readFileSync } from 'fs';
import mime from 'mime';
import { dirname, join, parse } from 'path';
import { IApi } from 'umi';
import webpack from 'webpack';
import BabelImportRedirectPlugin from './babel-import-redirect-plugin';
import BabelPluginAutoExport from './babel-plugin-auto-export';
import BabelPluginWarnRequire from './babel-plugin-warn-require';
import { DEFAULT_MF_NAME, MF_VA_PREFIX } from './constants';
import DepBuilder from './DepBuilder';
import DepInfo from './DepInfo';
import { getUmiRedirect } from './getUmiRedirect';
import { copy } from './utils';
const debug = createDebug('umi:mfsu');
export type TMode = 'production' | 'development';
export const checkConfig = (api: IApi) => {
const { mfsu } = api.config;
// .mfsu directory do not match babel-loader
if (mfsu && mfsu.development && mfsu.development.output) {
assert(
/\.mfsu/.test(mfsu.development.output),
`[MFSU] mfsu.development.output must match /\.mfsu/.`,
);
}
if (mfsu && mfsu.production && mfsu.production.output) {
assert(
/\.mfsu/.test(mfsu.production.output),
`[MFSU] mfsu.production.output must match /\.mfsu/.`,
);
}
};
export const getMfsuPath = (api: IApi, { mode }: { mode: TMode }) => {
if (mode === 'development') {
const configPath = api.userConfig.mfsu?.development?.output;
return configPath
? join(api.cwd, configPath)
: join(api.paths.absTmpPath!, '.cache', '.mfsu');
} else {
const configPath = api.userConfig.mfsu?.production?.output;
return configPath
? join(api.cwd, configPath)
: join(api.cwd, './.mfsu-production');
}
};
export const isMonacoWorker = (
api: IApi,
reqPath: string,
fileRelativePath: string,
) =>
/[a-zA-Z0-9]+\.worker\.js$/.test(reqPath) &&
existsSync(
join(
getMfsuPath(api, {
mode: 'development',
}),
fileRelativePath,
),
);
export const normalizeReqPath = (api: IApi, reqPath: string) => {
let normalPublicPath = api.config.publicPath as string;
if (/^https?\:\/\//.test(normalPublicPath)) {
normalPublicPath = new URL(normalPublicPath).pathname;
} else {
normalPublicPath = normalPublicPath.replace(/^(?:\.+\/?)+/, '/'); // normalPublicPath should start with '/'
}
const fileRelativePath = reqPath
.replace(new RegExp(`^${normalPublicPath}`), '/')
.slice(1);
const isMfAssets =
reqPath.startsWith(`${normalPublicPath}mf-va_`) ||
reqPath.startsWith(`${normalPublicPath}mf-dep_`) ||
reqPath.startsWith(`${normalPublicPath}mf-static/`) ||
isMonacoWorker(api, reqPath, fileRelativePath);
return {
isMfAssets,
normalPublicPath,
fileRelativePath,
};
};
export default function (api: IApi) {
const webpackAlias = {};
const webpackExternals: any[] = [];
let publicPath = '/';
let depInfo: DepInfo;
let depBuilder: DepBuilder;
let mode: TMode = 'development';
api.onPluginReady({
fn() {
const command = process.argv[2];
if (['dev', 'build'].includes(command)) {
console.log(chalk.hex('#faac00')('⏱️ MFSU Enabled'));
}
},
stage: 2,
});
api.onStart(async ({ name, args }) => {
checkConfig(api);
if (name === 'build') {
mode = 'production';
// @ts-ignore
} else if (name === 'mfsu' && args._[1] === 'build' && args.mode) {
// umi mfsu build --mode
// @ts-ignore
mode = args.mode || 'development';
}
assert(
['development', 'production'].includes(mode),
`[MFSU] Unsupported mode ${mode}, expect development or production.`,
);
debug(`mode: ${mode}`);
const tmpDir = getMfsuPath(api, { mode });
debug(`tmpDir: ${tmpDir}`);
if (!existsSync(tmpDir)) {
mkdirp.sync(tmpDir);
}
depInfo = new DepInfo({
tmpDir,
mode,
api,
cwd: api.cwd,
webpackAlias,
});
debug('load cache');
depInfo.loadCache();
depBuilder = new DepBuilder({
tmpDir,
mode,
api,
});
});
api.modifyConfig({
fn(memo) {
return {
...memo,
// Always enable dynamicImport when mfsu is enabled
dynamicImport: memo.dynamicImport || {},
// Lock chunks when mfsu is enabled
// @ts-ignore
chunks: memo.mfsu?.chunks || ['umi'],
};
},
stage: Infinity,
});
api.onBuildComplete(async ({ err }) => {
if (err) return;
debug(`build deps in production`);
await buildDeps();
});
api.onDevCompileDone(async () => {
debug(`build deps in development`);
await buildDeps();
});
api.describe({
key: 'mfsu',
config: {
schema(joi) {
return joi
.object({
development: joi.object({
output: joi.string(),
}),
production: joi.object({
output: joi.string(),
}),
mfName: joi.string(),
exportAllMembers: joi.object(),
chunks: joi.array().items(joi.string()),
ignoreNodeBuiltInModules: joi.boolean(),
})
.description('open mfsu feature');
},
},
enableBy() {
return (
(api.env === 'development' && api.userConfig.mfsu) ||
(api.env === 'production' && api.userConfig.mfsu?.production) ||
process.env.ENABLE_MFSU
);
},
});
api.modifyBabelPresetOpts({
fn: (opts, args) => {
return {
...opts,
...(args.mfsu
? {}
: {
importToAwaitRequire: {
remoteName:
(api.config.mfsu && api.config.mfsu.mfName) ||
DEFAULT_MF_NAME,
matchAll: true,
webpackAlias,
webpackExternals,
alias: {
[api.cwd]: '$CWD$',
},
// @ts-ignore
exportAllMembers: api.config.mfsu?.exportAllMembers,
onTransformDeps(opts: {
file: string;
source: string;
isMatch: boolean;
isExportAllDeclaration?: boolean;
}) {
const file = opts.file.replace(
api.paths.absSrcPath! + '/',
'@/',
);
if (process.env.MFSU_DEBUG && !opts.source.startsWith('.')) {
if (process.env.MFSU_DEBUG === 'MATCHED' && !opts.isMatch)
return;
if (process.env.MFSU_DEBUG === 'UNMATCHED' && opts.isMatch)
return;
console.log(
`> import ${chalk[opts.isMatch ? 'green' : 'red'](
opts.source,
)} from ${file}, ${
opts.isMatch ? 'MATCHED' : 'UNMATCHED'
}`,
);
}
// collect dependencies
if (opts.isMatch) {
depInfo.addTmpDep(opts.source, file);
}
},
},
}),
};
},
stage: Infinity,
});
api.modifyBabelOpts({
fn: async (opts) => {
webpackAlias['core-js'] = dirname(
require.resolve('core-js/package.json'),
);
webpackAlias['regenerator-runtime/runtime'] = require.resolve(
'regenerator-runtime/runtime',
);
// @ts-ignore
const umiRedirect = await getUmiRedirect(process.env.UMI_DIR);
// 降低 babel-preset-umi 的优先级,保证 core-js 可以被插件及时编译
opts.presets?.forEach((preset) => {
if (preset instanceof Array && /babel-preset-umi/.test(preset[0])) {
preset[1].env.useBuiltIns = false;
}
});
opts.plugins = [
BabelPluginWarnRequire,
BabelPluginAutoExport,
[
BabelImportRedirectPlugin,
{
umi: umiRedirect,
dumi: umiRedirect,
'@alipay/bigfish': umiRedirect,
},
],
...opts.plugins,
];
return opts;
},
stage: Infinity,
});
api.addBeforeMiddlewares(() => {
return (req, res, next) => {
const path = req.path;
const { isMfAssets, fileRelativePath } = normalizeReqPath(api, req.path);
if (isMfAssets) {
depBuilder.onBuildComplete(() => {
const mfsuPath = getMfsuPath(api, { mode: 'development' });
const content = readFileSync(join(mfsuPath, fileRelativePath));
res.setHeader(
'content-type',
`${mime.lookup(parse(path || '').ext)}; charset=UTF-8`,
);
// 排除入口文件,因为 hash 是入口文件控制的
if (!/remoteEntry.js/.test(req.url)) {
res.setHeader('cache-control', 'max-age=31536000,immutable');
}
res.send(content);
});
} else {
next();
}
};
});
// 修改 webpack 配置
api.register({
key: 'modifyBundleConfig',
fn(memo: any, { type, mfsu }: { mfsu: boolean; type: BundlerConfigType }) {
if (type === BundlerConfigType.csr) {
Object.assign(webpackAlias, memo.resolve!.alias || {});
const externals = memo.externals || {};
webpackExternals.push(
...(Array.isArray(externals) ? externals : [externals]),
);
publicPath = memo.output.publicPath;
if (!mfsu) {
const mfName =
(api.config.mfsu && api.config.mfsu.mfName) || DEFAULT_MF_NAME;
memo.plugins.push(
new webpack.container.ModuleFederationPlugin({
name: 'umi-app',
remotes: {
[mfName]: `${mfName}@${MF_VA_PREFIX}remoteEntry.js`,
},
}),
);
// 避免 MonacoEditorWebpackPlugin 在项目编译阶段重复编译 worker
const hasMonacoPlugin = memo.plugins.some((plugin: object) => {
return plugin.constructor.name === 'MonacoEditorWebpackPlugin';
});
if (hasMonacoPlugin) {
memo.plugins.push(
new (class MonacoEditorWebpackPluginHack {
apply(compiler: webpack.Compiler) {
const taps: { type: string; fn: Function; name: string }[] =
compiler.hooks.make['taps'];
compiler.hooks.make['taps'] = taps.filter((tap) => {
// ref: https://github.com/microsoft/monaco-editor-webpack-plugin/blob/3e40369/src/plugins/AddWorkerEntryPointPlugin.ts#L34
return !(tap.name === 'AddWorkerEntryPointPlugin');
});
}
})(),
);
}
}
}
return memo;
},
stage: Infinity,
});
async function buildDeps(opts: { force?: boolean } = {}) {
const { shouldBuild } = depInfo.loadTmpDeps();
debug(`shouldBuild: ${shouldBuild}, force: ${opts.force}`);
if (opts.force || shouldBuild) {
await depBuilder.build({
deps: depInfo.data.deps,
webpackAlias,
onBuildComplete(err: any, stats: any) {
debug(`build complete with err ${err}`);
if (err || stats.hasErrors()) {
return;
}
debug('write cache');
depInfo.writeCache();
if (mode === 'development') {
const server = api.getServer();
debug(`refresh server`);
server.sockWrite({ type: 'ok', data: { reload: true } });
}
},
});
}
if (mode === 'production') {
// production 模式,build 完后将产物移动到 dist 中
debug(`copy mf output files to dist`);
copy(
depBuilder.tmpDir,
join(api.cwd, api.userConfig.outputPath || './dist'),
);
}
}
// npx umi mfsu build
// npx umi mfsu build --mode production
// npx umi mfsu build --mode development --force
api.registerCommand({
name: 'mfsu',
async fn({ args }) {
switch (args._[0]) {
case 'build':
console.log('[MFSU] build deps...');
await buildDeps({
force: args.force as boolean,
});
break;
default:
throw new Error(
`[MFSU] Unsupported subcommand ${args._[0]} for mfsu.`,
);
}
},
});
} | the_stack |
import { mkdirSync, readFileSync, writeFileSync } from 'fs';
import path from 'path';
import * as astTypes from 'ast-types';
import * as babel from '@babel/core';
import traverse from '@babel/traverse';
import * as _ from 'lodash';
import kebabCase from 'lodash/kebabCase';
import * as prettier from 'prettier';
import remark from 'remark';
import remarkVisit from 'unist-util-visit';
import { defaultHandlers, parse as docgenParse, ReactDocgenApi } from 'react-docgen';
import muiDefaultPropsHandler from 'docs/src/modules/utils/defaultPropsHandler';
import { LANGUAGES } from 'docs/src/modules/constants';
import parseTest from 'docs/src/modules/utils/parseTest';
import generatePropTypeDescription, {
getChained,
} from 'docs/src/modules/utils/generatePropTypeDescription';
import { renderInline as renderMarkdownInline } from '@mui/markdown';
import createDescribeableProp, {
DescribeablePropDescriptor,
} from 'docs/src/modules/utils/createDescribeableProp';
import generatePropDescription from 'docs/src/modules/utils/generatePropDescription';
import parseStyles, { Styles } from 'docs/src/modules/utils/parseStyles';
import generateUtilityClass from '@mui/base/generateUtilityClass';
import * as ttp from 'typescript-to-proptypes';
import { getUnstyledFilename } from '../helpers';
import { ComponentInfo } from '../buildApiUtils';
const DEFAULT_PRETTIER_CONFIG_PATH = path.join(process.cwd(), 'prettier.config.js');
export interface ReactApi extends ReactDocgenApi {
demos: ReturnType<ComponentInfo['getDemos']>;
EOL: string;
filename: string;
apiPathname: string;
forwardsRefTo: string | undefined;
inheritance: ReturnType<ComponentInfo['getInheritance']>;
/**
* react component name
* @example 'Accordion'
*/
name: string;
muiName: string;
description: string;
spread: boolean | undefined;
/**
* result of path.readFileSync from the `filename` in utf-8
*/
src: string;
styles: Styles;
propsTable: _.Dictionary<{
default: string | undefined;
required: boolean | undefined;
type: { name: string | undefined; description: string | undefined };
deprecated: true | undefined;
deprecationInfo: string | undefined;
}>;
translations: {
componentDescription: string;
propDescriptions: { [key: string]: string | undefined };
classDescriptions: { [key: string]: { description: string; conditions?: string } };
};
}
const cssComponents = ['Box', 'Grid', 'Typography', 'Stack'];
export function writePrettifiedFile(
filename: string,
data: string,
prettierConfigPath: string = DEFAULT_PRETTIER_CONFIG_PATH,
options: object = {},
) {
const prettierConfig = prettier.resolveConfig.sync(filename, {
config: prettierConfigPath,
});
if (prettierConfig === null) {
throw new Error(
`Could not resolve config for '${filename}' using prettier config path '${prettierConfigPath}'.`,
);
}
writeFileSync(filename, prettier.format(data, { ...prettierConfig, filepath: filename }), {
encoding: 'utf8',
...options,
});
}
/**
* Produces markdown of the description that can be hosted anywhere.
*
* By default we assume that the markdown is hosted on mui.com which is
* why the source includes relative url. We transform them to absolute urls with
* this method.
*/
async function computeApiDescription(api: ReactApi, options: { host: string }): Promise<string> {
const { host } = options;
const file = await remark()
.use(function docsLinksAttacher() {
return function transformer(tree) {
remarkVisit(tree, 'link', (linkNode) => {
if ((linkNode.url as string).startsWith('/')) {
linkNode.url = `${host}${linkNode.url}`;
}
});
};
})
.process(api.description);
return file.contents.toString('utf-8').trim();
}
/**
* Add demos & API comment block to type definitions, e.g.:
* /**
* * Demos:
* *
* * - [Icons](https://mui.com/components/icons/)
* * - [Material Icons](https://mui.com/components/material-icons/)
* *
* * API:
* *
* * - [Icon API](https://mui.com/api/icon/)
*/
async function annotateComponentDefinition(api: ReactApi) {
const HOST = 'https://mui.com';
const typesFilename = api.filename.replace(/\.js$/, '.d.ts');
const typesSource = readFileSync(typesFilename, { encoding: 'utf8' });
const typesAST = await babel.parseAsync(typesSource, {
configFile: false,
filename: typesFilename,
presets: [require.resolve('@babel/preset-typescript')],
});
if (typesAST === null) {
throw new Error('No AST returned from babel.');
}
let start = 0;
let end = null;
traverse(typesAST, {
ExportDefaultDeclaration(babelPath) {
/**
* export default function Menu() {}
*/
let node: babel.Node = babelPath.node;
if (node.declaration.type === 'Identifier') {
// declare const Menu: {};
// export default Menu;
if (babel.types.isIdentifier(babelPath.node.declaration)) {
const bindingId = babelPath.node.declaration.name;
const binding = babelPath.scope.bindings[bindingId];
// The JSDoc MUST be located at the declaration
if (babel.types.isFunctionDeclaration(binding.path.node)) {
// For function declarations the binding is equal to the declaration
// /**
// */
// function Component() {}
node = binding.path.node;
} else {
// For variable declarations the binding points to the declarator.
// /**
// */
// const Component = () => {}
node = binding.path.parentPath.node;
}
}
}
const { leadingComments } = node;
const leadingCommentBlocks =
leadingComments != null
? leadingComments.filter(({ type }) => type === 'CommentBlock')
: null;
const jsdocBlock = leadingCommentBlocks != null ? leadingCommentBlocks[0] : null;
if (leadingCommentBlocks != null && leadingCommentBlocks.length > 1) {
throw new Error(
`Should only have a single leading jsdoc block but got ${
leadingCommentBlocks.length
}:\n${leadingCommentBlocks
.map(({ type, value }, index) => `#${index} (${type}): ${value}`)
.join('\n')}`,
);
}
if (jsdocBlock != null) {
start = jsdocBlock.start;
end = jsdocBlock.end;
} else if (node.start !== null) {
start = node.start - 1;
end = start;
}
},
});
if (end === null || start === 0) {
throw new TypeError(
"Don't know where to insert the jsdoc block. Probably no `default export` found",
);
}
let inheritanceAPILink = null;
if (api.inheritance !== null) {
inheritanceAPILink = `[${api.inheritance.name} API](${
api.inheritance.apiPathname.startsWith('http')
? api.inheritance.apiPathname
: `${HOST}${api.inheritance.apiPathname}`
})`;
}
const markdownLines = (await computeApiDescription(api, { host: HOST })).split('\n');
// Ensure a newline between manual and generated description.
if (markdownLines[markdownLines.length - 1] !== '') {
markdownLines.push('');
}
markdownLines.push(
'Demos:',
'',
...api.demos.map((item) => {
return `- [${item.name}](${
item.demoPathname.startsWith('http') ? item.demoPathname : `${HOST}${item.demoPathname}`
})`;
}),
'',
);
markdownLines.push(
'API:',
'',
`- [${api.name} API](${
api.apiPathname.startsWith('http') ? api.apiPathname : `${HOST}${api.apiPathname}`
})`,
);
if (api.inheritance !== null) {
markdownLines.push(`- inherits ${inheritanceAPILink}`);
}
const jsdoc = `/**\n${markdownLines
.map((line) => (line.length > 0 ? ` * ${line}` : ` *`))
.join('\n')}\n */`;
const typesSourceNew = typesSource.slice(0, start) + jsdoc + typesSource.slice(end);
writeFileSync(typesFilename, typesSourceNew, { encoding: 'utf8' });
}
/**
* Substitute CSS class description conditions with placeholder
*/
function extractClassConditions(descriptions: any) {
const classConditions: {
[key: string]: { description: string; conditions?: string; nodeName?: string };
} = {};
const stylesRegex =
/((Styles|State class|Class name) applied to )(.*?)(( if | unless | when |, ){1}(.*))?\./;
Object.entries(descriptions).forEach(([className, description]: any) => {
if (className) {
const conditions = description.match(stylesRegex);
if (conditions && conditions[6]) {
classConditions[className] = {
description: description.replace(stylesRegex, '$1{{nodeName}}$5{{conditions}}.'),
nodeName: conditions[3],
conditions: conditions[6].replace(/`(.*?)`/g, '<code>$1</code>'),
};
} else if (conditions && conditions[3] && conditions[3] !== 'the root element') {
classConditions[className] = {
description: description.replace(stylesRegex, '$1{{nodeName}}$5.'),
nodeName: conditions[3],
};
} else {
classConditions[className] = { description };
}
}
});
return classConditions;
}
/**
* @param filepath - absolute path
* @example toGitHubPath('/home/user/material-ui/packages/Accordion') === '/packages/Accordion'
* @example toGitHubPath('C:\\Development\material-ui\packages\Accordion') === '/packages/Accordion'
*/
function toGitHubPath(filepath: string): string {
return `/${path.relative(process.cwd(), filepath).replace(/\\/g, '/')}`;
}
const generateApiTranslations = (outputDirectory: string, reactApi: ReactApi) => {
const componentName = reactApi.name;
const apiDocsTranslationPath = path.resolve(outputDirectory, kebabCase(componentName));
function resolveApiDocsTranslationsComponentLanguagePath(language: typeof LANGUAGES[0]): string {
const languageSuffix = language === 'en' ? '' : `-${language}`;
return path.join(apiDocsTranslationPath, `${kebabCase(componentName)}${languageSuffix}.json`);
}
mkdirSync(apiDocsTranslationPath, {
mode: 0o777,
recursive: true,
});
writePrettifiedFile(
resolveApiDocsTranslationsComponentLanguagePath('en'),
JSON.stringify(reactApi.translations),
);
LANGUAGES.forEach((language) => {
if (language !== 'en') {
try {
writePrettifiedFile(
resolveApiDocsTranslationsComponentLanguagePath(language),
JSON.stringify(reactApi.translations),
undefined,
{ flag: 'wx' },
);
} catch (error) {
// File exists
}
}
});
};
const generateApiPage = (outputDirectory: string, reactApi: ReactApi) => {
/**
* Gather the metadata needed for the component's API page.
*/
const pageContent = {
// Sorted by required DESC, name ASC
props: _.fromPairs(
Object.entries(reactApi.propsTable).sort(([aName, aData], [bName, bData]) => {
if ((aData.required && bData.required) || (!aData.required && !bData.required)) {
return aName.localeCompare(bName);
}
if (aData.required) {
return -1;
}
return 1;
}),
),
name: reactApi.name,
styles: {
classes: reactApi.styles.classes,
globalClasses: _.fromPairs(
Object.entries(reactApi.styles.globalClasses).filter(([className, globalClassName]) => {
// Only keep "non-standard" global classnames
return globalClassName !== `Mui${reactApi.name}-${className}`;
}),
),
name: reactApi.styles.name,
},
spread: reactApi.spread,
forwardsRefTo: reactApi.forwardsRefTo,
filename: toGitHubPath(reactApi.filename),
inheritance: reactApi.inheritance
? {
component: reactApi.inheritance.name,
pathname: reactApi.inheritance.apiPathname,
}
: null,
demos: `<ul>${reactApi.demos
.map((item) => `<li><a href="${item.demoPathname}">${item.name}</a></li>`)
.join('\n')}</ul>`,
cssComponent: cssComponents.indexOf(reactApi.name) >= 0,
};
writePrettifiedFile(
path.resolve(outputDirectory, `${kebabCase(reactApi.name)}.json`),
JSON.stringify(pageContent),
);
writePrettifiedFile(
path.resolve(outputDirectory, `${kebabCase(reactApi.name)}.js`),
`import * as React from 'react';
import ApiPage from 'docs/src/modules/components/ApiPage';
import mapApiPageTranslations from 'docs/src/modules/utils/mapApiPageTranslations';
import jsonPageContent from './${kebabCase(reactApi.name)}.json';
export default function Page(props) {
const { descriptions, pageContent } = props;
return <ApiPage descriptions={descriptions} pageContent={pageContent} />;
}
Page.getInitialProps = () => {
const req = require.context(
'docs/translations/api-docs/${kebabCase(reactApi.name)}',
false,
/${kebabCase(reactApi.name)}.*.json$/,
);
const descriptions = mapApiPageTranslations(req);
return {
descriptions,
pageContent: jsonPageContent,
};
};
`.replace(/\r?\n/g, reactApi.EOL),
);
};
const attachTranslations = (reactApi: ReactApi) => {
const translations: ReactApi['translations'] = {
componentDescription: reactApi.description,
propDescriptions: {},
classDescriptions: {},
};
Object.entries(reactApi.props!).forEach(([propName, propDescriptor]) => {
let prop: DescribeablePropDescriptor | null;
try {
prop = createDescribeableProp(propDescriptor, propName);
} catch (error) {
prop = null;
}
if (prop) {
let description = generatePropDescription(prop, propName);
description = renderMarkdownInline(description);
if (propName === 'classes') {
description += ' See <a href="#css">CSS API</a> below for more details.';
} else if (propName === 'sx') {
description += ' See the <a href="/system/the-sx-prop/">`sx` page</a> for more details.';
}
translations.propDescriptions[propName] = description.replace(/\n@default.*$/, '');
}
});
/**
* CSS class descriptiohs.
*/
translations.classDescriptions = extractClassConditions(reactApi.styles.descriptions);
reactApi.translations = translations;
};
const attachPropsTable = (reactApi: ReactApi) => {
const propErrors: Array<[propName: string, error: Error]> = [];
const componentProps: ReactApi['propsTable'] = _.fromPairs(
Object.entries(reactApi.props!).map(([propName, propDescriptor]) => {
let prop: DescribeablePropDescriptor | null;
try {
prop = createDescribeableProp(propDescriptor, propName);
} catch (error) {
propErrors.push([propName, error as Error]);
prop = null;
}
if (prop === null) {
// have to delete `componentProps.undefined` later
return [] as any;
}
// Only keep `default` for bool props if it isn't 'false'.
let defaultValue: string | undefined;
if (
propDescriptor.type.name !== 'bool' ||
propDescriptor.jsdocDefaultValue?.value !== 'false'
) {
defaultValue = propDescriptor.jsdocDefaultValue?.value;
}
const propTypeDescription = generatePropTypeDescription(propDescriptor.type);
const chainedPropType = getChained(prop.type);
const requiredProp =
prop.required ||
/\.isRequired/.test(prop.type.raw) ||
(chainedPropType !== false && chainedPropType.required);
const deprecation = (propDescriptor.description || '').match(/@deprecated(\s+(?<info>.*))?/);
return [
propName,
{
type: {
name: propDescriptor.type.name,
description:
propTypeDescription !== propDescriptor.type.name ? propTypeDescription : undefined,
},
default: defaultValue,
// undefined values are not serialized => saving some bytes
required: requiredProp || undefined,
deprecated: !!deprecation || undefined,
deprecationInfo:
renderMarkdownInline(deprecation?.groups?.info || '').trim() || undefined,
},
];
}),
);
if (propErrors.length > 0) {
throw new Error(
`There were errors creating prop descriptions:\n${propErrors
.map(([propName, error]) => {
return ` - ${propName}: ${error}`;
})
.join('\n')}`,
);
}
// created by returning the `[]` entry
delete componentProps.undefined;
reactApi.propsTable = componentProps;
};
const systemComponents = ['Container', 'Box'];
/**
* - Build react component (specified filename) api by lookup at its definition (.d.ts or ts)
* and then generate the API page + json data
* - Generate the translations
* - Add the comment in the component filename with its demo & API urls (including the inherited component).
* this process is done by sourcing markdown files and filter matched `components` in the frontmatter
*/
const generateComponentApi = async (componentInfo: ComponentInfo, program: ttp.ts.Program) => {
const {
filename,
name,
muiName,
apiPathname,
apiPagesDirectory,
getInheritance,
getDemos,
readFile,
skipApiGeneration,
} = componentInfo;
const { shouldSkip, spread, EOL, src } = readFile();
if (shouldSkip) {
return null;
}
let reactApi: ReactApi;
if (systemComponents.includes(name)) {
reactApi = docgenParse(
src,
(ast) => {
let node;
astTypes.visit(ast, {
visitVariableDeclaration: (variablePath) => {
const definitions: any[] = [];
if (variablePath.node.declarations) {
variablePath
.get('declarations')
.each((declarator: any) => definitions.push(declarator.get('init')));
}
definitions.forEach((definition) => {
const definitionName = definition.value.callee.name;
if (definitionName === `create${name}`) {
node = definition;
}
});
return false;
},
});
return node;
},
defaultHandlers,
{ filename },
);
} else {
reactApi = docgenParse(src, null, defaultHandlers.concat(muiDefaultPropsHandler), { filename });
}
// === Handle unstyled component ===
const unstyledFileName = getUnstyledFilename(filename);
let unstyledSrc;
// Try to get data for the unstyled component
try {
unstyledSrc = readFileSync(unstyledFileName, 'utf8');
} catch (err) {
// Unstyled component does not exist
}
if (unstyledSrc) {
const unstyledReactAPI = docgenParse(
unstyledSrc,
null,
defaultHandlers.concat(muiDefaultPropsHandler),
{
filename: unstyledFileName,
},
);
Object.keys(unstyledReactAPI.props).forEach((prop) => {
if (
unstyledReactAPI.props[prop].defaultValue &&
reactApi.props &&
(!reactApi.props[prop] || !reactApi.props[prop].defaultValue)
) {
if (reactApi.props[prop]) {
reactApi.props[prop].defaultValue = unstyledReactAPI.props[prop].defaultValue;
reactApi.props[prop].jsdocDefaultValue = unstyledReactAPI.props[prop].jsdocDefaultValue;
} else {
reactApi.props[prop] = unstyledReactAPI.props[prop];
}
}
});
} // ================================
// Ignore what we might have generated in `annotateComponentDefinition`
const annotatedDescriptionMatch = reactApi.description.match(/(Demos|API):\r?\n\r?\n/);
if (annotatedDescriptionMatch !== null) {
reactApi.description = reactApi.description.slice(0, annotatedDescriptionMatch.index).trim();
}
reactApi.filename = filename;
reactApi.name = name;
reactApi.muiName = muiName;
reactApi.apiPathname = apiPathname;
reactApi.EOL = EOL;
reactApi.demos = getDemos();
if (reactApi.demos.length === 0) {
throw new Error(
'Unable to find demos. \n' +
`Be sure to include \`components: ${reactApi.name}\` in the markdown pages where the \`${reactApi.name}\` component is relevant. ` +
'Every public component should have a demo. ',
);
}
const testInfo = await parseTest(filename);
// no Object.assign to visually check for collisions
reactApi.forwardsRefTo = testInfo.forwardsRefTo;
reactApi.spread = testInfo.spread ?? spread;
reactApi.inheritance = getInheritance(testInfo.inheritComponent);
reactApi.styles = await parseStyles(reactApi, program);
if (reactApi.styles.classes.length > 0 && !reactApi.name.endsWith('Unstyled')) {
reactApi.styles.name = reactApi.muiName;
}
reactApi.styles.classes.forEach((key) => {
const globalClass = generateUtilityClass(reactApi.styles.name || reactApi.muiName, key);
reactApi.styles.globalClasses[key] = globalClass;
});
attachPropsTable(reactApi);
attachTranslations(reactApi);
// eslint-disable-next-line no-console
console.log('Built API docs for', reactApi.name);
if (!skipApiGeneration) {
// Generate pages, json and translations
generateApiTranslations(path.join(process.cwd(), 'docs/translations/api-docs'), reactApi);
generateApiPage(apiPagesDirectory, reactApi);
// Add comment about demo & api links (including inherited component) to the component file
await annotateComponentDefinition(reactApi);
}
return reactApi;
};
export default generateComponentApi; | the_stack |
import * as React from 'react';
import * as monacoEditor from 'monaco-editor';
import { FlexColDiv } from './FlexDivs';
export interface ITextRange {
/**
* Beginning position as a character index of the text in the editor
*/
pos: number;
/**
* End position as a character index of the text in the editor
*/
end: number;
}
/**
* Describes a marker. Markers refer to annotations (i.e. - squiggly lines) in code.
*/
export interface ISyntaxMarker extends ITextRange {
message: string;
}
/**
* Describes a styled range. This allows CSS styling to be applied to ranges of code.
*/
export interface IStyledRange extends ITextRange {
className: string;
}
export interface ICodeEditorProps {
className?: string;
style?: React.CSSProperties;
value?: string;
readOnly?: boolean;
language?: string;
onChange?: (value: string) => void;
disableLineNumbers?: boolean;
theme?: string;
markers?: ISyntaxMarker[];
syntaxStyles?: IStyledRange[];
wordWrap?: boolean;
}
export interface ICodeEditorState {
monaco?: typeof monacoEditor;
monacoErrorMessage?: string;
}
interface IMonacoWindow extends Window {
require: {
(paths: string[], callback: (monaco: typeof monacoEditor) => void): void;
config: (options: { paths: { [name: string]: string } }) => void;
};
MonacoEnvironment: {
getWorkerUrl: (workerId: string, label: string) => void;
};
}
declare const MONACO_URL: string;
const MONACO_BASE_URL: string = MONACO_URL;
export class CodeEditor extends React.Component<ICodeEditorProps, ICodeEditorState> {
private static _initializePromise: Promise<typeof monacoEditor>;
private static _editorIdCounter: number = 0;
private static _monaco: typeof monacoEditor;
private _existingSyntaxStyles: { [hash: string]: string } = {};
private _editorId: string;
private _isMounted: boolean = false;
private _editor: monacoEditor.editor.IStandaloneCodeEditor | undefined;
private _placeholderDivRef: HTMLDivElement | undefined;
private _hostDivRef: HTMLDivElement | undefined;
public constructor(props: ICodeEditorProps) {
super(props);
this._editorId = `tsdoc-monaco-${CodeEditor._editorIdCounter++}`;
this.state = {};
this._onWindowResize = this._onWindowResize.bind(this);
this._onRefHost = this._onRefHost.bind(this);
this._onRefPlaceholder = this._onRefPlaceholder.bind(this);
}
private get _value(): string | undefined {
if (this._editor) {
return this._editor.getValue();
} else {
return undefined;
}
}
private _getEditorModel(): monacoEditor.editor.ITextModel {
if (this._editor) {
const model: monacoEditor.editor.ITextModel | null = this._editor.getModel();
if (model) {
return model;
}
}
throw new Error('Invalid access to MonacoEditor.getModel()');
}
private static _initializeMonaco(): Promise<typeof monacoEditor> {
if (!CodeEditor._initializePromise) {
CodeEditor._initializePromise = new Promise(
(resolve: (monaco: typeof monacoEditor) => void, reject: (error: Error) => void) => {
const monacoWindow: IMonacoWindow = (window as unknown) as IMonacoWindow;
monacoWindow.require.config({ paths: { vs: `${MONACO_BASE_URL}vs/` } });
monacoWindow.MonacoEnvironment = {
getWorkerUrl: (workerId, label) => {
return `data:text/javascript;charset=utf-8,${encodeURIComponent(
'self.MonacoEnvironment = {' +
`baseUrl: '${MONACO_BASE_URL}'` +
'};' +
`importScripts('${MONACO_BASE_URL}vs/base/worker/workerMain.js');`
)}`;
}
};
monacoWindow.require(['vs/editor/editor.main'], (monaco) => {
if (monaco) {
resolve(monaco);
} else {
reject(new Error('Unable to load Monaco editor'));
}
});
}
).then((monaco) => {
CodeEditor._monaco = monaco;
return monaco;
});
}
return CodeEditor._initializePromise;
}
public componentDidMount(): void {
this._isMounted = true;
CodeEditor._initializeMonaco()
.then((monaco) => {
this.setState({ monaco });
if (this._isMounted) {
window.addEventListener('resize', this._onWindowResize);
}
})
.catch((error) => {
this.setState({ monacoErrorMessage: `Error loading Monaco editor: ${error}` });
});
}
public componentWillUnmount(): void {
this._isMounted = false;
this._editor = undefined;
this._placeholderDivRef = undefined;
this._hostDivRef = undefined;
window.removeEventListener('resize', this._onWindowResize);
}
public componentDidUpdate(prevProps: ICodeEditorProps): void {
if (this._editor) {
if (this._value !== this.props.value) {
this._editor.setValue(this.props.value || '');
}
if (CodeEditor._monaco) {
CodeEditor._monaco.editor.setModelMarkers(
this._getEditorModel(),
this._editorId,
(this.props.markers || []).map((marker) => {
const startPos: monacoEditor.Position = this._getEditorModel().getPositionAt(marker.pos);
const endPos: monacoEditor.Position = this._getEditorModel().getPositionAt(marker.end);
return {
startLineNumber: startPos.lineNumber,
startColumn: startPos.column,
endLineNumber: endPos.lineNumber,
endColumn: endPos.column,
severity: CodeEditor._monaco.MarkerSeverity.Error,
message: marker.message
};
})
);
if (this.props.theme !== prevProps.theme) {
CodeEditor._monaco.editor.setTheme(this.props.theme || 'vs');
}
}
if (this.props.disableLineNumbers !== prevProps.disableLineNumbers) {
this._editor.updateOptions({
lineNumbers: this.props.disableLineNumbers ? 'off' : 'on'
});
}
this._applySyntaxStyling(this.props.syntaxStyles || []);
}
}
public render(): React.ReactNode {
if (this.state.monacoErrorMessage) {
return (
<FlexColDiv className={this.props.className} style={this.props.style}>
{this.state.monacoErrorMessage}
</FlexColDiv>
);
} else {
// The Monaco application is very complex and its div does not resize reliably.
// To work around this, we render a blank placeholder div (that is well-behaved),
// and then the Monaco host div floats above that using absolute positioning
// and manual resizing.
return (
<div
className="playground-monaco-placeholder"
ref={this._onRefPlaceholder}
style={{ display: 'flex', flexDirection: 'column', flex: 1, ...this.props.style }}
>
<div
className="playground-monaco-host"
ref={this._onRefHost}
style={{ display: 'block', position: 'absolute' }}
/>
</div>
);
}
}
private _onRefPlaceholder(element: HTMLDivElement): void {
this._placeholderDivRef = element;
}
private _onRefHost(element: HTMLDivElement): void {
this._hostDivRef = element;
this._createEditor();
}
private _applySyntaxStyling(newSyntaxStyles: IStyledRange[]): void {
if (this._editor) {
// Find decorations to remove
const newExistingSyntaxStyles: { [hash: string]: string } = {};
const decorationsToAdd: IStyledRange[] = [];
const hashesOfDecorationsToAdd: string[] = [];
const decorationsToRemove: string[] = [];
for (const syntaxStyle of newSyntaxStyles) {
const hash: string = JSON.stringify(syntaxStyle);
if (this._existingSyntaxStyles[hash] !== undefined) {
newExistingSyntaxStyles[hash] = this._existingSyntaxStyles[hash];
delete this._existingSyntaxStyles[hash];
} else {
newExistingSyntaxStyles[hash] = ''; // Put an empty identifier here so we don't add duplicates
hashesOfDecorationsToAdd.push(hash);
decorationsToAdd.push(syntaxStyle);
}
}
for (const hash in this._existingSyntaxStyles) {
if (this._existingSyntaxStyles.hasOwnProperty(hash)) {
const decorationId: string = this._existingSyntaxStyles[hash];
decorationsToRemove.push(decorationId);
}
}
this._getEditorModel().deltaDecorations(decorationsToRemove, []);
const decorationIds: string[] = this._getEditorModel().deltaDecorations(
[],
decorationsToAdd.map((decoration) => {
const startPos: monacoEditor.Position = this._getEditorModel().getPositionAt(decoration.pos);
const endPos: monacoEditor.Position = this._getEditorModel().getPositionAt(decoration.end);
return {
range: new CodeEditor._monaco.Range(
startPos.lineNumber,
startPos.column,
endPos.lineNumber,
endPos.column
),
options: {
stickiness: CodeEditor._monaco.editor.TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges,
isWholeLine: false,
inlineClassName: decoration.className
}
};
})
);
for (let i: number = 0; i < decorationsToAdd.length; i++) {
newExistingSyntaxStyles[hashesOfDecorationsToAdd[i]] = decorationIds[i];
}
this._existingSyntaxStyles = newExistingSyntaxStyles;
}
}
private _safeOnChange(newValue: string): void {
if (this.props.onChange) {
try {
this.props.onChange(newValue);
} catch (e) {
console.error(`Error in onChange callback: ${e}`);
}
}
}
private _createEditor(): void {
CodeEditor._initializeMonaco()
.then((monaco) => {
if (!this._editor && this._hostDivRef) {
this._editor = monaco.editor.create(this._hostDivRef, {
value: this.props.value || '',
language: this.props.language,
readOnly: this.props.readOnly,
minimap: {
enabled: false
},
lineNumbers: this.props.disableLineNumbers ? 'off' : 'on',
theme: this.props.theme,
wordWrap: this.props.wordWrap ? 'on' : 'off'
});
this._getEditorModel().onDidChangeContent((e) => {
if (this._editor) {
this._safeOnChange(this._editor.getValue());
}
});
this._onWindowResize();
}
})
.catch((e) => {
console.error('CodeEditor._createEditor() failed: ' + e.toString());
});
}
private _onWindowResize(): void {
if (this._placeholderDivRef && this._hostDivRef) {
// Resize the host div to match whatever the browser did for the placeholder div
this._hostDivRef.style.width = this._placeholderDivRef.clientWidth + 'px';
this._hostDivRef.style.height = this._placeholderDivRef.clientHeight + 'px';
if (this._editor) {
this._editor.layout();
}
}
}
} | the_stack |
import React, {
ForwardedRef,
useCallback,
useLayoutEffect,
useMemo,
useState,
} from "react";
import {
ListRenderItem,
FlatListProps,
NativeScrollEvent,
NativeSyntheticEvent,
LayoutChangeEvent,
} from "react-native";
import {
PanGestureHandler,
State as GestureState,
FlatList,
PanGestureHandlerGestureEvent,
PanGestureHandlerStateChangeEvent,
} from "react-native-gesture-handler";
import Animated, {
and,
block,
call,
cond,
eq,
event,
greaterThan,
neq,
not,
onChange,
or,
set,
sub,
} from "react-native-reanimated";
import CellRendererComponent from "./CellRendererComponent";
import { DEFAULT_PROPS, isReanimatedV2, isWeb } from "../constants";
import PlaceholderItem from "./PlaceholderItem";
import RowItem from "./RowItem";
import ScrollOffsetListener from "./ScrollOffsetListener";
import { DraggableFlatListProps } from "../types";
import { useAutoScroll } from "../hooks/useAutoScroll";
import { useNode } from "../hooks/useNode";
import PropsProvider from "../context/propsContext";
import AnimatedValueProvider, {
useAnimatedValues,
} from "../context/animatedValueContext";
import RefProvider, { useRefs } from "../context/refContext";
import DraggableFlatListProvider from "../context/draggableFlatListContext";
type RNGHFlatListProps<T> = Animated.AnimateProps<
FlatListProps<T> & {
ref: React.Ref<FlatList<T>>;
simultaneousHandlers?: React.Ref<any> | React.Ref<any>[];
}
>;
const AnimatedFlatList = (Animated.createAnimatedComponent(
FlatList
) as unknown) as <T>(props: RNGHFlatListProps<T>) => React.ReactElement;
function DraggableFlatListInner<T>(props: DraggableFlatListProps<T>) {
const {
cellDataRef,
containerRef,
flatListRef,
isTouchActiveRef,
keyToIndexRef,
panGestureHandlerRef,
propsRef,
scrollOffsetRef,
} = useRefs<T>();
const {
activationDistance,
activeCellOffset,
activeCellSize,
activeIndexAnim,
containerSize,
disabled,
panGestureState,
resetTouchedCell,
scrollOffset,
scrollViewSize,
spacerIndexAnim,
touchAbsolute,
touchInit,
} = useAnimatedValues();
const {
dragHitSlop = DEFAULT_PROPS.dragHitSlop,
scrollEnabled = DEFAULT_PROPS.scrollEnabled,
activationDistance: activationDistanceProp = DEFAULT_PROPS.activationDistance,
} = props;
const [activeKey, setActiveKey] = useState<string | null>(null);
const keyExtractor = useCallback(
(item: T, index: number) => {
if (propsRef.current.keyExtractor)
return propsRef.current.keyExtractor(item, index);
else
throw new Error("You must provide a keyExtractor to DraggableFlatList");
},
[propsRef]
);
useLayoutEffect(() => {
props.data.forEach((d, i) => {
const key = keyExtractor(d, i);
keyToIndexRef.current.set(key, i);
});
}, [props.data, keyExtractor, keyToIndexRef]);
const drag = useCallback(
(activeKey: string) => {
if (!isTouchActiveRef.current.js) return;
const index = keyToIndexRef.current.get(activeKey);
const cellData = cellDataRef.current.get(activeKey);
if (cellData) {
activeCellOffset.setValue(
cellData.measurements.offset - scrollOffsetRef.current
);
activeCellSize.setValue(cellData.measurements.size);
}
const { onDragBegin } = propsRef.current;
if (index !== undefined) {
spacerIndexAnim.setValue(index);
activeIndexAnim.setValue(index);
setActiveKey(activeKey);
onDragBegin?.(index);
}
},
[
isTouchActiveRef,
keyToIndexRef,
cellDataRef,
propsRef,
activeCellOffset,
scrollOffsetRef,
activeCellSize,
spacerIndexAnim,
activeIndexAnim,
]
);
const autoScrollNode = useAutoScroll();
const onContainerLayout = ({
nativeEvent: { layout },
}: LayoutChangeEvent) => {
containerSize.setValue(props.horizontal ? layout.width : layout.height);
};
const onListContentSizeChange = (w: number, h: number) => {
scrollViewSize.setValue(props.horizontal ? w : h);
props.onContentSizeChange?.(w, h);
};
const onContainerTouchStart = () => {
isTouchActiveRef.current.js = true;
isTouchActiveRef.current.native.setValue(1);
return false;
};
const onContainerTouchEnd = () => {
isTouchActiveRef.current.js = false;
isTouchActiveRef.current.native.setValue(0);
};
let dynamicProps = {};
if (activationDistanceProp) {
const activeOffset = [-activationDistanceProp, activationDistanceProp];
dynamicProps = props.horizontal
? { activeOffsetX: activeOffset }
: { activeOffsetY: activeOffset };
}
const extraData = useMemo(
() => ({
activeKey,
extraData: props.extraData,
}),
[activeKey, props.extraData]
);
const renderItem: ListRenderItem<T> = useCallback(
({ item, index }) => {
const key = keyExtractor(item, index);
if (index !== keyToIndexRef.current.get(key))
keyToIndexRef.current.set(key, index);
return (
<RowItem
item={item}
itemKey={key}
renderItem={props.renderItem}
drag={drag}
extraData={props.extraData}
/>
);
},
[props.renderItem, props.extraData, drag, keyExtractor]
);
const resetHoverState = useCallback(() => {
activeIndexAnim.setValue(-1);
spacerIndexAnim.setValue(-1);
touchAbsolute.setValue(0);
disabled.setValue(0);
requestAnimationFrame(() => {
setActiveKey(null);
});
}, [activeIndexAnim, spacerIndexAnim, touchAbsolute, disabled]);
const onRelease = ([index]: readonly number[]) => {
// This shouldn't be necessary but seems to fix a bug where sometimes
// native values wouldn't update
isTouchActiveRef.current.native.setValue(0);
props.onRelease?.(index);
};
const onDragEnd = useCallback(
([from, to]: readonly number[]) => {
const { onDragEnd, data } = propsRef.current;
if (onDragEnd) {
const newData = [...data];
if (from !== to) {
newData.splice(from, 1);
newData.splice(to, 0, data[from]);
}
onDragEnd({ from, to, data: newData });
}
resetHoverState();
},
[resetHoverState, propsRef]
);
const onGestureRelease = useNode(
cond(
greaterThan(activeIndexAnim, -1),
[
set(disabled, 1),
set(isTouchActiveRef.current.native, 0),
call([activeIndexAnim], onRelease),
],
[call([activeIndexAnim], resetHoverState), resetTouchedCell]
)
);
const onPanStateChange = useMemo(
() =>
event([
{
nativeEvent: ({
state,
x,
y,
}: PanGestureHandlerStateChangeEvent["nativeEvent"]) =>
block([
cond(and(neq(state, panGestureState), not(disabled)), [
cond(
or(
eq(state, GestureState.BEGAN), // Called on press in on Android, NOT on ios!
// GestureState.BEGAN may be skipped on fast swipes
and(
eq(state, GestureState.ACTIVE),
neq(panGestureState, GestureState.BEGAN)
)
),
[
set(touchAbsolute, props.horizontal ? x : y),
set(touchInit, touchAbsolute),
]
),
cond(eq(state, GestureState.ACTIVE), [
set(
activationDistance,
sub(props.horizontal ? x : y, touchInit)
),
set(touchAbsolute, props.horizontal ? x : y),
]),
]),
cond(neq(panGestureState, state), [
set(panGestureState, state),
cond(
or(
eq(state, GestureState.END),
eq(state, GestureState.CANCELLED),
eq(state, GestureState.FAILED)
),
onGestureRelease
),
]),
]),
},
]),
[
activationDistance,
props.horizontal,
panGestureState,
disabled,
onGestureRelease,
touchAbsolute,
touchInit,
]
);
const onPanGestureEvent = useMemo(
() =>
event([
{
nativeEvent: ({
x,
y,
}: PanGestureHandlerGestureEvent["nativeEvent"]) =>
cond(
and(
greaterThan(activeIndexAnim, -1),
eq(panGestureState, GestureState.ACTIVE),
not(disabled)
),
[set(touchAbsolute, props.horizontal ? x : y)]
),
},
]),
[
activeIndexAnim,
disabled,
panGestureState,
props.horizontal,
touchAbsolute,
]
);
const scrollHandler = useMemo(() => {
// Web doesn't seem to like animated events
const webOnScroll = ({
nativeEvent: {
contentOffset: { x, y },
},
}: NativeSyntheticEvent<NativeScrollEvent>) => {
scrollOffset.setValue(props.horizontal ? x : y);
};
const mobileOnScroll = event([
{
nativeEvent: ({ contentOffset }: NativeScrollEvent) =>
block([
set(
scrollOffset,
props.horizontal ? contentOffset.x : contentOffset.y
),
autoScrollNode,
]),
},
]);
return isWeb ? webOnScroll : mobileOnScroll;
}, [autoScrollNode, props.horizontal, scrollOffset]);
return (
<DraggableFlatListProvider
activeKey={activeKey}
onDragEnd={onDragEnd}
keyExtractor={keyExtractor}
horizontal={!!props.horizontal}
>
<PanGestureHandler
ref={panGestureHandlerRef}
hitSlop={dragHitSlop}
onHandlerStateChange={onPanStateChange}
onGestureEvent={onPanGestureEvent}
simultaneousHandlers={props.simultaneousHandlers}
{...dynamicProps}
>
<Animated.View
style={props.containerStyle}
ref={containerRef}
onLayout={onContainerLayout}
onTouchEnd={onContainerTouchEnd}
onStartShouldSetResponderCapture={onContainerTouchStart}
//@ts-ignore
onClick={onContainerTouchEnd}
>
<ScrollOffsetListener
scrollOffset={scrollOffset}
onScrollOffsetChange={([offset]) => {
scrollOffsetRef.current = offset;
props.onScrollOffsetChange?.(offset);
}}
/>
{!!props.renderPlaceholder && (
<PlaceholderItem renderPlaceholder={props.renderPlaceholder} />
)}
<AnimatedFlatList
{...props}
CellRendererComponent={CellRendererComponent}
ref={flatListRef}
onContentSizeChange={onListContentSizeChange}
scrollEnabled={!activeKey && scrollEnabled}
renderItem={renderItem}
extraData={extraData}
keyExtractor={keyExtractor}
onScroll={scrollHandler}
scrollEventThrottle={16}
simultaneousHandlers={props.simultaneousHandlers}
removeClippedSubviews={false}
/>
<Animated.Code dependencies={[]}>
{() =>
block([
onChange(
isTouchActiveRef.current.native,
cond(not(isTouchActiveRef.current.native), onGestureRelease)
),
])
}
</Animated.Code>
</Animated.View>
</PanGestureHandler>
</DraggableFlatListProvider>
);
}
function DraggableFlatList<T>(
props: DraggableFlatListProps<T>,
ref: React.ForwardedRef<FlatList<T>>
) {
return (
<PropsProvider {...props}>
<AnimatedValueProvider>
<RefProvider flatListRef={ref}>
<DraggableFlatListInner {...props} />
</RefProvider>
</AnimatedValueProvider>
</PropsProvider>
);
}
// Generic forwarded ref type assertion taken from:
// https://fettblog.eu/typescript-react-generic-forward-refs/#option-1%3A-type-assertion
export default React.forwardRef(DraggableFlatList) as <T>(
props: DraggableFlatListProps<T> & { ref?: React.ForwardedRef<FlatList<T>> }
) => ReturnType<typeof DraggableFlatList>; | the_stack |
- TypeDoc is unable to generate documentation for a single exported module, as
we have with api.ts,
- TypeDoc has an unreasonable amount of dependencies and code,
- we want very nice looking documentation without superfluous junk. This gives
full control.
*/
// tslint:disable:object-literal-sort-keys
import * as assert from "assert";
import { execSync, spawnSync } from "child_process";
import * as fs from "fs";
import * as path from "path";
import * as ts from "typescript";
import { log } from "../src/util";
import { ArgEntry, DocEntry } from "../website/docs";
const repoBasePath = path.resolve(__dirname, "..");
const repoBaseUrl = "https://github.com/propelml/propel";
const fileGithubUrls = new Map<string, string>();
function getGithubUrlForFile(fileName: string) {
if (fileGithubUrls.has(fileName)) {
return fileGithubUrls.get(fileName);
}
const relName = path.relative(repoBasePath, fileName).replace(/\\/g, "/");
// Sanity check: verify that the file in it's current form has been
// committed.
let stdout = execSync(`git status --porcelain -- "${fileName}"`, {
cwd: path.dirname(fileName),
encoding: "utf8"
});
if (/\S/.test(stdout)) {
throw new Error(`File has been modified since last commit: ${relName}.`);
}
// Get the commit hash for that most recent commit that updated a file.
// This is done to reduce churn in the generated documentation; as long as a
// file doesn't change, the "source" links in the documentation won't change
// either.
stdout = execSync(`git log -n1 --pretty="%H" -- "${fileName}"`, {
cwd: path.dirname(fileName),
encoding: "utf8"
});
const commitSha = stdout.match(/^\s*([0-9a-fA-F]{40})\s*$/)[1];
const githubUrl = `${repoBaseUrl}/blob/${commitSha}/${relName}`;
// Sanity check: verify that the inferred github url can actually be
// loaded.
const { status, stderr } = spawnSync(
process.execPath,
[`${__dirname}/check_url.js`, githubUrl],
{ encoding: "utf8" }
);
if (status !== 0) {
const msg =
`File committed but not available on github: ${relName}\n` +
`You probably need to push your branch to github.\n` +
stderr;
console.warn(msg);
}
fileGithubUrls.set(fileName, githubUrl);
return githubUrl;
}
export function genJSON(): DocEntry[] {
// Global variables.
const { exclude } = require("../tsconfig");
const visitQueue: ts.Node[] = [];
const visitHistory = new Map<ts.Symbol, boolean>();
let checker: ts.TypeChecker = null;
const output: DocEntry[] = [];
function requestVisit(s: ts.Symbol) {
if (!visitHistory.has(s)) {
// Find original symbol (might not be in api.ts).
s = skipAlias(s, checker);
log("requestVisit", s.getName());
const decls = s.getDeclarations();
// What does it mean to have multiple declarations?
// assert(decls.length === 1);
const sourceFileName = decls[0].getSourceFile().fileName;
// Dont visit if sourceFileName is in tsconfig excludes
if (!exclude.some(matchesSourceFileName)) {
visitQueue.push(decls[0]);
visitHistory.set(s, true);
} else {
log("excluded", sourceFileName);
}
function matchesSourceFileName(excludeDir) {
// Replace is used for cross-platform compatibility
// as 'getSourceFile().fileName' returns posix path
const excludePath = path.resolve(__dirname, "..", excludeDir);
const posixExcludePath = excludePath.replace(/\\/g, "/");
return sourceFileName.includes(posixExcludePath);
}
}
}
function requestVisitType(t: ts.Type) {
if (t.symbol) {
requestVisit(t.symbol);
} else if (t.aliasSymbol) {
requestVisit(t.aliasSymbol);
}
}
function skipAlias(symbol: ts.Symbol, checker: ts.TypeChecker) {
return symbol.flags & ts.SymbolFlags.Alias ?
checker.getAliasedSymbol(symbol) : symbol;
}
/** Generate documentation for all classes in a set of .ts files */
function gen(rootFile: string, options: ts.CompilerOptions): void {
// Build a program using the set of root file names in fileNames
const program = ts.createProgram([rootFile], options);
// Get the checker, we will use it to find more about classes
checker = program.getTypeChecker();
// Find the SourceFile object corresponding to our rootFile.
let rootSourceFile = null;
for (const sourceFile of program.getSourceFiles()) {
if (path.resolve(sourceFile.fileName) === path.resolve(rootFile)) {
rootSourceFile = sourceFile;
break;
}
}
assert(rootSourceFile);
// Add all exported symbols of root module to visitQueue.
const moduleSymbol = checker.getSymbolAtLocation(rootSourceFile);
for (const s of checker.getExportsOfModule(moduleSymbol)) {
requestVisit(s);
}
// Process queue of Nodes that should be displayed in docs.
while (visitQueue.length) {
const n = visitQueue.shift();
visit(n);
}
}
// visit nodes finding exported classes
function visit(node: ts.Node) {
if (ts.isClassDeclaration(node) && node.name) {
// This is a top level class, get its symbol
visitClass(node);
} else if (ts.isTypeAliasDeclaration(node)) {
// const symbol = checker.getSymbolAtLocation(node.name);
// checker.typeToString
// checker.symbolToString
// console.error("- type alias", checker.typeToString(node.type));
// console.error(""); // New Line.
} else if (ts.isStringLiteral(node)) {
log("- string literal");
} else if (ts.isVariableDeclaration(node)) {
const symbol = checker.getSymbolAtLocation(node.name);
const name = symbol.getName();
if (ts.isFunctionLike(node.initializer)) {
visitMethod(node.initializer, name);
} else {
log("- var", name);
}
} else if (ts.isFunctionDeclaration(node)) {
const symbol = checker.getSymbolAtLocation(node.name);
visitMethod(node, symbol.getName());
} else if (ts.isFunctionTypeNode(node)) {
log("- FunctionTypeNode.. ?");
} else if (ts.isFunctionExpression(node)) {
const symbol = checker.getSymbolAtLocation(node.name);
const name = symbol ? symbol.getName() : "<unknown>";
log("- FunctionExpression", name);
} else if (ts.isInterfaceDeclaration(node)) {
visitClass(node);
} else if (ts.isObjectLiteralExpression(node)) {
// TODO Ignoring for now.
log("- ObjectLiteralExpression");
} else if (ts.isTypeLiteralNode(node)) {
// TODO Ignoring for now.
log("- TypeLiteral");
} else {
log("Unknown node", node.kind);
assert(false, "Unknown node");
}
}
function visitMethod(methodNode: ts.FunctionLike,
methodName: string, className?: string) {
// Get the documentation string.
const sym = checker.getSymbolAtLocation(methodNode.name);
const docstr = getFlatDocstr(sym);
const sig = checker.getSignatureFromDeclaration(methodNode);
const sigStr = checker.signatureToString(sig);
let name;
if (!className) {
name = methodName;
} else if (methodName.startsWith("[")) {
// EG [Symbol.iterator]
name = className + methodName;
} else {
name = `${className}.${methodName}`;
}
// Print each of the parameters.
const argEntries: ArgEntry[] = [];
for (const paramSymbol of sig.parameters) {
const paramType = checker.getTypeOfSymbolAtLocation(paramSymbol,
paramSymbol.valueDeclaration!);
requestVisitType(paramType);
argEntries.push({
name: paramSymbol.getName(),
typestr: checker.typeToString(paramType),
docstr: getFlatDocstr(paramSymbol),
});
}
const retType = sig.getReturnType();
requestVisitType(retType);
output.push({
name,
kind: "method",
typestr: sigStr,
args: argEntries,
retType: checker.typeToString(retType),
docstr,
sourceUrl: getSourceUrl(methodNode)
});
}
function getFlatDocstr(sym: ts.Symbol): string | undefined {
if (sym && sym.getDocumentationComment(checker).length > 0) {
return ts.displayPartsToString(sym.getDocumentationComment(checker));
}
return undefined;
}
function getSourceUrl(node: ts.Node): string {
const sourceFile = node.getSourceFile();
const docNodes = (node as any).jsDoc; // No public API for this?
const startNode = (docNodes && docNodes[0]) || node;
const [startLine, endLine] = [
startNode.getStart(),
node.getEnd()
].map(pos => sourceFile.getLineAndCharacterOfPosition(pos).line + 1);
const sourceRange =
endLine > startLine ? `L${startLine}-L${endLine}` : `L${startLine}`;
const githubUrl = getGithubUrlForFile(sourceFile.fileName);
return `${githubUrl}#${sourceRange}`;
}
function visitClass(node: ts.ClassDeclaration | ts.InterfaceDeclaration) {
const symbol = checker.getSymbolAtLocation(node.name);
const className = symbol.getName();
let docstr = null;
if (symbol.getDocumentationComment(checker).length > 0) {
docstr = ts.displayPartsToString(symbol.getDocumentationComment(checker));
}
output.push({
name: className,
kind: "class",
docstr,
sourceUrl: getSourceUrl(node)
});
for (const m of node.members) {
const name = classElementName(m);
// Skip private members.
if (ts.getCombinedModifierFlags(m) & ts.ModifierFlags.Private) {
log("private. skipping", name);
continue;
}
if (ts.isPropertySignature(m)) {
visitProp(m, name, className);
} else if (ts.isMethodSignature(m)) {
visitMethod(m, name, className);
} else if (ts.isConstructorDeclaration(m)) {
visitMethod(m, "constructor", className);
} else if (ts.isMethodDeclaration(m)) {
visitMethod(m, name, className);
} else if (ts.isPropertyDeclaration(m)) {
if (ts.isFunctionLike(m.initializer)) {
visitMethod(m.initializer, name, className);
} else {
visitProp(m, name, className);
}
} else if (ts.isGetAccessorDeclaration(m)) {
visitProp(m, name, className);
} else {
log("member", className, name);
}
}
}
function visitProp(node: ts.ClassElement | ts.PropertySignature,
name: string, className?: string) {
name = className ? `${className}.${name}` : name;
const symbol = checker.getSymbolAtLocation(node.name);
const t = checker.getTypeOfSymbolAtLocation(symbol, node);
output.push({
name,
kind: "property",
typestr: checker.typeToString(t),
docstr: getFlatDocstr(symbol),
sourceUrl: getSourceUrl(node)
});
}
function classElementName(m: ts.ClassElement | ts.TypeElement): string {
if (m.name) {
if (ts.isIdentifier(m.name)) {
return ts.idText(m.name);
}
if (ts.isComputedPropertyName(m.name)) {
const e = m.name.expression;
if (ts.isPropertyAccessExpression(e)) {
// This is for [Symbol.iterator]() { }
assert(ts.isIdentifier(e.name));
return `[Symbol.${e.name.text}]`;
}
}
}
return "<unknown>";
}
gen(repoBasePath + "/src/api.ts", require("../tsconfig.json"));
return output;
}
export function writeJSON(target = repoBasePath + "/build/website") {
const docs = genJSON();
const j = JSON.stringify(docs, null, 2);
fs.writeFileSync(target, j);
console.log("wrote", target);
}
if (require.main === module) {
const target = process.argv[2];
if (!target) {
console.log("Usage: ts-node tools/gendoc.ts ./website/docs.json");
process.exit(1);
}
writeJSON(target);
} | the_stack |
import { OfferParameters } from "./OfferParameters";
import { AcceptanceParameters } from "./AcceptanceParameters";
import { MultiplexingStream } from "./MultiplexingStream";
import { randomBytes } from "crypto";
import { getBufferFrom, writeAsync } from "./Utilities";
import CancellationToken from "cancellationtoken";
import * as msgpack from 'msgpack-lite';
import { Deferred } from "./Deferred";
import { FrameHeader } from "./FrameHeader";
import { ControlCode } from "./ControlCode";
import { ChannelSource } from "./QualifiedChannelId";
export interface Version {
major: number;
minor: number;
}
export interface HandshakeResult {
isOdd?: boolean;
protocolVersion: Version;
}
export abstract class MultiplexingStreamFormatter {
isOdd?: boolean;
abstract writeHandshakeAsync(): Promise<Buffer | null>;
abstract readHandshakeAsync(writeHandshakeResult: Buffer | null, cancellationToken: CancellationToken): Promise<HandshakeResult>;
abstract writeFrameAsync(header: FrameHeader, payload?: Buffer): Promise<void>;
abstract readFrameAsync(cancellationToken: CancellationToken): Promise<{ header: FrameHeader, payload: Buffer } | null>;
abstract serializeOfferParameters(offer: OfferParameters): Buffer;
abstract deserializeOfferParameters(payload: Buffer): OfferParameters;
abstract serializeAcceptanceParameters(acceptance: AcceptanceParameters): Buffer;
abstract deserializeAcceptanceParameters(payload: Buffer): AcceptanceParameters;
abstract serializeContentProcessed(bytesProcessed: number): Buffer;
abstract deserializeContentProcessed(payload: Buffer): number;
abstract end(): void;
protected static getIsOddRandomData(): Buffer {
return randomBytes(16);
}
protected static isOdd(localRandom: Buffer, remoteRandom: Buffer): boolean {
let isOdd: boolean | undefined;
for (let i = 0; i < localRandom.length; i++) {
const sent = localRandom[i];
const recv = remoteRandom[i];
if (sent > recv) {
isOdd = true;
break;
} else if (sent < recv) {
isOdd = false;
break;
}
}
if (isOdd === undefined) {
throw new Error("Unable to determine even/odd party.");
}
return isOdd;
}
protected createFrameHeader(code: ControlCode, id: number | undefined): FrameHeader {
if (!id) {
return new FrameHeader(code);
}
const channelIsOdd = id % 2 === 1;
// Remember that this is from the remote sender's point of view.
const source = channelIsOdd === this.isOdd ? ChannelSource.Remote : ChannelSource.Local;
return new FrameHeader(code, { id, source });
}
}
// tslint:disable-next-line: max-classes-per-file
export class MultiplexingStreamV1Formatter extends MultiplexingStreamFormatter {
/**
* The magic number to send at the start of communication when using v1 of the protocol.
*/
private static readonly protocolMagicNumber = new Buffer([0x2f, 0xdf, 0x1d, 0x50]);
constructor(private readonly stream: NodeJS.ReadWriteStream) {
super();
}
end() {
this.stream.end();
}
async writeHandshakeAsync(): Promise<Buffer> {
const randomSendBuffer = MultiplexingStreamFormatter.getIsOddRandomData();
const sendBuffer = Buffer.concat([MultiplexingStreamV1Formatter.protocolMagicNumber, randomSendBuffer]);
await writeAsync(this.stream, sendBuffer);
return randomSendBuffer;
}
async readHandshakeAsync(writeHandshakeResult: Buffer, cancellationToken: CancellationToken): Promise<HandshakeResult> {
const localRandomBuffer = writeHandshakeResult as Buffer;
const recvBuffer = await getBufferFrom(this.stream, MultiplexingStreamV1Formatter.protocolMagicNumber.length + 16, false, cancellationToken);
for (let i = 0; i < MultiplexingStreamV1Formatter.protocolMagicNumber.length; i++) {
const expected = MultiplexingStreamV1Formatter.protocolMagicNumber[i];
const actual = recvBuffer.readUInt8(i);
if (expected !== actual) {
throw new Error(`Protocol magic number mismatch. Expected ${expected} but was ${actual}.`);
}
}
const isOdd = MultiplexingStreamFormatter.isOdd(localRandomBuffer, recvBuffer.slice(MultiplexingStreamV1Formatter.protocolMagicNumber.length));
return { isOdd, protocolVersion: { major: 1, minor: 0 } };
}
async writeFrameAsync(header: FrameHeader, payload?: Buffer): Promise<void> {
const headerBuffer = new Buffer(7);
headerBuffer.writeInt8(header.code, 0);
headerBuffer.writeUInt32BE(header.channel?.id || 0, 1);
headerBuffer.writeUInt16BE(payload?.length || 0, 5);
await writeAsync(this.stream, headerBuffer);
if (payload && payload.length > 0) {
await writeAsync(this.stream, payload);
}
}
async readFrameAsync(cancellationToken: CancellationToken): Promise<{ header: FrameHeader, payload: Buffer } | null> {
if (this.isOdd === undefined) {
throw new Error("isOdd must be set first.");
}
const headerBuffer = await getBufferFrom(this.stream, 7, true, cancellationToken);
if (headerBuffer === null) {
return null;
}
const header = this.createFrameHeader(
headerBuffer.readInt8(0),
headerBuffer.readUInt32BE(1));
const payloadLength = headerBuffer.readUInt16BE(5);
const payload = await getBufferFrom(this.stream, payloadLength);
return { header, payload };
}
serializeOfferParameters(offer: OfferParameters): Buffer {
const payload = new Buffer(offer.name, MultiplexingStream.ControlFrameEncoding);
if (payload.length > MultiplexingStream.framePayloadMaxLength) {
throw new Error("Name is too long.");
}
return payload;
}
deserializeOfferParameters(payload: Buffer): OfferParameters {
return {
name: payload.toString(MultiplexingStream.ControlFrameEncoding),
};
}
serializeAcceptanceParameters(_: AcceptanceParameters): Buffer {
return new Buffer([]);
}
deserializeAcceptanceParameters(_: Buffer): AcceptanceParameters {
return {};
}
serializeContentProcessed(bytesProcessed: number): Buffer {
throw new Error("Not supported in the V1 protocol.");
}
deserializeContentProcessed(payload: Buffer): number {
throw new Error("Not supported in the V1 protocol.");
}
}
// tslint:disable-next-line: max-classes-per-file
export class MultiplexingStreamV2Formatter extends MultiplexingStreamFormatter {
private static readonly ProtocolVersion: Version = { major: 2, minor: 0 };
private readonly reader: msgpack.DecodeStream;
protected readonly writer: NodeJS.WritableStream;
constructor(stream: NodeJS.ReadWriteStream) {
super();
this.reader = msgpack.createDecodeStream();
stream.pipe(this.reader);
this.writer = stream;
}
end() {
this.writer.end();
}
async writeHandshakeAsync(): Promise<Buffer | null> {
const randomData = MultiplexingStreamFormatter.getIsOddRandomData();
const msgpackObject = [[MultiplexingStreamV2Formatter.ProtocolVersion.major, MultiplexingStreamV2Formatter.ProtocolVersion.minor], randomData];
await writeAsync(this.writer, msgpack.encode(msgpackObject));
return randomData;
}
async readHandshakeAsync(writeHandshakeResult: Buffer | null, cancellationToken: CancellationToken): Promise<HandshakeResult> {
if (!writeHandshakeResult) {
throw new Error("Provide the result of writeHandshakeAsync as a first argument.");
}
const handshake = await this.readMessagePackAsync(cancellationToken);
if (handshake === null) {
throw new Error("No data received during handshake.");
}
return {
isOdd: MultiplexingStreamFormatter.isOdd(writeHandshakeResult, handshake[1]),
protocolVersion: { major: handshake[0][0], minor: handshake[0][1] },
};
}
async writeFrameAsync(header: FrameHeader, payload?: Buffer): Promise<void> {
const msgpackObject: any[] = [header.code];
if (header.channel?.id) {
msgpackObject.push(header.channel.id);
if (payload && payload.length > 0) {
msgpackObject.push(payload);
}
} else if (payload && payload.length > 0) {
throw new Error("A frame may not contain payload without a channel ID.");
}
await writeAsync(this.writer, msgpack.encode(msgpackObject));
}
async readFrameAsync(cancellationToken: CancellationToken): Promise<{ header: FrameHeader; payload: Buffer; } | null> {
if (this.isOdd === undefined) {
throw new Error("isOdd must be set first.");
}
const msgpackObject = await this.readMessagePackAsync(cancellationToken) as [ControlCode, number, Buffer] | null;
if (msgpackObject === null) {
return null;
}
const header = this.createFrameHeader(
msgpackObject[0],
msgpackObject[1]);
return {
header,
payload: msgpackObject[2] || Buffer.from([]),
}
}
serializeOfferParameters(offer: OfferParameters): Buffer {
const payload: any[] = [offer.name];
if (offer.remoteWindowSize) {
payload.push(offer.remoteWindowSize);
}
return msgpack.encode(payload);
}
deserializeOfferParameters(payload: Buffer): OfferParameters {
const msgpackObject = msgpack.decode(payload);
return {
name: msgpackObject[0],
remoteWindowSize: msgpackObject[1],
};
}
serializeAcceptanceParameters(acceptance: AcceptanceParameters): Buffer {
const payload: any[] = [];
if (acceptance.remoteWindowSize) {
payload.push(acceptance.remoteWindowSize);
}
return msgpack.encode(payload);
}
deserializeAcceptanceParameters(payload: Buffer): AcceptanceParameters {
const msgpackObject = msgpack.decode(payload);
return {
remoteWindowSize: msgpackObject[0],
};
}
serializeContentProcessed(bytesProcessed: number): Buffer {
return msgpack.encode([bytesProcessed]);
}
deserializeContentProcessed(payload: Buffer): number {
return msgpack.decode(payload)[0];
}
protected async readMessagePackAsync(cancellationToken: CancellationToken): Promise<{} | [] | null> {
const streamEnded = new Deferred<void>();
while (true) {
const readObject = this.reader.read();
if (readObject === null) {
const bytesAvailable = new Deferred<void>();
this.reader.once("readable", bytesAvailable.resolve.bind(bytesAvailable));
this.reader.once("end", streamEnded.resolve.bind(streamEnded));
const endPromise = Promise.race([bytesAvailable.promise, streamEnded.promise]);
await (cancellationToken ? cancellationToken.racePromise(endPromise) : endPromise);
if (bytesAvailable.isCompleted) {
continue;
}
return null;
}
return readObject;
}
}
}
// tslint:disable-next-line: max-classes-per-file
export class MultiplexingStreamV3Formatter extends MultiplexingStreamV2Formatter {
private static readonly ProtocolV3Version: Version = { major: 2, minor: 0 };
writeHandshakeAsync(): Promise<null> {
return Promise.resolve(null);
}
readHandshakeAsync(): Promise<HandshakeResult> {
return Promise.resolve({ protocolVersion: MultiplexingStreamV3Formatter.ProtocolV3Version });
}
async writeFrameAsync(header: FrameHeader, payload?: Buffer): Promise<void> {
const msgpackObject: any[] = [header.code];
if (header.channel) {
msgpackObject.push(header.channel.id);
msgpackObject.push(header.channel.source);
if (payload && payload.length > 0) {
msgpackObject.push(payload);
}
} else if (payload && payload.length > 0) {
throw new Error("A frame may not contain payload without a channel ID.");
}
await writeAsync(this.writer, msgpack.encode(msgpackObject));
}
async readFrameAsync(cancellationToken: CancellationToken): Promise<{ header: FrameHeader; payload: Buffer; } | null> {
const msgpackObject = await this.readMessagePackAsync(cancellationToken) as [ControlCode, number, ChannelSource, Buffer] | null;
if (msgpackObject === null) {
return null;
}
const header = new FrameHeader(
msgpackObject[0],
msgpackObject.length > 1 ? { id: msgpackObject[1], source: msgpackObject[2] } : undefined);
return {
header,
payload: msgpackObject[3] || Buffer.from([]),
}
}
} | the_stack |
import { ethers, waffle } from "hardhat";
import { expect, use } from "chai";
import { solidity } from "ethereum-waffle";
use(solidity);
import { hexlify, keccak256, randomBytes } from "ethers/lib/utils";
import { Wallet, BigNumberish, constants, providers, Contract } from "ethers";
import { RevertableERC20, TransactionManager, ERC20 } from "@connext/nxtp-contracts";
import TransactionManagerArtifact from "@connext/nxtp-contracts/artifacts/contracts/TransactionManager.sol/TransactionManager.json";
import RouterArtifact from "@connext/nxtp-contracts/artifacts/contracts/Router.sol/Router.json";
import RevertableERC20Artifact from "@connext/nxtp-contracts/artifacts/contracts/test/RevertableERC20.sol/RevertableERC20.json";
import {
InvariantTransactionData,
signCancelTransactionPayload,
signFulfillTransactionPayload,
VariantTransactionData,
signRouterRemoveLiquidityTransactionPayload,
signRouterCancelTransactionPayload,
signRouterFulfillTransactionPayload,
signRouterPrepareTransactionPayload,
} from "@connext/nxtp-utils";
import { deployContract, MAX_FEE_PER_GAS } from "./utils";
import { getContractError } from "../src";
// import types
import { Router, RouterFactory } from "../typechain";
const convertToPrepareArgs = (transaction: InvariantTransactionData, record: VariantTransactionData) => {
const args = {
invariantData: transaction,
amount: record.amount,
expiry: record.expiry,
encryptedCallData: EmptyBytes,
encodedBid: EmptyBytes,
bidSignature: EmptyBytes,
encodedMeta: EmptyBytes,
};
return args;
};
const convertToFulfillArgs = (
transaction: InvariantTransactionData,
record: VariantTransactionData,
relayerFee: string,
signature: string,
callData: string = EmptyBytes,
) => {
const args = {
txData: {
...transaction,
...record,
},
relayerFee,
signature,
callData,
encodedMeta: EmptyBytes,
};
return args;
};
const convertToCancelArgs = (
transaction: InvariantTransactionData,
record: VariantTransactionData,
signature: string,
) => {
const args = {
txData: {
...transaction,
...record,
},
signature,
encodedMeta: EmptyBytes,
};
return args;
};
const { AddressZero } = constants;
const EmptyBytes = "0x";
const EmptyCallDataHash = keccak256(EmptyBytes);
const createFixtureLoader = waffle.createFixtureLoader;
describe("Router.sol", function () {
const [wallet, routerSigner, routerRecipient, user, receiver, gelato, other] =
waffle.provider.getWallets() as Wallet[];
let routerFactory: RouterFactory;
let transactionManagerReceiverSide: TransactionManager;
let token: RevertableERC20;
let computedRouterAddress: string;
let routerContract: Router;
const sendingChainId = 1337;
const receivingChainId = 1338;
const fixture = async () => {
transactionManagerReceiverSide = await deployContract<TransactionManager>(
TransactionManagerArtifact,
receivingChainId,
);
routerFactory = await deployContract<RouterFactory>("RouterFactory", wallet.address);
token = await deployContract<RevertableERC20>(RevertableERC20Artifact);
return {
routerFactory,
transactionManagerReceiverSide,
token,
};
};
const addPrivileges = async (tm: TransactionManager, routers: string[], assets: string[]) => {
for (const routerSigner of routers) {
const tx = await tm.addRouter(routerSigner, { maxFeePerGas: MAX_FEE_PER_GAS });
await tx.wait();
expect(await tm.approvedRouters(routerSigner)).to.be.true;
}
for (const assetId of assets) {
const tx = await tm.addAssetId(assetId, {
maxFeePerGas: MAX_FEE_PER_GAS,
});
await tx.wait();
expect(await tm.approvedAssets(assetId)).to.be.true;
}
};
const approveTokens = async (amount: BigNumberish, approver: Wallet, spender: string, asset: ERC20 = token) => {
const approveTx = await asset.connect(approver).approve(spender, amount);
await approveTx.wait();
const allowance = await asset.allowance(approver.address, spender);
expect(allowance).to.be.at.least(amount);
};
let loadFixture: ReturnType<typeof createFixtureLoader>;
before("create fixture loader", async () => {
loadFixture = createFixtureLoader([wallet, routerSigner, user, receiver, other]);
});
beforeEach(async function () {
({ routerFactory, transactionManagerReceiverSide, token } = await loadFixture(fixture));
const initTx = await routerFactory.connect(wallet).init(transactionManagerReceiverSide.address);
await initTx.wait();
const createTx: providers.TransactionResponse = await routerFactory
.connect(routerSigner)
.createRouter(routerSigner.address, routerRecipient.address);
const receipt = await createTx.wait();
expect(receipt.status).to.be.eq(1);
computedRouterAddress = await routerFactory.getRouterAddress(routerSigner.address);
routerContract = new Contract(computedRouterAddress, RouterArtifact.abi, ethers.provider) as Router;
// Prep contracts with routerSigner and assets
await addPrivileges(transactionManagerReceiverSide, [computedRouterAddress], [AddressZero, token.address]);
const liq = "10000";
let tx = await token.connect(wallet).transfer(routerSigner.address, liq);
await tx.wait();
await token.connect(wallet).transfer(computedRouterAddress, liq);
await approveTokens(liq, routerSigner, transactionManagerReceiverSide.address);
let addLiquidityTx = await transactionManagerReceiverSide
.connect(routerSigner)
.addLiquidityFor(liq, token.address, computedRouterAddress);
await addLiquidityTx.wait();
});
const getTransactionData = async (
txOverrides: Partial<InvariantTransactionData> = {},
recordOverrides: Partial<VariantTransactionData> = {},
): Promise<{
transaction: InvariantTransactionData;
record: VariantTransactionData;
}> => {
const transaction = {
receivingChainTxManagerAddress: transactionManagerReceiverSide.address,
user: user.address,
router: computedRouterAddress,
initiator: user.address,
sendingAssetId: AddressZero,
receivingAssetId: token.address,
sendingChainFallback: user.address,
callTo: AddressZero,
receivingAddress: receiver.address,
callDataHash: EmptyCallDataHash,
transactionId: hexlify(randomBytes(32)),
sendingChainId: sendingChainId,
receivingChainId: receivingChainId,
...txOverrides,
};
const day = 24 * 60 * 60;
const block = await ethers.provider.getBlock("latest");
const record = {
amount: "10",
expiry: block.timestamp + day + 5_000,
preparedBlockNumber: 10,
...recordOverrides,
};
return { transaction, record };
};
describe("constructor", async () => {
it("should deploy", async () => {
expect(computedRouterAddress).to.be.a("string");
});
it("should get transactionManagerAddress", async () => {
expect(await routerContract.transactionManager()).to.eq(transactionManagerReceiverSide.address);
});
it("should get routerSigner", async () => {
expect(await routerContract.routerSigner()).to.eq(routerSigner.address);
});
it("should get recipient", async () => {
expect(await routerContract.recipient()).to.eq(routerRecipient.address);
});
});
describe("setRecipient", () => {
it("should set contract property recipient", async () => {
const newSigner = Wallet.createRandom();
const tx = await routerContract.connect(routerSigner).setRecipient(newSigner.address);
const receipt = await tx.wait();
expect(receipt.status).to.eq(1);
expect(await routerContract.recipient()).to.eq(newSigner.address);
});
});
describe("setSigner", () => {
it("should set contract property routerSigner", async () => {
const newSigner = Wallet.createRandom();
const tx = await routerContract.connect(routerSigner).setSigner(newSigner.address);
const receipt = await tx.wait();
expect(receipt.status).to.eq(1);
expect(await routerContract.routerSigner()).to.eq(newSigner.address);
});
});
describe("removeLiquidity", () => {
it("should remove liquidity", async () => {
const amount = "100";
const assetId = token.address;
const routerRelayerFeeAsset = token.address;
const routerRelayerFee = "1";
const signature = await signRouterRemoveLiquidityTransactionPayload(
amount,
assetId,
routerRelayerFeeAsset,
routerRelayerFee,
receivingChainId,
routerSigner,
);
const tx = await routerContract
.connect(gelato)
.removeLiquidity(amount, assetId, routerRelayerFeeAsset, routerRelayerFee, signature);
const receipt = await tx.wait();
expect(receipt.status).to.eq(1);
});
});
describe("addRelayerFee", () => {
it.skip("should add relayer fee", async () => {
const amount = "100";
const assetId = token.address;
const tx = await routerContract.connect(routerSigner).addRelayerFee(amount, assetId);
const receipt = await tx.wait();
expect(receipt.status).to.eq(1);
// TODO: Check that the relayer fee was added
});
});
describe("removeRelayerFee", () => {
it("should remove relayer fee", async () => {
const amount = "100";
const assetId = token.address;
const tx = await routerContract.connect(routerSigner).removeRelayerFee(amount, assetId);
const receipt = await tx.wait();
expect(receipt.status).to.eq(1);
// TODO: Check if fee is removed
});
});
const prepare = async (
transaction: InvariantTransactionData,
record: VariantTransactionData,
routerRelayerFeeAsset = token.address,
routerRelayerFee = "0",
) => {
const args = convertToPrepareArgs(transaction, record);
// const balance = await getOnchainBalance(token.address, computedRouterAddress, ethers.provider);
// console.log(balance.toString());
const signature = await signRouterPrepareTransactionPayload(
transaction,
args.amount,
args.expiry,
args.encryptedCallData,
args.encodedBid,
args.bidSignature,
args.encodedMeta,
routerRelayerFeeAsset,
routerRelayerFee,
receivingChainId,
routerSigner,
);
const prepareTx = await routerContract
.connect(gelato)
.prepare(args, routerRelayerFeeAsset, routerRelayerFee, signature);
const receipt = await prepareTx.wait();
expect(receipt.status).to.be.eq(1);
return receipt;
};
describe("prepare", () => {
it("should fail to prepare a bad sig", async () => {
const { transaction, record } = await getTransactionData();
const routerRelayerFeeAsset = token.address;
const routerRelayerFee = "1";
const args = convertToPrepareArgs(transaction, record);
const signature = await signRouterPrepareTransactionPayload(
transaction,
args.amount,
args.expiry,
args.encryptedCallData,
args.encodedBid,
args.bidSignature,
args.encodedMeta,
routerRelayerFeeAsset,
routerRelayerFee,
receivingChainId,
other, // bad signer
);
await expect(
routerContract.connect(gelato).prepare(args, routerRelayerFeeAsset, routerRelayerFee, signature),
).to.be.revertedWith(getContractError("routerContract_prepare: INVALID_ROUTER_SIGNATURE"));
});
it("should prepare with a different sender", async () => {
const { transaction, record } = await getTransactionData();
await prepare(transaction, record);
});
it("should prepare with the signer and no sig", async () => {
const { transaction, record } = await getTransactionData();
const routerRelayerFeeAsset = token.address;
const routerRelayerFee = "1";
const args = convertToPrepareArgs(transaction, record);
const prepareTx = await routerContract
.connect(routerSigner)
.prepare(args, routerRelayerFeeAsset, routerRelayerFee, "0x");
const receipt = await prepareTx.wait();
expect(receipt.status).to.be.eq(1);
return receipt;
});
});
describe("fulfill", () => {
it("should fail to fulfill a bad sig", async () => {
const { transaction, record } = await getTransactionData();
const routerRelayerFeeAsset = token.address;
const routerRelayerFee = "1";
const relayerFee = "2";
await prepare(transaction, record);
// Generate signature from user
const fulfillSignature = await signFulfillTransactionPayload(
transaction.transactionId,
relayerFee,
transaction.receivingChainId,
transaction.receivingChainTxManagerAddress,
user,
);
const args = convertToFulfillArgs(transaction, record, "0", fulfillSignature);
const signature = await signRouterFulfillTransactionPayload(
args.txData,
fulfillSignature,
relayerFee,
args.callData,
args.encodedMeta,
routerRelayerFeeAsset,
routerRelayerFee,
sendingChainId,
other, // bad signer
);
await expect(
routerContract.connect(gelato).fulfill(args, routerRelayerFeeAsset, routerRelayerFee, signature),
).to.be.revertedWith(getContractError("routerContract_fulfill: INVALID_ROUTER_SIGNATURE"));
});
it("should fulfill with a different sender", async () => {
const { transaction, record } = await getTransactionData();
const routerRelayerFeeAsset = token.address;
const routerRelayerFee = "1";
const relayerFee = "2";
const { blockNumber } = await prepare(transaction, record);
// Generate signature from user
const fulfillSignature = await signFulfillTransactionPayload(
transaction.transactionId,
relayerFee,
transaction.receivingChainId,
transaction.receivingChainTxManagerAddress,
user,
);
const args = convertToFulfillArgs(
transaction,
{ ...record, preparedBlockNumber: blockNumber },
relayerFee,
fulfillSignature,
);
const signature = await signRouterFulfillTransactionPayload(
args.txData,
fulfillSignature,
relayerFee,
args.callData,
args.encodedMeta,
routerRelayerFeeAsset,
routerRelayerFee,
receivingChainId,
routerSigner,
);
const fulfillTx = await routerContract
.connect(gelato)
.fulfill(args, routerRelayerFeeAsset, routerRelayerFee, signature);
const receipt = await fulfillTx.wait();
expect(receipt.status).to.be.eq(1);
return receipt;
});
it("should fulfill with the signer and no sig", async () => {
const { transaction, record } = await getTransactionData();
const routerRelayerFeeAsset = token.address;
const routerRelayerFee = "1";
const { blockNumber } = await prepare(transaction, record);
// Generate signature from user
const fulfillSignature = await signFulfillTransactionPayload(
transaction.transactionId,
"0",
transaction.receivingChainId,
transaction.receivingChainTxManagerAddress,
user,
);
const args = convertToFulfillArgs(
transaction,
{ ...record, preparedBlockNumber: blockNumber },
"0",
fulfillSignature,
);
const fulfillTx = await routerContract
.connect(routerSigner)
.fulfill(args, routerRelayerFeeAsset, routerRelayerFee, "0x");
const receipt = await fulfillTx.wait();
expect(receipt.status).to.be.eq(1);
return receipt;
});
});
describe("cancel", () => {
it("should fail to cancel a bad sig", async () => {
const { transaction, record } = await getTransactionData();
const routerRelayerFeeAsset = token.address;
const routerRelayerFee = "1";
const { blockNumber } = await prepare(transaction, record);
// Generate signature from user
const cancelSignature = await signCancelTransactionPayload(
transaction.transactionId,
transaction.receivingChainId,
transaction.receivingChainTxManagerAddress,
user,
);
const args = convertToCancelArgs(transaction, { ...record, preparedBlockNumber: blockNumber }, cancelSignature);
const signature = await signRouterCancelTransactionPayload(
args.txData,
cancelSignature,
args.encodedMeta,
routerRelayerFeeAsset,
routerRelayerFee,
sendingChainId,
other, // bad signer
);
await expect(
routerContract.connect(gelato).cancel(args, routerRelayerFeeAsset, routerRelayerFee, signature),
).to.be.revertedWith(getContractError("routerContract_cancel: INVALID_ROUTER_SIGNATURE"));
});
it("should cancel with a different sender", async () => {
const { transaction, record } = await getTransactionData();
const routerRelayerFeeAsset = token.address;
const routerRelayerFee = "1";
const { blockNumber } = await prepare(transaction, record);
// Generate signature from user
const cancelSignature = await signCancelTransactionPayload(
transaction.transactionId,
transaction.receivingChainId,
transaction.receivingChainTxManagerAddress,
user,
);
const args = convertToCancelArgs(transaction, { ...record, preparedBlockNumber: blockNumber }, cancelSignature);
const signature = await signRouterCancelTransactionPayload(
args.txData,
cancelSignature,
args.encodedMeta,
routerRelayerFeeAsset,
routerRelayerFee,
receivingChainId,
routerSigner,
);
const cancelTx = await routerContract
.connect(gelato)
.cancel(args, routerRelayerFeeAsset, routerRelayerFee, signature);
const receipt = await cancelTx.wait();
expect(receipt.status).to.be.eq(1);
return receipt;
});
it("should cancel with the signer and no sig", async () => {
const { transaction, record } = await getTransactionData();
const routerRelayerFeeAsset = token.address;
const routerRelayerFee = "1";
const { blockNumber } = await prepare(transaction, record);
// Generate signature from user
const cancelSignature = await signCancelTransactionPayload(
transaction.transactionId,
transaction.receivingChainId,
transaction.receivingChainTxManagerAddress,
user,
);
const args = convertToCancelArgs(transaction, { ...record, preparedBlockNumber: blockNumber }, cancelSignature);
const cancelTx = await routerContract
.connect(routerSigner)
.cancel(args, routerRelayerFeeAsset, routerRelayerFee, "0x");
const receipt = await cancelTx.wait();
expect(receipt.status).to.be.eq(1);
return receipt;
});
});
}); | the_stack |
module CorsicaTests {
"use strict";
var DeclTest = function (element, options) {
return options;
};
(<any>DeclTest).supportedForProcessing = true;
window["DeclTest"] = DeclTest;
var AsyncDeclTest = function (element, options, complete) {
setTimeout(complete, 32);
return options;
};
(<any>AsyncDeclTest).supportedForProcessing = true;
window["AsyncDeclTest"] = AsyncDeclTest;
var leafCount = 0;
var containerCount = 0;
var ContainerTestLeaf = function (element, options) {
leafCount++;
};
(<any>ContainerTestLeaf).supportedForProcessing = true;
window["ContainerTestLeaf"] = ContainerTestLeaf;
var ContainerTestContainer = function (element, options) {
containerCount++;
};
(<any>ContainerTestContainer).isDeclarativeControlContainer = true;
(<any>ContainerTestContainer).supportedForProcessing = true;
window["ContainerTestContainer"] = ContainerTestContainer;
var SupportedForProcessingControl = function (element, options) {
element.winControl = this;
WinJS.UI.setOptions(this, options);
};
(<any>SupportedForProcessingControl).supportedForProcessing = true;
window["SupportedForProcessingControl"] = SupportedForProcessingControl;
var NotSupportedForProcessingControl = function (element, options) {
element.winControl = this;
WinJS.UI.setOptions(this, options);
};
window["NotSupportedForProcessingControl"] = NotSupportedForProcessingControl;
// Define a property on window with a long unicode string
window["\u624d\u80fd\u30bd\u042b\u2168\u84a4\u90f3\u0930\u094d\u0915\u094d\u0921\u094d\u0930\u093e\u00fc\u0131\u015f\u011f\u0130li\u064a\u0648\u0646\u064a\u0643\u0648\u062f\u00f6\u00c4\u00fc\u00df\u00a7\u624d\u80fd\u30bd\u042b\u2168\u84a4\u90f3\u0930\u094d\u0915\u094d\u0921\u094d\u0930\u093e\u00fc\u0131\u015f\u011f\u0130li\u064a\u0648\u0646\u064a\u0643\u0648\u062f\u00f6\u00c4\u00fc\u00df\u00a7Abcd123"] = "data";
function errorHandler(msg) {
try {
LiveUnit.Assert.fail("There was an unhandled error in your test: " + msg);
} catch (ex) { }
}
export class DeclarativeControls {
testSetControl() {
var control = {};
var element = document.createElement("div");
element.winControl = control;
LiveUnit.Assert.isTrue(control === element.winControl);
}
testContainers() {
var holder = document.createElement("div");
holder.innerHTML = "<div data-win-control='ContainerTestContainer'><div data-win-control='ContainerTestLeaf'></div></div>";
leafCount = 0;
containerCount = 0;
WinJS.UI.processAll(holder);
LiveUnit.Assert.areEqual(1, containerCount);
LiveUnit.Assert.areEqual(0, leafCount);
WinJS.UI.processAll(holder);
LiveUnit.Assert.areEqual(1, containerCount);
LiveUnit.Assert.areEqual(0, leafCount);
WinJS.UI.processAll(<Element>holder.firstChild.firstChild);
LiveUnit.Assert.areEqual(1, containerCount);
LiveUnit.Assert.areEqual(1, leafCount);
}
testBasicDeclaration() {
LiveUnit.Assert.isTrue(WinJS.Utilities.getMember("DeclTest"));
LiveUnit.Assert.areEqual(WinJS.Utilities.getMember("DeclTest")(5, 5), 5);
var holder = document.createElement("div");
holder.innerHTML = "<div data-win-control='DeclTest' data-win-options='{test:123}'></div>";
WinJS.UI.process(<Element>holder.firstChild);
var control = (<HTMLElement>holder.firstChild).winControl;
LiveUnit.Assert.areEqual(123, control.test);
}
testBasicDeclarationWhitespace() {
LiveUnit.Assert.isTrue(WinJS.Utilities.getMember("DeclTest"));
LiveUnit.Assert.areEqual(WinJS.Utilities.getMember("DeclTest")(5, 5), 5);
var holder = document.createElement("div");
holder.innerHTML = "<div data-win-control=' DeclTest ' data-win-options='{test:123}'></div>";
WinJS.UI.process(<Element>holder.firstChild);
var control = (<Element>holder.firstChild).winControl;
LiveUnit.Assert.areEqual(123, control.test);
}
testBasicAsyncDeclaration(complete) {
LiveUnit.Assert.isTrue(WinJS.Utilities.getMember("AsyncDeclTest"));
LiveUnit.Assert.areEqual(WinJS.Utilities.getMember("AsyncDeclTest")(5, 5, function () { }), 5);
var holder = document.createElement("div");
holder.innerHTML = "<div data-win-control='AsyncDeclTest' data-win-options='{test:123}'></div>";
WinJS.UI.process(<Element>holder.firstChild).then(function (control) {
LiveUnit.Assert.areEqual(123, control.test);
complete();
});
}
testCallbackBasicDeclaration() {
LiveUnit.Assert.isTrue(WinJS.Utilities.getMember("DeclTest"));
LiveUnit.Assert.areEqual(WinJS.Utilities.getMember("DeclTest")(5, 5), 5);
var holder = document.createElement("div");
holder.innerHTML = "<div data-win-control='DeclTest' data-win-options='{test:123}'></div>";
var callbackCount = 0;
var callback = function () {
callbackCount++;
};
WinJS.UI.process(<Element>holder.firstChild).then(callback);
LiveUnit.Assert.areEqual(1, callbackCount);
var control = (<Element>holder.firstChild).winControl;
LiveUnit.Assert.areEqual(123, control.test);
}
testCallbackForElementWithoutControl() {
LiveUnit.Assert.isTrue(WinJS.Utilities.getMember("DeclTest"));
LiveUnit.Assert.areEqual(WinJS.Utilities.getMember("DeclTest")(5, 5), 5);
var element = document.createElement("div");
var callbackCount = 0;
var callback = function () {
callbackCount++;
};
WinJS.UI.process(element).then(callback);
LiveUnit.Assert.areEqual(1, callbackCount);
}
testCallbackBasicDeclarationWithProcessAllOnRootWithControl() {
LiveUnit.Assert.isTrue(WinJS.Utilities.getMember("DeclTest"));
LiveUnit.Assert.areEqual(WinJS.Utilities.getMember("DeclTest")(5, 5), 5);
var holder = document.createElement("div");
holder.innerHTML = "<div data-win-control='DeclTest' data-win-options='{test:123}'></div>";
var callbackCount = 0;
var callback = function () {
callbackCount++;
};
WinJS.UI.processAll(<Element>holder.firstChild).then(callback);
LiveUnit.Assert.areEqual(1, callbackCount);
var control = (<Element>holder.firstChild).winControl;
LiveUnit.Assert.areEqual(123, control.test);
}
testCallbackBasicDeclarationWithProcessAll() {
LiveUnit.Assert.isTrue(WinJS.Utilities.getMember("DeclTest"));
LiveUnit.Assert.areEqual(WinJS.Utilities.getMember("DeclTest")(5, 5), 5);
var holder = document.createElement("div");
holder.innerHTML = "<div data-win-control='DeclTest' data-win-options='{test:123}'></div><div data-win-control='DeclTest' data-win-options='{test:134}'></div>";
var callbackCount = 0;
var callback = function () {
callbackCount++;
};
WinJS.UI.processAll(holder).then(callback);
LiveUnit.Assert.areEqual(1, callbackCount);
var control = (<Element>holder.firstChild).winControl;
LiveUnit.Assert.areEqual(123, control.test);
control = (<Element>holder.lastChild).winControl;
LiveUnit.Assert.areEqual(134, control.test);
}
testCallbackBasicDeclarationWithProcessAllWithoutControls() {
LiveUnit.Assert.isTrue(WinJS.Utilities.getMember("DeclTest"));
LiveUnit.Assert.areEqual(WinJS.Utilities.getMember("DeclTest")(5, 5), 5);
var holder = document.createElement("div");
var callbackCount = 0;
var callback = function () {
callbackCount++;
};
WinJS.UI.processAll(holder).then(callback);
LiveUnit.Assert.areEqual(1, callbackCount);
}
testInvalidDeclaration() {
var holder = document.createElement("div");
holder.innerHTML = "<div data-win-control='NotDeclTest' data-win-options='{test:123}'></div>";
var hadException = false;
var control;
WinJS.UI.process(<Element>holder.firstChild).then(
function (c) { control = c; },
function (e) {
LiveUnit.Assert.areEqual("Invalid data-win-control attribute", e);
hadException = true;
});
LiveUnit.Assert.isFalse(hadException);
LiveUnit.Assert.areEqual(undefined, control);
}
testProcessAll() {
var holder = document.createElement("div");
holder.innerHTML = "<div data-win-control='DeclTest' data-win-options='{test:123}'></div>";
WinJS.UI.processAll(holder);
var control = (<Element>holder.firstChild).winControl;
LiveUnit.Assert.areEqual(123, control.test);
}
testOptions1() {
var holder = document.createElement("div");
holder.innerHTML = "<div data-win-control='DeclTest' data-win-options='{test1:\"blah blah blah\", test2:-55.22}'></div>";
WinJS.UI.processAll(holder);
var control = (<Element>holder.firstChild).winControl;
LiveUnit.Assert.areEqual("blah blah blah", control.test1);
LiveUnit.Assert.areEqual(-55.22, control.test2);
}
testOptions2() {
var holder = document.createElement("div");
window['blahblah'] = "Testing...";
holder.innerHTML = "<div data-win-control='DeclTest' data-win-options='{test1:blahblah, test2:true, test3: false}'></div>";
WinJS.UI.processAll(holder);
var control = (<Element>holder.firstChild).winControl;
LiveUnit.Assert.areEqual("Testing...", control.test1);
LiveUnit.Assert.areEqual(true, control.test2);
LiveUnit.Assert.areEqual(false, control.test3);
delete window['blahblah'];
}
testOptions3() {
var holder = document.createElement("div");
holder.innerHTML = "<div data-win-control='DeclTest' data-win-options='{\"test1 with spaces\":-42, \"test2 with spaces\":+53.6, \"test3 with spaces\": +.55}'></div>";
WinJS.UI.processAll(holder);
var control = (<Element>holder.firstChild).winControl;
LiveUnit.Assert.areEqual(-42, control["test1 with spaces"]);
LiveUnit.Assert.areEqual(53.6, control["test2 with spaces"]);
LiveUnit.Assert.areEqual(0.55, control["test3 with spaces"]);
}
testOptions4() {
var holder = document.createElement("div");
window['testOptions4Function'] = function () { };
// used in this test
WinJS.Utilities.markSupportedForProcessing(window['testOptions4Function']);
holder.innerHTML = "<div data-win-control='DeclTest' data-win-options='{test1:+55, test2:null, test3: testOptions4Function}'></div>";
WinJS.UI.processAll(holder);
var control = (<Element>holder.firstChild).winControl;
LiveUnit.Assert.areEqual(55, control.test1);
LiveUnit.Assert.areEqual(null, control.test2);
LiveUnit.Assert.areEqual(window['testOptions4Function'], control.test3);
delete window['testOptions4Function'];
}
testOptions5() {
var holder = document.createElement("div");
window['blahblah'] = "Testing...";
holder.innerHTML = "<div data-win-control='DeclTest' data-win-options=\"{ test1: blahblah, test3: 'false' }\"></div>";
WinJS.UI.processAll(holder);
var control = (<Element>holder.firstChild).winControl;
LiveUnit.Assert.areEqual("Testing...", control.test1);
LiveUnit.Assert.areEqual("false", control.test3);
delete window['blahblah'];
}
testOptions6() {
var holder = document.createElement("div");
window['blahblah'] = { a: 20, b: { c: 30, d: 40 } };
holder.innerHTML = "<div data-win-control='DeclTest' data-win-options=\"{ test1: blahblah, test2: blahblah.a, test3: blahblah.b.c, test4: blahblah.b.d }\"></div>";
WinJS.UI.processAll(holder);
var control = (<Element>holder.firstChild).winControl;
LiveUnit.Assert.areEqual(window['blahblah'], control.test1);
LiveUnit.Assert.areEqual(20, control.test2);
LiveUnit.Assert.areEqual(30, control.test3);
LiveUnit.Assert.areEqual(40, control.test4);
delete window['blahblah'];
}
testOptions8() {
var holder = document.createElement("div");
holder.innerHTML = "<div data-win-control='DeclTest' data-win-options=\"{ test1:function() { alert('foo'); } }\"></div>";
var hitCatch = false;
WinJS.UI.processAll(holder).then(null, function () { hitCatch = true; });
LiveUnit.Assert.isTrue(hitCatch);
}
testManyControls() {
var holder = document.createElement("div");
var control;
for (var i = 0; i < 1000; i++) {
control = document.createElement("div");
control.setAttribute("data-win-control", "DeclTest");
control.setAttribute("data-win-options", "{test:" + i + "}");
holder.appendChild(control);
}
WinJS.UI.processAll(holder);
for (i = 0; i < 1000; i++) {
control = holder.children[i].winControl;
LiveUnit.Assert.areEqual(i, control.test);
}
}
// Test an options with value/property of a long unicode string
testLocalizedOptions1() {
var holder = document.createElement("div");
holder.innerHTML = "<div data-win-control='DeclTest' data-win-options='{test1:\"\u624d\u80fd\u30bd\u042b\u2168\u84a4\u90f3\u0930\u094d\u0915\u094d\u0921\u094d\u0930\u093e\u00fc\u0131\u015f\u011f\u0130li\u064a\u0648\u0646\u064a\u0643\u0648\u062f\u00f6\u00c4\u00fc\u00df\u00a7\u624d\u80fd\u30bd\u042b\u2168\u84a4\u90f3\u0930\u094d\u0915\u094d\u0921\u094d\u0930\u093e\u00fc\u0131\u015f\u011f\u0130li\u064a\u0648\u0646\u064a\u0643\u0648\u062f\u00f6\u00c4\u00fc\u00df\u00a7Abcd123\", \u624d\u80fd\u30bd\u042b\u2168\u84a4\u90f3\u0930\u094d\u0915\u094d\u0921\u094d\u0930\u093e\u00fc\u0131\u015f\u011f\u0130li\u064a\u0648\u0646\u064a\u0643\u0648\u062f\u00f6\u00c4\u00fc\u00df\u00a7\u624d\u80fd\u30bd\u042b\u2168\u84a4\u90f3\u0930\u094d\u0915\u094d\u0921\u094d\u0930\u093e\u00fc\u0131\u015f\u011f\u0130li\u064a\u0648\u0646\u064a\u0643\u0648\u062f\u00f6\u00c4\u00fc\u00df\u00a7Abcd123:-55.22}'></div>";
WinJS.UI.processAll(holder);
var control = (<Element>holder.firstChild).winControl;
LiveUnit.Assert.areEqual("\u624d\u80fd\u30bd\u042b\u2168\u84a4\u90f3\u0930\u094d\u0915\u094d\u0921\u094d\u0930\u093e\u00fc\u0131\u015f\u011f\u0130li\u064a\u0648\u0646\u064a\u0643\u0648\u062f\u00f6\u00c4\u00fc\u00df\u00a7\u624d\u80fd\u30bd\u042b\u2168\u84a4\u90f3\u0930\u094d\u0915\u094d\u0921\u094d\u0930\u093e\u00fc\u0131\u015f\u011f\u0130li\u064a\u0648\u0646\u064a\u0643\u0648\u062f\u00f6\u00c4\u00fc\u00df\u00a7Abcd123", control.test1);
LiveUnit.Assert.areEqual(-55.22, control["\u624d\u80fd\u30bd\u042b\u2168\u84a4\u90f3\u0930\u094d\u0915\u094d\u0921\u094d\u0930\u093e\u00fc\u0131\u015f\u011f\u0130li\u064a\u0648\u0646\u064a\u0643\u0648\u062f\u00f6\u00c4\u00fc\u00df\u00a7\u624d\u80fd\u30bd\u042b\u2168\u84a4\u90f3\u0930\u094d\u0915\u094d\u0921\u094d\u0930\u093e\u00fc\u0131\u015f\u011f\u0130li\u064a\u0648\u0646\u064a\u0643\u0648\u062f\u00f6\u00c4\u00fc\u00df\u00a7Abcd123"], "Can't name option property something localized");
}
testLocalizedOptions2() {
var holder = document.createElement("div");
holder.innerHTML = "<div data-win-control='DeclTest' data-win-options='{test1:\u624d\u80fd\u30bd\u042b\u2168\u84a4\u90f3\u0930\u094d\u0915\u094d\u0921\u094d\u0930\u093e\u00fc\u0131\u015f\u011f\u0130li\u064a\u0648\u0646\u064a\u0643\u0648\u062f\u00f6\u00c4\u00fc\u00df\u00a7\u624d\u80fd\u30bd\u042b\u2168\u84a4\u90f3\u0930\u094d\u0915\u094d\u0921\u094d\u0930\u093e\u00fc\u0131\u015f\u011f\u0130li\u064a\u0648\u0646\u064a\u0643\u0648\u062f\u00f6\u00c4\u00fc\u00df\u00a7Abcd123, test2: \u624d\u80fd\u30bd\u042b\u2168\u84a4\u90f3\u0930\u094d\u0915\u094d\u0921\u094d\u0930\u093e\u00fc\u0131\u015f\u011f\u0130li\u064a\u0648\u0646\u064a\u0643\u0648\u062f\u00f6\u00c4\u00fc\u00df\u00a7\u624d\u80fd\u30bd\u042b\u2168\u84a4\u90f3\u0930\u094d\u0915\u094d\u0921\u094d\u0930\u093e\u00fc\u0131\u015f\u011f\u0130li\u064a\u0648\u0646\u064a\u0643\u0648\u062f\u00f6\u00c4\u00fc\u00df\u00a7Abcd123}'></div>";
WinJS.UI.processAll(holder);
var control = (<Element>holder.firstChild).winControl;
LiveUnit.Assert.areEqual(window["\u624d\u80fd\u30bd\u042b\u2168\u84a4\u90f3\u0930\u094d\u0915\u094d\u0921\u094d\u0930\u093e\u00fc\u0131\u015f\u011f\u0130li\u064a\u0648\u0646\u064a\u0643\u0648\u062f\u00f6\u00c4\u00fc\u00df\u00a7\u624d\u80fd\u30bd\u042b\u2168\u84a4\u90f3\u0930\u094d\u0915\u094d\u0921\u094d\u0930\u093e\u00fc\u0131\u015f\u011f\u0130li\u064a\u0648\u0646\u064a\u0643\u0648\u062f\u00f6\u00c4\u00fc\u00df\u00a7Abcd123"], control.test1);
LiveUnit.Assert.areEqual(window["\u624d\u80fd\u30bd\u042b\u2168\u84a4\u90f3\u0930\u094d\u0915\u094d\u0921\u094d\u0930\u093e\u00fc\u0131\u015f\u011f\u0130li\u064a\u0648\u0646\u064a\u0643\u0648\u062f\u00f6\u00c4\u00fc\u00df\u00a7\u624d\u80fd\u30bd\u042b\u2168\u84a4\u90f3\u0930\u094d\u0915\u094d\u0921\u094d\u0930\u093e\u00fc\u0131\u015f\u011f\u0130li\u064a\u0648\u0646\u064a\u0643\u0648\u062f\u00f6\u00c4\u00fc\u00df\u00a7Abcd123"], control.test2);
}
testControlDocumentFragment(complete) {
var holder = document.createElement("div");
holder.innerHTML = "<div data-win-control='DeclTest' data-win-options='{test:123}'></div>";
WinJS.UI.Fragments.clearCache(holder);
var frag = document.createElement("div");
WinJS.UI.Fragments.renderCopy(holder).then(function (docfrag) {
frag.appendChild(docfrag);
WinJS.UI.Fragments.clearCache(holder);
var docFrag = document.createDocumentFragment();
docFrag.appendChild(frag);
WinJS.UI.processAll(<any>docFrag);
var control = (<Element>docFrag.firstChild.firstChild).winControl;
LiveUnit.Assert.areEqual(123, control.test);
complete();
});
}
testControlFragment(complete) {
var holder = document.createElement("div");
holder.innerHTML = "<div data-win-control='DeclTest' data-win-options='{test:123}'></div>";
WinJS.UI.Fragments.clearCache(holder);
var frag = document.createElement("div");
WinJS.UI.Fragments.renderCopy(holder).then(function (docfrag) {
frag.appendChild(docfrag);
WinJS.UI.Fragments.clearCache(holder);
WinJS.UI.process(<Element>frag.firstChild);
var control = (<Element>frag.firstChild).winControl;
LiveUnit.Assert.areEqual(123, control.test);
complete();
});
}
testOptionQueryExpressionBasicNotFoundElement(complete) {
var holder = document.createElement("div");
document.body.appendChild(holder);
try {
holder.innerHTML = "<div data-win-control='DeclTest' data-win-options='{a: select(\".test\")}'></div>";
WinJS.UI.processAll(holder);
var control = (<Element>holder.firstChild).winControl;
LiveUnit.Assert.areEqual(null, control.a);
}
finally {
WinJS.Utilities.disposeSubTree(holder);
document.body.removeChild(holder);
complete();
}
}
testOptionQueryExpressionBasicFindElementById_LookupFromRoot_AtRootScope(complete) {
var testElement = document.createElement("div");
testElement.id = "test";
testElement.className = "root";
var holder = document.createElement("div");
document.body.appendChild(testElement);
document.body.appendChild(holder);
try {
holder.innerHTML = "<div data-win-control='DeclTest' data-win-options='{a: select(\"#test\")}'></div>";
WinJS.UI.processAll(holder);
var control = (<Element>holder.firstChild).winControl;
LiveUnit.Assert.areEqual("DIV", control.a.tagName);
LiveUnit.Assert.areEqual("test", control.a.id);
LiveUnit.Assert.areEqual("root", control.a.className);
}
finally {
WinJS.Utilities.disposeSubTree(holder);
WinJS.Utilities.disposeSubTree(testElement);
document.body.removeChild(testElement);
document.body.removeChild(holder);
complete();
}
}
testOptionQueryExpressionBasicFindElementById_LookupFromRoot_AtCurrentScope(complete) {
var holder = document.createElement("div");
document.body.appendChild(holder);
try {
holder.innerHTML = "<div data-win-control='DeclTest' data-win-options='{a: select(\"#test\")}'></div>";
var currentTestElement = document.createElement("div");
currentTestElement.id = "test";
currentTestElement.className = "current";
holder.appendChild(currentTestElement);
WinJS.UI.processAll(holder);
var control = (<Element>holder.firstChild).winControl;
LiveUnit.Assert.areEqual("DIV", control.a.tagName);
LiveUnit.Assert.areEqual("test", control.a.id);
LiveUnit.Assert.areEqual("current", control.a.className);
}
finally {
WinJS.Utilities.disposeSubTree(holder);
document.body.removeChild(holder);
complete();
}
}
testOptionQueryExpressionBasicFindElementByClass_LookupFromRoot(complete) {
//The one at root should be selected
var rootTestElement = document.createElement("div");
rootTestElement.className = "test";
rootTestElement.id = "root";
document.body.appendChild(rootTestElement);
var holder = document.createElement("div");
document.body.appendChild(holder);
try {
holder.innerHTML = "<div data-win-control='DeclTest' data-win-options='{a: select(\".test\")}'></div>";
var currentTestElement = document.createElement("div");
currentTestElement.className = "test";
currentTestElement.id = "current";
holder.appendChild(currentTestElement);
WinJS.UI.processAll(holder);
var control = (<Element>holder.firstChild).winControl;
LiveUnit.Assert.areEqual("DIV", control.a.tagName);
LiveUnit.Assert.areEqual("test", control.a.className);
LiveUnit.Assert.areEqual("root", control.a.id);
}
finally {
WinJS.Utilities.disposeSubTree(holder);
WinJS.Utilities.disposeSubTree(rootTestElement);
document.body.removeChild(holder);
document.body.removeChild(rootTestElement);
complete();
}
}
testOptionQueryExpressionBasicFindElementByClass_LookupFromParent(complete) {
//The one at root should be selected
var holderParentElement = document.createElement("div");
holderParentElement.className = "test";
holderParentElement.id = "parent";
document.body.appendChild(holderParentElement);
var holder = document.createElement("div");
holderParentElement.appendChild(holder);
try {
holder.innerHTML = "<div data-win-control='DeclTest' data-win-options='{a: select(\".test\")}'></div>";
var currentTestElement = document.createElement("div");
currentTestElement.className = "test";
currentTestElement.id = "current";
holder.appendChild(currentTestElement);
WinJS.UI.processAll(holder);
var control = (<Element>holder.firstChild).winControl;
LiveUnit.Assert.areEqual("DIV", control.a.tagName);
LiveUnit.Assert.areEqual("test", control.a.className);
LiveUnit.Assert.areEqual("parent", control.a.id);
}
finally {
WinJS.Utilities.disposeSubTree(holderParentElement);
document.body.removeChild(holderParentElement);
complete();
}
}
testOptionQueryExpressionBasicFindElementByClass_FragmentNotParented_LookupFromFragment(complete) {
var mainTreeTestElement = document.createElement("div");
mainTreeTestElement.className = "test";
mainTreeTestElement.id = "root";
document.body.appendChild(mainTreeTestElement);
var holder = document.createElement("div");
document.body.appendChild(holder);
var frag = document.createElement("div");
holder.innerHTML = "<div><div data-win-control='DeclTest' data-win-options='{a: select(\".test\")}'></div></div>";
var fragTestElement = document.createElement("div");
fragTestElement.className = "test";
fragTestElement.id = "fragment";
holder.appendChild(fragTestElement);
WinJS.UI.Fragments.clearCache(holder);
WinJS.UI.Fragments.renderCopy(holder)
.then(function (docfrag) {
frag.appendChild(docfrag);
WinJS.UI.Fragments.clearCache(holder);
document.body.appendChild(frag);
return WinJS.UI.processAll(document.body);
})
.then(function () {
var control = frag.querySelector("[data-win-control=DeclTest]").winControl;
LiveUnit.Assert.areEqual("DIV", control.a.tagName);
LiveUnit.Assert.areEqual("test", control.a.className);
LiveUnit.Assert.areEqual("fragment", control.a.id);
})
.then(null, errorHandler)
.then(function () {
WinJS.Utilities.disposeSubTree(mainTreeTestElement);
WinJS.Utilities.disposeSubTree(holder);
WinJS.Utilities.disposeSubTree(frag);
document.body.removeChild(mainTreeTestElement);
document.body.removeChild(holder);
document.body.removeChild(frag);
})
.then(complete);
}
testOptionQueryExpressionBasicFindElementByClass_FragmentParented_LookupFromFragment(complete) {
var mainTreeTestElement = document.createElement("div");
mainTreeTestElement.className = "test";
mainTreeTestElement.id = "root";
try {
var holder = document.createElement("div");
holder.innerHTML = "<div><div data-win-control='DeclTest' data-win-options='{a: select(\".test\")}'></div></div>";
var fragTestElement = document.createElement("div");
fragTestElement.className = "test";
fragTestElement.id = "fragment";
holder.appendChild(fragTestElement);
WinJS.UI.Fragments.clearCache(holder);
WinJS.UI.Fragments.renderCopy(holder, mainTreeTestElement);
document.body.appendChild(mainTreeTestElement);
WinJS.UI.processAll(document.body);
var control = (<Element>mainTreeTestElement.firstChild.firstChild).winControl;
LiveUnit.Assert.areEqual("DIV", control.a.tagName);
LiveUnit.Assert.areEqual("test", control.a.className);
LiveUnit.Assert.areEqual("root", control.a.id);
}
finally {
WinJS.Utilities.disposeSubTree(mainTreeTestElement);
document.body.removeChild(mainTreeTestElement);
complete();
}
}
testOptionQueryExpressionBasicFindElementByClass_LocalTemplate_LookupFromWithinTemplate(complete) {
var holder = document.createElement("div");
holder.innerHTML = "<div id='test'><div data-win-control='DeclTest' data-win-options='{a: select(\"#test\") }' data-win-bind=\"textContent: text\"></div></div>";
var data = { text: "sometext" };
var template = new WinJS.Binding.Template(holder);
template.render(data)
.then(function (d) {
LiveUnit.Assert.areEqual("sometext", d.textContent);
LiveUnit.Assert.areEqual("DIV", (<Element>d.firstChild.firstChild).winControl.a.tagName);
LiveUnit.Assert.areEqual("test", (<Element>d.firstChild.firstChild).winControl.a.id);
})
.then(null, errorHandler)
.then(complete);
}
testScopedSelect() {
var docfrag = document.createDocumentFragment();
var d = document.createElement("div");
docfrag.appendChild(d);
d.className = "root";
d.innerHTML = "<div class='myClass'><div class='element'>element</div></div><div class='myClass2'>myClass2</div>";
(<any>d.children[0]).msParentSelectorScope = true;
(<any>d.children[1]).msParentSelectorScope = true;
var element = <HTMLElement>d.querySelector(".element");
LiveUnit.Assert.areEqual(d.children[0], WinJS.UI.scopedSelect(".myClass", element));
LiveUnit.Assert.areEqual(d.children[1], WinJS.UI.scopedSelect(".myClass2", element));
LiveUnit.Assert.areEqual((<HTMLElement>d.children[0]).children[0], WinJS.UI.scopedSelect(".element", element));
LiveUnit.Assert.areEqual(d, WinJS.UI.scopedSelect(".root", element));
}
testRequireSupportedForProcessing_StrictProcessing() {
try {
var f = function () { };
WinJS.Utilities.requireSupportedForProcessing(f);
LiveUnit.Assert.fail("should not get here when strictProcessing");
} catch (e) {
LiveUnit.Assert.areEqual("WinJS.Utilities.requireSupportedForProcessing", e.name);
}
try {
var f2 = function () { };
WinJS.Utilities.markSupportedForProcessing(f2);
WinJS.Utilities.requireSupportedForProcessing(f2);
} catch (e) {
LiveUnit.Assert.fail("should not get here when strictProcessing");
}
}
testUsingNotSupportedForProcessingCtor_StrictProcessing(complete) {
var holder = document.createElement("div");
holder.innerHTML = "<div data-win-control='NotSupportedForProcessingControl' data-win-options='{ test: 123 }'></div>";
WinJS.UI.processAll(<Element>holder.firstChild).then(
function () {
LiveUnit.Assert.fail("should not get here when strictProcessing");
},
function (e) {
LiveUnit.Assert.areEqual("WinJS.Utilities.requireSupportedForProcessing", e.name);
}
)
.then(null, errorHandler)
.then(complete);
}
testUsingNotSupportedForProcessingValue_StrictProcessing(complete) {
var holder = document.createElement("div");
holder.innerHTML = "<div data-win-control='SupportedForProcessingControl' data-win-options='{ something: eval }'></div>";
WinJS.UI.processAll(<Element>holder.firstChild).then(
function () {
LiveUnit.Assert.fail("should not get here when strictProcessing");
},
function (e) {
LiveUnit.Assert.areEqual("WinJS.Utilities.requireSupportedForProcessing", e.name);
}
)
.then(null, errorHandler)
.then(complete);
}
testUsingWindow_StrictProcessing(complete) {
var holder = document.createElement("div");
holder.innerHTML = "<div data-win-control='SupportedForProcessingControl' data-win-options='{ something: window }'></div>";
WinJS.UI.processAll(<Element>holder.firstChild).then(
function () {
LiveUnit.Assert.fail("should not get here when strictProcessing");
},
function (e) {
LiveUnit.Assert.areEqual("WinJS.Utilities.requireSupportedForProcessing", e.name);
}
)
.then(null, errorHandler)
.then(complete);
}
};
}
LiveUnit.registerTestClass("CorsicaTests.DeclarativeControls"); | the_stack |
import { Injectable } from '@nestjs/common';
import { Model } from 'mongoose';
import { InjectModel } from '@nestjs/mongoose';
import { UserDocument, UserModel } from './schemas/user.schema';
import { CreateUserInput, UpdateUserInput } from '../graphql.classes';
import { randomBytes } from 'crypto';
import { createTransport, SendMailOptions } from 'nodemailer';
import { ConfigService } from '../config/config.service';
import { MongoError } from 'mongodb';
import { AuthService } from '../auth/auth.service';
@Injectable()
export class UsersService {
constructor(
@InjectModel('User') private readonly userModel: Model<UserDocument>,
private configService: ConfigService,
private authService: AuthService,
) {}
/**
* Returns if the user has 'admin' set on the permissions array
*
* @param {string[]} permissions permissions property on a User
* @returns {boolean}
* @memberof UsersService
*/
isAdmin(permissions: string[]): boolean {
return permissions.includes('admin');
}
/**
* Adds any permission string to the user's permissions array property. Checks if that value exists
* before adding it.
*
* @param {string} permission The permission to add to the user
* @param {string} username The user's username
* @returns {(Promise<UserDocument | undefined>)} The user Document with the updated permission. Undefined if the
* user does not exist
* @memberof UsersService
*/
async addPermission(
permission: string,
username: string,
): Promise<UserDocument | undefined> {
const user = await this.findOneByUsername(username);
if (!user) return undefined;
if (user.permissions.includes(permission)) return user;
user.permissions.push(permission);
await user.save();
return user;
}
/**
* Removes any permission string from the user's permissions array property.
*
* @param {string} permission The permission to remove from the user
* @param {string} username The username of the user to remove the permission from
* @returns {(Promise<UserDocument | undefined>)} Returns undefined if the user does not exist
* @memberof UsersService
*/
async removePermission(
permission: string,
username: string,
): Promise<UserDocument | undefined> {
const user = await this.findOneByUsername(username);
if (!user) return undefined;
user.permissions = user.permissions.filter(
userPermission => userPermission !== permission,
);
await user.save();
return user;
}
/**
* Updates a user in the database. If any value is invalid, it will still update the other
* fields of the user.
*
* @param {string} username of the user to update
* @param {UpdateUserInput} fieldsToUpdate The user can update their username, email, password, or enabled. If
* the username is updated, the user's token will no longer work. If the user disables their account, only an admin
* can reenable it
* @returns {(Promise<UserDocument | undefined>)} Returns undefined if the user cannot be found
* @memberof UsersService
*/
async update(
username: string,
fieldsToUpdate: UpdateUserInput,
): Promise<UserDocument | undefined> {
if (fieldsToUpdate.username) {
const duplicateUser = await this.findOneByUsername(
fieldsToUpdate.username,
);
if (duplicateUser) fieldsToUpdate.username = undefined;
}
if (fieldsToUpdate.email) {
const duplicateUser = await this.findOneByEmail(fieldsToUpdate.email);
const emailValid = UserModel.validateEmail(fieldsToUpdate.email);
if (duplicateUser || !emailValid) fieldsToUpdate.email = undefined;
}
const fields: any = {};
if (fieldsToUpdate.password) {
if (
await this.authService.validateUserByPassword({
username,
password: fieldsToUpdate.password.oldPassword,
})
) {
fields.password = fieldsToUpdate.password.newPassword;
}
}
// Remove undefined keys for update
for (const key in fieldsToUpdate) {
if (typeof fieldsToUpdate[key] !== 'undefined' && key !== 'password') {
fields[key] = fieldsToUpdate[key];
}
}
let user: UserDocument | undefined | null = null;
if (Object.entries(fieldsToUpdate).length > 0) {
user = await this.userModel.findOneAndUpdate(
{ lowercaseUsername: username.toLowerCase() },
fields,
{ new: true, runValidators: true },
);
} else {
user = await this.findOneByUsername(username);
}
if (!user) return undefined;
return user;
}
/**
* Send an email with a password reset code and sets the reset token and expiration on the user.
* EMAIL_ENABLED must be true for this to run.
*
* @param {string} email address associated with an account to reset
* @returns {Promise<boolean>} if an email was sent or not
* @memberof UsersService
*/
async forgotPassword(email: string): Promise<boolean> {
if (!this.configService.emailEnabled) return false;
const user = await this.findOneByEmail(email);
if (!user) return false;
if (!user.enabled) return false;
const token = randomBytes(32).toString('hex');
// One day for expiration of reset token
const expiration = new Date(Date().valueOf() + 24 * 60 * 60 * 1000);
const transporter = createTransport({
service: this.configService.emailService,
auth: {
user: this.configService.emailUsername,
pass: this.configService.emailPassword,
},
});
const mailOptions: SendMailOptions = {
from: this.configService.emailFrom,
to: email,
subject: `Reset Password`,
text: `${user.username},
Replace this with a website that can pass the token:
${token}`,
};
return new Promise(resolve => {
transporter.sendMail(mailOptions, (err, info) => {
if (err) {
resolve(false);
return;
}
user.passwordReset = {
token,
expiration,
};
user.save().then(
() => resolve(true),
() => resolve(false),
);
});
});
}
/**
* Resets a password after the user forgot their password and requested a reset
*
* @param {string} username
* @param {string} code the token set when the password reset email was sent out
* @param {string} password the new password the user wants
* @returns {(Promise<UserDocument | undefined>)} Returns undefined if the code or the username is wrong
* @memberof UsersService
*/
async resetPassword(
username: string,
code: string,
password: string,
): Promise<UserDocument | undefined> {
const user = await this.findOneByUsername(username);
if (user && user.passwordReset && user.enabled !== false) {
if (user.passwordReset.token === code) {
user.password = password;
user.passwordReset = undefined;
await user.save();
return user;
}
}
return undefined;
}
/**
* Creates a user
*
* @param {CreateUserInput} createUserInput username, email, and password. Username and email must be
* unique, will throw an email with a description if either are duplicates
* @returns {Promise<UserDocument>} or throws an error
* @memberof UsersService
*/
async create(createUserInput: CreateUserInput): Promise<UserDocument> {
const createdUser = new this.userModel(createUserInput);
let user: UserDocument | undefined;
try {
user = await createdUser.save();
} catch (error) {
throw this.evaluateMongoError(error, createUserInput);
}
return user;
}
/**
* Returns a user by their unique email address or undefined
*
* @param {string} email address of user, not case sensitive
* @returns {(Promise<UserDocument | undefined>)}
* @memberof UsersService
*/
async findOneByEmail(email: string): Promise<UserDocument | undefined> {
const user = await this.userModel
.findOne({ lowercaseEmail: email.toLowerCase() })
.exec();
if (user) return user;
return undefined;
}
/**
* Returns a user by their unique username or undefined
*
* @param {string} username of user, not case sensitive
* @returns {(Promise<UserDocument | undefined>)}
* @memberof UsersService
*/
async findOneByUsername(username: string): Promise<UserDocument | undefined> {
const user = await this.userModel
.findOne({ lowercaseUsername: username.toLowerCase() })
.exec();
if (user) return user;
return undefined;
}
/**
* Gets all the users that are registered
*
* @returns {Promise<UserDocument[]>}
* @memberof UsersService
*/
async getAllUsers(): Promise<UserDocument[]> {
const users = await this.userModel.find().exec();
return users;
}
/**
* Deletes all the users in the database, used for testing
*
* @returns {Promise<void>}
* @memberof UsersService
*/
async deleteAllUsers(): Promise<void> {
await this.userModel.deleteMany({});
}
/**
* Reads a mongo database error and attempts to provide a better error message. If
* it is unable to produce a better error message, returns the original error message.
*
* @private
* @param {MongoError} error
* @param {CreateUserInput} createUserInput
* @returns {Error}
* @memberof UsersService
*/
private evaluateMongoError(
error: MongoError,
createUserInput: CreateUserInput,
): Error {
if (error.code === 11000) {
if (
error.message
.toLowerCase()
.includes(createUserInput.email.toLowerCase())
) {
throw new Error(
`e-mail ${createUserInput.email} is already registered`,
);
} else if (
error.message
.toLowerCase()
.includes(createUserInput.username.toLowerCase())
) {
throw new Error(
`Username ${createUserInput.username} is already registered`,
);
}
}
throw new Error(error.message);
}
} | the_stack |
import * as https from 'https';
import { Readable } from 'stream';
import { createGunzip } from 'zlib';
import { metricScope, Configuration, Unit } from 'aws-embedded-metrics';
import type { AWSError, S3 } from 'aws-sdk';
import * as JSONStream from 'JSONStream';
import { CatalogModel } from '../../../backend';
import * as aws from '../../../backend/shared/aws.lambda-shared';
import { requireEnv } from '../../../backend/shared/env.lambda-shared';
import { METRICS_NAMESPACE, MetricName, Environment, ObjectKey } from './constants';
Configuration.namespace = METRICS_NAMESPACE;
/**
* This package canary monitors the availability of the versions of a specified
* package in the ConstructHub catalog. It publishes metrics that help
* understand how much time passes between a pakcage appearing in the public
* registry and it's availability in the ConstructHub instance.
*
* From the moment a package has been published, and until it appeared in
* catalog, the `MetricName.DWELL_TIME` metric is emitted.
*
* Once the package has appeared in catalog, and until a new package version is
* identified in npmjs.com, the `MetricName.TIME_TO_CATALOG` metric is emitted.
*
* If a new package version is published before the previous one has appeared
* in catalog, both versions will be tracked at the same time, and the metrics
* will receive one sample per tracked version.
*/
export async function handler(event: unknown): Promise<void> {
console.log(`Event: ${JSON.stringify(event, null, 2)}`);
const packageName = requireEnv(Environment.PACKAGE_NAME);
const stateBucket = requireEnv(Environment.PACKAGE_CANARY_BUCKET_NAME);
const constructHubEndpoint = requireEnv(Environment.CONSTRUCT_HUB_BASE_URL);
const stateService = new CanaryStateService(stateBucket);
const constructHub = new ConstructHub(constructHubEndpoint);
const latest = await stateService.latest(packageName);
const state: CanaryState = await stateService.load(packageName)
// If we did not have any state, we'll bootstrap using the current latest version.
?? {
latest: {
...latest,
// If that latest version is ALREADY in catalog, pretend it was
// "instantaneously" there, so we avoid possibly reporting an breach of
// SLA alarm, when we really just observed presence of the package in
// catalog too late, for example on first deployment of the canary.
availableAt: await constructHub.isInCatalog(packageName, latest.version)
? latest.publishedAt
: undefined,
},
pending: {},
};
console.log(`Initial state: ${JSON.stringify(state, null, 2)}`);
// If the current "latest" isn't the one from state, it needs updating.
updateLatestIfNeeded(state, latest);
try {
await metricScope((metrics) => () => {
// Clear out default dimensions as we don't need those. See https://github.com/awslabs/aws-embedded-metrics-node/issues/73.
metrics.setDimensions();
metrics.putMetric(MetricName.TRACKED_VERSION_COUNT, Object.keys(state.pending).length + 1, Unit.Count);
})();
for (const versionState of [state.latest, ...Object.values(state.pending ?? {})]) {
console.log(`Checking state of ${versionState.version}, current: ${JSON.stringify(versionState, null, 2)}`);
await metricScope((metrics) => async () => {
// Clear out default dimensions as we don't need those. See https://github.com/awslabs/aws-embedded-metrics-node/issues/73.
metrics.setDimensions();
metrics.setProperty('PackageName', packageName);
metrics.setProperty('PackageVersion', versionState.version);
metrics.setProperty('IsLatest', state.latest.version === versionState.version);
if (!versionState.availableAt) {
if (versionState.version === state.latest.version) {
if (await constructHub.isInCatalog(packageName, versionState.version)) {
versionState.availableAt = new Date();
}
} else {
// Non-current versions will probably never make it to catalog (they're older than the
// current version), so instead, we check whether they have TypeScript documentation.
if (await constructHub.hasTypeScriptDocumentation(packageName, versionState.version)) {
versionState.availableAt = new Date();
}
}
}
if (versionState.availableAt) {
// Tells us how long it's taken for the package to make it to catalog after it was published.
metrics.putMetric(
MetricName.TIME_TO_CATALOG,
(versionState.availableAt.getTime() - versionState.publishedAt.getTime()) / 1_000,
Unit.Seconds,
);
// Stop tracking that version, as it's now available.
if (versionState.version in state.pending) {
delete state.pending[versionState.version];
}
} else {
// Tells us how long we've been waiting for this version to show up, so far.
metrics.putMetric(
MetricName.DWELL_TIME,
(Date.now() - versionState.publishedAt.getTime()) / 1_000,
Unit.Seconds,
);
}
})();
}
} finally {
await stateService.save(packageName, state);
}
}
class ConstructHub {
#catalog?: CatalogModel;
constructor(private readonly baseUrl: string) {}
/**
* Determines whether the specified package version is present in the catalog
* object or not.
*
* @param packageName the name of the checked package.
* @param packageVersion the version of the checked package.
*
* @returns `true` IIF the exact package version is found in the catalog.
*/
public async isInCatalog(packageName: string, packageVersion: string): Promise<boolean> {
const catalog = await this.getCatalog();
const filtered = catalog.packages.filter((p: any) => p.name === packageName && p.version === packageVersion);
if (filtered.length > 1) {
throw new Error(`Found multiple entries for ${packageName}@${packageVersion} in catalog`);
}
return filtered.length === 1;
}
/**
* Checks whether TypeScript documentation exists in ConstructHub for the
* specified package version.
*
* @param packageName the name of the checked package.
* @param packageVersion the version of the checked package.
*
* @returns `true` IIF the `docs-typescript.md` document exists for the
* specified package.
*/
public async hasTypeScriptDocumentation(packageName: string, packageVersion: string): Promise<boolean> {
return new Promise((ok, ko) => {
const url = `${this.baseUrl}/data/${packageName}/v${packageVersion}/docs-typescript.md`;
https.request(
url,
{ method: 'HEAD' },
(res) => {
if (res.statusCode === 200) {
// This returns HTTP 200 with text/html if it's a 404, due to how
// we configured CloudFront behaviors.
return ok(!!res.headers['content-type']?.startsWith('text/markdown'));
}
const err = new Error(`HEAD ${url} -- HTTP ${res.statusCode} (${res.statusMessage})`);
Error.captureStackTrace(err);
ko(err);
},
).end();
});
}
private async getCatalog(): Promise<CatalogModel> {
if (this.#catalog) {
return this.#catalog;
}
return this.#catalog = await getJSON(`${this.baseUrl}/catalog.json`);
}
}
class CanaryStateService {
constructor(private readonly bucketName: string) {}
/**
* Save the state to the bucket.
*/
public async save(packageName: string, state: CanaryState) {
const url = this.url(packageName);
console.log(`Saving to ${url}: ${JSON.stringify(state, null, 2)}`);
await aws.s3().putObject({
Bucket: this.bucketName,
Key: this.key(packageName),
Body: JSON.stringify(state, null, 2),
ContentType: 'application/json',
}).promise();
}
/**
* Load the state file for this package from the bucket.
*/
public async load(packageName: string): Promise<CanaryState | undefined> {
console.log(`Loading state for package '${packageName}'`);
const objectKey = this.key(packageName);
const url = this.url(packageName);
console.log(`Fetching: ${url}`);
const data = await aws.s3().getObject({ Bucket: this.bucketName, Key: objectKey }).promise()
.catch((err: AWSError) => err.code !== 'NoSuchKey'
? Promise.reject(err)
: Promise.resolve({ /* no data */ } as S3.GetObjectOutput));
if (!data?.Body) {
console.log(`Not found: ${url}`);
return undefined;
}
console.log(`Loaded: ${url}`);
return JSON.parse(data.Body.toString('utf-8'), (key, value) => {
if (key === 'publishedAt' || key === 'availableAt') {
return new Date(value);
}
return value;
});
}
/**
* Create a state from the latest version of the package.
*/
public async latest(packageName: string): Promise<CanaryState['latest']> {
console.log(`Fetching latest version information from NPM: ${packageName}`);
const version = await getJSON(`https://registry.npmjs.org/${encodeURIComponent(packageName)}/latest`, ['version']);
const publishedAt = await getJSON(`https://registry.npmjs.org/${encodeURIComponent(packageName)}`, ['time', version]);
console.log(`Package: ${packageName} | Version : ${version} | Published At: ${publishedAt}`);
return { version, publishedAt: new Date(publishedAt) };
}
private key(packageName: string): string {
return `${ObjectKey.STATE_PREFIX}${packageName}${ObjectKey.STATE_SUFFIX}`;
}
private url(packageName: string) {
return `s3://${this.bucketName}/${this.key(packageName)}`;
}
}
interface CanaryState {
/**
* The latest package version, as of the last execution of the canary.
*/
latest: {
/**
* The version we are tracking.
*/
readonly version: string;
/**
* The publish date of the version.
*/
readonly publishedAt: Date;
/**
* The date at which the version is available on the hub.
*/
availableAt?: Date;
};
/**
* Each existing, but not-yet-found versions that are still tracked.
*/
pending: {
[version: string]: {
/**
* The version we are tracking.
*/
readonly version: string;
/**
* The publish date of the version.
*/
readonly publishedAt: Date;
/**
* These pending packages are NEVER available at this point.
*/
availableAt: undefined;
};
};
}
/**
* Makes a request to the provided URL and returns the response after having
* parsed it from JSON.
*
* @param url the URL to get.
* @param jsonPath a JSON path to extract only a subset of the object.
*/
function getJSON(url: string, jsonPath?: string[]): Promise<any> {
return new Promise((ok, ko) => {
https.get(url, { headers: { 'Accept': 'application/json', 'Accept-Encoding': 'identity' } }, (res) => {
if (res.statusCode !== 200) {
const error = new Error(`GET ${url} - HTTP ${res.statusCode} (${res.statusMessage})`);
Error.captureStackTrace(error);
return ko(error);
}
res.once('error', ko);
const json = JSONStream.parse(jsonPath);
json.once('data', ok);
json.once('error', ko);
const plainPayload = res.headers['content-encoding'] === 'gzip' ? gunzip(res) : res;
plainPayload.pipe(json, { end: true });
});
});
}
/**
* Updates the `latest` property of `state` ti the provided `latest` value,
* unless this is already the current latest.
*
* If the previous latest version does not have the `availableAt` property, adds
* that to the `pending` set.
*
* @param state the state to be updated.
* @param latest the current "latest" version of the tracked package.
*/
function updateLatestIfNeeded(state: CanaryState, latest: CanaryState['latest']): void {
if (state.latest.version === latest.version) {
return;
}
// If the current "latest" isn't available yet, add it to the `pending` versions.
if (state.latest.availableAt == null) {
// The TypeScript version of jsii doesn't do control flow analysis well enough here to
// determine that the`if` branch guarantees `availableAt` is undefined here.
state.pending[state.latest.version] = { ...state.latest, availableAt: undefined };
}
state.latest = latest;
}
function gunzip(readable: Readable): Readable {
const gz = createGunzip();
readable.pipe(gz, { end: true });
return gz;
} | the_stack |
/// <reference path="../../../jqwidgets-ts/jqwidgets.d.ts" />
function createRibbon(
selector, fileItemButton, saveButton, saveAsButton, openButton, closeButton, exitButton,
subscriptButton, superscriptButton, boldButton, italicButton, underlineButton, strikethroughButton,
shrinkFontButton, copyButton, cutButton, growFontButton, formatPainterButton, clearFormattingButton, alignLeftButton, alignCenterButton, alignRightButton, alignJustifyButton, bulletListButton, numberedListButton, decreaseIndentButton, increaseIndentButton, sortButton, lineSpacingButton, showHideButton,
bucketColorButton, bucketColorPickerButton, fontButton, fontSizeButton,
changeCaseButton, fontColorButton, fontColorPickerButton, highlightColorButton, highlightColorPickerButton, pasteButton, pasteDropDownButton,
helpButton, aboutButton, updateButton,
gridSelector
)
{
var theme = 'demoTheme';
var fileItemButtonOptions: jqwidgets.DropDownButtonOptions = {
arrowSize: 0,
height: 26,
dropDownWidth: 120,
width: 50,
theme: theme
};
var fileItem: jqwidgets.jqxDropDownButton = jqwidgets.createInstance(fileItemButton, 'jqxDropDownButton', fileItemButtonOptions);
fileItem.setContent('<span style="position: relative; line-height: 26px; margin-left:10px;">File</span>');
var buttonsOptions: jqwidgets.ButtonOptions = { theme: theme };
function createButtonInstances(selectorName, jqxButtonType, options)
{
jqxButtonType = jqxButtonType || 'jqxButton';
var button: jqwidgets.jqxButton = jqwidgets.createInstance(selectorName, jqxButtonType, buttonsOptions);
return button;
}
// Create instances for buttons
var normalType = 'jqxButton';
var save = createButtonInstances(saveButton, normalType, buttonsOptions),
saveAs = createButtonInstances(saveAsButton, normalType, buttonsOptions),
open = createButtonInstances(openButton, normalType, buttonsOptions),
close = createButtonInstances(closeButton, normalType, buttonsOptions);
//exit = createButtonInstances(exitButton, buttonsOptions);
// initialization options - validated in typescript
// jqwidgets.RibbonOptions has generated TS definition
var options: jqwidgets.RibbonOptions = {
width: 802,
height: 131,
animationType: "none",
selectionMode: "click",
position: "top",
theme: "demoTheme",
mode: "default",
selectedIndex: 1,
initContent: function (item)
{
switch (item)
{
case 0:
break;
case 1:
var toggleButtonsOptions: jqwidgets.ButtonOptions = { theme: theme };
// Create ToggleButtons
var toggleType = 'jqxToggleButton';
var subscript = createButtonInstances(subscriptButton, toggleType, toggleButtonsOptions),
superscript = createButtonInstances(superscriptButton, toggleType, toggleButtonsOptions),
bold = createButtonInstances(boldButton, toggleType, toggleButtonsOptions),
italic = createButtonInstances(italicButton, toggleType, toggleButtonsOptions),
underline = createButtonInstances(underlineButton, toggleType, toggleButtonsOptions),
strikethrough = createButtonInstances(strikethroughButton, toggleType, toggleButtonsOptions);
var innerButtonsOptions: jqwidgets.ButtonOptions = { theme: theme };
var shrinkFont = createButtonInstances(shrinkFontButton, normalType, innerButtonsOptions),
copy = createButtonInstances(copyButton, normalType, innerButtonsOptions),
cut = createButtonInstances(cutButton, normalType, innerButtonsOptions),
growFont = createButtonInstances(growFontButton, normalType, innerButtonsOptions),
formatPainter = createButtonInstances(formatPainterButton, normalType, innerButtonsOptions),
clearFormatting = createButtonInstances(clearFormattingButton, normalType, innerButtonsOptions),
alignLeft = createButtonInstances(alignLeftButton, normalType, innerButtonsOptions),
alignCenter = createButtonInstances(alignCenterButton, normalType, innerButtonsOptions),
alignRight = createButtonInstances(alignRightButton, normalType, innerButtonsOptions),
alignJustify = createButtonInstances(alignJustifyButton, normalType, innerButtonsOptions),
bulletList = createButtonInstances(bulletListButton, normalType, innerButtonsOptions),
numberedList = createButtonInstances(numberedListButton, normalType, innerButtonsOptions),
decreaseIndent = createButtonInstances(decreaseIndentButton, normalType, innerButtonsOptions),
increaseIndent = createButtonInstances(increaseIndentButton, normalType, innerButtonsOptions),
sort = createButtonInstances(sortButton, normalType, innerButtonsOptions),
lineSpacing = createButtonInstances(lineSpacingButton, normalType, innerButtonsOptions),
showHide = createButtonInstances(showHideButton, normalType, innerButtonsOptions);
var tooltipsOptions: jqwidgets.TooltipOptions = {
position: "mouse",
content: "Cut (Ctrl + X)"
};
var cutTooltip: jqwidgets.jqxTooltip = jqwidgets.createInstance(cutButton, 'jqxTooltip', tooltipsOptions);
tooltipsOptions.content = "Copy (Ctrl + C)";
var copyTooltip: jqwidgets.jqxTooltip = jqwidgets.createInstance(copyButton, 'jqxTooltip', tooltipsOptions);
tooltipsOptions.content = "Subscript";
var subscriptTooltip: jqwidgets.jqxTooltip = jqwidgets.createInstance(subscriptButton, 'jqxTooltip', tooltipsOptions);
tooltipsOptions.content = "Superscript";
var subscriptTooltip: jqwidgets.jqxTooltip = jqwidgets.createInstance(superscriptButton, 'jqxTooltip', tooltipsOptions);
tooltipsOptions.content = "Bold (Ctrl + B)";
var boldTooltip: jqwidgets.jqxTooltip = jqwidgets.createInstance(boldButton, 'jqxTooltip', tooltipsOptions);
tooltipsOptions.content = "Italic (Ctrl + I)";
var italicTooltip: jqwidgets.jqxTooltip = jqwidgets.createInstance(italicButton, 'jqxTooltip', tooltipsOptions);
tooltipsOptions.content = "Underline (Ctrl + U)";
var underlineTooltip: jqwidgets.jqxTooltip = jqwidgets.createInstance(underlineButton, 'jqxTooltip', tooltipsOptions);
tooltipsOptions.content = "Strikethrough";
var underlineTooltip: jqwidgets.jqxTooltip = jqwidgets.createInstance(underlineButton, 'jqxTooltip', tooltipsOptions);
tooltipsOptions.content = "Align Text Left (Ctrl + L)";
var alignLeftTooltip: jqwidgets.jqxTooltip = jqwidgets.createInstance(underlineButton, 'jqxTooltip', tooltipsOptions);
tooltipsOptions.content = "Center (Ctrl + E)";
var alignCenterTooltip: jqwidgets.jqxTooltip = jqwidgets.createInstance(alignCenterButton, 'jqxTooltip', tooltipsOptions);
tooltipsOptions.content = "Align Text Right (Ctrl + R)";
var alignRightTooltip: jqwidgets.jqxTooltip = jqwidgets.createInstance(alignRightButton, 'jqxTooltip', tooltipsOptions);
tooltipsOptions.content = "Align Text Right (Ctrl + R)";
var alignRightTooltip: jqwidgets.jqxTooltip = jqwidgets.createInstance(alignRightButton, 'jqxTooltip', tooltipsOptions);
tooltipsOptions.content = "Bulleted List";
var bulletListTooltip: jqwidgets.jqxTooltip = jqwidgets.createInstance(bulletListButton, 'jqxTooltip', tooltipsOptions);
tooltipsOptions.content = "Numbered List";
var numberedListTooltip: jqwidgets.jqxTooltip = jqwidgets.createInstance(numberedListButton, 'jqxTooltip', tooltipsOptions);
tooltipsOptions.content = "Decrease Indent";
var decreaseIndentTooltip: jqwidgets.jqxTooltip = jqwidgets.createInstance(decreaseIndentButton, 'jqxTooltip', tooltipsOptions);
tooltipsOptions.content = "Increase Indent";
var increaseIndentTooltip: jqwidgets.jqxTooltip = jqwidgets.createInstance(increaseIndentButton, 'jqxTooltip', tooltipsOptions);
tooltipsOptions.content = "Sort Direction";
var sortTooltip: jqwidgets.jqxTooltip = jqwidgets.createInstance(sortButton, 'jqxTooltip', tooltipsOptions);
tooltipsOptions.content = "Line and Paragraph Spacing";
var lineSpacingTooltip: jqwidgets.jqxTooltip = jqwidgets.createInstance(lineSpacingButton, 'jqxTooltip', tooltipsOptions);
tooltipsOptions.content = "Show/Hide special characters";
var showHideTooltip: jqwidgets.jqxTooltip = jqwidgets.createInstance(showHideButton, 'jqxTooltip', tooltipsOptions);
tooltipsOptions.content = "Fill style";
tooltipsOptions.theme = theme;
var bucketColorTooltip: jqwidgets.jqxTooltip = jqwidgets.createInstance(bucketColorButton, 'jqxTooltip', tooltipsOptions);
var bucketColorOptions: jqwidgets.DropDownButtonOptions = {
width: 42,
theme: theme,
dropDownWidth: 180,
height: 19,
initContent: function ()
{
var bucketColorPickerOptions: jqwidgets.ColorPickerOptions = {
color: "000000",
colorMode: 'hue',
width: 180,
height: 180
};
var bucketColorPicker: jqwidgets.jqxColorPicker = jqwidgets.createInstance(bucketColorPickerButton, 'jqxColorPicker', bucketColorPickerOptions);
bucketColorPicker.addEventHandler('colorchange', function (event)
{
var bucketColorPickerPreview = document.getElementById('bucketColorPreview');
bucketColorPickerPreview.style.background = '#' + event.args.color.hex;
});
}
};
var bucketColor: jqwidgets.jqxDropDownButton = jqwidgets.createInstance(bucketColorButton, 'jqxDropDownButton', bucketColorOptions);
bucketColor.setContent('<div id="pickColor"><span style="position:relative; display:inline-block; top: 2px"><div class="icon paintcan"></div><span id="bucketColorPreview" style="display: block; position:absolute; height: 3px; width: 16px; background:#000"></span></span></div>');
var fontOptions: jqwidgets.DropDownListOptions = {
source: [
"<span style='font-family: Courier New;'>Courier New</span>",
"<span style='font-family: Times New Roman;'>Times New Roman</span>",
"<span style='font-family: Arial;'>Arial</span>"
],
width: 120,
height: 21,
theme: 'demoTheme',
autoDropDownHeight: true,
selectedIndex: 1
};
var font: jqwidgets.jqxDropDownList = jqwidgets.createInstance(fontButton, 'jqxDropDownList', fontOptions);
var fontSizeOptions: jqwidgets.DropDownListOptions = {
source: [8, 9, 10, 11, 12, 14, 18, 20, 22, 24],
theme: 'demoTheme',
renderer: function (index, label, value)
{
return '<span style="font-size:' + value + 'px;">' + value + '</span>';
},
width: 70, height: 21, autoDropDownHeight: true, selectedIndex: 2
};
var fontSize: jqwidgets.jqxDropDownList = jqwidgets.createInstance(fontSizeButton, 'jqxDropDownList', fontSizeOptions);
var subscriptDom = document.getElementById(subscriptButton.substr(1));
subscriptDom.addEventListener('click', function ()
{
if (superscript.toggled)
{
superscript.toggle();
}
});
var superscriptDom = document.getElementById(superscriptButton.substr(1));
superscriptDom.addEventListener('click', function ()
{
if (subscript.toggled)
{
subscript.toggle();
}
});
var changeCaseOptions: jqwidgets.DropDownListOptions = {
source: ['Sentence Case', 'lowercase', 'UPPERCASE', 'Capitalize Each Word'],
theme: 'demoTheme',
selectionRenderer: function (object, index, label)
{
return '<div class="icon change-case-16" style="top:3px; position:relative"></div>';
},
dropDownWidth: 150,
autoDropDownHeight: true, selectedIndex: 0, width: 40
};
var changeCase: jqwidgets.jqxDropDownList = jqwidgets.createInstance(changeCaseButton, 'jqxDropDownList', changeCaseOptions);
var fontColorOptions: jqwidgets.DropDownButtonOptions = {
width: 100,
theme: 'demoTheme',
dropDownWidth: 180,
height: 21,
initContent: function ()
{
var fontColorPickerOptions: jqwidgets.ColorPickerOptions = {
color: "000000",
colorMode: 'hue',
width: 180,
height: 180
};
var fontColorPicker: jqwidgets.jqxColorPicker = jqwidgets.createInstance(fontColorPickerButton, 'jqxColorPicker', fontColorPickerOptions);
fontColorPicker.addEventHandler('colorchange', function (event)
{
var fontColorPreview = document.getElementById('fontColorPreview');
fontColorPreview.style.background = '#' + event.args.color.hex;
});
}
};
var fontColor: jqwidgets.jqxDropDownButton = jqwidgets.createInstance(fontColorButton, 'jqxDropDownButton', fontColorOptions);
fontColor.setContent('<span style="position:relative; display:inline; top: 2px"><div class="icon FontDialogImage"></div><span id="fontColorPreview" style="display: block; position:absolute; height: 3px; width: 16px; background:#000"></span></span><span style="position:relative; display: inline; top:3px">Font Color</span>');
var highlightColorOptions: jqwidgets.DropDownButtonOptions = {
width: 130,
dropDownWidth: 180,
theme: 'demoTheme',
height: 21,
initContent: function ()
{
var highlightColorPickerOptions: jqwidgets.ColorPickerOptions = {
color: "FF0000",
colorMode: 'hue',
width: 180,
height: 180
};
var highlightColorPicker: jqwidgets.jqxColorPicker = jqwidgets.createInstance(highlightColorPickerButton, 'jqxColorPicker', highlightColorPickerOptions);
highlightColorPicker.addEventHandler('colorchange', function (event)
{
var highlightColorPreview = document.getElementById('highlightColorPreview');
highlightColorPreview.style.background = '#' + event.args.color.hex;
});
}
};
var highlightColor: jqwidgets.jqxDropDownButton = jqwidgets.createInstance(highlightColorButton, 'jqxDropDownButton', highlightColorOptions);
highlightColor.setContent('<span style="position:relative; display:inline; top: 2px"><div class="icon pencil"></div><span id="highlightColorPreview" style="display: block; position:absolute; height: 3px; width: 16px; background:#F00"></span></span><span style="position:relative; display: inline; top:3px">Highlight Color</span>');
var pasteData = [
{ label: 'Paste', imageClass: 'icon page_paste' },
{ label: 'Paste Special', imageClass: 'icon paste_plain' },
{ label: 'Paste text', imageClass: 'icon paste_word' },
{ label: 'Paste link', imageClass: 'icon PasteImage' }
];
var pasteButtonOptions: jqwidgets.ButtonOptions = {
width: 35,
theme: 'demoTheme',
height: 56
};
var paste: jqwidgets.jqxButton = jqwidgets.createInstance(pasteButton, 'jqxButton', pasteButtonOptions);
paste.addEventHandler('click', function (event)
{
var text = this.getElementsByClassName('pasteText')[0].innerHTML;
console.log(text + ' clicked');
});
paste.addEventHandler('mousedown', function (event)
{
event.preventDefault();
});
var pasteDropDownOptions: jqwidgets.DropDownListOptions = {
source: pasteData,
width: 22,
height: 10,
animationType: 'none',
dropDownWidth: '110px',
autoDropDownHeight: true,
renderer: function (index: number, label, value)
{
var labelEl = '<span style="font-size: 10px">' + label + '</span>';
var icon = '<span class="' + pasteData[index].imageClass + '" style=""></span>';
return '<span>' + icon + labelEl + '</span>';
},
selectionRenderer: function (object, index, label)
{
return "";
},
selectedIndex: 0
};
var pasteDropDown: jqwidgets.jqxDropDownList = jqwidgets.createInstance(pasteDropDownButton, 'jqxDropDownList', pasteDropDownOptions);
pasteDropDown.addEventHandler('select', function (event)
{
var index = event.args.index;
var icon = '<span class="' + pasteData[index].imageClass + '" style="zoom: 1.5"></span>';
var pasteButtonDom = document.getElementById(pasteButton.substr(1));
pasteButtonDom.innerHTML = icon + '<span class="pasteText">' + pasteData[index].label + '</span>';
paste.render();
});
break;
case 2:
var helpAboutUpdateOptions: jqwidgets.ButtonOptions = { width: 26, height: 26, theme: 'demoTheme' };
var help: jqwidgets.jqxButton = jqwidgets.createInstance(helpButton, 'jqxButton', helpAboutUpdateOptions);
var about: jqwidgets.jqxButton = jqwidgets.createInstance(aboutButton, 'jqxButton', helpAboutUpdateOptions);
var update: jqwidgets.jqxButton = jqwidgets.createInstance(updateButton, 'jqxButton', helpAboutUpdateOptions);
break;
}
}
};
// creates an instance
var myRibbon: jqwidgets.jqxRibbon = jqwidgets.createInstance(selector, 'jqxRibbon', options);
myRibbon.disableAt(0);
// jqxGrid code
// renderer for grid cells.
var numberrenderer = function (row:number, column:string, value:any):string
{
return '<div style="text-align: center; margin-top: 5px;">' + (1 + value) + '</div>';
};
// create Grid datafields and columns arrays.
var datafields = [];
var columns = [];
for (var i = 0; i < 26; i++)
{
var text = String.fromCharCode(65 + i);
if (i == 0)
{
var cssclass = 'jqx-widget-header';
if (theme != '') cssclass += ' jqx-widget-header-' + theme;
columns[columns.length] = {
pinned: true,
exportable: false,
text: "",
columntype: 'number',
cellclassname: cssclass,
cellsrenderer: numberrenderer
};
}
datafields[datafields.length] = { name: text };
columns[columns.length] = { text: text, datafield: text, width: 60, align: 'center' };
}
let source = {
unboundmode: true,
totalrecords: 100,
datafields: datafields,
updaterow: function (rowid, rowdata)
{
// synchronize with the server - send update command
}
};
let dataAdapter = new $.jqx.dataAdapter(source);
// initialize jqxGrid
let gridOptions: jqwidgets.GridOptions = {
width: 800,
source: dataAdapter,
editable: true,
columnsresize: true,
selectionmode: 'multiplecellsadvanced',
columns: columns
};
let grid: jqwidgets.jqxGrid = jqwidgets.createInstance(gridSelector, 'jqxGrid', gridOptions);
} | the_stack |
module fng.directives {
enum tabsSetupState {Y, N, Forced}
/*@ngInject*/
export function formInput($compile, $rootScope, $filter, $timeout, cssFrameworkService, formGenerator, formMarkupHelper):angular.IDirective {
return {
restrict: 'EA',
link: function (scope:fng.IFormScope, element, attrs:fng.IFormAttrs) {
// generate markup for bootstrap forms
//
// Bootstrap 3
// Horizontal (default)
// <div class="form-group">
// <label for="inputEmail3" class="col-sm-2 control-label">Email</label>
// <div class="col-sm-10">
// <input type="email" class="form-control" id="inputEmail3" placeholder="Email">
// </div>
// </div>
//
// Vertical
// <div class="form-group">
// <label for="exampleInputEmail1">Email address</label>
// <input type="email" class="form-control" id="exampleInputEmail1" placeholder="Enter email">
// </div>
//
// Inline or stacked
// <div class="form-group">
// <label class="sr-only" for="exampleInputEmail2">Email address</label>
// <input type="email" class="form-control" id="exampleInputEmail2" placeholder="Enter email">
// </div>
// Bootstrap 2
// Horizontal (default)
// <div class="control-group">
// <label class="control-label" for="inputEmail">Email</label>
// <div class="controls">
// <input type="text" id="inputEmail" placeholder="Email">
// </div>
// </div>
//
// Vertical
// <label>Label name</label>
// <input type="text" placeholder="Type something…">
// <span class="help-block">Example block-level help text here.</span>
//
// Inline or Stacked
// <input type="text" class="input-small" placeholder="Email">
var subkeys = [];
var tabsSetup:tabsSetupState = tabsSetupState.N;
var generateInput = function (fieldInfo, modelString, isRequired, idString, options) {
function generateEnumInstructions() : IEnumInstruction{
var enumInstruction:IEnumInstruction;
if (angular.isArray(scope[fieldInfo.options])) {
enumInstruction = {repeat: fieldInfo.options, value: 'option'};
} else if (scope[fieldInfo.options] && angular.isArray(scope[fieldInfo.options].values)) {
if (angular.isArray(scope[fieldInfo.options].labels)) {
enumInstruction = {
repeat: fieldInfo.options + '.values',
value: fieldInfo.options + '.values[$index]',
label: fieldInfo.options + '.labels[$index]'
};
} else {
enumInstruction = {
repeat: fieldInfo.options + '.values',
value: fieldInfo.options + '.values[$index]'
};
}
} else {
throw new Error('Invalid enumeration setup in field ' + fieldInfo.name);
}
return enumInstruction;
}
var nameString;
if (!modelString) {
var modelBase = (options.model || 'record') + '.';
modelString = modelBase;
if (options.subschema && fieldInfo.name.indexOf('.') !== -1) {
// Schema handling - need to massage the ngModel and the id
var compoundName = fieldInfo.name;
var root = options.subschemaroot;
var lastPart = compoundName.slice(root.length + 1);
if (options.index) {
modelString += root + '[' + options.index + '].' + lastPart;
idString = 'f_' + modelString.slice(modelBase.length).replace(/(\.|\[|]\.)/g, '-');
} else {
modelString += root;
if (options.subkey) {
idString = modelString.slice(modelBase.length).replace(/\./g, '-') + '-subkey' + options.subkeyno + '-' + lastPart;
modelString += '[' + '$_arrayOffset_' + root.replace(/\./g, '_') + '_' + options.subkeyno + '].' + lastPart;
} else {
modelString += '[$index].' + lastPart;
idString = null;
nameString = compoundName.replace(/\./g, '-');
}
}
} else {
modelString += fieldInfo.name;
}
}
var allInputsVars = formMarkupHelper.allInputsVars(scope, fieldInfo, options, modelString, idString, nameString);
var common = allInputsVars.common;
var value;
isRequired = isRequired || fieldInfo.required;
var requiredStr = isRequired ? ' required ' : '';
var enumInstruction:IEnumInstruction;
function handleReadOnlyDisabled(readonly: any): string {
let retVal = '';
if (readonly) {
// despite the option being "readonly", we should use disabled and ng-disabled rather than their readonly
// equivalents (which give controls the appearance of being read-only, but don't actually prevent user
// interaction)
if (typeof readonly === "boolean") {
retVal = ` disabled `;
} else {
retVal = ` ng-disabled="${readonly}" `;
}
}
return retVal;
}
switch (fieldInfo.type) {
case 'select' :
if (fieldInfo.select2) {
value = '<input placeholder="fng-select2 has been removed" readonly>';
} else {
common += handleReadOnlyDisabled(fieldInfo.readonly);
common += fieldInfo.add ? (' ' + fieldInfo.add + ' ') : '';
common += ` aria-label="${fieldInfo.label && fieldInfo.label !== "" ? fieldInfo.label : fieldInfo.name}" `;
value = '<select ' + common + 'class="' + allInputsVars.formControl.trim() + allInputsVars.compactClass + allInputsVars.sizeClassBS2 + '" ' + requiredStr + '>';
if (!isRequired) {
value += '<option></option>';
}
if (angular.isArray(fieldInfo.options)) {
angular.forEach(fieldInfo.options, function (optValue) {
if (_.isObject(optValue)) {
value += '<option value="' + ((<any>optValue).val || (<any>optValue).id) + '">' + ((<any>optValue).label || (<any>optValue).text) + '</option>';
} else {
value += '<option>' + optValue + '</option>';
}
});
} else {
enumInstruction = generateEnumInstructions();
value += '<option ng-repeat="option in ' + enumInstruction.repeat + '"';
if (enumInstruction.label) {
value += ' value="{{' + enumInstruction.value + '}}"> {{ ' + enumInstruction.label + ' }} </option> ';
} else {
value += '>{{' + enumInstruction.value + '}}</option> ';
}
}
value += '</select>';
}
break;
case 'link' :
value = '<fng-link model="' + modelString + '" ref="' + fieldInfo.ref + '"';
if (fieldInfo.form) {
value += ' form="' + fieldInfo.form + '"';
}
if (fieldInfo.linktab) {
value += ' linktab="' + fieldInfo.linktab + '"';
}
if (fieldInfo.linktext) {
value += ' text="' + fieldInfo.linktext + '"';
}
if (fieldInfo.readonly) {
if (typeof fieldInfo.readonly === "boolean") {
value += ` readonly="true"`;
} else {
value += ` ng-readonly="${fieldInfo.readonly}"`;
}
}
value += '></fng-link>';
break;
case 'radio' :
value = '';
common += requiredStr;
common += handleReadOnlyDisabled(fieldInfo.readonly);
common += fieldInfo.add ? (' ' + fieldInfo.add + ' ') : '';
var separateLines = options.formstyle === 'vertical' || (options.formstyle !== 'inline' && !fieldInfo.inlineRadio);
if (angular.isArray(fieldInfo.options)) {
if (options.subschema) {
common = common.replace('name="', 'name="{{$index}}-');
common = common.replace('id="', 'id="{{$index}}-');
}
let thisCommon: string;
angular.forEach(fieldInfo.options, function (optValue, idx) {
thisCommon = common.replace('id="', 'id="' + idx + '-');
value += `<input ${thisCommon} type="radio" aria-label="${optValue}" value="${optValue}">${optValue}`;
if (separateLines) {
value += '<br />';
}
});
} else {
var tagType = separateLines ? 'div' : 'span';
if (options.subschema) {
common = common.replace('$index', '$parent.$index')
.replace('name="', 'name="{{$parent.$index}}-')
.replace('id="', 'id="{{$parent.$index}}-');
}
enumInstruction = generateEnumInstructions();
value += '<' + tagType + ' ng-repeat="option in ' + enumInstruction.repeat + '">';
value += `<input ${common.replace('id="', 'id="{{$index}}-')} type="radio" aria-label="${enumInstruction.value}" value="{{ ${enumInstruction.value} }}"> {{ ${enumInstruction.label || enumInstruction.value} }} </${tagType}> `;
}
break;
case 'checkbox' :
common += requiredStr;
common += handleReadOnlyDisabled(fieldInfo.readonly);
common += fieldInfo.add ? (' ' + fieldInfo.add + ' ') : '';
value = formMarkupHelper.generateSimpleInput(common, fieldInfo, options);
if (cssFrameworkService.framework() === 'bs3') {
value = '<div class="checkbox">' + value + '</div>';
}
break;
default:
common += formMarkupHelper.addTextInputMarkup(allInputsVars, fieldInfo, requiredStr);
if (fieldInfo.type === 'textarea') {
if (fieldInfo.rows) {
if (fieldInfo.rows === 'auto') {
common += 'msd-elastic="\n" class="ng-animate" ';
} else {
common += 'rows = "' + fieldInfo.rows + '" ';
}
}
if (fieldInfo.editor === 'ckEditor') {
console.log('Deprecation Warning: "editor" property deprecated - use "add"');
common += 'ckeditor = "" ';
if (cssFrameworkService.framework() === 'bs3') {
allInputsVars.sizeClassBS3 = 'col-xs-12';
}
}
value = '<textarea ' + common + '></textarea>';
} else {
value = formMarkupHelper.generateSimpleInput(common, fieldInfo, options);
}
}
return formMarkupHelper.inputChrome(value, fieldInfo, options, allInputsVars);
};
var convertFormStyleToClass = function (aFormStyle) {
var result;
switch (aFormStyle) {
case 'horizontal' :
result = 'form-horizontal';
break;
case 'vertical' :
result = '';
break;
case 'inline' :
result = 'form-inline';
break;
case 'stacked' :
result = 'form-stacked';
break;
case 'horizontalCompact' :
result = 'form-horizontal compact';
break;
default:
result = 'form-horizontal compact';
break;
}
return result;
};
var containerInstructions = function (info) {
var result = {before: '', after: ''};
if (typeof info.containerType === 'function') {
result = info.containerType(info);
} else {
switch (info.containerType) {
case 'tab' :
var tabNo = -1;
for (var i = 0; i < scope.tabs.length; i++) {
if (scope.tabs[i].title === info.title) {
tabNo = i;
break;
}
}
if (tabNo >= 0) {
// TODO Figure out tab history updates (check for other tab-history-todos)
// result.before = '<uib-tab deselect="tabDeselect($event, $selectedIndex)" select="updateQueryForTab(\'' + info.title + '\')" heading="' + info.title + '"'
result.before = '<uib-tab deselect="tabDeselect($event, $selectedIndex)" select="updateQueryForTab(\'' + info.title + '\')" heading="' + info.title + '"';
if (tabNo > 0) {
result.before += 'active="tabs[' + tabNo + '].active"';
}
result.before += '>';
result.after = '</uib-tab>';
} else {
result.before = '<p>Error! Tab ' + info.title + ' not found in tab list</p>';
result.after = '';
}
break;
case 'tabset' :
result.before = '<uib-tabset>';
result.after = '</uib-tabset>';
break;
case 'well' :
result.before = '<div class="well">';
if (info.title) {
result.before += '<h4>' + info.title + '</h4>';
}
result.after = '</div>';
break;
case 'well-large' :
result.before = '<div class="well well-lg well-large">';
result.after = '</div>';
break;
case 'well-small' :
result.before = '<div class="well well-sm well-small">';
result.after = '</div>';
break;
case 'fieldset' :
result.before = '<fieldset>';
if (info.title) {
result.before += '<legend>' + info.title + '</legend>';
}
result.after = '</fieldset>';
break;
case undefined:
break;
case null:
break;
case '':
break;
default:
result.before = '<div class="' + info.containerType + '">';
if (info.title) {
var titleLook = info.titleTagOrClass || 'h4';
if (titleLook.match(/h[1-6]/)) {
result.before += '<' + titleLook + '>' + info.title + '</' + titleLook + '>';
} else {
result.before += '<p class="' + titleLook + '">' + info.title + '</p>';
}
}
result.after = '</div>';
break;
}
}
return result;
};
var generateInlineHeaders = function (instructionsArray, options: fng.IFormOptions, model: string, evenWhenEmpty: boolean) {
// "column" headers for nested schemas that use formStyle: "inline" will only line up with their respective
// controls when widths are applied to both the cg_f_xxxx and col_label_xxxx element using css.
// Likely, the widths will need to be the same, so consider using the following:
// div[id$="_f_<collection>_<field>"] {
// width: 100px;
// }
// one column can grow to the remaining available width thus:
// div[id$="_f_<collection>_<field>"] {
// flex-grow: 1;
// }
let hideWhenEmpty = evenWhenEmpty ? "" : `ng-hide="!${model} || ${model}.length === 0"`;
let res = `<div class="inline-col-headers" style="display:flex" ${hideWhenEmpty}>`;
for (const info of instructionsArray) {
// need to call this now to ensure the id is set. will probably be (harmlessly) called again later.
inferMissingProperties(info, options);
res += '<div ';
info.showWhen = info.showWhen || info.showwhen; // deal with use within a directive
if (info.showWhen) {
if (typeof info.showWhen === 'string') {
res += 'ng-show="' + info.showWhen + '"';
}
else {
res += 'ng-show="' + formMarkupHelper.generateNgShow(info.showWhen, model) + '"';
}
}
if (info.id && typeof info.id.replace === "function") {
res += ' id="col_label_' + info.id.replace(/\./g, '-') + '"';
}
res += ` class="inline-col-header"><label for="${info.id}" class="control-label">${info.label}</label></div>`;
}
res += "</div>";
return res;
};
var handleField = function (info, options: fng.IFormOptions) {
var fieldChrome = formMarkupHelper.fieldChrome(scope, info, options);
var template = fieldChrome.template;
if (info.schema) {
var niceName = info.name.replace(/\./g, '_');
var schemaDefName = '$_schema_' + niceName;
scope[schemaDefName] = info.schema;
if (info.schema) { // display as a control group
//schemas (which means they are arrays in Mongoose)
// Check for subkey - selecting out one or more of the array
if (info.subkey) {
info.subkey.path = info.name;
scope[schemaDefName + '_subkey'] = info.subkey;
var subKeyArray = angular.isArray(info.subkey) ? info.subkey : [info.subkey];
for (var arraySel = 0; arraySel < subKeyArray.length; arraySel++) {
var topAndTail = containerInstructions(subKeyArray[arraySel]);
template += topAndTail.before;
template += processInstructions(info.schema, null, {
subschema: 'true', // We are trying to behave like attrs here
formstyle: options.formstyle,
subkey: schemaDefName + '_subkey',
subkeyno: arraySel,
subschemaroot: info.name,
suppressNestingWarning: info.suppressNestingWarning
});
template += topAndTail.after;
}
subkeys.push(info);
} else {
if (options.subschema) {
if (!options.suppressNestingWarning) {
console.log('Attempts at supporting deep nesting have been removed - will hopefully be re-introduced at a later date');
}
} else {
let model: string = (options.model || 'record') + '.' + info.name;
/* Array header */
if (typeof info.customHeader == 'string') {
template += info.customHeader;
} else {
let topButton: string = '';
if (info.unshift) {
topButton = '<button id="unshift_' + info.id + '_btn" class="add-btn btn btn-default btn-xs btn-mini form-btn" ng-click="unshift(\'' + info.name + '\',$event)">' +
'<i class="' + formMarkupHelper.glyphClass() + '-plus"></i> Add</button>';
}
if (cssFrameworkService.framework() === 'bs3') {
template += '<div class="row schema-head"><div class="col-sm-offset-3">' + info.label + topButton + '</div></div>';
} else {
template += '<div class="schema-head">' + info.label + topButton + '</div>';
}
}
/* Array body */
if (info.formStyle === "inline" && info.inlineHeaders) {
template += generateInlineHeaders(info.schema, options, model, info.inlineHeaders === "always");
}
template += '<ol class="sub-doc"' + (info.sortable ? ` ui-sortable="sortableOptions" ng-model="${model}"` : '') + '>';
template += '<li ng-form class="' + (cssFrameworkService.framework() === 'bs2' ? 'row-fluid ' : '') +
(info.inlineHeaders ? 'width-controlled ' : '') +
convertFormStyleToClass(info.formStyle) + ' ' + (info.ngClass ? "ng-class:" + info.ngClass : "") + '" name="form_' + niceName + '{{$index}}" class="sub-doc well" id="' + info.id + 'List_{{$index}}" ' +
' ng-repeat="subDoc in ' + model + ' track by $index">';
if (cssFrameworkService.framework() === 'bs2') {
template += '<div class="row-fluid sub-doc">';
}
if (info.noRemove !== true || info.customSubDoc) {
template += ' <div class="sub-doc-btns">';
if (typeof info.customSubDoc == 'string') {
template += info.customSubDoc;
}
if (info.noRemove !== true) {
template += `<button ${info.noRemove ? 'ng-hide="' + info.noRemove + '"' : ''} name="remove_${info.id}_btn" ng-click="remove('${info.name}', $index, $event)"`;
if (info.remove) {
template += ' class="remove-btn btn btn-mini btn-default btn-xs form-btn"><i class="' + formMarkupHelper.glyphClass() + '-minus"></i> Remove';
} else {
template += ' style="position: relative; z-index: 20;" type="button" class="close pull-right">';
if (cssFrameworkService.framework() === 'bs3') {
template += '<span aria-hidden="true">×</span><span class="sr-only">Close</span>';
} else {
template += '<span>×</span>';
}
}
template += '</button>';
}
template += '</div> ';
}
template += processInstructions(info.schema, false, {
subschema: 'true',
formstyle: info.formStyle,
model: options.model,
subschemaroot: info.name,
suppressNestingWarning: info.suppressNestingWarning
});
if (cssFrameworkService.framework() === 'bs2') {
template += ' </div>';
}
template += '</li>';
template += '</ol>';
/* Array footer */
if (info.noAdd !== true || typeof info.customFooter == 'string' || info.noneIndicator) {
let footer: string = '';
if (typeof info.customFooter == 'string') {
footer = info.customFooter;
}
let hideCond = '';
let indicatorShowCond = `${options.model}.${info.name}.length == 0`;
if (info.noAdd === true) {
indicatorShowCond = `ng-show="${indicatorShowCond}"`;
} else {
hideCond = info.noAdd ? `ng-hide="${info.noAdd}"` : '';
indicatorShowCond = info.noAdd ? `ng-show="${info.noAdd} && ${indicatorShowCond}"` : '';
footer += `<button ${hideCond} id="add_${info.id}_btn" class="add-btn btn btn-default btn-xs btn-mini" ng-click="add('${info.name}',$event)">
<i class="' + formMarkupHelper.glyphClass() + '-plus"></i>
Add
</button>`;
}
if (info.noneIndicator) {
footer += `<span ${indicatorShowCond} class="none_indicator" id="no_${info.id}_indicator">None</span>`;
// hideCond for the schema-foot is if there's no add button and no indicator
hideCond = `${options.model}.${info.name}.length > 0`;
if (info.noAdd === true) {
hideCond = `ng-hide="${hideCond}"`;
} else {
hideCond = info.noAdd ? `ng-hide="${info.noAdd} && ${hideCond}"` : '';
}
}
if (footer !== '') {
if (cssFrameworkService.framework() === 'bs3') {
template += `<div ${hideCond} class="row schema-foot"><div class="col-sm-offset-3">${footer}</div></div>`;
} else {
template += `<div ${hideCond} class = "schema-foot ">${footer}</div>`;
}
}
}
}
}
}
}
else {
// Handle arrays here
var controlDivClasses = formMarkupHelper.controlDivClasses(options);
if (info.array) {
controlDivClasses.push('fng-array');
if (options.formstyle === 'inline' || options.formstyle === 'stacked') {
throw new Error('Cannot use arrays in an inline or stacked form');
}
template += formMarkupHelper.label(scope, info, info.type !== 'link', options);
template += formMarkupHelper.handleArrayInputAndControlDiv(generateInput(info, info.type === 'link' ? null : 'arrayItem.x', true, info.id + '_{{$index}}', options), controlDivClasses, info, options);
} else {
// Single fields here
template += formMarkupHelper.label(scope, info, null, options);
template += formMarkupHelper.handleInputAndControlDiv(generateInput(info, null, (<any>options).required, info.id, options), controlDivClasses);
}
}
template += fieldChrome.closeTag;
return template;
};
const inferMissingProperties = function (info: IFormInstruction, options?: IBaseFormOptions) {
// infer missing values
info.type = info.type || 'text';
if (info.id) {
if (typeof info.id === 'number' || info.id.match(/^[0-9]/)) {
info.id = '_' + info.id;
}
} else {
if (options && options.noid) {
info.id = null;
} else {
info.id = 'f_' + info.name.replace(/\./g, '_');
}
}
info.label = (info.label !== undefined) ? (info.label === null ? '' : info.label) : $filter('titleCase')(info.name.split('.').slice(-1)[0]);
};
// var processInstructions = function (instructionsArray, topLevel, groupId) {
// removing groupId as it was only used when called by containerType container, which is removed for now
var processInstructions = function (instructionsArray, topLevel, options:fng.IFormOptions) {
var result = '';
if (instructionsArray) {
for (var anInstruction = 0; anInstruction < instructionsArray.length; anInstruction++) {
var info = instructionsArray[anInstruction];
if (options.viewform) {
info = angular.copy(info);
info.readonly = true;
}
if (anInstruction === 0 && topLevel && !options.schema.match(/\$_schema_/) && typeof info.add !== 'object') {
info.add = info.add ? ' ' + info.add + ' ' : '';
if (info.add.indexOf('ui-date') === -1 && !options.noautofocus && !info.containerType) {
info.add = info.add + 'autofocus ';
}
}
var callHandleField = true;
if (info.directive) {
var directiveName = info.directive;
var newElement = '<' + directiveName + ' model="' + (options.model || 'record') + '"';
var thisElement = element[0];
inferMissingProperties(info, options);
for (var i = 0; i < thisElement.attributes.length; i++) {
var thisAttr = thisElement.attributes[i];
switch (thisAttr.nodeName) {
case 'class' :
var classes = thisAttr.value.replace('ng-scope', '');
if (classes.length > 0) {
newElement += ' class="' + classes + '"';
}
break;
case 'schema' :
var bespokeSchemaDefName = ('bespoke_' + info.name).replace(/\./g, '_');
scope[bespokeSchemaDefName] = angular.copy(info);
delete scope[bespokeSchemaDefName].directive;
newElement += ' schema="' + bespokeSchemaDefName + '"';
break;
default :
newElement += ' ' + thisAttr.nodeName + '="' + thisAttr.value + '"';
}
}
newElement += ' ';
var directiveCamel = $filter('camelCase')(info.directive);
for (var prop in info) {
if (info.hasOwnProperty(prop)) {
switch (prop) {
case 'directive' :
break;
case 'schema' :
break;
case 'add' :
switch (typeof info.add) {
case 'string' :
newElement += ' ' + info.add;
break;
case 'object' :
for (var subAdd in info.add) {
if (info.add.hasOwnProperty(subAdd)) {
newElement += ' ' + subAdd + '="' + info.add[subAdd].toString().replace(/"/g, '"') + '"';
}
}
break;
default:
throw new Error('Invalid add property of type ' + typeof(info.add) + ' in directive ' + info.name);
}
break;
case directiveCamel :
for (var subProp in info[prop]) {
if (info[prop].hasOwnProperty(subProp)) {
newElement += ` ${info.directive}-${subProp}="`;
if (typeof info[prop][subProp] === 'string') {
newElement += `${info[prop][subProp].replace(/"/g, '"')}"`;
} else {
newElement += `${JSON.stringify(info[prop][subProp]).replace(/"/g, '"')}"`;
}
}
}
break;
default:
if (info[prop]) {
if (typeof info[prop] === 'string') {
newElement += ' fng-fld-' + prop + '="' + info[prop].replace(/"/g, '"') + '"';
} else {
newElement += ' fng-fld-' + prop + '="' + JSON.stringify(info[prop]).replace(/"/g, '"') + '"';
}
}
break;
}
}
}
for (prop in options) {
if (options.hasOwnProperty(prop) && prop[0] !== '$' && typeof options[prop] !== 'undefined') {
newElement += ' fng-opt-' + prop + '="' + options[prop].toString().replace(/"/g, '"') + '"';
}
}
newElement += 'ng-model="' + info.name + '"></' + directiveName + '>';
result += newElement;
callHandleField = false;
} else if (info.containerType) {
var parts = containerInstructions(info);
switch (info.containerType) {
case 'tab' :
// maintain support for simplified tabset syntax for now
if (tabsSetup === tabsSetupState.N) {
tabsSetup = tabsSetupState.Forced;
result += '<uib-tabset active="activeTabNo">';
let activeTabNo: number = _.findIndex(scope.tabs, (tab) => (tab.active));
scope.activeTabNo = activeTabNo >= 0 ? activeTabNo : 0;
}
result += parts.before;
result += processInstructions(info.content, null, options);
result += parts.after;
break;
case 'tabset' :
tabsSetup = tabsSetupState.Y;
result += parts.before;
result += processInstructions(info.content, null, options);
result += parts.after;
break;
default:
// includes wells, fieldset
result += parts.before;
result += processInstructions(info.content, null, options);
result += parts.after;
break;
}
callHandleField = false;
} else if (options.subkey) {
// Don't display fields that form part of the subkey, as they should not be edited (because in these circumstances they form some kind of key)
var objectToSearch = angular.isArray(scope[options.subkey]) ? scope[options.subkey][0].keyList : scope[options.subkey].keyList;
if (_.find(objectToSearch, (value, key) => scope[options.subkey].path + '.' + key === info.name )) {
callHandleField = false;
}
}
if (callHandleField) {
// if (groupId) {
// scope['showHide' + groupId] = true;
// }
inferMissingProperties(info, options);
result += handleField(info, options);
}
}
} else {
console.log('Empty array passed to processInstructions');
result = '';
}
return result;
};
var unwatch = scope.$watch(attrs.schema, function (newValue: any) {
if (newValue) {
var newArrayValue: Array<any> = angular.isArray(newValue) ? newValue : [newValue]; // otherwise some old tests stop working for no real reason
if (newArrayValue.length > 0 && typeof unwatch === "function") {
unwatch();
unwatch = null;
var elementHtml = '';
var recordAttribute = attrs.model || 'record'; // By default data comes from scope.record
var theRecord = scope[recordAttribute];
theRecord = theRecord || {};
if ((attrs.subschema || attrs.model) && !attrs.forceform) {
elementHtml = '';
} else {
scope.topLevelFormName = attrs.name || 'myForm'; // Form name defaults to myForm
// Copy attrs we don't process into form
var customAttrs = '';
for (var thisAttr in attrs) {
if (attrs.hasOwnProperty(thisAttr)) {
if (thisAttr[0] !== '$' && ['name', 'formstyle', 'schema', 'subschema', 'model', 'viewform'].indexOf(thisAttr) === -1) {
customAttrs += ' ' + attrs.$attr[thisAttr] + '="' + attrs[thisAttr] + '"';
}
}
}
let tag = attrs.forceform ? 'ng-form' : 'form';
elementHtml = `<${tag} name="${scope.topLevelFormName}" class="${convertFormStyleToClass(attrs.formstyle)}" novalidate ${customAttrs}>`;
}
if (theRecord === scope.topLevelFormName) {
throw new Error('Model and Name must be distinct - they are both ' + theRecord);
}
elementHtml += processInstructions(newArrayValue, true, attrs);
if (tabsSetup === tabsSetupState.Forced) {
elementHtml += '</uib-tabset>';
}
elementHtml += attrs.subschema ? '' : '</form>';
//console.log(elementHtml);
element.replaceWith($compile(elementHtml)(scope));
// If there are subkeys we need to fix up ng-model references when record is read
// If we have modelControllers we need to let them know when we have form + data
let sharedData = scope[attrs.shared || 'sharedData'];
let modelControllers = sharedData ? sharedData.modelControllers : [];
if ((subkeys.length > 0 || modelControllers.length > 0) && !scope.phaseWatcher){
var unwatch2 = scope.$watch('phase', function (newValue) {
scope.phaseWatcher = true;
if (newValue === 'ready' && typeof unwatch2 === "function") {
unwatch2();
unwatch2 = null;
// Tell the 'model controllers' that the form and data are there
for (var i = 0; i < modelControllers.length; i++) {
if (modelControllers[i].onAllReady) {
modelControllers[i].onAllReady(scope);
}
}
// For each one of the subkeys sets in the form we need to fix up ng-model references
for (var subkeyCtr = 0; subkeyCtr < subkeys.length; subkeyCtr++) {
var info = subkeys[subkeyCtr];
var arrayOffset;
var matching;
var arrayToProcess = angular.isArray(info.subkey) ? info.subkey : [info.subkey];
var parts = info.name.split('.');
var dataVal = theRecord;
while (parts.length > 1) {
dataVal = dataVal[parts.shift()] || {};
}
dataVal = dataVal[parts[0]] = dataVal[parts[0]] || [];
// For each of the required subkeys of this type
for (var thisOffset = 0; thisOffset < arrayToProcess.length; thisOffset++) {
if (arrayToProcess[thisOffset].selectFunc) {
// Get the array offset from a function
if (!scope[arrayToProcess[thisOffset].selectFunc] || typeof scope[arrayToProcess[thisOffset].selectFunc] !== 'function') {
throw new Error('Subkey function ' + arrayToProcess[thisOffset].selectFunc + ' is not properly set up');
}
arrayOffset = scope[arrayToProcess[thisOffset].selectFunc](theRecord, info);
} else if (arrayToProcess[thisOffset].keyList) {
// We are choosing the array element by matching one or more keys
var thisSubkeyList = arrayToProcess[thisOffset].keyList;
for (arrayOffset = 0; arrayOffset < dataVal.length; arrayOffset++) {
matching = true;
for (var keyField in thisSubkeyList) {
if (thisSubkeyList.hasOwnProperty(keyField)) {
// Not (currently) concerned with objects here - just simple types and lookups
if (dataVal[arrayOffset][keyField] !== thisSubkeyList[keyField] &&
(typeof dataVal[arrayOffset][keyField] === 'undefined' || !dataVal[arrayOffset][keyField].text || dataVal[arrayOffset][keyField].text !== thisSubkeyList[keyField])) {
matching = false;
break;
}
}
}
if (matching) {
break;
}
}
if (!matching) {
// There is no matching array element
switch (arrayToProcess[thisOffset].onNotFound) {
case 'error' :
var errorMessage = 'Cannot find matching ' + (arrayToProcess[thisOffset].title || arrayToProcess[thisOffset].path);
//Have to do this async as setPristine clears it
$timeout(function() {
scope.showError(errorMessage, 'Unable to set up form correctly');
});
arrayOffset = -1;
//throw new Error(scope.errorMessage);
break;
case 'create':
default:
let nameElements = info.name.split('.');
let lastPart: string = nameElements.pop();
let possibleArray: string = nameElements.join('.');
let obj = theRecord;
// Should loop here when / if we re-introduce nesting
if (possibleArray) {
obj = obj[possibleArray];
}
arrayOffset = obj[lastPart].push(thisSubkeyList) - 1;
break;
}
}
} else {
throw new Error('Invalid subkey setup for ' + info.name);
}
scope['$_arrayOffset_' + info.name.replace(/\./g, '_') + '_' + thisOffset] = arrayOffset;
}
}
}
});
}
$rootScope.$broadcast('formInputDone', attrs.name);
if (formGenerator.updateDataDependentDisplay && theRecord && Object.keys(theRecord).length > 0) {
// If this is not a test force the data dependent updates to the DOM
formGenerator.updateDataDependentDisplay(theRecord, null, true, scope);
}
}
}
}, true);
}
};
}
} | the_stack |
export type BaseConstructor<T> = Function & { prototype: T };
/**
* A plain object with following properties:
*
* **src**: *string*
* File system path, relative path or URL. The [data URI](https://en.wikipedia.org/wiki/Data_URI_scheme) scheme is also supported. Relative paths are resolved relative to 'package.json'. On Android the name of a bundled [drawable resource](https://developer.android.com/guide/topics/resources/drawable-resource.html) can be provided with the url scheme `android-drawable`, e.g. `android-drawable://ic_info_black`.
*
* **width**: *number | 'auto' (optional)*
* Image width in dip, extracted from the image file when missing or `'auto'`.
*
* **height**: *number | 'auto' (optional)*
* Image height in dip, extracted from the image file when missing or `'auto'`.
*
* **scale**: *number | 'auto' (optional)*
* Image scale factor, the image will be scaled down by this factor. The scale will be inferred from the image file name if it follows the pattern "@\<scale\>x", e.g. `"image@2x.jpg"`. The pattern is ignored if `scale`, `width` or `height` are set to a number or if `scale` is set to `"auto"`.
*/
export type ImageSource = string | ImageBitmap | Blob;
export type ImageLikeObject = {src: ImageSource, scale?: number | "auto", width?: number | "auto", height?: number | "auto"};
/**
* Images can be specified as strings or Image/ImageLikeObject.
*
* An **Image** instance can be created using the **Image** constructor or using **Image.from**.
*
* The string shorthand `"image.jpg"` equals `{src: "image.jpg"}`.
*
* The scale can be part of the file name in the pattern of "@\<scale\>x", e.g. `"image@2x.jpg"`. The pattern is ignored if `scale`, `width` or `height` are set to a number or if `scale` is set to `"auto"`.
*/
export type ImageValue = ImageLikeObject | Image | ImageSource | null;
export type ColorArray = [number, number, number, number]|[number, number, number];
export type ColorLikeObject = {red: number, green: number, blue: number, alpha?: number};
/**
* Colors can be specified as strings, arrays or Color/Color-like objects.
*
* A **Color** instance can be created with the **Color** constructor or using **Color.from**.
*
* A **Color**-like object is a plain object with "red", "green", "blue" and optional "alpha" properties.
* Example: **{red: 0, green: 127, blue: 255, alpha: 120}**
*
* A color array has consist of 3 or 4 numbers between (and including) 0 and 255,
* i.e. **[red, green, blue, alpha]**. If omitted, alpha is 255.
*
* As a string the following formats can be used:
* - **"#xxxxxx"**
* - **"#xxx"**
* - **"#xxxxxxxx"**
* - **"#xxxx"**
* - **"rgb(r, g, b)"** with **r**, **g** and **b** being numbers in the range 0..255.
* - **"rgba(r, g, b, a)"** with **a** being a number in the range 0..1.
* - a color name from the CSS3 specification.
* - **"transparent"** sets a fully transparent color. This is a shortcut for **"rgba(0, 0, 0, 0)"**.
* - **"initial"** resets the color to its (platform-dependent) default.
*
* Setting a ColorValue property to null also resets it to the default color.
*
* Type guards for `ColorValue` are available as **Color.isColorValue** and **Color.isValidColorValue**
*/
export type ColorValue = ColorLikeObject | ColorArray | string | 'initial' | null;
export type FontWeight = 'black' | 'bold' | 'medium' | 'thin' | 'light' | 'normal';
export type FontStyle = 'italic' | 'normal';
export type FontLikeObject = {size: number, family?: string[], weight?: FontWeight, style?: FontStyle};
/**
* Fonts can be specified as strings or Font/Font-like objects.
*
* A **Font** instance can be created with the **Font** constructor or using **Font.from**.
*
* A **Font**-like object is a plain object with "size" and optional "family", "weight" and "style" properties.
* Example: **{size: 16, family: ['serif'], weight: 'bold', style: 'italic'}**
*
* Generic font families supported across all platforms are **"serif"**, **"sans-serif"**, **"condensed"** and **"monospace"**.
* Supported font weights are **"light"**, **"thin"**, **"normal"**, **"medium"**, **"bold"** and **"black"**.
*
* As a string, the shorthand syntax known from CSS is used: **"[font-style] [font-weight] font-size [font-family[, font-family]*]"**. The font family may be omitted, in this case the default system font will be used. The value **"initial"** represents the platform default.
*/
export type FontValue = FontLikeObject|string|'initial'|null;
export interface PercentLikeObject {
percent: number;
}
export type PercentString = string;
/**
*
* Percents can be specified as strings or Percent/Percent-like objects.
*
* A **Percent** instance can be created with the **Percent** constructor or using **Percent.from**.
*
* A **Percent**-like object is a plain object with a *percent* property with a number between and including 0 and 100.
*
* A percent string contains a number between and including 0 and 100 and and ends with `%`.
*
*/
export type PercentValue = PercentString | PercentLikeObject;
/**
* Defines how the widget should be arranged. When setting the layout of a widget using **LayoutData**, all currently set layout attributes not in the new LayoutData object will be implicitly reset to null (i.e. "not specified").
*/
export type LayoutDataValue = LayoutDataLikeObject|'center'|'stretch'|'stretchX'|'stretchY';
export interface LayoutDataLikeObject {
left?: 'auto' | ConstraintValue;
right?: 'auto' | ConstraintValue;
top?: 'auto' | ConstraintValue;
bottom?: 'auto' | ConstraintValue;
centerX?: 'auto' | Offset | true;
centerY?: 'auto' | Offset | true;
baseline?: 'auto' | SiblingReferenceValue |true;
width?: 'auto' | Dimension;
height?: 'auto' | Dimension;
}
export interface LayoutDataProperties {
left?: 'auto' | Constraint;
right?: 'auto' | Constraint;
top?: 'auto' | Constraint;
bottom?: 'auto' | Constraint;
centerX?: 'auto' | Offset;
centerY?: 'auto' | Offset;
baseline?: 'auto' | SiblingReference;
width?: 'auto' | Dimension;
height?: 'auto' | Dimension;
}
export type LinearGradientLikeObject = {
colorStops: Array<ColorValue | [ColorValue, PercentValue]>,
direction?: number | 'left' | 'top' | 'right' | 'bottom'
}
/**
* Linear gradients can be specified as strings or [LinearGradient](./LinearGradient.html) or
* `LinearGradient`-like objects.
*
* An `LinearGradient` instance can be created using the `LinearGradient` constructor or using
* `LinearGradient.from`.
*
* A `LinearGradient`-like object is a plain object with "colorStops" and optional "direction"
* properties.
* "colorStops" is an array containing atleast one `ColorValue` or `[ColorValue, PercentValue]`.
* "direction" is a number in degrees or one of "left", "top", "right" and "bottom".
*
* As string, following CSS subset can be used:
*
* <color-stop> ::= <color> [ <number>% ]
* <linear-gradient> ::= linear-gradient( [ <number>deg | to ( left | top | right | bottom ), ] <color-stop> { , <color-stop> } )
*/
export type LinearGradientValue = LinearGradientLikeObject | string | 'initial' | null;
/**
* A Widget's bounds
*/
export interface Bounds {
/**
* the horizontal offset from the parent's left edge in dip
*/
left: number;
/**
* the vertical offset from the parent's top edge in dip
*/
top: number;
/**
* the width of the widget in dip
*/
width: number;
/**
* the height of the widget in dip
*/
height: number;
}
export interface Transformation {
/**
* Clock-wise rotation in radians. Defaults to \`0\`.
*/
rotation?: number;
/**
* Horizontal scale factor. Defaults to \`1\`.
*/
scaleX?: number;
/**
* Vertical scale factor. Defaults to \`1\`.
*/
scaleY?: number;
/**
* Horizontal translation (shift) in dip. Defaults to \`0\`.
*/
translationX?: number;
/**
* Vertical translation (shift) in dip. Defaults to \`0\`.
*/
translationY?: number;
/**
* Z-axis translation (shift) in dip. Defaults to \`0\`. Android 5.0+ only.
*/
translationZ?: number;
}
export type SelectorString = string;
export type SiblingSelectorString = string;
/**
* An expression or a predicate function to select a set of widgets.
*/
export type Selector<
Candidate extends Widget = Widget,
Result extends Candidate = Candidate
> = SelectorString | SelectorFunction<Candidate> | Constructor<Result> | SFC<Result>;
export type SelectorFunction<Candidate extends Widget> = (widget: Candidate, index: number, collection: WidgetCollection<Candidate>) => boolean;
/**
* A positive float, or 0, representing device independent pixels.
*/
export type Dimension = number;
/**
* A positive or negative float, or 0, representing device independent pixels.
*/
export type Offset = number;
export type PrevString = 'prev()';
type NextString = 'next()';
export type SiblingReferenceSymbol = typeof LayoutData.next | typeof LayoutData.prev
export type SiblingReference = Widget | SiblingReferenceSymbol | SiblingSelectorString;
export type SiblingReferenceValue = Widget | SiblingReferenceSymbol | SiblingSelectorString;
export type ConstraintArray = [SiblingReferenceValue | PercentValue, Offset];
export type ConstraintArrayValue = [SiblingReference | PercentValue, Offset];
export type ConstraintLikeObject = {
reference: SiblingReferenceValue | PercentValue;
offset?: Offset;
}|{
reference?: SiblingReferenceValue | PercentValue;
offset: Offset;
};
/**
* Distance to a parent's or sibling's opposing edge in one of these formats:
* - **offset** the distance from the parent's opposing edge in device independent pixels
* - **percentage** the distance from the parent's opposing edge in percent of the parent's width
* - **Widget** attach this edge to the given siblings's opposing edge
* - **"selector"**
* - **"prev()"** Same as above, but as space-separated string list instead of array
* - **"selector offset"**
* - **"prev() offset"**
* - **[Widget, offset]** the distance from the given widget's opposing edge in pixel
* - **"Widget, offset"**Same as above, but as space-separated string list instead of array.
* - **[percentage, offset]** the distance from the parent's opposing edge in percent of the parent's width plus a fixed offset in pixels
* - **"percentage offset"** Same as above, but as space-separated string list instead of array
* - **[selector, offset]**
* - **["prev()", offset]**
*/
export type ConstraintValue = Constraint
| ConstraintArrayValue
| ConstraintLikeObject
| Offset
| PercentValue
| SiblingReferenceValue
| true;
export interface AnimationOptions {
/**
* Time until the animation starts in ms, defaults to 0.
*/
delay?: number;
/**
* Duration of the animation in ms.
*/
duration?: number;
/**
* Easing function applied to the animation.
*/
easing?: "linear"|"ease-in"|"ease-out"|"ease-in-out";
/**
* Number of times to repeat the animation, defaults to 0.
*/
repeat?: number;
/**
* If true, alternates the direction of the animation on every repeat.
*/
reverse?: boolean;
/**
* no effect, but will be given in animation events.
*/
name?: string;
}
/**
* Represents dimensions on four edges of a box, as used for padding.
*/
export type BoxDimensions = number | string | [number, number?, number?, number?] | {
/**
* The left part, in dip.
*/
left?: number;
/**
* The right part, in dip.
*/
right?: number;
/**
* The top part, in dip.
*/
top?: number;
/**
* The bottom part, in dip.
*/
bottom?: number;
}
export interface PropertyChangedEvent<T, U> extends EventObject<T>{
readonly value: U
originalEvent?: PropertyChangedEvent<object, unknown> | null;
}
export class JsxProcessor {
public readonly jsxFactory: Symbol;
public readonly jsxType: Symbol;
createElement(type: {prototype: JSX.ElementClass, new(): object}|string, attributes: object, ...children: Array<JSX.ElementClass>): JSX.ElementClass | string;
createIntrinsicElement(type: string, attributes: object): JSX.ElementClass | string;
createCustomComponent(type: {prototype: JSX.ElementClass, new(): object}, attributes: object): JSX.ElementClass | string;
createFunctionalComponent(type: ((param: object) => any), attributes: object): JSX.ElementClass | string;
createNativeObject(Type: {prototype: JSX.ElementClass, new(): NativeObject}, attributes: object): NativeObject;
}
export function asFactory<
OriginalConstructor extends Constructor<JSXCandidate> & {prototype: Instance},
Instance extends JSXCandidate = InstanceType<OriginalConstructor>
> (constructor: OriginalConstructor): CallableConstructor<OriginalConstructor>;
export type ModuleLoader = (
module: Module,
exports: object,
require: (fn: string) => object,
__filename: string,
__dirname: string
) => void;
export type ResourceData<Resources extends ResourceBaseData<any>, RawType = any> = Record<keyof Resources, Selectable<RawType>>;
export type ColorResourceData<Resources extends {[P in keyof Resources]: Color}> = Record<keyof Resources, Selectable<ColorValue>>;
export type FontResourceData<Resources extends {[P in keyof Resources]: Font}> = Record<keyof Resources, Selectable<FontValue>>;
export type TextResourceData<Resources extends {[P in keyof Resources]: string}> = Record<keyof Resources, Selectable<string>>;
export type RuleSetObject = ({[selectorOrAttribute: string]: any}) & {prototype?: never};
export type RuleSetStatic = RuleSetObject | Array<RuleSetObject>;
export type RuleSetCallback<Target> = ((widget: Target) => RuleSetStatic) | null;
export type RuleSet<Target = Widget> = RuleSetStatic | RuleSetCallback<Target> | null;
export type ApplyAttributes<WidgetConstructor extends BaseConstructor<Widget>> = ApplyAttributesTypedSetter<WidgetConstructor> | ApplyAttributesUntypedSetter | ApplyAttributesRuleSet;
export type ApplyAttributesTypedSetter<WidgetConstructor extends BaseConstructor<Widget>> = {
target: WidgetConstructor,
selector?: string,
children?: Attributes<WidgetConstructor['prototype']>,
attr?: Attributes<WidgetConstructor['prototype']>
};
export type ApplyAttributesUntypedSetter = {
target?: never,
selector?: string,
children?: Attributes<Widget>,
attr?: Attributes<Widget>
};
export type ApplyAttributesRuleSet = {
children?: RuleSet
};
export namespace widgets {
export class ObservableData {
constructor(properties?: Record<string, any>);
[Symbol.observable](): Observable<PropertyChangedEvent<this, unknown>>;
}
}
export type ObservableData = widgets.ObservableData;
export type ObservableDataConstructor = typeof widgets.ObservableData;
export interface ObservableDataFactory extends ObservableDataConstructor {
<T extends object>(properties?: T): ObservableData & T;
}
export const ObservableData: ObservableDataFactory; | the_stack |
import { Projection, ProjectionOptions, VNode, VNodeProperties } from "./interfaces";
const NAMESPACE_W3 = "http://www.w3.org/";
const NAMESPACE_SVG = `${NAMESPACE_W3}2000/svg`;
const NAMESPACE_XLINK = `${NAMESPACE_W3}1999/xlink`;
let emptyArray = <VNode[]>[];
export let extend = <T>(base: T, overrides: any): T => {
let result = {} as any;
Object.keys(base).forEach((key) => {
result[key] = (base as any)[key];
});
if (overrides) {
Object.keys(overrides).forEach((key) => {
result[key] = overrides[key];
});
}
return result;
};
let same = (vnode1: VNode, vnode2: VNode) => {
if (vnode1.vnodeSelector !== vnode2.vnodeSelector) {
return false;
}
if (vnode1.properties && vnode2.properties) {
if (vnode1.properties.key !== vnode2.properties.key) {
return false;
}
return vnode1.properties.bind === vnode2.properties.bind;
}
return !vnode1.properties && !vnode2.properties;
};
let checkStyleValue = (styleValue: unknown) => {
if (typeof styleValue !== "string") {
throw new Error("Style values must be strings");
}
};
let findIndexOfChild = (children: VNode[], sameAs: VNode, start: number) => {
if (sameAs.vnodeSelector !== "") {
// Never scan for text-nodes
for (let i = start; i < children.length; i++) {
if (same(children[i], sameAs)) {
return i;
}
}
}
return -1;
};
let checkDistinguishable = (
childNodes: VNode[],
indexToCheck: number,
parentVNode: VNode,
operation: string
) => {
let childNode = childNodes[indexToCheck];
if (childNode.vnodeSelector === "") {
return; // Text nodes need not be distinguishable
}
let properties = childNode.properties;
let key = properties
? properties.key === undefined
? properties.bind
: properties.key
: undefined;
if (!key) {
// A key is just assumed to be unique
for (let i = 0; i < childNodes.length; i++) {
if (i !== indexToCheck) {
let node = childNodes[i];
if (same(node, childNode)) {
throw new Error(
`${parentVNode.vnodeSelector} had a ${childNode.vnodeSelector} child ${
operation === "added" ? operation : "removed"
}, but there is now more than one. You must add unique key properties to make them distinguishable.`
);
}
}
}
}
};
let nodeAdded = (vNode: VNode) => {
if (vNode.properties) {
let enterAnimation = vNode.properties.enterAnimation;
if (enterAnimation) {
enterAnimation(vNode.domNode as Element, vNode.properties);
}
}
};
let removedNodes: VNode[] = [];
let requestedIdleCallback = false;
let visitRemovedNode = (node: VNode) => {
(node.children || []).forEach(visitRemovedNode);
if (node.properties && node.properties.afterRemoved) {
node.properties.afterRemoved.apply(node.properties.bind || node.properties, [
<Element>node.domNode,
]);
}
};
let processPendingNodeRemovals = (): void => {
requestedIdleCallback = false;
removedNodes.forEach(visitRemovedNode);
removedNodes.length = 0;
};
let scheduleNodeRemoval = (vNode: VNode): void => {
removedNodes.push(vNode);
if (!requestedIdleCallback) {
requestedIdleCallback = true;
if (typeof window !== "undefined" && "requestIdleCallback" in window) {
window.requestIdleCallback(processPendingNodeRemovals, { timeout: 16 });
} else {
setTimeout(processPendingNodeRemovals, 16);
}
}
};
let nodeToRemove = (vNode: VNode) => {
let domNode: Node = vNode.domNode!;
if (vNode.properties) {
let exitAnimation = vNode.properties.exitAnimation;
if (exitAnimation) {
(domNode as HTMLElement).style.pointerEvents = "none";
let removeDomNode = () => {
if (domNode.parentNode) {
domNode.parentNode.removeChild(domNode);
scheduleNodeRemoval(vNode);
}
};
exitAnimation(domNode as Element, removeDomNode, vNode.properties);
return;
}
}
if (domNode.parentNode) {
domNode.parentNode.removeChild(domNode);
scheduleNodeRemoval(vNode);
}
};
let setProperties = (
domNode: Node,
properties: VNodeProperties | undefined,
projectionOptions: ProjectionOptions
) => {
if (!properties) {
return;
}
let eventHandlerInterceptor = projectionOptions.eventHandlerInterceptor;
let propNames = Object.keys(properties);
let propCount = propNames.length;
for (let i = 0; i < propCount; i++) {
let propName = propNames[i];
let propValue = properties[propName];
if (propName === "className") {
throw new Error('Property "className" is not supported, use "class".');
} else if (propName === "class") {
toggleClasses(domNode as HTMLElement, propValue as string, true);
} else if (propName === "classes") {
// object with string keys and boolean values
let classNames = Object.keys(propValue);
let classNameCount = classNames.length;
for (let j = 0; j < classNameCount; j++) {
let className = classNames[j];
if (propValue[className]) {
(domNode as Element).classList.add(className);
}
}
} else if (propName === "styles") {
// object with string keys and string (!) values
let styleNames = Object.keys(propValue);
let styleCount = styleNames.length;
for (let j = 0; j < styleCount; j++) {
let styleName = styleNames[j];
let styleValue = propValue[styleName];
if (styleValue) {
checkStyleValue(styleValue);
projectionOptions.styleApplyer!(<HTMLElement>domNode, styleName, styleValue);
}
}
} else if (propName !== "key" && propValue !== null && propValue !== undefined) {
let type = typeof propValue;
if (type === "function") {
if (propName.lastIndexOf("on", 0) === 0) {
// lastIndexOf(,0)===0 -> startsWith
if (eventHandlerInterceptor) {
propValue = eventHandlerInterceptor(propName, propValue, domNode, properties); // intercept eventhandlers
}
if (propName === "oninput") {
(function () {
// record the evt.target.value, because IE and Edge sometimes do a requestAnimationFrame between changing value and running oninput
let oldPropValue = propValue;
propValue = function (this: HTMLElement, evt: Event) {
oldPropValue.apply(this, [evt]);
(evt.target as any)["oninput-value"] = (evt.target as HTMLInputElement).value; // may be HTMLTextAreaElement as well
};
})();
}
}
(domNode as any)[propName] = propValue;
} else if (projectionOptions.namespace === NAMESPACE_SVG) {
if (propName === "href") {
(domNode as Element).setAttributeNS(NAMESPACE_XLINK, propName, propValue);
} else {
// all SVG attributes are read-only in DOM, so...
(domNode as Element).setAttribute(propName, propValue);
}
} else if (type === "string" && propName !== "value" && propName !== "innerHTML") {
(domNode as Element).setAttribute(propName, propValue);
} else {
(domNode as any)[propName] = propValue;
}
}
}
};
let addChildren = (
domNode: Node,
children: VNode[] | undefined,
projectionOptions: ProjectionOptions
) => {
if (!children) {
return;
}
for (let child of children) {
createDom(child, domNode, undefined, projectionOptions);
}
};
export let initPropertiesAndChildren = (
domNode: Node,
vnode: VNode,
projectionOptions: ProjectionOptions
): void => {
addChildren(domNode, vnode.children, projectionOptions); // children before properties, needed for value property of <select>.
if (vnode.text) {
domNode.textContent = vnode.text;
}
setProperties(domNode, vnode.properties, projectionOptions);
if (vnode.properties && vnode.properties.afterCreate) {
vnode.properties.afterCreate.apply(vnode.properties.bind || vnode.properties, [
domNode as Element,
projectionOptions,
vnode.vnodeSelector,
vnode.properties,
vnode.children,
]);
}
};
export let createDom = (
vnode: VNode,
parentNode: Node,
insertBefore: Node | null | undefined,
projectionOptions: ProjectionOptions
): void => {
let domNode: Node | undefined;
let start = 0;
let vnodeSelector = vnode.vnodeSelector;
let doc = parentNode.ownerDocument!;
if (vnodeSelector === "") {
domNode = vnode.domNode = doc.createTextNode(vnode.text!);
if (insertBefore !== undefined) {
parentNode.insertBefore(domNode, insertBefore);
} else {
parentNode.appendChild(domNode);
}
} else {
for (let i = 0; i <= vnodeSelector.length; ++i) {
let c = vnodeSelector.charAt(i);
if (i === vnodeSelector.length || c === "." || c === "#") {
let type = vnodeSelector.charAt(start - 1);
let found = vnodeSelector.slice(start, i);
if (type === ".") {
(domNode! as HTMLElement).classList.add(found);
} else if (type === "#") {
(domNode! as Element).id = found;
} else {
if (found === "svg") {
projectionOptions = extend(projectionOptions, {
namespace: NAMESPACE_SVG,
});
}
if (projectionOptions.namespace !== undefined) {
domNode = vnode.domNode = doc.createElementNS(projectionOptions.namespace, found);
} else {
domNode = vnode.domNode = vnode.domNode || doc.createElement(found);
if (found === "input" && vnode.properties && vnode.properties.type !== undefined) {
// IE8 and older don't support setting input type after the DOM Node has been added to the document
(domNode as Element).setAttribute("type", vnode.properties.type);
}
}
if (insertBefore !== undefined) {
parentNode.insertBefore(domNode, insertBefore);
} else if (domNode.parentNode !== parentNode) {
parentNode.appendChild(domNode);
}
}
start = i + 1;
}
}
initPropertiesAndChildren(domNode!, vnode, projectionOptions);
}
};
let updateDom: (previous: VNode, vnode: VNode, projectionOptions: ProjectionOptions) => boolean;
/**
* Adds or removes classes from an Element
* @param domNode the element
* @param classes a string separated list of classes
* @param on true means add classes, false means remove
*/
let toggleClasses = (domNode: HTMLElement, classes: string | null | undefined, on: boolean) => {
if (!classes) {
return;
}
classes.split(" ").forEach((classToToggle) => {
if (classToToggle) {
domNode.classList.toggle(classToToggle, on);
}
});
};
let updateProperties = (
domNode: Node,
previousProperties: VNodeProperties | undefined,
properties: VNodeProperties | undefined,
projectionOptions: ProjectionOptions
) => {
if (!properties) {
return;
}
let propertiesUpdated = false;
let propNames = Object.keys(properties);
let propCount = propNames.length;
for (let i = 0; i < propCount; i++) {
let propName = propNames[i];
// assuming that properties will be nullified instead of missing is by design
let propValue = properties[propName];
let previousValue = previousProperties![propName];
if (propName === "class") {
if (previousValue !== propValue) {
toggleClasses(domNode as HTMLElement, previousValue, false);
toggleClasses(domNode as HTMLElement, propValue, true);
}
} else if (propName === "classes") {
let classList = (domNode as Element).classList;
let classNames = Object.keys(propValue);
let classNameCount = classNames.length;
for (let j = 0; j < classNameCount; j++) {
let className = classNames[j];
let on = !!propValue[className];
let previousOn = !!previousValue[className];
if (on === previousOn) {
continue;
}
propertiesUpdated = true;
if (on) {
classList.add(className);
} else {
classList.remove(className);
}
}
} else if (propName === "styles") {
let styleNames = Object.keys(propValue);
let styleCount = styleNames.length;
for (let j = 0; j < styleCount; j++) {
let styleName = styleNames[j];
let newStyleValue = propValue[styleName];
let oldStyleValue = previousValue[styleName];
if (newStyleValue === oldStyleValue) {
continue;
}
propertiesUpdated = true;
if (newStyleValue) {
checkStyleValue(newStyleValue);
projectionOptions.styleApplyer!(domNode as HTMLElement, styleName, newStyleValue);
} else {
projectionOptions.styleApplyer!(domNode as HTMLElement, styleName, "");
}
}
} else {
if (!propValue && typeof previousValue === "string") {
propValue = "";
}
if (propName === "value") {
// value can be manipulated by the user directly and using event.preventDefault() is not an option
let domValue = (domNode as any)[propName];
if (
domValue !== propValue && // The 'value' in the DOM tree !== newValue
((domNode as any)["oninput-value"]
? domValue === (domNode as any)["oninput-value"] // If the last reported value to 'oninput' does not match domValue, do nothing and wait for oninput
: propValue !== previousValue) // Only update the value if the vdom changed
) {
// The edge cases are described in the tests
(domNode as any)[propName] = propValue; // Reset the value, even if the virtual DOM did not change
(domNode as any)["oninput-value"] = undefined;
} // else do not update the domNode, otherwise the cursor position would be changed
if (propValue !== previousValue) {
propertiesUpdated = true;
}
} else if (propValue !== previousValue) {
let type = typeof propValue;
if (type !== "function" || !projectionOptions.eventHandlerInterceptor) {
// Function updates are expected to be handled by the EventHandlerInterceptor
if (projectionOptions.namespace === NAMESPACE_SVG) {
if (propName === "href") {
(domNode as Element).setAttributeNS(NAMESPACE_XLINK, propName, propValue);
} else {
// all SVG attributes are read-only in DOM, so...
(domNode as Element).setAttribute(propName, propValue);
}
} else if (type === "string" && propName !== "innerHTML") {
if (propName === "role" && propValue === "") {
(domNode as any).removeAttribute(propName);
} else {
(domNode as Element).setAttribute(propName, propValue);
}
} else if ((domNode as any)[propName] !== propValue) {
// Comparison is here for side-effects in Edge with scrollLeft and scrollTop
(domNode as any)[propName] = propValue;
}
propertiesUpdated = true;
}
}
}
}
return propertiesUpdated;
};
let updateChildren = (
vnode: VNode,
domNode: Node,
oldChildren: VNode[] | undefined,
newChildren: VNode[] | undefined,
projectionOptions: ProjectionOptions
) => {
if (oldChildren === newChildren) {
return false;
}
oldChildren = oldChildren || emptyArray;
newChildren = newChildren || emptyArray;
let oldChildrenLength = oldChildren.length;
let newChildrenLength = newChildren.length;
let oldIndex = 0;
let newIndex = 0;
let i: number;
let textUpdated = false;
while (newIndex < newChildrenLength) {
let oldChild = oldIndex < oldChildrenLength ? oldChildren[oldIndex] : undefined;
let newChild = newChildren[newIndex];
if (oldChild !== undefined && same(oldChild, newChild)) {
textUpdated = updateDom(oldChild, newChild, projectionOptions) || textUpdated;
oldIndex++;
} else {
let findOldIndex = findIndexOfChild(oldChildren, newChild, oldIndex + 1);
if (findOldIndex >= 0) {
// Remove preceding missing children
for (i = oldIndex; i < findOldIndex; i++) {
nodeToRemove(oldChildren[i]);
checkDistinguishable(oldChildren, i, vnode, "removed");
}
textUpdated =
updateDom(oldChildren[findOldIndex], newChild, projectionOptions) || textUpdated;
oldIndex = findOldIndex + 1;
} else {
// New child
createDom(
newChild,
domNode,
oldIndex < oldChildrenLength ? oldChildren[oldIndex].domNode : undefined,
projectionOptions
);
nodeAdded(newChild);
checkDistinguishable(newChildren, newIndex, vnode, "added");
}
}
newIndex++;
}
if (oldChildrenLength > oldIndex) {
// Remove child fragments
for (i = oldIndex; i < oldChildrenLength; i++) {
nodeToRemove(oldChildren[i]);
checkDistinguishable(oldChildren, i, vnode, "removed");
}
}
return textUpdated;
};
updateDom = (previous, vnode, projectionOptions) => {
let domNode = previous.domNode!;
let textUpdated = false;
if (previous === vnode) {
return false; // By contract, VNode objects may not be modified anymore after passing them to maquette
}
let updated = false;
if (vnode.vnodeSelector === "") {
if (vnode.text !== previous.text) {
let newTextNode = domNode.ownerDocument!.createTextNode(vnode.text!);
domNode.parentNode!.replaceChild(newTextNode, domNode);
vnode.domNode = newTextNode;
textUpdated = true;
return textUpdated;
}
vnode.domNode = domNode;
} else {
if (vnode.vnodeSelector.lastIndexOf("svg", 0) === 0) {
// lastIndexOf(needle,0)===0 means StartsWith
projectionOptions = extend(projectionOptions, {
namespace: NAMESPACE_SVG,
});
}
if (previous.text !== vnode.text) {
updated = true;
if (vnode.text === undefined) {
domNode.removeChild(domNode.firstChild!); // the only textnode presumably
} else {
domNode.textContent = vnode.text;
}
}
vnode.domNode = domNode;
updated =
updateChildren(vnode, domNode, previous.children, vnode.children, projectionOptions) ||
updated;
updated =
updateProperties(domNode, previous.properties, vnode.properties, projectionOptions) ||
updated;
if (vnode.properties && vnode.properties.afterUpdate) {
vnode.properties.afterUpdate.apply(vnode.properties.bind || vnode.properties, [
<Element>domNode,
projectionOptions,
vnode.vnodeSelector,
vnode.properties,
vnode.children,
]);
}
}
if (updated && vnode.properties && vnode.properties.updateAnimation) {
vnode.properties.updateAnimation(<Element>domNode, vnode.properties, previous.properties);
}
return textUpdated;
};
export let createProjection = (vnode: VNode, projectionOptions: ProjectionOptions): Projection => {
return {
getLastRender: () => vnode,
update: (updatedVnode: VNode) => {
if (vnode.vnodeSelector !== updatedVnode.vnodeSelector) {
throw new Error(
"The selector for the root VNode may not be changed. (consider using dom.merge and add one extra level to the virtual DOM)"
);
}
let previousVNode = vnode;
vnode = updatedVnode;
updateDom(previousVNode, updatedVnode, projectionOptions);
},
domNode: <Element>vnode.domNode,
};
}; | the_stack |
* @module Tiles
*/
import { assert, BeTimePoint } from "@itwin/core-bentley";
import { Matrix3d, Point3d, Range3d, Transform, Vector3d, XYZProps } from "@itwin/core-geometry";
import { Cartographic, ColorDef, Frustum, FrustumPlanes, GeoCoordStatus, ViewFlagOverrides } from "@itwin/core-common";
import { BackgroundMapGeometry } from "../BackgroundMapGeometry";
import { GeoConverter } from "../GeoServices";
import { IModelApp } from "../IModelApp";
import { GraphicBranch } from "../render/GraphicBranch";
import { GraphicBuilder } from "../render/GraphicBuilder";
import { SceneContext } from "../ViewContext";
import { GraphicsCollectorDrawArgs, MapTile, RealityTile, RealityTileDrawArgs, RealityTileLoader, RealityTileParams, Tile, TileDrawArgs, TileGraphicType, TileParams, TileTree, TileTreeParams } from "./internal";
/** @internal */
export class TraversalDetails {
public queuedChildren = new Array<Tile>();
public childrenLoading = false;
public childrenSelected = false;
public initialize() {
this.queuedChildren.length = 0;
this.childrenLoading = false;
this.childrenSelected = false;
}
}
/** @internal */
export class TraversalChildrenDetails {
private _childDetails: TraversalDetails[] = [];
public initialize() {
for (const child of this._childDetails)
child.initialize();
}
public getChildDetail(index: number) {
while (this._childDetails.length <= index)
this._childDetails.push(new TraversalDetails());
return this._childDetails[index];
}
public combine(parentDetails: TraversalDetails) {
parentDetails.queuedChildren.length = 0;
parentDetails.childrenLoading = false;
parentDetails.childrenSelected = false;
for (const child of this._childDetails) {
parentDetails.childrenLoading = parentDetails.childrenLoading || child.childrenLoading;
parentDetails.childrenSelected = parentDetails.childrenSelected || child.childrenSelected;
for (const queuedChild of child.queuedChildren)
parentDetails.queuedChildren.push(queuedChild);
}
}
}
/** @internal */
export class TraversalSelectionContext {
public preloaded = new Set<RealityTile>();
public missing = new Array<RealityTile>();
public get selectionCountExceeded() { return this._maxSelectionCount === undefined ? false : (this.missing.length + this.selected.length) > this._maxSelectionCount; } // Avoid selecting excessive number of tiles.
constructor(public selected: Tile[], public displayedDescendants: Tile[][], public preloadDebugBuilder?: GraphicBuilder, private _maxSelectionCount?: number) { }
public selectOrQueue(tile: RealityTile, args: TileDrawArgs, traversalDetails: TraversalDetails) {
tile.selectSecondaryTiles(args, this);
tile.markUsed(args);
if (tile.isReady) {
args.markReady(tile);
this.selected.push(tile);
tile.markDisplayed();
this.displayedDescendants.push((traversalDetails.childrenSelected) ? traversalDetails.queuedChildren.slice() : []);
traversalDetails.queuedChildren.length = 0;
traversalDetails.childrenLoading = false;
traversalDetails.childrenSelected = true;
} else if (!tile.isNotFound) {
traversalDetails.queuedChildren.push(tile);
if (!tile.isLoaded)
this.missing.push(tile);
}
}
public preload(tile: RealityTile, args: TileDrawArgs): void {
if (!this.preloaded.has(tile)) {
if (this.preloadDebugBuilder)
tile.addBoundingGraphic(this.preloadDebugBuilder, ColorDef.red);
tile.markUsed(args);
tile.selectSecondaryTiles(args, this);
this.preloaded.add(tile);
if (!tile.isNotFound && !tile.isLoaded)
this.missing.push(tile);
}
}
public select(tiles: RealityTile[], args: TileDrawArgs): void {
for (const tile of tiles) {
tile.markUsed(args);
this.selected.push(tile);
this.displayedDescendants.push([]);
}
}
}
const scratchFrustum = new Frustum();
const scratchFrustumPlanes = new FrustumPlanes();
const scratchCarto = Cartographic.createZero();
const scratchPoint = Point3d.createZero(), scratchOrigin = Point3d.createZero();
const scratchRange = Range3d.createNull();
const scratchX = Vector3d.createZero(), scratchY = Vector3d.createZero(), scratchZ = Vector3d.createZero();
const scratchMatrix = Matrix3d.createZero(), scratchTransform = Transform.createZero();
interface ChildReprojection {
child: RealityTile;
ecefCenter: Point3d;
dbPoints: Point3d[]; // Center, xEnd, yEnd, zEnd
}
/** @internal */
export interface RealityTileTreeParams extends TileTreeParams {
readonly loader: RealityTileLoader;
readonly yAxisUp?: boolean;
readonly rootTile: RealityTileParams;
readonly rootToEcef?: Transform;
readonly gcsConverterAvailable: boolean;
}
/** @internal */
export class RealityTileTree extends TileTree {
public traversalChildrenByDepth: TraversalChildrenDetails[] = [];
public readonly loader: RealityTileLoader;
public readonly yAxisUp: boolean;
public cartesianRange: Range3d;
public cartesianTransitionDistance: number;
protected _gcsConverter: GeoConverter | undefined;
protected _rootTile: RealityTile;
protected _rootToEcef?: Transform;
protected _ecefToDb?: Transform;
public constructor(params: RealityTileTreeParams) {
super(params);
this.loader = params.loader;
this.yAxisUp = true === params.yAxisUp;
this._rootTile = this.createTile(params.rootTile);
this.cartesianRange = BackgroundMapGeometry.getCartesianRange(this.iModel);
this.cartesianTransitionDistance = this.cartesianRange.diagonal().magnitudeXY() * .25; // Transition distance from elliptical to cartesian.
this._gcsConverter = params.gcsConverterAvailable ? params.iModel.geoServices.getConverter("WGS84") : undefined;
if (params.rootToEcef) {
this._rootToEcef = params.rootToEcef;
const dbToRoot = this.iModelTransform.inverse();
if (dbToRoot) {
const dbToEcef = this._rootToEcef.multiplyTransformTransform(dbToRoot);
this._ecefToDb = dbToEcef.inverse();
}
}
}
public get rootTile(): RealityTile { return this._rootTile; }
public get is3d() { return true; }
public get maxDepth() { return this.loader.maxDepth; }
public get minDepth() { return this.loader.minDepth; }
public override get isContentUnbounded() { return this.loader.isContentUnbounded; }
public get isTransparent() { return false; }
protected _selectTiles(args: TileDrawArgs): Tile[] { return this.selectRealityTiles(args, []); }
public get viewFlagOverrides(): ViewFlagOverrides { return this.loader.viewFlagOverrides; }
public override get parentsAndChildrenExclusive() { return this.loader.parentsAndChildrenExclusive; }
public createTile(props: TileParams): RealityTile { return new RealityTile(props, this); }
public prune(): void {
const olderThan = BeTimePoint.now().minus(this.expirationTime);
this.rootTile.purgeContents(olderThan);
}
public draw(args: TileDrawArgs): void {
const displayedTileDescendants = new Array<RealityTile[]>();
const debugControl = args.context.target.debugControl;
const selectBuilder = (debugControl && debugControl.displayRealityTileRanges) ? args.context.createSceneGraphicBuilder() : undefined;
const preloadDebugBuilder = (debugControl && debugControl.displayRealityTilePreload) ? args.context.createSceneGraphicBuilder() : undefined;
const graphicTypeBranches = new Map<TileGraphicType, GraphicBranch>();
const selectedTiles = this.selectRealityTiles(args, displayedTileDescendants, preloadDebugBuilder);
let sortIndices;
if (!this.parentsAndChildrenExclusive) {
sortIndices = selectedTiles.map((_x, i) => i);
sortIndices.sort((a, b) => selectedTiles[a].depth - selectedTiles[b].depth);
}
const classifier = args.context.planarClassifiers.get(this.modelId);
if (classifier && !(args instanceof GraphicsCollectorDrawArgs))
classifier.collectGraphics(args.context, { modelId: this.modelId, tiles: selectedTiles, location: args.location, isPointCloud: this.isPointCloud });
assert(selectedTiles.length === displayedTileDescendants.length);
for (let i = 0; i < selectedTiles.length; i++) {
const index = sortIndices ? sortIndices[i] : i;
const selectedTile = selectedTiles[index];
const graphics = args.getTileGraphics(selectedTile);
const tileGraphicType = selectedTile.graphicType;
let targetBranch;
if (undefined !== tileGraphicType && tileGraphicType !== args.context.graphicType) {
if (!(targetBranch = graphicTypeBranches.get(tileGraphicType))) {
graphicTypeBranches.set(tileGraphicType, targetBranch = new GraphicBranch(false));
targetBranch.setViewFlagOverrides(args.graphics.viewFlagOverrides);
targetBranch.symbologyOverrides = args.graphics.symbologyOverrides;
}
}
if (!targetBranch)
targetBranch = args.graphics;
if (undefined !== graphics) {
const displayedDescendants = displayedTileDescendants[index];
if (0 === displayedDescendants.length || !this.loader.parentsAndChildrenExclusive || selectedTile.allChildrenIncluded(displayedDescendants)) {
targetBranch.add(graphics);
if (selectBuilder) selectedTile.addBoundingGraphic(selectBuilder, ColorDef.green);
} else {
if (selectBuilder)
selectedTile.addBoundingGraphic(selectBuilder, ColorDef.red);
for (const displayedDescendant of displayedDescendants) {
const clipVector = displayedDescendant.getContentClip();
if (selectBuilder)
displayedDescendant.addBoundingGraphic(selectBuilder, ColorDef.blue);
if (undefined === clipVector) {
targetBranch.add(graphics);
} else {
clipVector.transformInPlace(args.location);
if (!this.isTransparent)
for (const primitive of clipVector.clips)
for (const clipPlanes of primitive.fetchClipPlanesRef()!.convexSets)
for (const plane of clipPlanes.planes)
plane.offsetDistance(-displayedDescendant.radius * .05); // Overlap with existing (high resolution) tile slightly to avoid cracks.
const branch = new GraphicBranch(false);
branch.add(graphics);
const clipVolume = args.context.target.renderSystem.createClipVolume(clipVector);
targetBranch.add(args.context.createGraphicBranch(branch, Transform.createIdentity(), { clipVolume }));
}
}
}
if (preloadDebugBuilder)
targetBranch.add(preloadDebugBuilder.finish());
if (selectBuilder)
targetBranch.add(selectBuilder.finish());
const rangeGraphic = selectedTile.getRangeGraphic(args.context);
if (undefined !== rangeGraphic)
targetBranch.add(rangeGraphic);
}
}
args.drawGraphics();
for (const graphicTypeBranch of graphicTypeBranches) {
args.drawGraphicsWithType(graphicTypeBranch[0], graphicTypeBranch[1]);
}
}
public getTraversalChildren(depth: number) {
while (this.traversalChildrenByDepth.length <= depth)
this.traversalChildrenByDepth.push(new TraversalChildrenDetails());
return this.traversalChildrenByDepth[depth];
}
public doReprojectChildren(tile: Tile): boolean {
if (!(tile instanceof RealityTile) || !tile.region || this._gcsConverter === undefined || this._rootToEcef === undefined || undefined === this._ecefToDb)
return false;
const tileRange = this.iModelTransform.isIdentity ? tile.range : this.iModelTransform.multiplyRange(tile.range, scratchRange);
return this.cartesianRange.intersectsRange(tileRange);
}
public reprojectAndResolveChildren(parent: Tile, children: Tile[], resolve: (children: Tile[] | undefined) => void): void {
if (!this.doReprojectChildren(parent)) {
resolve(children);
return;
}
const ecefToDb = this._ecefToDb!; // Tested for undefined in doReprojectChildren
const rootToDb = this.iModelTransform;
const dbToEcef = ecefToDb.inverse()!;
const reprojectChildren = new Array<ChildReprojection>();
for (const child of children) {
const realityChild = child as RealityTile;
const childRange = realityChild.rangeCorners ? Range3d.createTransformedArray(rootToDb, realityChild.rangeCorners) : rootToDb.multiplyRange(realityChild.contentRange, scratchRange);
const dbCenter = childRange.center;
const ecefCenter = dbToEcef.multiplyPoint3d(dbCenter);
const dbPoints = [dbCenter, dbCenter.plusXYZ(1), dbCenter.plusXYZ(0, 1), dbCenter.plusXYZ(0, 0, 1)];
reprojectChildren.push({ child: realityChild, ecefCenter, dbPoints });
}
if (reprojectChildren.length === 0)
resolve(children);
else {
const requestProps = new Array<XYZProps>();
for (const reprojection of reprojectChildren) {
for (const dbPoint of reprojection.dbPoints) {
const ecefPoint = dbToEcef.multiplyPoint3d(dbPoint);
const carto = Cartographic.fromEcef(ecefPoint, scratchCarto);
if (carto)
requestProps.push({ x: carto.longitudeDegrees, y: carto.latitudeDegrees, z: carto.height });
}
}
if (requestProps.length !== 4 * reprojectChildren.length)
resolve(children);
else {
this._gcsConverter!.getIModelCoordinatesFromGeoCoordinates(requestProps).then((response) => {
const reprojectedCoords = response.iModelCoords;
const dbToRoot = rootToDb.inverse()!;
const getReprojectedPoint = (original: Point3d, reprojectedXYZ: XYZProps) => {
scratchPoint.setFromJSON(reprojectedXYZ);
const cartesianDistance = this.cartesianRange.distanceToPoint(scratchPoint);
if (cartesianDistance < this.cartesianTransitionDistance)
return scratchPoint.interpolate(cartesianDistance / this.cartesianTransitionDistance, original, scratchPoint);
else
return original;
};
let responseIndex = 0;
for (const reprojection of reprojectChildren) {
if (reprojectedCoords.every((coord) => coord.s === GeoCoordStatus.Success)) {
const reprojectedOrigin = getReprojectedPoint(reprojection.dbPoints[0], reprojectedCoords[responseIndex++].p).clone(scratchOrigin);
const xVector = Vector3d.createStartEnd(reprojectedOrigin, getReprojectedPoint(reprojection.dbPoints[1], reprojectedCoords[responseIndex++].p), scratchX);
const yVector = Vector3d.createStartEnd(reprojectedOrigin, getReprojectedPoint(reprojection.dbPoints[2], reprojectedCoords[responseIndex++].p), scratchY);
const zVector = Vector3d.createStartEnd(reprojectedOrigin, getReprojectedPoint(reprojection.dbPoints[3], reprojectedCoords[responseIndex++].p), scratchZ);
const matrix = Matrix3d.createColumns(xVector, yVector, zVector, scratchMatrix);
if (matrix !== undefined) {
const dbReprojection = Transform.createMatrixPickupPutdown(matrix, reprojection.dbPoints[0], reprojectedOrigin, scratchTransform);
if (dbReprojection) {
const rootReprojection = dbToRoot.multiplyTransformTransform(dbReprojection).multiplyTransformTransform(rootToDb);
reprojection.child.reproject(rootReprojection);
}
}
}
}
resolve(children);
}).catch(() => {
resolve(children); // Error occured in reprojection - just resolve with unprojected corners.
});
}
}
}
public getBaseRealityDepth(_sceneContext: SceneContext) { return -1; }
public selectRealityTiles(args: TileDrawArgs, displayedDescendants: RealityTile[][], preloadDebugBuilder?: GraphicBuilder): RealityTile[] {
this._lastSelected = BeTimePoint.now();
const selected: RealityTile[] = [];
const context = new TraversalSelectionContext(selected, displayedDescendants, preloadDebugBuilder, args.maxRealityTreeSelectionCount);
const rootTile = this.rootTile;
const debugControl = args.context.target.debugControl;
const freezeTiles = debugControl && debugControl.freezeRealityTiles;
rootTile.selectRealityTiles(context, args, new TraversalDetails());
const baseDepth = this.getBaseRealityDepth(args.context);
if (!args.context.target.renderSystem.isMobile && 0 === context.missing.length) { // We skip preloading on mobile devices.
if (baseDepth > 0) // Maps may force loading of low level globe tiles.
rootTile.preloadRealityTilesAtDepth(baseDepth, context, args);
if (!freezeTiles)
this.preloadTilesForScene(args, context, undefined);
}
if (!freezeTiles)
for (const tile of context.missing) {
const loadableTile = tile.loadableTile;
loadableTile.markUsed(args);
args.insertMissing(loadableTile);
}
if (debugControl && debugControl.logRealityTiles) {
this.logTiles("Selected: ", selected.values());
const preloaded = [];
for (const tile of context.preloaded)
preloaded.push(tile);
this.logTiles("Preloaded: ", preloaded.values());
this.logTiles("Missing: ", context.missing.values());
const imageryTiles: RealityTile[] = [];
for (const selectedTile of selected) {
if (selectedTile instanceof MapTile) {
const selectedImageryTiles = (selectedTile).imageryTiles;
if (selectedImageryTiles)
selectedImageryTiles.forEach((tile) => imageryTiles.push(tile));
}
}
if (imageryTiles.length)
this.logTiles("Imagery:", imageryTiles.values());
}
IModelApp.tileAdmin.addTilesForViewport(args.context.viewport, selected, args.readyTiles);
return selected;
}
public preloadTilesForScene(args: TileDrawArgs, context: TraversalSelectionContext, frustumTransform?: Transform) {
const preloadFrustum = args.viewingSpace.getPreloadFrustum(frustumTransform, scratchFrustum);
const preloadFrustumPlanes = new FrustumPlanes(preloadFrustum);
const worldToNpc = preloadFrustum.toMap4d();
const preloadWorldToViewMap = args.viewingSpace.calcNpcToView().multiplyMapMap(worldToNpc!);
const preloadArgs = new RealityTileDrawArgs(args, preloadWorldToViewMap, preloadFrustumPlanes);
scratchFrustumPlanes.init(preloadFrustum);
if (context.preloadDebugBuilder) {
context.preloadDebugBuilder.setSymbology(ColorDef.blue, ColorDef.blue, 2, 0);
context.preloadDebugBuilder.addFrustum(preloadFrustum);
}
this.rootTile.preloadTilesInFrustum(preloadArgs, context, 2);
}
protected logTiles(label: string, tiles: IterableIterator<Tile>) {
let depthString = "";
let min = 10000, max = -10000;
let count = 0;
const depthMap = new Map<number, number>();
for (const tile of tiles) {
count++;
const depth = tile.depth;
min = Math.min(min, tile.depth);
max = Math.max(max, tile.depth);
const found = depthMap.get(depth);
depthMap.set(depth, found === undefined ? 1 : found + 1);
}
depthMap.forEach((key, value) => depthString += `${key}-${value}, `);
// eslint-disable-next-line no-console
console.log(`${label}: ${count} Min: ${min} Max: ${max} Depths: ${depthString}`);
}
} | the_stack |
import config from "../config"
export type PageKind = 'view' | 'static-page' | 'page'
export type Options = {
kind: (path: string[]) => PageKind
isStaticView: (path: string[]) => boolean
isStaticPage: (path: string[]) => boolean
isStandardPage: (path: string[]) => boolean
}
export const options = (kind: (path: string[]) => PageKind) : Options => ({
kind,
isStaticView: p => kind(p) === 'view',
isStaticPage: p => kind(p) === 'static-page',
isStandardPage: p => kind(p) === 'page',
})
// [ 'Home_' ] => true
const isHomepage = (path: string[]) =>
path.join('') === config.reserved.homepage
// [ 'NotFound' ] => true
const isNotFoundPage = (path: string[]) =>
path.join('') === config.reserved.notFound
// [ 'Users', 'Name_', 'Settings' ] => [ 'Name' ]
const dynamicRouteSegments = (path : string[]) : string[] =>
isHomepage(path) || isNotFoundPage(path)
? []
: path.filter(isDynamicSegment)
.map(segment => segment.substr(0, segment.length - 1))
const isDynamicSegment = (segment : string) : boolean =>
segment !== config.reserved.homepage
&& segment !== config.reserved.notFound
&& segment.endsWith('_')
// "AboutUs" => "aboutUs"
const fromPascalToCamelCase = (str : string) : string =>
str[0].toLowerCase() + str.substring(1)
// "AboutUs" => "about-us"
const fromPascalToSlugCase = (str : string) =>
str.split('').map((c, i) => i === 0 || c === c.toLowerCase() ? c : `-${c}`).join('').toLowerCase()
// "about-us" => "AboutUs"
const fromSlugToPascalCase = (str : string) =>
str.split('-').map(c => c[0].toUpperCase() + c.substring(1)).join('')
// "/about-us" => [ "AboutUs" ]
// "Pages.AboutUs" => [ "AboutUs" ]
// "Pages/AboutUs.elm" => [ "AboutUs" ]
export const urlArgumentToPages = (url : string) : string[] => {
// Cleanup common mistakes
if (url.endsWith('.elm')) { url = url.split('.elm').join('') }
if (url.startsWith('Pages')) { url = url.substring('Pages'.length) }
return url === '/'
? [ config.reserved.homepage ]
: url.split('/')
.map(str => str.split('.'))
.reduce((a, b) => a.concat(b))
.filter(a => a).map(seg => seg.startsWith(':') ? seg.slice(1) + '_' : seg)
.map(fromSlugToPascalCase)
}
// [ "Settings", "Notifications" ] => "Settings__Notifications"
export const routeVariant = (path : string[]) : string =>
path.join('__')
// General Elm things
export const multilineList = (items : string[]) : string =>
items.length === 0
? `[]`
: `[ ${items.join('\n, ')}\n]`
export const multilineRecord = (sep : ':' | '=', items: [string, string][]) : string =>
items.length === 0
? `{}`
: `{ ${items.map(([k, v]) => `${k} ${sep} ${v}`).join('\n, ')}\n}`
export const customType = (type : string, variants : string[]) : string =>
`type ${type}\n = ${variants.join('\n | ')}`
export const indent = (lines : string, n : number = 1) : string =>
lines.split('\n')
.map(line => [...Array(n)].map(_ => ` `).join('') + line)
.join('\n')
// Used by Gen.Route
export const routeParameters = (path : string[]) : string => {
const dynamics = dynamicRouteSegments(path)
if (dynamics.length === 0) {
return `()`
} else {
return `{ ${dynamics.map(d => `${fromPascalToCamelCase(d)} : String`).join(', ')} }`
}
}
const routeParameters2 = (path : string[]) : string => {
const dynamics = dynamicRouteSegments(path)
if (dynamics.length === 0) {
return ``
} else {
return ` { ${dynamics.map(d => `${fromPascalToCamelCase(d)} : String`).join(', ')} }`
}
}
const routeParamVariable = (path : string[]) : string =>
(dynamicRouteSegments(path).length === 0)
? ``
: ` params`
const routeParamValue = (path : string[]) : string =>
(dynamicRouteSegments(path).length === 0)
? `()`
: `params`
export const paramsRouteParserMap = (path : string[]) : string =>
dynamicRouteSegments(path).length === 0
? ``
: `Parser.map Params `
export const routeParser = (path : string[]) : string => {
const fromPiece = (p : string) : string =>
(p === config.reserved.homepage) ? `Parser.top`
: p.endsWith('_') ? `Parser.string`
: `Parser.s "${fromPascalToSlugCase(p)}"`
return `${paramsRouteParserMap(path)}(` + path.map(fromPiece).join(' </> ') + `)`
}
export const routeParserMap = (path: string[]) : string =>
`Parser.map ${routeVariant(path)} ${paramsModule(path)}.parser`
export const routeTypeVariant = (path : string[]) : string =>
`${routeVariant(path)}${routeParameters2(path)}`
export const routeTypeDefinition = (paths: string[][]) : string =>
customType(`Route`, paths.map(routeTypeVariant))
export const routeParserList = (paths: string[][]) : string =>
multilineList(paths.map(routeParserMap))
export const routeToHref = (paths: string[][]) : string =>
caseExpression(paths, {
variable: 'route',
condition: (path) =>
(dynamicRouteSegments(path).length === 0)
? routeVariant(path)
: `${routeVariant(path)} params`,
result: (path) => `joinAsHref ${routeToHrefSegments(path)}`
})
export const routeToHrefSegments = (path: string[]) : string => {
const segments = path.filter(p => p !== config.reserved.homepage)
const hrefFragments =
segments.map(segment =>
isDynamicSegment(segment)
? `params.${fromPascalToCamelCase(segment.substring(0, segment.length - 1))}`
: `"${fromPascalToSlugCase(segment)}"`
)
return hrefFragments.length === 0
? `[]`
: `[ ${hrefFragments.join(', ')} ]`
}
export const paramsImports = (paths: string[][]) : string =>
paths.map(path => `import Gen.Params.${path.join('.')}`).join('\n')
export const pagesImports = (paths: string[][]) : string =>
paths.map(path => `import ${pageModuleName(path)}`).join('\n')
const pageModuleName = (path : string[]) : string =>
`Pages.${path.join('.')}`
export const pagesModelDefinition = (paths : string[][], options : Options) : string =>
customType('Model',
paths.map(path => (() => {
if (path[0] === config.reserved.redirecting) return config.reserved.redirecting
switch (options.kind(path)) {
case 'view': return `${modelVariant(path)} ${params(path)}`
case 'static-page': return `${modelVariant(path)} ${params(path)} ${model(path, options)}`
case 'page': return `${modelVariant(path)} ${params(path)} ${model(path, options)}`
}
})())
)
export const pagesMsgDefinition = (paths : string[][], options: Options) : string =>
(paths.length === 0)
? `type Msg = None`
: customType('Msg', paths.map(path => `${msgVariant(path)} ${msg(path, options)}`))
export const pagesBundleAnnotation = (paths : string[][], options : Options) : string =>
indent(multilineRecord(':',
paths.map(path => [
bundleName(path),
(() => {
switch (options.kind(path)) {
case 'view': return `Static ${params(path)}`
case 'static-page': return `Bundle ${params(path)} ${model(path, options)} ${msg(path, options)}`
case `page`: return `Bundle ${params(path)} ${model(path, options)} ${msg(path, options)}`
}
})()
])
))
export const pagesBundleDefinition = (paths : string[][], options : Options) : string =>
indent(multilineRecord('=',
paths.map(path => [
bundleName(path),
(() => {
switch (options.kind(path)) {
case 'view': return `static ${pageModuleName(path)}.view Model.${modelVariant(path)}`
case 'static-page': return `bundle ${pageModuleName(path)}.page Model.${modelVariant(path)} Msg.${msgVariant(path)}`
case `page`: return `bundle ${pageModuleName(path)}.page Model.${modelVariant(path)} Msg.${msgVariant(path)}`
}
})()
])
))
const bundleName = (path : string[]) : string =>
path.map(fromPascalToCamelCase).join('__')
const paramsModule = (path : string[]) =>
`Gen.Params.${path.join('.')}`
const params = (path : string[]) =>
`${paramsModule(path)}.Params`
const model = (path: string[], options : Options) : string => {
switch (options.kind(path)) {
case 'view': return `()`
case 'static-page': return `()`
case 'page': return `Pages.${path.join('.')}.Model`
}
}
const modelVariant = (path: string[]) : string =>
`${path.join('__')}`
const msgVariant = (path: string[]) : string =>
`${path.join('__')}`
const msg = (path: string[], options: Options) : string =>
options.isStandardPage(path)
? `Pages.${path.join('.')}.Msg`
: `Never`
export const pagesInitBody = (paths: string[][]) : string =>
indent(caseExpression(paths, {
variable: 'route',
condition: path => `Route.${routeVariant(path)}${routeParamVariable(path)}`,
result: path => `pages.${bundleName(path)}.init ${routeParamValue(path)}`
}))
export const pagesUpdateBody = (paths: string[][], options : Options) : string =>
indent(caseExpression(paths, {
variable: '( msg_, model_ )',
condition: path => `( Msg.${msgVariant(path)} msg, ${destructuredModel(path, options)} )`,
result: path => `pages.${bundleName(path)}.update params msg model`
}))
export const pagesUpdateCatchAll =
`
_ ->
\\_ _ _ -> ( model_, Effect.none )`
export const pagesViewBody = (paths: string[][], options : Options) : string =>
indent(caseExpressionWithRedirectingModel(`\\_ _ _ -> View.none`, paths, {
variable: 'model_',
condition: path => `${destructuredModel(path, options)}`,
result: path => `pages.${bundleName(path)}.view ${pageModelArguments(path, options)}`
}))
export const pagesSubscriptionsBody = (paths: string[][], options : Options) : string =>
indent(caseExpressionWithRedirectingModel(`\\_ _ _ -> Sub.none`, paths, {
variable: 'model_',
condition: path => `${destructuredModel(path, options)}`,
result: path => `pages.${bundleName(path)}.subscriptions ${pageModelArguments(path, options)}`
}))
const caseExpressionWithRedirectingModel = (fallback : string, items: string[][], options : { variable : string, condition : (item: string[]) => string, result: (item: string[]) => string }) =>
caseExpression([ [ config.reserved.redirecting ] ].concat(items), {
variable: options.variable,
condition: (item) => item[0] === config.reserved.redirecting
? `Model.${config.reserved.redirecting}`
: options.condition(item),
result: (item) => item[0] === config.reserved.redirecting
? fallback
: options.result(item)
})
const caseExpression = <T>(items: T[], options : { variable : string, condition : (item: T) => string, result: (item: T) => string }) =>
`case ${options.variable} of
${items.map(item => ` ${options.condition(item)} ->\n ${options.result(item)}`).join('\n\n')}`
const destructuredModel = (path: string[], options : Options) : string => {
switch (options.kind(path)) {
case 'view': return `Model.${modelVariant(path)} params`
case 'static-page': return `Model.${modelVariant(path)} params model`
case 'page': return `Model.${modelVariant(path)} params model`
}
}
const pageModelArguments = (path: string[], options : Options) : string => {
switch (options.kind(path)) {
case 'view': return `params ()`
case 'static-page': return `params model`
case 'page': return `params model`
}
}
const exposes = (value : string) => (str : string) : boolean => {
const regex = new RegExp('^module\\s+[^\\s]+\\s+exposing\\s+\\(((?:\\.\\)|[^)])+)\\)')
const match = (str.match(regex) || [])[1]
if (match) {
return match.split(',').filter(a => a).map(a => a.trim()).includes(value)
} else {
return false
}
}
export const exposesModel = exposes('Model')
export const exposesMsg = (str : string) => exposes('Msg')(str) || exposes('Msg(..)')(str)
export const exposesPageFunction = exposes('page')
export const exposesViewFunction = exposes('view')
export const isStandardPage = (src : string) =>
exposesPageFunction(src)
&& exposesModel(src)
&& exposesMsg(src)
export const isStaticPage = (src : string) =>
exposesPageFunction(src)
export const isStaticView = (src : string) =>
exposesViewFunction(src) | the_stack |
import { collectionWithQueryAtom } from "@/atoms/firestore";
import {
actionDeleteDoc,
actionDuplicateDoc,
actionSetFieldValue,
} from "@/atoms/firestore.action";
import {
navigatorCollectionPathAtom,
navigatorPathAtom,
propertyListAtom,
propertyListCoreAtom,
sorterAtom,
} from "@/atoms/navigator";
import {
actionAddFilter,
actionExportDocCSV,
actionExportDocJSON,
actionExportViewCSV,
actionExportViewJSON,
actionRemoveProperty,
actionSetProperty,
actionSubmitQuery,
} from "@/atoms/navigator.action";
import {
atomObservable,
getRecoilExternalLoadable,
setRecoilExternalState,
} from "@/atoms/RecoilExternalStatePortal";
import { largeDataAtom } from "@/atoms/ui";
import { actionToggleModalPickProperty } from "@/atoms/ui.action";
import { useContextMenu } from "@/hooks/contextMenu";
import { ClientDocumentSnapshot } from "@/types/ClientDocumentSnapshot";
import {
getIdFromPath,
getSampleColumn,
ignoreBackdropEvent,
} from "@/utils/common";
import { Cell } from "@zendeskgarden/react-tables";
import classNames from "classnames";
import { get, sumBy, throttle, uniqueId } from "lodash";
import React, { useCallback, useEffect, useMemo, useRef } from "react";
import { Scrollbars } from "react-custom-scrollbars";
import {
useFlexLayout,
useResizeColumns,
useSortBy,
useTable,
} from "react-table";
import { useAsync, useCustomCompareEffect } from "react-use";
import AutoSizer from "react-virtualized-auto-sizer";
import { FixedSizeList } from "react-window";
import { useRecoilValue, useSetRecoilState } from "recoil";
import EditableCell, { IDReadOnlyField } from "../EditableCell";
const EASY_SCROLL_COLUMN_COUNT = 5;
function TableWrapper({
columns,
data,
onRowClick,
onSortColumn,
}: {
columns: any[];
data: ClientDocumentSnapshot[];
onRowClick: (
e: React.MouseEvent<HTMLDivElement, MouseEvent>,
doc: ClientDocumentSnapshot
) => void;
onSortColumn: (
sorter: {
id: string;
desc: boolean;
}[]
) => void;
}) {
const defaultColumn = React.useMemo(
() => ({
minWidth: 50,
width: 100,
maxWidth: 600,
}),
[]
);
const {
getTableProps,
getTableBodyProps,
headerGroups,
rows,
prepareRow,
state,
} = useTable(
{
columns,
data,
defaultColumn,
disableMultiSort: false,
manualSortBy: true,
} as any,
useSortBy,
useResizeColumns,
useFlexLayout
// useBlockLayout
);
const tableState = state as any;
const listRef = useRef();
const headerRef = useRef<HTMLDivElement>(null);
const newestDocRef = useRef<undefined | ClientDocumentSnapshot>(undefined);
const scrollerRef = useRef(null);
useEffect(() => {
onSortColumn(tableState.sortBy);
}, [tableState.sortBy]);
useEffect(() => {
const pathObserver = atomObservable(navigatorPathAtom).subscribe({
next: (path) => {
const docId = getIdFromPath(path);
if (docId) {
scrollToDocId(docId);
}
},
error: (error) => {
console.log(error);
},
});
return () => {
return pathObserver.unsubscribe();
};
}, [data]);
// Hook to auto scroll to newest doc
useCustomCompareEffect(
() => {
const newestDoc = data
.filter((doc) => doc.isNew)
.sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime())
.pop();
if (newestDoc && newestDoc.id !== newestDocRef.current?.id) {
newestDocRef.current = newestDoc;
scrollToDocId(newestDoc.id);
}
},
[data.length],
([prevLength], [nextLength]) => {
return prevLength <= nextLength;
}
);
const scrollToDocId = useCallback(
(id: string) => {
const docElement = document.querySelector(`[data-id='${id}']`);
if (docElement) {
const observer = new IntersectionObserver(
function (entries, observer) {
if (!entries[0].isIntersecting) {
docElement.scrollIntoView({ block: "center" });
}
// Ignore scroll if element is in view
observer.disconnect();
},
{ threshold: [1] }
);
observer.observe(docElement);
return;
}
const dataIndex = data.findIndex((doc) => doc.id === id);
const position = (listRef.current as any)?._getItemStyle(dataIndex);
if (position && position.top >= 0) {
(scrollerRef.current as any)?.scrollTop(position.top);
}
},
[data]
);
const RenderRow = useCallback(
({ data, index, style }) => {
const row = data[index];
prepareRow(row);
const rowOrigin = row.original as ClientDocumentSnapshot;
return (
<div
{...row.getRowProps({
style: {
...style,
minWidth: "100%",
width: "auto",
},
key: rowOrigin.id,
})}
className="border-b border-gray-300 hover:bg-gray-200 group"
data-id={rowOrigin.id}
onClick={(e) => onRowClick(e, rowOrigin)}
>
{row.cells.map((cell) => {
return (
// eslint-disable-next-line react/jsx-key
<div
{...cell.getCellProps()}
className="border-r border-gray-200 last:border-r-0 group-hover:border-gray-300"
cm-template="rowContext"
cm-id="rowContext"
cm-payload-id={rowOrigin.id}
cm-payload-path={rowOrigin.ref.path}
cm-payload-column={cell.column.id}
>
{cell.render("Cell")}
</div>
);
})}
</div>
);
},
[prepareRow]
);
const handleScroll = useCallback(
({ target }) => {
if (columns.length < EASY_SCROLL_COLUMN_COUNT) {
scrollWindowDebounce(target);
}
},
[columns.length]
);
const handleScrollStop = useCallback(() => {
if (columns.length >= EASY_SCROLL_COLUMN_COUNT) {
const scrollTop = (scrollerRef.current as any)?.getScrollTop() || 0;
const scrollLeft = (scrollerRef.current as any)?.getScrollLeft() || 0;
(listRef.current as any)?.scrollTo(scrollTop);
headerRef.current?.scrollTo(scrollLeft, 0);
}
}, [scrollerRef.current, columns.length]);
const scrollWindowDebounce = useCallback(
throttle(({ scrollTop, scrollLeft }) => {
(listRef.current as any)?.scrollTo(scrollTop);
headerRef.current?.scrollTo(scrollLeft, 0);
}, 200),
[]
);
return (
<AutoSizer>
{({ height, width }) => (
<table
{...getTableProps()}
className="w-full h-full border-b border-gray-300"
>
<thead>
{headerGroups.map((headerGroup) => (
// eslint-disable-next-line react/jsx-key
<div
{...headerGroup.getHeaderGroupProps({
style: {
width,
overflow: "hidden",
minWidth: "unset",
},
className: "border-t border-b border-gray-300",
})}
ref={headerRef}
>
{headerGroup.headers.map((column) => (
// eslint-disable-next-line react/jsx-key
<th
{...column.getHeaderProps(
(column as any).getSortByToggleProps()
)}
className="text-left text-gray-500 border-r border-gray-200"
>
<div
{...(column as any).getResizerProps({
onClick: ignoreBackdropEvent,
})}
className={classNames(
"w-px h-full inline-block transform translate-x-px hover:bg-gray-400 pl-1 absolute top-0 -right-px"
)}
/>
{column.render("Header", {
isSorted: (column as any)?.isSorted,
isSortedDesc: (column as any).isSortedDesc,
toggleSortBy: (column as any).toggleSortBy,
})}
</th>
))}
</div>
))}
</thead>
<tbody {...getTableBodyProps()} className="block h-full">
<Scrollbars
style={{ height: height - 36, width }}
autoHide
onScroll={handleScroll}
onScrollStop={handleScrollStop}
hideTracksWhenNotNeeded
ref={scrollerRef}
>
<FixedSizeList
height={height - 34}
itemCount={rows.length}
itemSize={36}
width={width}
itemData={rows}
itemKey={(id, data) => data[id].original.id}
ref={listRef}
style={{ overflow: false }}
>
{RenderRow}
</FixedSizeList>
</Scrollbars>
</tbody>
</table>
)}
</AutoSizer>
);
}
interface IColumnHeaderProps {
fieldPath: string;
collectionPath: string;
isSorted: boolean;
isSortedDesc: boolean;
hidable: boolean;
toggleSortBy: (descending: boolean, isMulti: boolean) => void;
isIdColumn?: boolean;
}
function ColumnHeader({
fieldPath,
collectionPath,
isSorted,
isSortedDesc,
toggleSortBy,
hidable = true,
isIdColumn = false,
}: IColumnHeaderProps) {
// TODO: Move listener to outside component
useContextMenu(
"ADD",
() => {
actionToggleModalPickProperty(true);
},
fieldPath
);
useContextMenu(
"HIDE",
({ column }: { column: string }) => {
if (hidable) {
actionRemoveProperty(collectionPath, column);
}
},
fieldPath
);
useContextMenu(
"ASC",
() => {
toggleSortBy(false, false);
},
fieldPath
);
useContextMenu(
"DESC",
() => {
toggleSortBy(true, false);
},
fieldPath
);
useContextMenu(
"FILTER",
({ column }: { column: string }) => {
actionAddFilter(column, "==", collectionPath);
},
fieldPath
);
return (
<div
className="flex flex-row items-center justify-between p-1.5"
cm-template={isIdColumn ? undefined : "columnHeaderContext"}
cm-payload-column={fieldPath}
cm-id={fieldPath}
>
<div className="font-semibold text-gray-800 truncate">{fieldPath}</div>
{isSorted && (
<span>
{isSortedDesc ? (
<svg
className="w-4"
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M3 4h13M3 8h9m-9 4h6m4 0l4-4m0 0l4 4m-4-4v12"
/>
</svg>
) : (
<svg
className="w-4"
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M3 4h13M3 8h9m-9 4h9m5-4v12m0 0l-4-4m4 4l4-4"
/>
</svg>
)}
</span>
)}
</div>
);
}
interface IRowContextPayload {
id: string;
path: string;
}
function DataTable() {
const collectionPath = useRecoilValue(navigatorCollectionPathAtom);
const setPath = useSetRecoilState(navigatorPathAtom);
const data = useRecoilValue(collectionWithQueryAtom(collectionPath));
const properties = useRecoilValue(propertyListAtom(collectionPath));
useAsync(async () => {
// Auto set property if it haven't set
const propertiesCore = await getRecoilExternalLoadable(
propertyListCoreAtom(collectionPath)
).toPromise();
if (!propertiesCore && properties.length === 0 && data.length > 0) {
actionSetProperty(collectionPath, getSampleColumn(data));
}
}, [collectionPath, properties, data]);
const columnViewer = useMemo(() => {
const docColumns = properties.map((key, index) => ({
Header: (props) => (
<ColumnHeader
{...props}
fieldPath={key}
collectionPath={collectionPath}
/>
),
accessor: (originalRow) => get(originalRow, key),
id: key,
width: Math.max(
Math.min(
key.length * 10,
(sumBy(
data,
(row) => get(row.data(), key)?.toString()?.length || 100
) /
(data.length || 1)) *
10 // 1 character = 3px
),
200
),
Cell: ({ row, column, value }: { row: any; column: any; value: any }) => {
return (
<EditableCell
value={value}
key={column.id}
row={row.original}
column={column}
tabIndex={row.index * row.cells.length + index}
/>
);
},
}));
return [
{
Header: (props) => (
<ColumnHeader
{...props}
fieldPath="_id"
hidable={false}
collectionPath={collectionPath}
isIdColumn
/>
),
id: "__id",
accessor: "id",
disableSortBy: true,
Cell: ({
value,
row,
}: {
value: any;
row: { original: ClientDocumentSnapshot };
}) => <IDReadOnlyField value={value} isNew={row.original.isNew} />,
},
...docColumns,
{
Header: () => (
<div
className="flex justify-center w-5 h-full text-gray-400 cursor-pointer"
role="presentation"
onClick={() => actionToggleModalPickProperty(true)}
>
<svg
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M12 6v6m0 0v6m0-6h6m-6 0H6"
/>
</svg>
</div>
),
width: 50,
id: "addColumn",
Cell: () => null,
},
];
}, [properties, collectionPath]);
const handleRowClick = useCallback(
(
e: React.MouseEvent<HTMLDivElement, MouseEvent>,
doc: ClientDocumentSnapshot
) => {
setPath(doc.ref.path);
},
[]
);
useContextMenu<IRowContextPayload>(
"DUPLICATE",
({ path }) => {
actionDuplicateDoc(path);
},
"rowContext"
);
useContextMenu(
"CONVERT_NUMBER",
({ path, column }: { path: string; column: string }) => {
actionSetFieldValue(path, column, "number");
},
"rowContext"
);
useContextMenu(
"CONVERT_STRING",
({ path, column }: { path: string; column: string }) => {
actionSetFieldValue(path, column, "string");
},
"rowContext"
);
useContextMenu(
"CONVERT_BOOLEAN",
({ path, column }: { path: string; column: string }) => {
actionSetFieldValue(path, column, "boolean");
},
"rowContext"
);
useContextMenu(
"CONVERT_MAP",
({ path, column }: { path: string; column: string }) => {
actionSetFieldValue(path, column, "map");
},
"rowContext"
);
useContextMenu(
"CONVERT_ARRAY",
({ path, column }: { path: string; column: string }) => {
actionSetFieldValue(path, column, "array");
},
"rowContext"
);
useContextMenu(
"CONVERT_TIME",
({ path, column }: { path: string; column: string }) => {
actionSetFieldValue(path, column, "timestamp");
},
"rowContext"
);
useContextMenu(
"CONVERT_GEOPOINT",
({ path, column }: { path: string; column: string }) => {
actionSetFieldValue(path, column, "geopoint");
},
"rowContext"
);
useContextMenu(
"CONVERT_NULL",
({ path, column }: { path: string; column: string }) => {
actionSetFieldValue(path, column, "null");
},
"rowContext"
);
useContextMenu<IRowContextPayload>(
"EXPORT_CSV",
({ path }) => {
actionExportDocCSV(path);
},
"rowContext"
);
useContextMenu<IRowContextPayload>(
"EXPORT_JSON",
({ path }) => {
actionExportDocJSON(path);
},
"rowContext"
);
useContextMenu<IRowContextPayload>(
"EXPORT_VIEW_CSV",
() => {
actionExportViewCSV();
},
"rowContext"
);
useContextMenu<IRowContextPayload>(
"EXPORT_VIEW_JSON",
() => {
actionExportViewJSON();
},
"rowContext"
);
useContextMenu<IRowContextPayload>(
"DELETE",
({ path }) => {
actionDeleteDoc(path);
},
"rowContext"
);
const handleSortColumn = useCallback(
(sortBy) => {
setRecoilExternalState(
sorterAtom(collectionPath),
sortBy.map((sorter) => ({
id: uniqueId("sorter_"),
field: sorter.id,
sort: sorter.desc ? "desc" : "asc",
}))
);
actionSubmitQuery();
},
[collectionPath]
);
return (
<div className="w-full h-full mt-2 border-l border-r border-gray-300">
<TableWrapper
columns={columnViewer}
data={data}
onRowClick={handleRowClick}
onSortColumn={handleSortColumn}
/>
</div>
);
}
const DataTableLoader = () => {
const isLoaded = useRecoilValue(largeDataAtom); // Make parent suspense
if (isLoaded) {
return <DataTable />;
}
return null;
};
export default DataTable; | the_stack |
import { DiagnosticAddendum } from '../common/diagnostic';
import { Localizer } from '../localization/localize';
import { maxSubtypesForInferredType, TypeEvaluator } from './typeEvaluatorTypes';
import {
AnyType,
ClassType,
combineTypes,
FunctionType,
FunctionTypeFlags,
isAny,
isAnyOrUnknown,
isClass,
isClassInstance,
isFunction,
isInstantiableClass,
isNever,
isTypeSame,
isTypeVar,
isUnion,
isUnknown,
isUnpacked,
isVariadicTypeVar,
ParamSpecEntry,
Type,
TypeBase,
TypeVarScopeId,
TypeVarType,
UnknownType,
Variance,
} from './types';
import {
addConditionToType,
AssignTypeFlags,
buildTypeVarContextFromSpecializedClass,
containsLiteralType,
convertParamSpecValueToType,
convertToInstance,
convertToInstantiable,
getTypeCondition,
getTypeVarScopeId,
isEffectivelyInstantiable,
isPartlyUnknown,
mapSubtypes,
specializeTupleClass,
stripLiteralValue,
transformExpectedTypeForConstructor,
} from './typeUtils';
import { TypeVarContext } from './typeVarContext';
// Assigns the source type to the dest type var in the type var context. If an existing
// type is already associated with that type var name, it attempts to either widen or
// narrow the type (depending on the value of the isContravariant parameter). The goal is
// to produce the narrowest type that meets all of the requirements. If the type var context
// has been "locked", it simply validates that the srcType is compatible (with no attempt
// to widen or narrow).
export function assignTypeToTypeVar(
evaluator: TypeEvaluator,
destType: TypeVarType,
srcType: Type,
diag: DiagnosticAddendum | undefined,
typeVarContext: TypeVarContext,
flags = AssignTypeFlags.Default,
recursionCount = 0
): boolean {
let isTypeVarInScope = true;
const isContravariant = (flags & AssignTypeFlags.ReverseTypeVarMatching) !== 0;
// If the TypeVar doesn't have a scope ID, then it's being used
// outside of a valid TypeVar scope. This will be reported as a
// separate error. Just ignore this case to avoid redundant errors.
if (!destType.scopeId) {
return true;
}
// Verify that we are solving for the scope associated with this
// type variable.
if (!typeVarContext.hasSolveForScope(destType.scopeId)) {
if (isAnyOrUnknown(srcType) || (isClass(srcType) && ClassType.derivesFromAnyOrUnknown(srcType))) {
return true;
}
// If we're in "ignore type var scope" mode, don't generate
// an error in this path.
if ((flags & AssignTypeFlags.IgnoreTypeVarScope) !== 0) {
return true;
}
// If we're in "reverse type var" mode, simply make sure that
// the concrete type is assignable.
if (isContravariant) {
if (
evaluator.assignType(
evaluator.makeTopLevelTypeVarsConcrete(destType),
evaluator.makeTopLevelTypeVarsConcrete(srcType),
/* diag */ undefined,
/* destTypeVarContext */ undefined,
/* srcTypeVarContext */ undefined,
flags,
recursionCount
)
) {
return true;
}
}
isTypeVarInScope = false;
if (!destType.details.isSynthesized) {
diag?.addMessage(
Localizer.DiagnosticAddendum.typeAssignmentMismatch().format({
sourceType: evaluator.printType(srcType),
destType: evaluator.printType(destType),
})
);
return false;
}
}
if ((flags & AssignTypeFlags.SkipSolveTypeVars) !== 0) {
return evaluator.assignType(
evaluator.makeTopLevelTypeVarsConcrete(destType),
evaluator.makeTopLevelTypeVarsConcrete(srcType),
diag,
/* destTypeVarContext */ undefined,
/* srcTypeVarContext */ undefined,
flags,
recursionCount
);
}
if (destType.details.isParamSpec) {
return assignTypeToParamSpec(evaluator, destType, srcType, diag, typeVarContext, recursionCount);
}
if (destType.details.isVariadic) {
if (!isUnpacked(srcType)) {
const tupleClassType = evaluator.getTupleClassType();
if (tupleClassType && isInstantiableClass(tupleClassType)) {
// Package up the type into a tuple.
srcType = convertToInstance(
specializeTupleClass(
tupleClassType,
[{ type: srcType, isUnbounded: false }],
/* isTypeArgumentExplicit */ true,
/* stripLiterals */ true,
/* isUnpackedTuple */ true
)
);
} else {
srcType = UnknownType.create();
}
}
}
// If we're attempting to assign `type` to Type[T], transform `type` into `Type[Any]`.
if (
TypeBase.isInstantiable(destType) &&
isClassInstance(srcType) &&
ClassType.isBuiltIn(srcType, 'type') &&
!srcType.typeArguments
) {
srcType = AnyType.create();
}
const curEntry = typeVarContext.getTypeVar(destType);
const curNarrowTypeBound = curEntry?.narrowBound;
const curWideTypeBound = curEntry?.wideBound ?? destType.details.boundType;
// Handle the constrained case. This case needs to be handled specially
// because type narrowing isn't used in this case. For example, if the
// source type is "Literal[1]" and the constraint list includes the type
// "float", the resulting type is float.
if (destType.details.constraints.length > 0) {
let constrainedType: Type | undefined;
const concreteSrcType = evaluator.makeTopLevelTypeVarsConcrete(srcType);
if (isTypeVar(srcType)) {
if (
evaluator.assignType(
destType,
concreteSrcType,
/* diag */ undefined,
new TypeVarContext(destType.scopeId),
/* srcTypeVarContext */ undefined,
AssignTypeFlags.Default,
recursionCount
)
) {
constrainedType = srcType;
// If the source and dest are both instantiables (type[T]), then
// we need to convert to an instance (T) for the
if (TypeBase.isInstantiable(srcType)) {
constrainedType = convertToInstance(srcType);
}
}
} else {
let isCompatible = true;
// Subtypes that are not conditionally dependent on the dest type var
// must all map to the same constraint. For example, Union[str, bytes]
// cannot be assigned to AnyStr.
let unconditionalConstraintIndex: number | undefined;
// Find the narrowest constrained type that is compatible.
constrainedType = mapSubtypes(concreteSrcType, (srcSubtype) => {
let constrainedSubtype: Type | undefined;
if (isAnyOrUnknown(srcSubtype)) {
return srcSubtype;
}
let constraintIndexUsed: number | undefined;
destType.details.constraints.forEach((constraint, i) => {
const adjustedConstraint = TypeBase.isInstantiable(destType)
? convertToInstantiable(constraint)
: constraint;
if (
evaluator.assignType(
adjustedConstraint,
srcSubtype,
/* diag */ undefined,
/* destTypeVarContext */ undefined,
/* srcTypeVarContext */ undefined,
AssignTypeFlags.Default,
recursionCount
)
) {
if (
!constrainedSubtype ||
evaluator.assignType(
TypeBase.isInstantiable(destType)
? convertToInstantiable(constrainedSubtype)
: constrainedSubtype,
adjustedConstraint,
/* diag */ undefined,
/* destTypeVarContext */ undefined,
/* srcTypeVarContext */ undefined,
AssignTypeFlags.Default,
recursionCount
)
) {
constrainedSubtype = addConditionToType(constraint, getTypeCondition(srcSubtype));
constraintIndexUsed = i;
}
}
});
if (!constrainedSubtype) {
// We found a source subtype that is not compatible with the dest.
// This is OK if we're handling the contravariant case because only
// one subtype needs to be assignable in that case.
if (!isContravariant) {
isCompatible = false;
}
}
// If this subtype isn't conditional, make sure it maps to the same
// constraint index as previous unconditional subtypes.
if (constraintIndexUsed !== undefined && !getTypeCondition(srcSubtype)) {
if (
unconditionalConstraintIndex !== undefined &&
unconditionalConstraintIndex !== constraintIndexUsed
) {
isCompatible = false;
}
unconditionalConstraintIndex = constraintIndexUsed;
}
return constrainedSubtype;
});
if (isNever(constrainedType) || !isCompatible) {
constrainedType = undefined;
}
// If the type is a union, see if the entire union is assignable to one
// of the constraints.
if (!constrainedType && isUnion(concreteSrcType)) {
constrainedType = destType.details.constraints.find((constraint) => {
const adjustedConstraint = TypeBase.isInstantiable(destType)
? convertToInstantiable(constraint)
: constraint;
return evaluator.assignType(
adjustedConstraint,
concreteSrcType,
/* diag */ undefined,
/* destTypeVarContext */ undefined,
/* srcTypeVarContext */ undefined,
AssignTypeFlags.Default,
recursionCount
);
});
}
}
// If there was no constrained type that was assignable
// or there were multiple types that were assignable and they
// are not conditional, it's an error.
if (!constrainedType) {
diag?.addMessage(
Localizer.DiagnosticAddendum.typeConstrainedTypeVar().format({
type: evaluator.printType(srcType),
name: destType.details.name,
})
);
return false;
}
if (curNarrowTypeBound && !isAnyOrUnknown(curNarrowTypeBound)) {
if (
!evaluator.assignType(
curNarrowTypeBound,
constrainedType,
/* diag */ undefined,
/* destTypeVarContext */ undefined,
/* srcTypeVarContext */ undefined,
AssignTypeFlags.Default,
recursionCount
)
) {
// Handle the case where one of the constrained types is a wider
// version of another constrained type that was previously assigned
// to the type variable.
if (
evaluator.assignType(
constrainedType,
curNarrowTypeBound,
/* diag */ undefined,
/* destTypeVarContext */ undefined,
/* srcTypeVarContext */ undefined,
AssignTypeFlags.Default,
recursionCount
)
) {
if (!typeVarContext.isLocked() && isTypeVarInScope) {
typeVarContext.setTypeVarType(destType, constrainedType);
}
} else {
diag?.addMessage(
Localizer.DiagnosticAddendum.typeConstrainedTypeVar().format({
type: evaluator.printType(constrainedType),
name: evaluator.printType(curNarrowTypeBound),
})
);
return false;
}
}
} else {
// Assign the type to the type var.
if (!typeVarContext.isLocked() && isTypeVarInScope) {
typeVarContext.setTypeVarType(destType, constrainedType);
}
}
return true;
}
// Handle the unconstrained (but possibly bound) case.
let newNarrowTypeBound = curNarrowTypeBound;
let newWideTypeBound = curWideTypeBound;
const diagAddendum = diag ? new DiagnosticAddendum() : undefined;
// Strip literals if the existing value contains no literals. This allows
// for explicit (but no implicit) literal specialization of a generic class.
const retainLiterals =
(flags & AssignTypeFlags.RetainLiteralsForTypeVar) !== 0 ||
typeVarContext.getRetainLiterals(destType) ||
(destType.details.boundType && containsLiteralType(destType.details.boundType)) ||
destType.details.constraints.some((t) => containsLiteralType(t));
let adjSrcType = retainLiterals ? srcType : stripLiteralValue(srcType);
if (TypeBase.isInstantiable(destType)) {
if (isEffectivelyInstantiable(adjSrcType)) {
adjSrcType = convertToInstance(adjSrcType);
} else {
diag?.addMessage(
Localizer.DiagnosticAddendum.typeAssignmentMismatch().format({
sourceType: evaluator.printType(adjSrcType),
destType: evaluator.printType(destType),
})
);
return false;
}
}
if (isContravariant || (flags & AssignTypeFlags.AllowTypeVarNarrowing) !== 0) {
// Update the wide type bound.
if (!curWideTypeBound) {
newWideTypeBound = adjSrcType;
} else if (
!isTypeSame(
curWideTypeBound,
adjSrcType,
/* ignorePseudoGeneric */ undefined,
/* ignoreTypeFlags */ undefined,
recursionCount
)
) {
if (
evaluator.assignType(
curWideTypeBound,
evaluator.makeTopLevelTypeVarsConcrete(adjSrcType),
diagAddendum,
/* destTypeVarContext */ undefined,
/* srcTypeVarContext */ undefined,
flags & AssignTypeFlags.IgnoreTypeVarScope,
recursionCount
)
) {
// The srcType is narrower than the current wideTypeBound, so replace it.
newWideTypeBound = adjSrcType;
} else if (
!evaluator.assignType(
adjSrcType,
curWideTypeBound,
diagAddendum,
/* destTypeVarContext */ undefined,
/* srcTypeVarContext */ undefined,
flags & AssignTypeFlags.IgnoreTypeVarScope,
recursionCount
)
) {
if (diag && diagAddendum) {
diag.addMessage(
Localizer.DiagnosticAddendum.typeAssignmentMismatch().format({
sourceType: evaluator.printType(adjSrcType),
destType: evaluator.printType(curWideTypeBound),
})
);
diag.addAddendum(diagAddendum);
}
return false;
}
}
// Make sure we haven't narrowed it beyond the current narrow bound.
if (curNarrowTypeBound) {
if (
!evaluator.assignType(
newWideTypeBound!,
curNarrowTypeBound,
/* diag */ undefined,
/* destTypeVarContext */ undefined,
/* srcTypeVarContext */ undefined,
flags & AssignTypeFlags.IgnoreTypeVarScope,
recursionCount
)
) {
if (diag && diagAddendum) {
diag.addMessage(
Localizer.DiagnosticAddendum.typeAssignmentMismatch().format({
sourceType: evaluator.printType(adjSrcType),
destType: evaluator.printType(curNarrowTypeBound),
})
);
diag.addAddendum(diagAddendum);
}
return false;
}
}
} else {
if (!curNarrowTypeBound) {
// There was previously no narrow bound. We've now established one.
newNarrowTypeBound = adjSrcType;
} else if (
!isTypeSame(
curNarrowTypeBound,
adjSrcType,
/* ignorePseudoGeneric */ undefined,
/* ignoreTypeFlags */ undefined,
recursionCount
)
) {
if (
evaluator.assignType(
curNarrowTypeBound,
adjSrcType,
diagAddendum,
new TypeVarContext(destType.scopeId),
/* srcTypeVarContext */ undefined,
flags,
recursionCount
)
) {
// No need to widen. Stick with the existing type unless it's unknown
// or partly unknown, in which case we'll replace it with a known type
// as long as it doesn't violate the current narrow bound.
if (
isPartlyUnknown(curNarrowTypeBound) &&
!isUnknown(adjSrcType) &&
evaluator.assignType(
adjSrcType,
curNarrowTypeBound,
/* diag */ undefined,
new TypeVarContext(destType.scopeId),
/* srcTypeVarContext */ undefined,
flags & AssignTypeFlags.IgnoreTypeVarScope,
recursionCount
)
) {
newNarrowTypeBound = adjSrcType;
} else {
newNarrowTypeBound = curNarrowTypeBound;
}
} else {
// We need to widen the type.
if (typeVarContext.isLocked() || isTypeVar(adjSrcType)) {
diag?.addMessage(
Localizer.DiagnosticAddendum.typeAssignmentMismatch().format({
sourceType: evaluator.printType(curNarrowTypeBound),
destType: evaluator.printType(adjSrcType),
})
);
return false;
}
// Don't allow widening for variadic type variables.
const possibleVariadic = destType;
if (isVariadicTypeVar(possibleVariadic)) {
diag?.addMessage(
Localizer.DiagnosticAddendum.typeAssignmentMismatch().format({
sourceType: evaluator.printType(curNarrowTypeBound),
destType: evaluator.printType(adjSrcType),
})
);
return false;
}
if (
evaluator.assignType(
adjSrcType,
curNarrowTypeBound,
/* diag */ undefined,
new TypeVarContext(destType.scopeId),
/* srcTypeVarContext */ undefined,
flags & AssignTypeFlags.IgnoreTypeVarScope,
recursionCount
)
) {
newNarrowTypeBound = adjSrcType;
} else {
const objectType = evaluator.getObjectType();
// In some extreme edge cases, the narrow type bound can become
// a union with so many subtypes that performance grinds to a
// halt. We'll detect this case and widen the resulting type
// to an 'object' instead of making the union even bigger. This
// is still a valid solution to the TypeVar.
if (
isUnion(curNarrowTypeBound) &&
curNarrowTypeBound.subtypes.length > maxSubtypesForInferredType &&
(destType as TypeVarType).details.boundType !== undefined &&
objectType &&
isClassInstance(objectType)
) {
newNarrowTypeBound = combineTypes([curNarrowTypeBound, objectType]);
} else {
newNarrowTypeBound = combineTypes([curNarrowTypeBound, adjSrcType]);
}
}
}
}
// Make sure we don't exceed the wide type bound.
if (curWideTypeBound && newNarrowTypeBound) {
if (
!isTypeSame(
curWideTypeBound,
newNarrowTypeBound,
/* ignorePseudoGeneric */ undefined,
/* ignoreTypeFlags */ undefined,
recursionCount
)
) {
let makeConcrete = true;
// Handle the case where the wide type is type T and the narrow type
// is type T | <some other type>. In this case, it violates the
// wide type bound.
if (isTypeVar(curWideTypeBound)) {
if (isTypeSame(newNarrowTypeBound, curWideTypeBound)) {
makeConcrete = false;
} else if (
isUnion(newNarrowTypeBound) &&
newNarrowTypeBound.subtypes.some((subtype) => isTypeSame(subtype, curWideTypeBound))
) {
makeConcrete = false;
}
}
if (
!evaluator.assignType(
makeConcrete ? evaluator.makeTopLevelTypeVarsConcrete(curWideTypeBound) : curWideTypeBound,
newNarrowTypeBound,
diag?.createAddendum(),
new TypeVarContext(destType.scopeId),
/* srcTypeVarContext */ undefined,
flags & AssignTypeFlags.IgnoreTypeVarScope,
recursionCount
)
) {
if (diag && diagAddendum) {
diag.addMessage(
Localizer.DiagnosticAddendum.typeAssignmentMismatch().format({
sourceType: evaluator.printType(adjSrcType),
destType: evaluator.printType(curWideTypeBound),
})
);
}
return false;
}
}
}
}
// If there's a bound type, make sure the source is assignable to it.
if (destType.details.boundType) {
const updatedType = (newNarrowTypeBound || newWideTypeBound)!;
// If the dest is a Type[T] but the source is not a valid Type,
// skip the assignType check and the diagnostic addendum, which will
// be confusing and inaccurate.
if (TypeBase.isInstantiable(destType) && !TypeBase.isInstantiable(srcType)) {
return false;
}
// In general, bound types cannot be generic, but the "Self" type is an
// exception. In this case, we need to use the original TypeVarContext
// to solve for the generic type variable(s) in the bound type.
const effectiveTypeVarContext = destType.details.isSynthesizedSelf
? typeVarContext
: new TypeVarContext(destType.scopeId);
if (
!evaluator.assignType(
destType.details.boundType,
evaluator.makeTopLevelTypeVarsConcrete(updatedType),
diag?.createAddendum(),
effectiveTypeVarContext,
/* srcTypeVarContext */ undefined,
flags & AssignTypeFlags.IgnoreTypeVarScope,
recursionCount
)
) {
// Avoid adding a message that will confuse users if the TypeVar was
// synthesized for internal purposes.
if (!destType.details.isSynthesized) {
diag?.addMessage(
Localizer.DiagnosticAddendum.typeBound().format({
sourceType: evaluator.printType(updatedType),
destType: evaluator.printType(destType.details.boundType),
name: TypeVarType.getReadableName(destType),
})
);
}
return false;
}
}
if (!typeVarContext.isLocked() && isTypeVarInScope) {
typeVarContext.setTypeVarType(destType, newNarrowTypeBound, newWideTypeBound, retainLiterals);
}
return true;
}
function assignTypeToParamSpec(
evaluator: TypeEvaluator,
destType: TypeVarType,
srcType: Type,
diag: DiagnosticAddendum | undefined,
typeVarContext: TypeVarContext,
recursionCount = 0
) {
if (isTypeVar(srcType) && srcType.details.isParamSpec) {
const existingEntry = typeVarContext.getParamSpec(destType);
if (existingEntry) {
if (existingEntry.parameters.length === 0 && existingEntry.paramSpec) {
// If there's an existing entry that matches, that's fine.
if (
isTypeSame(
existingEntry.paramSpec,
srcType,
/* ignorePseudoGeneric */ undefined,
/* ignoreTypeFlags */ undefined,
recursionCount
)
) {
return true;
}
}
} else {
if (!typeVarContext.isLocked() && typeVarContext.hasSolveForScope(destType.scopeId)) {
typeVarContext.setParamSpec(destType, {
flags: FunctionTypeFlags.None,
parameters: [],
typeVarScopeId: undefined,
docString: undefined,
paramSpec: srcType,
});
}
return true;
}
} else if (isFunction(srcType)) {
const functionSrcType = srcType;
const parameters = srcType.details.parameters.map((p, index) => {
const paramSpecEntry: ParamSpecEntry = {
category: p.category,
name: p.name,
isNameSynthesized: p.isNameSynthesized,
hasDefault: !!p.hasDefault,
type: FunctionType.getEffectiveParameterType(functionSrcType, index),
};
return paramSpecEntry;
});
const existingEntry = typeVarContext.getParamSpec(destType);
if (existingEntry) {
if (existingEntry.paramSpec === srcType.details.paramSpec) {
// Convert the remaining portion of the signature to a function
// for comparison purposes.
const existingFunction = convertParamSpecValueToType(existingEntry, /* omitParamSpec */ true);
const assignedFunction = convertParamSpecValueToType(
{
parameters,
flags: srcType.details.flags,
typeVarScopeId: srcType.details.typeVarScopeId,
docString: undefined,
paramSpec: undefined,
},
/* omitParamSpec */ true
);
if (
evaluator.assignType(
existingFunction,
assignedFunction,
/* diag */ undefined,
/* destTypeVarContext */ undefined,
/* srcTypeVarContext */ undefined,
AssignTypeFlags.SkipFunctionReturnTypeCheck,
recursionCount
)
) {
return true;
}
}
} else {
if (!typeVarContext.isLocked() && typeVarContext.hasSolveForScope(destType.scopeId)) {
typeVarContext.setParamSpec(destType, {
parameters,
typeVarScopeId: srcType.details.typeVarScopeId,
flags: srcType.details.flags,
docString: srcType.details.docString,
paramSpec: srcType.details.paramSpec,
});
}
return true;
}
} else if (isAnyOrUnknown(srcType)) {
return true;
}
diag?.addMessage(
Localizer.DiagnosticAddendum.typeParamSpec().format({
type: evaluator.printType(srcType),
name: destType.details.name,
})
);
return false;
}
// In cases where the expected type is a specialized base class of the
// source type, we need to determine which type arguments in the derived
// class will make it compatible with the specialized base class. This method
// performs this reverse mapping of type arguments and populates the type var
// map for the target type. If the type is not assignable to the expected type,
// it returns false.
export function populateTypeVarContextBasedOnExpectedType(
evaluator: TypeEvaluator,
type: ClassType,
expectedType: Type,
typeVarContext: TypeVarContext,
liveTypeVarScopes: TypeVarScopeId[] | undefined
): boolean {
if (isAny(expectedType)) {
type.details.typeParameters.forEach((typeParam) => {
typeVarContext.setTypeVarType(typeParam, expectedType);
});
return true;
}
if (!isClass(expectedType)) {
return false;
}
// If the expected type is generic (but not specialized), we can't proceed.
const expectedTypeArgs = expectedType.typeArguments;
if (!expectedTypeArgs) {
return evaluator.assignType(
type,
expectedType,
/* diag */ undefined,
typeVarContext,
/* srcTypeVarContext */ undefined,
AssignTypeFlags.PopulatingExpectedType
);
}
// If the expected type is the same as the target type (commonly the case),
// we can use a faster method.
if (ClassType.isSameGenericClass(expectedType, type)) {
const sameClassTypeVarContext = buildTypeVarContextFromSpecializedClass(expectedType);
sameClassTypeVarContext.getTypeVars().forEach((entry) => {
const typeVarType = sameClassTypeVarContext.getTypeVarType(entry.typeVar);
if (typeVarType) {
// Skip this if the type argument is a TypeVar defined by the class scope because
// we're potentially solving for these TypeVars.
if (!isTypeVar(typeVarType) || typeVarType.scopeId !== type.details.typeVarScopeId) {
typeVarContext.setTypeVarType(
entry.typeVar,
entry.typeVar.details.variance === Variance.Covariant ? undefined : typeVarType,
entry.typeVar.details.variance === Variance.Contravariant ? undefined : typeVarType,
entry.retainLiteral
);
}
}
});
return true;
}
// Create a generic version of the expected type.
const expectedTypeScopeId = getTypeVarScopeId(expectedType);
const synthExpectedTypeArgs = ClassType.getTypeParameters(expectedType).map((typeParam, index) => {
const typeVar = TypeVarType.createInstance(`__dest${index}`);
typeVar.details.isSynthesized = true;
// Use invariance here so we set the narrow and wide values on the TypeVar.
typeVar.details.variance = Variance.Invariant;
typeVar.scopeId = expectedTypeScopeId;
return typeVar;
});
const genericExpectedType = ClassType.cloneForSpecialization(
expectedType,
synthExpectedTypeArgs,
/* isTypeArgumentExplicit */ true
);
// For each type param in the target type, create a placeholder type variable.
const typeArgs = ClassType.getTypeParameters(type).map((_, index) => {
const typeVar = TypeVarType.createInstance(`__source${index}`);
typeVar.details.isSynthesized = true;
typeVar.details.synthesizedIndex = index;
typeVar.details.isExemptFromBoundCheck = true;
return typeVar;
});
const specializedType = ClassType.cloneForSpecialization(type, typeArgs, /* isTypeArgumentExplicit */ true);
const syntheticTypeVarContext = new TypeVarContext(expectedTypeScopeId);
if (
evaluator.assignType(
genericExpectedType,
specializedType,
/* diag */ undefined,
syntheticTypeVarContext,
/* srcTypeVarContext */ undefined,
AssignTypeFlags.PopulatingExpectedType
)
) {
let isResultValid = true;
synthExpectedTypeArgs.forEach((typeVar, index) => {
const synthTypeVar = syntheticTypeVarContext.getTypeVarType(typeVar);
// Is this one of the synthesized type vars we allocated above? If so,
// the type arg that corresponds to this type var maps back to the target type.
if (
synthTypeVar &&
isTypeVar(synthTypeVar) &&
synthTypeVar.details.isSynthesized &&
synthTypeVar.details.synthesizedIndex !== undefined
) {
const targetTypeVar =
ClassType.getTypeParameters(specializedType)[synthTypeVar.details.synthesizedIndex];
if (index < expectedTypeArgs.length) {
let expectedTypeArgValue: Type | undefined = expectedTypeArgs[index];
if (liveTypeVarScopes) {
expectedTypeArgValue = transformExpectedTypeForConstructor(
expectedTypeArgValue,
typeVarContext,
liveTypeVarScopes
);
}
if (expectedTypeArgValue) {
typeVarContext.setTypeVarType(
targetTypeVar,
typeVar.details.variance === Variance.Covariant ? undefined : expectedTypeArgValue,
typeVar.details.variance === Variance.Contravariant ? undefined : expectedTypeArgValue
);
} else {
isResultValid = false;
}
}
}
});
return isResultValid;
}
return false;
} | the_stack |
import UdsClient from "../../../../../main/js/joynr/messaging/uds/UdsClient";
import FakeUdsServer from "./FakeUdsServer";
import MagicCookieUtil from "../../../../../main/js/joynr/messaging/uds/MagicCookieUtil";
import JoynrMessage from "../../../../../main/js/joynr/messaging/JoynrMessage";
import * as MessageSerializer from "../../../../../main/js/joynr/messaging/MessageSerializer";
import * as UtilInternal from "../../../../../main/js/joynr/util/UtilInternal";
import UdsClientAddress from "../../../../../main/js/generated/joynr/system/RoutingTypes/UdsClientAddress";
import JoynrRuntimeException from "joynr/joynr/exceptions/JoynrRuntimeException";
import fs = require("fs");
const UDS_PATH = "/tmp/joynr.ts.uds.udsclienttest.sock";
let expectedJoynrMessage: JoynrMessage;
let joynrMessage: JoynrMessage;
let serializedJoynrMessage: Buffer;
let expectedSerializedInitMessage: Buffer;
let expectedInitMessageLength: number;
interface UdsLibJoynrProvisioning {
socketPath: string;
clientId: string;
connectSleepTimeMs: number;
onMessageCallback: Function;
onFatalRuntimeError: (error: JoynrRuntimeException) => void;
}
const sendSpy = jest.fn();
const shutdownSpy = jest.fn();
const onMessageCallbackSpy = jest.fn();
const onFatalRuntimeErrorSpy = jest.fn();
const parameters: UdsLibJoynrProvisioning = {
socketPath: UDS_PATH,
clientId: "testClientId",
connectSleepTimeMs: 500,
onMessageCallback: onMessageCallbackSpy,
onFatalRuntimeError: onFatalRuntimeErrorSpy
};
class SpyUdsClient extends UdsClient {
private readonly sendSpy: any;
private readonly shutdownSpy: any;
public constructor(parameters: UdsLibJoynrProvisioning, shutdownSpy: any, sendSpy: any) {
super(parameters);
this.sendSpy = sendSpy;
this.shutdownSpy = shutdownSpy;
}
public async send(joynrMessage: JoynrMessage): Promise<void> {
super.send(joynrMessage);
this.sendSpy(joynrMessage);
}
public shutdown(callback?: Function): void {
super.shutdown(callback);
this.shutdownSpy();
}
}
let testUdsServer: FakeUdsServer;
let testServerSpy: any;
let testUdsClient: UdsClient;
const sleep = (ms: number): Promise<any> => {
return new Promise(resolve => setTimeout(resolve, ms));
};
const waitFor = (condition: () => boolean, timeout: number): Promise<any> => {
const checkIntervalMs = 100;
const start = Date.now();
const check = (resolve: any, reject: any) => {
if (condition()) {
resolve();
} else if (Date.now() > start + timeout) {
reject(`${condition.name} failed, even after getting ${timeout} ms to try`);
} else {
setTimeout(_ => check(resolve, reject), checkIntervalMs);
}
};
return new Promise(check);
};
async function waitForConnection() {
const onConnectionCondition = (): boolean => {
return testServerSpy.onConnection.mock.calls.length > 0;
};
await waitFor(onConnectionCondition, 1000);
expect(testServerSpy.onConnection).toHaveBeenCalledTimes(1);
}
async function checkInitConnectionOfUdsClient() {
await waitForConnection();
const onMessageReceivedCondition = (): boolean => {
return testServerSpy.onMessageReceived.mock.calls.length === 1;
};
await waitFor(onMessageReceivedCondition, 1000);
expect(testServerSpy.onMessageReceived).toHaveBeenCalledTimes(1);
const actualReceivedInitMessageBuff = testServerSpy.onMessageReceived.mock.calls[0][1];
const receivedInitMagicCookie: string = MagicCookieUtil.getMagicCookieBuff(
actualReceivedInitMessageBuff
).toString();
expect(receivedInitMagicCookie).toEqual(MagicCookieUtil.INIT_COOKIE);
const receivedLengthOfInitMsg: number = MagicCookieUtil.getPayloadLength(actualReceivedInitMessageBuff);
expect(receivedLengthOfInitMsg).toEqual(expectedSerializedInitMessage.length);
const receivedPayloadOfInitMsgBuff = MagicCookieUtil.getPayloadBuff(actualReceivedInitMessageBuff);
expect(receivedPayloadOfInitMsgBuff).toEqual(expectedSerializedInitMessage);
}
function checkReceivedJoynrMessage(actualJoynrMessage: any): boolean {
if (actualJoynrMessage) {
const deserializedJoynrMessage = MessageSerializer.parse(serializedJoynrMessage);
expect(actualJoynrMessage).toEqual(deserializedJoynrMessage);
return true;
}
return false;
}
async function sendBuffer(socket: any, data: Buffer, onMessageCallbackCondition: () => boolean) {
socket.write(data);
await waitFor(onMessageCallbackCondition, 1000);
}
describe(`libjoynr-js.joynr.messaging.uds.UdsClient`, () => {
beforeEach(done => {
expectedJoynrMessage = new JoynrMessage({
payload: "test message from uds client",
type: JoynrMessage.JOYNRMESSAGE_TYPE_REQUEST
});
expectedJoynrMessage.from = "client";
expectedJoynrMessage.to = "server";
expectedJoynrMessage.expiryDate = 1;
expectedJoynrMessage.compress = false;
expectedSerializedInitMessage = Buffer.from(
JSON.stringify(
new UdsClientAddress({
id: parameters.clientId
})
)
);
expectedInitMessageLength =
expectedSerializedInitMessage.length + MagicCookieUtil.MAGIC_COOKIE_AND_PAYLOAD_LENGTH;
joynrMessage = UtilInternal.extendDeep(
new JoynrMessage({ payload: "test message from uds client", type: JoynrMessage.JOYNRMESSAGE_TYPE_REQUEST }),
expectedJoynrMessage
);
serializedJoynrMessage = MessageSerializer.stringify(joynrMessage);
testUdsServer = new FakeUdsServer(UDS_PATH);
testServerSpy = testUdsServer.getServerSpy();
testUdsServer.start(done);
});
it(`connects to the server`, async () => {
testUdsClient = new UdsClient(parameters);
await waitForConnection();
testUdsClient.shutdown();
});
it(`tries to reconnect until the server is available`, async () => {
testUdsServer.stop();
testUdsClient = new UdsClient(parameters);
const onConnectionCondition = (): boolean => {
return testServerSpy.onConnection.mock.calls.length > 0;
};
await sleep(3000);
expect(testServerSpy.onConnection).toHaveBeenCalledTimes(0);
testUdsServer.start();
await waitFor(onConnectionCondition, 1000);
expect(testServerSpy.onConnection).toHaveBeenCalledTimes(1);
testUdsClient.shutdown();
});
it(`calls onFatalRuntimeError and shutdown when R/W permissions to the socket are not granted`, async () => {
fs.chmodSync(UDS_PATH, 0);
testUdsClient = new SpyUdsClient(parameters, shutdownSpy, sendSpy);
await sleep(1000);
expect(testServerSpy.onConnection).toHaveBeenCalledTimes(0);
const errorMessage = `Fatal runtime error, stopping all communication permanently: Error: EACCES: permission denied, access '${UDS_PATH}'`;
expect(onFatalRuntimeErrorSpy).toHaveBeenCalledWith(new JoynrRuntimeException({ detailMessage: errorMessage }));
expect(shutdownSpy).toHaveBeenCalledTimes(1);
});
it(`sends init message on connect`, async () => {
testUdsClient = new UdsClient(parameters);
await checkInitConnectionOfUdsClient();
testUdsClient.shutdown();
});
it(`sends a complete message to the server after init message`, async () => {
testUdsClient = new UdsClient(parameters);
await checkInitConnectionOfUdsClient();
jest.clearAllMocks();
await testUdsClient.send(joynrMessage);
const onMessageReceivedCondition = (): boolean => {
return testServerSpy.onMessageReceived.mock.calls.length === 1;
};
await waitFor(onMessageReceivedCondition, 1000);
expect(testServerSpy.onMessageReceived).toHaveBeenCalledTimes(1);
// actual received buffer by the server
const actualReceivedBuff = testServerSpy.onMessageReceived.mock.calls[0][1];
const actualCookie: string = MagicCookieUtil.getMagicCookieBuff(actualReceivedBuff).toString();
expect(actualCookie).toEqual(MagicCookieUtil.MESSAGE_COOKIE);
const actualLength: number = MagicCookieUtil.getPayloadLength(actualReceivedBuff);
expect(actualLength).toEqual(serializedJoynrMessage.length);
const actualSerializedJoynrMessage = MagicCookieUtil.getPayloadBuff(actualReceivedBuff);
expect(actualSerializedJoynrMessage.length).toEqual(serializedJoynrMessage.length);
expect(actualSerializedJoynrMessage).toEqual(serializedJoynrMessage);
// deserialize received serialized joynr message and check it
const actualJoynrMessage = MessageSerializer.parse(actualSerializedJoynrMessage);
expect(checkReceivedJoynrMessage(actualJoynrMessage)).toEqual(true);
testUdsClient.shutdown();
});
it(`disconnects when the server stops/crashes and calls onFatalRuntimeError`, async () => {
testUdsClient = new SpyUdsClient(parameters, shutdownSpy, sendSpy);
await waitForConnection();
testUdsServer.stop();
const onShutdownCondition = (): boolean => {
return shutdownSpy.mock.calls.length === 1;
};
await waitFor(onShutdownCondition, 1000);
expect(shutdownSpy).toHaveBeenCalledTimes(1);
expect(onFatalRuntimeErrorSpy).toHaveBeenCalledWith(
new JoynrRuntimeException({
detailMessage:
"Fatal runtime error, stopping all communication permanently: The server closed the connection."
})
);
});
it(`calls onMessageCallback when a complete message arrives from the server`, async () => {
testUdsClient = new SpyUdsClient(parameters, shutdownSpy, sendSpy);
await waitForConnection();
// when a complete message is arrived as a single or assembled from different chunk,
const udsSerializedJoynrMessage = MagicCookieUtil.writeMagicCookies(
serializedJoynrMessage,
MagicCookieUtil.MESSAGE_COOKIE
);
const socket = testServerSpy.onConnection.mock.calls[0][0];
socket.write(udsSerializedJoynrMessage);
const onMessageCallbackCondition = (): boolean => {
return onMessageCallbackSpy.mock.calls.length > 0;
};
await waitFor(onMessageCallbackCondition, 1000);
expect(onMessageCallbackSpy).toHaveBeenCalledTimes(1);
// check received args of onMessageCallback, which is the joynrMessage
const actualJoynrMessage = onMessageCallbackSpy.mock.calls[0][0];
expect(checkReceivedJoynrMessage(actualJoynrMessage)).toEqual(true);
testUdsClient.shutdown();
});
it(`receives a complete message from the server through several chunks`, async () => {
testUdsClient = new SpyUdsClient(parameters, shutdownSpy, sendSpy);
await waitForConnection();
const socket = testServerSpy.onConnection.mock.calls[0][0];
// check received joynrMessage
const udsSerializedJoynrMessage = MagicCookieUtil.writeMagicCookies(
serializedJoynrMessage,
MagicCookieUtil.MESSAGE_COOKIE
);
const onMessageCallbackCondition = (): boolean => {
return onMessageCallbackSpy.mock.calls.length > 0;
};
// partial magic cookie
const incompleteMsgPart1 = Buffer.from(udsSerializedJoynrMessage.subarray(0, 3));
await sendBuffer(socket, incompleteMsgPart1, () => {
return true;
});
expect(onMessageCallbackSpy).toHaveBeenCalledTimes(0);
// partial payload length header
const incompleteMsgPart2 = Buffer.from(udsSerializedJoynrMessage.subarray(3, 8));
await sendBuffer(socket, incompleteMsgPart2, () => {
return true;
});
expect(onMessageCallbackSpy).toHaveBeenCalledTimes(0);
// partial payload
const incompleteMsgPart3 = Buffer.from(
udsSerializedJoynrMessage.subarray(8, udsSerializedJoynrMessage.length - 10)
);
await sendBuffer(socket, incompleteMsgPart3, () => {
return true;
});
expect(onMessageCallbackSpy).toHaveBeenCalledTimes(0);
const incompleteMsgPart4 = Buffer.from(
udsSerializedJoynrMessage.subarray(udsSerializedJoynrMessage.length - 10, udsSerializedJoynrMessage.length)
);
await sendBuffer(socket, incompleteMsgPart4, onMessageCallbackCondition);
expect(onMessageCallbackSpy).toHaveBeenCalledTimes(1);
// check received joynr message
const actualJoynrMessage = onMessageCallbackSpy.mock.calls[0][0];
expect(checkReceivedJoynrMessage(actualJoynrMessage)).toEqual(true);
testUdsClient.shutdown();
});
it(`receives two complete messages in a chunk and calls onmessage for both`, async () => {
testUdsClient = new SpyUdsClient(parameters, shutdownSpy, sendSpy);
await waitForConnection();
const socket = testServerSpy.onConnection.mock.calls[0][0];
const udsSerializedJoynrMessage1 = MagicCookieUtil.writeMagicCookies(
serializedJoynrMessage,
MagicCookieUtil.MESSAGE_COOKIE
);
const udsSerializedJoynrMessage2 = MagicCookieUtil.writeMagicCookies(
serializedJoynrMessage,
MagicCookieUtil.MESSAGE_COOKIE
);
const onMessageCallbackCondition = (): boolean => {
return onMessageCallbackSpy.mock.calls.length > 1;
};
const twoMessagesArray = [udsSerializedJoynrMessage1, udsSerializedJoynrMessage2];
// we send a buffer which contains two messages
const bufferContainsTwoUdsMsgs = Buffer.concat(twoMessagesArray);
await sendBuffer(socket, bufferContainsTwoUdsMsgs, onMessageCallbackCondition);
expect(onMessageCallbackSpy).toHaveBeenCalledTimes(2);
// check received joynr messages
const actualJoynrMessage1 = onMessageCallbackSpy.mock.calls[0][0];
expect(checkReceivedJoynrMessage(actualJoynrMessage1)).toEqual(true);
const actualJoynrMessage2 = onMessageCallbackSpy.mock.calls[1][0];
expect(checkReceivedJoynrMessage(actualJoynrMessage2)).toEqual(true);
testUdsClient.shutdown();
});
it("queues messages when the uds server is still unavailable", async () => {
testUdsServer.stop();
testUdsClient = new UdsClient(parameters);
await testUdsClient.send(joynrMessage);
await testUdsClient.send(joynrMessage);
await testUdsClient.send(joynrMessage);
expect(testUdsClient.numberOfQueuedMessages).toBe(3);
testUdsClient.shutdown();
});
it("delivers queued messages when the uds server becomes available", async () => {
testUdsServer.stop();
testUdsClient = new UdsClient(parameters);
const numberOfMessages = 10;
const expectedReceivedBytes =
expectedInitMessageLength +
(MagicCookieUtil.MAGIC_COOKIE_AND_PAYLOAD_LENGTH + serializedJoynrMessage.length) * numberOfMessages;
const onCompleteReceivedBytesCondition = (): boolean => {
const callCount = testServerSpy.onMessageReceived.mock.calls.length;
if (callCount === 0) {
return false;
}
let accumulatedReceivedBytes = 0;
for (let i = 0; i < callCount; i++) {
accumulatedReceivedBytes += testServerSpy.onMessageReceived.mock.calls[i][1].length;
}
return accumulatedReceivedBytes === expectedReceivedBytes;
};
const promises = [];
for (let i = 0; i < numberOfMessages; i++) {
promises.push(testUdsClient.send(joynrMessage));
}
await Promise.all(promises);
expect(testUdsClient.numberOfQueuedMessages).toBe(numberOfMessages);
testUdsServer.start();
await waitForConnection();
expect(testServerSpy.onConnection).toHaveBeenCalledTimes(1);
expect(testUdsClient.numberOfQueuedMessages).toBe(0);
await waitFor(onCompleteReceivedBytesCondition, 1000);
testUdsClient.shutdown();
});
it(`closes the connection against the server when receiving data which does not contain magic cookie`, async () => {
testUdsClient = new SpyUdsClient(parameters, shutdownSpy, sendSpy);
await waitForConnection();
const socket = testServerSpy.onConnection.mock.calls[0][0];
const garbageData: Buffer = Buffer.from(`garbage data sent by the server, client must close the connection`);
await sendBuffer(socket, garbageData, () => {
return true;
});
expect(onMessageCallbackSpy).toHaveBeenCalledTimes(0);
const onShutdownCondition = (): boolean => {
return shutdownSpy.mock.calls.length > 0;
};
await waitFor(onShutdownCondition, 1000);
expect(shutdownSpy).toHaveBeenCalledTimes(1);
expect(onFatalRuntimeErrorSpy).toHaveBeenCalledWith(
new JoynrRuntimeException({
detailMessage:
"Fatal runtime error, stopping all communication permanently: Received invalid cookies garb. Close the connection."
})
);
});
it(`receives a complete message via multiple chunks from the server`, async () => {
testUdsClient = new SpyUdsClient(parameters, shutdownSpy, sendSpy);
await waitForConnection();
const socket = testServerSpy.onConnection.mock.calls[0][0];
const onMessageCallbackCondition = (): boolean => {
return onMessageCallbackSpy.mock.calls.length > 0;
};
const udsSerializedJoynrMessage = MagicCookieUtil.writeMagicCookies(
serializedJoynrMessage,
MagicCookieUtil.MESSAGE_COOKIE
);
// server sends chunk1/2
const chunk1 = Buffer.from(udsSerializedJoynrMessage.subarray(0, udsSerializedJoynrMessage.length - 25));
await sendBuffer(socket, chunk1, () => {
return true;
});
expect(onMessageCallbackSpy).toHaveBeenCalledTimes(0);
await sleep(100);
// server sends chunk2/2
const chunk2 = Buffer.from(
udsSerializedJoynrMessage.subarray(udsSerializedJoynrMessage.length - 25, udsSerializedJoynrMessage.length)
);
await sendBuffer(socket, chunk2, onMessageCallbackCondition);
expect(onMessageCallbackSpy).toHaveBeenCalledTimes(1);
testUdsClient.shutdown();
});
it(`receives a few messages via multiple chunks from the server`, async () => {
testUdsClient = new SpyUdsClient(parameters, shutdownSpy, sendSpy);
await waitForConnection();
const socket = testServerSpy.onConnection.mock.calls[0][0];
const udsSerializedJoynrMessage1 = MagicCookieUtil.writeMagicCookies(
serializedJoynrMessage,
MagicCookieUtil.MESSAGE_COOKIE
);
const udsSerializedJoynrMessage2 = MagicCookieUtil.writeMagicCookies(
serializedJoynrMessage,
MagicCookieUtil.MESSAGE_COOKIE
);
const onMessageCallbackCondition1 = (): boolean => {
return onMessageCallbackSpy.mock.calls.length > 0;
};
const partOfMessage2 = Buffer.from(
udsSerializedJoynrMessage2.subarray(0, udsSerializedJoynrMessage2.length - 25)
);
const arrayOfData = [udsSerializedJoynrMessage1, partOfMessage2];
// server sends chunk1/2, message1 + part of message2
const chunk1 = Buffer.concat(arrayOfData);
await sendBuffer(socket, chunk1, onMessageCallbackCondition1);
expect(onMessageCallbackSpy).toHaveBeenCalledTimes(1);
await sleep(100);
// server sends chunk2/2, the remaining from message2
const chunk2 = Buffer.from(
udsSerializedJoynrMessage2.subarray(
udsSerializedJoynrMessage2.length - 25,
udsSerializedJoynrMessage2.length
)
);
const onMessageCallbackCondition2 = (): boolean => {
return onMessageCallbackSpy.mock.calls.length === 2;
};
await sendBuffer(socket, chunk2, onMessageCallbackCondition2);
expect(onMessageCallbackSpy).toHaveBeenCalledTimes(2);
testUdsClient.shutdown();
});
it(`receives a message with no payload from the server`, async () => {
onMessageCallbackSpy.mockClear();
testUdsClient = new SpyUdsClient(parameters, shutdownSpy, sendSpy);
await waitForConnection();
const zeroPayloadMessage = Buffer.alloc(0, 0);
const udsZeroPayloadMessage = MagicCookieUtil.writeMagicCookies(
zeroPayloadMessage,
MagicCookieUtil.MESSAGE_COOKIE
);
const socket = testServerSpy.onConnection.mock.calls[0][0];
await sendBuffer(socket, udsZeroPayloadMessage, () => {
return true;
});
// wait a bit to be sure that we received a message.
await sleep(1000);
expect(onMessageCallbackSpy).toHaveBeenCalledTimes(0);
testUdsClient.shutdown();
});
it(`shutdown mode delays resolving UdsClient.send Promise till the data is written out`, async () => {
testUdsClient = new SpyUdsClient(parameters, shutdownSpy, sendSpy);
await checkInitConnectionOfUdsClient();
testUdsClient.enableShutdownMode();
jest.clearAllMocks();
await testUdsClient.send(joynrMessage);
testUdsClient.shutdown();
expect(sendSpy).toHaveBeenCalledWith(joynrMessage);
// server receives the message
const onMessageReceivedCondition = (): boolean => {
return testServerSpy.onMessageReceived.mock.calls.length > 0;
};
await waitFor(onMessageReceivedCondition, 1000);
expect(testServerSpy.onMessageReceived).toHaveBeenCalledTimes(1);
const actualReceivedBuff = testServerSpy.onMessageReceived.mock.calls[0][1];
const actualSerializedJoynrMessage = MagicCookieUtil.getPayloadBuff(actualReceivedBuff);
expect(actualSerializedJoynrMessage).toEqual(serializedJoynrMessage);
const actualJoynrMessage = MessageSerializer.parse(actualSerializedJoynrMessage);
expect(checkReceivedJoynrMessage(actualJoynrMessage)).toEqual(true);
});
it(`calls onFatalRuntimeError when deserialization received joynr message fails`, async () => {
testUdsClient = new SpyUdsClient(parameters, shutdownSpy, sendSpy);
await waitForConnection();
const serializedSpoiledJoynrMessage = Buffer.from(serializedJoynrMessage);
serializedSpoiledJoynrMessage[0] = 56; // spoil the first byte. Default is 1
const udsSerializedJoynrMessage = MagicCookieUtil.writeMagicCookies(
serializedSpoiledJoynrMessage,
MagicCookieUtil.MESSAGE_COOKIE
);
const socket = testServerSpy.onConnection.mock.calls[0][0];
await sendBuffer(socket, udsSerializedJoynrMessage, () => {
return true;
});
const onFatalRuntimeErrorCondition = (): boolean => {
return onFatalRuntimeErrorSpy.mock.calls.length === 1;
};
await waitFor(onFatalRuntimeErrorCondition, 1000);
expect(onMessageCallbackSpy).toHaveBeenCalledTimes(0);
expect(onFatalRuntimeErrorSpy).toHaveBeenCalledWith(
new JoynrRuntimeException({
detailMessage:
"Fatal runtime error, stopping all communication permanently: Error: smrf.deserialize: got exception Error: unsupported version: 56, dropping the message!"
})
);
testUdsClient.shutdown();
});
it(`sends huge volume of big messages to check robustness of the internal buffer`, async () => {
testUdsClient = new UdsClient(parameters);
await waitForConnection();
const numberOfMessages = 1024;
const bigJoynrMessage = new JoynrMessage({
payload: Buffer.alloc(1024, 65).toString(),
type: JoynrMessage.JOYNRMESSAGE_TYPE_REQUEST
});
bigJoynrMessage.from = "client";
bigJoynrMessage.to = "server";
bigJoynrMessage.expiryDate = 1;
bigJoynrMessage.compress = false;
const serializedBigJoynrMessage = MessageSerializer.stringify(bigJoynrMessage);
const expectedReceivedBytes =
expectedInitMessageLength +
(MagicCookieUtil.MAGIC_COOKIE_AND_PAYLOAD_LENGTH + serializedBigJoynrMessage.length) * numberOfMessages;
const onCompleteReceivedBytesCondition = (): boolean => {
const callCount = testServerSpy.onMessageReceived.mock.calls.length;
if (callCount === 0) {
return false;
}
let accumulatedReceivedBytes = 0;
for (let i = 0; i < callCount; i++) {
accumulatedReceivedBytes += testServerSpy.onMessageReceived.mock.calls[i][1].length;
}
return accumulatedReceivedBytes === expectedReceivedBytes;
};
const arrayOfPromises = [];
for (let i = 0; i < numberOfMessages; i++) {
arrayOfPromises.push(testUdsClient.send(bigJoynrMessage));
}
await Promise.all(arrayOfPromises);
await waitFor(onCompleteReceivedBytesCondition, 1000);
testUdsClient.shutdown();
});
afterEach(done => {
testUdsServer.stop(() => done());
jest.clearAllMocks();
});
}); | the_stack |
import {DataDescription} from './DataDescription';
import {
memo,
useMemo,
useRef,
useState,
useEffect,
useCallback,
createContext,
useContext,
} from 'react';
import styled from '@emotion/styled';
import DataPreview, {DataValueExtractor, InspectorName} from './DataPreview';
import {getSortedKeys} from './utils';
import React from 'react';
import {useHighlighter, HighlightManager} from '../Highlight';
import {Dropdown, Menu, Tooltip} from 'antd';
import {tryGetFlipperLibImplementation} from '../../plugin/FlipperLib';
import {safeStringify} from '../../utils/safeStringify';
import {useInUnitTest} from '../../utils/useInUnitTest';
import {theme} from '../theme';
export {DataValueExtractor} from './DataPreview';
export const RootDataContext = createContext<() => any>(() => ({}));
export const contextMenuTrigger = ['contextMenu' as const];
const BaseContainer = styled.div<{depth?: number; disabled?: boolean}>(
(props) => ({
fontFamily: 'Menlo, monospace',
fontSize: 11,
lineHeight: '17px',
filter: props.disabled ? 'grayscale(100%)' : '',
margin: props.depth === 0 ? '7.5px 0' : '0',
paddingLeft: 10,
userSelect: 'text',
width: '100%',
}),
);
BaseContainer.displayName = 'DataInspector:BaseContainer';
const RecursiveBaseWrapper = styled.span({
color: theme.errorColor,
});
RecursiveBaseWrapper.displayName = 'DataInspector:RecursiveBaseWrapper';
const Wrapper = styled.span({
color: theme.textColorSecondary,
});
Wrapper.displayName = 'DataInspector:Wrapper';
const PropertyContainer = styled.span({
paddingTop: '2px',
});
PropertyContainer.displayName = 'DataInspector:PropertyContainer';
const ExpandControl = styled.span({
color: theme.textColorSecondary,
fontSize: 10,
marginLeft: -11,
marginRight: 5,
whiteSpace: 'pre',
});
ExpandControl.displayName = 'DataInspector:ExpandControl';
const Added = styled.div({
backgroundColor: theme.semanticColors.diffAddedBackground,
});
const Removed = styled.div({
backgroundColor: theme.semanticColors.diffRemovedBackground,
});
export type DataInspectorSetValue = (path: Array<string>, val: any) => void;
export type DataInspectorDeleteValue = (path: Array<string>) => void;
export type DataInspectorExpanded = {
[key: string]: boolean;
};
export type DiffMetadataExtractor = (
data: any,
diff: any,
key: string,
) => Array<{
data: any;
diff?: any;
status?: 'added' | 'removed';
}>;
type DataInspectorProps = {
/**
* Object to inspect.
*/
data: any;
/**
* Object to compare with the provided `data` property.
* Differences will be styled accordingly in the UI.
*/
diff?: any;
/**
* Current name of this value.
*/
name?: string;
/**
* Current depth.
*/
depth: number;
/**
* An array containing the current location of the data relative to its root.
*/
parentPath: Array<string>;
/**
* Whether to expand the root by default.
*/
expandRoot?: boolean;
/**
* An array of paths that are currently expanded.
*/
expanded: DataInspectorExpanded;
/**
* An optional callback that will explode a value into its type and value.
* Useful for inspecting serialised data.
*/
extractValue?: DataValueExtractor;
/**
* Callback whenever the current expanded paths is changed.
*/
onExpanded?: ((path: string, expanded: boolean) => void) | undefined | null;
/**
* Callback whenever delete action is invoked on current path.
*/
onDelete?: DataInspectorDeleteValue | undefined | null;
/**
* Render callback that can be used to customize the rendering of object keys.
*/
onRenderName?: (
path: Array<string>,
name: string,
highlighter: HighlightManager,
) => React.ReactElement;
/**
* Render callback that can be used to customize the rendering of object values.
*/
onRenderDescription?: (description: React.ReactElement) => React.ReactElement;
/**
* Callback when a value is edited.
*/
setValue?: DataInspectorSetValue | undefined | null;
/**
* Whether all objects and arrays should be collapsed by default.
*/
collapsed?: boolean;
/**
* Ancestry of parent objects, used to avoid recursive objects.
*/
parentAncestry: Array<Object>;
/**
* Object of properties that will have tooltips
*/
tooltips?: any;
};
const defaultValueExtractor: DataValueExtractor = (value: any) => {
const type = typeof value;
if (type === 'number') {
return {mutable: true, type: 'number', value};
}
if (type === 'string') {
return {mutable: true, type: 'string', value};
}
if (type === 'boolean') {
return {mutable: true, type: 'boolean', value};
}
if (type === 'undefined') {
return {mutable: true, type: 'undefined', value};
}
if (value === null) {
return {mutable: true, type: 'null', value};
}
if (Array.isArray(value)) {
return {mutable: true, type: 'array', value};
}
if (Object.prototype.toString.call(value) === '[object Date]') {
return {mutable: true, type: 'date', value};
}
if (type === 'object') {
return {mutable: true, type: 'object', value};
}
};
function isPureObject(obj: Object) {
return (
obj !== null &&
Object.prototype.toString.call(obj) !== '[object Date]' &&
typeof obj === 'object'
);
}
const diffMetadataExtractor: DiffMetadataExtractor = (
data: any,
key: string,
diff?: any,
) => {
if (diff == null) {
return [{data: data[key]}];
}
const val = data[key];
const diffVal = diff[key];
if (!data.hasOwnProperty(key)) {
return [{data: diffVal, status: 'removed'}];
}
if (!diff.hasOwnProperty(key)) {
return [{data: val, status: 'added'}];
}
if (isPureObject(diffVal) && isPureObject(val)) {
return [{data: val, diff: diffVal}];
}
if (diffVal !== val) {
// Check if there's a difference between the original value and
// the value from the diff prop
// The property name still exists, but the values may be different.
return [
{data: val, status: 'added'},
{data: diffVal, status: 'removed'},
];
}
return Object.prototype.hasOwnProperty.call(data, key) ? [{data: val}] : [];
};
function isComponentExpanded(data: any, diffType: string, diffValue: any) {
if (diffValue == null) {
return false;
}
if (diffType === 'object') {
const sortedDataValues = Object.keys(data)
.sort()
.map((key) => data[key]);
const sortedDiffValues = Object.keys(diffValue)
.sort()
.map((key) => diffValue[key]);
if (JSON.stringify(sortedDataValues) !== JSON.stringify(sortedDiffValues)) {
return true;
}
} else {
if (data !== diffValue) {
return true;
}
}
return false;
}
const recursiveMarker = <RecursiveBaseWrapper>Recursive</RecursiveBaseWrapper>;
/**
* An expandable data inspector.
*
* This component is fairly low level. It's likely you're looking for
* [`<ManagedDataInspector>`](#manageddatainspector).
*/
export const DataInspectorNode: React.FC<DataInspectorProps> = memo(
function DataInspectorImpl({
data,
depth,
diff,
expandRoot,
parentPath,
onExpanded,
onDelete,
onRenderName,
onRenderDescription,
extractValue: extractValueProp,
expanded: expandedPaths,
name,
parentAncestry,
collapsed,
tooltips,
setValue: setValueProp,
}) {
const highlighter = useHighlighter();
const getRoot = useContext(RootDataContext);
const isUnitTest = useInUnitTest();
const shouldExpand = useRef(false);
const expandHandle = useRef(undefined as any);
const [renderExpanded, setRenderExpanded] = useState(false);
const path = useMemo(
() => (name === undefined ? parentPath : parentPath.concat([name])),
[parentPath, name],
);
const extractValue = useCallback(
(data: any, depth: number, path: string[]) => {
let res;
if (extractValueProp) {
res = extractValueProp(data, depth, path);
}
if (!res) {
res = defaultValueExtractor(data, depth, path);
}
return res;
},
[extractValueProp],
);
const res = useMemo(
() => extractValue(data, depth, path),
[extractValue, data, depth, path],
);
const resDiff = useMemo(
() => extractValue(diff, depth, path),
[extractValue, diff, depth, path],
);
const ancestry = useMemo(
() => (res ? parentAncestry!.concat([res.value]) : []),
[parentAncestry, res?.value],
);
let isExpandable = false;
if (!res) {
shouldExpand.current = false;
} else {
isExpandable = isValueExpandable(res.value);
}
if (isExpandable) {
if (
expandRoot === true ||
shouldBeExpanded(expandedPaths, path, collapsed)
) {
shouldExpand.current = true;
} else if (resDiff) {
shouldExpand.current = isComponentExpanded(
res!.value,
resDiff.type,
resDiff.value,
);
}
}
useEffect(() => {
if (!shouldExpand.current) {
setRenderExpanded(false);
} else {
if (isUnitTest) {
setRenderExpanded(true);
} else {
expandHandle.current = requestIdleCallback(() => {
setRenderExpanded(true);
});
}
}
return () => {
if (!isUnitTest) {
cancelIdleCallback(expandHandle.current);
}
};
}, [shouldExpand.current, isUnitTest]);
const setExpanded = useCallback(
(pathParts: Array<string>, isExpanded: boolean) => {
if (!onExpanded || !expandedPaths) {
return;
}
const path = pathParts.join('.');
onExpanded(path, isExpanded);
},
[onExpanded, expandedPaths],
);
const handleClick = useCallback(() => {
if (!isUnitTest) {
cancelIdleCallback(expandHandle.current);
}
const isExpanded = shouldBeExpanded(expandedPaths, path, collapsed);
setExpanded(path, !isExpanded);
}, [expandedPaths, path, collapsed, isUnitTest]);
const handleDelete = useCallback(
(path: Array<string>) => {
if (!onDelete) {
return;
}
onDelete(path);
},
[onDelete],
);
/**
* RENDERING
*/
if (!res) {
return null;
}
// the data inspector makes values read only when setValue isn't set so we just need to set it
// to null and the readOnly status will be propagated to all children
const setValue = res.mutable ? setValueProp : null;
const {value, type, extra} = res;
if (parentAncestry!.includes(value)) {
return recursiveMarker;
}
let expandGlyph = '';
if (isExpandable) {
if (shouldExpand.current) {
expandGlyph = '▼';
} else {
expandGlyph = '▶';
}
} else {
if (depth !== 0) {
expandGlyph = ' ';
}
}
let propertyNodesContainer = null;
if (isExpandable && renderExpanded) {
const propertyNodes = [];
const diffValue = diff && resDiff ? resDiff.value : null;
const keys = getSortedKeys({...value, ...diffValue});
for (const key of keys) {
const diffMetadataArr = diffMetadataExtractor(value, key, diffValue);
for (const [index, metadata] of diffMetadataArr.entries()) {
const metaKey = key + index;
const dataInspectorNode = (
<DataInspectorNode
parentAncestry={ancestry}
extractValue={extractValue}
setValue={setValue}
expanded={expandedPaths}
collapsed={collapsed}
onExpanded={onExpanded}
onDelete={onDelete}
onRenderName={onRenderName}
onRenderDescription={onRenderDescription}
parentPath={path}
depth={depth + 1}
key={metaKey}
name={key}
data={metadata.data}
diff={metadata.diff}
tooltips={tooltips}
/>
);
switch (metadata.status) {
case 'added':
propertyNodes.push(
<Added key={metaKey}>{dataInspectorNode}</Added>,
);
break;
case 'removed':
propertyNodes.push(
<Removed key={metaKey}>{dataInspectorNode}</Removed>,
);
break;
default:
propertyNodes.push(dataInspectorNode);
}
}
}
propertyNodesContainer = propertyNodes;
}
if (expandRoot === true) {
return <>{propertyNodesContainer}</>;
}
// create name components
const nameElems = [];
if (typeof name !== 'undefined') {
const text = onRenderName
? onRenderName(path, name, highlighter)
: highlighter.render(name);
nameElems.push(
<Tooltip
title={tooltips != null && tooltips[name]}
key="name"
placement="left">
<InspectorName>{text}</InspectorName>
</Tooltip>,
);
nameElems.push(<span key="sep">: </span>);
}
// create description or preview
let descriptionOrPreview;
if (renderExpanded || !isExpandable) {
descriptionOrPreview = (
<DataDescription
path={path}
setValue={setValue}
type={type}
value={value}
extra={extra}
/>
);
descriptionOrPreview = onRenderDescription
? onRenderDescription(descriptionOrPreview)
: descriptionOrPreview;
} else {
descriptionOrPreview = (
<DataPreview
path={path}
type={type}
value={value}
extractValue={extractValue}
depth={depth}
/>
);
}
descriptionOrPreview = (
<span>
{nameElems}
{descriptionOrPreview}
</span>
);
let wrapperStart;
let wrapperEnd;
if (renderExpanded) {
if (type === 'object') {
wrapperStart = <Wrapper>{'{'}</Wrapper>;
wrapperEnd = <Wrapper>{'}'}</Wrapper>;
}
if (type === 'array') {
wrapperStart = <Wrapper>{'['}</Wrapper>;
wrapperEnd = <Wrapper>{']'}</Wrapper>;
}
}
function getContextMenu() {
const lib = tryGetFlipperLibImplementation();
return (
<Menu>
<Menu.Item
key="copyClipboard"
onClick={() => {
lib?.writeTextToClipboard(safeStringify(getRoot()));
}}>
Copy tree
</Menu.Item>
{lib?.isFB && (
<Menu.Item
key="createPaste"
onClick={() => {
lib?.createPaste(safeStringify(getRoot()));
}}>
Create paste from tree
</Menu.Item>
)}
<Menu.Divider />
<Menu.Item
key="copyValue"
onClick={() => {
lib?.writeTextToClipboard(safeStringify(data));
}}>
Copy value
</Menu.Item>
{!isExpandable && onDelete ? (
<Menu.Item
key="delete"
onClick={() => {
handleDelete(path);
}}>
Delete
</Menu.Item>
) : null}
</Menu>
);
}
return (
<Dropdown overlay={getContextMenu} trigger={contextMenuTrigger}>
<BaseContainer
depth={depth}
disabled={!!setValueProp && !!setValue === false}>
<PropertyContainer onClick={isExpandable ? handleClick : undefined}>
{expandedPaths && <ExpandControl>{expandGlyph}</ExpandControl>}
{descriptionOrPreview}
{wrapperStart}
</PropertyContainer>
{propertyNodesContainer}
{wrapperEnd}
</BaseContainer>
</Dropdown>
);
},
dataInspectorPropsAreEqual,
);
function shouldBeExpanded(
expanded: DataInspectorExpanded,
pathParts: Array<string>,
collapsed?: boolean,
) {
// if we have no expanded object then expand everything
if (expanded == null) {
return true;
}
const path = pathParts.join('.');
// check if there's a setting for this path
if (Object.prototype.hasOwnProperty.call(expanded, path)) {
return expanded[path];
}
// check if all paths are collapsed
if (collapsed === true) {
return false;
}
// by default all items are expanded
return true;
}
function dataInspectorPropsAreEqual(
props: DataInspectorProps,
nextProps: DataInspectorProps,
) {
// Optimization: it would be much faster to not pass the expanded tree
// down the tree, but rather introduce an ExpandStateManager, and subscribe per node
// check if any expanded paths effect this subtree
if (nextProps.expanded !== props.expanded) {
const path = !nextProps.name
? '' // root
: !nextProps.parentPath.length
? nextProps.name // root element
: nextProps.parentPath.join('.') + '.' + nextProps.name;
// we are being collapsed
if (props.expanded[path] !== nextProps.expanded[path]) {
return false;
}
// one of our children was expande
for (const key in nextProps.expanded) {
if (key.startsWith(path) === false) {
// this key doesn't effect us
continue;
}
if (nextProps.expanded[key] !== props.expanded[key]) {
return false;
}
}
}
// basic equality checks for the rest
return (
nextProps.data === props.data &&
nextProps.diff === props.diff &&
nextProps.name === props.name &&
nextProps.depth === props.depth &&
nextProps.parentPath === props.parentPath &&
nextProps.onExpanded === props.onExpanded &&
nextProps.onDelete === props.onDelete &&
nextProps.setValue === props.setValue &&
nextProps.collapsed === props.collapsed &&
nextProps.expandRoot === props.expandRoot
);
}
function isValueExpandable(data: any) {
return (
typeof data === 'object' && data !== null && Object.keys(data).length > 0
);
} | the_stack |
namespace luci {
/**
* Describes the exposed functionality of a single Polymer RPC call, defined
* in "rpc-call.html".
*/
interface PolymerClientCall {
/** Aborts the call, if it is currently ongoing. */
abort(): void;
/**
* Completes performs the configured RPC, returning a Promise that
* resolves with the call's result on completion and an HTTP/gRPC error on
* failure.
*/
completes: Promise<any>;
}
/**
* PolymerClient describes the exposed functionality of the Polymer RPC
* client,
* defined in "rpc-client.html".
*
* TODO(dnj): Fully port the Polymer RPC client to TypeScript. For now, we'll
* let it continue to do the request/response logic and piggyback on top of
* its
* Promises to provide retries and advanced capabilities.
*/
export interface PolymerClient {
/** Name of the RPC service to invoke. */
service: string;
/** Name of the RPC method to invoke. */
method: string;
/** Request contents. */
request: any;
/**
* Constructs the RPC call, returning its result. Will return an HttpError
* instance (see "rpc-error.html") on HTTP error, and a GrpcError (see
* "rpc-call.html") on gRPC error.
*
* Call returns an object configured to execute an RPC against the specified
* service and method.
*/
call(): PolymerClientCall;
}
/**
* An RPC client implementation.
*
* This client implements exponential backoff retries on transient HTTP and
* gRPC errors.
*/
export class Client {
/** Retry instance to use for retries. */
transientRetry: Retry = {retries: 10, delay: 500, maxDelay: 15000};
/**
* Constructs a new Client.
*
* @param pc "rpc-client.html" client instance to use for calls.
*/
constructor(private pc: PolymerClient) {}
/**
* Call invokes the specified service's method, returning a Promise.
*
* @param service the RPC service name to call.
* @param method the RPC method name to call.
* @param request optional request body content.
*
* @returns A Promise that resolves to the RPC response, or errors with an
* error, including HttpError or GrpcError on HTTP/gRPC failure
* respectively.
*/
async call<T>(service: string, method: string, request?: T) {
return this.callOp(undefined, service, method, request);
}
async callOp<T>(
op: luci.Operation|undefined, service: string, method: string,
request?: T) {
let transientRetry = new RetryIterator(this.transientRetry);
let currentCall: PolymerClientCall;
let resp = await transientRetry.do(
() => {
if (op && currentCall) {
// Unregister previous call instances' cancellation callbacks.
op.removeCancelCallback(currentCall.abort);
}
// Configure the client for this request.
this.pc.service = service;
this.pc.method = method;
this.pc.request = request;
// Execute the configured request.
//
// If we are supplied an operation, allow it to cancel the call
// directly.
currentCall = this.pc.call();
if (op) {
op.addCancelCallback(currentCall.abort);
}
return currentCall.completes;
},
(err: Error, delay: number) => {
// Is this a transient error?
if (!isTransientError(err)) {
throw err;
}
console.warn(
`Transient error calling ` +
`${service}.${method} with params:`,
request, `:`, err, `; retrying after ${delay}ms.`);
},
op);
return resp.response;
}
}
/**
* gRPC Codes
*
* Copied from "rpc-code.html" and, more directly,
* https://github.com/grpc/grpc-go/blob/972dbd2/codes/codes.go#L43
*/
export enum Code {
OK = 0,
CANCELED = 1,
UNKNOWN = 2,
INVALID_ARGUMENT = 3,
DEADLINE_EXCEEDED = 4,
NOT_FOUND = 5,
ALREADY_EXISTS = 6,
PERMISSION_DENIED = 7,
UNAUTHENTICATED = 16,
RESOURCE_EXHAUSTED = 8,
FAILED_PRECONDITION = 9,
ABORTED = 10,
OUT_OF_RANGE = 11,
UNIMPLEMENTED = 12,
INTERNAL = 13,
UNAVAILABLE = 14,
DATA_LOSS = 15
}
/** A gRPC error, which is an error paired with a gRPC Code. */
export class GrpcError extends Error {
constructor(readonly code: Code, readonly description?: string) {
super('code = ' + code + ', desc = ' + description);
}
/**
* Converts the supplied Error into a GrpcError if its name is
* "GrpcError". This merges between the non-Typescript RPC code and this
* error type.
*/
static convert(err: Error): GrpcError|null {
if (err.name === 'GrpcError') {
let aerr = err as any as {code: Code, description: string};
return new GrpcError(aerr.code, aerr.description);
}
return null;
}
/** Returns true if the error is considered transient. */
get transient(): boolean {
switch (this.code) {
case Code.INTERNAL:
case Code.UNAVAILABLE:
case Code.RESOURCE_EXHAUSTED:
return true;
default:
return false;
}
}
}
/** An HTTP error, which is an error paired with an HTTP code. */
export class HttpError extends Error {
constructor(readonly code: number, readonly description?: string) {
super('code = ' + code + ', desc = ' + description);
}
/**
* Converts the supplied Error into a HttpError if its name is
* "HttpError". This merges between the non-Typescript RPC code and this
* error type.
*/
static convert(err: Error): HttpError|null {
if (err.name === 'HttpError') {
let aerr = err as any as {code: number, description: string};
return new HttpError(aerr.code, aerr.description);
}
return null;
}
/** Returns true if the error is considered transient. */
get transient(): boolean {
return (this.code >= 500);
}
}
/**
* Generic error processing function to determine if an error is known to be
* transient.
*/
export function isTransientError(err: Error): boolean {
let grpc = GrpcError.convert(err);
if (grpc) {
return grpc.transient;
}
// Is this an HTTP Error?
let http = HttpError.convert(err);
if (http) {
return http.transient;
}
// Unknown error.
return false;
}
/**
* RetryIterator configuration class.
*
* A user will define the retry parameters using a Retry instance, then create
* a RetryIterator with them.
*/
export type Retry = {
// The number of retries to perform before failing. If undefined, will retry
// indefinitely.
retries?: number;
// The amount of time to delay in between retry attempts, in milliseconds.
// If undefined or < 0, no delay will be imposed.
delay: number;
// The maximum delay to apply, in milliseconds. If > 0 and delay scales past
// "maxDelay", it will be capped at "maxDelay".
maxDelay?: number;
// delayScaling is the multiplier applied to "delay" in between retries. If
// undefined or <= 1, DEFAULT_DELAY_SCALING will be used.
delayScaling?: number;
};
/** RetryCallback is an optional callback type used in "do". */
export type RetryCallback = (err: Error, delay: number) => void;
/**
* Stopped is a sentinel error thrown by RetryIterator when it runs out of
* retries.
*/
export const STOPPED = new Error('retry stopped');
/**
* Generic exponential backoff retry delay generator.
*
* A RetryIterator is a specific configured instance of a Retry. Each call to
* "next()" returns the next delay in the retry sequence.
*/
export class RetryIterator {
// Default scaling if no delay is specified.
static readonly DEFAULT_DELAY_SCALING = 2;
private delay: number;
private retries: number|undefined;
private maxDelay: number;
private delayScaling: number;
constructor(config: Retry) {
this.retries = config.retries;
this.maxDelay = (config.maxDelay || 0);
this.delay = (config.delay || 0);
this.delayScaling = (config.delayScaling || 0);
if (this.delayScaling < 1) {
this.delayScaling = RetryIterator.DEFAULT_DELAY_SCALING;
}
}
/**
* @returns the next delay, in milliseconds. If there are no more retries,
* returns undefined.
*/
next(): number {
// Apply retries, if they have been enabled.
if (this.retries !== undefined) {
if (this.retries <= 0) {
// No more retries remaining.
throw STOPPED;
}
this.retries--;
}
let delay = this.delay;
this.delay *= this.delayScaling;
if (this.maxDelay > 0 && delay > this.maxDelay) {
this.delay = delay = this.maxDelay;
}
return delay;
}
/**
* Executes a Promise, retrying if the Promise raises an error.
*
* "do" iteratively tries to execute a Promise, generated by "gen". If that
* Promise raises an error, "do" will retry until it either runs out of
* retries, or the Promise does not return an error. Each retry, "do" will
* invoke "gen" again to generate a new Promise.
*
* An optional "onError" callback can be supplied. If it is, it will be
* invoked in between each retry. The callback may, itself, throw, in which
* case the retry loop will stop. This can be used for reporting and/or
* selective retries.
*
* @param gen Promise generator function for retries.
* @param onError optional callback to be invoked in between retries.
* @param op if supplied, this Operation will be used to cancel retries.
*
* @throws any the error generated by "gen"'s Promise, if out of retries,
* or the error raised by onError if it chooses to throw.
*/
async do<T>(
gen: () => Promise<T>, onError?: RetryCallback, op?: luci.Operation) {
let base = this.doImpl(gen, onError);
if (op) {
base = op.wrap(base);
}
return base;
}
private async doImpl<T>(
gen: () => Promise<T>, onError?: RetryCallback, op?: luci.Operation) {
while (true) {
let genErr: Error;
try {
return await gen();
} catch (e) {
genErr = e;
}
let delay: number;
try {
delay = this.next();
} catch (e) {
if (e !== STOPPED) {
console.warn('Unexpected error generating next delay:', e);
}
// If we could not generate another retry delay, raise the initial
// Promise's error.
throw genErr;
}
if (onError) {
// Note: this may throw.
onError(genErr, delay);
}
await luci.sleepPromise(delay, op);
}
}
}
} | the_stack |
import traverse, {NodePath} from 'babel-traverse';
import * as babel from 'babel-types';
import * as clone from 'clone';
import {FileRelativeUrl, Import, PackageRelativeUrl, ResolvedUrl} from 'polymer-analyzer';
import {rollup} from 'rollup';
import {getAnalysisDocument} from './analyzer-utils';
import {serialize} from './babel-utils';
import {AssignedBundle, BundleManifest} from './bundle-manifest';
import {Bundler} from './bundler';
import {getOrSetBundleModuleExportName} from './es6-module-utils';
import {appendUrlPath, ensureLeadingDot, getFileExtension} from './url-utils';
import {rewriteObject} from './utils';
/**
* Utility class to rollup/merge ES6 modules code using rollup and rewrite
* import statements to point to appropriate bundles.
*/
export class Es6Rewriter {
constructor(
public bundler: Bundler,
public manifest: BundleManifest,
public bundle: AssignedBundle) {
}
async rollup(url: ResolvedUrl, code: string) {
// This is a synthetic module specifier used to identify the code to rollup
// and differentiate it from the a request to contents of the document at
// the actual given url which should load from the analyzer.
const input = '*bundle*';
const analysis =
await this.bundler.analyzer.analyze([...this.bundle.bundle.files]);
const external: string[] = [];
for (const [url, bundle] of this.manifest.bundles) {
if (url !== this.bundle.url) {
external.push(...[...bundle.files, url]);
}
}
// For each document loaded from the analyzer, we build a map of the
// original specifiers to the resolved URLs since we want to use analyzer
// resolutions for such things as bare module specifiers.
const jsImportResolvedUrls =
new Map<ResolvedUrl, Map<string, ResolvedUrl>>();
const rollupBundle = await rollup({
input,
external,
onwarn: (warning: string) => {},
treeshake: false,
plugins: [
{
name: 'analyzerPlugin',
resolveId: (importee: string, importer?: string) => {
if (importee === input) {
return input;
}
if (importer) {
if (jsImportResolvedUrls.has(importer as ResolvedUrl)) {
const resolutions =
jsImportResolvedUrls.get(importer as ResolvedUrl)!;
if (resolutions.has(importee)) {
return resolutions.get(importee);
}
}
return this.bundler.analyzer.urlResolver.resolve(
importer === input ? url : importer as ResolvedUrl,
importee as FileRelativeUrl)! as string;
}
return this.bundler.analyzer.urlResolver.resolve(
importee as PackageRelativeUrl)! as string;
},
load: (id: ResolvedUrl) => {
if (id === input) {
return code;
}
if (this.bundle.bundle.files.has(id)) {
const document = getAnalysisDocument(analysis, id);
if (!jsImportResolvedUrls.has(id)) {
const jsImports = document.getFeatures({
kind: 'js-import',
imported: false,
externalPackages: true,
excludeBackreferences: true,
}) as Set<Import>;
const resolutions = new Map<string, ResolvedUrl>();
jsImportResolvedUrls.set(id, resolutions);
for (const jsImport of jsImports) {
const source = jsImport.astNode && jsImport.astNode.source &&
jsImport.astNode.source.value;
if (source && jsImport.document !== undefined) {
resolutions.set(source, jsImport.document.url);
}
}
}
return document.parsedDocument.contents;
}
},
},
],
experimentalDynamicImport: true,
});
const {code: rolledUpCode} = await rollupBundle.generate({
format: 'es',
freeze: false,
});
// We have to force the extension of the URL to analyze here because inline
// es6 module document url is going to end in `.html` and the file would be
// incorrectly analyzed as an HTML document.
const rolledUpUrl = getFileExtension(url) === '.js' ?
url :
appendUrlPath(url, '_inline_es6_module.js');
const rolledUpDocument = await this.bundler.analyzeContents(
rolledUpUrl as ResolvedUrl, rolledUpCode);
const babelFile = rolledUpDocument.parsedDocument.ast;
this._rewriteImportStatements(url, babelFile);
this._deduplicateImportStatements(babelFile);
const {code: rewrittenCode} = serialize(babelFile);
return {code: rewrittenCode, map: undefined};
}
/**
* Attempts to reduce the number of distinct import declarations by combining
* those referencing the same source into the same declaration. Results in
* deduplication of imports of the same item as well.
*
* Before:
* import {a} from './module-1.js';
* import {b} from './module-1.js';
* import {c} from './module-2.js';
* After:
* import {a,b} from './module-1.js';
* import {c} from './module-2.js';
*/
private _deduplicateImportStatements(node: babel.Node) {
const importDeclarations = new Map<string, babel.ImportDeclaration>();
traverse(node, {
noScope: true,
ImportDeclaration: {
enter(path: NodePath) {
const importDeclaration = path.node;
if (!babel.isImportDeclaration(importDeclaration)) {
return;
}
const source = babel.isStringLiteral(importDeclaration.source) &&
importDeclaration.source.value;
if (!source) {
return;
}
const hasNamespaceSpecifier = importDeclaration.specifiers.some(
(s) => babel.isImportNamespaceSpecifier(s));
const hasDefaultSpecifier = importDeclaration.specifiers.some(
(s) => babel.isImportDefaultSpecifier(s));
if (!importDeclarations.has(source) && !hasNamespaceSpecifier &&
!hasDefaultSpecifier) {
importDeclarations.set(source, importDeclaration);
} else if (importDeclarations.has(source)) {
const existingDeclaration = importDeclarations.get(source)!;
for (const specifier of importDeclaration.specifiers) {
existingDeclaration.specifiers.push(specifier);
}
path.remove();
}
}
}
});
}
/**
* Rewrite import declarations source URLs reference the bundle URL for
* bundled files and import names to correspond to names as exported by
* bundles.
*/
private _rewriteImportStatements(baseUrl: ResolvedUrl, node: babel.Node) {
const this_ = this;
traverse(node, {
noScope: true,
// Dynamic import() syntax doesn't have full type support yet, so we
// have to use generic `enter` and walk all nodes until that's fixed.
// TODO(usergenic): Switch this to the `Import: { enter }` style
// after dynamic imports fully supported.
enter(path: NodePath) {
if (path.node.type === 'Import') {
this_._rewriteDynamicImport(baseUrl, node, path);
}
},
});
traverse(node, {
noScope: true,
ImportDeclaration: {
enter(path: NodePath) {
const importDeclaration = path.node as babel.ImportDeclaration;
if (!babel.isStringLiteral(importDeclaration.source)) {
// We can't actually handle values which are not string literals, so
// we'll skip them.
return;
}
const source = importDeclaration.source.value as ResolvedUrl;
const sourceBundle = this_.manifest.getBundleForFile(source);
// If there is no import bundle, then this URL is not bundled (maybe
// excluded or something) so we should just ensure the URL is
// converted back to a relative URL.
if (!sourceBundle) {
importDeclaration.source.value =
this_.bundler.analyzer.urlResolver.relative(baseUrl, source);
return;
}
for (const specifier of importDeclaration.specifiers) {
if (babel.isImportSpecifier(specifier)) {
this_._rewriteImportSpecifierName(
specifier, source, sourceBundle);
}
if (babel.isImportDefaultSpecifier(specifier)) {
this_._rewriteImportDefaultSpecifier(
specifier, source, sourceBundle);
}
if (babel.isImportNamespaceSpecifier(specifier)) {
this_._rewriteImportNamespaceSpecifier(
specifier, source, sourceBundle);
}
}
importDeclaration.source.value =
ensureLeadingDot(this_.bundler.analyzer.urlResolver.relative(
baseUrl, sourceBundle.url));
}
}
});
}
/**
* Extends dynamic import statements to extract the explicitly namespace
* export for the imported module.
*
* Before:
* import('./module-a.js')
* .then((moduleA) => moduleA.doSomething());
*
* After:
* import('./bundle_1.js')
* .then(({$moduleA}) => $moduleA)
* .then((moduleA) => moduleA.doSomething());
*/
private _rewriteDynamicImport(
baseUrl: ResolvedUrl,
root: babel.Node,
importNodePath: NodePath) {
if (!importNodePath) {
return;
}
const importCallExpression = importNodePath.parent;
if (!importCallExpression ||
!babel.isCallExpression(importCallExpression)) {
return;
}
const importCallArgument = importCallExpression.arguments[0];
if (!babel.isStringLiteral(importCallArgument)) {
return;
}
const sourceUrl = importCallArgument.value;
const resolvedSourceUrl = this.bundler.analyzer.urlResolver.resolve(
baseUrl, sourceUrl as FileRelativeUrl);
if (!resolvedSourceUrl) {
return;
}
const sourceBundle = this.manifest.getBundleForFile(resolvedSourceUrl);
// TODO(usergenic): To support *skipping* the rewrite, we need a way to
// identify whether a bundle contains a single top-level module or is a
// merged bundle with multiple top-level modules.
let exportName;
if (sourceBundle) {
exportName =
getOrSetBundleModuleExportName(sourceBundle, resolvedSourceUrl, '*');
}
// If there's no source bundle or the namespace export name of the bundle
// is just '*', then we don't need to append a .then() to transform the
// return value of the import(). Lets just rewrite the URL to be a relative
// path and exit.
if (!sourceBundle || exportName === '*') {
const relativeSourceUrl =
ensureLeadingDot(this.bundler.analyzer.urlResolver.relative(
baseUrl, resolvedSourceUrl));
importCallArgument.value = relativeSourceUrl;
return;
}
// Rewrite the URL to be a relative path to the bundle.
const relativeSourceUrl = ensureLeadingDot(
this.bundler.analyzer.urlResolver.relative(baseUrl, sourceBundle.url));
importCallArgument.value = relativeSourceUrl;
const importCallExpressionParent = importNodePath.parentPath.parent!;
if (!importCallExpressionParent) {
return;
}
const thenifiedCallExpression = babel.callExpression(
babel.memberExpression(
clone(importCallExpression), babel.identifier('then')),
[babel.arrowFunctionExpression(
[
babel.objectPattern(
[babel.objectProperty(
babel.identifier(exportName),
babel.identifier(exportName),
undefined,
true) as any]),
],
babel.identifier(exportName))]);
rewriteObject(importCallExpression, thenifiedCallExpression);
}
/**
* Changes an import specifier to use the exported name defined in the bundle.
*
* Before:
* import {something} from './module-a.js';
*
* After:
* import {something_1} from './bundle_1.js';
*/
private _rewriteImportSpecifierName(
specifier: babel.ImportSpecifier,
source: ResolvedUrl,
sourceBundle: AssignedBundle) {
const originalExportName = specifier.imported.name;
const exportName = getOrSetBundleModuleExportName(
sourceBundle, source, originalExportName);
specifier.imported.name = exportName;
}
/**
* Changes an import specifier to use the exported name for original module's
* default as defined in the bundle.
*
* Before:
* import moduleA from './module-a.js';
*
* After:
* import {$moduleADefault} from './bundle_1.js';
*/
private _rewriteImportDefaultSpecifier(
specifier: babel.ImportDefaultSpecifier,
source: ResolvedUrl,
sourceBundle: AssignedBundle) {
const exportName =
getOrSetBundleModuleExportName(sourceBundle, source, 'default');
// No rewrite necessary if default is the name, since this indicates there
// was no rewriting or bundling of the default export.
if (exportName === 'default') {
return;
}
const importSpecifier = specifier as any as babel.ImportSpecifier;
Object.assign(
importSpecifier,
{type: 'ImportSpecifier', imported: babel.identifier(exportName)});
}
/**
* Changes an import specifier to use the exported name for original module's
* namespace as defined in the bundle.
*
* Before:
* import * as moduleA from './module-a.js';
*
* After:
* import {$moduleA} from './bundle_1.js';
*/
private _rewriteImportNamespaceSpecifier(
specifier: babel.ImportNamespaceSpecifier,
source: ResolvedUrl,
sourceBundle: AssignedBundle) {
const exportName =
getOrSetBundleModuleExportName(sourceBundle, source, '*');
// No rewrite necessary if * is the name, since this indicates there was no
// bundling of the namespace.
if (exportName === '*') {
return;
}
const importSpecifier = specifier as any as babel.ImportSpecifier;
Object.assign(
importSpecifier,
{type: 'ImportSpecifier', imported: babel.identifier(exportName)});
}
} | the_stack |
import { Spreadsheet } from '../base/index';
import { getSheetIndex, SheetModel, isHiddenRow, CellModel, getCell, setCell, Workbook, getSheet } from '../../workbook/index';
import { initiateChart, ChartModel, getRangeIndexes, isNumber, isDateTime, dateToInt, LegendPosition, getSheetIndexFromAddress } from '../../workbook/common/index';
import { Overlay, Dialog } from '../services/index';
import { overlay, locale, refreshChartCellObj, getRowIdxFromClientY, getColIdxFromClientX, deleteChart, dialog, overlayEleSize, undoRedoForChartDesign, BeforeActionData } from '../common/index';
import { BeforeImageRefreshData, BeforeChartEventArgs, completeAction, clearChartBorder, focusBorder } from '../common/index';
import { Chart, ColumnSeries, Category, ILoadedEventArgs, StackingColumnSeries, BarSeries, ChartSeriesType, AccumulationLabelPosition } from '@syncfusion/ej2-charts';
import { AreaSeries, StackingAreaSeries, AccumulationChart, IAccLoadedEventArgs } from '@syncfusion/ej2-charts';
import { Legend, StackingBarSeries, SeriesModel, LineSeries, StackingLineSeries, AxisModel, ScatterSeries } from '@syncfusion/ej2-charts';
import { AccumulationLegend, PieSeries, AccumulationTooltip, AccumulationDataLabel, AccumulationSeriesModel } from '@syncfusion/ej2-charts';
import { L10n, isNullOrUndefined, getComponent, closest, detach, isUndefined } from '@syncfusion/ej2-base';
import { Tooltip } from '@syncfusion/ej2-popups';
import { getTypeFromFormat } from '../../workbook/integrations/index';
import { updateChart, deleteChartColl, getFormattedCellObject, setChart, getCellAddress, ChartTheme } from '../../workbook/common/index';
import { insertChart, chartRangeSelection, addChartEle, chartDesignTab, removeDesignChart } from '../common/index';
import { DataLabel, DataLabelSettingsModel, IBeforeResizeEventArgs } from '@syncfusion/ej2-charts';
import { LegendSettingsModel, LabelPosition, ChartType, isHiddenCol, beginAction } from '../../workbook/index';
Chart.Inject(ColumnSeries, LineSeries, BarSeries, AreaSeries, StackingColumnSeries, StackingLineSeries, StackingBarSeries, ScatterSeries);
Chart.Inject(StackingAreaSeries, Category, Legend, Tooltip, DataLabel);
AccumulationChart.Inject(PieSeries, AccumulationTooltip, AccumulationDataLabel, AccumulationLegend);
/**
* Represents Chart support for Spreadsheet.
*/
export class SpreadsheetChart {
private parent: Spreadsheet;
private chart: Chart | AccumulationChart;
/**
* Constructor for the Spreadsheet Chart module.
*
* @param {Spreadsheet} parent - Constructor for the Spreadsheet Chart module.
*/
constructor(parent: Spreadsheet) {
this.parent = parent;
this.addEventListener();
}
/**
* Adding event listener for success and failure
*
* @returns {void} - Adding event listener for success and failure
*/
private addEventListener(): void {
this.parent.on(initiateChart, this.initiateChartHandler, this);
this.parent.on(refreshChartCellObj, this.refreshChartCellObj, this);
this.parent.on(updateChart, this.updateChartHandler, this);
this.parent.on(deleteChart, this.deleteChart, this);
this.parent.on(clearChartBorder, this.clearBorder, this);
this.parent.on(insertChart, this.insertChartHandler, this);
this.parent.on(chartRangeSelection, this.chartRangeHandler, this);
this.parent.on(chartDesignTab, this.chartDesignTabHandler, this);
this.parent.on(addChartEle, this.updateChartElement, this);
this.parent.on(undoRedoForChartDesign, this.undoRedoForChartDesign, this);
}
private insertChartHandler(args: { action: string, id: string, isChart?: boolean }): void {
let chartType: ChartType = 'Column';
switch (args.id) {
case 'clusteredColumn':
chartType = 'Column';
break;
case 'stackedColumn':
chartType = 'StackingColumn';
break;
case 'stackedColumn100':
chartType = 'StackingColumn100';
break;
case 'clusteredBar':
chartType = 'Bar';
break;
case 'stackedBar':
chartType = 'StackingBar';
break;
case 'stackedBar100':
chartType = 'StackingBar100';
break;
case 'area':
chartType = 'Area';
break;
case 'stackedArea':
chartType = 'StackingArea';
break;
case 'stackedArea100':
chartType = 'StackingArea100';
break;
case 'line':
chartType = 'Line';
break;
case 'stackedLine':
chartType = 'StackingLine';
break;
case 'stackedLine100':
chartType = 'StackingLine100';
break;
case 'pie':
chartType = 'Pie';
break;
case 'doughnut':
chartType = 'Doughnut';
break;
// case 'radar':
// chartType = ;
// break;
// case 'radar_markers':
// chartType = 'Column';
// break;
case 'scatter':
chartType = 'Scatter';
break;
}
const chart: ChartModel[] = [{ type: chartType }];
if (args.isChart) {
this.parent.notify(setChart, { chart: chart });
} else {
this.parent.notify(chartDesignTab, { chartType: chartType, triggerEvent: true });
}
}
private chartRangeHandler(): void {
const overlayEle: HTMLElement = document.querySelector('.e-datavisualization-chart.e-ss-overlay-active') as HTMLElement;
if (overlayEle) {
const chartId: string = overlayEle.getElementsByClassName('e-control')[0].id;
const chartColl: ChartModel[] = this.parent.chartColl;
const chartCollLen: number = chartColl.length;
for (let idx: number = 0; idx < chartCollLen; idx++) {
const chartEle: HTMLElement = document.getElementById(chartColl[idx].id);
if (overlayEle && chartEle && chartColl[idx].id === chartId) {
this.parent.notify(initiateChart, {
option: chartColl[idx], chartCount: this.parent.chartCount, isRefresh: true
});
}
}
}
}
private getPropertyValue(rIdx: number, cIdx: number, sheetIndex: number): string | number {
const sheets: SheetModel[] = this.parent.sheets;
if (sheets[sheetIndex] && sheets[sheetIndex].rows[rIdx] && sheets[sheetIndex].rows[rIdx].cells[cIdx]) {
const cell: CellModel = getCell(rIdx, cIdx, this.parent.sheets[sheetIndex]);
let value: string | number = '';
if (cell.format) {
const formatObj: { [key: string]: string | boolean | CellModel } = {
type: getTypeFromFormat(cell.format),
value: cell && cell.value, format: cell && cell.format ?
cell.format : 'General', formattedText: cell && cell.value,
onLoad: true, isRightAlign: false, cell: cell,
rowIndex: rIdx.toString(), colIndex: cIdx.toString()
};
if (cell) {
this.parent.notify(getFormattedCellObject, formatObj);
if (typeof (formatObj.value) === 'number') {
// eslint-disable-next-line no-useless-escape
const escapeRegx: RegExp = new RegExp('[!@#$%^&()+=\';,{}|\":<>~_-]', 'g');
formatObj.formattedText = (formatObj.formattedText.toString()).replace(escapeRegx, '');
value = parseInt(formatObj.formattedText.toString(), 10);
} else {
value = formatObj.formattedText && formatObj.formattedText.toString();
}
}
} else {
value = this.parent.sheets[sheetIndex].rows[rIdx].cells[cIdx].value;
}
value = isNullOrUndefined(value) ? '' : value;
return value;
} else {
return '';
}
}
private updateChartHandler(args: { chart: ChartModel }): void {
const series: SeriesModel[] = this.initiateChartHandler({ option: args.chart, isRefresh: true }) as SeriesModel[];
const chartObj: HTMLElement = this.parent.element.querySelector('.' + args.chart.id);
if (chartObj) {
let chartComp: Chart = getComponent(chartObj, 'chart');
if (isNullOrUndefined(chartComp)) {
chartComp = getComponent(chartObj, 'accumulationchart');
}
chartComp.series = series;
chartComp.refresh();
}
}
private refreshChartCellObj(args: BeforeImageRefreshData): void {
const sheetIndex: number = isUndefined(args.sheetIdx) ? this.parent.activeSheetIndex : args.sheetIdx;
const sheet: SheetModel = getSheet(this.parent, sheetIndex);
const prevCellObj: CellModel = getCell(args.prevRowIdx, args.prevColIdx, sheet);
const currCellObj: CellModel = getCell(args.currentRowIdx, args.currentColIdx, sheet);
const prevCellChart: object[] = prevCellObj ? prevCellObj.chart : [];
let prevChartObj: ChartModel;
let currChartObj: ChartModel[];
const prevCellChartLen: number = (prevCellChart && prevCellChart.length) ? prevCellChart.length : 0;
if (prevCellObj && prevCellObj.chart) {
for (let i: number = 0; i < prevCellChartLen; i++) {
if ((prevCellChart[i] as ChartModel).id === args.id.split('_overlay')[0]) {
prevChartObj = prevCellChart[i];
prevChartObj.height = args.currentHeight;
prevChartObj.width = args.currentWidth;
prevChartObj.top = args.currentTop;
prevChartObj.left = args.currentLeft;
prevCellChart.splice(i, 1);
for (let idx: number = 0, chartCollLen: number = this.parent.chartColl.length; idx < chartCollLen; idx++) {
if (prevChartObj.id === this.parent.chartColl[idx].id) {
prevChartObj.height = args.currentHeight;
this.parent.chartColl[idx].width = args.currentWidth;
this.parent.chartColl[idx].top = args.currentTop;
this.parent.chartColl[idx].left = args.currentLeft;
}
}
}
}
if (currCellObj && currCellObj.chart) {
currChartObj = currCellObj.chart;
if (prevChartObj) {
currChartObj.push(prevChartObj);
}
}
if (currChartObj) {
setCell(args.currentRowIdx, args.currentColIdx, sheet, { chart: currChartObj }, true);
} else {
setCell(args.currentRowIdx, args.currentColIdx, sheet, { chart: [prevChartObj] }, true);
}
if (args.requestType === 'chartRefresh' && !args.isUndoRedo) {
const eventArgs: BeforeImageRefreshData = {
requestType: 'chartRefresh', currentRowIdx: args.currentRowIdx, currentColIdx: args.currentColIdx,
currentWidth: args.currentWidth, prevHeight: args.prevHeight, prevWidth: args.prevWidth,
prevRowIdx: args.prevRowIdx, prevColIdx: args.prevColIdx, prevTop: args.prevTop, prevLeft: args.prevLeft,
currentTop: args.currentTop, currentLeft: args.currentLeft, currentHeight: args.currentHeight,
id: args.id, sheetIdx: sheetIndex
};
this.parent.notify('actionComplete', { eventArgs: eventArgs, action: 'chartRefresh' });
}
}
}
private processChartRange(
range: number[], dataSheetIdx: number, opt: ChartModel): { xRange: number[], yRange: number[], lRange: number[] } {
let xRange: number[];
let yRange: number[];
let lRange: number[];
const minr: number = range[0];
const minc: number = range[1]; let isStringSeries: boolean = false;
const maxr: number = range[2]; const maxc: number = range[3]; const isSingleRow: boolean = minr === maxr;
const isSingleCol: boolean = minc === maxc;
const trVal: number | string = this.getPropertyValue(minr, maxc, dataSheetIdx);
// trVal = this.getParseValue(trVal);
const blVal: number | string = this.getPropertyValue(maxr, minc, dataSheetIdx);
// blVal = this.getParseValue(blVal);
const tlVal: number | string = this.getPropertyValue(minr, minc, dataSheetIdx);
// tlVal = this.getParseValue(tlVal);
if (!isNumber(blVal) || !tlVal) {
isStringSeries = true;
}
if (isNullOrUndefined(tlVal) && !isSingleRow && !isSingleCol || (opt.type === 'Scatter' && range[3] - range[1] === 1)) {
xRange = [minr + 1, minc, maxr, minc];
yRange = [minr + 1, minc + 1, maxr, maxc];
lRange = [minr, minc + 1, minr, maxc];
} else if ((!isNullOrUndefined(blVal) && isStringSeries && !isSingleRow && !isSingleCol)) {
if (!isNullOrUndefined(trVal) && (!isNumber(trVal) || !tlVal)) {
xRange = [minr + 1, minc, maxr, minc];
yRange = [minr + 1, minc + 1, maxr, maxc];
lRange = [minr, minc + 1, minr, maxc];
} else {
xRange = [minr, minc, maxr, minc];
yRange = [minr, minc + 1, maxr, maxc];
}
} else {
yRange = [minr, minc, maxr, maxc];
if ((!isNullOrUndefined(trVal) && !isNumber(trVal) && !isDateTime(trVal))) {
lRange = [minr, minc, minr, maxc];
yRange[0] = yRange[0] + 1;
} else if (isNullOrUndefined(tlVal) && (isSingleRow || isSingleCol)) {
lRange = [minr, minc, minr, maxc];
if (isSingleRow) {
yRange[1] = yRange[1] + 1;
lRange[3] = lRange[1];
} else {
yRange[0] = yRange[0] + 1;
}
}
}
return { xRange: xRange, yRange: yRange, lRange: lRange };
}
private toIntrnlRange(range: number[], sheetIdx: number): number[] {
if (!range) {
range = getRangeIndexes[this.parent.sheets[sheetIdx].selectedRange];
} else if (typeof (range) === 'string') {
range = getRangeIndexes[range];
}
return range;
}
private getRangeData(options: { range: number[], sheetIdx: number, skipFormula: boolean, isYvalue: boolean }): { value: number }[] {
options.range = this.toIntrnlRange(options.range, options.sheetIdx);
const rowIdx: number[] = []; const arr: { value: number }[] = [];
this.pushRowData(
options, options.range[0], options.range[1], options.range[2], options.range[3], arr, rowIdx, true, options.isYvalue);
return arr;
}
private pushRowData(
options: { range: number[], sheetIdx: number, skipFormula: boolean }, minr: number,
minc: number, maxr: number, maxc: number, arr: object[], rowIdx: number[], isDataSrcEnsured: boolean, isYvalue: boolean): void {
const minCol: number = minc; const sheet: SheetModel = this.parent.sheets[options.sheetIdx];
while (minr <= maxr) {
if (isHiddenRow(sheet, minr)) { minr++; continue; }
minc = minCol;
while (minc <= maxc) {
if (isHiddenCol(sheet, minc)) { minc++; continue; }
let value: string | number = '';
const cell: CellModel = getCell(minr, minc, sheet);
if (cell && cell.format && !isYvalue) {
const forArgs: { [key: string]: string | boolean | CellModel } = {
value: cell && cell.value, format: cell && cell.format ? cell.format : 'General',
formattedText: cell && cell.value, onLoad: true,
type: cell && getTypeFromFormat(cell.format),
rowIndex: minr.toString(), colIndex: minc.toString(),
isRightAlign: false, cell: cell
};
this.parent.notify(getFormattedCellObject, forArgs);
value = forArgs.formattedText ? forArgs.formattedText.toString() : '';
} else {
value = cell ? (!isNullOrUndefined(cell.value) ? cell.value : '') : '';
}
// = this.parent.getValueRowCol(options.sheetIdx, minr + 1, minc + 1);
arr.push({ value });
minc++;
}
minr++;
}
rowIdx.push(minr);
}
private toArrayData(args: { value: number }[]): string[] {
const prop: string = 'value'; let obj: object; let i: number = 0;
const temp: string[] = []; const len: number = args.length;
while (i < len) {
obj = args[i];
if (Object.keys(obj).length) {
if (prop in obj) {
temp.push(obj[prop]);
}
} else {
temp.push('');
}
i++;
}
return temp;
}
private getVirtualXValues(limit: number): string[] {
let i: number = 1; const arr: string[] = [];
while (i < limit) {
arr.push(i.toString());
i++;
}
return arr;
}
private processChartSeries(
options: ChartModel, sheetIndex: number, xRange: number[], yRange: number[],
lRange: number[]): { series: SeriesModel[] | AccumulationSeriesModel[], xRange: number[], yRange: number[], lRange: number[] } {
options = options || {};
let seriesName: string = '';
const dataLabel: DataLabelSettingsModel = {};
let val: number | string; let xValue: string[];
let lValue: string[]; let diff: number;
let pArr: object[];
let pObj: object = {};
let j: number;
let i: number = 0; let yInc: number = 0;
const sArr: SeriesModel[] = []; let dtVal: number;
sheetIndex = isNullOrUndefined(sheetIndex) ? this.parent.getActiveSheet().index : sheetIndex;
const sheet: SheetModel = this.parent.sheets[sheetIndex];
const yValue: { value: number }[] = this.getRangeData({ range: yRange, sheetIdx: sheetIndex, skipFormula: true, isYvalue: true });
const rDiff: number = ((yRange[2] - yRange[0]) + 1) - this.parent.hiddenCount(yRange[0], yRange[2], 'rows', sheet);
const cDiff: number = ((yRange[3] - yRange[1]) + 1) - this.parent.hiddenCount(yRange[0], yRange[2], 'columns', sheet);
if (options.isSeriesInRows) {
xValue = lRange ? this.toArrayData(
this.getRangeData({ range: lRange, sheetIdx: sheetIndex, skipFormula: false, isYvalue: false })) :
this.getVirtualXValues(cDiff + 1);
if (xRange) {
lValue = this.toArrayData(this.getRangeData(
{ range: xRange, sheetIdx: sheetIndex, skipFormula: false, isYvalue: false }));
}
diff = rDiff;
} else {
xValue = xRange ? this.toArrayData(this.getRangeData(
{ range: xRange, sheetIdx: sheetIndex, skipFormula: false, isYvalue: false })) :
this.getVirtualXValues(rDiff + 1);
if (lRange) {
lValue = this.toArrayData(this.getRangeData(
{ range: lRange, sheetIdx: sheetIndex, skipFormula: false, isYvalue: false }));
}
diff = cDiff;
}
const len: number = xValue.length;
const inc: number = options.isSeriesInRows ? 1 : diff;
if (!isNullOrUndefined(options.dataLabelSettings)) {
dataLabel.visible = options.dataLabelSettings.visible;
dataLabel.position = options.dataLabelSettings.position;
}
while (i < diff) {
j = 0;
pArr = [];
yInc = options.isSeriesInRows ? yInc : i;
while (j < len) {
if (yValue[yInc]) {
val = yValue[yInc].value;
if (isNumber(val)) {
val = Number(val);
} else {
dtVal = dateToInt(val);
val = isNaN(dtVal) ? 0 : dtVal;
}
pArr.push({ x: xValue[j], y: val });
}
yInc += inc;
j++;
}
if (lValue && lValue.length > 0) {
seriesName = lValue[i] as string;
} else {
seriesName = 'series' + i;
}
if (options.type) {
const type: ChartType = options.type;
if (type === 'Line' || type === 'StackingLine' || type === 'StackingLine100') {
pObj = {
dataSource: pArr, type: options.type, xName: 'x', yName: 'y', name: seriesName.toString(), marker: {
visible: true,
width: 10,
height: 10,
dataLabel: dataLabel
}
};
} else if (type === 'Scatter') {
pObj = {
dataSource: pArr, type: options.type, xName: 'x', yName: 'y', name: seriesName.toString(), marker: {
visible: false,
width: 12,
height: 12,
shape: 'Circle',
dataLabel: dataLabel
}
};
} else if (type === 'Pie' || type === 'Doughnut') {
const innerRadius: string = options.type === 'Pie' ? '0%' : '40%';
const visible: boolean = dataLabel.visible;
const position: AccumulationLabelPosition = isNullOrUndefined(dataLabel.position) ? 'Inside' : dataLabel.position === 'Outer' ? 'Outside' : 'Inside';
pObj = {
dataSource: pArr,
dataLabel: {
visible: !isNullOrUndefined(visible) ? visible : false, position: position, name: 'text', font: { fontWeight: '600' }
},
radius: '100%', xName: 'x', yName: 'y', innerRadius: innerRadius
};
} else {
pObj = {
dataSource: pArr, type: options.type, xName: 'x', yName: 'y',
name: seriesName.toString(), marker: { dataLabel: dataLabel }
};
}
}
sArr.push(pObj);
i++;
}
let retVal: { series: SeriesModel[], xRange: number[], yRange: number[], lRange: number[] };
if (options.type) {
retVal = {
series: sArr, xRange: options.isSeriesInRows ? lRange : xRange,
yRange: yRange, lRange: options.isSeriesInRows ? xRange : lRange
};
}
return retVal;
}
private primaryYAxisFormat(yRange: number[]): string {
if (isNullOrUndefined(yRange)) {
return '{value}';
}
let type: string;
const cell: CellModel = getCell(yRange[0], yRange[1], this.parent.getActiveSheet());
if (cell && cell.format) {
type = getTypeFromFormat(cell.format);
if (type === 'Accounting') {
return '${value}';
} else if (type === 'Currency') {
return '${value}';
} else if (type === 'Percentage') {
return '{value}%';
}
}
return '{value}';
}
private focusChartRange(xRange: number[], yRange: number[], lRange: number[]): void {
const border: string[] =
['e-rcborderright', 'e-rcborderbottom', 'e-vcborderright', 'e-vcborderbottom', 'e-bcborderright', 'e-bcborderbottom'];
this.clearBorder();
let range: number[]; const sheet: SheetModel = this.parent.getActiveSheet();
const isFreezePane: boolean = !!(sheet.frozenRows || sheet.frozenColumns);
if (lRange) {
if (isFreezePane) {
range = lRange;
} else {
this.parent.notify(focusBorder, {
startcell: { rowIndex: lRange[0], colIndex: lRange[1] },
endcell: { rowIndex: lRange[2], colIndex: lRange[3] }, classes: [border[0], border[1]]
});
}
}
if (xRange) {
if (isFreezePane) {
if (range) {
range[0] = Math.min(lRange[0], xRange[0]); range[1] = Math.min(lRange[1], xRange[1]);
range[2] = Math.max(lRange[2], xRange[2]); range[3] = Math.max(lRange[3], xRange[3]);
} else {
range = xRange;
}
} else {
this.parent.notify(focusBorder, {
startcell: { rowIndex: xRange[0], colIndex: xRange[1] },
endcell: { rowIndex: xRange[2], colIndex: xRange[3] }, classes: [border[2], border[3]]
});
}
}
if (isFreezePane && range) {
this.parent.notify(focusBorder, {
startcell: { rowIndex: Math.min(range[0], yRange[0]), colIndex: Math.min(range[1], yRange[1]) },
endcell: {
rowIndex: Math.max(range[2], yRange[2]), colIndex: Math.max(range[3],
yRange[3])
}, classes: [border[4], border[5]]
});
} else {
this.parent.notify(focusBorder, {
startcell: { rowIndex: yRange[0], colIndex: yRange[1] },
endcell: { rowIndex: yRange[2], colIndex: yRange[3] }, classes: [border[4], border[5]]
});
}
}
private clearBorder(): void {
const sheet: SheetModel = this.parent.getActiveSheet();
if (sheet.frozenColumns || sheet.frozenRows) {
const chartIndicator: Element[] = [].slice.call(this.parent.element.getElementsByClassName('e-chart-range'));
chartIndicator.forEach((indicator: Element): void => { detach(indicator); });
return;
}
const mainCont: Element = this.parent.getMainContent();
const border: string[] =
['e-rcborderright', 'e-rcborderbottom', 'e-vcborderright', 'e-vcborderbottom', 'e-bcborderright', 'e-bcborderbottom'];
for (let borderIdx: number = 0, borderLen: number = border.length; borderIdx < borderLen; borderIdx++) {
const eleColl: NodeListOf<Element> = mainCont.querySelectorAll('.' + border[borderIdx]);
for (let tdIdx: number = 0, eleCollLen: number = eleColl.length; tdIdx < eleCollLen; tdIdx++) {
const td: HTMLElement = eleColl[tdIdx] as HTMLElement;
td.classList.remove(border[borderIdx]);
}
}
}
private initiateChartHandler(argsOpt: {
option: ChartModel, chartCount?: number, isRefresh?: boolean, isInitCell?: boolean,
triggerEvent?: boolean, dataSheetIdx?: number, range?: string, isPaste?: boolean
}): SeriesModel[] | AccumulationSeriesModel[] {
const chart: ChartModel = argsOpt.option;
let isRangeSelect: boolean = true;
isRangeSelect = isNullOrUndefined(argsOpt.isInitCell) ? true : !argsOpt.isInitCell;
argsOpt.triggerEvent = isNullOrUndefined(argsOpt.triggerEvent) ? true : argsOpt.triggerEvent;
let seriesModel: SeriesModel[];
argsOpt.isRefresh = isNullOrUndefined(argsOpt.isRefresh) ? false : argsOpt.isRefresh;
const sheetIdx: number = (chart.range && chart.range.indexOf('!') > 0) ?
getSheetIndex(this.parent as Workbook, chart.range.split('!')[0]) : this.parent.activeSheetIndex;
const sheet: SheetModel = getSheet(this.parent, sheetIdx);
let range: string = chart.range ? chart.range : this.parent.getActiveSheet().selectedRange;
const rangeIdx: number[] = getRangeIndexes(range);
let options: ChartModel = {};
let isRowLesser: boolean;
let eventArgs: BeforeChartEventArgs;
if (!this.parent.allowChart && sheet.isProtected) {
return seriesModel;
}
const args: {
sheetIndex: number, reqType: string, type: string, shapeType: string, action: string,
options: ChartModel, range: string, operation: string
} = {
sheetIndex: sheetIdx, reqType: 'shape', type: 'actionBegin', shapeType: 'chart',
action: 'create', options: chart, range: range, operation: 'create'
};
options = args.options;
range = args.range;
options = options || {};
if (rangeIdx.length > 0) {
const rDiff: number = rangeIdx[2] - rangeIdx[0];
const cDiff: number = rangeIdx[3] - rangeIdx[1];
if (rDiff < cDiff) {
isRowLesser = true;
}
}
options.isSeriesInRows = isRowLesser ? true : options.isSeriesInRows ? options.isSeriesInRows : false;
argsOpt.dataSheetIdx = isNullOrUndefined(argsOpt.dataSheetIdx) ? sheetIdx : argsOpt.dataSheetIdx;
const chartRange: { xRange: number[], yRange: number[], lRange: number[] } =
this.processChartRange(rangeIdx, argsOpt.dataSheetIdx, options);
const xRange: number[] = chartRange.xRange;
const yRange: number[] = chartRange.yRange;
const lRange: number[] = chartRange.lRange;
if (sheetIdx === this.parent.activeSheetIndex && isRangeSelect) {
this.focusChartRange(xRange, yRange, lRange);
}
const chartOptions: { series: SeriesModel[] | AccumulationSeriesModel[], xRange: number[], yRange: number[], lRange: number[] } =
this.processChartSeries(options, argsOpt.dataSheetIdx, xRange, yRange, lRange);
const primaryXAxis: AxisModel = {
majorGridLines: chart.primaryXAxis && chart.primaryXAxis.majorGridLines &&
!isNullOrUndefined(chart.primaryXAxis.majorGridLines.width) ?
{ width: chart.primaryXAxis.majorGridLines.width } : { width: 0 },
minorGridLines: chart.primaryXAxis && chart.primaryXAxis.minorGridLines &&
!isNullOrUndefined(chart.primaryXAxis.minorGridLines.width) ?
{ width: chart.primaryXAxis.minorGridLines.width } : { width: 0 },
minorTicksPerInterval: chart.primaryXAxis && chart.primaryXAxis.minorGridLines && chart.primaryXAxis.minorGridLines.width > 0 ?
5 : 0,
lineStyle: { width: 0 },
valueType: 'Category',
visible: chart.primaryXAxis ? chart.primaryXAxis.visible : true,
title: chart.primaryXAxis ? chart.primaryXAxis.title : ''
};
const primaryYAxis: AxisModel = {
lineStyle: { width: 0 },
majorGridLines: chart.primaryYAxis && chart.primaryYAxis.majorGridLines &&
!isNullOrUndefined(chart.primaryYAxis.majorGridLines.width) ?
{ width: chart.primaryYAxis.majorGridLines.width } : { width: 1 },
minorGridLines: chart.primaryYAxis && chart.primaryYAxis.minorGridLines &&
!isNullOrUndefined(chart.primaryYAxis.minorGridLines.width) ?
{ width: chart.primaryYAxis.minorGridLines.width } : { width: 0 },
minorTicksPerInterval: chart.primaryYAxis && chart.primaryYAxis.minorGridLines && chart.primaryYAxis.minorGridLines.width > 0 ?
5 : 0,
labelFormat: this.primaryYAxisFormat(yRange),
visible: chart.primaryYAxis ? chart.primaryYAxis.visible : true,
title: chart.primaryYAxis ? chart.primaryYAxis.title : ''
};
if (argsOpt.isRefresh) {
return chartOptions.series;
}
if (argsOpt.triggerEvent) {
eventArgs = {
type: chart.type, theme: chart.theme, isSeriesInRows: chart.isSeriesInRows, range: chart.range, id: chart.id,
height: chart.height, width: chart.width, posRange: argsOpt.range, isInitCell: argsOpt.isInitCell, cancel: false
};
this.parent.notify(beginAction, { eventArgs: eventArgs, action: 'beforeInsertChart' });
if (eventArgs.cancel) { return []; }
chart.type = eventArgs.type;
chart.theme = eventArgs.theme;
chart.isSeriesInRows = eventArgs.isSeriesInRows;
chart.range = eventArgs.range;
chart.id = eventArgs.id;
chart.height = eventArgs.height;
chart.width = eventArgs.width;
}
const id: string = chart.id + '_overlay';
const overlayObj: Overlay = this.parent.serviceLocator.getService(overlay) as Overlay;
const eleRange: string = !isNullOrUndefined(argsOpt.isInitCell) && argsOpt.isInitCell ? argsOpt.range : range;
const element: HTMLElement = overlayObj.insertOverlayElement(id, eleRange, getSheetIndexFromAddress(this.parent, eleRange));
element.classList.add('e-datavisualization-chart');
element.style.width = chart.width + 'px';
element.style.height = chart.height + 'px';
if (sheet.frozenRows || sheet.frozenColumns) {
overlayObj.adjustFreezePaneSize(chart, element, eleRange);
} else {
element.style.top = isNullOrUndefined(chart.top) ? element.style.top : (chart.top + 'px');
element.style.left = isNullOrUndefined(chart.left) ? element.style.left : (chart.left + 'px');
chart.top = parseInt(element.style.top.replace('px', ''), 10);
chart.left = parseInt(element.style.left.replace('px', ''), 10);
}
this.parent.notify(overlayEleSize, { height: chart.height, width: chart.width });
const legendSettings: LegendSettingsModel =
(chart.type === 'Pie' || chart.type === 'Doughnut') ? { position: 'Bottom', visible: true } : {};
if (!isNullOrUndefined(chart.legendSettings)) {
legendSettings.visible = chart.legendSettings.visible;
legendSettings.position = chart.legendSettings.position;
}
const chartContent: HTMLElement =
this.parent.createElement('div', {
id: chart.id, className: chart.id
});
if (chart.type !== 'Pie' && chart.type !== 'Doughnut') {
this.chart = new Chart({
primaryXAxis: primaryXAxis,
primaryYAxis: primaryYAxis,
chartArea: {
border: {
width: 0
}
},
title: chart.title,
legendSettings: legendSettings,
theme: chart.theme,
series: chartOptions.series as SeriesModel[],
tooltip: {
enable: true
},
width: element.style.width,
height: element.style.height,
load: (args: ILoadedEventArgs) => {
let selectedTheme: string = chart.theme;
selectedTheme = selectedTheme ? selectedTheme : 'Material';
args.chart.theme = selectedTheme as ChartTheme;
},
beforeResize: (args: IBeforeResizeEventArgs) => {
args.cancelResizedEvent = true; // This is for cancel the resized event.
}
});
this.chart.appendTo(chartContent);
} else {
this.chart = new AccumulationChart({
title: chart.title,
legendSettings: legendSettings,
theme: chart.theme,
series: chartOptions.series as AccumulationSeriesModel[],
width: element.style.width,
height: element.style.height,
center: { x: '50%', y: '50%' },
enableSmartLabels: true,
enableAnimation: true,
load: (args: IAccLoadedEventArgs) => {
let selectedTheme: string = chart.theme;
selectedTheme = selectedTheme ? selectedTheme : 'Material';
args.chart.theme = selectedTheme as ChartTheme;
},
beforeResize: (args: IBeforeResizeEventArgs) => {
args.cancelResizedEvent = true; // This is for cancel the resized event.
}
});
this.chart.appendTo(chartContent);
}
element.appendChild(chartContent);
if (argsOpt.triggerEvent) {
this.parent.notify(completeAction, { eventArgs: eventArgs, action: 'insertChart' });
}
return seriesModel;
}
public deleteChart(args: { id: string, range?: string, isUndoRedo?: boolean }): void {
this.clearBorder();
let chartElements: HTMLElement = null;
let sheet: SheetModel = this.parent.getActiveSheet();
if (isNullOrUndefined(args.id)) {
chartElements = document.querySelector('.e-datavisualization-chart.e-ss-overlay-active') as HTMLElement;
args.id = chartElements ? chartElements.getElementsByClassName('e-control')[0].id : null;
} else {
args.id = args.id.includes('overlay') ? args.id : args.id + '_overlay';
chartElements = document.getElementById(args.id);
}
if (isNullOrUndefined(args.id)) {
return;
} else {
args.id = args.id.includes('overlay') ? args.id : args.id + '_overlay';
}
let rowIdx: number; let colIdx: number;
let prevCellChart: ChartModel[];
let isRemoveEle: boolean = false;
let chartObj: ChartModel;
for (let i: number = 0, chartCollLen: number = this.parent.chartColl.length; i < chartCollLen; i++) {
if (this.parent.chartColl[i].id === args.id.split('_overlay')[0]) {
chartObj = this.parent.chartColl[i];
break;
}
}
const eventArgs: BeforeChartEventArgs = {
id: chartObj.id, range: chartObj.range, type: chartObj.type, theme: chartObj.theme, height: chartObj.height,
width: chartObj.width, isSeriesInRows: chartObj.isSeriesInRows, isInitCell: true, posRange: null,
top: chartObj.top, left: chartObj.left, cancel: false
};
if (chartElements) {
let chartTop: { clientY: number, isImage?: boolean, target?: Element };
let chartleft: { clientX: number, isImage?: boolean, target?: Element };
if (sheet.frozenRows || sheet.frozenColumns) {
const clientRect: ClientRect = chartElements.getBoundingClientRect();
chartTop = { clientY: clientRect.top }; chartleft = { clientX: clientRect.left };
if (clientRect.top < this.parent.getColumnHeaderContent().getBoundingClientRect().bottom) {
chartTop.target = this.parent.getColumnHeaderContent();
}
if (clientRect.left < this.parent.getRowHeaderContent().getBoundingClientRect().right) {
chartleft.target = this.parent.getRowHeaderTable();
}
} else {
chartTop = { clientY: chartElements.offsetTop, isImage: true };
chartleft = { clientX: chartElements.offsetLeft, isImage: true };
}
this.parent.notify(deleteChartColl, { id: args.id });
this.parent.notify(getRowIdxFromClientY, chartTop); this.parent.notify(getColIdxFromClientX, chartleft);
isRemoveEle = true;
rowIdx = chartTop.clientY; colIdx = chartleft.clientX;
sheet = this.parent.sheets[this.parent.activeSheetIndex];
} else {
this.parent.notify(deleteChartColl, { id: args.id });
const sheetIndex: number = args.range && args.range.indexOf('!') > 0 ? getSheetIndex(this.parent as Workbook, args.range.split('!')[0]) :
this.parent.activeSheetIndex;
const rangeVal: string = args.range ? args.range.indexOf('!') > 0 ? args.range.split('!')[1] : args.range.split('!')[0] :
this.parent.getActiveSheet().selectedRange;
const index: number[] = getRangeIndexes(rangeVal);
rowIdx = index[0]; colIdx = index[1];
sheet = this.parent.sheets[sheetIndex];
}
const cellObj: CellModel = getCell(rowIdx, colIdx, sheet);
if (cellObj) {
prevCellChart = cellObj.chart;
}
const chartLength: number = prevCellChart ? prevCellChart.length : null;
for (let i: number = 0; i < chartLength; i++) {
if (args.id === prevCellChart[i].id + '_overlay') {
prevCellChart.splice(i, 1);
}
}
if (isRemoveEle) {
document.getElementById(args.id).remove();
this.parent.notify(removeDesignChart, {});
}
setCell(rowIdx, colIdx, sheet, { chart: prevCellChart }, true);
eventArgs.posRange = getCellAddress(rowIdx, colIdx);
if (!args.isUndoRedo) {
this.parent.notify(completeAction, { eventArgs: eventArgs, action: 'deleteChart' });
}
}
private updateChartModel
(eleId: string, chartComp: Chart | AccumulationChart, currCellObj: CellModel,
chartCollId: number, isAccumulationChart?: boolean): void {
const accumulationChartComp: AccumulationChart = chartComp as AccumulationChart;
chartComp = chartComp as Chart;
const chartId: string = this.parent.chartColl[chartCollId].id;
if (isAccumulationChart &&
['PHAxes', 'PVAxes', 'PHAxisTitle', 'PVAxisTitle', 'GLMajorHorizontal',
'GLMajorVertical', 'GLMinorHorizontal', 'GLMinorVertical'].indexOf(eleId) > -1) { return; }
for (let idx: number = 0, chartsCount: number = currCellObj.chart.length; idx < chartsCount; idx++) {
if (currCellObj.chart[idx].id === chartId) {
switch (eleId) {
case 'PHAxes': case 'PHAxisTitle':
if (isNullOrUndefined(currCellObj.chart[idx].primaryXAxis)) {
currCellObj.chart[idx].primaryXAxis = {}; this.parent.chartColl[chartCollId].primaryXAxis = {};
}
if (eleId === 'PHAxes') {
currCellObj.chart[idx].primaryXAxis.visible = chartComp.primaryXAxis.visible;
this.parent.chartColl[chartCollId].primaryXAxis.visible = chartComp.primaryXAxis.visible;
} else if (eleId === 'PHAxisTitle') {
currCellObj.chart[idx].primaryXAxis.title = chartComp.primaryXAxis.title;
this.parent.chartColl[chartCollId].primaryXAxis.title = chartComp.primaryXAxis.title;
} break;
case 'PVAxes': case 'PVAxisTitle':
if (isNullOrUndefined(currCellObj.chart[idx].primaryYAxis)) {
currCellObj.chart[idx].primaryYAxis = {}; this.parent.chartColl[chartCollId].primaryYAxis = {};
}
if (eleId === 'PVAxes') {
currCellObj.chart[idx].primaryYAxis.visible = chartComp.primaryYAxis.visible;
this.parent.chartColl[chartCollId].primaryYAxis.visible = chartComp.primaryYAxis.visible;
} else if (eleId === 'PVAxisTitle') {
currCellObj.chart[idx].primaryYAxis.title = chartComp.primaryYAxis.title;
this.parent.chartColl[chartCollId].primaryYAxis.title = chartComp.primaryYAxis.title;
} break;
case 'ChartTitleNone': case 'ChartTitleAbove':
currCellObj.chart[idx].title = chartComp.title; this.parent.chartColl[chartCollId].title = chartComp.title;
break;
case 'DLNone': case 'DLCenter': case 'DLInsideend': case 'DLInsidebase': case 'DLOutsideend':
if (isNullOrUndefined(currCellObj.chart[idx].dataLabelSettings)) {
currCellObj.chart[idx].dataLabelSettings = {}; this.parent.chartColl[chartCollId].dataLabelSettings = {};
}
if (eleId === 'DLNone') {
currCellObj.chart[idx].dataLabelSettings.visible = false;
this.parent.chartColl[chartCollId].dataLabelSettings.visible = false;
} else {
currCellObj.chart[idx].dataLabelSettings.visible = true;
this.parent.chartColl[chartCollId].dataLabelSettings.visible = true;
let position: LabelPosition;
if (isAccumulationChart) {
position = accumulationChartComp.series[0].dataLabel.position === 'Outside' ? 'Outer' : 'Middle';
} else {
position = chartComp.series[0].marker.dataLabel.position;
}
currCellObj.chart[idx].dataLabelSettings.position = position;
this.parent.chartColl[chartCollId].dataLabelSettings.position = position;
} break;
case 'GLMajorHorizontal':
if (isNullOrUndefined(currCellObj.chart[idx].primaryYAxis)) {
currCellObj.chart[idx].primaryYAxis = {}; this.parent.chartColl[chartCollId].primaryYAxis = {};
}
if (isNullOrUndefined(currCellObj.chart[idx].primaryYAxis.majorGridLines)) {
currCellObj.chart[idx].primaryYAxis.majorGridLines = {};
this.parent.chartColl[chartCollId].primaryYAxis.majorGridLines = {};
}
currCellObj.chart[idx].primaryYAxis.majorGridLines.width = chartComp.primaryYAxis.majorGridLines.width;
this.parent.chartColl[chartCollId].primaryYAxis.majorGridLines.width = chartComp.primaryYAxis.majorGridLines.width;
break;
case 'GLMajorVertical':
if (isNullOrUndefined(currCellObj.chart[idx].primaryXAxis)) {
currCellObj.chart[idx].primaryXAxis = {}; this.parent.chartColl[chartCollId].primaryXAxis = {};
}
if (isNullOrUndefined(currCellObj.chart[idx].primaryXAxis.majorGridLines)) {
currCellObj.chart[idx].primaryXAxis.majorGridLines = {};
this.parent.chartColl[chartCollId].primaryXAxis.majorGridLines = {};
}
currCellObj.chart[idx].primaryXAxis.majorGridLines.width = chartComp.primaryXAxis.majorGridLines.width;
this.parent.chartColl[chartCollId].primaryXAxis.majorGridLines.width = chartComp.primaryXAxis.majorGridLines.width;
break;
case 'GLMinorHorizontal':
if (isNullOrUndefined(currCellObj.chart[idx].primaryYAxis)) {
currCellObj.chart[idx].primaryYAxis = {}; this.parent.chartColl[chartCollId].primaryYAxis = {};
}
if (isNullOrUndefined(currCellObj.chart[idx].primaryYAxis.minorGridLines)) {
currCellObj.chart[idx].primaryYAxis.minorGridLines = {};
this.parent.chartColl[chartCollId].primaryYAxis.minorGridLines = {};
}
currCellObj.chart[idx].primaryYAxis.minorGridLines.width = chartComp.primaryYAxis.minorGridLines.width;
this.parent.chartColl[chartCollId].primaryYAxis.minorGridLines.width = chartComp.primaryYAxis.minorGridLines.width;
break;
case 'GLMinorVertical':
if (isNullOrUndefined(currCellObj.chart[idx].primaryXAxis)) {
currCellObj.chart[idx].primaryXAxis = {}; this.parent.chartColl[chartCollId].primaryXAxis = {};
}
if (isNullOrUndefined(currCellObj.chart[idx].primaryXAxis.minorGridLines)) {
currCellObj.chart[idx].primaryXAxis.minorGridLines = {};
this.parent.chartColl[chartCollId].primaryXAxis.minorGridLines = {};
}
currCellObj.chart[idx].primaryXAxis.minorGridLines.width = chartComp.primaryXAxis.minorGridLines.width;
this.parent.chartColl[chartCollId].primaryXAxis.minorGridLines.width = chartComp.primaryXAxis.minorGridLines.width;
break;
case 'LegendNone': case 'LegendsRight': case 'LegendsLeft': case 'LegendsBottom': case 'LegendsTop':
if (isNullOrUndefined(currCellObj.chart[idx].legendSettings)) {
currCellObj.chart[idx].legendSettings = {}; this.parent.chartColl[chartCollId].legendSettings = {};
}
currCellObj.chart[idx].legendSettings.visible = chartComp.legendSettings.visible;
this.parent.chartColl[chartCollId].legendSettings.visible = chartComp.legendSettings.visible;
if (eleId !== 'LegendNone') {
currCellObj.chart[idx].legendSettings.position = chartComp.legendSettings.position as LegendPosition;
this.parent.chartColl[chartCollId].legendSettings.position =
chartComp.legendSettings.position as LegendPosition; break;
}
}
}
}
}
private updateChartElement(value: string, chartComp: Chart | AccumulationChart, currCellObj: CellModel,
chartCollId: number, title: string, isAccumulationChart?: boolean, address?: string, triggerEvent?: boolean): void {
if (isAccumulationChart &&
['PHAxes', 'PVAxes', 'PHAxisTitle', 'PVAxisTitle', 'GLMajorHorizontal',
'GLMajorVertical', 'GLMinorHorizontal', 'GLMinorVertical'].indexOf(value) > -1) { return; }
let chartSeries: SeriesModel[] | AccumulationSeriesModel[];
switch (value) {
case 'PHAxes':
chartComp = chartComp as Chart;
chartComp.primaryXAxis.visible = !chartComp.primaryXAxis.visible;
break;
case 'PVAxes':
chartComp = chartComp as Chart;
chartComp.primaryYAxis.visible = !chartComp.primaryYAxis.visible;
break;
case 'PHAxisTitle':
chartComp = chartComp as Chart;
chartComp.primaryXAxis.title = title;
break;
case 'PVAxisTitle':
chartComp = chartComp as Chart;
chartComp.primaryYAxis.title = title;
break;
case 'ChartTitleNone':
chartComp.title = '';
break;
case 'ChartTitleAbove':
chartComp.title = title;
break;
case 'DLNone':
case 'DLCenter':
case 'DLInsideend':
case 'DLInsidebase':
case 'DLOutsideend':
chartComp = isAccumulationChart ? chartComp as AccumulationChart : chartComp as Chart;
chartSeries = chartComp.series;
if (value === 'DLNone') {
for (let idx: number = 0, len: number = chartSeries.length; idx < len; idx++) {
if (isAccumulationChart) {
(chartSeries as AccumulationSeriesModel)[idx].dataLabel.visible = false;
} else {
(chartSeries[idx] as SeriesModel).marker.dataLabel.visible = false;
}
}
} else {
for (let idx: number = 0, len: number = chartSeries.length; idx < len; idx++) {
if (isAccumulationChart) {
const position: AccumulationLabelPosition = value === 'DLOutsideend' ? 'Outside' : 'Inside';
(chartSeries as AccumulationSeriesModel)[idx].dataLabel.visible = true;
(chartSeries as AccumulationSeriesModel)[idx].dataLabel.position = position;
} else {
const position: LabelPosition =
value === 'DLCenter' ? 'Middle' : value === 'DLInsideend' ? 'Top' : value === 'DLInsidebase' ?
'Bottom' : value === 'DLOutsideend' ? 'Outer' : (chartSeries[0] as SeriesModel).marker.dataLabel.position;
(chartSeries[idx] as SeriesModel).marker.dataLabel.visible = true;
(chartSeries[idx] as SeriesModel).marker.dataLabel.position = position;
}
}
}
chartComp.series = chartSeries;
if (isAccumulationChart) {
chartComp.refresh();
}
break;
case 'GLMajorHorizontal':
chartComp = chartComp as Chart;
chartComp.primaryYAxis.majorGridLines.width = chartComp.primaryYAxis.majorGridLines.width === 0 ? 1 : 0;
break;
case 'GLMajorVertical':
chartComp = chartComp as Chart;
chartComp.primaryXAxis.majorGridLines.width = chartComp.primaryXAxis.majorGridLines.width === 0 ? 1 : 0;
break;
case 'GLMinorHorizontal':
chartComp = chartComp as Chart;
chartComp.primaryYAxis.minorTicksPerInterval = chartComp.primaryYAxis.minorGridLines.width === 0 ? 5 : 0;
chartComp.primaryYAxis.minorGridLines.width = chartComp.primaryYAxis.minorGridLines.width === 0 ? 1 : 0;
break;
case 'GLMinorVertical':
chartComp = chartComp as Chart;
chartComp.primaryXAxis.minorTicksPerInterval = chartComp.primaryXAxis.minorGridLines.width === 0 ? 5 : 0;
chartComp.primaryXAxis.minorGridLines.width = chartComp.primaryXAxis.minorGridLines.width === 0 ? 1 : 0;
break;
case 'LegendNone':
chartComp.legendSettings.visible = false;
break;
case 'LegendsRight':
case 'LegendsLeft':
case 'LegendsBottom':
case 'LegendsTop':
chartComp.legendSettings.visible = true;
chartComp.legendSettings.position = value === 'LegendsRight' ? 'Right' : value === 'LegendsLeft' ? 'Left' : value ===
'LegendsBottom' ? 'Bottom' : value === 'LegendsTop' ? 'Top' : chartComp.legendSettings.position;
break;
}
this.updateChartModel(value, chartComp, currCellObj, chartCollId, isAccumulationChart);
if (triggerEvent) {
const eventArgs = { addChartEle: value, id: chartComp.element.id + '_overlay', title: title, address: address };
this.parent.notify(completeAction, { action: 'chartDesign', eventArgs: eventArgs });
}
}
private undoRedoForChartDesign(args: { addChartEle: string, switchRowColumn: boolean, chartTheme: ChartTheme, chartType: ChartType, beforeActionData: BeforeActionData, address: string, id: string, title: string, isUndo: boolean }): void {
const overlayElem: HTMLElement = document.getElementById(args.id);
if (!overlayElem) {
return;
}
const chartElem: HTMLElement = this.getChartElement(overlayElem);
let chartComp: Chart = getComponent(chartElem, 'chart');
if (isNullOrUndefined(chartComp)) {
chartComp = getComponent(chartElem, 'accumulationchart');
}
const addressInfo: { indices: number[], sheetIndex: number } = this.parent.getAddressInfo(args.address);
const cell: CellModel = getCell(addressInfo.indices[0], addressInfo.indices[1], getSheet(this.parent, addressInfo.sheetIndex));
const chartCollectionId: number = this.getChartCollectionId(chartElem.id);
let chart: ChartModel;
let property: string = args.addChartEle;
let title: string = args.title;
for (let i: number = 0; i < args.beforeActionData.cellDetails[0].chart.length; i++) {
if (chartElem.id === args.beforeActionData.cellDetails[0].chart[i].id) {
chart = args.beforeActionData.cellDetails[0].chart[i];
break;
}
}
if (args.switchRowColumn) {
this.switchRowColumn(chartCollectionId, chartElem.id, chartComp, cell);
} else if (args.chartTheme) {
this.switchChartTheme(chartCollectionId, chartElem.id, args.isUndo ? chart.theme : args.chartTheme, chartComp, cell);
} else if (args.chartType) {
this.switchChartType(chartCollectionId, chartElem.id, args.isUndo ? chart.type : args.chartType, chartComp, cell);
} else if (args.addChartEle) {
if (args.isUndo) {
let position: string;
switch (property) {
case 'DLNone':
case 'DLCenter':
case 'DLInsideend':
case 'DLInsidebase':
case 'DLOutsideend':
position = chart.dataLabelSettings && chart.dataLabelSettings.position;
property = position === 'Middle' ? 'DLCenter' : position === 'Top' ? 'DLInsideend' : position === 'Bottom' ?
'DLInsidebase' : position === 'Outer' ? 'DLOutsideend' : 'DLNone';
break;
case 'LegendNone':
case 'LegendsRight':
case 'LegendsLeft':
case 'LegendsBottom':
case 'LegendsTop':
if (chart.legendSettings && !chart.legendSettings.visible) {
position = 'LegendNone';
} else {
position = chart.legendSettings && chart.legendSettings.position;
property = position === 'Right' ? 'LegendsRight' : position === 'Left' ? 'LegendsLeft' : position ===
'Bottom' ? 'LegendsBottom' : position === 'Top' ? 'LegendsTop' : 'LegendsBottom';
}
break;
case 'PVAxisTitle':
title = chart.primaryYAxis && chart.primaryYAxis.title;
break;
case 'PHAxisTitle':
title = chart.primaryXAxis && chart.primaryXAxis.title;
break;
case 'ChartTitleNone':
case 'ChartTitleAbove':
title = chart.title;
break;
}
}
this.updateChartElement(property, chartComp, cell, chartCollectionId, title, null, args.address);
}
}
private chartDesignTabHandler(
args: { switchRowColumn?: boolean, chartType?: ChartType, chartTheme?: ChartTheme, addChartEle?: string, id?:string, title?:string, triggerEvent?: boolean }): void {
let isAccumulationChart: boolean = false;
const sheet: SheetModel = this.parent.sheets[this.parent.activeSheetIndex];
const switchRowColumn: boolean = args.switchRowColumn;
const chartType: ChartType = args.chartType;
const chartTheme: ChartTheme = args.chartTheme;
const addChartEle: string = args.addChartEle;
let chartComp: Chart | AccumulationChart = null;
let chartCollId: number;
const overlayElem: HTMLElement = args.id ? document.getElementById(args.id) : document.querySelector('.e-datavisualization-chart.e-ss-overlay-active') as HTMLElement;
if (!overlayElem) {
return;
}
const opensTitleDialog: boolean = addChartEle === 'ChartTitleAbove' || addChartEle === 'PHAxisTitle' || addChartEle === 'PVAxisTitle';
let chartTop: { clientY: number, isImage?: boolean, target?: Element };
let chartleft: { clientX: number, isImage?: boolean, target?: Element };
if (sheet.frozenRows || sheet.frozenColumns) {
const clientRect: ClientRect = overlayElem.getBoundingClientRect();
chartTop = { clientY: clientRect.top }; chartleft = { clientX: clientRect.left };
if (clientRect.top < this.parent.getColumnHeaderContent().getBoundingClientRect().bottom) {
chartTop.target = this.parent.getColumnHeaderContent();
}
if (clientRect.left < this.parent.getRowHeaderContent().getBoundingClientRect().right) {
chartleft.target = this.parent.getRowHeaderTable();
}
} else {
chartTop = { clientY: overlayElem.offsetTop, isImage: true };
chartleft = { clientX: overlayElem.offsetLeft, isImage: true };
}
this.parent.notify(getRowIdxFromClientY, chartTop);
this.parent.notify(getColIdxFromClientX, chartleft);
const currCellObj: CellModel = getCell(chartTop.clientY, chartleft.clientX, sheet);
const address: string = sheet.name + '!' + getCellAddress(chartTop.clientY, chartleft.clientX);
if (args.triggerEvent) {
const eventArgs = { switchRowColumn: args.switchRowColumn, chartType: args.chartType, chartTheme: args.chartTheme, addChartEle: args.addChartEle, id: overlayElem.id, address: address, cancel: false };
this.parent.notify(beginAction, { action: 'chartDesign', eventArgs: eventArgs });
if (eventArgs.cancel) {
return;
}
}
const chartObj: HTMLElement = this.getChartElement(overlayElem);
const chartId: string = chartObj.getAttribute('id');
chartCollId = this.getChartCollectionId(chartId);
if (chartObj) {
chartComp = getComponent(chartObj, 'chart');
if (isNullOrUndefined(chartComp)) {
chartComp = getComponent(chartObj, 'accumulationchart');
isAccumulationChart = true;
}
}
if (switchRowColumn && !isAccumulationChart) {
this.switchRowColumn(chartCollId, chartId, chartComp, currCellObj);
}
if (chartType) {
this.switchChartType(chartCollId, chartId, chartType, chartComp, currCellObj);
}
if (chartTheme) {
this.switchChartTheme(chartCollId, chartId, chartTheme, chartComp, currCellObj);
}
if (addChartEle) {
if (opensTitleDialog && !args.title) {
if (this.parent.element.getElementsByClassName('e-title-dlg').length > 0) {
return;
}
else {
this.titleDlgHandler(addChartEle, chartComp as Chart, currCellObj, chartCollId, isAccumulationChart, address, args.triggerEvent);
}
} else {
this.updateChartElement(addChartEle, chartComp, currCellObj, chartCollId, args.title, isAccumulationChart);
}
}
if (args.triggerEvent && !opensTitleDialog) {
const eventArgs = { switchRowColumn: args.switchRowColumn, chartType: args.chartType, chartTheme: args.chartTheme, addChartEle: args.addChartEle, id: overlayElem.id, address: address };
this.parent.notify(completeAction, { action: 'chartDesign', eventArgs: eventArgs });
}
}
private switchRowColumn(chartCollId: number, chartId: string, chartComp: Chart | AccumulationChart, cell: CellModel): void {
this.parent.chartColl[chartCollId].isSeriesInRows =
isNullOrUndefined(this.parent.chartColl[chartCollId].isSeriesInRows) ?
true : !this.parent.chartColl[chartCollId].isSeriesInRows;
for (let idx: number = 0, chartCount: number = cell.chart.length; idx < chartCount; idx++) {
if (cell.chart[idx].id === chartId) {
cell.chart[idx].isSeriesInRows =
isNullOrUndefined(cell.chart[idx].isSeriesInRows) ? true : !cell.chart[idx].isSeriesInRows;
}
}
const chartSeries: SeriesModel[] =
this.initiateChartHandler({ option: this.parent.chartColl[chartCollId], isRefresh: true }) as SeriesModel[];
chartComp.series = chartSeries;
}
private switchChartTheme(chartCollId: number, chartId: string, theme: ChartTheme, chartComp: Chart | AccumulationChart, cell: CellModel): void {
this.parent.chartColl[chartCollId].theme = theme;
for (let idx: number = 0, chartCount: number = cell.chart.length; idx < chartCount; idx++) {
if (cell.chart[idx].id === chartId) {
cell.chart[idx].theme = theme;
}
}
chartComp.theme = theme;
chartComp.refresh();
}
private switchChartType(chartCollId: number, chartId: string, chartType: ChartType, chartComp: Chart | AccumulationChart, cell: CellModel): void {
const type: ChartType = this.parent.chartColl[chartCollId].type;
this.parent.chartColl[chartCollId].type = chartType;
for (let idx: number = 0, chartCount: number = cell.chart.length; idx < chartCount; idx++) {
if (cell.chart[idx].id === chartId) {
cell.chart[idx].type = chartType;
}
}
if (chartType !== 'Pie' && chartType !== 'Doughnut') {
if (type === 'Pie' || type === 'Doughnut') {
this.changeCharType(chartCollId);
} else {
const chartSeries: SeriesModel[] = chartComp.series as SeriesModel[];
for (let idx: number = 0, len: number = chartSeries.length; idx < len; idx++) {
chartSeries[idx].type = chartType as ChartSeriesType;
}
chartComp.series = chartSeries;
chartComp.refresh();
}
} else {
if (type === 'Pie' || type === 'Doughnut') {
const chartSeries: AccumulationSeriesModel[] = chartComp.series as AccumulationSeriesModel[];
for (let idx: number = 0, len: number = chartSeries.length; idx < len; idx++) {
chartSeries[idx].innerRadius = chartType === 'Pie' ? '0%' : '40%';
}
chartComp.series = chartSeries;
chartComp.refresh();
} else {
this.changeCharType(chartCollId);
}
}
}
private getChartElement(overlayElem: Element): HTMLElement {
let chartObj: HTMLElement = overlayElem.querySelector('.e-chart');
if (isNullOrUndefined(chartObj)) {
chartObj = overlayElem.querySelector('.e-accumulationchart');
}
return chartObj;
}
private getChartCollectionId(id: string): number {
let chartCollectionId: number;
for (let i: number = 0, len: number = this.parent.chartColl.length; i < len; i++) {
if (id === this.parent.chartColl[i].id) {
chartCollectionId = i;
}
}
return chartCollectionId;
}
private changeCharType(chartCollId: number): void {
let chartEle: HTMLElement = document.getElementById(this.parent.chartColl[chartCollId].id);
let chartParEle: Element = closest(chartEle, '.e-datavisualization-chart');
chartParEle.remove();
this.parent.notify(initiateChart, {
option: this.parent.chartColl[chartCollId], isInitCell: false, triggerEvent: false,
isPaste: false
});
chartEle = document.getElementById(this.parent.chartColl[chartCollId].id);
chartParEle = closest(chartEle, '.e-datavisualization-chart');
if (!chartParEle.classList.contains('e-ss-overlay-active')) {
chartParEle.classList.add('e-ss-overlay-active');
}
}
private titleDlgHandler(addChartEle: string, chartComp: Chart, currCellObj: CellModel,
chartCollId: number, isAccumulationChart?: boolean, address?: string, triggerEvent?: boolean): void {
let title: string = '';
if (isAccumulationChart && (addChartEle === 'PHAxisTitle' || addChartEle === 'PVAxisTitle')) {
return;
}
const l10n: L10n = this.parent.serviceLocator.getService(locale);
const dialogInst: Dialog = (this.parent.serviceLocator.getService(dialog) as Dialog);
dialogInst.show({
width: 375, showCloseIcon: true, isModal: true, cssClass: 'e-title-dlg',
header: addChartEle === 'chart_abovechart' ? l10n.getConstant('ChartTitle') : addChartEle ===
'PHAxisTitle' ? l10n.getConstant('HorizontalAxisTitle') : l10n.getConstant('VerticalAxisTitle'),
target: document.querySelector('.e-control.e-spreadsheet') as HTMLElement,
beforeOpen: (): void => {
dialogInst.dialogInstance.content = this.titleDlgContent(addChartEle, chartComp);
dialogInst.dialogInstance.dataBind();
this.parent.element.focus();
},
buttons: [{
buttonModel: {
content: l10n.getConstant('Ok'),
isPrimary: true,
cssClass: 'e-btn e-clearall-btn e-flat'
},
click: (): void => {
const dlgCont: HTMLElement = this.parent.element.querySelector('.e-title-dlg').
getElementsByClassName('e-title-dlg-content')[0] as HTMLElement;
title = dlgCont.getElementsByTagName('input')[0].value;
dialogInst.hide();
this.updateChartElement(addChartEle, chartComp, currCellObj, chartCollId, title, null, address, triggerEvent);
}
}]
});
dialogInst.dialogInstance.refresh();
}
private titleDlgContent(addChartEle: string, chartComp: Chart): HTMLElement {
const l10n: L10n = this.parent.serviceLocator.getService(locale);
const dlgText: string = l10n.getConstant('EnterTitle');
const dlgContent: HTMLElement = this.parent.createElement('div', { className: 'e-title-dlg-content' });
const value1Text: HTMLElement = this.parent.createElement('span', { className: 'e-header e-top-header', innerHTML: dlgText });
const value1Inp: HTMLInputElement =
this.parent.createElement('input', { className: 'e-input', id: 'titleInput', attrs: { type: 'text' } });
dlgContent.appendChild(value1Text);
dlgContent.appendChild(value1Inp);
if (chartComp) {
if (addChartEle === 'PHAxisTitle') {
value1Inp.value = chartComp.primaryXAxis.title ? chartComp.primaryXAxis.title : value1Inp.value;
} else if (addChartEle === 'PVAxisTitle') {
value1Inp.value = chartComp.primaryYAxis.title ? chartComp.primaryYAxis.title : value1Inp.value;
} else {
value1Inp.value = chartComp.title ? chartComp.title : value1Inp.value;
}
}
return dlgContent;
}
/**
* Removing event listener for success and failure
*
* @returns {void} - Removing event listener for success and failure
*/
private removeEventListener(): void {
if (!this.parent.isDestroyed) {
this.parent.off(initiateChart, this.initiateChartHandler);
this.parent.off(refreshChartCellObj, this.refreshChartCellObj);
this.parent.off(updateChart, this.updateChartHandler);
this.parent.off(deleteChart, this.deleteChart);
this.parent.off(clearChartBorder, this.clearBorder);
this.parent.off(insertChart, this.insertChartHandler);
this.parent.off(chartRangeSelection, this.chartRangeHandler);
this.parent.off(chartDesignTab, this.chartDesignTabHandler);
this.parent.off(addChartEle, this.updateChartElement);
this.parent.off(undoRedoForChartDesign, this.undoRedoForChartDesign);
}
}
/**
* To Remove the event listeners.
*
* @returns {void} - To Remove the event listeners.
*/
public destroy(): void {
this.removeEventListener();
this.parent = null;
let chartEle: HTMLElement = null;
if (this.chart) {
chartEle = this.chart.element;
this.chart.destroy();
}
if (chartEle) { detach(chartEle); } this.chart = null;
}
/**
* Get the sheet chart module name.
*
* @returns {string} - Get the module name.
*/
public getModuleName(): string {
return 'spreadsheetChart';
}
} | the_stack |
import type {BrowserObject} from 'webdriverio'
import {createEvent, createStore, restore, sample} from 'effector'
import {block, h, list, node, rec, remap, spec, text, using} from 'forest'
// let addGlobals: Function
declare const act: (cb?: () => any) => Promise<void>
declare const initBrowser: () => Promise<void>
declare const el: HTMLElement
// let execFun: <T>(cb: (() => Promise<T> | T) | string) => Promise<T>
// let readHTML: () => string
declare const browser: BrowserObject
declare const exec: (cb: () => any) => Promise<string[]>
declare const execFunc: <T>(cb: () => Promise<T>) => Promise<T>
beforeEach(async () => {
await initBrowser()
}, 10e3)
it('works', async () => {
const [s1] = await exec(async () => {
const store = createStore([{name: 'alice'}, {name: 'bob'}, {name: 'carol'}])
using(el, () => {
h('header', () => {
h('h1', {
text: 'App title',
})
})
h('ul', () => {
list(store, ({store}) => {
h('li', {
text: remap(store, 'name'),
})
})
})
})
await act()
})
expect(s1).toMatchInlineSnapshot(`
"
<header><h1>App title</h1></header>
<ul>
<li>alice</li>
<li>bob</li>
<li>carol</li>
</ul>
"
`)
})
it('update content after store update', async () => {
const [s1, s2] = await exec(async () => {
const updateText = createEvent<string>()
const text = restore(updateText, 'text value')
using(el, () => {
h('div', {
text,
})
})
await act()
await act(() => {
updateText('updated')
})
})
expect(s1).toMatchInlineSnapshot(`
"
<div>text value</div>
"
`)
expect(s2).toMatchInlineSnapshot(`
"
<div>updated</div>
"
`)
})
it('support reactive style properties', async () => {
const [s1, s2] = await exec(async () => {
const updateAlign = createEvent<string>()
const align = restore(updateAlign, 'start')
using(el, () => {
h('div', {
text: 'content',
style: {
justifySelf: align,
},
})
})
await act()
await act(() => {
updateAlign('center')
})
})
expect(s1).toMatchInlineSnapshot(`
"
<div style='justify-self: start'>content</div>
"
`)
expect(s2).toMatchInlineSnapshot(`
"
<div style='justify-self: center'>content</div>
"
`)
})
describe('node(event) + upward store update', () => {
test('with units inside using', async () => {
const result = await execFunc(async () => {
let result = '--'
using(el, () => {
const update = createEvent<string>()
const target = createStore('--').on(update, (_, upd) => upd)
target.watch(value => {
result = value
})
h('div', () => {
node(node => {
update(node.tagName)
})
})
})
await act()
return result
})
expect(result).toMatchInlineSnapshot(`"DIV"`)
})
test('with units in root', async () => {
const result = await execFunc(async () => {
let result = '--'
const update = createEvent<string>()
const target = createStore('--').on(update, (_, upd) => upd)
target.watch(value => {
result = value
})
using(el, () => {
h('div', () => {
node(node => {
update(node.tagName)
})
})
})
await act()
return result
})
expect(result).toMatchInlineSnapshot(`"DIV"`)
})
})
test('node() is called exactly once', async () => {
const result = await execFunc(async () => {
let result = 0
using(el, () => {
h('div', () => {
node(() => {
result += 1
})
})
})
await act()
return result
})
expect(result).toBe(1)
})
it('support reactive style variables', async () => {
const [s1, s2] = await exec(async () => {
const updateAlign = createEvent<string>()
const align = restore(updateAlign, 'start')
using(el, () => {
h('div', {
text: 'content',
style: {
justifySelf: 'var(--align)',
},
styleVar: {
align,
},
})
})
await act()
await act(() => {
updateAlign('center')
})
})
expect(s1).toMatchInlineSnapshot(`
"
<div style='justify-self: var(--align); --align: start'>
content
</div>
"
`)
expect(s2).toMatchInlineSnapshot(`
"
<div style='justify-self: var(--align); --align: center'>
content
</div>
"
`)
})
it.skip('remove watch calls after node removal', async () => {
const [s1, s2, s3, s4] = await exec(async () => {
const tick = createEvent<number>()
const logRecord = createEvent<string>()
const removeUser = createEvent<string>()
let id = 0
const log = createStore<{id: number; value: string}[]>([]).on(
logRecord,
(list, rec) => [...list, {value: rec, id: ++id}],
)
const users = createStore(['alice', 'bob', 'carol']).on(
removeUser,
(list, user) => list.filter(e => e !== user),
)
using(el, () => {
h('section', () => {
list(users, ({store}) => {
h('div', {text: store})
sample({
source: store,
clock: tick,
fn: (user, tick) => ({user, tick}),
}).watch(({user, tick}) => {
logRecord(`[${tick}] ${user}`)
})
})
})
h('section', () => {
list(
{source: log, key: 'id', fields: ['value']},
({fields: [value]}) => {
h('div', {text: value})
},
)
})
})
await act()
await act(() => {
tick(0)
})
await act(() => {
removeUser('bob')
})
await act(() => {
tick(1)
})
})
expect(s1).toMatchInlineSnapshot(`
"
<section>
<div>alice</div>
<div>bob</div>
<div>carol</div>
</section>
<section></section>
"
`)
expect(s2).toMatchInlineSnapshot(`
"
<section>
<div>alice</div>
<div>bob</div>
<div>carol</div>
</section>
<section>
<div>[0] alice</div>
<div>[0] bob</div>
<div>[0] carol</div>
</section>
"
`)
expect(s3).toMatchInlineSnapshot(`
"
<section>
<div>alice</div>
<div>carol</div>
</section>
<section>
<div>[0] alice</div>
<div>[0] bob</div>
<div>[0] carol</div>
</section>
"
`)
expect(s4).toMatchInlineSnapshot(`
"
<section>
<div>alice</div>
<div>carol</div>
</section>
<section>
<div>[0] alice</div>
<div>[0] bob</div>
<div>[0] carol</div>
<div>[1] alice</div>
<div>[1] carol</div>
</section>
"
`)
})
describe('node reader', () => {
it('called after dom node mounting', async () => {
const [s1] = await exec(async () => {
type Log = {
id: number
key: string
value: string
}
const addLog = createEvent<{key: any; value: any}>()
const logs = createStore<Log[]>([]).on(addLog, (list, {key, value}) => [
...list,
{
id: list.length,
key: String(key),
value: String(value),
},
])
using(el, () => {
h('div', () => {
node(node => {
addLog({
key: 'is connected',
value: node.isConnected,
})
addLog({
key: 'has parent',
value: !!node.parentElement,
})
})
})
h('dl', () => {
list(
{source: logs, key: 'id', fields: ['key', 'value']},
({fields: [key, value]}) => {
h('dt', {text: key})
h('dd', {text: value})
},
)
})
})
await act()
})
expect(s1).toMatchInlineSnapshot(`
"
<div></div>
<dl>
<dt>is connected</dt>
<dd>true</dd>
<dt>has parent</dt>
<dd>true</dd>
</dl>
"
`)
})
})
it('support multiply text nodes', async () => {
const [s1, s2] = await exec(async () => {
const trigger = createEvent()
const foo = createStore('aaa').on(trigger, () => 'cccc')
const bar = createStore('bbb').on(trigger, () => 'dddd')
using(el, () => {
h('div', () => {
spec({text: foo})
spec({text: bar})
})
})
await act()
await act(() => {
trigger()
})
})
expect(s1).toMatchInlineSnapshot(`
"
<div>aaabbb</div>
"
`)
expect(s2).toMatchInlineSnapshot(`
"
<div>ccccdddd</div>
"
`)
})
describe('dom namespaces', () => {
test('svg support', async () => {
const [s1] = await exec(async () => {
using(el, () => {
h('div', () => {
h('svg', {
attr: {width: 500},
fn() {
h('g', {
attr: {transform: 'translate(5 10)'},
})
},
})
})
})
await act()
})
expect(s1).toMatchInlineSnapshot(`
"
<div>
<svg xmlns='http://www.w3.org/2000/svg' width='500'>
<g transform='translate(5 10)'></g>
</svg>
</div>
"
`)
})
test('foreignObject support', async () => {
const [s1] = await exec(async () => {
using(el, () => {
h('div', () => {
h('svg', {
attr: {width: 500},
fn() {
h('g', {
attr: {transform: 'translate(5 10)'},
fn() {
h('foreignObject', () => {
h('div', {
attr: {title: 'foreign child'},
fn() {
h('div', {
attr: {title: 'nested child'},
})
},
})
})
},
})
},
})
})
})
await act()
})
expect(s1).toMatchInlineSnapshot(`
"
<div>
<svg xmlns='http://www.w3.org/2000/svg' width='500'>
<g transform='translate(5 10)'>
<foreignObject
><div
xmlns='http://www.w3.org/1999/xhtml'
title='foreign child'
>
<div title='nested child'></div></div
></foreignObject>
</g>
</svg>
</div>
"
`)
})
})
test('hydrate', async () => {
const [s1, s2] = await exec(async () => {
const inc = createEvent()
const count = createStore(0).on(inc, x => x + 1)
const rootItem = createStore(null)
const Item = rec<any>({
fn() {
h('div', {
text: 'root',
})
},
})
const Tag = block({
fn() {
h('span', {
text: 'SPAN',
})
},
})
const App = block({
fn() {
Tag()
h('h1', {text: 'List'})
Item({store: rootItem})
h('p', {
text: ['count = ', count],
})
},
})
el.innerHTML = `
<span>SPAN</span>
<h1>List</h1>
<div>root</div>
<p>count = 0</p>
`
using(el, {
fn: App,
hydrate: true,
})
await act()
await act(async () => {
inc()
})
})
expect(s1).toMatchInlineSnapshot(`
"
<span>SPAN</span>
<h1>List</h1>
<div>root</div>
<p>count = 0</p>
"
`)
expect(s2).toMatchInlineSnapshot(`
"
<span>SPAN</span>
<h1>List</h1>
<div>root</div>
<p>count = 1</p>
"
`)
})
test('template match bug', async () => {
const [s1, s2] = await exec(async () => {
const initial = Array.from({length: 15}, (_, id) => ({
id: `id_${id}`,
data: (id * 1000).toString(36),
}))
const patch = createEvent<{id: string; data: string}>()
const $list = createStore(initial).on(patch, (list, {id, data}) => {
return list.map(item => {
if (item.id === id) return {id, data}
return item
})
})
using(el, () => {
h('ul', () => {
list($list, ({store}) => {
const click = createEvent<MouseEvent>()
sample({
source: store,
clock: click,
fn: ({id}) => ({id, data: 'PATCHED'}),
target: patch,
})
const [id, data] = remap(store, ['id', 'data'] as const)
h('li', {
attr: {id},
handler: {click},
fn() {
h('u', {text: data})
},
})
})
})
})
await act()
await act(async () => {
const li = el.querySelector('#id_0')! as HTMLElement
li.click()
})
})
expect(s1).toMatchInlineSnapshot(`
"
<ul>
<li id='id_0'><u>0</u></li>
<li id='id_1'><u>rs</u></li>
<li id='id_2'><u>1jk</u></li>
<li id='id_3'><u>2bc</u></li>
<li id='id_4'><u>334</u></li>
<li id='id_5'><u>3uw</u></li>
<li id='id_6'><u>4mo</u></li>
<li id='id_7'><u>5eg</u></li>
<li id='id_8'><u>668</u></li>
<li id='id_9'><u>6y0</u></li>
<li id='id_10'><u>7ps</u></li>
<li id='id_11'><u>8hk</u></li>
<li id='id_12'><u>99c</u></li>
<li id='id_13'><u>a14</u></li>
<li id='id_14'><u>asw</u></li>
</ul>
"
`)
expect(s2).toMatchInlineSnapshot(`
"
<ul>
<li id='id_0'><u>PATCHED</u></li>
<li id='id_1'><u>rs</u></li>
<li id='id_2'><u>1jk</u></li>
<li id='id_3'><u>2bc</u></li>
<li id='id_4'><u>334</u></li>
<li id='id_5'><u>3uw</u></li>
<li id='id_6'><u>4mo</u></li>
<li id='id_7'><u>5eg</u></li>
<li id='id_8'><u>668</u></li>
<li id='id_9'><u>6y0</u></li>
<li id='id_10'><u>7ps</u></li>
<li id='id_11'><u>8hk</u></li>
<li id='id_12'><u>99c</u></li>
<li id='id_13'><u>a14</u></li>
<li id='id_14'><u>asw</u></li>
</ul>
"
`)
})
describe('text``', () => {
it('support template literals', async () => {
const [s1] = await exec(async () => {
const name = createStore('alice')
const nbsp = '\u00A0'
using(el, () => {
h('span', () => {
text`username${nbsp}: ${name}`
})
})
await act()
})
expect(s1).toMatchInlineSnapshot(`
"
<span>username : alice</span>
"
`)
})
test('text(store) edge case', async () => {
const [s1] = await exec(async () => {
const name = createStore('alice')
using(el, () => {
h('span', () => {
//@ts-expect-error
text(name)
})
})
await act()
})
expect(s1).toMatchInlineSnapshot(`
"
<span>alice</span>
"
`)
})
test('text(string) edge case', async () => {
const [s1] = await exec(async () => {
using(el, () => {
h('span', () => {
//@ts-expect-error
text('alice')
})
})
await act()
})
expect(s1).toMatchInlineSnapshot(`
"
<span>alice</span>
"
`)
})
test('text(array) edge case', async () => {
const [s1] = await exec(async () => {
const name = createStore('alice')
using(el, () => {
h('span', () => {
//@ts-expect-error
text(['username: ', name])
})
})
await act()
})
expect(s1).toMatchInlineSnapshot(`
"
<span>username: alice</span>
"
`)
})
}) | the_stack |
import Avatar from '@material-ui/core/Avatar'
import Button from '@material-ui/core/Button'
import Divider from '@material-ui/core/Divider'
import List from '@material-ui/core/List'
import ListItem from '@material-ui/core/ListItem'
import ListItemAvatar from '@material-ui/core/ListItemAvatar'
import ListItemText from '@material-ui/core/ListItemText'
import SwipeableDrawer from '@material-ui/core/SwipeableDrawer'
import TextField from '@material-ui/core/TextField'
import { Add, ArrowLeft, Block, Delete, Edit, Forum, GroupAdd, SupervisorAccount } from '@material-ui/icons'
import { ChatService } from '@xrengine/client-core/src/social/state/ChatService'
import { useFriendState } from '@xrengine/client-core/src/social/state/FriendState'
import { FriendService } from '@xrengine/client-core/src/social/state/FriendService'
import { useGroupState } from '@xrengine/client-core/src/social/state/GroupState'
import { GroupService } from '@xrengine/client-core/src/social/state/GroupService'
import { InviteService } from '@xrengine/client-core/src/social/state/InviteService'
import { useLocationState } from '@xrengine/client-core/src/social/state/LocationState'
import { usePartyState } from '@xrengine/client-core/src/social/state/PartyState'
import { PartyService } from '@xrengine/client-core/src/social/state/PartyService'
import { useAuthState } from '@xrengine/client-core/src/user/state/AuthState'
import { UserService } from '@xrengine/client-core/src/user/state/UserService'
import { useUserState } from '@xrengine/client-core/src/user/state/UserState'
import { Group as GroupType } from '@xrengine/common/src/interfaces/Group'
import classNames from 'classnames'
import _ from 'lodash'
import React, { useEffect, useState } from 'react'
import { useDispatch } from '@xrengine/client-core/src/store'
import styles from './Left.module.scss'
import { GroupAction } from '@xrengine/client-core/src/social/state/GroupActions'
interface Props {
harmony?: boolean
setHarmonyOpen?: any
openBottomDrawer?: boolean
leftDrawerOpen: boolean
setLeftDrawerOpen: any
setRightDrawerOpen: any
authState?: any
setBottomDrawerOpen: any
detailsType?: string
setDetailsType?: any
groupFormMode?: string
setGroupFormMode?: any
groupFormOpen?: boolean
setGroupFormOpen?: any
groupForm?: any
setGroupForm?: any
selectedUser?: any
setSelectedUser?: any
selectedGroup?: any
setSelectedGroup?: any
}
const initialSelectedUserState = {
id: '',
name: '',
userRole: '',
identityProviders: [],
relationType: {},
inverseRelationType: {},
avatarUrl: ''
}
const initialGroupForm = {
id: '',
name: '',
groupUsers: [],
description: ''
}
const LeftDrawer = (props: Props): any => {
try {
const {
harmony,
setHarmonyOpen,
setLeftDrawerOpen,
leftDrawerOpen,
setRightDrawerOpen,
setBottomDrawerOpen,
detailsType,
setDetailsType,
groupFormMode,
setGroupFormMode,
groupFormOpen,
setGroupFormOpen,
groupForm,
setGroupForm,
selectedUser,
setSelectedUser,
selectedGroup,
setSelectedGroup
} = props
const dispatch = useDispatch()
const userState = useUserState()
const user = useAuthState().user
const friendState = useFriendState()
const friendSubState = friendState.friends
const groupState = useGroupState()
const groupSubState = groupState.groups
const partyState = usePartyState()
const party = partyState.party
const [tabIndex, setTabIndex] = useState(0)
const [friendDeletePending, setFriendDeletePending] = useState('')
const [groupDeletePending, setGroupDeletePending] = useState('')
const [groupUserDeletePending, setGroupUserDeletePending] = useState('')
const [partyDeletePending, setPartyDeletePending] = useState(false)
const [partyTransferOwnerPending, setPartyTransferOwnerPending] = useState('')
const [partyUserDeletePending, setPartyUserDeletePending] = useState('')
const [selectedAccordion, setSelectedAccordion] = useState('')
const [locationBanPending, setLocationBanPending] = useState('')
const selfGroupUser =
selectedGroup.id && selectedGroup.id.length > 0
? selectedGroup.groupUsers.find((groupUser) => groupUser.userId === user.id.value)
: {}
const partyUsers = party && party?.partyUsers && party?.partyUsers?.value ? party.partyUsers.value : []
const selfPartyUser =
party && party?.partyUsers?.value
? party?.partyUsers?.value?.find((partyUser) => partyUser.user.id === user.id.value)
: null
const currentLocation = useLocationState().currentLocation.location.value
useEffect(() => {
if (friendState.updateNeeded.value === true && friendState.getFriendsInProgress.value !== true) {
FriendService.getFriends('', 0)
}
/* if (selectedUser.id?.length > 0 && friendState.get('closeDetails') === selectedUser.id) {
closeDetails()
friendState.set('closeDetails', '')
}*/
}, [friendState.updateNeeded.value, friendState.getFriendsInProgress.value])
useEffect(() => {
if (groupState.updateNeeded.value === true && groupState.getGroupsInProgress.value !== true) {
GroupService.getGroups(0)
}
if (selectedGroup?.id.length > 0 && groupState.closeDetails.value === selectedGroup.id) {
closeDetails()
dispatch(GroupAction.removeCloseGroupDetail())
}
}, [groupState.updateNeeded.value, groupState.getGroupsInProgress.value])
useEffect(() => {
if (partyState.updateNeeded.value === true) {
PartyService.getParty()
}
}, [partyState.updateNeeded.value])
useEffect(() => {
if (user.instanceId.value != null && userState.layerUsersUpdateNeeded.value === true)
UserService.getLayerUsers(true)
if (user.channelInstanceId.value != null && userState.channelLayerUsersUpdateNeeded.value === true)
UserService.getLayerUsers(false)
}, [user, userState.layerUsersUpdateNeeded.value, userState.channelLayerUsersUpdateNeeded.value])
const showFriendDeleteConfirm = (e, friendId) => {
e.preventDefault()
setFriendDeletePending(friendId)
}
const cancelFriendDelete = (e) => {
e.preventDefault()
setFriendDeletePending('')
}
const confirmFriendDelete = (e, friendId) => {
e.preventDefault()
setFriendDeletePending('')
FriendService.unfriend(friendId)
closeDetails()
setLeftDrawerOpen(false)
}
const nextFriendsPage = (): void => {
if (friendSubState.skip.value + friendSubState.limit.value < friendSubState.total.value) {
FriendService.getFriends('', friendSubState.skip.value + friendSubState.limit.value)
}
}
const showGroupDeleteConfirm = (e, groupId) => {
e.preventDefault()
setGroupDeletePending(groupId)
}
const cancelGroupDelete = (e) => {
e.preventDefault()
setGroupDeletePending('')
}
const confirmGroupDelete = (e, groupId) => {
e.preventDefault()
setGroupDeletePending('')
GroupService.removeGroup(groupId)
setSelectedGroup(initialGroupForm)
setDetailsType('')
setLeftDrawerOpen(false)
}
/*
const showLocationBanConfirm = (e, userId) => {
e.preventDefault()
setLocationBanPending(userId)
}
const cancelLocationBan = (e) => {
e.preventDefault()
setLocationBanPending('')
}
const confirmLocationBan = (e, userId) => {
e.preventDefault()
console.log('Confirming location ban')
setLocationBanPending('')
LocationService.banUserFromLocation(userId, currentLocation.id)
} */
const nextGroupsPage = (): void => {
if (groupSubState.skip.value + groupSubState.limit.value < groupSubState.total.value) {
GroupService.getGroups(groupSubState.skip.value + groupSubState.limit.value)
}
}
const showGroupUserDeleteConfirm = (e, groupUserId) => {
e.preventDefault()
setGroupUserDeletePending(groupUserId)
}
const cancelGroupUserDelete = (e) => {
e.preventDefault()
setGroupUserDeletePending('')
}
const confirmGroupUserDelete = (e, groupUserId) => {
e.preventDefault()
const groupUser = _.find(selectedGroup.groupUsers, (groupUser) => groupUser.id === groupUserId)
setGroupUserDeletePending('')
GroupService.removeGroupUser(groupUserId)
if (groupUser.userId === user.id.value) {
setSelectedGroup(initialGroupForm)
setDetailsType('')
setLeftDrawerOpen(false)
}
}
const showPartyDeleteConfirm = (e) => {
e.preventDefault()
setPartyDeletePending(true)
}
const cancelPartyDelete = (e) => {
e.preventDefault()
setPartyDeletePending(false)
}
const confirmPartyDelete = (e, partyId) => {
e.preventDefault()
setPartyDeletePending(false)
PartyService.removeParty(partyId)
setLeftDrawerOpen(false)
}
const showPartyUserDeleteConfirm = (e, partyUserId) => {
e.preventDefault()
setPartyUserDeletePending(partyUserId)
}
const cancelPartyUserDelete = (e) => {
e.preventDefault()
setPartyUserDeletePending('')
}
const confirmPartyUserDelete = (e, partyUserId) => {
e.preventDefault()
const partyUser = _.find(partyUsers, (pUser) => pUser.id === partyUserId)
setPartyUserDeletePending('')
PartyService.removePartyUser(partyUserId)
if (partyUser && partyUser.user.id === user.id.value) setLeftDrawerOpen(false)
}
const showTransferPartyOwnerConfirm = (e, partyUserId) => {
e.preventDefault()
setPartyTransferOwnerPending(partyUserId)
}
const cancelTransferPartyOwner = (e) => {
e.preventDefault()
setPartyTransferOwnerPending('')
}
const confirmTransferPartyOwner = (e, partyUserId) => {
e.preventDefault()
setPartyTransferOwnerPending('')
PartyService.transferPartyOwner(partyUserId)
}
const handleChange = (event: any, newValue: number): void => {
event.preventDefault()
setTabIndex(newValue)
}
const openDetails = (type, object) => {
setDetailsType(type)
if (type === 'user') {
setSelectedUser(object)
} else if (type === 'group') {
setSelectedGroup(object)
}
}
const closeDetails = () => {
setLeftDrawerOpen(false)
setDetailsType('')
setSelectedUser(initialSelectedUserState)
setSelectedGroup(initialGroupForm)
}
const openGroupForm = (mode: string, group?: GroupType) => {
setGroupFormOpen(true)
setGroupFormMode(mode)
if (group != null) {
setGroupForm({
id: group.id,
name: group.name,
groupUsers: group.groupUsers,
description: group.description
})
}
}
const closeGroupForm = (): void => {
setLeftDrawerOpen(false)
setGroupFormOpen(false)
setGroupForm(initialGroupForm)
}
const handleGroupCreateInput = (e: any): void => {
const value = e.target.value
const form = Object.assign({}, groupForm)
form[e.target.name] = value
setGroupForm(form)
}
const submitGroup = (e: any): void => {
e.preventDefault()
const form = {
id: groupForm.id,
name: groupForm.name,
description: groupForm.description
}
if (groupFormMode === 'create') {
delete form.id
GroupService.createGroup(form)
} else {
GroupService.patchGroup(form)
}
setLeftDrawerOpen(false)
setGroupFormOpen(false)
setGroupForm(initialGroupForm)
}
const createNewParty = (): void => {
PartyService.createParty()
}
const onListScroll = (e): void => {
if (e.target.scrollHeight - e.target.scrollTop === e.target.clientHeight) {
if (tabIndex === 0) {
nextFriendsPage()
} else if (tabIndex === 1) {
nextGroupsPage()
}
}
}
const openInvite = (targetObjectType?: string, targetObjectId?: string): void => {
InviteService.updateInviteTarget(targetObjectType, targetObjectId)
setLeftDrawerOpen(false)
setRightDrawerOpen(true)
}
const openChat = (targetObjectType: string, targetObject: any): void => {
setLeftDrawerOpen(false)
if (harmony !== true) setBottomDrawerOpen(true)
// else if (harmony === true) setHarmonyOpen(true);
setTimeout(() => {
ChatService.updateChatTarget(targetObjectType, targetObject)
ChatService.updateMessageScrollInit(true)
}, 100)
}
const handleAccordionSelect = (accordionType: string) => (event: React.ChangeEvent<{}>, isExpanded: boolean) => {
if (accordionType === selectedAccordion) {
setSelectedAccordion('')
} else {
setSelectedAccordion(accordionType)
}
}
return (
<div>
<SwipeableDrawer
className={classNames({
[styles['flex-column']]: true,
[styles['left-drawer']]: true
})}
anchor="left"
open={leftDrawerOpen === true}
onClose={() => {
setLeftDrawerOpen(false)
}}
onOpen={() => {}}
>
{groupFormOpen === false && detailsType === 'user' && (
<div className={styles['details-container']}>
<div className={styles.header}>
<Button className={styles.backButton} onClick={closeDetails}>
<ArrowLeft />
</Button>
<Divider />
</div>
<div className={styles.details}>
<div
className={classNames({
[styles.avatarUrl]: true,
[styles['flex-center']]: true
})}
>
<Avatar src={selectedUser.avatarUrl} />
</div>
<div
className={classNames({
[styles.userName]: true,
[styles['flex-center']]: true
})}
>
<div>{selectedUser.name}</div>
</div>
<div
className={classNames({
[styles.userId]: true,
[styles['flex-center']]: true
})}
>
<div>ID: {selectedUser.id}</div>
</div>
<div
className={classNames({
'action-buttons': true,
[styles['flex-center']]: true,
[styles['flex-column']]: true
})}
>
<Button
variant="contained"
color="primary"
startIcon={<Forum />}
onClick={() => {
openChat('user', selectedUser)
}}
>
Chat
</Button>
<Button
variant="contained"
color="secondary"
startIcon={<GroupAdd />}
onClick={() => openInvite('user', selectedUser.id)}
>
Invite
</Button>
{friendDeletePending !== selectedUser.id && (
<Button
variant="contained"
className={styles['background-red']}
startIcon={<Delete />}
onClick={(e) => showFriendDeleteConfirm(e, selectedUser.id)}
>
Unfriend
</Button>
)}
{friendDeletePending === selectedUser.id && (
<div className={styles.deleteConfirm}>
<Button
variant="contained"
startIcon={<Delete />}
className={styles['background-red']}
onClick={(e) => confirmFriendDelete(e, selectedUser.id)}
>
Unfriend
</Button>
<Button variant="contained" color="secondary" onClick={(e) => cancelFriendDelete(e)}>
Cancel
</Button>
</div>
)}
</div>
</div>
</div>
)}
{groupFormOpen === false && detailsType === 'party' && (
<div className={styles['details-container']}>
<div className={styles.header}>
<Button className={styles.backButton} onClick={closeDetails}>
<ArrowLeft />
</Button>
<Divider />
</div>
{party?.value == null && (
<div>
<div className={styles.title}>You are not currently in a party</div>
<div className={styles['flex-center']}>
<Button variant="contained" color="primary" startIcon={<Add />} onClick={() => createNewParty()}>
Create Party
</Button>
</div>
</div>
)}
{party?.value != null && (
<div className={styles['list-container']}>
<div className={styles.title}>Current Party</div>
<div
className={classNames({
[styles['party-id']]: true,
[styles['flex-center']]: true
})}
>
<div>ID: {party?.id?.value}</div>
</div>
<div
className={classNames({
'action-buttons': true,
[styles['flex-center']]: true,
[styles['flex-column']]: true
})}
>
<Button
variant="contained"
color="primary"
startIcon={<Forum />}
onClick={() => openChat('party', party?.value)}
>
Chat
</Button>
{selfPartyUser?.isOwner === true && (
<Button
variant="contained"
color="secondary"
startIcon={<GroupAdd />}
onClick={() => openInvite('party', party?.id?.value)}
>
Invite
</Button>
)}
{partyDeletePending !== true && selfPartyUser?.isOwner === true && (
<Button
variant="contained"
className={styles['background-red']}
startIcon={<Delete />}
onClick={(e) => showPartyDeleteConfirm(e)}
>
Delete
</Button>
)}
{partyDeletePending === true && (
<div className={styles.deleteConfirm}>
<Button
variant="contained"
startIcon={<Delete />}
className={styles['background-red']}
onClick={(e) => confirmPartyDelete(e, party?.id?.value)}
>
Delete
</Button>
<Button variant="contained" color="secondary" onClick={(e) => cancelPartyDelete(e)}>
Cancel
</Button>
</div>
)}
</div>
<Divider />
<div
className={classNames({
[styles.title]: true,
[styles['margin-top']]: true
})}
>
Members
</div>
<List
className={classNames({
[styles['flex-center']]: true,
[styles['flex-column']]: true
})}
onScroll={(e) => onListScroll(e)}
>
{partyUsers &&
partyUsers.length > 0 &&
[...partyUsers]
.sort((a, b) => (a?.user?.name || '')?.localeCompare(b?.user?.name || ''))
.map((partyUser) => {
return (
<ListItem key={partyUser.id}>
<ListItemAvatar>
<Avatar src={partyUser.user.avatarUrl} />
</ListItemAvatar>
{user.id.value === partyUser.id && partyUser.isOwner === true && (
<ListItemText primary={partyUser.user.name + ' (you, owner)'} />
)}
{user.id.value === partyUser.id && partyUser.isOwner !== true && (
<ListItemText primary={partyUser.user.name + ' (you)'} />
)}
{user.id.value !== partyUser.id && partyUser.isOwner === true && (
<ListItemText primary={partyUser.user.name + ' (owner)'} />
)}
{user.id.value !== partyUser.id && partyUser.isOwner !== true && (
<ListItemText primary={partyUser.user.name} />
)}
{partyUserDeletePending !== partyUser.id &&
partyTransferOwnerPending !== partyUser.id &&
selfPartyUser?.isOwner === true &&
user.id.value !== partyUser.id && (
<Button
variant="contained"
className={styles.groupUserMakeOwnerInit}
color="primary"
onClick={(e) => showTransferPartyOwnerConfirm(e, partyUser.id)}
>
<SupervisorAccount />
</Button>
)}
{partyUserDeletePending !== partyUser.id && partyTransferOwnerPending === partyUser.id && (
<div className={styles.userConfirmButtons}>
<Button
variant="contained"
color="primary"
onClick={(e) => confirmTransferPartyOwner(e, partyUser.id)}
>
Make Owner
</Button>
<Button
variant="contained"
color="secondary"
onClick={(e) => cancelTransferPartyOwner(e)}
>
Cancel
</Button>
</div>
)}
{partyTransferOwnerPending !== partyUser.id &&
partyUserDeletePending !== partyUser.id &&
selfPartyUser?.isOwner === true &&
user.id.value !== partyUser.id && (
<Button
className={styles.groupUserDeleteInit}
onClick={(e) => showPartyUserDeleteConfirm(e, partyUser.id)}
>
<Delete />
</Button>
)}
{partyUserDeletePending !== partyUser.id && user.id.value === partyUser.id && (
<Button
className={styles.groupUserDeleteInit}
onClick={(e) => showPartyUserDeleteConfirm(e, partyUser.id)}
>
<Delete />
</Button>
)}
{partyTransferOwnerPending !== partyUser.id && partyUserDeletePending === partyUser.id && (
<div className={styles.userConfirmButtons}>
{user.id.value !== partyUser.id && (
<Button
variant="contained"
color="primary"
onClick={(e) => confirmPartyUserDelete(e, partyUser.id)}
>
Remove User
</Button>
)}
{user.id.value === partyUser.id && (
<Button
variant="contained"
color="primary"
onClick={(e) => confirmPartyUserDelete(e, partyUser.id)}
>
Leave party
</Button>
)}
<Button
variant="contained"
color="secondary"
onClick={(e) => cancelPartyUserDelete(e)}
>
Cancel
</Button>
</div>
)}
</ListItem>
)
})}
</List>
</div>
)}
</div>
)}
{groupFormOpen === false && detailsType === 'group' && (
<div className={styles['details-container']}>
<div className={styles.header}>
<Button className={styles.backButton} onClick={closeDetails}>
<ArrowLeft />
</Button>
<Divider />
</div>
<div
className={classNames({
[styles.details]: true,
[styles['list-container']]: true
})}
>
<div
className={classNames({
[styles.title]: true,
[styles['flex-center']]: true
})}
>
<div>{selectedGroup.name}</div>
</div>
<div
className={classNames({
'group-id': true,
[styles['flex-center']]: true
})}
>
<div>ID: {selectedGroup.id}</div>
</div>
<div
className={classNames({
[styles.description]: true,
[styles['flex-center']]: true
})}
>
<div>{selectedGroup.description}</div>
</div>
<div
className={classNames({
'action-buttons': true,
[styles['flex-center']]: true,
[styles['flex-column']]: true
})}
>
<Button
variant="contained"
color="primary"
startIcon={<Forum />}
onClick={() => {
openChat('group', selectedGroup)
}}
>
Chat
</Button>
{selfGroupUser != null && selfGroupUser.groupUserRank === 'owner' && (
<Button
variant="contained"
startIcon={<Edit />}
onClick={() => openGroupForm('update', selectedGroup)}
>
Edit
</Button>
)}
{selfGroupUser != null &&
(selfGroupUser.groupUserRank === 'owner' || selfGroupUser.groupUserRank === 'admin') && (
<Button
variant="contained"
color="secondary"
startIcon={<GroupAdd />}
onClick={() => openInvite('group', selectedGroup.id)}
>
Invite
</Button>
)}
{groupDeletePending !== selectedGroup.id &&
selfGroupUser != null &&
selfGroupUser.groupUserRank === 'owner' && (
<Button
variant="contained"
className={styles['background-red']}
startIcon={<Delete />}
onClick={(e) => showGroupDeleteConfirm(e, selectedGroup.id)}
>
Delete
</Button>
)}
{groupDeletePending === selectedGroup.id && (
<div className={styles.deleteConfirm}>
<Button
variant="contained"
startIcon={<Delete />}
className={styles['background-red']}
onClick={(e) => confirmGroupDelete(e, selectedGroup.id)}
>
Delete
</Button>
<Button variant="contained" color="secondary" onClick={(e) => cancelGroupDelete(e)}>
Cancel
</Button>
</div>
)}
</div>
<Divider />
<div
className={classNames({
[styles.title]: true,
[styles['margin-top']]: true
})}
>
Members
</div>
<List
className={classNames({
[styles['flex-center']]: true,
[styles['flex-column']]: true
})}
>
{selectedGroup &&
selectedGroup.groupUsers &&
selectedGroup.groupUsers.length > 0 &&
selectedGroup.groupUsers
.sort((a, b) => a.name - b.name)
.map((groupUser) => {
return (
<ListItem key={groupUser.id}>
<ListItemAvatar>
<Avatar src={groupUser.user.avatarUrl} />
</ListItemAvatar>
{user.id.value === groupUser.userId && (
<ListItemText
className={styles.marginRight5px}
primary={groupUser.user.name + ' (you)'}
/>
)}
{user.id.value !== groupUser.userId && (
<ListItemText className={styles.marginRight5px} primary={groupUser.user.name} />
)}
{groupUserDeletePending !== groupUser.id &&
selfGroupUser != null &&
(selfGroupUser.groupUserRank === 'owner' || selfGroupUser.groupUserRank === 'admin') &&
user.id.value !== groupUser.userId && (
<Button
className={styles.groupUserDeleteInit}
onClick={(e) => showGroupUserDeleteConfirm(e, groupUser.id)}
>
<Delete />
</Button>
)}
{groupUserDeletePending !== groupUser.id && user.id.value === groupUser.userId && (
<Button
className={styles.groupUserDeleteInit}
onClick={(e) => showGroupUserDeleteConfirm(e, groupUser.id)}
>
<Delete />
</Button>
)}
{groupUserDeletePending === groupUser.id && (
<div className={styles.groupUserDeleteConfirm}>
{user.id.value !== groupUser.userId && (
<Button
variant="contained"
color="primary"
onClick={(e) => confirmGroupUserDelete(e, groupUser.id)}
>
<Delete />
</Button>
)}
{user.id.value === groupUser.userId && (
<Button
variant="contained"
color="primary"
onClick={(e) => confirmGroupUserDelete(e, groupUser.id)}
>
<Delete />
</Button>
)}
<Button variant="contained" color="secondary" onClick={(e) => cancelGroupUserDelete(e)}>
<Block />
</Button>
</div>
)}
</ListItem>
)
})}
</List>
</div>
</div>
)}
{groupFormOpen === true && (
<form className={styles['group-form']} noValidate onSubmit={(e) => submitGroup(e)}>
{groupFormMode === 'create' && <div className={styles.title}>New Group</div>}
{groupFormMode === 'update' && <div className={styles.title}>Update Group</div>}
<TextField
variant="outlined"
margin="normal"
required
fullWidth
id="name"
label="Group Name"
name="name"
autoComplete="name"
autoFocus
value={groupForm.name}
onChange={(e) => handleGroupCreateInput(e)}
/>
<TextField
variant="outlined"
margin="normal"
required
fullWidth
id="description"
label="Group Description"
name="description"
autoComplete="description"
autoFocus
value={groupForm.description}
onChange={(e) => handleGroupCreateInput(e)}
/>
<div
className={classNames({
[styles['flex-center']]: true,
[styles['flex-column']]: true
})}
>
<Button type="submit" variant="contained" color="primary" className={styles.submit}>
{groupFormMode === 'create' && 'Create Group'}
{groupFormMode === 'update' && 'Update Group'}
</Button>
<Button variant="contained" color="secondary" onClick={() => closeGroupForm()}>
Cancel
</Button>
</div>
</form>
)}
</SwipeableDrawer>
</div>
)
} catch (err) {
console.log('LeftDrawer error:')
console.log(err)
}
}
export default LeftDrawer | the_stack |
import { PagedAsyncIterableIterator } from "@azure/core-paging";
import * as coreHttp from "@azure/core-http";
import * as Mappers from "../models/mappers";
import * as Parameters from "../models/parameters";
import { PhoneNumbersClientContext } from "../phoneNumbersClientContext";
import { LROPoller, shouldDeserializeLRO } from "../lro";
import {
PurchasedPhoneNumber,
PhoneNumbersListPhoneNumbersNextOptionalParams,
PhoneNumbersListPhoneNumbersOptionalParams,
PhoneNumberType,
PhoneNumberAssignmentType,
PhoneNumberCapabilities,
PhoneNumbersSearchAvailablePhoneNumbersOptionalParams,
PhoneNumbersSearchAvailablePhoneNumbersResponse,
PhoneNumbersGetSearchResultResponse,
PhoneNumbersPurchasePhoneNumbersOptionalParams,
PhoneNumbersPurchasePhoneNumbersResponse,
PhoneNumbersGetOperationResponse,
PhoneNumbersUpdateCapabilitiesOptionalParams,
PhoneNumbersUpdateCapabilitiesResponse,
PhoneNumbersGetByNumberResponse,
PhoneNumbersReleasePhoneNumberResponse,
PhoneNumbersListPhoneNumbersResponse,
PhoneNumbersListPhoneNumbersNextResponse
} from "../models";
/** Class representing a PhoneNumbers. */
export class PhoneNumbers {
private readonly client: PhoneNumbersClientContext;
/**
* Initialize a new instance of the class PhoneNumbers class.
* @param client Reference to the service client
*/
constructor(client: PhoneNumbersClientContext) {
this.client = client;
}
/**
* Gets the list of all purchased phone numbers.
* @param options The options parameters.
*/
public listPhoneNumbers(
options?: PhoneNumbersListPhoneNumbersOptionalParams
): PagedAsyncIterableIterator<PurchasedPhoneNumber> {
const iter = this.listPhoneNumbersPagingAll(options);
return {
next() {
return iter.next();
},
[Symbol.asyncIterator]() {
return this;
},
byPage: () => {
return this.listPhoneNumbersPagingPage(options);
}
};
}
private async *listPhoneNumbersPagingPage(
options?: PhoneNumbersListPhoneNumbersOptionalParams
): AsyncIterableIterator<PurchasedPhoneNumber[]> {
let result = await this._listPhoneNumbers(options);
yield result.phoneNumbers || [];
let continuationToken = result.nextLink;
while (continuationToken) {
result = await this._listPhoneNumbersNext(continuationToken, options);
continuationToken = result.nextLink;
yield result.phoneNumbers || [];
}
}
private async *listPhoneNumbersPagingAll(
options?: PhoneNumbersListPhoneNumbersOptionalParams
): AsyncIterableIterator<PurchasedPhoneNumber> {
for await (const page of this.listPhoneNumbersPagingPage(options)) {
yield* page;
}
}
/**
* Search for available phone numbers to purchase.
* @param countryCode The ISO 3166-2 country code, e.g. US.
* @param phoneNumberType The type of phone numbers to search for, e.g. geographic, or tollFree.
* @param assignmentType The assignment type of the phone numbers to search for. A phone number can be
* assigned to a person, or to an application.
* @param capabilities Capabilities of a phone number.
* @param options The options parameters.
*/
async searchAvailablePhoneNumbers(
countryCode: string,
phoneNumberType: PhoneNumberType,
assignmentType: PhoneNumberAssignmentType,
capabilities: PhoneNumberCapabilities,
options?: PhoneNumbersSearchAvailablePhoneNumbersOptionalParams
): Promise<LROPoller<PhoneNumbersSearchAvailablePhoneNumbersResponse>> {
const operationArguments: coreHttp.OperationArguments = {
countryCode,
phoneNumberType,
assignmentType,
capabilities,
options: this.getOperationOptions(options, "location")
};
const sendOperation = (
args: coreHttp.OperationArguments,
spec: coreHttp.OperationSpec
) => {
return this.client.sendOperationRequest(args, spec) as Promise<
PhoneNumbersSearchAvailablePhoneNumbersResponse
>;
};
const initialOperationResult = await sendOperation(
operationArguments,
searchAvailablePhoneNumbersOperationSpec
);
return new LROPoller({
initialOperationArguments: operationArguments,
initialOperationSpec: searchAvailablePhoneNumbersOperationSpec,
initialOperationResult,
sendOperation,
finalStateVia: "location"
});
}
/**
* Gets a phone number search result by search id.
* @param searchId The search Id.
* @param options The options parameters.
*/
getSearchResult(
searchId: string,
options?: coreHttp.OperationOptions
): Promise<PhoneNumbersGetSearchResultResponse> {
const operationArguments: coreHttp.OperationArguments = {
searchId,
options: coreHttp.operationOptionsToRequestOptionsBase(options || {})
};
return this.client.sendOperationRequest(
operationArguments,
getSearchResultOperationSpec
) as Promise<PhoneNumbersGetSearchResultResponse>;
}
/**
* Purchases phone numbers.
* @param options The options parameters.
*/
async purchasePhoneNumbers(
options?: PhoneNumbersPurchasePhoneNumbersOptionalParams
): Promise<LROPoller<PhoneNumbersPurchasePhoneNumbersResponse>> {
const operationArguments: coreHttp.OperationArguments = {
options: this.getOperationOptions(options, "undefined")
};
const sendOperation = (
args: coreHttp.OperationArguments,
spec: coreHttp.OperationSpec
) => {
return this.client.sendOperationRequest(args, spec) as Promise<
PhoneNumbersPurchasePhoneNumbersResponse
>;
};
const initialOperationResult = await sendOperation(
operationArguments,
purchasePhoneNumbersOperationSpec
);
return new LROPoller({
initialOperationArguments: operationArguments,
initialOperationSpec: purchasePhoneNumbersOperationSpec,
initialOperationResult,
sendOperation
});
}
/**
* Gets an operation by its id.
* @param operationId The id of the operation
* @param options The options parameters.
*/
getOperation(
operationId: string,
options?: coreHttp.OperationOptions
): Promise<PhoneNumbersGetOperationResponse> {
const operationArguments: coreHttp.OperationArguments = {
operationId,
options: coreHttp.operationOptionsToRequestOptionsBase(options || {})
};
return this.client.sendOperationRequest(
operationArguments,
getOperationOperationSpec
) as Promise<PhoneNumbersGetOperationResponse>;
}
/**
* Cancels an operation by its id.
* @param operationId The id of the operation
* @param options The options parameters.
*/
cancelOperation(
operationId: string,
options?: coreHttp.OperationOptions
): Promise<coreHttp.RestResponse> {
const operationArguments: coreHttp.OperationArguments = {
operationId,
options: coreHttp.operationOptionsToRequestOptionsBase(options || {})
};
return this.client.sendOperationRequest(
operationArguments,
cancelOperationOperationSpec
) as Promise<coreHttp.RestResponse>;
}
/**
* Updates the capabilities of a phone number.
* @param phoneNumber The phone number id in E.164 format. The leading plus can be either + or encoded
* as %2B, e.g. +11234567890.
* @param options The options parameters.
*/
async updateCapabilities(
phoneNumber: string,
options?: PhoneNumbersUpdateCapabilitiesOptionalParams
): Promise<LROPoller<PhoneNumbersUpdateCapabilitiesResponse>> {
const operationArguments: coreHttp.OperationArguments = {
phoneNumber,
options: this.getOperationOptions(options, "location")
};
const sendOperation = (
args: coreHttp.OperationArguments,
spec: coreHttp.OperationSpec
) => {
return this.client.sendOperationRequest(args, spec) as Promise<
PhoneNumbersUpdateCapabilitiesResponse
>;
};
const initialOperationResult = await sendOperation(
operationArguments,
updateCapabilitiesOperationSpec
);
return new LROPoller({
initialOperationArguments: operationArguments,
initialOperationSpec: updateCapabilitiesOperationSpec,
initialOperationResult,
sendOperation,
finalStateVia: "location"
});
}
/**
* Gets the details of the given purchased phone number.
* @param phoneNumber The purchased phone number whose details are to be fetched in E.164 format, e.g.
* +11234567890.
* @param options The options parameters.
*/
getByNumber(
phoneNumber: string,
options?: coreHttp.OperationOptions
): Promise<PhoneNumbersGetByNumberResponse> {
const operationArguments: coreHttp.OperationArguments = {
phoneNumber,
options: coreHttp.operationOptionsToRequestOptionsBase(options || {})
};
return this.client.sendOperationRequest(
operationArguments,
getByNumberOperationSpec
) as Promise<PhoneNumbersGetByNumberResponse>;
}
/**
* Releases a purchased phone number.
* @param phoneNumber Phone number to be released, e.g. +11234567890.
* @param options The options parameters.
*/
async releasePhoneNumber(
phoneNumber: string,
options?: coreHttp.OperationOptions
): Promise<LROPoller<PhoneNumbersReleasePhoneNumberResponse>> {
const operationArguments: coreHttp.OperationArguments = {
phoneNumber,
options: this.getOperationOptions(options, "undefined")
};
const sendOperation = (
args: coreHttp.OperationArguments,
spec: coreHttp.OperationSpec
) => {
return this.client.sendOperationRequest(args, spec) as Promise<
PhoneNumbersReleasePhoneNumberResponse
>;
};
const initialOperationResult = await sendOperation(
operationArguments,
releasePhoneNumberOperationSpec
);
return new LROPoller({
initialOperationArguments: operationArguments,
initialOperationSpec: releasePhoneNumberOperationSpec,
initialOperationResult,
sendOperation
});
}
/**
* Gets the list of all purchased phone numbers.
* @param options The options parameters.
*/
private _listPhoneNumbers(
options?: PhoneNumbersListPhoneNumbersOptionalParams
): Promise<PhoneNumbersListPhoneNumbersResponse> {
const operationArguments: coreHttp.OperationArguments = {
options: coreHttp.operationOptionsToRequestOptionsBase(options || {})
};
return this.client.sendOperationRequest(
operationArguments,
listPhoneNumbersOperationSpec
) as Promise<PhoneNumbersListPhoneNumbersResponse>;
}
/**
* ListPhoneNumbersNext
* @param nextLink The nextLink from the previous successful call to the ListPhoneNumbers method.
* @param options The options parameters.
*/
private _listPhoneNumbersNext(
nextLink: string,
options?: PhoneNumbersListPhoneNumbersNextOptionalParams
): Promise<PhoneNumbersListPhoneNumbersNextResponse> {
const operationArguments: coreHttp.OperationArguments = {
nextLink,
options: coreHttp.operationOptionsToRequestOptionsBase(options || {})
};
return this.client.sendOperationRequest(
operationArguments,
listPhoneNumbersNextOperationSpec
) as Promise<PhoneNumbersListPhoneNumbersNextResponse>;
}
private getOperationOptions<TOptions extends coreHttp.OperationOptions>(
options: TOptions | undefined,
finalStateVia?: string
): coreHttp.RequestOptionsBase {
const operationOptions: coreHttp.OperationOptions = options || {};
operationOptions.requestOptions = {
...operationOptions.requestOptions,
shouldDeserialize: shouldDeserializeLRO(finalStateVia)
};
return coreHttp.operationOptionsToRequestOptionsBase(operationOptions);
}
}
// Operation Specifications
const serializer = new coreHttp.Serializer(Mappers, /* isXml */ false);
const searchAvailablePhoneNumbersOperationSpec: coreHttp.OperationSpec = {
path: "/availablePhoneNumbers/countries/{countryCode}/:search",
httpMethod: "POST",
responses: {
200: {
bodyMapper: Mappers.PhoneNumberSearchResult,
headersMapper: Mappers.PhoneNumbersSearchAvailablePhoneNumbersHeaders
},
201: {
bodyMapper: Mappers.PhoneNumberSearchResult,
headersMapper: Mappers.PhoneNumbersSearchAvailablePhoneNumbersHeaders
},
202: {
bodyMapper: Mappers.PhoneNumberSearchResult,
headersMapper: Mappers.PhoneNumbersSearchAvailablePhoneNumbersHeaders
},
204: {
bodyMapper: Mappers.PhoneNumberSearchResult,
headersMapper: Mappers.PhoneNumbersSearchAvailablePhoneNumbersHeaders
},
default: {
bodyMapper: Mappers.CommunicationErrorResponse
}
},
requestBody: {
parameterPath: {
phoneNumberType: ["phoneNumberType"],
assignmentType: ["assignmentType"],
capabilities: ["capabilities"],
areaCode: ["options", "areaCode"],
quantity: ["options", "quantity"]
},
mapper: { ...Mappers.PhoneNumberSearchRequest, required: true }
},
queryParameters: [Parameters.apiVersion],
urlParameters: [Parameters.endpoint, Parameters.countryCode],
headerParameters: [Parameters.contentType, Parameters.accept],
mediaType: "json",
serializer
};
const getSearchResultOperationSpec: coreHttp.OperationSpec = {
path: "/availablePhoneNumbers/searchResults/{searchId}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.PhoneNumberSearchResult
},
default: {
bodyMapper: Mappers.CommunicationErrorResponse
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [Parameters.endpoint, Parameters.searchId],
headerParameters: [Parameters.accept],
serializer
};
const purchasePhoneNumbersOperationSpec: coreHttp.OperationSpec = {
path: "/availablePhoneNumbers/:purchase",
httpMethod: "POST",
responses: {
200: {
headersMapper: Mappers.PhoneNumbersPurchasePhoneNumbersHeaders
},
201: {
headersMapper: Mappers.PhoneNumbersPurchasePhoneNumbersHeaders
},
202: {
headersMapper: Mappers.PhoneNumbersPurchasePhoneNumbersHeaders
},
204: {
headersMapper: Mappers.PhoneNumbersPurchasePhoneNumbersHeaders
},
default: {
bodyMapper: Mappers.CommunicationErrorResponse
}
},
requestBody: {
parameterPath: { searchId: ["options", "searchId"] },
mapper: { ...Mappers.PhoneNumberPurchaseRequest, required: true }
},
queryParameters: [Parameters.apiVersion],
urlParameters: [Parameters.endpoint],
headerParameters: [Parameters.contentType, Parameters.accept],
mediaType: "json",
serializer
};
const getOperationOperationSpec: coreHttp.OperationSpec = {
path: "/phoneNumbers/operations/{operationId}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.PhoneNumberOperation,
headersMapper: Mappers.PhoneNumbersGetOperationHeaders
},
default: {
bodyMapper: Mappers.CommunicationErrorResponse
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [Parameters.endpoint, Parameters.operationId],
headerParameters: [Parameters.accept],
serializer
};
const cancelOperationOperationSpec: coreHttp.OperationSpec = {
path: "/phoneNumbers/operations/{operationId}",
httpMethod: "DELETE",
responses: {
204: {},
default: {
bodyMapper: Mappers.CommunicationErrorResponse
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [Parameters.endpoint, Parameters.operationId],
headerParameters: [Parameters.accept],
serializer
};
const updateCapabilitiesOperationSpec: coreHttp.OperationSpec = {
path: "/phoneNumbers/{phoneNumber}/capabilities",
httpMethod: "PATCH",
responses: {
200: {
bodyMapper: Mappers.PurchasedPhoneNumber,
headersMapper: Mappers.PhoneNumbersUpdateCapabilitiesHeaders
},
201: {
bodyMapper: Mappers.PurchasedPhoneNumber,
headersMapper: Mappers.PhoneNumbersUpdateCapabilitiesHeaders
},
202: {
bodyMapper: Mappers.PurchasedPhoneNumber,
headersMapper: Mappers.PhoneNumbersUpdateCapabilitiesHeaders
},
204: {
bodyMapper: Mappers.PurchasedPhoneNumber,
headersMapper: Mappers.PhoneNumbersUpdateCapabilitiesHeaders
},
default: {
bodyMapper: Mappers.CommunicationErrorResponse
}
},
requestBody: {
parameterPath: { calling: ["options", "calling"], sms: ["options", "sms"] },
mapper: Mappers.PhoneNumberCapabilitiesRequest
},
queryParameters: [Parameters.apiVersion],
urlParameters: [Parameters.endpoint, Parameters.phoneNumber],
headerParameters: [Parameters.accept, Parameters.contentType1],
mediaType: "json",
serializer
};
const getByNumberOperationSpec: coreHttp.OperationSpec = {
path: "/phoneNumbers/{phoneNumber}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.PurchasedPhoneNumber
},
default: {
bodyMapper: Mappers.CommunicationErrorResponse
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [Parameters.endpoint, Parameters.phoneNumber],
headerParameters: [Parameters.accept],
serializer
};
const releasePhoneNumberOperationSpec: coreHttp.OperationSpec = {
path: "/phoneNumbers/{phoneNumber}",
httpMethod: "DELETE",
responses: {
200: {
headersMapper: Mappers.PhoneNumbersReleasePhoneNumberHeaders
},
201: {
headersMapper: Mappers.PhoneNumbersReleasePhoneNumberHeaders
},
202: {
headersMapper: Mappers.PhoneNumbersReleasePhoneNumberHeaders
},
204: {
headersMapper: Mappers.PhoneNumbersReleasePhoneNumberHeaders
},
default: {
bodyMapper: Mappers.CommunicationErrorResponse
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [Parameters.endpoint, Parameters.phoneNumber],
headerParameters: [Parameters.accept],
serializer
};
const listPhoneNumbersOperationSpec: coreHttp.OperationSpec = {
path: "/phoneNumbers",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.PurchasedPhoneNumbers
},
default: {
bodyMapper: Mappers.CommunicationErrorResponse
}
},
queryParameters: [Parameters.apiVersion, Parameters.skip, Parameters.top],
urlParameters: [Parameters.endpoint],
headerParameters: [Parameters.accept],
serializer
};
const listPhoneNumbersNextOperationSpec: coreHttp.OperationSpec = {
path: "{nextLink}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.PurchasedPhoneNumbers
},
default: {
bodyMapper: Mappers.CommunicationErrorResponse
}
},
queryParameters: [Parameters.apiVersion, Parameters.skip, Parameters.top],
urlParameters: [Parameters.endpoint, Parameters.nextLink],
headerParameters: [Parameters.accept],
serializer
}; | the_stack |
import * as pulumi from "@pulumi/pulumi";
import { input as inputs, output as outputs } from "../types";
import * as utilities from "../utilities";
/**
* A managed metastore service that serves metadata queries.
*
* ## Example Usage
* ### Dataproc Metastore Service Basic
*
* ```typescript
* import * as pulumi from "@pulumi/pulumi";
* import * as gcp from "@pulumi/gcp";
*
* const _default = new gcp.dataproc.MetastoreService("default", {
* serviceId: "metastore-srv",
* location: "us-central1",
* port: 9080,
* tier: "DEVELOPER",
* maintenanceWindow: {
* hourOfDay: 2,
* dayOfWeek: "SUNDAY",
* },
* hiveMetastoreConfig: {
* version: "2.3.6",
* },
* }, {
* provider: google_beta,
* });
* ```
*
* ## Import
*
* Service can be imported using any of these accepted formats
*
* ```sh
* $ pulumi import gcp:dataproc/metastoreService:MetastoreService default projects/{{project}}/locations/{{location}}/services/{{service_id}}
* ```
*
* ```sh
* $ pulumi import gcp:dataproc/metastoreService:MetastoreService default {{project}}/{{location}}/{{service_id}}
* ```
*
* ```sh
* $ pulumi import gcp:dataproc/metastoreService:MetastoreService default {{location}}/{{service_id}}
* ```
*/
export class MetastoreService extends pulumi.CustomResource {
/**
* Get an existing MetastoreService resource's state with the given name, ID, and optional extra
* properties used to qualify the lookup.
*
* @param name The _unique_ name of the resulting resource.
* @param id The _unique_ provider ID of the resource to lookup.
* @param state Any extra arguments used during the lookup.
* @param opts Optional settings to control the behavior of the CustomResource.
*/
public static get(name: string, id: pulumi.Input<pulumi.ID>, state?: MetastoreServiceState, opts?: pulumi.CustomResourceOptions): MetastoreService {
return new MetastoreService(name, <any>state, { ...opts, id: id });
}
/** @internal */
public static readonly __pulumiType = 'gcp:dataproc/metastoreService:MetastoreService';
/**
* Returns true if the given object is an instance of MetastoreService. This is designed to work even
* when multiple copies of the Pulumi SDK have been loaded into the same process.
*/
public static isInstance(obj: any): obj is MetastoreService {
if (obj === undefined || obj === null) {
return false;
}
return obj['__pulumiType'] === MetastoreService.__pulumiType;
}
/**
* A Cloud Storage URI (starting with gs://) that specifies where artifacts related to the metastore service are stored.
*/
public /*out*/ readonly artifactGcsUri!: pulumi.Output<string>;
/**
* The URI of the endpoint used to access the metastore service.
*/
public /*out*/ readonly endpointUri!: pulumi.Output<string>;
/**
* Configuration information specific to running Hive metastore software as the metastore service.
* Structure is documented below.
*/
public readonly hiveMetastoreConfig!: pulumi.Output<outputs.dataproc.MetastoreServiceHiveMetastoreConfig | undefined>;
/**
* User-defined labels for the metastore service.
*/
public readonly labels!: pulumi.Output<{[key: string]: string} | undefined>;
/**
* The location where the autoscaling policy should reside.
* The default value is `global`.
*/
public readonly location!: pulumi.Output<string | undefined>;
/**
* The one hour maintenance window of the metastore service.
* This specifies when the service can be restarted for maintenance purposes in UTC time.
* Structure is documented below.
*/
public readonly maintenanceWindow!: pulumi.Output<outputs.dataproc.MetastoreServiceMaintenanceWindow | undefined>;
/**
* The relative resource name of the metastore service.
*/
public /*out*/ readonly name!: pulumi.Output<string>;
/**
* The relative resource name of the VPC network on which the instance can be accessed. It is specified in the following form:
* "projects/{projectNumber}/global/networks/{network_id}".
*/
public readonly network!: pulumi.Output<string>;
/**
* The TCP port at which the metastore service is reached. Default: 9083.
*/
public readonly port!: pulumi.Output<number>;
/**
* The ID of the project in which the resource belongs.
* If it is not provided, the provider project is used.
*/
public readonly project!: pulumi.Output<string>;
/**
* The ID of the metastore service. The id must contain only letters (a-z, A-Z), numbers (0-9), underscores (_),
* and hyphens (-). Cannot begin or end with underscore or hyphen. Must consist of between
* 3 and 63 characters.
*/
public readonly serviceId!: pulumi.Output<string>;
/**
* The current state of the metastore service.
*/
public /*out*/ readonly state!: pulumi.Output<string>;
/**
* Additional information about the current state of the metastore service, if available.
*/
public /*out*/ readonly stateMessage!: pulumi.Output<string>;
/**
* The tier of the service.
* Possible values are `DEVELOPER` and `ENTERPRISE`.
*/
public readonly tier!: pulumi.Output<string>;
/**
* Create a MetastoreService resource with the given unique name, arguments, and options.
*
* @param name The _unique_ name of the resource.
* @param args The arguments to use to populate this resource's properties.
* @param opts A bag of options that control this resource's behavior.
*/
constructor(name: string, args: MetastoreServiceArgs, opts?: pulumi.CustomResourceOptions)
constructor(name: string, argsOrState?: MetastoreServiceArgs | MetastoreServiceState, opts?: pulumi.CustomResourceOptions) {
let inputs: pulumi.Inputs = {};
opts = opts || {};
if (opts.id) {
const state = argsOrState as MetastoreServiceState | undefined;
inputs["artifactGcsUri"] = state ? state.artifactGcsUri : undefined;
inputs["endpointUri"] = state ? state.endpointUri : undefined;
inputs["hiveMetastoreConfig"] = state ? state.hiveMetastoreConfig : undefined;
inputs["labels"] = state ? state.labels : undefined;
inputs["location"] = state ? state.location : undefined;
inputs["maintenanceWindow"] = state ? state.maintenanceWindow : undefined;
inputs["name"] = state ? state.name : undefined;
inputs["network"] = state ? state.network : undefined;
inputs["port"] = state ? state.port : undefined;
inputs["project"] = state ? state.project : undefined;
inputs["serviceId"] = state ? state.serviceId : undefined;
inputs["state"] = state ? state.state : undefined;
inputs["stateMessage"] = state ? state.stateMessage : undefined;
inputs["tier"] = state ? state.tier : undefined;
} else {
const args = argsOrState as MetastoreServiceArgs | undefined;
if ((!args || args.serviceId === undefined) && !opts.urn) {
throw new Error("Missing required property 'serviceId'");
}
inputs["hiveMetastoreConfig"] = args ? args.hiveMetastoreConfig : undefined;
inputs["labels"] = args ? args.labels : undefined;
inputs["location"] = args ? args.location : undefined;
inputs["maintenanceWindow"] = args ? args.maintenanceWindow : undefined;
inputs["network"] = args ? args.network : undefined;
inputs["port"] = args ? args.port : undefined;
inputs["project"] = args ? args.project : undefined;
inputs["serviceId"] = args ? args.serviceId : undefined;
inputs["tier"] = args ? args.tier : undefined;
inputs["artifactGcsUri"] = undefined /*out*/;
inputs["endpointUri"] = undefined /*out*/;
inputs["name"] = undefined /*out*/;
inputs["state"] = undefined /*out*/;
inputs["stateMessage"] = undefined /*out*/;
}
if (!opts.version) {
opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()});
}
super(MetastoreService.__pulumiType, name, inputs, opts);
}
}
/**
* Input properties used for looking up and filtering MetastoreService resources.
*/
export interface MetastoreServiceState {
/**
* A Cloud Storage URI (starting with gs://) that specifies where artifacts related to the metastore service are stored.
*/
artifactGcsUri?: pulumi.Input<string>;
/**
* The URI of the endpoint used to access the metastore service.
*/
endpointUri?: pulumi.Input<string>;
/**
* Configuration information specific to running Hive metastore software as the metastore service.
* Structure is documented below.
*/
hiveMetastoreConfig?: pulumi.Input<inputs.dataproc.MetastoreServiceHiveMetastoreConfig>;
/**
* User-defined labels for the metastore service.
*/
labels?: pulumi.Input<{[key: string]: pulumi.Input<string>}>;
/**
* The location where the autoscaling policy should reside.
* The default value is `global`.
*/
location?: pulumi.Input<string>;
/**
* The one hour maintenance window of the metastore service.
* This specifies when the service can be restarted for maintenance purposes in UTC time.
* Structure is documented below.
*/
maintenanceWindow?: pulumi.Input<inputs.dataproc.MetastoreServiceMaintenanceWindow>;
/**
* The relative resource name of the metastore service.
*/
name?: pulumi.Input<string>;
/**
* The relative resource name of the VPC network on which the instance can be accessed. It is specified in the following form:
* "projects/{projectNumber}/global/networks/{network_id}".
*/
network?: pulumi.Input<string>;
/**
* The TCP port at which the metastore service is reached. Default: 9083.
*/
port?: pulumi.Input<number>;
/**
* The ID of the project in which the resource belongs.
* If it is not provided, the provider project is used.
*/
project?: pulumi.Input<string>;
/**
* The ID of the metastore service. The id must contain only letters (a-z, A-Z), numbers (0-9), underscores (_),
* and hyphens (-). Cannot begin or end with underscore or hyphen. Must consist of between
* 3 and 63 characters.
*/
serviceId?: pulumi.Input<string>;
/**
* The current state of the metastore service.
*/
state?: pulumi.Input<string>;
/**
* Additional information about the current state of the metastore service, if available.
*/
stateMessage?: pulumi.Input<string>;
/**
* The tier of the service.
* Possible values are `DEVELOPER` and `ENTERPRISE`.
*/
tier?: pulumi.Input<string>;
}
/**
* The set of arguments for constructing a MetastoreService resource.
*/
export interface MetastoreServiceArgs {
/**
* Configuration information specific to running Hive metastore software as the metastore service.
* Structure is documented below.
*/
hiveMetastoreConfig?: pulumi.Input<inputs.dataproc.MetastoreServiceHiveMetastoreConfig>;
/**
* User-defined labels for the metastore service.
*/
labels?: pulumi.Input<{[key: string]: pulumi.Input<string>}>;
/**
* The location where the autoscaling policy should reside.
* The default value is `global`.
*/
location?: pulumi.Input<string>;
/**
* The one hour maintenance window of the metastore service.
* This specifies when the service can be restarted for maintenance purposes in UTC time.
* Structure is documented below.
*/
maintenanceWindow?: pulumi.Input<inputs.dataproc.MetastoreServiceMaintenanceWindow>;
/**
* The relative resource name of the VPC network on which the instance can be accessed. It is specified in the following form:
* "projects/{projectNumber}/global/networks/{network_id}".
*/
network?: pulumi.Input<string>;
/**
* The TCP port at which the metastore service is reached. Default: 9083.
*/
port?: pulumi.Input<number>;
/**
* The ID of the project in which the resource belongs.
* If it is not provided, the provider project is used.
*/
project?: pulumi.Input<string>;
/**
* The ID of the metastore service. The id must contain only letters (a-z, A-Z), numbers (0-9), underscores (_),
* and hyphens (-). Cannot begin or end with underscore or hyphen. Must consist of between
* 3 and 63 characters.
*/
serviceId: pulumi.Input<string>;
/**
* The tier of the service.
* Possible values are `DEVELOPER` and `ENTERPRISE`.
*/
tier?: pulumi.Input<string>;
} | the_stack |
import { useTheme } from '@pluralsight/ps-design-system-theme'
import {
ValueOf,
isString,
useMatchMedia,
classNames
} from '@pluralsight/ps-design-system-util'
import React from 'react'
import ConditionalWrap from './conditional-wrap'
import '../css/index.css'
import { toPercentageString } from '../js/index'
import Shave from './shave'
import * as vars from '../vars/index'
const formatImageWidth = (
image: unknown,
size?: ValueOf<typeof vars.sizes>
): string => {
return image && size !== vars.sizes.small
? `(${vars.style.overlaysWidth} + ${vars.style.overlaysMarginRight})`
: `0px`
}
const formatActionBarWidth = (actionBar: unknown): string => {
return Array.isArray(actionBar) && actionBar.length > 1
? `(${actionBar.length} * ${vars.style.actionBarActionWidth} + ${actionBar.length} * ${vars.style.actionBarActionMarginLeft})`
: '0px'
}
type MetadataNode =
| string
| React.ReactElement<typeof Text>
| React.ReactElement<typeof TextLink>
// NOTE: the `title` prop clashes with a native html attr so we're exclude
// it from being mistakenly used in any child component
interface RowProps
extends Omit<
React.DetailedHTMLProps<
React.HTMLAttributes<HTMLDivElement>,
HTMLDivElement
>,
'title'
> {
actionBar?: React.ReactNode[] // <Button size="small" appearance="secondary" />
actionBarVisible?: boolean
fullOverlay?: React.ReactNode | React.ReactElement<typeof FullOverlayLink>
fullOverlayVisible?: boolean
image?:
| React.ReactElement<typeof Image>
| React.ReactElement<typeof ImageLink>
metadata1?: MetadataNode[]
metadata2?: MetadataNode[]
progress?: number
size?: ValueOf<typeof vars.sizes>
title?:
| string
| React.ReactElement<typeof Text>
| React.ReactElement<typeof TextLink>
titleTruncated?: boolean
}
interface RowStatics {
FullOverlayLink: typeof FullOverlayLink
Image: typeof Image
ImageLink: typeof ImageLink
Text: typeof Text
TextLink: typeof TextLink
sizes: typeof vars.sizes
}
const Row: React.FC<RowProps> & RowStatics = props => {
const themeName = useTheme()
const {
actionBar,
actionBarVisible = false,
fullOverlay,
fullOverlayVisible = false,
image,
metadata1,
metadata2,
progress,
size: initialSize,
title,
titleTruncated,
className,
...rest
} = props
const isDesktop = useMatchMedia('screen and (min-width: 769px)')
const size = initialSize || (isDesktop ? vars.sizes.medium : vars.sizes.small)
return (
<div
className={classNames(className, 'psds-row', `psds-theme--${themeName}`)}
{...rest}
>
{renderOverlays({
fullOverlay,
fullOverlayVisible,
image,
progress,
size
})}
<Words image={image} size={size} actionBar={actionBar}>
<Title size={size} truncated={titleTruncated}>
{title}
</Title>
{renderMetaData(metadata1, { size })}
{renderMetaData(metadata2, { size })}
</Words>
{renderActionBar({ actionBar, actionBarVisible, fullOverlay })}
</div>
)
}
const renderActionBar = (
props: Pick<RowProps, 'actionBar' | 'actionBarVisible' | 'fullOverlay'>
) => {
const { actionBar } = props
if (!Array.isArray(actionBar) || actionBar.length === 0) return null
return (
<ActionBar
actionBarVisible={props.actionBarVisible}
fullOverlay={props.fullOverlay}
>
{actionBar}
</ActionBar>
)
}
const renderOverlays = (
props: Pick<
RowProps,
'fullOverlay' | 'fullOverlayVisible' | 'image' | 'progress' | 'size'
>
) => {
if (!props.image || props.size === vars.sizes.small) return null
return (
<Overlays>
{renderImage(props)}
<FullOverlayFocusManager
fullOverlayVisible={props.fullOverlayVisible}
fullOverlay={props.fullOverlay}
/>
{renderProgress({ progress: props.progress })}
</Overlays>
)
}
const renderImage = (props: Pick<RowProps, 'image'>) => {
return props.image || null
}
const renderMetaData = (
metadata: MetadataNode[] | undefined,
props: Required<Pick<RowProps, 'size'>>
) => {
if (!metadata) return null
return (
<Metadata size={props.size}>
{metadata.map((datum, i) => {
const hasNext = i < metadata.length - 1
return [
<MetadataDatum key={`datum${i}`}>{datum}</MetadataDatum>,
hasNext && <MetadataDot key={`dot${i}`} />
]
})}
</Metadata>
)
}
const renderProgress = (props: Pick<RowProps, 'progress'>) => {
if (!props.progress) return null
return (
<Progress>
<ProgressBar progress={props.progress} />
</Progress>
)
}
interface ActionBarProps
extends Pick<RowProps, 'actionBarVisible' | 'fullOverlay'> {}
const ActionBar: React.FC<ActionBarProps> = props => {
const { actionBarVisible, fullOverlay, ...rest } = props
return (
<div
className={classNames(
'psds-row__action-bar',
!!fullOverlay && 'psds-row__action-bar--fullOverlay',
actionBarVisible && 'psds-row__action-bar--actionBarVisible'
)}
{...rest}
/>
)
}
interface FullOverlayFocusManagerProps
extends Pick<RowProps, 'fullOverlay' | 'fullOverlayVisible'> {}
const FullOverlayFocusManager: React.FC<FullOverlayFocusManagerProps> =
props => {
const { fullOverlayVisible, fullOverlay } = props
const [isFocused, setFocused] = React.useState(false)
const handleFocus: React.FocusEventHandler<HTMLDivElement> = () => {
setFocused(true)
}
const handleBlur: React.FocusEventHandler<HTMLDivElement> = () => {
setFocused(false)
}
if (!React.isValidElement(fullOverlay)) return null
return (
<FullOverlay
isFocused={isFocused}
fullOverlayVisible={fullOverlayVisible}
>
{React.cloneElement(fullOverlay, {
onFocus: handleFocus,
onBlur: handleBlur
})}
</FullOverlay>
)
}
interface FullOverlayProps
extends React.HTMLAttributes<HTMLDivElement>,
Pick<RowProps, 'fullOverlayVisible'> {
isFocused: boolean
}
const FullOverlay: React.FC<FullOverlayProps> = props => {
const { fullOverlayVisible, isFocused, className, ...rest } = props
return (
<div
className={classNames(
className,
'psds-row__full-overlay',
isFocused && 'psds-row__full-overlay--isFocused',
fullOverlayVisible && 'psds-row__full-overlay--fullOverlayVisible'
)}
{...rest}
/>
)
}
interface FullOverlayLinkProps extends React.HTMLAttributes<HTMLSpanElement> {}
const FullOverlayLink: React.FC<FullOverlayLinkProps> = ({
className,
...props
}) => {
return (
<span
className={classNames(className, 'psds-row__full-overlay-link')}
{...props}
/>
)
}
FullOverlayLink.displayName = 'Row.FullOverlayLink'
interface ImageProps extends React.HTMLAttributes<HTMLDivElement> {
src: string
}
const Image: React.FC<ImageProps> = props => {
const { src, className, style, ...rest } = props
return (
<div
className={classNames(className, 'psds-row__image')}
style={{ ...style, backgroundImage: `url(${src})` }}
{...rest}
/>
)
}
Image.displayName = 'Row.Image'
interface ImageLinkProps extends React.HTMLAttributes<HTMLSpanElement> {}
const ImageLink: React.FC<ImageLinkProps> = ({ className, ...props }) => {
return (
<span
className={classNames('psds-row__image-link', className)}
{...props}
/>
)
}
ImageLink.displayName = 'Row.ImageLink'
interface MetadataProps
extends React.HTMLAttributes<HTMLDivElement>,
Required<Pick<RowProps, 'size'>> {}
const Metadata: React.FC<MetadataProps> = props => {
const { size, className, ...rest } = props
const themeName = useTheme()
return (
<div
className={classNames(
className,
'psds-row__metadata',
`psds-row__metadatapsds-theme--${themeName}`,
`psds-row__metadata--size-${size}`
)}
{...rest}
/>
)
}
interface MetadataDatumProps extends React.HTMLAttributes<HTMLSpanElement> {}
const MetadataDatum: React.FC<MetadataDatumProps> = ({
className,
...props
}) => {
return (
<span
className={classNames(className, 'psds-row__metadata__datum')}
{...props}
/>
)
}
interface MetadataDotProps extends React.HTMLAttributes<HTMLSpanElement> {}
const MetadataDot: React.FC<MetadataDotProps> = ({ className, ...props }) => {
return (
<span
className={classNames(className, 'psds-row__metadata__dot')}
{...props}
aria-hidden
>
·
</span>
)
}
interface OverlaysProps extends React.HTMLAttributes<HTMLDivElement> {}
const Overlays: React.FC<OverlaysProps> = ({ className, ...props }) => {
return (
<div className={classNames(className, 'psds-row__overlays')} {...props} />
)
}
interface ProgressProps extends React.HTMLAttributes<HTMLDivElement> {}
const Progress: React.FC<ProgressProps> = ({ className, ...props }) => {
return (
<div className={classNames(className, 'psds-row__progress')} {...props} />
)
}
interface ProgressBarProps
extends React.HTMLAttributes<HTMLDivElement>,
Required<Pick<RowProps, 'progress'>> {}
const ProgressBar: React.FC<ProgressBarProps> = props => {
const { progress = 0, style, className, ...rest } = props
const percent = toPercentageString(progress)
const complete = percent === '100%'
return (
<div
className={classNames(
className,
'psds-row__progress__bar',
complete && 'psds-row__progress__bar--complete'
)}
style={{ ...style, width: percent }}
{...rest}
role="progressbar"
aria-valuemin={0}
aria-valuemax={100}
aria-valuenow={progress}
aria-label={`${percent} complete`}
/>
)
}
interface TextProps extends React.HTMLAttributes<HTMLSpanElement> {}
const Text: React.FC<TextProps> = props => <span {...props} />
Text.displayName = 'Row.Text'
interface TextLinkProps extends React.HTMLAttributes<HTMLSpanElement> {
children: React.ReactElement<'a'>
truncated?: boolean
}
const TextLink: React.FC<TextLinkProps> = props => {
const { children, truncated = false, className, ...rest } = props
const themeName = useTheme()
const anchor = React.Children.only(children)
const anchorText = anchor.props.children
const shouldWrap = truncated && isString(anchorText)
const shaveWrap = (child: React.ReactNode) => {
if (!isString(child)) return null
return <Shave lines={2}>{child}</Shave>
}
return (
<span
className={classNames(
className,
'psds-row__text-link',
`psds-row__text-link psds-theme--${themeName}`
)}
{...rest}
>
<a {...anchor.props}>
<ConditionalWrap shouldWrap={shouldWrap} wrapper={shaveWrap}>
{anchorText}
</ConditionalWrap>
</a>
</span>
)
}
TextLink.displayName = 'Row.TextLink'
interface TitleProps
extends React.HTMLAttributes<HTMLDivElement>,
Required<Pick<RowProps, 'size'>> {
truncated?: boolean
}
const Title: React.FC<TitleProps> = props => {
const { children, size, truncated = false, className, ...rest } = props
const themeName = useTheme()
const wrapAsLink = (child: React.ReactNode) => {
if (!React.isValidElement(child)) return null
return React.cloneElement(child, { truncated })
}
const wrapWithShave = (child: React.ReactNode) => {
return (
<ConditionalWrap shouldWrap={truncated} wrapper={shaveWrap}>
{child}
</ConditionalWrap>
)
}
const shaveWrap = (child: React.ReactNode) => {
if (!isString(child)) return null
return <Shave lines={2}>{child}</Shave>
}
return (
<div
className={classNames(
className,
'psds-row__title',
`psds-row__title--size-${size}`,
`psds-row__title psds-theme--${themeName}`
)}
{...rest}
>
{isString(children) ? wrapWithShave(children) : wrapAsLink(children)}
</div>
)
}
interface WordsProps
extends Pick<RowProps, 'actionBar' | 'image' | 'size'>,
React.HTMLAttributes<HTMLDivElement> {}
const Words: React.FC<WordsProps> = props => {
const { actionBar, image, size, className, style, ...rest } = props
const imgWidth = formatImageWidth(image, size)
const actionBarWidth = formatActionBarWidth(actionBar)
return (
<div
className={classNames(className, 'psds-row__words')}
style={{
...style,
maxWidth: `calc(100% - ${imgWidth} - ${actionBarWidth})`
}}
{...rest}
/>
)
}
Row.FullOverlayLink = FullOverlayLink
Row.Image = Image
Row.ImageLink = ImageLink
Row.Text = Text
Row.TextLink = TextLink
Row.sizes = vars.sizes
export const sizes = Row.sizes
export default Row | the_stack |
import PropTypes from "prop-types";
import * as React from "react";
import { routerShape } from "react-router";
import { Trans } from "@lingui/macro";
import { i18nMark } from "@lingui/react";
import { Icon } from "@dcos/ui-kit";
import { ProductIcons } from "@dcos/ui-kit/dist/packages/icons/dist/product-icons-enum";
import { iconSizeS } from "@dcos/ui-kit/dist/packages/design-tokens/build/js/designTokens";
import { DataLayerType } from "@extension-kid/data-layer";
import { NotificationServiceType } from "@extension-kid/notification-service";
import {
ToastNotification,
ToastAppearance,
} from "@extension-kid/toast-notifications";
import gql from "graphql-tag";
import { map } from "rxjs/operators";
import { DCOS_CHANGE } from "#SRC/js/constants/EventTypes";
import RouterUtil from "#SRC/js/utils/RouterUtil";
import AppDispatcher from "#SRC/js/events/AppDispatcher";
import ContainerUtil from "#SRC/js/utils/ContainerUtil";
import DCOSStore from "#SRC/js/stores/DCOSStore";
import DSLExpression from "#SRC/js/structs/DSLExpression";
import Loader from "#SRC/js/components/Loader";
import Page from "#SRC/js/components/Page";
import RequestErrorMsg from "#SRC/js/components/RequestErrorMsg";
import {
REQUEST_COSMOS_PACKAGE_UNINSTALL_SUCCESS,
REQUEST_COSMOS_PACKAGE_UNINSTALL_ERROR,
} from "#SRC/js/constants/ActionTypes";
import container from "#SRC/js/container";
import { TYPES } from "#SRC/js/types/containerTypes";
import ActionKeys from "../../constants/ActionKeys";
import MarathonActions from "../../events/MarathonActions";
import ServiceActions from "../../events/ServiceActions";
import Pod from "../../structs/Pod";
import PodDetail from "../pod-detail/PodDetail";
import Service from "../../structs/Service";
import { ServiceActionItem } from "../../constants/ServiceActionItem";
import ServiceAttributeHasVolumesFilter from "../../filters/ServiceAttributeHasVolumesFilter";
import ServiceAttributeHealthFilter from "../../filters/ServiceAttributeHealthFilter";
import ServiceAttributeIsFilter from "../../filters/ServiceAttributeIsFilter";
import ServiceAttributeIsPodFilter from "../../filters/ServiceAttributeIsPodFilter";
import ServiceAttributeIsCatalogFilter from "../../filters/ServiceAttributeIsCatalogFilter";
import ServiceAttributeNoHealthchecksFilter from "../../filters/ServiceAttributeNoHealthchecksFilter";
import ServiceBreadcrumbs from "../../components/ServiceBreadcrumbs";
import ServiceDetail from "../service-detail/ServiceDetail";
import ServiceItemNotFound from "../../components/ServiceItemNotFound";
import ServiceModals from "../../components/modals/ServiceModals";
import ServiceNameTextFilter from "../../filters/ServiceNameTextFilter";
import ServiceTree from "../../structs/ServiceTree";
import ServiceTreeView from "./ServiceTreeView";
import ServicesQuotaView from "./ServicesQuotaView";
import {
REQUEST_MARATHON_DEPLOYMENT_ROLLBACK_ERROR,
REQUEST_MARATHON_DEPLOYMENT_ROLLBACK_SUCCESS,
REQUEST_MARATHON_GROUP_CREATE_ERROR,
REQUEST_MARATHON_GROUP_CREATE_SUCCESS,
REQUEST_MARATHON_GROUP_DELETE_ERROR,
REQUEST_MARATHON_GROUP_DELETE_SUCCESS,
REQUEST_MARATHON_GROUP_EDIT_ERROR,
REQUEST_MARATHON_GROUP_EDIT_SUCCESS,
REQUEST_MARATHON_SERVICE_DELETE_ERROR,
REQUEST_MARATHON_SERVICE_DELETE_SUCCESS,
REQUEST_MARATHON_SERVICE_EDIT_ERROR,
REQUEST_MARATHON_SERVICE_EDIT_SUCCESS,
REQUEST_MARATHON_SERVICE_RESET_DELAY_ERROR,
REQUEST_MARATHON_SERVICE_RESET_DELAY_SUCCESS,
REQUEST_MARATHON_SERVICE_RESTART_ERROR,
REQUEST_MARATHON_SERVICE_RESTART_SUCCESS,
} from "../../constants/ActionTypes";
import {
MARATHON_DEPLOYMENTS_CHANGE,
MARATHON_DEPLOYMENTS_ERROR,
MARATHON_GROUPS_CHANGE,
MARATHON_GROUPS_ERROR,
MARATHON_QUEUE_CHANGE,
MARATHON_QUEUE_ERROR,
MARATHON_SERVICE_VERSIONS_CHANGE,
MARATHON_SERVICE_VERSIONS_ERROR,
} from "../../constants/EventTypes";
const SERVICE_FILTERS = [
new ServiceAttributeHealthFilter(),
new ServiceAttributeHasVolumesFilter(),
new ServiceAttributeIsFilter(),
new ServiceAttributeIsPodFilter(),
new ServiceAttributeIsCatalogFilter(),
new ServiceAttributeNoHealthchecksFilter(),
new ServiceNameTextFilter(),
];
const dl = container.get(DataLayerType);
const notificationService = container.get(NotificationServiceType);
function i18nTranslate(id, values) {
const i18n = container.get(TYPES.I18n);
if (i18n) {
return i18n._(id, values);
}
return id;
}
/**
* Increments error count for each fetch type when we have a request error and
* resets to zero when fetch was successful for type
* @param {Object} fetchErrors
* @param {Object} action
* @return {Object} updated fetch errors
*/
function countFetchErrors(fetchErrors, action) {
switch (action.type) {
case MARATHON_DEPLOYMENTS_ERROR:
case MARATHON_GROUPS_ERROR:
case MARATHON_QUEUE_ERROR:
case MARATHON_SERVICE_VERSIONS_ERROR:
fetchErrors[action.type] = (fetchErrors[action.type] || 0) + 1;
return fetchErrors;
case MARATHON_DEPLOYMENTS_CHANGE:
case MARATHON_GROUPS_CHANGE:
case MARATHON_QUEUE_CHANGE:
case MARATHON_SERVICE_VERSIONS_CHANGE:
fetchErrors[action.type] = 0;
return fetchErrors;
default:
return false;
}
}
function getMesosRoles$() {
return dl
.query(
gql`
query {
roles
}
`,
{}
)
.pipe(map((result) => result.data.roles));
}
class ServicesContainer extends React.Component {
static propTypes = {
params: PropTypes.object.isRequired,
location: PropTypes.object.isRequired,
};
state = {
actionErrors: {},
fetchErrors: {},
filterExpression: new DSLExpression(),
isLoading: true,
lastUpdate: 0,
pendingActions: {},
roles: [],
};
componentDidMount() {
// This is so we get notified when the serviceTree is ready in DCOSStore. Making this a promise would be nice.
DCOSStore.addChangeListener(DCOS_CHANGE, this.onStoreChange);
DCOSStore.on(DCOS_CHANGE, () => {
if (this.state.isLoading) {
this.forceUpdate();
}
});
this.onStoreChange();
// Listen for server actions so we can update state immediately
// on the completion of an API request.
this.dispatcher = AppDispatcher.register(this.handleServerAction);
const roles$ = getMesosRoles$();
if (roles$) {
this.rolesSub = roles$.subscribe((roles) => {
this.setState({ roles });
});
}
}
UNSAFE_componentWillMount() {
this.propsToState(this.props);
}
UNSAFE_componentWillReceiveProps(nextProps) {
this.propsToState(nextProps);
}
componentWillUnmount() {
AppDispatcher.unregister(this.dispatcher);
DCOSStore.removeChangeListener(DCOS_CHANGE, this.onStoreChange);
if (this.rolesSub) {
this.rolesSub.unsubscribe();
}
}
getChildContext() {
return {
modalHandlers: this.getModalHandlers(),
};
}
propsToState(props) {
const itemId = decodeURIComponent(props.params.id || "/");
const filterQuery = props.location.query.q || "";
this.setState({
filterExpression: new DSLExpression(filterQuery),
itemId,
});
}
onStoreChange = () => {
// Throttle updates from DCOSStore
if (
Date.now() - this.state.lastUpdate > 1000 ||
(DCOSStore.serviceDataReceived && this.state.isLoading)
) {
this.setState({
isLoading: !DCOSStore.serviceDataReceived,
lastUpdate: Date.now(),
});
}
};
revertDeployment = (...args) => {
this.setPendingAction(ActionKeys.REVERT_DEPLOYMENT);
return MarathonActions.revertDeployment(...args);
};
createGroup = (...args) => {
this.setPendingAction(ActionKeys.GROUP_CREATE);
return MarathonActions.createGroup(...args);
};
deleteGroup = (...args) => {
this.setPendingAction(ActionKeys.GROUP_DELETE);
return ServiceActions.deleteGroup(...args);
};
editGroup = (...args) => {
this.setPendingAction(ActionKeys.GROUP_EDIT);
return MarathonActions.editGroup(...args);
};
deleteService = (...args) => {
this.setPendingAction(ActionKeys.SERVICE_DELETE);
return ServiceActions.deleteService(...args);
};
editService = (...args) => {
this.setPendingAction(ActionKeys.SERVICE_EDIT);
return MarathonActions.editService(...args);
};
restartService = (...args) => {
this.setPendingAction(ActionKeys.SERVICE_RESTART);
return MarathonActions.restartService(...args);
};
resetDelayedService = (...args) => {
this.setPendingAction(ActionKeys.SERVICE_RESET_DELAY);
return MarathonActions.resetDelayedService(...args);
};
handleServerAction = (payload) => {
const { action } = payload;
// Increment/clear fetching errors based on action
const fetchErrors = countFetchErrors(
{
...this.state.fetchErrors,
},
action
);
// Only set state if fetchErrors changed
if (fetchErrors) {
this.setState({ fetchErrors });
}
switch (action.type) {
case REQUEST_MARATHON_DEPLOYMENT_ROLLBACK_ERROR:
this.unsetPendingAction(ActionKeys.REVERT_DEPLOYMENT, action.data);
break;
case REQUEST_MARATHON_DEPLOYMENT_ROLLBACK_SUCCESS:
this.unsetPendingAction(ActionKeys.REVERT_DEPLOYMENT);
break;
case REQUEST_MARATHON_GROUP_CREATE_ERROR:
this.unsetPendingAction(ActionKeys.GROUP_CREATE, action.data);
break;
case REQUEST_MARATHON_GROUP_CREATE_SUCCESS:
this.unsetPendingAction(ActionKeys.GROUP_CREATE);
break;
case REQUEST_MARATHON_GROUP_DELETE_ERROR:
this.unsetPendingAction(ActionKeys.GROUP_DELETE, action.data);
break;
case REQUEST_MARATHON_GROUP_DELETE_SUCCESS:
this.unsetPendingAction(ActionKeys.GROUP_DELETE);
break;
case REQUEST_MARATHON_GROUP_EDIT_ERROR:
this.unsetPendingAction(ActionKeys.GROUP_EDIT, action.data);
break;
case REQUEST_MARATHON_GROUP_EDIT_SUCCESS:
this.unsetPendingAction(ActionKeys.GROUP_EDIT);
break;
case REQUEST_MARATHON_SERVICE_DELETE_ERROR:
this.unsetPendingAction(ActionKeys.SERVICE_DELETE, action.data);
break;
case REQUEST_MARATHON_SERVICE_DELETE_SUCCESS:
this.unsetPendingAction(ActionKeys.SERVICE_DELETE);
break;
case REQUEST_MARATHON_SERVICE_EDIT_ERROR:
this.unsetPendingAction(ActionKeys.SERVICE_EDIT, action.data);
break;
case REQUEST_MARATHON_SERVICE_EDIT_SUCCESS:
this.unsetPendingAction(ActionKeys.SERVICE_EDIT);
break;
case REQUEST_MARATHON_SERVICE_RESTART_ERROR:
this.unsetPendingAction(ActionKeys.SERVICE_RESTART, action.data);
break;
case REQUEST_MARATHON_SERVICE_RESTART_SUCCESS:
this.unsetPendingAction(ActionKeys.SERVICE_RESTART);
break;
case REQUEST_MARATHON_SERVICE_RESET_DELAY_ERROR:
notificationService.push(
this.getResetDelayErrorToast(action.serviceName)
);
this.unsetPendingAction(ActionKeys.SERVICE_RESET_DELAY, action.data);
break;
case REQUEST_MARATHON_SERVICE_RESET_DELAY_SUCCESS:
notificationService.push(
this.getResetDelaySuccessToast(action.serviceName)
);
this.unsetPendingAction(ActionKeys.SERVICE_RESET_DELAY);
break;
case REQUEST_COSMOS_PACKAGE_UNINSTALL_SUCCESS:
this.unsetPendingAction(ActionKeys.SERVICE_DELETE);
break;
case REQUEST_COSMOS_PACKAGE_UNINSTALL_ERROR:
this.unsetPendingAction(ActionKeys.SERVICE_DELETE, action.data);
break;
}
};
handleModalClose = (key) => {
if (key) {
this.clearActionError(key);
}
this.setState({ modal: {} });
};
handleFilterExpressionChange = (filterExpression) => {
const { router } = this.context;
const {
location: { pathname },
} = this.props;
router.push({ pathname, query: { q: filterExpression.value } });
this.setState({ filterExpression });
};
/**
* Sets the actionType to pending in state which will in turn be pushed
* to children components as a prop. Also clears any existing error for
* the actionType
* @param {String} actionType
*/
setPendingAction(actionType) {
const { actionErrors, pendingActions } = this.state;
this.setState({
actionErrors: ContainerUtil.adjustActionErrors(
actionErrors,
actionType,
null
),
pendingActions: ContainerUtil.adjustPendingActions(
pendingActions,
actionType,
true
),
});
}
/**
* Sets the pending actionType to false in state which will in turn be
* pushed down to children via props. Can optional set an error for the
* actionType
* @param {String} actionType
* @param {Any} error
*/
unsetPendingAction(actionType, error = null) {
const { actionErrors, pendingActions } = this.state;
this.setState({
actionErrors: ContainerUtil.adjustActionErrors(
actionErrors,
actionType,
error
),
pendingActions: ContainerUtil.adjustPendingActions(
pendingActions,
actionType,
false
),
});
}
clearActionError = (actionType) => {
const { actionErrors } = this.state;
this.setState({
actionErrors: ContainerUtil.adjustActionErrors(
actionErrors,
actionType,
null
),
});
};
getModalHandlers() {
const set = (id, props) => {
// Set props to be passed into modal
this.setState({
modal: {
...props,
id,
},
});
};
return {
createGroup: () => set(ServiceActionItem.CREATE_GROUP),
openServiceUI(props) {
window.open(props.service.getWebURL(), "_blank");
},
// All methods below (except resetDelayedService) work on ServiceTree and Service types
deleteService: (props) => set(ServiceActionItem.DELETE, props),
editService: (props) => set(ServiceActionItem.EDIT, props),
resetDelayedService: (props) =>
set(ServiceActionItem.RESET_DELAYED, props),
restartService: (props) => set(ServiceActionItem.RESTART, props),
resumeService: (props) => set(ServiceActionItem.RESUME, props),
scaleService: (props) => set(ServiceActionItem.SCALE, props),
stopService: (props) => set(ServiceActionItem.STOP, props),
};
}
getActions() {
return {
revertDeployment: this.revertDeployment,
createGroup: this.createGroup,
deleteGroup: this.deleteGroup,
editGroup: this.editGroup,
deleteService: this.deleteService,
editService: this.editService,
resetDelayedService: this.resetDelayedService,
restartService: this.restartService,
};
}
/**
* This function validates the current modalProps and returns
* them validated/corrected
*
* This function updates the `service` information from DCOSStore -
* if possible - or deletes the modal `id` from the object - if
* necessary (effectivly closes the modal, when the respective
* service got deleted)
*
* Depending on the current state `modalProps` need to contain either:
*
* - service and id ({ service: Service, id: String })
* when the modal `id` is open or should be opened.
* when opening the modal, `modalProps.service` is not yet set,
* so we have to set it.
*
* - only a service ({ service: Service })
* when no modal is open or the current modal is to be closed
* reson is, that even if no modal is open, they are rendered into
* the dom and need a valid service
*
* @param {object} props - an object which contains id and a service ("modalProps")
* @param {ServiceTree} [service] - service information
* @returns {object} updated and cleaned up modal information (props)
*/
getCorrectedModalProps(props, service) {
const modalProps = {
...props,
};
if (!modalProps.service && service) {
modalProps.service = service;
}
if (
modalProps.service &&
DCOSStore.serviceTree.findItemById(modalProps.service.id)
) {
modalProps.service = DCOSStore.serviceTree.findItemById(
modalProps.service.id
);
} else if (modalProps.id) {
delete modalProps.id;
}
return modalProps;
}
getModals(service) {
return (
<ServiceModals
actions={this.getActions()}
actionErrors={this.state.actionErrors}
clearError={this.clearActionError}
onClose={this.handleModalClose}
pendingActions={this.state.pendingActions}
modalProps={this.getCorrectedModalProps(this.state.modal, service)}
/>
);
}
getEmptyPage(itemType) {
const { itemId } = this.state;
return (
<Page>
<Page.Header breadcrumbs={<ServiceBreadcrumbs />} />
<ServiceItemNotFound
message={
<Trans render="span">
The {itemType} with the ID of "{itemId}" could not be found.
</Trans>
}
/>
</Page>
);
}
getPodDetail(item) {
const { children, params, routes } = this.props;
return (
<PodDetail
actions={this.getActions()}
params={params}
pod={item}
routes={routes}
>
{children}
{this.getModals(item)}
</PodDetail>
);
}
getServiceDetail(item) {
const { children, params, routes } = this.props;
return (
<ServiceDetail
actions={this.getActions()}
errors={this.state.actionErrors}
clearError={this.clearActionError}
params={params}
routes={routes}
service={item}
>
{children}
{this.getModals(item)}
</ServiceDetail>
);
}
getServiceTree = (item) => {
const { children, params, routes } = this.props;
const { filterExpression, roles } = this.state;
const isEmpty = item.getItems().length === 0;
let filteredServices = item;
if (filterExpression.defined) {
filteredServices = filterExpression.filter(
SERVICE_FILTERS,
filteredServices.flattenItems()
);
}
// TODO: move modals to Page
return (
<ServiceTreeView
filters={SERVICE_FILTERS}
filterExpression={filterExpression}
isEmpty={isEmpty}
onFilterExpressionChange={this.handleFilterExpressionChange}
params={params}
routes={routes}
services={filteredServices.getItems()}
serviceTree={item}
roles={roles}
>
{children}
{this.getModals(item)}
</ServiceTreeView>
);
};
getServiceQuota = (item) => {
const { children, params, routes } = this.props;
return (
<ServicesQuotaView params={params} routes={routes} serviceTree={item}>
{children}
{this.getModals(item)}
</ServicesQuotaView>
);
};
getResetDelaySuccessToast = (serviceName) => {
const title = i18nTranslate(i18nMark("Reset Delay Successful"));
const description = i18nTranslate(
i18nMark("Delay has cleared and {serviceName} is now relaunching."),
{ serviceName }
);
return new ToastNotification(title, {
appearance: ToastAppearance.Success,
autodismiss: true,
description,
});
};
getResetDelayErrorToast = (serviceName) => {
const title = i18nTranslate(i18nMark("Reset Delay Failed"));
const description = i18nTranslate(
i18nMark(
"Delay reset failed and did not relaunch {serviceName}. Please try again."
),
{ serviceName }
);
return new ToastNotification(title, {
appearance: ToastAppearance.Danger,
autodismiss: true,
description,
});
};
render() {
const { children, params, routes } = this.props;
const { fetchErrors, isLoading, itemId } = this.state;
// TODO react-router: Temp hack if we are deeper than overview/:id we should render child routes
if (Object.keys(params).length > 1) {
return children;
}
// Still Loading
if (isLoading) {
return (
<Page>
<Page.Header
breadcrumbs={<ServiceBreadcrumbs serviceID={this.state.itemId} />}
/>
<Loader />
</Page>
);
}
// Check if a single endpoint has failed more than 3 times
const fetchError = Object.values(fetchErrors).some(
(errorCount) => errorCount > 3
);
// API Failures
if (fetchError) {
return <RequestErrorMsg />;
}
// Find item in root tree
const item =
itemId === "/"
? DCOSStore.serviceTree
: DCOSStore.serviceTree.findItemById(itemId);
// Show Tree
const currentRoutePath = RouterUtil.reconstructPathFromRoutes(routes);
if (currentRoutePath.startsWith("/services/overview")) {
// Not found
if (!(item instanceof ServiceTree)) {
return this.getEmptyPage("group");
}
// TODO: move modals to Page
return this.getServiceTree(item);
}
if (currentRoutePath.startsWith("/services/quota")) {
return this.getServiceQuota(item);
}
if (item instanceof Pod) {
return this.getPodDetail(item);
}
if (item instanceof Service) {
return this.getServiceDetail(item);
}
// Not found
return this.getEmptyPage("service");
}
}
// Make these modal handlers available via context
// so any child can trigger the opening of modals
ServicesContainer.childContextTypes = {
modalHandlers: PropTypes.shape({
createGroup: PropTypes.func,
deleteService: PropTypes.func,
editService: PropTypes.func,
restartService: PropTypes.func,
resumeService: PropTypes.func,
scaleService: PropTypes.func,
stopService: PropTypes.func,
openServiceUI: PropTypes.func,
resetDelayedService: PropTypes.func,
}),
};
ServicesContainer.contextTypes = {
router: routerShape,
};
ServicesContainer.routeConfig = {
label: i18nMark("Services"),
icon: <Icon shape={ProductIcons.ServicesInverse} size={iconSizeS} />,
matches: /^\/services\/(detail|overview|quota)/,
};
export default ServicesContainer; | the_stack |
import { NodeAPI } from 'node-red'
import express from 'express'
import HapCategories from './types/HapCategories'
import { Characteristic, Perms, SerializedService, Service } from 'hap-nodejs'
import CustomCharacteristicType from './types/CustomCharacteristicType'
import HAPServiceNodeType from './types/HAPServiceNodeType'
import HAPServiceConfigType from './types/HAPServiceConfigType'
import { logger } from '@nrchkb/logger'
import { Storage } from './Storage'
const version = require('../../package.json').version.trim()
module.exports = function (RED: NodeAPI) {
const log = logger('NRCHKB', 'API')
// Service API
const _initServiceAPI = () => {
log.debug('Initialize ServiceAPI')
type ServiceData = {
[key: string]: Partial<SerializedService> & {
nrchkbDisabledText?: string
}
}
// Service API response data
const serviceData: ServiceData = {
BatteryService: {
nrchkbDisabledText:
'BatteryService (deprecated, replaced by Battery)',
},
BridgeConfiguration: {
nrchkbDisabledText: 'BridgeConfiguration (deprecated, unused)',
},
BridgingState: {
nrchkbDisabledText: 'BridgingState (deprecated, unused)',
},
Relay: {
nrchkbDisabledText:
'Relay (deprecated, replaced by CloudRelay)',
},
Slat: {
nrchkbDisabledText: 'Slat (deprecated, replaced by Slats)',
},
TimeInformation: {
nrchkbDisabledText: 'TimeInformation (deprecated, unused)',
},
TunneledBTLEAccessoryService: {
nrchkbDisabledText:
'TunneledBTLEAccessoryService (deprecated, replaced by Tunnel)',
},
}
Object.values(Service)
.filter((service) => service.prototype instanceof Service)
.map((service) => {
const newService = Service.serialize(new service())
newService.displayName = service.name
return newService
})
.forEach((serialized) => {
serviceData[serialized.displayName] = {
...serviceData?.[serialized.displayName],
...serialized,
}
})
// Retrieve Service Types
RED.httpAdmin.get(
'/nrchkb/service/types',
RED.auth.needsPermission('nrchkb.read'),
(_req: express.Request, res: express.Response) => {
res.json(serviceData)
}
)
}
// NRCHKB Info API
const _initNRCHKBInfoAPI = () => {
log.debug('Initialize NRCHKB Info API')
log.debug(`Running version: ${version}`)
const releaseVersionRegex = /(\d+)\.(\d+)\.(\d+)/
const devVersionRegex = /(\d+)\.(\d+)\.(\d+)-dev\.(\d+)/
const releaseVersionFound = releaseVersionRegex.test(version)
const devVersionFound = devVersionRegex.test(version)
let xyzVersion = '0.0.0'
if (devVersionFound) {
try {
const match = devVersionRegex.exec(version)
if (match) {
xyzVersion = `0.${match[1]}${match[2]}${match[3]}.${match[4]}`
} else {
log.debug('Could not match dev version')
}
} catch (e) {
console.error(e)
}
} else if (releaseVersionFound) {
try {
const match = releaseVersionRegex.exec(version)
if (match) {
xyzVersion = match[0]
} else {
log.debug('Could not match release version')
}
} catch (e) {
console.error(e)
}
} else {
log.debug('Bad version format')
xyzVersion = '0.0.0'
}
log.debug(`Evaluated as: ${xyzVersion}`)
const experimental = process.env.NRCHKB_EXPERIMENTAL === 'true'
log.debug(`Running experimental: ${experimental}`)
// Retrieve NRCHKB version
RED.httpAdmin.get(
'/nrchkb/info',
RED.auth.needsPermission('nrchkb.read'),
(_req: express.Request, res: express.Response) => {
res.json({
version: xyzVersion,
experimental,
})
}
)
}
// NRCHKB Custom Characteristics API
const _initNRCHKBCustomCharacteristicsAPI = async () => {
const getCustomCharacteristics = () => {
return Storage.loadCustomCharacteristics()
.then((value) => {
log.trace(`loadCustomCharacteristics()`)
log.trace(value)
if (Array.isArray(value)) {
return value
} else {
log.debug(
'customCharacteristics is not Array, returning empty value'
)
return []
}
})
.catch((error) => {
log.error(
`Failed to get customCharacteristics in nrchkbStorage due to ${error}`
)
return []
})
}
const characteristicNameToKey = (name: string) => {
return name.replace(' ', '')
}
const refreshCustomCharacteristics = (
customCharacteristics: CustomCharacteristicType[]
) => {
log.debug('Refreshing Custom Characteristics')
const customCharacteristicKeys: string[] = []
customCharacteristics.forEach(({ name, UUID, ...props }) => {
if (!!UUID && !!name) {
const key = characteristicNameToKey(name)
log.debug(
`Adding Custom Characteristic ${name} using key ${key}`
)
if (customCharacteristicKeys.includes(key)) {
log.error(
`Cannot add ${name}. Another Custom Characteristic already defined using key ${key}`
)
return
}
const validatedProps = props
if (validatedProps.validValues?.length === 0) {
validatedProps.validValues = undefined
}
if (
!validatedProps.validValueRanges?.[0] ||
!validatedProps.validValueRanges?.[1]
) {
validatedProps.validValueRanges = undefined
}
if (validatedProps.adminOnlyAccess?.length === 0) {
validatedProps.adminOnlyAccess = undefined
}
class CustomCharacteristic extends Characteristic {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
static readonly UUID: string = UUID!
constructor() {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
super(name!, CustomCharacteristic.UUID, {
...validatedProps,
perms: validatedProps.perms ?? [
Perms.PAIRED_READ,
Perms.PAIRED_WRITE,
Perms.NOTIFY,
],
})
this.value = this.getDefaultValue()
}
}
Object.defineProperty(CustomCharacteristic, 'name', {
value: key,
configurable: true,
})
Object.defineProperty(Characteristic, key, {
value: CustomCharacteristic,
configurable: true,
})
customCharacteristicKeys.push(key)
}
})
new Promise((resolve) => {
const isRedInitialized = () => {
try {
RED.nodes.eachNode(() => {
return
})
resolve(true)
} catch (_) {
log.debug('Waiting for RED to be initialized')
setTimeout(isRedInitialized, 1000)
}
}
isRedInitialized()
}).then(() => {
RED.nodes.eachNode((node) => {
if (node.type === 'homekit-service') {
const serviceNodeConfig = node as HAPServiceConfigType
const serviceNode = RED.nodes.getNode(
serviceNodeConfig.id
) as HAPServiceNodeType
if (
serviceNode &&
serviceNode.characteristicProperties &&
serviceNode.service
) {
for (const key in serviceNode.characteristicProperties) {
if (customCharacteristicKeys.includes(key)) {
const characteristic = serviceNode.service
// @ts-ignore
.getCharacteristic(Characteristic[key])
.setProps(
serviceNode
.characteristicProperties[key]
)
serviceNode.supported.push(key)
characteristic.on(
'get',
serviceNode.onCharacteristicGet
)
characteristic.on(
'set',
serviceNode.onCharacteristicSet
)
characteristic.on(
'change',
serviceNode.onCharacteristicChange
)
}
}
}
}
})
})
}
log.debug('Initialize NRCHKBCustomCharacteristicsAPI')
getCustomCharacteristics().then((value) =>
refreshCustomCharacteristics(value)
)
// Retrieve NRCHKB version
RED.httpAdmin.get(
'/nrchkb/config',
RED.auth.needsPermission('nrchkb.read'),
async (_req: express.Request, res: express.Response) => {
res.json({
customCharacteristics: await getCustomCharacteristics(),
})
}
)
// Change NRCHKB version
RED.httpAdmin.post(
'/nrchkb/config',
RED.auth.needsPermission('nrchkb.write'),
async (req: express.Request, res: express.Response) => {
const customCharacteristics: CustomCharacteristicType[] =
req.body.customCharacteristics || []
Storage.saveCustomCharacteristics(customCharacteristics)
.then(() => {
res.sendStatus(200)
refreshCustomCharacteristics(customCharacteristics)
})
.catch((error) => {
log.error(error)
res.sendStatus(500)
})
}
)
}
// Accessory API
const _initAccessoryAPI = function () {
log.debug('Initialize AccessoryAPI')
// Accessory Categories API response data
const accessoryCategoriesData: {
[key: number]: string
} = {}
// Prepare Accessory data once
Object.keys(HapCategories)
.sort()
.filter((x) => parseInt(x) >= 0)
.forEach((key) => {
const keyNumber = key as unknown as number
accessoryCategoriesData[keyNumber] = HapCategories[keyNumber]
})
// Retrieve Accessory Types
RED.httpAdmin.get(
'/nrchkb/accessory/categories',
RED.auth.needsPermission('nrchkb.read'),
(_req: express.Request, res: express.Response) => {
res.json(accessoryCategoriesData)
}
)
}
const init = () => {
_initServiceAPI()
_initNRCHKBInfoAPI()
_initAccessoryAPI()
// Experimental feature
if (process.env.NRCHKB_EXPERIMENTAL === 'true') {
_initNRCHKBCustomCharacteristicsAPI().then()
}
}
return {
init,
}
} | the_stack |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.