text stringlengths 2.5k 6.39M | kind stringclasses 3
values |
|---|---|
import { GraphQLResolveInfo, GraphQLScalarType, GraphQLScalarTypeConfig } from 'graphql'
export type Maybe<T> = T | null
export type Exact<T extends { [key: string]: unknown }> = { [K in keyof T]: T[K] }
export type MakeOptional<T, K extends keyof T> = Omit<T, K> & { [SubKey in K]?: Maybe<T[SubKey]> }
export type MakeMaybe<T, K extends keyof T> = Omit<T, K> & { [SubKey in K]: Maybe<T[SubKey]> }
export type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>
/** All built-in and custom scalars, mapped to their actual values */
export type Scalars = {
ID: string
String: string
Boolean: boolean
Int: number
Float: number
Json: any
}
export type Query = {
readonly __typename?: 'Query'
readonly schema?: Maybe<_Schema>
}
export type _Argument = _ValidatorArgument | _PathArgument | _LiteralArgument
export type _Column = _Field & {
readonly __typename?: '_Column'
readonly name: Scalars['String']
readonly type: Scalars['String']
readonly enumName?: Maybe<Scalars['String']>
readonly defaultValue?: Maybe<Scalars['Json']>
readonly nullable: Scalars['Boolean']
readonly rules: ReadonlyArray<_Rule>
readonly validators: ReadonlyArray<_Validator>
}
export type _Entity = {
readonly __typename?: '_Entity'
readonly name: Scalars['String']
readonly customPrimaryAllowed: Scalars['Boolean']
readonly fields: ReadonlyArray<_Field>
readonly unique: ReadonlyArray<_UniqueConstraint>
}
export type _Enum = {
readonly __typename?: '_Enum'
readonly name: Scalars['String']
readonly values: ReadonlyArray<Scalars['String']>
}
export type _Field = {
readonly name: Scalars['String']
readonly type: Scalars['String']
readonly nullable?: Maybe<Scalars['Boolean']>
readonly rules: ReadonlyArray<_Rule>
readonly validators: ReadonlyArray<_Validator>
}
export type _LiteralArgument = {
readonly __typename?: '_LiteralArgument'
readonly value?: Maybe<Scalars['Json']>
}
export enum _OnDeleteBehaviour {
Restrict = 'restrict',
Cascade = 'cascade',
SetNull = 'setNull'
}
export type _OrderBy = {
readonly __typename?: '_OrderBy'
readonly path: ReadonlyArray<Scalars['String']>
readonly direction: _OrderByDirection
}
export enum _OrderByDirection {
Asc = 'asc',
Desc = 'desc'
}
export type _PathArgument = {
readonly __typename?: '_PathArgument'
readonly path: ReadonlyArray<Scalars['String']>
}
export type _Relation = _Field & {
readonly __typename?: '_Relation'
readonly name: Scalars['String']
readonly type: Scalars['String']
readonly side: _RelationSide
readonly targetEntity: Scalars['String']
readonly ownedBy?: Maybe<Scalars['String']>
readonly inversedBy?: Maybe<Scalars['String']>
readonly nullable?: Maybe<Scalars['Boolean']>
readonly onDelete?: Maybe<_OnDeleteBehaviour>
readonly orphanRemoval?: Maybe<Scalars['Boolean']>
readonly orderBy?: Maybe<ReadonlyArray<_OrderBy>>
readonly rules: ReadonlyArray<_Rule>
readonly validators: ReadonlyArray<_Validator>
}
export enum _RelationSide {
Owning = 'owning',
Inverse = 'inverse'
}
export type _Rule = {
readonly __typename?: '_Rule'
readonly message?: Maybe<_RuleMessage>
readonly validator: Scalars['Int']
}
export type _RuleMessage = {
readonly __typename?: '_RuleMessage'
readonly text?: Maybe<Scalars['String']>
}
export type _Schema = {
readonly __typename?: '_Schema'
readonly enums: ReadonlyArray<_Enum>
readonly entities: ReadonlyArray<_Entity>
}
export type _UniqueConstraint = {
readonly __typename?: '_UniqueConstraint'
readonly fields: ReadonlyArray<Scalars['String']>
}
export type _Validator = {
readonly __typename?: '_Validator'
readonly operation: Scalars['String']
readonly arguments: ReadonlyArray<_Argument>
}
export type _ValidatorArgument = {
readonly __typename?: '_ValidatorArgument'
readonly validator: Scalars['Int']
}
export type ResolverTypeWrapper<T> = Promise<T> | T
export type LegacyStitchingResolver<TResult, TParent, TContext, TArgs> = {
fragment: string
resolve: ResolverFn<TResult, TParent, TContext, TArgs>
}
export type NewStitchingResolver<TResult, TParent, TContext, TArgs> = {
selectionSet: string
resolve: ResolverFn<TResult, TParent, TContext, TArgs>
}
export type StitchingResolver<TResult, TParent, TContext, TArgs> = LegacyStitchingResolver<TResult, TParent, TContext, TArgs> | NewStitchingResolver<TResult, TParent, TContext, TArgs>
export type Resolver<TResult, TParent = {}, TContext = {}, TArgs = {}> =
| ResolverFn<TResult, TParent, TContext, TArgs>
| StitchingResolver<TResult, TParent, TContext, TArgs>
export type ResolverFn<TResult, TParent, TContext, TArgs> = (
parent: TParent,
args: TArgs,
context: TContext,
info: GraphQLResolveInfo
) => Promise<TResult> | TResult
export type SubscriptionSubscribeFn<TResult, TParent, TContext, TArgs> = (
parent: TParent,
args: TArgs,
context: TContext,
info: GraphQLResolveInfo
) => AsyncIterator<TResult> | Promise<AsyncIterator<TResult>>
export type SubscriptionResolveFn<TResult, TParent, TContext, TArgs> = (
parent: TParent,
args: TArgs,
context: TContext,
info: GraphQLResolveInfo
) => TResult | Promise<TResult>
export interface SubscriptionSubscriberObject<TResult, TKey extends string, TParent, TContext, TArgs> {
subscribe: SubscriptionSubscribeFn<{ [key in TKey]: TResult }, TParent, TContext, TArgs>
resolve?: SubscriptionResolveFn<TResult, { [key in TKey]: TResult }, TContext, TArgs>
}
export interface SubscriptionResolverObject<TResult, TParent, TContext, TArgs> {
subscribe: SubscriptionSubscribeFn<any, TParent, TContext, TArgs>
resolve: SubscriptionResolveFn<TResult, any, TContext, TArgs>
}
export type SubscriptionObject<TResult, TKey extends string, TParent, TContext, TArgs> =
| SubscriptionSubscriberObject<TResult, TKey, TParent, TContext, TArgs>
| SubscriptionResolverObject<TResult, TParent, TContext, TArgs>
export type SubscriptionResolver<TResult, TKey extends string, TParent = {}, TContext = {}, TArgs = {}> =
| ((...args: any[]) => SubscriptionObject<TResult, TKey, TParent, TContext, TArgs>)
| SubscriptionObject<TResult, TKey, TParent, TContext, TArgs>
export type TypeResolveFn<TTypes, TParent = {}, TContext = {}> = (
parent: TParent,
context: TContext,
info: GraphQLResolveInfo
) => Maybe<TTypes> | Promise<Maybe<TTypes>>
export type IsTypeOfResolverFn<T = {}, TContext = {}> = (obj: T, context: TContext, info: GraphQLResolveInfo) => boolean | Promise<boolean>
export type NextResolverFn<T> = () => Promise<T>
export type DirectiveResolverFn<TResult = {}, TParent = {}, TContext = {}, TArgs = {}> = (
next: NextResolverFn<TResult>,
parent: TParent,
args: TArgs,
context: TContext,
info: GraphQLResolveInfo
) => TResult | Promise<TResult>
/** Mapping between all available schema types and the resolvers types */
export type ResolversTypes = {
Json: ResolverTypeWrapper<Scalars['Json']>
Query: ResolverTypeWrapper<{}>
_Argument: ResolversTypes['_ValidatorArgument'] | ResolversTypes['_PathArgument'] | ResolversTypes['_LiteralArgument']
_Column: ResolverTypeWrapper<_Column>
String: ResolverTypeWrapper<Scalars['String']>
Boolean: ResolverTypeWrapper<Scalars['Boolean']>
_Entity: ResolverTypeWrapper<_Entity>
_Enum: ResolverTypeWrapper<_Enum>
_Field: ResolversTypes['_Column'] | ResolversTypes['_Relation']
_LiteralArgument: ResolverTypeWrapper<_LiteralArgument>
_OnDeleteBehaviour: _OnDeleteBehaviour
_OrderBy: ResolverTypeWrapper<_OrderBy>
_OrderByDirection: _OrderByDirection
_PathArgument: ResolverTypeWrapper<_PathArgument>
_Relation: ResolverTypeWrapper<_Relation>
_RelationSide: _RelationSide
_Rule: ResolverTypeWrapper<_Rule>
Int: ResolverTypeWrapper<Scalars['Int']>
_RuleMessage: ResolverTypeWrapper<_RuleMessage>
_Schema: ResolverTypeWrapper<_Schema>
_UniqueConstraint: ResolverTypeWrapper<_UniqueConstraint>
_Validator: ResolverTypeWrapper<Omit<_Validator, 'arguments'> & { arguments: ReadonlyArray<ResolversTypes['_Argument']> }>
_ValidatorArgument: ResolverTypeWrapper<_ValidatorArgument>
}
/** Mapping between all available schema types and the resolvers parents */
export type ResolversParentTypes = {
Json: Scalars['Json']
Query: {}
_Argument: ResolversParentTypes['_ValidatorArgument'] | ResolversParentTypes['_PathArgument'] | ResolversParentTypes['_LiteralArgument']
_Column: _Column
String: Scalars['String']
Boolean: Scalars['Boolean']
_Entity: _Entity
_Enum: _Enum
_Field: ResolversParentTypes['_Column'] | ResolversParentTypes['_Relation']
_LiteralArgument: _LiteralArgument
_OrderBy: _OrderBy
_PathArgument: _PathArgument
_Relation: _Relation
_Rule: _Rule
Int: Scalars['Int']
_RuleMessage: _RuleMessage
_Schema: _Schema
_UniqueConstraint: _UniqueConstraint
_Validator: Omit<_Validator, 'arguments'> & { arguments: ReadonlyArray<ResolversParentTypes['_Argument']> }
_ValidatorArgument: _ValidatorArgument
}
export interface JsonScalarConfig extends GraphQLScalarTypeConfig<ResolversTypes['Json'], any> {
name: 'Json'
}
export type QueryResolvers<ContextType = any, ParentType extends ResolversParentTypes['Query'] = ResolversParentTypes['Query']> = {
schema?: Resolver<Maybe<ResolversTypes['_Schema']>, ParentType, ContextType>
}
export type _ArgumentResolvers<ContextType = any, ParentType extends ResolversParentTypes['_Argument'] = ResolversParentTypes['_Argument']> = {
__resolveType: TypeResolveFn<'_ValidatorArgument' | '_PathArgument' | '_LiteralArgument', ParentType, ContextType>
}
export type _ColumnResolvers<ContextType = any, ParentType extends ResolversParentTypes['_Column'] = ResolversParentTypes['_Column']> = {
name?: Resolver<ResolversTypes['String'], ParentType, ContextType>
type?: Resolver<ResolversTypes['String'], ParentType, ContextType>
enumName?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>
defaultValue?: Resolver<Maybe<ResolversTypes['Json']>, ParentType, ContextType>
nullable?: Resolver<ResolversTypes['Boolean'], ParentType, ContextType>
rules?: Resolver<ReadonlyArray<ResolversTypes['_Rule']>, ParentType, ContextType>
validators?: Resolver<ReadonlyArray<ResolversTypes['_Validator']>, ParentType, ContextType>
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>
}
export type _EntityResolvers<ContextType = any, ParentType extends ResolversParentTypes['_Entity'] = ResolversParentTypes['_Entity']> = {
name?: Resolver<ResolversTypes['String'], ParentType, ContextType>
customPrimaryAllowed?: Resolver<ResolversTypes['Boolean'], ParentType, ContextType>
fields?: Resolver<ReadonlyArray<ResolversTypes['_Field']>, ParentType, ContextType>
unique?: Resolver<ReadonlyArray<ResolversTypes['_UniqueConstraint']>, ParentType, ContextType>
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>
}
export type _EnumResolvers<ContextType = any, ParentType extends ResolversParentTypes['_Enum'] = ResolversParentTypes['_Enum']> = {
name?: Resolver<ResolversTypes['String'], ParentType, ContextType>
values?: Resolver<ReadonlyArray<ResolversTypes['String']>, ParentType, ContextType>
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>
}
export type _FieldResolvers<ContextType = any, ParentType extends ResolversParentTypes['_Field'] = ResolversParentTypes['_Field']> = {
__resolveType: TypeResolveFn<'_Column' | '_Relation', ParentType, ContextType>
name?: Resolver<ResolversTypes['String'], ParentType, ContextType>
type?: Resolver<ResolversTypes['String'], ParentType, ContextType>
nullable?: Resolver<Maybe<ResolversTypes['Boolean']>, ParentType, ContextType>
rules?: Resolver<ReadonlyArray<ResolversTypes['_Rule']>, ParentType, ContextType>
validators?: Resolver<ReadonlyArray<ResolversTypes['_Validator']>, ParentType, ContextType>
}
export type _LiteralArgumentResolvers<ContextType = any, ParentType extends ResolversParentTypes['_LiteralArgument'] = ResolversParentTypes['_LiteralArgument']> = {
value?: Resolver<Maybe<ResolversTypes['Json']>, ParentType, ContextType>
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>
}
export type _OrderByResolvers<ContextType = any, ParentType extends ResolversParentTypes['_OrderBy'] = ResolversParentTypes['_OrderBy']> = {
path?: Resolver<ReadonlyArray<ResolversTypes['String']>, ParentType, ContextType>
direction?: Resolver<ResolversTypes['_OrderByDirection'], ParentType, ContextType>
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>
}
export type _PathArgumentResolvers<ContextType = any, ParentType extends ResolversParentTypes['_PathArgument'] = ResolversParentTypes['_PathArgument']> = {
path?: Resolver<ReadonlyArray<ResolversTypes['String']>, ParentType, ContextType>
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>
}
export type _RelationResolvers<ContextType = any, ParentType extends ResolversParentTypes['_Relation'] = ResolversParentTypes['_Relation']> = {
name?: Resolver<ResolversTypes['String'], ParentType, ContextType>
type?: Resolver<ResolversTypes['String'], ParentType, ContextType>
side?: Resolver<ResolversTypes['_RelationSide'], ParentType, ContextType>
targetEntity?: Resolver<ResolversTypes['String'], ParentType, ContextType>
ownedBy?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>
inversedBy?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>
nullable?: Resolver<Maybe<ResolversTypes['Boolean']>, ParentType, ContextType>
onDelete?: Resolver<Maybe<ResolversTypes['_OnDeleteBehaviour']>, ParentType, ContextType>
orphanRemoval?: Resolver<Maybe<ResolversTypes['Boolean']>, ParentType, ContextType>
orderBy?: Resolver<Maybe<ReadonlyArray<ResolversTypes['_OrderBy']>>, ParentType, ContextType>
rules?: Resolver<ReadonlyArray<ResolversTypes['_Rule']>, ParentType, ContextType>
validators?: Resolver<ReadonlyArray<ResolversTypes['_Validator']>, ParentType, ContextType>
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>
}
export type _RuleResolvers<ContextType = any, ParentType extends ResolversParentTypes['_Rule'] = ResolversParentTypes['_Rule']> = {
message?: Resolver<Maybe<ResolversTypes['_RuleMessage']>, ParentType, ContextType>
validator?: Resolver<ResolversTypes['Int'], ParentType, ContextType>
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>
}
export type _RuleMessageResolvers<ContextType = any, ParentType extends ResolversParentTypes['_RuleMessage'] = ResolversParentTypes['_RuleMessage']> = {
text?: Resolver<Maybe<ResolversTypes['String']>, ParentType, ContextType>
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>
}
export type _SchemaResolvers<ContextType = any, ParentType extends ResolversParentTypes['_Schema'] = ResolversParentTypes['_Schema']> = {
enums?: Resolver<ReadonlyArray<ResolversTypes['_Enum']>, ParentType, ContextType>
entities?: Resolver<ReadonlyArray<ResolversTypes['_Entity']>, ParentType, ContextType>
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>
}
export type _UniqueConstraintResolvers<ContextType = any, ParentType extends ResolversParentTypes['_UniqueConstraint'] = ResolversParentTypes['_UniqueConstraint']> = {
fields?: Resolver<ReadonlyArray<ResolversTypes['String']>, ParentType, ContextType>
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>
}
export type _ValidatorResolvers<ContextType = any, ParentType extends ResolversParentTypes['_Validator'] = ResolversParentTypes['_Validator']> = {
operation?: Resolver<ResolversTypes['String'], ParentType, ContextType>
arguments?: Resolver<ReadonlyArray<ResolversTypes['_Argument']>, ParentType, ContextType>
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>
}
export type _ValidatorArgumentResolvers<ContextType = any, ParentType extends ResolversParentTypes['_ValidatorArgument'] = ResolversParentTypes['_ValidatorArgument']> = {
validator?: Resolver<ResolversTypes['Int'], ParentType, ContextType>
__isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>
}
export type Resolvers<ContextType = any> = {
Json?: GraphQLScalarType
Query?: QueryResolvers<ContextType>
_Argument?: _ArgumentResolvers<ContextType>
_Column?: _ColumnResolvers<ContextType>
_Entity?: _EntityResolvers<ContextType>
_Enum?: _EnumResolvers<ContextType>
_Field?: _FieldResolvers<ContextType>
_LiteralArgument?: _LiteralArgumentResolvers<ContextType>
_OrderBy?: _OrderByResolvers<ContextType>
_PathArgument?: _PathArgumentResolvers<ContextType>
_Relation?: _RelationResolvers<ContextType>
_Rule?: _RuleResolvers<ContextType>
_RuleMessage?: _RuleMessageResolvers<ContextType>
_Schema?: _SchemaResolvers<ContextType>
_UniqueConstraint?: _UniqueConstraintResolvers<ContextType>
_Validator?: _ValidatorResolvers<ContextType>
_ValidatorArgument?: _ValidatorArgumentResolvers<ContextType>
}
/**
* @deprecated
* Use "Resolvers" root object instead. If you wish to get "IResolvers", add "typesPrefix: I" to your config.
*/
export type IResolvers<ContextType = any> = Resolvers<ContextType> | the_stack |
import React, {
useState,
useEffect,
useRef,
useContext,
forwardRef,
useImperativeHandle,
} from 'react';
import { SplitGroupProps, CollapsedConfig } from './interface';
import { ConfigContext } from '../ConfigProvider';
import cs from '../_util/classNames';
import { isFunction, isNumber, isUndefined, isObject, isString } from '../_util/is';
import ResizeTrigger from './resize-trigger';
import { on, off } from '../_util/dom';
const DIRECTION_HORIZONTAL = 'horizontal';
const DIRECTION_VERTICAL = 'vertical';
function SplitGroup(props: SplitGroupProps, ref) {
const { panes, style, className, component = 'div', direction = 'horizontal', icon } = props;
const { getPrefixCls } = useContext(ConfigContext);
const defaultOffset = 1 / panes.length;
const wrapperRef = useRef<HTMLElement>();
const recordRef = useRef<Array<{ moving: boolean; startOffset: number; startPosition: number }>>(
new Array(panes.length).fill({
moving: false,
startOffset: 0,
startPosition: 0,
})
);
const paneContainers = useRef<HTMLElement[]>([]);
const movingIndex = useRef<number>(0);
const prevOffsets = useRef<number[]>([]);
const [offsets, setOffsets] = useState<number[]>(new Array(panes.length).fill(defaultOffset));
const [isMoving, setIsMoving] = useState(false);
const [triggerSize, setTriggerSize] = useState<number[]>(new Array(panes.length).fill(0));
const [collapsedStatus, setCollapsedStatus] = useState<{ prev: boolean; next: boolean }[]>(
new Array(Math.max(panes.length - 1, 0)).fill({ prev: false, next: false })
);
const prefixCls = getPrefixCls('resizebox-split-group');
const isHorizontal = direction === DIRECTION_HORIZONTAL;
const isTriggerHorizontal = !isHorizontal;
const classNames = cs(
prefixCls,
`${prefixCls}-${isHorizontal ? DIRECTION_HORIZONTAL : DIRECTION_VERTICAL}`,
{ [`${prefixCls}-moving`]: isMoving },
className
);
const Tag = component as any;
// 获取初始的 offset, 将传入的size 都转为像素值。
const getInitialOffsets = () => {
let newOffsets = [];
panes.forEach((pane) => {
const { size } = pane;
if (!isUndefined(size)) {
newOffsets.push(formatSize(size));
} else {
newOffsets.push(undefined);
}
});
// 剩余的空间均分给没有设置 size 的面板
const noSizeArr = newOffsets.filter((size) => !size);
const remainPercent =
1 -
newOffsets.reduce((a, b) => {
const formatA = a || 0;
const formatB = b || 0;
return formatA + formatB;
}, 0);
const averagePercent = remainPercent / noSizeArr.length;
newOffsets = newOffsets.map((size) => {
if (!isUndefined(size)) {
return size;
}
return averagePercent;
});
return newOffsets;
};
// 计算每一个面板的占位像素,需要减去前面跟当前伸缩杆的宽度
const getPaneSize = (index) => {
const prevTriggerSize = triggerSize[index - 1] || 0;
const currentTriggerSize = triggerSize[index];
const baseVal = offsets[index] * 100;
const unit = '%';
return `calc(${baseVal}${unit} - ${(prevTriggerSize + currentTriggerSize) / 2}px)`;
};
// 入参 百分比/像素值 => 全部转化为百分比(响应式)
function formatSize(size?: number | string) {
const totalPX = isHorizontal ? wrapperRef.current.offsetWidth : wrapperRef.current.offsetHeight;
if (!size || (isNumber(size) && size < 0)) {
return 0;
}
const percent = isString(size) ? parseFloat(size) / totalPX : size;
return Math.min(percent, 1);
}
// 计算阈值,因为伸缩杆会影响到当前面板 跟 下一个面板。所以同时计算两个阈值。
const getMinAndMax = (index: number) => {
const next = Math.min(index + 1, panes.length - 1);
const totalOffset = offsets[index] + offsets[next];
const currentMin = formatSize(panes[index].min) || 0;
let currentMax = formatSize(panes[index].max) || totalOffset;
const nextMin = formatSize(panes[next].min) || 0;
let nextMax = formatSize(panes[next].max) || totalOffset;
// min 的优先级高于 max
currentMax = Math.min(totalOffset - nextMin, currentMax);
nextMax = Math.min(totalOffset - currentMin, nextMax);
return {
currentMin,
currentMax,
nextMin,
nextMax,
};
};
// 拖拽时,获取新的占位距离。影响当前面板跟下一个面板的占位值。
const getNewOffsets = (startOffset: number, startPosition: number, currentPosition: number) => {
const current = movingIndex.current;
const next = current + 1;
const newOffsets = [...offsets];
const currentPercent = offsets[current];
const nextPercent = offsets[next];
const totalPercent = currentPercent + nextPercent;
const { currentMin: minOffset, currentMax: maxOffset } = getMinAndMax(current);
let moveOffset = startOffset + formatSize(`${currentPosition - startPosition}px`);
moveOffset = Math.max(minOffset, moveOffset);
moveOffset = Math.min(maxOffset, moveOffset);
newOffsets[current] = moveOffset;
// 保证 totalOffset = nextOffset + currentOffset 不变。
newOffsets[next] = totalPercent - moveOffset;
return newOffsets;
};
function onTriggerResize(e, index) {
const { contentRect } = e[0];
const currentSize = contentRect[isTriggerHorizontal ? 'height' : 'width'];
const newTriggerSize = [...triggerSize];
newTriggerSize[index] = currentSize;
setTriggerSize(newTriggerSize);
}
// 判断快速收缩按钮是否展示
const getCollapsedConfig = (index: number) => {
let collapsible = panes[index].collapsible;
if (!isObject(collapsible)) {
collapsible = !collapsible ? {} : { prev: true, next: true };
}
const { prev, next } = collapsible;
if (!prev && !next) {
return {};
}
if (!collapsedStatus[index]) {
return {};
}
// 传入了prev的配置,或者 没有传入 prev 的配置,但是已经处于向下收缩完毕状态
const hasPrev = !!prev || (!prev && collapsedStatus[index].next);
// 传入了next的配置,或者 没有传入 next 的配置,但是已经处于向上收缩完毕状态
const hasNext = !!next || (!next && collapsedStatus[index].prev);
return { hasPrev, hasNext };
};
// 移动开始,记录初始值,绑定移动事件
function onTriggerMouseDown(e, index) {
props.onMovingStart && props.onMovingStart(index);
movingIndex.current = index;
const currentRecord = recordRef.current[index];
currentRecord.moving = true;
currentRecord.startOffset = offsets[index];
currentRecord.startPosition = isHorizontal ? e.pageX : e.pageY;
setIsMoving(true);
on(window, 'mousemove', moving);
on(window, 'touchmove', moving);
on(window, 'mouseup', moveEnd);
on(window, 'touchend', moveEnd);
on(window, 'contextmenu', moveEnd);
document.body.style.cursor = isTriggerHorizontal ? 'row-resize' : 'col-resize';
}
// 移动中,更新 当前面板跟下一个面板 占位大小
function moving(e) {
const index = movingIndex.current;
const currentRecord = recordRef.current[index];
const totalPX = isHorizontal ? wrapperRef.current.offsetWidth : wrapperRef.current.offsetHeight;
if (currentRecord.moving) {
const newOffsets = getNewOffsets(
currentRecord.startOffset,
currentRecord.startPosition,
isHorizontal ? e.pageX : e.pageY
);
setOffsets(newOffsets);
prevOffsets.current = newOffsets;
props.onMoving &&
props.onMoving(
e,
newOffsets.map((value) => `${value * totalPX}px`),
index
);
}
}
// 移动结束,解除事件绑定
function moveEnd() {
const index = movingIndex.current;
recordRef.current[index].moving = false;
setIsMoving(false);
off(window, 'mousemove', moving);
off(window, 'touchmove', moving);
off(window, 'mouseup', moveEnd);
off(window, 'touchend', moveEnd);
off(window, 'contextmenu', moveEnd);
document.body.style.cursor = 'default';
props.onMovingEnd && props.onMovingEnd(index);
}
// 点击快速收缩按钮的回调。
function handleCollapsed(e, index, status: 'prev' | 'next', callback) {
const next = index + 1;
const newOffset = [...offsets];
const currentOffset = offsets[index];
const nextOffset = offsets[next];
const totalOffset = currentOffset + nextOffset;
const totalPX = isHorizontal ? wrapperRef.current.offsetWidth : wrapperRef.current.offsetHeight;
const { currentMin, nextMin } = getMinAndMax(index);
// 取消收缩时,应该重置为上一个状态。所以从preOffsets里拿值
let newCurrentOffset = prevOffsets.current[index];
let newNextOffset = prevOffsets.current[next];
// 当前面板的收缩状态。
let collapsed = collapsedStatus[index][status];
// 点击向上收缩按钮。收缩态是:currentPane = currentMin;
if (status === 'prev') {
// 如果下一个面板不是在收缩状态 或者 下一个面板被手动拖拽到收缩状态
if (nextOffset !== nextMin || newNextOffset === nextMin) {
// 当前面板收缩。
newCurrentOffset = currentMin;
newNextOffset = totalOffset - currentMin;
collapsed = true;
}
// 点击向下收缩按钮
} else if (currentOffset !== currentMin || newCurrentOffset === currentMin) {
newCurrentOffset = totalOffset - nextMin;
newNextOffset = nextMin;
collapsed = true;
}
newOffset[index] = newCurrentOffset;
newOffset[next] = newNextOffset;
props.onMoving &&
props.onMoving(
e,
newOffset.map((value) => `${value * totalPX}px`),
index
);
props.onMovingEnd && props.onMovingEnd(index);
setOffsets(newOffset);
if (isFunction(callback)) {
callback(e, index, status, collapsed);
}
}
useEffect(() => {
const offsets = getInitialOffsets();
setOffsets(offsets);
prevOffsets.current = offsets;
}, [JSON.stringify(panes.map((item) => item.size))]);
useImperativeHandle(ref, () => wrapperRef.current, []);
useEffect(() => {
const newCollapsedStatus = [];
offsets.forEach((offset, index) => {
const currentCollapsedStatus = { prev: false, next: false };
const next = index + 1;
const { currentMin, nextMin } = getMinAndMax(index);
// 当 offsets 变化时,更新各个面板的 collapsed 状态
if (offset === currentMin) {
currentCollapsedStatus.prev = true;
} else if (offsets[next] === nextMin) {
currentCollapsedStatus.next = true;
}
newCollapsedStatus.push(currentCollapsedStatus);
});
setCollapsedStatus(newCollapsedStatus);
}, [offsets]);
return (
<Tag style={style} className={classNames} ref={wrapperRef}>
{panes.map((pane, index) => {
const { content, disabled, trigger, resizable = true, collapsible = {} } = pane;
const { hasPrev, hasNext } = getCollapsedConfig(index);
const prevConfig: CollapsedConfig =
isObject(collapsible) && isObject(collapsible.prev) ? collapsible.prev : {};
const nextConfig: CollapsedConfig =
isObject(collapsible) && isObject(collapsible.next) ? collapsible.next : {};
return (
<React.Fragment key={index}>
<div
className={`${prefixCls}-pane`}
style={{ flexBasis: getPaneSize(index) }}
ref={(el) => (paneContainers.current[index] = el)}
>
{content}
</div>
{!disabled && index !== panes.length - 1 && (
<ResizeTrigger
className={`${prefixCls}-trigger`}
direction={isTriggerHorizontal ? DIRECTION_HORIZONTAL : DIRECTION_VERTICAL}
icon={icon}
onResize={(e) => onTriggerResize(e, index)}
onMouseDown={(e) => onTriggerMouseDown(e, index)}
collapsible={{
prev: hasPrev
? {
onClick: (e) => handleCollapsed(e, index, 'prev', prevConfig.onClick),
icon: prevConfig.icon,
collapsed: collapsedStatus[index].prev,
}
: undefined,
next: hasNext
? {
onClick: (e) => handleCollapsed(e, index, 'next', nextConfig.onClick),
icon: nextConfig.icon,
collapsed: collapsedStatus[index].next,
}
: undefined,
}}
resizable={resizable}
renderChildren={trigger}
/>
)}
</React.Fragment>
);
})}
</Tag>
);
}
const SplitGroupComponent = forwardRef<unknown, SplitGroupProps>(SplitGroup);
SplitGroupComponent.displayName = 'ResizeBoxSplitGroup';
export default SplitGroupComponent; | the_stack |
import 'mocha';
import { expect } from 'chai';
import * as tmp from 'tmp';
import * as fs from 'fs';
import * as os from 'os';
import * as path from 'path';
import { Storage } from '@google-cloud/storage';
import pMap from 'p-map';
import {
EXAMPLE_FILE,
EXAMPLE_DIR,
FILES_IN_DIR,
EXAMPLE_PREFIX,
FILES_IN_DIR_WITHOUT_PARENT_DIR,
TXT_FILES_IN_DIR,
TXT_FILES_IN_DIR_WITHOUT_PARENT_DIR,
TXT_FILES_IN_TOP_DIR,
} from './constants.test';
import { Client } from '../src/client';
const storage = new Storage({
projectId: process.env.UPLOAD_CLOUD_STORAGE_TEST_PROJECT,
});
const PERF_TEST_FILE_COUNT = 10000;
// skip performance test and error message verification on Windows
const isWin = os.platform() === 'win32';
describe('Integration Upload ', function () {
let testBucket: string;
// helper function to create a new bucket
async function getNewBucket(): Promise<string> {
const bucketName = `test-${Math.round(Math.random() * 1000)}${
process.env.GITHUB_SHA
}`;
const [bucket] = await storage.createBucket(bucketName, {
location: 'US',
});
return bucket.name;
}
// helper func to get all files in test bucket
async function getFilesInBucket(): Promise<string[]> {
if (testBucket) {
const [files] = await storage.bucket(testBucket).getFiles();
return files.map((f) => f.name);
}
return [];
}
// create a new bucket for tests
this.beforeAll(async function () {
if (!process.env.UPLOAD_CLOUD_STORAGE_TEST_PROJECT) {
this.skip();
}
testBucket = await getNewBucket();
process.env.UPLOAD_ACTION_NO_LOG = 'true';
});
// skip test if no bucket is set
this.beforeEach(function () {
if (!process.env.UPLOAD_CLOUD_STORAGE_TEST_PROJECT) {
this.skip();
}
});
// remove all files in bucket before each test
this.afterEach(async function () {
const [files] = await storage.bucket(testBucket).getFiles();
const uploader = async (name: string): Promise<number> => {
const del = await storage.bucket(testBucket).file(name).delete();
return del[0].statusCode;
};
await pMap(
files.map((f) => f.name),
uploader,
{ concurrency: 100 },
);
const [checkFiles] = await storage.bucket(testBucket).getFiles();
expect(checkFiles.length).eq(0);
});
// delete bucket after all tests
this.afterAll(async function () {
if (testBucket) {
await storage.bucket(testBucket).delete();
}
});
it('uploads a single file', async function () {
const uploader = new Client();
const uploadResponse = await uploader.upload(
testBucket,
'./tests/testdata/test1.txt',
);
expect(uploadResponse[0][0].name).eql('test1.txt');
const filesInBucket = await getFilesInBucket();
expect(filesInBucket.length).eq(1);
expect(filesInBucket).to.have.members(['test1.txt']);
});
it('uploads a single file with prefix no gzip', async function () {
const uploader = new Client();
const uploadResponse = await uploader.upload(
`${testBucket}/${EXAMPLE_PREFIX}`,
'./tests/testdata/test1.txt',
'',
false,
);
const expectedFile = `${EXAMPLE_PREFIX}/test1.txt`;
expect(uploadResponse[0][0].name).eql(expectedFile);
const filesInBucket = await getFilesInBucket();
expect(filesInBucket.length).eq(1);
expect(filesInBucket).to.have.members([expectedFile]);
});
it('uploads a single file with metadata', async function () {
const uploader = new Client();
const uploadResponse = await uploader.upload(
testBucket,
'./tests/testdata/test1.txt',
'',
true,
true,
true,
undefined,
100,
{
contentType: 'application/json',
metadata: {
foo: 'bar',
},
},
);
expect(uploadResponse[0][0].name).eql('test1.txt');
const filesInBucket = await getFilesInBucket();
expect(filesInBucket.length).eq(1);
expect(filesInBucket).to.have.members(['test1.txt']);
const metadata = uploadResponse[0][0].metadata;
expect(metadata.contentType).eql('application/json');
expect(Object.keys(metadata.metadata).length).eq(1);
expect(metadata.metadata.foo).eql('bar');
});
it('uploads a single file with prefix without resumeable', async function () {
const uploader = new Client();
const uploadResponse = await uploader.upload(
`${testBucket}/${EXAMPLE_PREFIX}`,
'./tests/testdata/test1.txt',
'',
false,
false,
);
const expectedFile = `${EXAMPLE_PREFIX}/test1.txt`;
expect(uploadResponse[0][0].name).eql(expectedFile);
const filesInBucket = await getFilesInBucket();
expect(filesInBucket.length).eq(1);
expect(filesInBucket).to.have.members([expectedFile]);
});
it('uploads a single file without extension', async function () {
const uploader = new Client();
const uploadResponse = await uploader.upload(
`${testBucket}/${EXAMPLE_PREFIX}`,
'./tests/testdata/testfile',
);
const expectedFile = `${EXAMPLE_PREFIX}/testfile`;
expect(uploadResponse[0][0].name).eql(expectedFile);
const filesInBucket = await getFilesInBucket();
expect(filesInBucket.length).eq(1);
expect(filesInBucket).to.have.members([expectedFile]);
});
it('uploads a single file with non ascii filename 🚀', async function () {
const uploader = new Client();
const uploadResponse = await uploader.upload(
`${testBucket}/${EXAMPLE_PREFIX}`,
'./tests/testdata/🚀',
);
const expectedFile = `${EXAMPLE_PREFIX}/🚀`;
expect(uploadResponse[0][0].name).eql(expectedFile);
const filesInBucket = await getFilesInBucket();
expect(filesInBucket.length).eq(1);
expect(filesInBucket).to.have.members([expectedFile]);
});
it('uploads a directory', async function () {
const uploader = new Client();
await uploader.upload(testBucket, EXAMPLE_DIR);
const filesInBucket = await getFilesInBucket();
expect(filesInBucket.length).eq(FILES_IN_DIR.length);
expect(filesInBucket).to.have.members(FILES_IN_DIR);
});
it('uploads a directory with prefix', async function () {
const uploader = new Client();
await uploader.upload(`${testBucket}/${EXAMPLE_PREFIX}`, EXAMPLE_DIR);
const filesInBucket = await getFilesInBucket();
const filesInDirWithPrefix = FILES_IN_DIR.map(
(f) => `${EXAMPLE_PREFIX}/${f}`,
);
expect(filesInBucket.length).eq(filesInDirWithPrefix.length);
expect(filesInBucket).to.have.members(filesInDirWithPrefix);
});
it('uploads a directory without parentDir', async function () {
const uploader = new Client();
await uploader.upload(testBucket, EXAMPLE_DIR, '', true, true, false);
const filesInBucket = await getFilesInBucket();
expect(filesInBucket.length).eq(FILES_IN_DIR_WITHOUT_PARENT_DIR.length);
expect(filesInBucket).to.have.members(FILES_IN_DIR_WITHOUT_PARENT_DIR);
});
it('uploads a directory with custom metadata', async function () {
const uploader = new Client();
await uploader.upload(
testBucket,
EXAMPLE_DIR,
'',
true,
true,
true,
undefined,
100,
{
metadata: {
foo: 'bar',
},
},
);
const filesInBucket = await getFilesInBucket();
expect(filesInBucket.length).eq(FILES_IN_DIR.length);
expect(filesInBucket).to.have.members(FILES_IN_DIR);
const [files] = await storage.bucket(testBucket).getFiles();
files.forEach((f) => {
switch (path.extname(f.name)) {
case '.json': {
expect(f.metadata.contentType).eql('application/json');
break;
}
case '.txt': {
expect(f.metadata.contentType).eql('text/plain');
break;
}
default: {
expect(f.metadata.contentType).to.be.undefined;
break;
}
}
expect(Object.keys(f.metadata.metadata).length).eq(1);
expect(f.metadata.metadata.foo).eql('bar');
});
});
it('uploads a directory with prefix without parentDir', async function () {
const uploader = new Client();
await uploader.upload(
`${testBucket}/${EXAMPLE_PREFIX}`,
EXAMPLE_DIR,
'',
true,
true,
false,
);
const filesInBucket = await getFilesInBucket();
const filesInDirWithPrefix = FILES_IN_DIR_WITHOUT_PARENT_DIR.map(
(f) => `${EXAMPLE_PREFIX}/${f}`,
);
expect(filesInBucket.length).eq(filesInDirWithPrefix.length);
expect(filesInBucket).to.have.members(filesInDirWithPrefix);
});
it('uploads a directory with globstar txt', async function () {
const uploader = new Client();
await uploader.upload(testBucket, EXAMPLE_DIR, '**/*.txt');
const filesInBucket = await getFilesInBucket();
expect(filesInBucket.length).eq(TXT_FILES_IN_DIR.length);
expect(filesInBucket).to.have.members(TXT_FILES_IN_DIR);
});
it('uploads a directory with globstar txt without parentDir', async function () {
const uploader = new Client();
await uploader.upload(
testBucket,
EXAMPLE_DIR,
'**/*.txt',
true,
true,
false,
);
const filesInBucket = await getFilesInBucket();
expect(filesInBucket.length).eq(TXT_FILES_IN_DIR_WITHOUT_PARENT_DIR.length);
expect(filesInBucket).to.have.members(TXT_FILES_IN_DIR_WITHOUT_PARENT_DIR);
});
it('uploads a directory with prefix with globstar txt without parentDir', async function () {
const uploader = new Client();
await uploader.upload(
`${testBucket}/${EXAMPLE_PREFIX}`,
EXAMPLE_DIR,
'**/*.txt',
true,
true,
false,
);
const filesInBucket = await getFilesInBucket();
const filesInDirWithPrefix = TXT_FILES_IN_DIR_WITHOUT_PARENT_DIR.map(
(f) => `${EXAMPLE_PREFIX}/${f}`,
);
expect(filesInBucket.length).eq(filesInDirWithPrefix.length);
expect(filesInBucket).to.have.members(filesInDirWithPrefix);
});
it('uploads a directory with top level txt glob', async function () {
const uploader = new Client();
await uploader.upload(testBucket, EXAMPLE_DIR, '*.txt');
const filesInBucket = await getFilesInBucket();
expect(filesInBucket.length).eq(TXT_FILES_IN_TOP_DIR.length);
expect(filesInBucket).to.have.members(TXT_FILES_IN_TOP_DIR);
});
it(`performance test with ${PERF_TEST_FILE_COUNT} files`, async function () {
if (isWin) {
this.skip();
}
tmp.setGracefulCleanup();
const { name: tmpDirPath } = tmp.dirSync();
for (let i = 0; i < PERF_TEST_FILE_COUNT; i++) {
const { name: tmpFilePath } = tmp.fileSync({
prefix: 'upload-act-test-',
postfix: '.txt',
dir: tmpDirPath,
});
fs.writeFileSync(tmpFilePath, path.posix.basename(tmpFilePath));
}
const uploader = new Client();
await uploader.upload(testBucket, tmpDirPath, '', true, false);
const filesInBucket = await getFilesInBucket();
expect(filesInBucket.length).eq(PERF_TEST_FILE_COUNT);
});
it('throws an error for a non existent dir', async function () {
if (isWin) {
this.skip();
}
try {
const uploader = new Client();
await uploader.upload(testBucket, EXAMPLE_DIR + '/nonexistent');
throw new Error(`error should have been thrown`);
} catch (err) {
expect(`${err}`).to.include('ENOENT');
}
});
it('throws an error for a non existent bucket', async function () {
try {
const uploader = new Client();
await uploader.upload(testBucket + 'nonexistent', EXAMPLE_FILE);
throw new Error(`error should have been thrown`);
} catch (err) {
expect(err).to.be;
}
});
}); | the_stack |
'use strict';
import {
ExtensionContext, workspace, Uri
} from 'vscode';
import * as path from 'path';
import * as fs from 'fs';
import opn = require('open');
import { DomainInfo, PlanStep, PlanStepCommitment, HappeningType, Plan, HelpfulAction, PddlWorkspace, VariableExpression } from 'pddl-workspace';
import { PlanFunctionEvaluator, Util as ValUtil } from 'ai-planning-val';
import { capitalize, CustomVisualization } from 'pddl-gantt';
import { SwimLane } from './SwimLane';
import { PlanReportSettings } from './PlanReportSettings';
import { VAL_STEP_PATH, CONF_PDDL, VALUE_SEQ_PATH, PLAN_REPORT_LINE_PLOT_GROUP_BY_LIFTED, DEFAULT_EPSILON, VAL_VERBOSE } from '../configuration/configuration';
import { ensureAbsoluteGlobalStoragePath, WebviewUriConverter } from '../utils';
import { handleValStepError } from '../planView/valStepErrorHandler';
const DIGITS = 4;
export class PlanReportGenerator {
planStepHeight = 20;
settings: Map<Plan, PlanReportSettings> = new Map();
constructor(private context: ExtensionContext, private options: PlanReportOptions) {
}
async export(plans: Plan[], planId: number): Promise<boolean> {
const html = await this.generateHtml(plans, planId);
const htmlFile = await ValUtil.toFile("plan-report", ".html", html);
const uri = Uri.parse("file://" + htmlFile);
opn(uri.toString());
return true; //env.openExternal(uri);
}
async generateHtml(plans: Plan[], planId = -1): Promise<string> {
const selectedPlan = planId < 0 ? plans.length - 1 : planId;
const maxCost = Math.max(...plans.map(plan => plan.metric ?? 0));
const planSelectors = plans.map((plan, planIndex) => this.renderPlanSelector(plan, planIndex, selectedPlan, maxCost)).join(" ");
const planSelectorsDisplayStyle = plans.length > 1 ? "flex" : "none";
const planHtmlArr: string[] = await Promise.all(plans.map(async (plan, planIndex) => await this.renderPlan(plan, planIndex, selectedPlan)));
const plansHtml = planHtmlArr.join("\n\n");
const plansChartsScript = this.createPlansChartsScript(plans);
const relativePath = path.join('views', 'planview');
const staticPath = path.join(relativePath, 'static');
const ganttStylesPath = path.join('node_modules', 'pddl-gantt', 'styles');
const html = `<!DOCTYPE html>
<head>
<title>Plan report</title>
<meta http-equiv="Content-Security-Policy"
content="default-src 'none'; img-src vscode-resource: https: data:; script-src vscode-resource: https://www.gstatic.com/charts/ 'unsafe-inline'; style-src vscode-resource: https://www.gstatic.com/charts/ 'unsafe-inline';"
/>
${await this.includeStyle(this.asAbsolutePath(ganttStylesPath, 'pddl-gantt.css'))}
${await this.includeStyle(this.asAbsolutePath(staticPath, 'plans.css'))}
${await this.includeScript(this.asAbsolutePath(path.join(relativePath, 'out'), 'plans.js'))}
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
${await this.includeScript(this.asAbsolutePath(staticPath, 'charts.js'))}
</head>
<body onload="scrollPlanSelectorIntoView(${selectedPlan})">
<div class="planSelectors" style="display: ${planSelectorsDisplayStyle};">${planSelectors}
</div>
${plansHtml}
${plansChartsScript}
</body>`;
return html;
}
asAbsolutePath(...paths: string[]): Uri {
let uri = Uri.file(this.context.asAbsolutePath(path.join(...paths)));
if (!this.options.selfContained && this.options.resourceUriConverter) {
uri = this.options.resourceUriConverter.asWebviewUri(uri);
}
return uri;
}
renderPlanSelector(plan: Plan, planIndex: number, selectedPlan: number, maxCost: number): string {
let className = "planSelector";
if (planIndex === selectedPlan) { className += " planSelector-selected"; }
const normalizedCost = (plan.cost ?? 0) / maxCost * 100;
const costRounded = plan.cost ? plan.cost.toFixed(DIGITS) : NaN;
const tooltip = `Plan #${planIndex}
Metric value / cost: ${plan.cost}
Makespan: ${plan.makespan}
States evaluated: ${plan.statesEvaluated}`;
return `
<div class="${className}" plan="${planIndex}" onclick="showPlan(${planIndex})"><span>${costRounded}</span>
<div class="planMetricBar" style="height: ${normalizedCost}px" title="${tooltip}"></div>
</div>`;
}
shouldDisplay(planStep: PlanStep, plan: Plan): boolean {
if (this.settings.has(plan)) {
return this.settings.get(plan)!.shouldDisplay(planStep);
}
else { return true; }
}
async renderPlan(plan: Plan, planIndex: number, selectedPlan: number): Promise<string> {
plan = capitalize(plan);
let planVisualizerPath: string | undefined;
if (plan.domain) {
const settings = await PlanReportSettings.load(plan.domain.fileUri);
planVisualizerPath = settings.getPlanVisualizerScript();
this.settings.set(plan, settings);
}
const styleDisplay = planIndex === selectedPlan ? "block" : "none";
let stateViz = '';
if (planVisualizerPath && plan.domain) {
const absPath = path.join(PddlWorkspace.getFolderPath(plan.domain.fileUri), planVisualizerPath);
try {
const planVisualizerText = (await workspace.fs.readFile(Uri.file(absPath))).toString();
const planVisualizer = eval(planVisualizerText) as CustomVisualization;
const width = this.options.displayWidth;
stateViz = planVisualizer.visualizePlanHtml?.(plan, width) ??
`<div class="hint">Only 'visualizePlanHtml' option is supported by the exported plan report currently. </div>`;
stateViz = `<div class="stateView" plan="${planIndex}" style="margin: 5px; width: ${width}px; display: ${styleDisplay};">${stateViz}</div>`;
}
catch (ex) {
console.warn(ex);
}
}
const stepsToDisplay = plan.steps
.filter(step => this.shouldDisplay(step, plan));
// split this to two batches and insert helpful actions in between
const planHeadSteps = stepsToDisplay
.filter(step => this.isPlanHeadStep(step, plan));
const relaxedPlanSteps = stepsToDisplay
.filter(step => !this.isPlanHeadStep(step, plan));
const oneIfHelpfulActionsPresent = (plan.hasHelpfulActions() ? 1 : 0);
const relaxedPlanStepIndexOffset = planHeadSteps.length + oneIfHelpfulActionsPresent;
const ganttChartHtml = planHeadSteps
.map((step, stepIndex) => this.renderGanttStep(step, stepIndex, plan, planIndex)).join("\n")
+ this.renderHelpfulActions(plan, planHeadSteps.length) + '\n'
+ relaxedPlanSteps
.map((step, stepIndex) => this.renderGanttStep(step, stepIndex + relaxedPlanStepIndexOffset, plan, planIndex)).join("\n");
const ganttChartHeight = (stepsToDisplay.length + oneIfHelpfulActionsPresent) * this.planStepHeight;
const ganttChart = ` <div class="gantt" plan="${planIndex}" style="margin: 5px; height: ${ganttChartHeight}px; display: ${styleDisplay};">
${ganttChartHtml}
</div>`;
let objectsHtml = '';
if (!this.options.disableSwimLaneView && plan.domain && plan.problem) {
const allTypeObjects = plan.domain.getConstants().merge(plan.problem.getObjectsTypeMap());
objectsHtml = plan.domain.getTypes()
.filter(type => type !== "object")
.map(type => {
const typeObjects = allTypeObjects.getTypeCaseInsensitive(type);
return typeObjects
? this.renderTypeSwimLanes(type, typeObjects.getObjects(), plan)
: '';
}).join("\n");
}
const swimLanes = ` <div class="resourceUtilization" plan="${planIndex}" style="display: ${styleDisplay};">
<table>
${objectsHtml}
</table>
</div>`;
const valStepPath = ensureAbsoluteGlobalStoragePath(workspace.getConfiguration(CONF_PDDL).get<string>(VAL_STEP_PATH), this.context);
const valueSeqPath = ensureAbsoluteGlobalStoragePath(workspace.getConfiguration(CONF_PDDL).get<string>(VALUE_SEQ_PATH), this.context);
const valVerbose = workspace.getConfiguration(CONF_PDDL).get<boolean>(VAL_VERBOSE, false);
let lineCharts = ` <div class="lineChart" plan="${planIndex}" style="display: ${styleDisplay};margin-top: 20px;">\n`;
let lineChartScripts = '';
if (!this.options.disableLinePlots && plan.domain && plan.problem) {
const groupByLifted = workspace.getConfiguration(CONF_PDDL).get<boolean>(PLAN_REPORT_LINE_PLOT_GROUP_BY_LIFTED, true);
const evaluator = new PlanFunctionEvaluator(plan, { valStepPath, valueSeqPath, shouldGroupByLifted: groupByLifted, verbose: valVerbose });
if (evaluator.isAvailable()) {
try {
const functionValues = await evaluator.evaluate();
functionValues.forEach((values, liftedVariable) => {
const chartDivId = `chart_${planIndex}_${liftedVariable.declaredName}`;
lineCharts += this.createLineChartDiv(chartDivId);
let chartTitleWithUnit = values.legend.length > 1 ? liftedVariable.name : liftedVariable.getFullName();
if (liftedVariable.getUnit()) { chartTitleWithUnit += ` [${liftedVariable.getUnit()}]`; }
lineChartScripts += ` drawChart('${chartDivId}', '${chartTitleWithUnit}', '', ${JSON.stringify(values.legend)}, ${JSON.stringify(values.values)}, ${this.options.displayWidth});\n`;
});
// add one plot for declared metric
for (let metricIndex = 0; metricIndex < plan.problem.getMetrics().length; metricIndex++) {
const metric = plan.problem.getMetrics()[metricIndex];
const metricExpression = metric.getExpression();
if (metricExpression instanceof VariableExpression) {
if (metricExpression.name === "total-time") {
continue;
}
}
const metricValues = await evaluator.evaluateExpression(metric.getExpression());
const chartDivId = `chart_${planIndex}_metric${metricIndex}`;
lineCharts += this.createLineChartDiv(chartDivId);
const chartTitleWithUnit = metric.getDocumentation()[metric.getDocumentation().length - 1];
lineChartScripts += ` drawChart('${chartDivId}', '${chartTitleWithUnit}', '', ['${/*unit?*/""}'], ${JSON.stringify(metricValues.values)}, ${this.options.displayWidth});\n`;
}
} catch (err) {
console.error(err);
const valStepPath = evaluator.getValStepPath();
if (valStepPath) {
handleValStepError(err, valStepPath);
}
}
}
else {
lineCharts += `<a href="command:pddl.downloadVal" title="Click to initiate download. You will be able to see what is being downloaded and from where...">Download plan validation tools (a.k.a. VAL) to see line plots of function values.</a>`;
}
}
lineCharts += `\n </div>`;
const hint = plan.domain && plan.problem ? '' : `<div class="hint"><b>Hint:</b> Problem file was not identified for this plan. Open the associated domain and problem and visualize the plan again.</div>`;
return `${this.options.selfContained || this.options.disableHamburgerMenu ? '' : this.renderMenu()}
${stateViz}
${ganttChart}
${swimLanes}
${lineCharts}
${hint}
<script>function drawPlan${planIndex}Charts(){\n${lineChartScripts}}</script>
`;
}
private createLineChartDiv(chartDivId: string): string {
return ` <div id="${chartDivId}" style="width: ${this.options.displayWidth + 100}px; height: ${Math.round(this.options.displayWidth / 2)}px"></div>\n`;
}
renderHelpfulActions(plan: Plan, planHeadLength: number): string {
if (plan.hasHelpfulActions()) {
const fromTop = planHeadLength * this.planStepHeight;
const fromLeft = this.toViewCoordinates(plan.now, plan);
const text = plan.helpfulActions?.map((helpfulAction, index) => this.renderHelpfulAction(index, helpfulAction)).join(', ');
return `\n <div class="planstep" style="top: ${fromTop}px; left: ${fromLeft}px; margin-top: 3px">▶ ${text}</div>`;
}
else {
return '';
}
}
renderHelpfulAction(index: number, helpfulAction: HelpfulAction): string {
const suffix = PlanReportGenerator.getActionSuffix(helpfulAction);
const beautifiedName = `${helpfulAction.actionName}<sub>${suffix}</sub>`;
return `${index + 1}. <a href="#" onclick="navigateToChildOfSelectedState('${helpfulAction.actionName}')">${beautifiedName}</a>`;
}
static getActionSuffix(helpfulAction: HelpfulAction): string {
switch (helpfulAction.kind) {
case HappeningType.START:
return '├';
case HappeningType.END:
return '┤';
}
return '';
}
isPlanHeadStep(step: PlanStep, plan: Plan): boolean {
return plan.now === undefined ||
step.commitment === PlanStepCommitment.Committed ||
step.commitment === PlanStepCommitment.EndsInRelaxedPlan;
}
createPlansChartsScript(plans: Plan[]): string {
const selectedPlan = plans.length - 1;
return ` <script>
google.charts.setOnLoadCallback(drawCharts);
function drawCharts() {
drawPlan${selectedPlan}Charts();
}
</script>`;
}
renderTypeSwimLanes(type: string, objects: string[], plan: Plan): string {
return ` <tr>
<th>${type}</th>
<th style="width: ${this.options.displayWidth}px"></th>
</tr>
`
+ objects.map(obj => this.renderObjectSwimLane(obj, plan)).join('\n');
}
renderObjectSwimLane(obj: string, plan: Plan): string {
const subLanes = new SwimLane(1);
const stepsInvolvingThisObject = plan.steps
.filter(step => this.shouldDisplay(step, plan))
.filter(step => this.shouldDisplayObject(step, obj, plan))
.map(step => this.renderSwimLameStep(step, plan, obj, subLanes))
.join('\n');
return ` <tr>
<td class="objectName"><div>${obj}</div></td>
<td style="position: relative; height: ${subLanes.laneCount() * this.planStepHeight}px;">
${stepsInvolvingThisObject}
</td>
</tr>
`;
}
private shouldDisplayObject(step: PlanStep, obj: string, plan: Plan): boolean {
if (!this.settings.has(plan)) {
return true;
}
const liftedAction = plan.domain?.getActions()
.find(a => a.getNameOrEmpty().toLowerCase() === step.getActionName().toLowerCase());
if (!liftedAction) {
console.debug('Unexpected plan action: ' + step.getActionName());
return true;
}
let fromArgument = 0;
do {
const indexOfArgument = step.getObjects().indexOf(obj, fromArgument);
fromArgument = indexOfArgument + 1;
if (indexOfArgument > -1 && indexOfArgument < liftedAction.parameters.length) {
const parameter = liftedAction.parameters[indexOfArgument];
const shouldIgnoreThisArgument = this.settings.get(plan)?.shouldIgnoreActionParameter(liftedAction.name ?? 'unnamed', parameter.name);
if (!shouldIgnoreThisArgument) {
return true;
}
}
} while (fromArgument > 0);
return false;
}
renderSwimLameStep(step: PlanStep, plan: Plan, thisObj: string, swimLanes: SwimLane): string {
const actionColor = this.getActionColor(step, plan.domain);
const leftOffset = this.computeLeftOffset(step, plan);
const width = this.computeWidth(step, plan) + this.computeRelaxedWidth(step, plan);
const objects = step.getObjects()
.map(obj => obj.toLowerCase() === thisObj.toLowerCase() ? '@' : obj)
.join(' ');
const availableLane = swimLanes.placeNext(leftOffset, width);
const fromTop = availableLane * this.planStepHeight + 1;
return `
<div class="resourceTaskTooltip" style="background-color: ${actionColor}; left: ${leftOffset}px; width: ${width}px; top: ${fromTop}px;">${step.getActionName()} ${objects}<span class="resourceTaskTooltipText">${this.toActionTooltip(step)}</span></div>`;
}
renderGanttStep(step: PlanStep, index: number, plan: Plan, planIndex: number): string {
const actionLink = this.toActionLink(step.getActionName(), plan);
const fromTop = index * this.planStepHeight;
const fromLeft = this.computeLeftOffset(step, plan);
const width = this.computeWidth(step, plan);
const widthRelaxed = this.computeRelaxedWidth(step, plan);
const actionColor = plan.domain ? this.getActionColor(step, plan.domain) : 'gray';
const actionIterations = step.getIterations() > 1 ? `${step.getIterations()}x` : '';
return ` <div class="planstep" id="plan${planIndex}step${index}" style="left: ${fromLeft}px; top: ${fromTop}px; "><div class="planstep-bar" title="${this.toActionTooltipPlain(step)}" style="width: ${width}px; background-color: ${actionColor}"></div><div class="planstep-bar-relaxed whitecarbon" style="width: ${widthRelaxed}px;"></div>${actionLink} ${step.getObjects().join(' ')} ${actionIterations}</div>`;
}
toActionLink(actionName: string, plan: Plan): string {
if (this.options.selfContained || !plan.domain) {
return actionName;
}
else {
const revealActionUri = encodeURI('command:pddl.revealAction?' + JSON.stringify([plan.domain.fileUri, actionName]));
return `<a href="${revealActionUri}" title="Reveal '${actionName}' action in the domain file">${actionName}</a>`;
}
}
toActionTooltip(step: PlanStep): string {
const durationRow = step.isDurative && step.getDuration() !== undefined ?
`<tr><td class="actionToolTip">Duration: </td><td class="actionToolTip">${step.getDuration()?.toFixed(DIGITS)}</td></tr>
<tr><td class="actionToolTip">End: </td><td class="actionToolTip">${step.getEndTime().toFixed(DIGITS)}</td></tr>` :
'';
return `<table><tr><th colspan="2" class="actionToolTip">${step.getActionName()} ${step.getObjects().join(' ')}</th></tr><tr><td class="actionToolTip" style="width:50px">Start:</td><td class="actionToolTip">${step.getStartTime().toFixed(DIGITS)}</td></tr>${durationRow}</table>`;
}
toActionTooltipPlain(step: PlanStep): string {
const durationRow = step.isDurative && step.getDuration() !== undefined ?
`Duration: ${step.getDuration()?.toFixed(DIGITS)}, End: ${step.getEndTime().toFixed(DIGITS)}` :
'';
const startTime = step.getStartTime() !== undefined ?
`, Start: ${step.getStartTime().toFixed(DIGITS)}` :
'';
return `${step.getActionName()} ${step.getObjects().join(' ')}${startTime} ${durationRow}`;
}
async includeStyle(uri: Uri): Promise<string> {
if (this.options.selfContained) {
const styleText = await fs.promises.readFile(uri.fsPath, { encoding: 'utf-8' });
return `<style>\n${styleText}\n</style>`;
} else {
return `<link rel = "stylesheet" type = "text/css" href = "${uri.toString()}" />`;
}
}
async includeScript(uri: Uri): Promise<string> {
if (this.options.selfContained) {
const scriptText = await fs.promises.readFile(uri.fsPath, { encoding: 'utf-8' });
return `<script>\n${scriptText}\n</script>`;
} else {
return `<script src="${uri.toString()}"></script>`;
}
}
computeLeftOffset(step: PlanStep, plan: Plan): number {
return this.toViewCoordinates(step.getStartTime(), plan);
}
renderMenu(): string {
return ` <div class="menu" onclick="postCommand('showMenu')" title="Click to show menu options...">☰</div>`;
}
computePlanHeadDuration(step: PlanStep, plan: Plan): number {
if (plan.now === undefined) { return step.getDuration() ?? DEFAULT_EPSILON; }
else if (step.getEndTime() < plan.now) {
if (step.commitment === PlanStepCommitment.Committed) { return step.getDuration() ?? DEFAULT_EPSILON; }
else { return 0; } // the end was not committed yet
}
else if (step.getStartTime() >= plan.now) { return 0; }
else {
switch (step.commitment) {
case PlanStepCommitment.Committed:
return step.getDuration() ?? DEFAULT_EPSILON;
case PlanStepCommitment.EndsInRelaxedPlan:
return 0;
case PlanStepCommitment.StartsInRelaxedPlan:
return plan.now - step.getStartTime();
default:
return 0; // should not happen
}
}
}
computeWidth(step: PlanStep, plan: Plan): number {
// remove the part of the planStep duration that belongs to the relaxed plan
const planHeadDuration = this.computePlanHeadDuration(step, plan);
return Math.max(1, this.toViewCoordinates(planHeadDuration, plan));
}
computeRelaxedWidth(step: PlanStep, plan: Plan): number {
const planHeadDuration = this.computePlanHeadDuration(step, plan);
// remove the part of the planStep duration that belongs to the planhead part
const relaxedDuration = (step.getDuration() ?? DEFAULT_EPSILON) - planHeadDuration;
return this.toViewCoordinates(relaxedDuration, plan);
}
/** Converts the _time_ argument to view coordinates */
toViewCoordinates(time: number | undefined, plan: Plan): number {
return (time ?? 0) / plan.makespan * this.options.displayWidth;
}
getActionColor(step: PlanStep, domain?: DomainInfo): string {
const actionIndex = domain?.getActions()
.findIndex(action => action.getNameOrEmpty().toLowerCase() === step.getActionName().toLowerCase());
if (actionIndex === undefined || actionIndex < 0) {
return 'gray';
}
else {
return this.colors[actionIndex * 7 % this.colors.length];
}
}
colors = ['#ff0000', '#ff4000', '#ff8000', '#ffbf00', '#ffff00', '#bfff00', '#80ff00', '#40ff00', '#00ff00', '#00ff40', '#00ff80', '#00ffbf', '#00ffff', '#00bfff', '#0080ff', '#0040ff', '#0000ff', '#4000ff', '#8000ff', '#bf00ff', '#ff00ff', '#ff00bf', '#ff0080', '#ff0040'];
}
export interface PlanReportOptions {
displayWidth: number;
selfContained?: boolean;
disableSwimLaneView?: boolean;
disableLinePlots?: boolean;
disableHamburgerMenu?: boolean;
resourceUriConverter?: WebviewUriConverter;
} | the_stack |
import { BuilderContext, targetFromTargetString } from '@angular-devkit/architect';
import { BuildTarget, CloudRunOptions, DeployBuilderSchema, FirebaseTools, FSHost } from '../interfaces';
import { existsSync, readFileSync, renameSync, writeFileSync } from 'fs';
import { copySync, removeSync } from 'fs-extra';
import { dirname, join } from 'path';
import { execSync, spawn, SpawnOptionsWithoutStdio } from 'child_process';
import { defaultFunction, defaultPackage, DEFAULT_FUNCTION_NAME, dockerfile } from './functions-templates';
import { satisfies } from 'semver';
import open from 'open';
import { SchematicsException } from '@angular-devkit/schematics';
import { firebaseFunctionsDependencies } from '../versions.json';
import * as winston from 'winston';
import tripleBeam from 'triple-beam';
import * as inquirer from 'inquirer';
const DEFAULT_EMULATOR_PORT = 5000;
const DEFAULT_EMULATOR_HOST = 'localhost';
const DEFAULT_CLOUD_RUN_OPTIONS: Partial<CloudRunOptions> = {
memory: '1Gi',
timeout: 60,
maxInstances: 'default',
maxConcurrency: 'default', // TODO tune concurrency for cloud run + angular
minInstances: 'default',
cpus: 1,
};
const spawnAsync = async (
command: string,
options?: SpawnOptionsWithoutStdio
) =>
new Promise<Buffer>((resolve, reject) => {
const [spawnCommand, ...args] = command.split(/\s+/);
const spawnProcess = spawn(spawnCommand, args, options);
const chunks: Buffer[] = [];
const errorChunks: Buffer[] = [];
spawnProcess.stdout.on('data', (data) => {
process.stdout.write(data.toString());
chunks.push(data);
});
spawnProcess.stderr.on('data', (data) => {
process.stderr.write(data.toString());
errorChunks.push(data);
});
spawnProcess.on('error', (error) => {
reject(error);
});
spawnProcess.on('close', (code) => {
if (code === 1) {
reject(Buffer.concat(errorChunks).toString());
return;
}
resolve(Buffer.concat(chunks));
});
});
export type DeployBuilderOptions = DeployBuilderSchema & Record<string, any>;
const escapeRegExp = (str: string) => str.replace(/[\-\[\]\/{}()*+?.\\^$|]/g, '\\$&');
const moveSync = (src: string, dest: string) => {
copySync(src, dest);
removeSync(src);
};
const deployToHosting = async (
firebaseTools: FirebaseTools,
context: BuilderContext,
workspaceRoot: string,
options: DeployBuilderOptions,
firebaseToken?: string,
) => {
// tslint:disable-next-line:no-non-null-assertion
const siteTarget = options.target ?? context.target!.project;
if (options.preview) {
await firebaseTools.serve({
port: DEFAULT_EMULATOR_PORT,
host: DEFAULT_EMULATOR_HOST,
targets: [`hosting:${siteTarget}`],
nonInteractive: true,
projectRoot: workspaceRoot,
});
const { deployProject } = await inquirer.prompt({
type: 'confirm',
name: 'deployProject',
message: 'Would you like to deploy your application to Firebase Hosting?'
});
if (!deployProject) { return; }
}
return await firebaseTools.deploy({
only: `hosting:${siteTarget}`,
cwd: workspaceRoot,
token: firebaseToken,
nonInteractive: true,
projectRoot: workspaceRoot,
});
};
const defaultFsHost: FSHost = {
moveSync,
writeFileSync,
renameSync,
copySync,
removeSync,
existsSync,
};
const findPackageVersion = (packageManager: string, name: string) => {
const match = execSync(`${packageManager} list ${name}`).toString().match(`[^|\s]${escapeRegExp(name)}[@| ][^\s]+(\s.+)?$`);
return match ? match[0].split(new RegExp(`${escapeRegExp(name)}[@| ]`))[1].split(/\s/)[0] : null;
};
const getPackageJson = (context: BuilderContext, workspaceRoot: string, options: DeployBuilderOptions, main?: string) => {
const dependencies: Record<string, string> = {};
const devDependencies: Record<string, string> = {};
if (options.ssr !== 'cloud-run') {
Object.keys(firebaseFunctionsDependencies).forEach(name => {
const { version, dev } = firebaseFunctionsDependencies[name];
(dev ? devDependencies : dependencies)[name] = version;
});
}
if (existsSync(join(workspaceRoot, 'angular.json'))) {
const angularJson = JSON.parse(readFileSync(join(workspaceRoot, 'angular.json')).toString());
const packageManager = angularJson.cli?.packageManager ?? 'npm';
// tslint:disable-next-line:no-non-null-assertion
const server = angularJson.projects[context.target!.project].architect.server;
const externalDependencies = server?.options?.externalDependencies || [];
const bundleDependencies = server?.options?.bundleDependencies ?? true;
if (bundleDependencies) {
externalDependencies.forEach(externalDependency => {
const packageVersion = findPackageVersion(packageManager, externalDependency);
if (packageVersion) { dependencies[externalDependency] = packageVersion; }
});
} else {
if (existsSync(join(workspaceRoot, 'package.json'))) {
const packageJson = JSON.parse(readFileSync(join(workspaceRoot, 'package.json')).toString());
Object.keys(packageJson.dependencies).forEach((dependency: string) => {
dependencies[dependency] = packageJson.dependencies[dependency];
});
} // TODO should we throw?
}
}
// TODO should we throw?
return defaultPackage(dependencies, devDependencies, options, main);
};
export const deployToFunction = async (
firebaseTools: FirebaseTools,
context: BuilderContext,
workspaceRoot: string,
staticBuildTarget: BuildTarget,
serverBuildTarget: BuildTarget,
options: DeployBuilderOptions,
firebaseToken?: string,
fsHost: FSHost = defaultFsHost
) => {
const staticBuildOptions = await context.getTargetOptions(targetFromTargetString(staticBuildTarget.name));
if (!staticBuildOptions.outputPath || typeof staticBuildOptions.outputPath !== 'string') {
throw new Error(
`Cannot read the output path option of the Angular project '${staticBuildTarget.name}' in angular.json`
);
}
const serverBuildOptions = await context.getTargetOptions(targetFromTargetString(serverBuildTarget.name));
if (!serverBuildOptions.outputPath || typeof serverBuildOptions.outputPath !== 'string') {
throw new Error(
`Cannot read the output path option of the Angular project '${serverBuildTarget.name}' in angular.json`
);
}
const staticOut = join(workspaceRoot, staticBuildOptions.outputPath);
const serverOut = join(workspaceRoot, serverBuildOptions.outputPath);
const functionsOut = options.outputPath ? join(workspaceRoot, options.outputPath) : dirname(serverOut);
const functionName = options.functionName || DEFAULT_FUNCTION_NAME;
const newStaticOut = join(functionsOut, staticBuildOptions.outputPath);
const newServerOut = join(functionsOut, serverBuildOptions.outputPath);
// New behavior vs. old
if (options.outputPath) {
fsHost.removeSync(functionsOut);
fsHost.copySync(staticOut, newStaticOut);
fsHost.copySync(serverOut, newServerOut);
} else {
fsHost.moveSync(staticOut, newStaticOut);
fsHost.moveSync(serverOut, newServerOut);
}
const packageJson = getPackageJson(context, workspaceRoot, options);
const nodeVersion = packageJson.engines.node;
if (!satisfies(process.versions.node, nodeVersion.toString())) {
context.logger.warn(
`⚠️ Your Node.js version (${process.versions.node}) does not match the Firebase Functions runtime (${nodeVersion}).`
);
}
const functionsPackageJsonPath = join(functionsOut, 'package.json');
fsHost.writeFileSync(
functionsPackageJsonPath,
JSON.stringify(packageJson, null, 2)
);
fsHost.writeFileSync(
join(functionsOut, 'index.js'),
defaultFunction(serverBuildOptions.outputPath, options, functionName)
);
if (!options.prerender) {
try {
fsHost.renameSync(
join(newStaticOut, 'index.html'),
join(newStaticOut, 'index.original.html')
);
} catch (e) { }
}
// tslint:disable-next-line:no-non-null-assertion
const siteTarget = options.target ?? context.target!.project;
if (fsHost.existsSync(functionsPackageJsonPath)) {
execSync(`npm --prefix ${functionsOut} install`);
} else {
console.error(`No package.json exists at ${functionsOut}`);
}
if (options.preview) {
await firebaseTools.serve({
port: DEFAULT_EMULATOR_PORT,
host: DEFAULT_EMULATOR_HOST,
targets: [`hosting:${siteTarget}`, `functions:${functionName}`],
nonInteractive: true,
projectRoot: workspaceRoot,
});
const { deployProject} = await inquirer.prompt({
type: 'confirm',
name: 'deployProject',
message: 'Would you like to deploy your application to Firebase Hosting & Cloud Functions?'
});
if (!deployProject) { return; }
}
return await firebaseTools.deploy({
only: `hosting:${siteTarget},functions:${functionName}`,
cwd: workspaceRoot,
token: firebaseToken,
nonInteractive: true,
projectRoot: workspaceRoot,
});
};
export const deployToCloudRun = async (
firebaseTools: FirebaseTools,
context: BuilderContext,
workspaceRoot: string,
staticBuildTarget: BuildTarget,
serverBuildTarget: BuildTarget,
options: DeployBuilderOptions,
firebaseToken?: string,
fsHost: FSHost = defaultFsHost
) => {
const staticBuildOptions = await context.getTargetOptions(targetFromTargetString(staticBuildTarget.name));
if (!staticBuildOptions.outputPath || typeof staticBuildOptions.outputPath !== 'string') {
throw new Error(
`Cannot read the output path option of the Angular project '${staticBuildTarget.name}' in angular.json`
);
}
const serverBuildOptions = await context.getTargetOptions(targetFromTargetString(serverBuildTarget.name));
if (!serverBuildOptions.outputPath || typeof serverBuildOptions.outputPath !== 'string') {
throw new Error(
`Cannot read the output path option of the Angular project '${serverBuildTarget.name}' in angular.json`
);
}
const staticOut = join(workspaceRoot, staticBuildOptions.outputPath);
const serverOut = join(workspaceRoot, serverBuildOptions.outputPath);
const cloudRunOut = options.outputPath ? join(workspaceRoot, options.outputPath) : join(dirname(serverOut), 'run');
const serviceId = options.functionName || DEFAULT_FUNCTION_NAME;
const newStaticOut = join(cloudRunOut, staticBuildOptions.outputPath);
const newServerOut = join(cloudRunOut, serverBuildOptions.outputPath);
// This is needed because in the server output there's a hardcoded dependency on $cwd/dist/browser,
// This assumes that we've deployed our application dist directory and we're running the server
// in the parent directory. To have this precondition, we move dist/browser to dist/dist/browser
// since the firebase function runs the server from dist.
fsHost.removeSync(cloudRunOut);
fsHost.copySync(staticOut, newStaticOut);
fsHost.copySync(serverOut, newServerOut);
const packageJson = getPackageJson(context, workspaceRoot, options, join(serverBuildOptions.outputPath, 'main.js'));
const nodeVersion = packageJson.engines.node;
if (!satisfies(process.versions.node, nodeVersion.toString())) {
context.logger.warn(
`⚠️ Your Node.js version (${process.versions.node}) does not match the Cloud Run runtime (${nodeVersion}).`
);
}
fsHost.writeFileSync(
join(cloudRunOut, 'package.json'),
JSON.stringify(packageJson, null, 2),
);
fsHost.writeFileSync(
join(cloudRunOut, 'Dockerfile'),
dockerfile(options)
);
if (!options.prerender) {
try {
fsHost.renameSync(
join(newStaticOut, 'index.html'),
join(newStaticOut, 'index.original.html')
);
} catch (e) { }
}
if (options.preview) {
throw new SchematicsException('Cloud Run preview not supported.');
}
const deployArguments: Array<any> = [];
const cloudRunOptions = options.cloudRunOptions || {};
Object.entries(DEFAULT_CLOUD_RUN_OPTIONS).forEach(([k, v]) => {
cloudRunOptions[k] ||= v;
});
// lean on the schema for validation (rather than sanitize)
if (cloudRunOptions.cpus) { deployArguments.push('--cpu', cloudRunOptions.cpus); }
if (cloudRunOptions.maxConcurrency) { deployArguments.push('--concurrency', cloudRunOptions.maxConcurrency); }
if (cloudRunOptions.maxInstances) { deployArguments.push('--max-instances', cloudRunOptions.maxInstances); }
if (cloudRunOptions.memory) { deployArguments.push('--memory', cloudRunOptions.memory); }
if (cloudRunOptions.minInstances) { deployArguments.push('--min-instances', cloudRunOptions.minInstances); }
if (cloudRunOptions.timeout) { deployArguments.push('--timeout', cloudRunOptions.timeout); }
if (cloudRunOptions.vpcConnector) { deployArguments.push('--vpc-connector', cloudRunOptions.vpcConnector); }
// TODO validate serviceId, firebaseProject, and vpcConnector both to limit errors and opp for injection
context.logger.info(`📦 Deploying to Cloud Run`);
await spawnAsync(`gcloud builds submit ${cloudRunOut} --tag gcr.io/${options.firebaseProject}/${serviceId} --project ${options.firebaseProject} --quiet`);
await spawnAsync(`gcloud run deploy ${serviceId} --image gcr.io/${options.firebaseProject}/${serviceId} --project ${options.firebaseProject} ${deployArguments.join(' ')} --platform managed --allow-unauthenticated --region=${options.region} --quiet`);
// tslint:disable-next-line:no-non-null-assertion
const siteTarget = options.target ?? context.target!.project;
// TODO deploy cloud run
return await firebaseTools.deploy({
only: `hosting:${siteTarget}`,
cwd: workspaceRoot,
token: firebaseToken,
nonInteractive: true,
projectRoot: workspaceRoot,
});
};
export default async function deploy(
firebaseTools: FirebaseTools,
context: BuilderContext,
staticBuildTarget: BuildTarget,
serverBuildTarget: BuildTarget | undefined,
prerenderBuildTarget: BuildTarget | undefined,
firebaseProject: string,
options: DeployBuilderOptions,
firebaseToken?: string,
) {
if (!firebaseToken) {
await firebaseTools.login();
const user = await firebaseTools.login({ projectRoot: context.workspaceRoot });
console.log(`Logged into Firebase as ${user.email}.`);
}
if (prerenderBuildTarget) {
const run = await context.scheduleTarget(
targetFromTargetString(prerenderBuildTarget.name),
prerenderBuildTarget.options
);
await run.result;
} else {
if (!context.target) {
throw new Error('Cannot execute the build target');
}
context.logger.info(`📦 Building "${context.target.project}"`);
const builders = [
context.scheduleTarget(
targetFromTargetString(staticBuildTarget.name),
staticBuildTarget.options
).then(run => run.result)
];
if (serverBuildTarget) {
builders.push(context.scheduleTarget(
targetFromTargetString(serverBuildTarget.name),
serverBuildTarget.options
).then(run => run.result));
}
await Promise.all(builders);
}
try {
await firebaseTools.use(firebaseProject, {
project: firebaseProject,
projectRoot: context.workspaceRoot,
});
} catch (e) {
throw new Error(`Cannot select firebase project '${firebaseProject}'`);
}
options.firebaseProject = firebaseProject;
const logger = new winston.transports.Console({
level: 'info',
format: winston.format.printf((info) => {
const emulator = info[tripleBeam.SPLAT as any]?.[1]?.metadata?.emulator;
const text = info[tripleBeam.SPLAT as any]?.[0];
if (text?.replace) {
const plainText = text.replace(/\x1B\[([0-9]{1,2}(;[0-9]{1,2})?)?[mGK]/g, '');
if (emulator?.name === 'hosting' && plainText.startsWith('Local server: ')) {
open(plainText.split(': ')[1]);
}
}
return [info.message, ...(info[tripleBeam.SPLAT as any] || [])]
.filter((chunk) => typeof chunk === 'string')
.join(' ');
})
});
firebaseTools.logger.logger.add(logger);
if (serverBuildTarget) {
if (options.ssr === 'cloud-run') {
await deployToCloudRun(
firebaseTools,
context,
context.workspaceRoot,
staticBuildTarget,
serverBuildTarget,
options,
firebaseToken,
);
} else {
await deployToFunction(
firebaseTools,
context,
context.workspaceRoot,
staticBuildTarget,
serverBuildTarget,
options,
firebaseToken,
);
}
} else {
await deployToHosting(
firebaseTools,
context,
context.workspaceRoot,
options,
firebaseToken,
);
}
} | the_stack |
import {
addFileToProjectContents,
getContentsTreeFileFromString,
ProjectContentTreeRoot,
walkContentsTree,
} from '../../components/assets'
import { EditorModel } from '../../components/editor/action-types'
import { updateFile } from '../../components/editor/actions/action-creators'
import { EditorState, StoryboardFilePath } from '../../components/editor/store/editor-state'
import {
Compare,
compareCompose,
compareField,
compareIfIs,
compareOn,
comparePrimitive,
} from '../../utils/compare'
import {
emptyComments,
isUtopiaJSXComponent,
JSXElement,
unparsedCode,
UtopiaJSXComponent,
utopiaJSXComponent,
} from '../shared/element-template'
import { forEachValue } from '../shared/object-utils'
import { forceNotNull } from '../shared/optional-utils'
import {
EmptyExportsDetail,
ExportDetail,
exportVariable,
exportVariables,
forEachParseSuccess,
importAlias,
isParsedTextFile,
isParseSuccess,
isTextFile,
mergeExportsDetail,
parseSuccess,
ParseSuccess,
RevisionsState,
textFile,
textFileContents,
} from '../shared/project-file-types'
import { addImport } from '../workers/common/project-file-utils'
import {
BakedInStoryboardUID,
BakedInStoryboardVariableName,
createSceneFromComponent,
createStoryboardElement,
} from './scene-utils'
const PossiblyMainComponentNames: Array<string> = ['App', 'Application', 'Main']
interface DefaultComponentToImport {
type: 'DEFAULT_COMPONENT_TO_IMPORT'
path: string
}
interface NamedComponentToImport {
type: 'NAMED_COMPONENT_TO_IMPORT'
path: string
possibleMainComponentName: boolean
toImport: string
}
interface UnexportedRenderedComponent {
type: 'UNEXPORTED_RENDERED_COMPONENT'
path: string
elementName: string
}
function defaultComponentToImport(path: string): DefaultComponentToImport {
return {
type: 'DEFAULT_COMPONENT_TO_IMPORT',
path: path,
}
}
function namedComponentToImport(
path: string,
possibleMainComponentName: boolean,
toImport: string,
): NamedComponentToImport {
return {
type: 'NAMED_COMPONENT_TO_IMPORT',
path: path,
possibleMainComponentName: possibleMainComponentName,
toImport: toImport,
}
}
function unexportedRenderedComponent(
path: string,
elementName: string,
): UnexportedRenderedComponent {
return {
type: 'UNEXPORTED_RENDERED_COMPONENT',
path: path,
elementName: elementName,
}
}
type ComponentToImport =
| DefaultComponentToImport
| NamedComponentToImport
| UnexportedRenderedComponent
function isDefaultComponentToImport(
toImport: ComponentToImport,
): toImport is DefaultComponentToImport {
return toImport.type === 'DEFAULT_COMPONENT_TO_IMPORT'
}
function isNamedComponentToImport(toImport: ComponentToImport): toImport is NamedComponentToImport {
return toImport.type === 'NAMED_COMPONENT_TO_IMPORT'
}
function isUnexportedRenderedComponent(
toImport: ComponentToImport,
): toImport is UnexportedRenderedComponent {
return toImport.type === 'UNEXPORTED_RENDERED_COMPONENT'
}
const compareDefaultComponentToImport: Compare<DefaultComponentToImport> = compareCompose(
compareOn((toImport) => toImport.path.split('/').length, comparePrimitive),
)
const compareNamedComponentToImport: Compare<NamedComponentToImport> = compareCompose(
compareOn((toImport) => toImport.path.split('/').length, comparePrimitive),
compareField('possibleMainComponentName', comparePrimitive),
compareField('toImport', comparePrimitive),
)
const compareUnexportedRenderedComponent: Compare<UnexportedRenderedComponent> = compareCompose(
compareOn((toImport) => toImport.path.split('/').length, comparePrimitive),
compareOn(
(toImport) => PossiblyMainComponentNames.includes(toImport.elementName),
comparePrimitive,
),
)
// Highest priority last.
const componentToImportTypesInPriorityOrder: Array<ComponentToImport['type']> = [
'NAMED_COMPONENT_TO_IMPORT',
'DEFAULT_COMPONENT_TO_IMPORT',
'UNEXPORTED_RENDERED_COMPONENT',
]
const compareComponentToImport: Compare<ComponentToImport> = compareCompose(
compareOn((toImport) => toImport.path.split('/').length, comparePrimitive),
compareIfIs(isDefaultComponentToImport, compareDefaultComponentToImport),
compareIfIs(isNamedComponentToImport, compareNamedComponentToImport),
compareIfIs(isUnexportedRenderedComponent, compareUnexportedRenderedComponent),
compareOn(
(toImport) => componentToImportTypesInPriorityOrder.indexOf(toImport.type),
comparePrimitive,
),
)
export function addStoryboardFileToProject(editorModel: EditorModel): EditorModel | null {
const storyboardFile = getContentsTreeFileFromString(
editorModel.projectContents,
StoryboardFilePath,
)
if (storyboardFile == null) {
let currentImportCandidate: ComponentToImport | null = null
function updateCandidate(importCandidate: ComponentToImport): void {
if (currentImportCandidate == null) {
currentImportCandidate = importCandidate
} else {
if (compareComponentToImport(importCandidate, currentImportCandidate) > 0) {
currentImportCandidate = importCandidate
}
}
}
walkContentsTree(editorModel.projectContents, (fullPath, file) => {
if (isParsedTextFile(file)) {
// For those successfully parsed files, we want to search all of the components.
forEachParseSuccess((success) => {
let namedExportKeys: Array<string> = []
for (const exportDetail of success.exportsDetail) {
switch (exportDetail.type) {
case 'EXPORT_DEFAULT_FUNCTION_OR_CLASS':
updateCandidate(defaultComponentToImport(fullPath))
break
case 'EXPORT_CLASS':
{
const possibleMainComponentName = PossiblyMainComponentNames.includes(
exportDetail.className,
)
updateCandidate(
namedComponentToImport(
fullPath,
possibleMainComponentName,
exportDetail.className,
),
)
}
break
case 'EXPORT_FUNCTION':
{
const possibleMainComponentName = PossiblyMainComponentNames.includes(
exportDetail.functionName,
)
updateCandidate(
namedComponentToImport(
fullPath,
possibleMainComponentName,
exportDetail.functionName,
),
)
}
break
case 'EXPORT_VARIABLES':
case 'EXPORT_DESTRUCTURED_ASSIGNMENT':
case 'REEXPORT_VARIABLES':
{
for (const exportVar of exportDetail.variables) {
const exportName = exportVar.variableAlias ?? exportVar.variableName
if (exportName !== 'default') {
namedExportKeys.push(exportName)
const possibleMainComponentName = PossiblyMainComponentNames.includes(
exportName,
)
updateCandidate(
namedComponentToImport(fullPath, possibleMainComponentName, exportName),
)
}
}
}
break
case 'EXPORT_IDENTIFIER':
{
const possibleMainComponentName = PossiblyMainComponentNames.includes(
exportDetail.name,
)
updateCandidate(
namedComponentToImport(fullPath, possibleMainComponentName, exportDetail.name),
)
}
break
case 'REEXPORT_WILDCARD':
break
case 'EXPORT_VARIABLES_WITH_MODIFIER':
{
for (const exportName of exportDetail.variables) {
if (exportName !== 'default') {
namedExportKeys.push(exportName)
const possibleMainComponentName = PossiblyMainComponentNames.includes(
exportName,
)
updateCandidate(
namedComponentToImport(fullPath, possibleMainComponentName, exportName),
)
}
}
}
break
default:
const _exhaustiveCheck: never = exportDetail
throw new Error(`Unhandled type ${JSON.stringify(exportDetail)}`)
}
}
}, file.fileContents.parsed)
}
})
if (currentImportCandidate == null) {
return null
} else {
return addStoryboardFileForComponent(currentImportCandidate, editorModel)
}
} else {
return null
}
}
function addStoryboardFileForComponent(
createFileWithComponent: ComponentToImport,
editorModel: EditorState,
): EditorState {
// Add import of storyboard and scene components.
let imports = addImport(StoryboardFilePath, 'react', null, [], 'React', {})
imports = addImport(
StoryboardFilePath,
'utopia-api',
null,
[importAlias('Storyboard'), importAlias('Scene')],
null,
imports,
)
// Create the storyboard variable.
let sceneElement: JSXElement
let updatedProjectContents: ProjectContentTreeRoot = editorModel.projectContents
switch (createFileWithComponent.type) {
case 'NAMED_COMPONENT_TO_IMPORT':
sceneElement = createSceneFromComponent(
StoryboardFilePath,
createFileWithComponent.toImport,
'scene-1',
)
imports = addImport(
StoryboardFilePath,
createFileWithComponent.path,
null,
[importAlias(createFileWithComponent.toImport)],
null,
imports,
)
break
case 'DEFAULT_COMPONENT_TO_IMPORT':
sceneElement = createSceneFromComponent(StoryboardFilePath, 'StoryboardComponent', 'scene-1')
imports = addImport(
StoryboardFilePath,
createFileWithComponent.path,
'StoryboardComponent',
[],
null,
imports,
)
break
case 'UNEXPORTED_RENDERED_COMPONENT':
sceneElement = createSceneFromComponent(
StoryboardFilePath,
createFileWithComponent.elementName,
'scene-1',
)
imports = addImport(
StoryboardFilePath,
createFileWithComponent.path,
null,
[importAlias(createFileWithComponent.elementName)],
null,
imports,
)
// Modify the targeted file to export the component we're interested in.
const fileToModify = forceNotNull(
`Unable to find file at ${createFileWithComponent.path}`,
getContentsTreeFileFromString(updatedProjectContents, createFileWithComponent.path),
)
if (isTextFile(fileToModify)) {
if (isParseSuccess(fileToModify.fileContents.parsed)) {
const currentSuccess: ParseSuccess = fileToModify.fileContents.parsed
const updatedExports = mergeExportsDetail(currentSuccess.exportsDetail, [
exportVariables([exportVariable(createFileWithComponent.elementName, null)]),
])
const updatedParseSuccess = parseSuccess(
currentSuccess.imports,
currentSuccess.topLevelElements,
currentSuccess.highlightBounds,
currentSuccess.jsxFactoryFunction,
currentSuccess.combinedTopLevelArbitraryBlock,
updatedExports,
)
const updatedContents = textFileContents(
fileToModify.fileContents.code,
updatedParseSuccess,
RevisionsState.ParsedAhead,
)
const updatedTextFile = textFile(
updatedContents,
fileToModify.lastSavedContents,
updatedParseSuccess,
fileToModify.lastRevisedTime,
)
updatedProjectContents = addFileToProjectContents(
updatedProjectContents,
createFileWithComponent.path,
updatedTextFile,
)
} else {
throw new Error(`Unexpectedly ${createFileWithComponent.path} is not a parse success.`)
}
} else {
throw new Error(`${createFileWithComponent.path} was not a text file as expected.`)
}
break
default:
const _exhaustiveCheck: never = createFileWithComponent
throw new Error(`Unhandled type ${JSON.stringify(createFileWithComponent)}`)
}
const storyboardElement = createStoryboardElement([sceneElement], BakedInStoryboardUID)
const storyboardComponent = utopiaJSXComponent(
BakedInStoryboardVariableName,
false,
'var',
'block',
null,
[],
storyboardElement,
null,
false,
emptyComments,
)
// Add the component import.
// Create the file.
const success = parseSuccess(
imports,
[unparsedCode('\n\n'), storyboardComponent],
{},
null,
null,
[exportVariables([exportVariable(BakedInStoryboardVariableName, null)])],
)
const storyboardFileContents = textFile(
textFileContents('', success, RevisionsState.ParsedAhead),
null,
success,
0,
)
// Update the model.
updatedProjectContents = addFileToProjectContents(
updatedProjectContents,
StoryboardFilePath,
storyboardFileContents,
)
return {
...editorModel,
projectContents: updatedProjectContents,
}
} | the_stack |
import { RGBA, Color } from './color';
import { ansiColorIdentifiers } from './colorMap';
import { linkify } from './linkify';
export function handleANSIOutput(text: string): HTMLSpanElement {
let workspaceFolder = undefined;
const root: HTMLSpanElement = document.createElement('span');
const textLength: number = text.length;
let styleNames: string[] = [];
let customFgColor: RGBA | string | undefined;
let customBgColor: RGBA | string | undefined;
let customUnderlineColor: RGBA | string | undefined;
let colorsInverted: boolean = false;
let currentPos: number = 0;
let buffer: string = '';
while (currentPos < textLength) {
let sequenceFound: boolean = false;
// Potentially an ANSI escape sequence.
// See http://ascii-table.com/ansi-escape-sequences.php & https://en.wikipedia.org/wiki/ANSI_escape_code
if (text.charCodeAt(currentPos) === 27 && text.charAt(currentPos + 1) === '[') {
const startPos: number = currentPos;
currentPos += 2; // Ignore 'Esc[' as it's in every sequence.
let ansiSequence: string = '';
while (currentPos < textLength) {
const char: string = text.charAt(currentPos);
ansiSequence += char;
currentPos++;
// Look for a known sequence terminating character.
if (char.match(/^[ABCDHIJKfhmpsu]$/)) {
sequenceFound = true;
break;
}
}
if (sequenceFound) {
// Flush buffer with previous styles.
appendStylizedStringToContainer(root, buffer, styleNames, workspaceFolder, customFgColor, customBgColor, customUnderlineColor);
buffer = '';
/*
* Certain ranges that are matched here do not contain real graphics rendition sequences. For
* the sake of having a simpler expression, they have been included anyway.
*/
if (ansiSequence.match(/^(?:[34][0-8]|9[0-7]|10[0-7]|[0-9]|2[1-5,7-9]|[34]9|5[8,9]|1[0-9])(?:;[349][0-7]|10[0-7]|[013]|[245]|[34]9)?(?:;[012]?[0-9]?[0-9])*;?m$/)) {
const styleCodes: number[] = ansiSequence.slice(0, -1) // Remove final 'm' character.
.split(';') // Separate style codes.
.filter(elem => elem !== '') // Filter empty elems as '34;m' -> ['34', ''].
.map(elem => parseInt(elem, 10)); // Convert to numbers.
if (styleCodes[0] === 38 || styleCodes[0] === 48 || styleCodes[0] === 58) {
// Advanced color code - can't be combined with formatting codes like simple colors can
// Ignores invalid colors and additional info beyond what is necessary
const colorType = (styleCodes[0] === 38) ? 'foreground' : ((styleCodes[0] === 48) ? 'background' : 'underline');
if (styleCodes[1] === 5) {
set8BitColor(styleCodes, colorType);
} else if (styleCodes[1] === 2) {
set24BitColor(styleCodes, colorType);
}
} else {
setBasicFormatters(styleCodes);
}
} else {
// Unsupported sequence so simply hide it.
}
} else {
currentPos = startPos;
}
}
if (sequenceFound === false) {
buffer += text.charAt(currentPos);
currentPos++;
}
}
// Flush remaining text buffer if not empty.
if (buffer) {
appendStylizedStringToContainer(root, buffer, styleNames, workspaceFolder, customFgColor, customBgColor, customUnderlineColor);
}
return root;
/**
* Change the foreground or background color by clearing the current color
* and adding the new one.
* @param colorType If `'foreground'`, will change the foreground color, if
* `'background'`, will change the background color, and if `'underline'`
* will set the underline color.
* @param color Color to change to. If `undefined` or not provided,
* will clear current color without adding a new one.
*/
function changeColor(colorType: 'foreground' | 'background' | 'underline', color?: RGBA | string | undefined): void {
if (colorType === 'foreground') {
customFgColor = color;
} else if (colorType === 'background') {
customBgColor = color;
} else if (colorType === 'underline') {
customUnderlineColor = color;
}
styleNames = styleNames.filter(style => style !== `code-${colorType}-colored`);
if (color !== undefined) {
styleNames.push(`code-${colorType}-colored`);
}
}
/**
* Swap foreground and background colors. Used for color inversion. Caller should check
* [] flag to make sure it is appropriate to turn ON or OFF (if it is already inverted don't call
*/
function reverseForegroundAndBackgroundColors(): void {
const oldFgColor: RGBA | string | undefined = customFgColor;
changeColor('foreground', customBgColor);
changeColor('background', oldFgColor);
}
/**
* Calculate and set basic ANSI formatting. Supports ON/OFF of bold, italic, underline,
* double underline, crossed-out/strikethrough, overline, dim, blink, rapid blink,
* reverse/invert video, hidden, superscript, subscript and alternate font codes,
* clearing/resetting of foreground, background and underline colors,
* setting normal foreground and background colors, and bright foreground and
* background colors. Not to be used for codes containing advanced colors.
* Will ignore invalid codes.
* @param styleCodes Array of ANSI basic styling numbers, which will be
* applied in order. New colors and backgrounds clear old ones; new formatting
* does not.
* @see {@link https://en.wikipedia.org/wiki/ANSI_escape_code#SGR }
*/
function setBasicFormatters(styleCodes: number[]): void {
for (const code of styleCodes) {
switch (code) {
case 0: { // reset (everything)
styleNames = [];
customFgColor = undefined;
customBgColor = undefined;
break;
}
case 1: { // bold
styleNames = styleNames.filter(style => style !== `code-bold`);
styleNames.push('code-bold');
break;
}
case 2: { // dim
styleNames = styleNames.filter(style => style !== `code-dim`);
styleNames.push('code-dim');
break;
}
case 3: { // italic
styleNames = styleNames.filter(style => style !== `code-italic`);
styleNames.push('code-italic');
break;
}
case 4: { // underline
styleNames = styleNames.filter(style => (style !== `code-underline` && style !== `code-double-underline`));
styleNames.push('code-underline');
break;
}
case 5: { // blink
styleNames = styleNames.filter(style => style !== `code-blink`);
styleNames.push('code-blink');
break;
}
case 6: { // rapid blink
styleNames = styleNames.filter(style => style !== `code-rapid-blink`);
styleNames.push('code-rapid-blink');
break;
}
case 7: { // invert foreground and background
if (!colorsInverted) {
colorsInverted = true;
reverseForegroundAndBackgroundColors();
}
break;
}
case 8: { // hidden
styleNames = styleNames.filter(style => style !== `code-hidden`);
styleNames.push('code-hidden');
break;
}
case 9: { // strike-through/crossed-out
styleNames = styleNames.filter(style => style !== `code-strike-through`);
styleNames.push('code-strike-through');
break;
}
case 10: { // normal default font
styleNames = styleNames.filter(style => !style.startsWith('code-font'));
break;
}
case 11: case 12: case 13: case 14: case 15: case 16: case 17: case 18: case 19: case 20: { // font codes (and 20 is 'blackletter' font code)
styleNames = styleNames.filter(style => !style.startsWith('code-font'));
styleNames.push(`code-font-${code - 10}`);
break;
}
case 21: { // double underline
styleNames = styleNames.filter(style => (style !== `code-underline` && style !== `code-double-underline`));
styleNames.push('code-double-underline');
break;
}
case 22: { // normal intensity (bold off and dim off)
styleNames = styleNames.filter(style => (style !== `code-bold` && style !== `code-dim`));
break;
}
case 23: { // Neither italic or blackletter (font 10)
styleNames = styleNames.filter(style => (style !== `code-italic` && style !== `code-font-10`));
break;
}
case 24: { // not underlined (Neither singly nor doubly underlined)
styleNames = styleNames.filter(style => (style !== `code-underline` && style !== `code-double-underline`));
break;
}
case 25: { // not blinking
styleNames = styleNames.filter(style => (style !== `code-blink` && style !== `code-rapid-blink`));
break;
}
case 27: { // not reversed/inverted
if (colorsInverted) {
colorsInverted = false;
reverseForegroundAndBackgroundColors();
}
break;
}
case 28: { // not hidden (reveal)
styleNames = styleNames.filter(style => style !== `code-hidden`);
break;
}
case 29: { // not crossed-out
styleNames = styleNames.filter(style => style !== `code-strike-through`);
break;
}
case 53: { // overlined
styleNames = styleNames.filter(style => style !== `code-overline`);
styleNames.push('code-overline');
break;
}
case 55: { // not overlined
styleNames = styleNames.filter(style => style !== `code-overline`);
break;
}
case 39: { // default foreground color
changeColor('foreground', undefined);
break;
}
case 49: { // default background color
changeColor('background', undefined);
break;
}
case 59: { // default underline color
changeColor('underline', undefined);
break;
}
case 73: { // superscript
styleNames = styleNames.filter(style => (style !== `code-superscript` && style !== `code-subscript`));
styleNames.push('code-superscript');
break;
}
case 74: { // subscript
styleNames = styleNames.filter(style => (style !== `code-superscript` && style !== `code-subscript`));
styleNames.push('code-subscript');
break;
}
case 75: { // neither superscript or subscript
styleNames = styleNames.filter(style => (style !== `code-superscript` && style !== `code-subscript`));
break;
}
default: {
setBasicColor(code);
break;
}
}
}
}
/**
* Calculate and set styling for complicated 24-bit ANSI color codes.
* @param styleCodes Full list of integer codes that make up the full ANSI
* sequence, including the two defining codes and the three RGB codes.
* @param colorType If `'foreground'`, will set foreground color, if
* `'background'`, will set background color, and if it is `'underline'`
* will set the underline color.
* @see {@link https://en.wikipedia.org/wiki/ANSI_escape_code#24-bit }
*/
function set24BitColor(styleCodes: number[], colorType: 'foreground' | 'background' | 'underline'): void {
if (styleCodes.length >= 5 &&
styleCodes[2] >= 0 && styleCodes[2] <= 255 &&
styleCodes[3] >= 0 && styleCodes[3] <= 255 &&
styleCodes[4] >= 0 && styleCodes[4] <= 255) {
const customColor = new RGBA(styleCodes[2], styleCodes[3], styleCodes[4]);
changeColor(colorType, customColor);
}
}
/**
* Calculate and set styling for advanced 8-bit ANSI color codes.
* @param styleCodes Full list of integer codes that make up the ANSI
* sequence, including the two defining codes and the one color code.
* @param colorType If `'foreground'`, will set foreground color, if
* `'background'`, will set background color and if it is `'underline'`
* will set the underline color.
* @see {@link https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit }
*/
function set8BitColor(styleCodes: number[], colorType: 'foreground' | 'background' | 'underline'): void {
let colorNumber = styleCodes[2];
const color = calcANSI8bitColor(colorNumber);
if (color) {
changeColor(colorType, color);
} else if (colorNumber >= 0 && colorNumber <= 15) {
if (colorType === 'underline') {
// for underline colors we just decode the 0-15 color number to theme color, set and return
changeColor(colorType, ansiColorIdentifiers[colorNumber].colorValue);
return;
}
// Need to map to one of the four basic color ranges (30-37, 90-97, 40-47, 100-107)
colorNumber += 30;
if (colorNumber >= 38) {
// Bright colors
colorNumber += 52;
}
if (colorType === 'background') {
colorNumber += 10;
}
setBasicColor(colorNumber);
}
}
/**
* Calculate and set styling for basic bright and dark ANSI color codes. Uses
* theme colors if available. Automatically distinguishes between foreground
* and background colors; does not support color-clearing codes 39 and 49.
* @param styleCode Integer color code on one of the following ranges:
* [30-37, 90-97, 40-47, 100-107]. If not on one of these ranges, will do
* nothing.
*/
function setBasicColor(styleCode: number): void {
// const theme = themeService.getColorTheme();
let colorType: 'foreground' | 'background' | undefined;
let colorIndex: number | undefined;
if (styleCode >= 30 && styleCode <= 37) {
colorIndex = styleCode - 30;
colorType = 'foreground';
} else if (styleCode >= 90 && styleCode <= 97) {
colorIndex = (styleCode - 90) + 8; // High-intensity (bright)
colorType = 'foreground';
} else if (styleCode >= 40 && styleCode <= 47) {
colorIndex = styleCode - 40;
colorType = 'background';
} else if (styleCode >= 100 && styleCode <= 107) {
colorIndex = (styleCode - 100) + 8; // High-intensity (bright)
colorType = 'background';
}
if (colorIndex !== undefined && colorType) {
changeColor(colorType, ansiColorIdentifiers[colorIndex]?.colorValue);
}
}
}
export function appendStylizedStringToContainer(
root: HTMLElement,
stringContent: string,
cssClasses: string[],
workspaceFolder: string | undefined,
customTextColor?: RGBA | string,
customBackgroundColor?: RGBA | string,
customUnderlineColor?: RGBA | string
): void {
if (!root || !stringContent) {
return;
}
const container = linkify(stringContent, true, workspaceFolder);
container.className = cssClasses.join(' ');
if (customTextColor) {
container.style.color = typeof customTextColor === 'string' ? customTextColor : Color.Format.CSS.formatRGB(new Color(customTextColor));
}
if (customBackgroundColor) {
container.style.backgroundColor = typeof customBackgroundColor === 'string' ? customBackgroundColor : Color.Format.CSS.formatRGB(new Color(customBackgroundColor));
}
if (customUnderlineColor) {
container.style.textDecorationColor = typeof customUnderlineColor === 'string' ? customUnderlineColor : Color.Format.CSS.formatRGB(new Color(customUnderlineColor));
}
root.appendChild(container);
}
/**
* Calculate the color from the color set defined in the ANSI 8-bit standard.
* Standard and high intensity colors are not defined in the standard as specific
* colors, so these and invalid colors return `undefined`.
* @see {@link https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit } for info.
* @param colorNumber The number (ranging from 16 to 255) referring to the color
* desired.
*/
export function calcANSI8bitColor(colorNumber: number): RGBA | undefined {
if (colorNumber % 1 !== 0) {
// Should be integer
return;
} if (colorNumber >= 16 && colorNumber <= 231) {
// Converts to one of 216 RGB colors
colorNumber -= 16;
let blue: number = colorNumber % 6;
colorNumber = (colorNumber - blue) / 6;
let green: number = colorNumber % 6;
colorNumber = (colorNumber - green) / 6;
let red: number = colorNumber;
// red, green, blue now range on [0, 5], need to map to [0,255]
const convFactor: number = 255 / 5;
blue = Math.round(blue * convFactor);
green = Math.round(green * convFactor);
red = Math.round(red * convFactor);
return new RGBA(red, green, blue);
} else if (colorNumber >= 232 && colorNumber <= 255) {
// Converts to a grayscale value
colorNumber -= 232;
const colorLevel: number = Math.round(colorNumber / 23 * 255);
return new RGBA(colorLevel, colorLevel, colorLevel);
} else {
return;
}
} | the_stack |
import { PagedAsyncIterableIterator } from "@azure/core-paging";
import { PollerLike, PollOperationState } from "@azure/core-lro";
import {
DeploymentResource,
DeploymentsListOptionalParams,
DeploymentsListForClusterOptionalParams,
DeploymentsGetOptionalParams,
DeploymentsGetResponse,
DeploymentsCreateOrUpdateOptionalParams,
DeploymentsCreateOrUpdateResponse,
DeploymentsDeleteOptionalParams,
DeploymentsUpdateOptionalParams,
DeploymentsUpdateResponse,
DeploymentsStartOptionalParams,
DeploymentsStopOptionalParams,
DeploymentsRestartOptionalParams,
DeploymentsGetLogFileUrlOptionalParams,
DeploymentsGetLogFileUrlResponse,
DiagnosticParameters,
DeploymentsGenerateHeapDumpOptionalParams,
DeploymentsGenerateThreadDumpOptionalParams,
DeploymentsStartJFROptionalParams
} from "../models";
/// <reference lib="esnext.asynciterable" />
/** Interface representing a Deployments. */
export interface Deployments {
/**
* Handles requests to list all resources in an App.
* @param resourceGroupName The name of the resource group that contains the resource. You can obtain
* this value from the Azure Resource Manager API or the portal.
* @param serviceName The name of the Service resource.
* @param appName The name of the App resource.
* @param options The options parameters.
*/
list(
resourceGroupName: string,
serviceName: string,
appName: string,
options?: DeploymentsListOptionalParams
): PagedAsyncIterableIterator<DeploymentResource>;
/**
* List deployments for a certain service
* @param resourceGroupName The name of the resource group that contains the resource. You can obtain
* this value from the Azure Resource Manager API or the portal.
* @param serviceName The name of the Service resource.
* @param options The options parameters.
*/
listForCluster(
resourceGroupName: string,
serviceName: string,
options?: DeploymentsListForClusterOptionalParams
): PagedAsyncIterableIterator<DeploymentResource>;
/**
* Get a Deployment and its properties.
* @param resourceGroupName The name of the resource group that contains the resource. You can obtain
* this value from the Azure Resource Manager API or the portal.
* @param serviceName The name of the Service resource.
* @param appName The name of the App resource.
* @param deploymentName The name of the Deployment resource.
* @param options The options parameters.
*/
get(
resourceGroupName: string,
serviceName: string,
appName: string,
deploymentName: string,
options?: DeploymentsGetOptionalParams
): Promise<DeploymentsGetResponse>;
/**
* Create a new Deployment or update an exiting Deployment.
* @param resourceGroupName The name of the resource group that contains the resource. You can obtain
* this value from the Azure Resource Manager API or the portal.
* @param serviceName The name of the Service resource.
* @param appName The name of the App resource.
* @param deploymentName The name of the Deployment resource.
* @param deploymentResource Parameters for the create or update operation
* @param options The options parameters.
*/
beginCreateOrUpdate(
resourceGroupName: string,
serviceName: string,
appName: string,
deploymentName: string,
deploymentResource: DeploymentResource,
options?: DeploymentsCreateOrUpdateOptionalParams
): Promise<
PollerLike<
PollOperationState<DeploymentsCreateOrUpdateResponse>,
DeploymentsCreateOrUpdateResponse
>
>;
/**
* Create a new Deployment or update an exiting Deployment.
* @param resourceGroupName The name of the resource group that contains the resource. You can obtain
* this value from the Azure Resource Manager API or the portal.
* @param serviceName The name of the Service resource.
* @param appName The name of the App resource.
* @param deploymentName The name of the Deployment resource.
* @param deploymentResource Parameters for the create or update operation
* @param options The options parameters.
*/
beginCreateOrUpdateAndWait(
resourceGroupName: string,
serviceName: string,
appName: string,
deploymentName: string,
deploymentResource: DeploymentResource,
options?: DeploymentsCreateOrUpdateOptionalParams
): Promise<DeploymentsCreateOrUpdateResponse>;
/**
* Operation to delete a Deployment.
* @param resourceGroupName The name of the resource group that contains the resource. You can obtain
* this value from the Azure Resource Manager API or the portal.
* @param serviceName The name of the Service resource.
* @param appName The name of the App resource.
* @param deploymentName The name of the Deployment resource.
* @param options The options parameters.
*/
beginDelete(
resourceGroupName: string,
serviceName: string,
appName: string,
deploymentName: string,
options?: DeploymentsDeleteOptionalParams
): Promise<PollerLike<PollOperationState<void>, void>>;
/**
* Operation to delete a Deployment.
* @param resourceGroupName The name of the resource group that contains the resource. You can obtain
* this value from the Azure Resource Manager API or the portal.
* @param serviceName The name of the Service resource.
* @param appName The name of the App resource.
* @param deploymentName The name of the Deployment resource.
* @param options The options parameters.
*/
beginDeleteAndWait(
resourceGroupName: string,
serviceName: string,
appName: string,
deploymentName: string,
options?: DeploymentsDeleteOptionalParams
): Promise<void>;
/**
* Operation to update an exiting Deployment.
* @param resourceGroupName The name of the resource group that contains the resource. You can obtain
* this value from the Azure Resource Manager API or the portal.
* @param serviceName The name of the Service resource.
* @param appName The name of the App resource.
* @param deploymentName The name of the Deployment resource.
* @param deploymentResource Parameters for the update operation
* @param options The options parameters.
*/
beginUpdate(
resourceGroupName: string,
serviceName: string,
appName: string,
deploymentName: string,
deploymentResource: DeploymentResource,
options?: DeploymentsUpdateOptionalParams
): Promise<
PollerLike<
PollOperationState<DeploymentsUpdateResponse>,
DeploymentsUpdateResponse
>
>;
/**
* Operation to update an exiting Deployment.
* @param resourceGroupName The name of the resource group that contains the resource. You can obtain
* this value from the Azure Resource Manager API or the portal.
* @param serviceName The name of the Service resource.
* @param appName The name of the App resource.
* @param deploymentName The name of the Deployment resource.
* @param deploymentResource Parameters for the update operation
* @param options The options parameters.
*/
beginUpdateAndWait(
resourceGroupName: string,
serviceName: string,
appName: string,
deploymentName: string,
deploymentResource: DeploymentResource,
options?: DeploymentsUpdateOptionalParams
): Promise<DeploymentsUpdateResponse>;
/**
* Start the deployment.
* @param resourceGroupName The name of the resource group that contains the resource. You can obtain
* this value from the Azure Resource Manager API or the portal.
* @param serviceName The name of the Service resource.
* @param appName The name of the App resource.
* @param deploymentName The name of the Deployment resource.
* @param options The options parameters.
*/
beginStart(
resourceGroupName: string,
serviceName: string,
appName: string,
deploymentName: string,
options?: DeploymentsStartOptionalParams
): Promise<PollerLike<PollOperationState<void>, void>>;
/**
* Start the deployment.
* @param resourceGroupName The name of the resource group that contains the resource. You can obtain
* this value from the Azure Resource Manager API or the portal.
* @param serviceName The name of the Service resource.
* @param appName The name of the App resource.
* @param deploymentName The name of the Deployment resource.
* @param options The options parameters.
*/
beginStartAndWait(
resourceGroupName: string,
serviceName: string,
appName: string,
deploymentName: string,
options?: DeploymentsStartOptionalParams
): Promise<void>;
/**
* Stop the deployment.
* @param resourceGroupName The name of the resource group that contains the resource. You can obtain
* this value from the Azure Resource Manager API or the portal.
* @param serviceName The name of the Service resource.
* @param appName The name of the App resource.
* @param deploymentName The name of the Deployment resource.
* @param options The options parameters.
*/
beginStop(
resourceGroupName: string,
serviceName: string,
appName: string,
deploymentName: string,
options?: DeploymentsStopOptionalParams
): Promise<PollerLike<PollOperationState<void>, void>>;
/**
* Stop the deployment.
* @param resourceGroupName The name of the resource group that contains the resource. You can obtain
* this value from the Azure Resource Manager API or the portal.
* @param serviceName The name of the Service resource.
* @param appName The name of the App resource.
* @param deploymentName The name of the Deployment resource.
* @param options The options parameters.
*/
beginStopAndWait(
resourceGroupName: string,
serviceName: string,
appName: string,
deploymentName: string,
options?: DeploymentsStopOptionalParams
): Promise<void>;
/**
* Restart the deployment.
* @param resourceGroupName The name of the resource group that contains the resource. You can obtain
* this value from the Azure Resource Manager API or the portal.
* @param serviceName The name of the Service resource.
* @param appName The name of the App resource.
* @param deploymentName The name of the Deployment resource.
* @param options The options parameters.
*/
beginRestart(
resourceGroupName: string,
serviceName: string,
appName: string,
deploymentName: string,
options?: DeploymentsRestartOptionalParams
): Promise<PollerLike<PollOperationState<void>, void>>;
/**
* Restart the deployment.
* @param resourceGroupName The name of the resource group that contains the resource. You can obtain
* this value from the Azure Resource Manager API or the portal.
* @param serviceName The name of the Service resource.
* @param appName The name of the App resource.
* @param deploymentName The name of the Deployment resource.
* @param options The options parameters.
*/
beginRestartAndWait(
resourceGroupName: string,
serviceName: string,
appName: string,
deploymentName: string,
options?: DeploymentsRestartOptionalParams
): Promise<void>;
/**
* Get deployment log file URL
* @param resourceGroupName The name of the resource group that contains the resource. You can obtain
* this value from the Azure Resource Manager API or the portal.
* @param serviceName The name of the Service resource.
* @param appName The name of the App resource.
* @param deploymentName The name of the Deployment resource.
* @param options The options parameters.
*/
getLogFileUrl(
resourceGroupName: string,
serviceName: string,
appName: string,
deploymentName: string,
options?: DeploymentsGetLogFileUrlOptionalParams
): Promise<DeploymentsGetLogFileUrlResponse>;
/**
* Generate Heap Dump
* @param resourceGroupName The name of the resource group that contains the resource. You can obtain
* this value from the Azure Resource Manager API or the portal.
* @param serviceName The name of the Service resource.
* @param appName The name of the App resource.
* @param deploymentName The name of the Deployment resource.
* @param diagnosticParameters Parameters for the diagnostic operation
* @param options The options parameters.
*/
beginGenerateHeapDump(
resourceGroupName: string,
serviceName: string,
appName: string,
deploymentName: string,
diagnosticParameters: DiagnosticParameters,
options?: DeploymentsGenerateHeapDumpOptionalParams
): Promise<PollerLike<PollOperationState<void>, void>>;
/**
* Generate Heap Dump
* @param resourceGroupName The name of the resource group that contains the resource. You can obtain
* this value from the Azure Resource Manager API or the portal.
* @param serviceName The name of the Service resource.
* @param appName The name of the App resource.
* @param deploymentName The name of the Deployment resource.
* @param diagnosticParameters Parameters for the diagnostic operation
* @param options The options parameters.
*/
beginGenerateHeapDumpAndWait(
resourceGroupName: string,
serviceName: string,
appName: string,
deploymentName: string,
diagnosticParameters: DiagnosticParameters,
options?: DeploymentsGenerateHeapDumpOptionalParams
): Promise<void>;
/**
* Generate Thread Dump
* @param resourceGroupName The name of the resource group that contains the resource. You can obtain
* this value from the Azure Resource Manager API or the portal.
* @param serviceName The name of the Service resource.
* @param appName The name of the App resource.
* @param deploymentName The name of the Deployment resource.
* @param diagnosticParameters Parameters for the diagnostic operation
* @param options The options parameters.
*/
beginGenerateThreadDump(
resourceGroupName: string,
serviceName: string,
appName: string,
deploymentName: string,
diagnosticParameters: DiagnosticParameters,
options?: DeploymentsGenerateThreadDumpOptionalParams
): Promise<PollerLike<PollOperationState<void>, void>>;
/**
* Generate Thread Dump
* @param resourceGroupName The name of the resource group that contains the resource. You can obtain
* this value from the Azure Resource Manager API or the portal.
* @param serviceName The name of the Service resource.
* @param appName The name of the App resource.
* @param deploymentName The name of the Deployment resource.
* @param diagnosticParameters Parameters for the diagnostic operation
* @param options The options parameters.
*/
beginGenerateThreadDumpAndWait(
resourceGroupName: string,
serviceName: string,
appName: string,
deploymentName: string,
diagnosticParameters: DiagnosticParameters,
options?: DeploymentsGenerateThreadDumpOptionalParams
): Promise<void>;
/**
* Start JFR
* @param resourceGroupName The name of the resource group that contains the resource. You can obtain
* this value from the Azure Resource Manager API or the portal.
* @param serviceName The name of the Service resource.
* @param appName The name of the App resource.
* @param deploymentName The name of the Deployment resource.
* @param diagnosticParameters Parameters for the diagnostic operation
* @param options The options parameters.
*/
beginStartJFR(
resourceGroupName: string,
serviceName: string,
appName: string,
deploymentName: string,
diagnosticParameters: DiagnosticParameters,
options?: DeploymentsStartJFROptionalParams
): Promise<PollerLike<PollOperationState<void>, void>>;
/**
* Start JFR
* @param resourceGroupName The name of the resource group that contains the resource. You can obtain
* this value from the Azure Resource Manager API or the portal.
* @param serviceName The name of the Service resource.
* @param appName The name of the App resource.
* @param deploymentName The name of the Deployment resource.
* @param diagnosticParameters Parameters for the diagnostic operation
* @param options The options parameters.
*/
beginStartJFRAndWait(
resourceGroupName: string,
serviceName: string,
appName: string,
deploymentName: string,
diagnosticParameters: DiagnosticParameters,
options?: DeploymentsStartJFROptionalParams
): Promise<void>;
} | the_stack |
import { Logging } from "matrix-appservice-bridge";
import * as yargs from "yargs";
import { AdminCommand, ResponseCallback } from "./AdminCommand";
import { Main } from "./Main";
import { BridgedRoom } from "./BridgedRoom";
const log = Logging.get("AdminCommands");
const RoomIdCommandOption = {
alias: "R",
demandOption: true,
description: "Matrix Room ID",
};
export class AdminCommands {
private yargs: yargs.Argv;
private commands: AdminCommand[];
constructor(private main: Main) {
this.commands = [
this.list,
this.show,
this.link,
this.unlink,
this.join,
this.leave,
this.stalerooms,
this.doOauth,
this.help,
];
this.yargs = yargs.parserConfiguration({})
.version(false)
.help(false); // We provide our own help, and version is not required.
this.commands.forEach((cmd) => {
this.yargs = this.yargs.command(
cmd.command,
cmd.description,
(yg: yargs.Argv) => void yg.options(cmd.options || {}),
cmd.handler.bind(cmd)
).exitProcess(false)
.showHelpOnFail(false);
});
}
public get list(): AdminCommand {
return new AdminCommand(
"list",
"list the linked rooms",
async ({respond, team, room}: {
respond: ResponseCallback,
team?: string,
room?: string,
}) => {
const quotemeta = (s: string) => s.replace(/\W/g, "\\$&");
let nameFilter: RegExp;
if (team) {
nameFilter = new RegExp(`^${quotemeta(team)}\\.#`);
}
let found = 0;
this.main.rooms.all.forEach((r) => {
const channelName = r.SlackChannelName || "UNKNOWN";
if (nameFilter && !nameFilter.test(channelName)) {
return;
}
if (room && !r.MatrixRoomId.includes(room)) {
return;
}
const slack = r.SlackChannelId ?
`${channelName} (${r.SlackChannelId})` :
channelName;
let status = r.getStatus();
if (!status.startsWith("ready")) {
status = status.toUpperCase();
}
found++;
respond(`${status} ${slack} -- ${r.MatrixRoomId}`);
});
if (!found) {
respond("No rooms found");
}
},
{
room: {
alias: "R",
description: "Filter only Matrix room IDs containing this string fragment",
},
team: {
alias: "T",
description: "Filter only rooms for this Slack team domain",
},
},
);
}
public get show(): AdminCommand {
return new AdminCommand(
"show",
"show a single connected room",
({respond, channel_id, room}: {
respond: ResponseCallback,
channel_id?: string,
room?: string
}) => {
let bridgedRoom: BridgedRoom|undefined;
if (room) {
bridgedRoom = this.main.rooms.getByMatrixRoomId(room);
} else if (channel_id) {
bridgedRoom = this.main.rooms.getBySlackChannelId(channel_id);
} else {
respond("Require exactly one of room or channel_id");
return;
}
if (!bridgedRoom) {
respond("No such room");
return;
}
respond("Bridged Room:");
respond(" Status: " + bridgedRoom.getStatus());
respond(" Slack Name: " + bridgedRoom.SlackChannelName || "PENDING");
respond(" Slack Team: " + bridgedRoom.SlackTeamId || "PENDING");
if (bridgedRoom.SlackWebhookUri) {
respond(" Webhook URI: " + bridgedRoom.SlackWebhookUri);
}
respond(" Inbound ID: " + bridgedRoom.InboundId);
respond(" Inbound URL: " + this.main.getInboundUrlForRoom(bridgedRoom));
respond(" Matrix room ID: " + bridgedRoom.MatrixRoomId);
respond(" Using RTM: " + (bridgedRoom.SlackTeamId ? this.main.teamIsUsingRtm(bridgedRoom.SlackTeamId) : false).toString());
},
{
channel_id: {
alias: "I",
description: "Slack channel ID",
},
room: { ...RoomIdCommandOption, demandOption: false },
},
);
}
public get link(): AdminCommand {
return new AdminCommand(
"link",
"connect a Matrix and a Slack room together",
async ({respond, room, channel_id, webhook_url, slack_bot_token, team_id}: {
respond: ResponseCallback,
room?: string,
channel_id?: string,
webhook_url?: string,
slack_bot_token?: string,
team_id?: string,
}) => {
try {
if (!room) {
respond("Room not provided");
return;
}
const r = await this.main.actionLink({
matrix_room_id: room,
slack_bot_token,
team_id,
slack_channel_id: channel_id,
slack_webhook_uri: webhook_url,
});
respond("Room is now " + r.getStatus());
if (r.SlackWebhookUri) {
respond("Inbound URL is " + this.main.getInboundUrlForRoom(r));
} else {
respond("Remember to invite the slack bot to the slack channel.");
}
} catch (ex) {
log.warn("Failed to link channel", ex);
if ((ex as Error).message === "Failed to get channel info") {
respond("Cannot link - Bot doesn't have visibility on channel. Is it invited on slack?");
} else {
respond("Cannot link - " + ex);
}
}
},
{
channel_id: {
alias: "I",
description: "Slack channel ID",
},
room: RoomIdCommandOption,
slack_bot_token: {
alias: "t",
description: "Slack bot user token. Used with Slack bot user & Events api",
},
team_id: {
alias: "T",
description: "Slack team ID. Used with Slack bot user & Events api",
},
webhook_url: {
alias: "u",
description: "Slack webhook URL. Used with Slack outgoing hooks integration",
},
},
);
}
public get unlink(): AdminCommand {
return new AdminCommand(
"unlink",
"disconnect a linked Matrix and Slack room",
async ({respond, room}: {
respond: ResponseCallback,
room?: string,
}) => {
if (!room) {
respond("Room not provided");
return;
}
try {
await this.main.actionUnlink({
matrix_room_id: room,
});
respond("Unlinked");
} catch (ex) {
respond("Cannot unlink - " + ex);
}
},
{
room: RoomIdCommandOption,
},
);
}
public get join(): AdminCommand {
return new AdminCommand(
"join room",
"join a new room",
async ({respond, room}: {
respond: ResponseCallback,
room?: string,
}) => {
if (!room) {
respond("No room provided");
return;
}
await this.main.botIntent.join(room);
respond("Joined");
},
{
room: RoomIdCommandOption,
},
);
}
public get leave(): AdminCommand {
return new AdminCommand(
"leave room",
"leave an unlinked room",
async ({respond, room}: {
respond: ResponseCallback,
room?: string,
}) => {
if (!room) {
respond("Room not provided");
return;
}
const userIds = await this.main.listGhostUsers(room);
respond(`Draining ${userIds.length} ghosts from ${room}`);
await Promise.all(userIds.map(async (userId) => this.main.getIntent(userId).leave(room)));
await this.main.botIntent.leave(room);
respond("Drained");
},
{
room: RoomIdCommandOption,
},
);
}
public get stalerooms(): AdminCommand {
return new AdminCommand(
"stalerooms",
"list rooms the bot user is a member of that are unlinked",
async ({respond}: { respond: ResponseCallback }) => {
const roomIds = await this.main.listRoomsFor();
roomIds.forEach((id) => {
if (id === this.main.config.matrix_admin_room ||
this.main.rooms.getByMatrixRoomId(id)) {
return;
}
respond(id);
});
},
);
}
public get doOauth(): AdminCommand {
return new AdminCommand(
"oauth userId puppet",
"generate an oauth url to bind your account with",
async ({respond, userId, puppet}: {
respond: ResponseCallback,
userId?: string,
puppet?: boolean,
}) => {
if (!this.main.oauth2) {
respond("Oauth is not configured on this bridge");
return;
}
if (!userId) {
respond("userId not provided");
return;
}
const token = this.main.oauth2.getPreauthToken(userId);
const authUri = this.main.oauth2.makeAuthorizeURL(
token,
token,
puppet,
);
respond(authUri);
},
{
userId: {
type: "string",
description: "The userId to bind to the oauth token",
},
puppet: {
type: "boolean",
description: "Does the user need puppeting permissions",
},
},
);
}
public get help(): AdminCommand {
return new AdminCommand(
"help [command]",
"describes the commands available",
({respond, command}: {
respond: ResponseCallback,
command?: string,
}) => {
if (command) {
const cmd = this.commands.find((adminCommand) => (adminCommand.command.split(' ')[0] === command));
if (!cmd) {
respond("Command not found. No help can be provided.");
return;
}
cmd.detailedHelp().forEach((s) => respond(s));
return;
}
this.commands.forEach((cmd) => {
respond(cmd.simpleHelp());
});
},
{
command: {
description: "Get help about a particular command",
},
},
);
}
public async parse(argv: string, respond: ResponseCallback): Promise<boolean> {
// yargs has no way to tell us if a command matched, so we have this
// slightly whacky function to manage it.
let matched = false;
await this.yargs.parse(argv, {
matched: () => { matched = true; },
respond,
});
return matched;
}
} | the_stack |
import 'mocha';
import expect from 'expect';
import sinon from 'sinon';
import lodash from 'lodash';
import { AmqplibInstrumentation, EndOperation, PublishParams } from '../src';
import { getTestSpans, registerInstrumentation } from 'opentelemetry-instrumentation-testing-utils';
const instrumentation = registerInstrumentation(new AmqplibInstrumentation());
import amqp, { ConsumeMessage } from 'amqplib';
import { MessagingDestinationKindValues, SemanticAttributes } from '@opentelemetry/semantic-conventions';
import { Span, SpanKind, SpanStatusCode } from '@opentelemetry/api';
import { asyncConfirmPublish, asyncConfirmSend, asyncConsume } from './utils';
import { TEST_RABBITMQ_HOST, TEST_RABBITMQ_PASS, TEST_RABBITMQ_PORT, TEST_RABBITMQ_USER } from './config';
const msgPayload = 'payload from test';
const queueName = 'queue-name-from-unittest';
// signal that the channel is closed in test, thus it should not be closed again in afterEach.
// could not find a way to get this from amqplib directly.
const CHANNEL_CLOSED_IN_TEST = Symbol('opentelemetry.amqplib.unittest.channel_closed_in_test');
describe('amqplib instrumentation promise model', function () {
const url = `amqp://${TEST_RABBITMQ_USER}:${TEST_RABBITMQ_PASS}@${TEST_RABBITMQ_HOST}:${TEST_RABBITMQ_PORT}`;
const censoredUrl = `amqp://${TEST_RABBITMQ_USER}:***@${TEST_RABBITMQ_HOST}:${TEST_RABBITMQ_PORT}`;
let conn: amqp.Connection;
before(async () => {
conn = await amqp.connect(url);
});
after(async () => {
await conn.close();
});
let endHookSpy;
const expectConsumeEndSpyStatus = (expectedEndOperations: EndOperation[]): void => {
expect(endHookSpy.callCount).toBe(expectedEndOperations.length);
expectedEndOperations.forEach((endOperation: EndOperation, index: number) => {
expect(endHookSpy.args[index][3]).toEqual(endOperation);
switch (endOperation) {
case EndOperation.AutoAck:
case EndOperation.Ack:
case EndOperation.AckAll:
expect(endHookSpy.args[index][2]).toBeFalsy();
break;
case EndOperation.Reject:
case EndOperation.Nack:
case EndOperation.NackAll:
case EndOperation.ChannelClosed:
case EndOperation.ChannelError:
expect(endHookSpy.args[index][2]).toBeTruthy();
break;
}
});
};
describe('channel', () => {
let channel: amqp.Channel;
beforeEach(async () => {
endHookSpy = sinon.spy();
instrumentation.setConfig({
consumeEndHook: endHookSpy,
});
channel = await conn.createChannel();
await channel.assertQueue(queueName, { durable: false });
await channel.purgeQueue(queueName);
// install an error handler, otherwise when we have tests that create error on the channel,
// it throws and crash process
channel.on('error', (err) => {});
});
afterEach(async () => {
if (!channel[CHANNEL_CLOSED_IN_TEST]) {
try {
await new Promise<void>((resolve) => {
channel.on('close', resolve);
channel.close();
});
} catch {}
}
});
it('simple publish and consume from queue', async () => {
const hadSpaceInBuffer = channel.sendToQueue(queueName, Buffer.from(msgPayload));
expect(hadSpaceInBuffer).toBeTruthy();
await asyncConsume(channel, queueName, [(msg) => expect(msg.content.toString()).toEqual(msgPayload)], {
noAck: true,
});
const [publishSpan, consumeSpan] = getTestSpans();
// assert publish span
expect(publishSpan.kind).toEqual(SpanKind.PRODUCER);
expect(publishSpan.attributes[SemanticAttributes.MESSAGING_SYSTEM]).toEqual('rabbitmq');
expect(publishSpan.attributes[SemanticAttributes.MESSAGING_DESTINATION]).toEqual(''); // according to spec: "This will be an empty string if the default exchange is used"
expect(publishSpan.attributes[SemanticAttributes.MESSAGING_DESTINATION_KIND]).toEqual(
MessagingDestinationKindValues.TOPIC
);
expect(publishSpan.attributes[SemanticAttributes.MESSAGING_RABBITMQ_ROUTING_KEY]).toEqual(queueName);
expect(publishSpan.attributes[SemanticAttributes.MESSAGING_PROTOCOL]).toEqual('AMQP');
expect(publishSpan.attributes[SemanticAttributes.MESSAGING_PROTOCOL_VERSION]).toEqual('0.9.1');
expect(publishSpan.attributes[SemanticAttributes.MESSAGING_URL]).toEqual(censoredUrl);
expect(publishSpan.attributes[SemanticAttributes.NET_PEER_NAME]).toEqual(TEST_RABBITMQ_HOST);
expect(publishSpan.attributes[SemanticAttributes.NET_PEER_PORT]).toEqual(TEST_RABBITMQ_PORT);
// assert consume span
expect(consumeSpan.kind).toEqual(SpanKind.CONSUMER);
expect(consumeSpan.attributes[SemanticAttributes.MESSAGING_SYSTEM]).toEqual('rabbitmq');
expect(consumeSpan.attributes[SemanticAttributes.MESSAGING_DESTINATION]).toEqual(''); // according to spec: "This will be an empty string if the default exchange is used"
expect(consumeSpan.attributes[SemanticAttributes.MESSAGING_DESTINATION_KIND]).toEqual(
MessagingDestinationKindValues.TOPIC
);
expect(consumeSpan.attributes[SemanticAttributes.MESSAGING_RABBITMQ_ROUTING_KEY]).toEqual(queueName);
expect(consumeSpan.attributes[SemanticAttributes.MESSAGING_PROTOCOL]).toEqual('AMQP');
expect(consumeSpan.attributes[SemanticAttributes.MESSAGING_PROTOCOL_VERSION]).toEqual('0.9.1');
expect(consumeSpan.attributes[SemanticAttributes.MESSAGING_URL]).toEqual(censoredUrl);
expect(consumeSpan.attributes[SemanticAttributes.NET_PEER_NAME]).toEqual(TEST_RABBITMQ_HOST);
expect(consumeSpan.attributes[SemanticAttributes.NET_PEER_PORT]).toEqual(TEST_RABBITMQ_PORT);
// assert context propagation
expect(consumeSpan.spanContext().traceId).toEqual(publishSpan.spanContext().traceId);
expect(consumeSpan.parentSpanId).toEqual(publishSpan.spanContext().spanId);
expectConsumeEndSpyStatus([EndOperation.AutoAck]);
});
describe('ending consume spans', () => {
it('message acked sync', async () => {
channel.sendToQueue(queueName, Buffer.from(msgPayload));
await asyncConsume(channel, queueName, [(msg) => channel.ack(msg)]);
// assert consumed message span has ended
expect(getTestSpans().length).toBe(2);
expectConsumeEndSpyStatus([EndOperation.Ack]);
});
it('message acked async', async () => {
channel.sendToQueue(queueName, Buffer.from(msgPayload));
// start async timer and ack the message after the callback returns
await new Promise<void>((resolve) => {
asyncConsume(channel, queueName, [
(msg) =>
setTimeout(() => {
channel.ack(msg);
resolve();
}, 1),
]);
});
// assert consumed message span has ended
expect(getTestSpans().length).toBe(2);
expectConsumeEndSpyStatus([EndOperation.Ack]);
});
it('message nack no requeue', async () => {
channel.sendToQueue(queueName, Buffer.from(msgPayload));
await asyncConsume(channel, queueName, [(msg) => channel.nack(msg, false, false)]);
await new Promise((resolve) => setTimeout(resolve, 20)); // just make sure we don't get it again
// assert consumed message span has ended
expect(getTestSpans().length).toBe(2);
const [_, consumerSpan] = getTestSpans();
expect(consumerSpan.status.code).toEqual(SpanStatusCode.ERROR);
expect(consumerSpan.status.message).toEqual('nack called on message without requeue');
expectConsumeEndSpyStatus([EndOperation.Nack]);
});
it('message nack requeue, then acked', async () => {
channel.sendToQueue(queueName, Buffer.from(msgPayload));
// @ts-ignore
await asyncConsume(channel, queueName, [
(msg: amqp.Message) => channel.nack(msg, false, true),
(msg: amqp.Message) => channel.ack(msg),
]);
// assert we have the requeued message sent again
expect(getTestSpans().length).toBe(3);
const [_, rejectedConsumerSpan, successConsumerSpan] = getTestSpans();
expect(rejectedConsumerSpan.status.code).toEqual(SpanStatusCode.ERROR);
expect(rejectedConsumerSpan.status.message).toEqual('nack called on message with requeue');
expect(successConsumerSpan.status.code).toEqual(SpanStatusCode.UNSET);
expectConsumeEndSpyStatus([EndOperation.Nack, EndOperation.Ack]);
});
it('ack allUpTo 2 msgs sync', async () => {
lodash.times(3, () => channel.sendToQueue(queueName, Buffer.from(msgPayload)));
// @ts-ignore
await asyncConsume(channel, queueName, [
null,
(msg) => channel.ack(msg, true),
(msg) => channel.ack(msg),
]);
// assert all 3 messages are acked, including the first one which is acked by allUpTo
expect(getTestSpans().length).toBe(6);
expectConsumeEndSpyStatus([EndOperation.Ack, EndOperation.Ack, EndOperation.Ack]);
});
it('nack allUpTo 2 msgs sync', async () => {
lodash.times(3, () => channel.sendToQueue(queueName, Buffer.from(msgPayload)));
// @ts-ignore
await asyncConsume(channel, queueName, [
null,
(msg) => channel.nack(msg, true, false),
(msg) => channel.nack(msg, false, false),
]);
// assert all 3 messages are acked, including the first one which is acked by allUpTo
expect(getTestSpans().length).toBe(6);
lodash.range(3, 6).forEach((i) => {
expect(getTestSpans()[i].status.code).toEqual(SpanStatusCode.ERROR);
expect(getTestSpans()[i].status.message).toEqual('nack called on message without requeue');
});
expectConsumeEndSpyStatus([EndOperation.Nack, EndOperation.Nack, EndOperation.Nack]);
});
it('ack not in received order', async () => {
lodash.times(3, () => channel.sendToQueue(queueName, Buffer.from(msgPayload)));
// @ts-ignore
const msgs = await asyncConsume(channel, queueName, [null, null, null]);
channel.ack(msgs[1]);
channel.ack(msgs[2]);
channel.ack(msgs[0]);
// assert all 3 span messages are ended
expect(getTestSpans().length).toBe(6);
expectConsumeEndSpyStatus([EndOperation.Ack, EndOperation.Ack, EndOperation.Ack]);
});
it('ackAll', async () => {
lodash.times(2, () => channel.sendToQueue(queueName, Buffer.from(msgPayload)));
// @ts-ignore
await asyncConsume(channel, queueName, [null, () => channel.ackAll()]);
// assert all 2 span messages are ended by call to ackAll
expect(getTestSpans().length).toBe(4);
expectConsumeEndSpyStatus([EndOperation.AckAll, EndOperation.AckAll]);
});
it('nackAll', async () => {
lodash.times(2, () => channel.sendToQueue(queueName, Buffer.from(msgPayload)));
// @ts-ignore
await asyncConsume(channel, queueName, [null, () => channel.nackAll(false)]);
// assert all 2 span messages are ended by calling nackAll
expect(getTestSpans().length).toBe(4);
lodash.range(2, 4).forEach((i) => {
expect(getTestSpans()[i].status.code).toEqual(SpanStatusCode.ERROR);
expect(getTestSpans()[i].status.message).toEqual('nackAll called on message without requeue');
});
expectConsumeEndSpyStatus([EndOperation.NackAll, EndOperation.NackAll]);
});
it('reject', async () => {
lodash.times(1, () => channel.sendToQueue(queueName, Buffer.from(msgPayload)));
// @ts-ignore
await asyncConsume(channel, queueName, [(msg) => channel.reject(msg, false)]);
expect(getTestSpans().length).toBe(2);
expect(getTestSpans()[1].status.code).toEqual(SpanStatusCode.ERROR);
expect(getTestSpans()[1].status.message).toEqual('reject called on message without requeue');
expectConsumeEndSpyStatus([EndOperation.Reject]);
});
it('reject with requeue', async () => {
lodash.times(1, () => channel.sendToQueue(queueName, Buffer.from(msgPayload)));
// @ts-ignore
await asyncConsume(channel, queueName, [
(msg) => channel.reject(msg, true),
(msg) => channel.reject(msg, false),
]);
expect(getTestSpans().length).toBe(3);
expect(getTestSpans()[1].status.code).toEqual(SpanStatusCode.ERROR);
expect(getTestSpans()[1].status.message).toEqual('reject called on message with requeue');
expect(getTestSpans()[2].status.code).toEqual(SpanStatusCode.ERROR);
expect(getTestSpans()[2].status.message).toEqual('reject called on message without requeue');
expectConsumeEndSpyStatus([EndOperation.Reject, EndOperation.Reject]);
});
it('closing channel should end all open spans on it', async () => {
lodash.times(1, () => channel.sendToQueue(queueName, Buffer.from(msgPayload)));
await new Promise<void>((resolve) =>
asyncConsume(channel, queueName, [
async (msg) => {
await channel.close();
resolve();
channel[CHANNEL_CLOSED_IN_TEST] = true;
},
])
);
expect(getTestSpans().length).toBe(2);
expect(getTestSpans()[1].status.code).toEqual(SpanStatusCode.ERROR);
expect(getTestSpans()[1].status.message).toEqual('channel closed');
expectConsumeEndSpyStatus([EndOperation.ChannelClosed]);
});
it('error on channel should end all open spans on it', (done) => {
lodash.times(2, () => channel.sendToQueue(queueName, Buffer.from(msgPayload)));
channel.on('close', () => {
expect(getTestSpans().length).toBe(4);
// second consume ended with valid ack, previous message not acked when channel is errored.
// since we first ack the second message, it appear first in the finished spans array
expect(getTestSpans()[2].status.code).toEqual(SpanStatusCode.UNSET);
expect(getTestSpans()[3].status.code).toEqual(SpanStatusCode.ERROR);
expect(getTestSpans()[3].status.message).toEqual('channel error');
expectConsumeEndSpyStatus([EndOperation.Ack, EndOperation.ChannelError]);
done();
});
asyncConsume(channel, queueName, [
null,
(msg) => {
try {
channel.ack(msg);
channel[CHANNEL_CLOSED_IN_TEST] = true;
// ack the same msg again, this is not valid and should close the channel
channel.ack(msg);
} catch {}
},
]);
});
it('not acking the message trigger timeout', async () => {
instrumentation.setConfig({
consumeEndHook: endHookSpy,
consumeTimeoutMs: 1,
});
lodash.times(1, () => channel.sendToQueue(queueName, Buffer.from(msgPayload)));
await asyncConsume(channel, queueName, [null]);
// we have timeout of 1 ms, so we wait more than that and check span indeed ended
await new Promise((resolve) => setTimeout(resolve, 10));
expect(getTestSpans().length).toBe(2);
expectConsumeEndSpyStatus([EndOperation.InstrumentationTimeout]);
});
});
describe('routing and exchange', () => {
it('topic exchange', async () => {
const exchangeName = 'topic exchange';
const routingKey = 'topic.name.from.unittest';
await channel.assertExchange(exchangeName, 'topic', { durable: false });
const { queue: queueName } = await channel.assertQueue('', { durable: false });
await channel.bindQueue(queueName, exchangeName, '#');
channel.publish(exchangeName, routingKey, Buffer.from(msgPayload));
await asyncConsume(channel, queueName, [null], {
noAck: true,
});
const [publishSpan, consumeSpan] = getTestSpans();
// assert publish span
expect(publishSpan.kind).toEqual(SpanKind.PRODUCER);
expect(publishSpan.attributes[SemanticAttributes.MESSAGING_SYSTEM]).toEqual('rabbitmq');
expect(publishSpan.attributes[SemanticAttributes.MESSAGING_DESTINATION]).toEqual(exchangeName);
expect(publishSpan.attributes[SemanticAttributes.MESSAGING_DESTINATION_KIND]).toEqual(
MessagingDestinationKindValues.TOPIC
);
expect(publishSpan.attributes[SemanticAttributes.MESSAGING_RABBITMQ_ROUTING_KEY]).toEqual(routingKey);
expect(publishSpan.attributes[SemanticAttributes.MESSAGING_PROTOCOL]).toEqual('AMQP');
expect(publishSpan.attributes[SemanticAttributes.MESSAGING_PROTOCOL_VERSION]).toEqual('0.9.1');
// assert consume span
expect(consumeSpan.kind).toEqual(SpanKind.CONSUMER);
expect(consumeSpan.attributes[SemanticAttributes.MESSAGING_SYSTEM]).toEqual('rabbitmq');
expect(consumeSpan.attributes[SemanticAttributes.MESSAGING_DESTINATION]).toEqual(exchangeName);
expect(consumeSpan.attributes[SemanticAttributes.MESSAGING_DESTINATION_KIND]).toEqual(
MessagingDestinationKindValues.TOPIC
);
expect(consumeSpan.attributes[SemanticAttributes.MESSAGING_RABBITMQ_ROUTING_KEY]).toEqual(routingKey);
expect(consumeSpan.attributes[SemanticAttributes.MESSAGING_PROTOCOL]).toEqual('AMQP');
expect(consumeSpan.attributes[SemanticAttributes.MESSAGING_PROTOCOL_VERSION]).toEqual('0.9.1');
// assert context propagation
expect(consumeSpan.spanContext().traceId).toEqual(publishSpan.spanContext().traceId);
expect(consumeSpan.parentSpanId).toEqual(publishSpan.spanContext().spanId);
});
});
it('moduleVersionAttributeName works with publish and consume', async () => {
const VERSION_ATTR = 'module.version';
instrumentation.setConfig({
moduleVersionAttributeName: VERSION_ATTR,
});
channel.sendToQueue(queueName, Buffer.from(msgPayload));
await asyncConsume(channel, queueName, [(msg) => expect(msg.content.toString()).toEqual(msgPayload)], {
noAck: true,
});
expect(getTestSpans().length).toBe(2);
getTestSpans().forEach((s) => expect(s.attributes[VERSION_ATTR]).toMatch(/\d{1,4}\.\d{1,4}\.\d{1,5}.*/));
});
describe('hooks', () => {
it('publish and consume hooks success', async () => {
const attributeNameFromHook = 'attribute.name.from.hook';
const hookAttributeValue = 'attribute value from hook';
const attributeNameFromEndHook = 'attribute.name.from.endhook';
const endHookAttributeValue = 'attribute value from end hook';
instrumentation.setConfig({
publishHook: (span: Span, publishParams: PublishParams): void => {
span.setAttribute(attributeNameFromHook, hookAttributeValue);
expect(publishParams.exchange).toEqual('');
expect(publishParams.routingKey).toEqual(queueName);
expect(publishParams.content.toString()).toEqual(msgPayload);
},
consumeHook: (span: Span, msg: amqp.ConsumeMessage | null): void => {
span.setAttribute(attributeNameFromHook, hookAttributeValue);
expect(msg.content.toString()).toEqual(msgPayload);
},
consumeEndHook: (
span: Span,
msg: amqp.ConsumeMessage | null,
rejected: boolean,
endOperation: EndOperation
): void => {
span.setAttribute(attributeNameFromEndHook, endHookAttributeValue);
expect(endOperation).toEqual(EndOperation.AutoAck);
},
});
channel.sendToQueue(queueName, Buffer.from(msgPayload));
await asyncConsume(channel, queueName, [null], {
noAck: true,
});
expect(getTestSpans().length).toBe(2);
expect(getTestSpans()[0].attributes[attributeNameFromHook]).toEqual(hookAttributeValue);
expect(getTestSpans()[1].attributes[attributeNameFromHook]).toEqual(hookAttributeValue);
expect(getTestSpans()[1].attributes[attributeNameFromEndHook]).toEqual(endHookAttributeValue);
});
it('hooks throw should not affect user flow or span creation', async () => {
const attributeNameFromHook = 'attribute.name.from.hook';
const hookAttributeValue = 'attribute value from hook';
instrumentation.setConfig({
publishHook: (span: Span, publishParams: PublishParams): void => {
span.setAttribute(attributeNameFromHook, hookAttributeValue);
throw new Error('error from hook');
},
consumeHook: (span: Span, msg: amqp.ConsumeMessage | null): void => {
span.setAttribute(attributeNameFromHook, hookAttributeValue);
throw new Error('error from hook');
},
});
channel.sendToQueue(queueName, Buffer.from(msgPayload));
await asyncConsume(channel, queueName, [null], {
noAck: true,
});
expect(getTestSpans().length).toBe(2);
getTestSpans().forEach((s) => expect(s.attributes[attributeNameFromHook]).toEqual(hookAttributeValue));
});
});
describe('delete queue', () => {
it('consumer receives null msg when a queue is deleted in broker', async () => {
const queueNameForDeletion = 'queue-to-be-deleted';
await channel.assertQueue(queueNameForDeletion, { durable: false });
await channel.purgeQueue(queueNameForDeletion);
await channel.consume(queueNameForDeletion, (msg: ConsumeMessage | null) => {}, { noAck: true });
await channel.deleteQueue(queueNameForDeletion);
});
});
});
describe('confirm channel', () => {
let confirmChannel: amqp.ConfirmChannel;
beforeEach(async () => {
endHookSpy = sinon.spy();
instrumentation.setConfig({
consumeEndHook: endHookSpy,
});
confirmChannel = await conn.createConfirmChannel();
await confirmChannel.assertQueue(queueName, { durable: false });
await confirmChannel.purgeQueue(queueName);
// install an error handler, otherwise when we have tests that create error on the channel,
// it throws and crash process
confirmChannel.on('error', (err) => {});
});
afterEach(async () => {
if (!confirmChannel[CHANNEL_CLOSED_IN_TEST]) {
try {
await new Promise<void>((resolve) => {
confirmChannel.on('close', resolve);
confirmChannel.close();
});
} catch {}
}
});
it('simple publish with confirm and consume from queue', async () => {
await asyncConfirmSend(confirmChannel, queueName, msgPayload);
await asyncConsume(
confirmChannel,
queueName,
[(msg) => expect(msg.content.toString()).toEqual(msgPayload)],
{
noAck: true,
}
);
const [publishSpan, consumeSpan] = getTestSpans();
// assert publish span
expect(publishSpan.kind).toEqual(SpanKind.PRODUCER);
expect(publishSpan.attributes[SemanticAttributes.MESSAGING_SYSTEM]).toEqual('rabbitmq');
expect(publishSpan.attributes[SemanticAttributes.MESSAGING_DESTINATION]).toEqual(''); // according to spec: "This will be an empty string if the default exchange is used"
expect(publishSpan.attributes[SemanticAttributes.MESSAGING_DESTINATION_KIND]).toEqual(
MessagingDestinationKindValues.TOPIC
);
expect(publishSpan.attributes[SemanticAttributes.MESSAGING_RABBITMQ_ROUTING_KEY]).toEqual(queueName);
expect(publishSpan.attributes[SemanticAttributes.MESSAGING_PROTOCOL]).toEqual('AMQP');
expect(publishSpan.attributes[SemanticAttributes.MESSAGING_PROTOCOL_VERSION]).toEqual('0.9.1');
expect(publishSpan.attributes[SemanticAttributes.MESSAGING_URL]).toEqual(censoredUrl);
expect(publishSpan.attributes[SemanticAttributes.NET_PEER_NAME]).toEqual(TEST_RABBITMQ_HOST);
expect(publishSpan.attributes[SemanticAttributes.NET_PEER_PORT]).toEqual(TEST_RABBITMQ_PORT);
// assert consume span
expect(consumeSpan.kind).toEqual(SpanKind.CONSUMER);
expect(consumeSpan.attributes[SemanticAttributes.MESSAGING_SYSTEM]).toEqual('rabbitmq');
expect(consumeSpan.attributes[SemanticAttributes.MESSAGING_DESTINATION]).toEqual(''); // according to spec: "This will be an empty string if the default exchange is used"
expect(consumeSpan.attributes[SemanticAttributes.MESSAGING_DESTINATION_KIND]).toEqual(
MessagingDestinationKindValues.TOPIC
);
expect(consumeSpan.attributes[SemanticAttributes.MESSAGING_RABBITMQ_ROUTING_KEY]).toEqual(queueName);
expect(consumeSpan.attributes[SemanticAttributes.MESSAGING_PROTOCOL]).toEqual('AMQP');
expect(consumeSpan.attributes[SemanticAttributes.MESSAGING_PROTOCOL_VERSION]).toEqual('0.9.1');
expect(consumeSpan.attributes[SemanticAttributes.MESSAGING_URL]).toEqual(censoredUrl);
expect(consumeSpan.attributes[SemanticAttributes.NET_PEER_NAME]).toEqual(TEST_RABBITMQ_HOST);
expect(consumeSpan.attributes[SemanticAttributes.NET_PEER_PORT]).toEqual(TEST_RABBITMQ_PORT);
// assert context propagation
expect(consumeSpan.spanContext().traceId).toEqual(publishSpan.spanContext().traceId);
expectConsumeEndSpyStatus([EndOperation.AutoAck]);
});
it('confirm throw should not affect span end', async () => {
const confirmUserError = new Error('callback error');
await asyncConfirmSend(confirmChannel, queueName, msgPayload, () => {
throw confirmUserError;
}).catch((reject) => expect(reject).toEqual(confirmUserError));
await asyncConsume(
confirmChannel,
queueName,
[(msg) => expect(msg.content.toString()).toEqual(msgPayload)],
{
noAck: true,
}
);
expect(getTestSpans()).toHaveLength(2);
expectConsumeEndSpyStatus([EndOperation.AutoAck]);
});
describe('ending consume spans', () => {
it('message acked sync', async () => {
await asyncConfirmSend(confirmChannel, queueName, msgPayload);
await asyncConsume(confirmChannel, queueName, [(msg) => confirmChannel.ack(msg)]);
// assert consumed message span has ended
expect(getTestSpans().length).toBe(2);
expectConsumeEndSpyStatus([EndOperation.Ack]);
});
it('message acked async', async () => {
await asyncConfirmSend(confirmChannel, queueName, msgPayload);
// start async timer and ack the message after the callback returns
await new Promise<void>((resolve) => {
asyncConsume(confirmChannel, queueName, [
(msg) =>
setTimeout(() => {
confirmChannel.ack(msg);
resolve();
}, 1),
]);
});
// assert consumed message span has ended
expect(getTestSpans().length).toBe(2);
expectConsumeEndSpyStatus([EndOperation.Ack]);
});
it('message nack no requeue', async () => {
await asyncConfirmSend(confirmChannel, queueName, msgPayload);
await asyncConsume(confirmChannel, queueName, [(msg) => confirmChannel.nack(msg, false, false)]);
await new Promise((resolve) => setTimeout(resolve, 20)); // just make sure we don't get it again
// assert consumed message span has ended
expect(getTestSpans().length).toBe(2);
const [_, consumerSpan] = getTestSpans();
expect(consumerSpan.status.code).toEqual(SpanStatusCode.ERROR);
expect(consumerSpan.status.message).toEqual('nack called on message without requeue');
expectConsumeEndSpyStatus([EndOperation.Nack]);
});
it('message nack requeue, then acked', async () => {
await asyncConfirmSend(confirmChannel, queueName, msgPayload);
// @ts-ignore
await asyncConsume(confirmChannel, queueName, [
(msg: amqp.Message) => confirmChannel.nack(msg, false, true),
(msg: amqp.Message) => confirmChannel.ack(msg),
]);
// assert we have the requeued message sent again
expect(getTestSpans().length).toBe(3);
const [_, rejectedConsumerSpan, successConsumerSpan] = getTestSpans();
expect(rejectedConsumerSpan.status.code).toEqual(SpanStatusCode.ERROR);
expect(rejectedConsumerSpan.status.message).toEqual('nack called on message with requeue');
expect(successConsumerSpan.status.code).toEqual(SpanStatusCode.UNSET);
expectConsumeEndSpyStatus([EndOperation.Nack, EndOperation.Ack]);
});
it('ack allUpTo 2 msgs sync', async () => {
await Promise.all(lodash.times(3, () => asyncConfirmSend(confirmChannel, queueName, msgPayload)));
// @ts-ignore
await asyncConsume(confirmChannel, queueName, [
null,
(msg) => confirmChannel.ack(msg, true),
(msg) => confirmChannel.ack(msg),
]);
// assert all 3 messages are acked, including the first one which is acked by allUpTo
expect(getTestSpans().length).toBe(6);
expectConsumeEndSpyStatus([EndOperation.Ack, EndOperation.Ack, EndOperation.Ack]);
});
it('nack allUpTo 2 msgs sync', async () => {
await Promise.all(lodash.times(3, () => asyncConfirmSend(confirmChannel, queueName, msgPayload)));
// @ts-ignore
await asyncConsume(confirmChannel, queueName, [
null,
(msg) => confirmChannel.nack(msg, true, false),
(msg) => confirmChannel.nack(msg, false, false),
]);
// assert all 3 messages are acked, including the first one which is acked by allUpTo
expect(getTestSpans().length).toBe(6);
lodash.range(3, 6).forEach((i) => {
expect(getTestSpans()[i].status.code).toEqual(SpanStatusCode.ERROR);
expect(getTestSpans()[i].status.message).toEqual('nack called on message without requeue');
});
expectConsumeEndSpyStatus([EndOperation.Nack, EndOperation.Nack, EndOperation.Nack]);
});
it('ack not in received order', async () => {
await Promise.all(lodash.times(3, () => asyncConfirmSend(confirmChannel, queueName, msgPayload)));
// @ts-ignore
const msgs = await asyncConsume(confirmChannel, queueName, [null, null, null]);
confirmChannel.ack(msgs[1]);
confirmChannel.ack(msgs[2]);
confirmChannel.ack(msgs[0]);
// assert all 3 span messages are ended
expect(getTestSpans().length).toBe(6);
expectConsumeEndSpyStatus([EndOperation.Ack, EndOperation.Ack, EndOperation.Ack]);
});
it('ackAll', async () => {
await Promise.all(lodash.times(2, () => asyncConfirmSend(confirmChannel, queueName, msgPayload)));
// @ts-ignore
await asyncConsume(confirmChannel, queueName, [null, () => confirmChannel.ackAll()]);
// assert all 2 span messages are ended by call to ackAll
expect(getTestSpans().length).toBe(4);
expectConsumeEndSpyStatus([EndOperation.AckAll, EndOperation.AckAll]);
});
it('nackAll', async () => {
await Promise.all(lodash.times(2, () => asyncConfirmSend(confirmChannel, queueName, msgPayload)));
// @ts-ignore
await asyncConsume(confirmChannel, queueName, [null, () => confirmChannel.nackAll(false)]);
// assert all 2 span messages are ended by calling nackAll
expect(getTestSpans().length).toBe(4);
lodash.range(2, 4).forEach((i) => {
expect(getTestSpans()[i].status.code).toEqual(SpanStatusCode.ERROR);
expect(getTestSpans()[i].status.message).toEqual('nackAll called on message without requeue');
});
expectConsumeEndSpyStatus([EndOperation.NackAll, EndOperation.NackAll]);
});
it('reject', async () => {
await Promise.all(lodash.times(1, () => asyncConfirmSend(confirmChannel, queueName, msgPayload)));
// @ts-ignore
await asyncConsume(confirmChannel, queueName, [(msg) => confirmChannel.reject(msg, false)]);
expect(getTestSpans().length).toBe(2);
expect(getTestSpans()[1].status.code).toEqual(SpanStatusCode.ERROR);
expect(getTestSpans()[1].status.message).toEqual('reject called on message without requeue');
expectConsumeEndSpyStatus([EndOperation.Reject]);
});
it('reject with requeue', async () => {
await Promise.all(lodash.times(1, () => asyncConfirmSend(confirmChannel, queueName, msgPayload)));
// @ts-ignore
await asyncConsume(confirmChannel, queueName, [
(msg) => confirmChannel.reject(msg, true),
(msg) => confirmChannel.reject(msg, false),
]);
expect(getTestSpans().length).toBe(3);
expect(getTestSpans()[1].status.code).toEqual(SpanStatusCode.ERROR);
expect(getTestSpans()[1].status.message).toEqual('reject called on message with requeue');
expect(getTestSpans()[2].status.code).toEqual(SpanStatusCode.ERROR);
expect(getTestSpans()[2].status.message).toEqual('reject called on message without requeue');
expectConsumeEndSpyStatus([EndOperation.Reject, EndOperation.Reject]);
});
it('closing channel should end all open spans on it', async () => {
await Promise.all(lodash.times(1, () => asyncConfirmSend(confirmChannel, queueName, msgPayload)));
await new Promise<void>((resolve) =>
asyncConsume(confirmChannel, queueName, [
async (msg) => {
await confirmChannel.close();
resolve();
confirmChannel[CHANNEL_CLOSED_IN_TEST] = true;
},
])
);
expect(getTestSpans().length).toBe(2);
expect(getTestSpans()[1].status.code).toEqual(SpanStatusCode.ERROR);
expect(getTestSpans()[1].status.message).toEqual('channel closed');
expectConsumeEndSpyStatus([EndOperation.ChannelClosed]);
});
it('error on channel should end all open spans on it', (done) => {
Promise.all(lodash.times(2, () => asyncConfirmSend(confirmChannel, queueName, msgPayload))).then(() => {
confirmChannel.on('close', () => {
expect(getTestSpans().length).toBe(4);
// second consume ended with valid ack, previous message not acked when channel is errored.
// since we first ack the second message, it appear first in the finished spans array
expect(getTestSpans()[2].status.code).toEqual(SpanStatusCode.UNSET);
expect(getTestSpans()[3].status.code).toEqual(SpanStatusCode.ERROR);
expect(getTestSpans()[3].status.message).toEqual('channel error');
expectConsumeEndSpyStatus([EndOperation.Ack, EndOperation.ChannelError]);
done();
});
asyncConsume(confirmChannel, queueName, [
null,
(msg) => {
try {
confirmChannel.ack(msg);
confirmChannel[CHANNEL_CLOSED_IN_TEST] = true;
// ack the same msg again, this is not valid and should close the channel
confirmChannel.ack(msg);
} catch {}
},
]);
});
});
it('not acking the message trigger timeout', async () => {
instrumentation.setConfig({
consumeEndHook: endHookSpy,
consumeTimeoutMs: 1,
});
await Promise.all(lodash.times(1, () => asyncConfirmSend(confirmChannel, queueName, msgPayload)));
await asyncConsume(confirmChannel, queueName, [null]);
// we have timeout of 1 ms, so we wait more than that and check span indeed ended
await new Promise((resolve) => setTimeout(resolve, 10));
expect(getTestSpans().length).toBe(2);
expectConsumeEndSpyStatus([EndOperation.InstrumentationTimeout]);
});
});
describe('routing and exchange', () => {
it('topic exchange', async () => {
const exchangeName = 'topic exchange';
const routingKey = 'topic.name.from.unittest';
await confirmChannel.assertExchange(exchangeName, 'topic', { durable: false });
const { queue: queueName } = await confirmChannel.assertQueue('', { durable: false });
await confirmChannel.bindQueue(queueName, exchangeName, '#');
await asyncConfirmPublish(confirmChannel, exchangeName, routingKey, msgPayload);
await asyncConsume(confirmChannel, queueName, [null], {
noAck: true,
});
const [publishSpan, consumeSpan] = getTestSpans();
// assert publish span
expect(publishSpan.kind).toEqual(SpanKind.PRODUCER);
expect(publishSpan.attributes[SemanticAttributes.MESSAGING_SYSTEM]).toEqual('rabbitmq');
expect(publishSpan.attributes[SemanticAttributes.MESSAGING_DESTINATION]).toEqual(exchangeName);
expect(publishSpan.attributes[SemanticAttributes.MESSAGING_DESTINATION_KIND]).toEqual(
MessagingDestinationKindValues.TOPIC
);
expect(publishSpan.attributes[SemanticAttributes.MESSAGING_RABBITMQ_ROUTING_KEY]).toEqual(routingKey);
expect(publishSpan.attributes[SemanticAttributes.MESSAGING_PROTOCOL]).toEqual('AMQP');
expect(publishSpan.attributes[SemanticAttributes.MESSAGING_PROTOCOL_VERSION]).toEqual('0.9.1');
// assert consume span
expect(consumeSpan.kind).toEqual(SpanKind.CONSUMER);
expect(consumeSpan.attributes[SemanticAttributes.MESSAGING_SYSTEM]).toEqual('rabbitmq');
expect(consumeSpan.attributes[SemanticAttributes.MESSAGING_DESTINATION]).toEqual(exchangeName);
expect(consumeSpan.attributes[SemanticAttributes.MESSAGING_DESTINATION_KIND]).toEqual(
MessagingDestinationKindValues.TOPIC
);
expect(consumeSpan.attributes[SemanticAttributes.MESSAGING_RABBITMQ_ROUTING_KEY]).toEqual(routingKey);
expect(consumeSpan.attributes[SemanticAttributes.MESSAGING_PROTOCOL]).toEqual('AMQP');
expect(consumeSpan.attributes[SemanticAttributes.MESSAGING_PROTOCOL_VERSION]).toEqual('0.9.1');
// assert context propagation
expect(consumeSpan.spanContext().traceId).toEqual(publishSpan.spanContext().traceId);
expect(consumeSpan.parentSpanId).toEqual(publishSpan.spanContext().spanId);
});
});
it('moduleVersionAttributeName works with publish and consume', async () => {
const VERSION_ATTR = 'module.version';
instrumentation.setConfig({
moduleVersionAttributeName: VERSION_ATTR,
});
await asyncConfirmSend(confirmChannel, queueName, msgPayload);
await asyncConsume(
confirmChannel,
queueName,
[(msg) => expect(msg.content.toString()).toEqual(msgPayload)],
{
noAck: true,
}
);
expect(getTestSpans().length).toBe(2);
getTestSpans().forEach((s) => expect(s.attributes[VERSION_ATTR]).toMatch(/\d{1,4}\.\d{1,4}\.\d{1,5}.*/));
});
describe('hooks', () => {
it('publish and consume hooks success', async () => {
const attributeNameFromHook = 'attribute.name.from.hook';
const hookAttributeValue = 'attribute value from hook';
const attributeNameFromConfirmEndHook = 'attribute.name.from.confirm.endhook';
const confirmEndHookAttributeValue = 'attribute value from confirm end hook';
const attributeNameFromConsumeEndHook = 'attribute.name.from.consume.endhook';
const consumeEndHookAttributeValue = 'attribute value from consume end hook';
instrumentation.setConfig({
publishHook: (span: Span, publishParams: PublishParams) => {
span.setAttribute(attributeNameFromHook, hookAttributeValue);
expect(publishParams.exchange).toEqual('');
expect(publishParams.routingKey).toEqual(queueName);
expect(publishParams.content.toString()).toEqual(msgPayload);
expect(publishParams.isConfirmChannel).toBe(true);
},
publishConfirmHook: (span, publishParams) => {
span.setAttribute(attributeNameFromConfirmEndHook, confirmEndHookAttributeValue);
expect(publishParams.exchange).toEqual('');
expect(publishParams.routingKey).toEqual(queueName);
expect(publishParams.content.toString()).toEqual(msgPayload);
},
consumeHook: (span: Span, msg: amqp.ConsumeMessage | null) => {
span.setAttribute(attributeNameFromHook, hookAttributeValue);
expect(msg.content.toString()).toEqual(msgPayload);
},
consumeEndHook: (
span: Span,
msg: amqp.ConsumeMessage | null,
rejected: boolean,
endOperation: EndOperation
): void => {
span.setAttribute(attributeNameFromConsumeEndHook, consumeEndHookAttributeValue);
expect(endOperation).toEqual(EndOperation.AutoAck);
},
});
await asyncConfirmSend(confirmChannel, queueName, msgPayload);
await asyncConsume(confirmChannel, queueName, [null], {
noAck: true,
});
expect(getTestSpans().length).toBe(2);
expect(getTestSpans()[0].attributes[attributeNameFromHook]).toEqual(hookAttributeValue);
expect(getTestSpans()[0].attributes[attributeNameFromConfirmEndHook]).toEqual(
confirmEndHookAttributeValue
);
expect(getTestSpans()[1].attributes[attributeNameFromHook]).toEqual(hookAttributeValue);
expect(getTestSpans()[1].attributes[attributeNameFromConsumeEndHook]).toEqual(
consumeEndHookAttributeValue
);
});
it('hooks throw should not affect user flow or span creation', async () => {
const attributeNameFromHook = 'attribute.name.from.hook';
const hookAttributeValue = 'attribute value from hook';
instrumentation.setConfig({
publishHook: (span: Span, publishParams: PublishParams): void => {
span.setAttribute(attributeNameFromHook, hookAttributeValue);
throw new Error('error from hook');
},
publishConfirmHook: (span: Span, publishParams: PublishParams): void => {
span.setAttribute(attributeNameFromHook, hookAttributeValue);
throw new Error('error from hook');
},
consumeHook: (span: Span, msg: amqp.ConsumeMessage | null): void => {
span.setAttribute(attributeNameFromHook, hookAttributeValue);
throw new Error('error from hook');
},
});
await asyncConfirmSend(confirmChannel, queueName, msgPayload);
await asyncConsume(confirmChannel, queueName, [null], {
noAck: true,
});
expect(getTestSpans().length).toBe(2);
getTestSpans().forEach((s) => expect(s.attributes[attributeNameFromHook]).toEqual(hookAttributeValue));
});
});
});
}); | the_stack |
import type * as aj from './animatedJava'
import * as fs from 'fs'
import * as path from 'path'
import { tl } from './util/intl'
import { mkdir } from './util/ezfs'
import { settings } from './settings'
import { CustomError } from './util/customError'
import { format, safeFunctionName } from './util/replace'
import { getModelPath } from './util/minecraft/resourcepack'
// @ts-ignore
import transparent from './assets/transparent.png'
// Exports the model.json rig files
async function exportRigModels(
models: aj.ModelObject,
variantModels: aj.VariantModels
) {
console.groupCollapsed('Export Rig Models')
const metaPath = path.join(
settings.animatedJava.rigModelsExportFolder,
'.aj_meta'
)
if (!fs.existsSync(metaPath)) {
const files = fs.readdirSync(
settings.animatedJava.rigModelsExportFolder
)
// If the meta folder is empty, just write the meta and export models. However it there are other files/folder in there, show a warning.
if (files.length > 0) {
await new Promise<void>((resolve, reject) => {
let d = new Dialog({
id: 'animatedJava.rigFolderHasUnknownContent',
title: tl(
'animatedJava.dialogs.errors.rigFolderHasUnknownContent.title'
),
lines: [
tl(
'animatedJava.dialogs.errors.rigFolderHasUnknownContent.body',
{
path: settings.animatedJava
.rigModelsExportFolder,
files: files.join(', '),
}
),
],
// @ts-ignore
width: 512 + 128,
buttons: ['Overwrite', 'Cancel'],
confirmIndex: 0,
cancelIndex: 1,
onConfirm() {
d.hide()
Blockbench.writeFile(metaPath, {
// @ts-ignore
content: Project.UUID,
custom_writer: null,
})
resolve()
},
onCancel() {
d.hide()
reject(
new CustomError(
'Rig Folder Unused -> User Cancelled Export Process',
{ intentional: true, silent: true }
)
)
},
}).show()
})
} else {
Blockbench.writeFile(metaPath, {
// @ts-ignore
content: Project.UUID,
custom_writer: null,
})
}
// @ts-ignore
} else if (fs.readFileSync(metaPath, 'utf-8') !== Project.UUID) {
const files = fs.readdirSync(
settings.animatedJava.rigModelsExportFolder
)
await new Promise<void>((resolve, reject) => {
let d = new Dialog({
id: 'animatedJava.rigFolderAlreadyUsedByOther',
title: tl(
'animatedJava.dialogs.errors.rigFolderAlreadyUsedByOther.title'
),
lines: [
tl(
'animatedJava.dialogs.errors.rigFolderAlreadyUsedByOther.body',
{
path: settings.animatedJava.rigModelsExportFolder,
files: files.join(', '),
}
),
],
// @ts-ignore
width: 512 + 128,
buttons: ['Overwrite', 'Cancel'],
confirmIndex: 0,
cancelIndex: 1,
onConfirm() {
d.hide()
Blockbench.writeFile(metaPath, {
// @ts-ignore
content: Project.UUID,
custom_writer: null,
})
resolve()
},
onCancel() {
d.hide()
reject(
new CustomError(
'Rig Folder Already Occupied -> User Cancelled Export Process',
{ intentional: true, silent: true }
)
)
},
}).show()
})
}
console.log('Export Models:', models)
console.group('Details')
for (const [name, model] of Object.entries(models)) {
// Get the model's file path
const modelFilePath = path.join(
settings.animatedJava.rigModelsExportFolder,
name + '.json'
)
console.log('Exporting Model', modelFilePath, model.elements)
// Export the model
const modelJSON = {
__credit:
'Generated using Animated Java (https://animated-java.dev/)',
...model,
aj: undefined,
}
Blockbench.writeFile(modelFilePath, {
content: autoStringify(modelJSON),
custom_writer: null,
})
}
console.groupEnd()
console.log('Export Variant Models:', variantModels)
console.group('Details')
for (const [variantName, variant] of Object.entries(variantModels)) {
const variantFolderPath = path.join(
settings.animatedJava.rigModelsExportFolder,
variantName
)
// Don't export empty variants
if (Object.entries(variant).length < 1) continue
mkdir(variantFolderPath, { recursive: true })
for (const [modelName, model] of Object.entries(variant)) {
// Get the model's file path
const modelFilePath = path.join(
variantFolderPath,
`${modelName}.json`
)
console.log('Exporting Model', modelFilePath)
// Export the model
const modelJSON = {
__credit:
'Generated using Animated Java (https://animated-java.dev/)',
...model,
aj: undefined,
}
Blockbench.writeFile(modelFilePath, {
content: autoStringify(modelJSON),
custom_writer: null,
})
}
}
console.groupEnd()
console.groupEnd()
}
interface Override {
predicate: {
custom_model_data: number
}
model: string
}
interface PredicateModel {
parent: string
textures: {
layer0: string
}
overrides: Override[]
aj: {
includedRigs: Record<
string,
{
usedIDs: (number | [number, number])[]
name: string
}
>
}
}
function throwPredicateMergingError(reason: string) {
throw new CustomError('Predicate Missing Overrides List', {
intentional: true,
dialog: {
id: 'animatedJava.predicateMergeFailed',
title: tl(
'animatedJava.dialogs.errors.predicateMergeFailed.title',
{
reason,
}
),
lines: [
tl('animatedJava.dialogs.errors.predicateMergeFailed.body', {
reason,
}),
],
width: 512 + 256,
singleButton: true,
},
})
}
async function exportPredicate(
models: aj.ModelObject,
variantModels: aj.VariantModels,
ajSettings: aj.Settings
) {
console.groupCollapsed('Export Predicate Model')
const predicateJSON = {
parent: 'item/generated',
textures: {
layer0: `item/${ajSettings.rigItem.replace('minecraft:', '')}`,
},
overrides: [],
aj: {
includedRigs: {},
},
}
let usedIDs = []
function* idGen() {
let id = 1
while (true) {
if (!usedIDs.includes(id)) yield id
id++
}
}
if (fs.existsSync(ajSettings.predicateFilePath)) {
const stringContent = await fs.promises.readFile(
ajSettings.predicateFilePath,
{
encoding: 'utf-8',
}
)
let oldPredicate: PredicateModel
try {
oldPredicate = JSON.parse(stringContent)
} catch (err) {
throwPredicateMergingError(
tl(
'animatedJava.dialogs.errors.predicateMergeFailed.reasons.invalidJson'
)
)
}
console.log(oldPredicate)
// @ts-ignore
if (oldPredicate) {
if (!oldPredicate?.aj) {
throwPredicateMergingError(
tl(
'animatedJava.dialogs.errors.predicateMergeFailed.reasons.ajMetaMissing'
)
)
} else if (!oldPredicate.overrides) {
throwPredicateMergingError(
tl(
'animatedJava.dialogs.errors.predicateMergeFailed.reasons.overridesMissing'
)
)
}
}
const data = oldPredicate?.aj?.includedRigs || {}
if (!oldPredicate?.aj?.includedRigs) {
data.preExistingIds = {
name: 'preExistingIds',
usedIDs: packArr(
oldPredicate.overrides.map((override) => {
usedIDs.push(override.predicate.custom_model_data)
return override.predicate.custom_model_data
})
),
}
} else {
Object.entries(data).forEach(([id, dat]) => {
let ids = dat.usedIDs
// @ts-ignore
if (id !== Project.UUID) {
for (let i = 0; i < ids.length; i++) {
if (Array.isArray(ids[i])) {
for (let k = ids[i][0]; k <= ids[i][1]; k++) {
usedIDs.push(k)
}
} else {
usedIDs.push(ids[i])
}
}
}
})
}
// @ts-ignore
delete data[Project.UUID]
predicateJSON.aj.includedRigs = data
predicateJSON.overrides = oldPredicate.overrides.filter((override) => {
return usedIDs.includes(override.predicate.custom_model_data)
})
}
const idGenerator = idGen()
let myMeta = []
for (const [modelName, model] of Object.entries(models)) {
// this will always be a number as the generator is infinite.
model.aj.customModelData = idGenerator.next().value as number
predicateJSON.overrides.push({
predicate: { custom_model_data: model.aj.customModelData },
model: getModelPath(
path.join(ajSettings.rigModelsExportFolder, modelName),
modelName
),
})
myMeta.push(model.aj.customModelData)
}
for (const [variantName, variant] of Object.entries(variantModels))
for (const [modelName, model] of Object.entries(variant)) {
model.aj.customModelData = idGenerator.next().value as number
myMeta.push(model.aj.customModelData)
predicateJSON.overrides.push({
predicate: { custom_model_data: model.aj.customModelData },
model: getModelPath(
path.join(
ajSettings.rigModelsExportFolder,
variantName,
modelName
),
modelName
),
})
}
predicateJSON.overrides.sort((a: any, b: any) => {
return a.predicate.custom_model_data - b.predicate.custom_model_data
})
//@ts-ignore
predicateJSON.aj.includedRigs[Project.UUID] = {
name: settings.animatedJava.projectName,
usedIDs: packArr(myMeta),
}
Blockbench.writeFile(ajSettings.predicateFilePath, {
content: autoStringify(predicateJSON),
custom_writer: null,
})
console.groupEnd()
}
function packArr(arr) {
//take an array of numbers and return an array of ranges of consecutive numbers and if a number is not consecutive it is put in its the resulting array
let result = []
let currentRange = [arr[0]]
for (let i = 1; i < arr.length; i++) {
if (arr[i] - arr[i - 1] === 1) {
currentRange.push(arr[i])
} else {
result.push(currentRange)
currentRange = [arr[i]]
}
}
result.push(currentRange)
return result.map((range) => {
if (range.length === 1) {
return range[0]
} else {
return [range[0], range[range.length - 1]]
}
})
}
async function exportTransparentTexture() {
console.log(transparent)
Blockbench.writeFile(settings.animatedJava.transparentTexturePath, {
content: Buffer.from(
String(transparent).replace('data:image/png;base64,', ''),
'base64'
),
custom_writer: null,
})
}
export { exportRigModels, exportPredicate, exportTransparentTexture } | the_stack |
import { expect } from "chai";
import React from "react";
import sinon from "sinon";
import { ColorByName, ColorDef } from "@itwin/core-common";
import { fireEvent, render } from "@testing-library/react";
import { RelativePosition, SpecialKey } from "@itwin/appui-abstract";
import { TestUtils } from "../TestUtils";
import { ColorPickerPopup } from "../../imodel-components-react/color/ColorPickerPopup";
describe("<ColorPickerPopup/>", () => {
const colorDef = ColorDef.create(ColorByName.blue);
before(async () => {
await TestUtils.initializeUiIModelComponents();
});
after(() => {
TestUtils.terminateUiIModelComponents();
});
it("should render", () => {
const renderedComponent = render(<ColorPickerPopup initialColor={colorDef} />);
expect(renderedComponent).not.to.be.undefined;
expect(renderedComponent.container.querySelector(".components-caret")).to.be.null;
});
it("should render with caret", () => {
const renderedComponent = render(<ColorPickerPopup initialColor={colorDef} showCaret />);
expect(renderedComponent).not.to.be.undefined;
expect(renderedComponent.container.querySelector(".components-caret")).not.to.be.null;
});
it("button press should open popup and allow color selection", async () => {
const spyOnColorPick = sinon.spy();
function handleColorPick(color: ColorDef): void {
expect(color.tbgr).to.be.equal(ColorByName.red as number);
spyOnColorPick();
}
const renderedComponent = render(<ColorPickerPopup initialColor={colorDef} onColorChange={handleColorPick} showCaret />);
expect(renderedComponent.getByTestId("components-colorpicker-popup-button")).to.exist;
const pickerButton = renderedComponent.getByTestId("components-colorpicker-popup-button");
expect(pickerButton.tagName).to.be.equal("BUTTON");
expect(renderedComponent.container.querySelector(".icon-caret-down")).not.to.be.null;
fireEvent.click(pickerButton);
expect(renderedComponent.container.querySelector(".icon-caret-up")).not.to.be.null;
const popupDiv = renderedComponent.getByTestId("components-colorpicker-panel");
expect(popupDiv).not.to.be.undefined;
if (popupDiv) {
const colorSwatch = popupDiv.querySelector("button.components-colorpicker-panel-swatch") as HTMLElement;
expect(colorSwatch).not.to.be.null;
fireEvent.click(colorSwatch);
expect(spyOnColorPick).to.be.calledOnce;
}
});
it("button press should open popup and allow color selection of specified preset", async () => {
const spyOnColorPick = sinon.spy();
function handleColorPick(color: ColorDef): void {
expect(color.tbgr).to.be.equal(ColorByName.green as number);
spyOnColorPick();
}
const renderedComponent = render(<ColorPickerPopup initialColor={colorDef} popupPosition={RelativePosition.BottomRight} colorDefs={[ColorDef.green, ColorDef.black, ColorDef.red]} onColorChange={handleColorPick} />);
expect(renderedComponent.getByTestId("components-colorpicker-popup-button")).to.exist;
const pickerButton = renderedComponent.getByTestId("components-colorpicker-popup-button");
expect(pickerButton.tagName).to.be.equal("BUTTON");
fireEvent.click(pickerButton);
const popupDiv = renderedComponent.getByTestId("components-colorpicker-panel");
expect(popupDiv).not.to.be.undefined;
if (popupDiv) {
const colorSwatch = popupDiv.querySelector("button.components-colorpicker-panel-swatch") as HTMLElement;
expect(colorSwatch).not.to.be.null;
fireEvent.click(colorSwatch);
expect(spyOnColorPick).to.be.calledOnce;
}
});
it("readonly - button press should not open popup", async () => {
const renderedComponent = render(<ColorPickerPopup initialColor={colorDef} colorDefs={[ColorDef.blue, ColorDef.black, ColorDef.red]} readonly={true} />);
const pickerButton = renderedComponent.getByTestId("components-colorpicker-popup-button");
expect(pickerButton.tagName).to.be.equal("BUTTON");
fireEvent.click(pickerButton);
const corePopupDiv = renderedComponent.queryByTestId("core-popup");
expect(corePopupDiv).not.to.be.null;
if (corePopupDiv)
expect(corePopupDiv.classList.contains("visible")).to.be.false;
});
it("button press should open popup and allow trigger color selection when popup closed", async () => {
const spyOnColorPopupClosed = sinon.spy();
function handleColorPopupClosed(color: ColorDef): void {
expect(color.tbgr).to.be.equal(ColorDef.green.tbgr);
spyOnColorPopupClosed();
}
const renderedComponent = render(<ColorPickerPopup initialColor={colorDef} popupPosition={RelativePosition.BottomRight} colorDefs={[ColorDef.green, ColorDef.black, ColorDef.red]} onClose={handleColorPopupClosed} />);
expect(renderedComponent.getByTestId("components-colorpicker-popup-button")).to.exist;
const pickerButton = renderedComponent.getByTestId("components-colorpicker-popup-button");
expect(pickerButton.tagName).to.be.equal("BUTTON");
fireEvent.click(pickerButton);
const popupDiv = renderedComponent.getByTestId("components-colorpicker-panel");
expect(popupDiv).not.to.be.undefined;
if (popupDiv) {
const colorSwatch = popupDiv.querySelector("button.components-colorpicker-panel-swatch") as HTMLElement;
expect(colorSwatch).not.to.be.null;
fireEvent.click(colorSwatch);
}
fireEvent.click(pickerButton); /* close popup */
expect(spyOnColorPopupClosed).to.be.calledOnce;
});
it("captureClicks property should stop mouse click propagation", async () => {
const spyOnClick = sinon.spy();
/* eslint-disable-next-line jsx-a11y/no-static-element-interactions, jsx-a11y/click-events-have-key-events */
const renderedComponent = render(<div onClick={spyOnClick}>
<ColorPickerPopup initialColor={colorDef} popupPosition={RelativePosition.BottomRight} colorDefs={[ColorDef.green, ColorDef.black, ColorDef.red]} captureClicks={true} />
</div>);
const pickerButton = renderedComponent.getByTestId("components-colorpicker-popup-button");
fireEvent.click(pickerButton);
expect(spyOnClick).not.to.be.called;
const popupDiv = renderedComponent.getByTestId("components-colorpicker-panel");
expect(popupDiv).not.to.be.undefined;
if (popupDiv) {
const colorSwatch = popupDiv.querySelector("button.components-colorpicker-panel-swatch") as HTMLElement;
expect(colorSwatch).not.to.be.null;
fireEvent.click(colorSwatch);
}
expect(spyOnClick).not.to.be.called;
});
it("mouse click should propagate if captureClicks not set to true", async () => {
const spyOnClick = sinon.spy();
/* eslint-disable-next-line jsx-a11y/no-static-element-interactions, jsx-a11y/click-events-have-key-events */
const renderedComponent = render(<div onClick={spyOnClick}>
<ColorPickerPopup initialColor={colorDef} popupPosition={RelativePosition.BottomRight} colorDefs={[ColorDef.green, ColorDef.black, ColorDef.red]} />
</div>);
const pickerButton = renderedComponent.getByTestId("components-colorpicker-popup-button");
fireEvent.click(pickerButton);
expect(spyOnClick).to.be.called;
const popupDiv = renderedComponent.getByTestId("components-colorpicker-panel");
expect(popupDiv).not.to.be.undefined;
if (popupDiv) {
const colorSwatch = popupDiv.querySelector("button.components-colorpicker-panel-swatch") as HTMLElement;
expect(colorSwatch).not.to.be.null;
fireEvent.click(colorSwatch);
}
expect(spyOnClick).to.be.calledTwice;
});
it("ensure update prop is handled", async () => {
/* eslint-disable-next-line jsx-a11y/no-static-element-interactions, jsx-a11y/click-events-have-key-events */
const renderedComponent = render(<div>
<ColorPickerPopup initialColor={colorDef} popupPosition={RelativePosition.BottomRight} colorDefs={[ColorDef.green, ColorDef.black, ColorDef.red]} />
</div>);
let colorSwatch = renderedComponent.container.querySelector("div.components-colorpicker-button-color-swatch") as HTMLElement;
expect(colorSwatch.style.backgroundColor).to.eql("rgb(0, 0, 255)");
// ensure update prop is handled
const newColorDef = ColorDef.create(ColorByName.green); // green = 0x008000,
renderedComponent.rerender(<div><ColorPickerPopup initialColor={newColorDef} popupPosition={RelativePosition.BottomRight} colorDefs={[ColorDef.green, ColorDef.black, ColorDef.red]} /></div>);
colorSwatch = renderedComponent.container.querySelector("div.components-colorpicker-button-color-swatch") as HTMLElement;
expect(colorSwatch.style.backgroundColor).to.eql("rgb(0, 128, 0)");
});
it("ensure closing X is shown", async () => {
const spyOnClick = sinon.spy();
/* eslint-disable-next-line jsx-a11y/no-static-element-interactions, jsx-a11y/click-events-have-key-events */
const renderedComponent = render(<div>
<ColorPickerPopup initialColor={colorDef} popupPosition={RelativePosition.BottomRight}
colorDefs={[ColorDef.green, ColorDef.black, ColorDef.red]} captureClicks={true} onClick={spyOnClick} />
</div>);
const pickerButton = renderedComponent.getByTestId("components-colorpicker-popup-button");
fireEvent.click(pickerButton);
const popupDiv = renderedComponent.getByTestId("components-colorpicker-panel");
expect(popupDiv).not.to.be.undefined;
const closeButton = renderedComponent.getByTestId("core-dialog-close");
fireEvent.click(closeButton);
await TestUtils.flushAsyncOperations();
expect(renderedComponent.container.querySelector("button.core-dialog-close")).to.be.null;
});
it("ensure closing X is NOT shown", async () => {
const spyOnClick = sinon.spy();
/* eslint-disable-next-line jsx-a11y/no-static-element-interactions, jsx-a11y/click-events-have-key-events */
const renderedComponent = render(<div>
<ColorPickerPopup initialColor={colorDef} popupPosition={RelativePosition.BottomRight} hideCloseButton
colorDefs={[ColorDef.green, ColorDef.black, ColorDef.red]} captureClicks={true} onClick={spyOnClick} />
</div>);
const pickerButton = renderedComponent.getByTestId("components-colorpicker-popup-button");
fireEvent.click(pickerButton);
const popupDiv = renderedComponent.getByTestId("components-colorpicker-panel");
expect(popupDiv).not.to.be.undefined;
expect(popupDiv.querySelector("button.core-dialog-close")).to.be.null;
});
it("ensure rgb values are shown", async () => {
const spyOnClick = sinon.spy();
const spyOnChange = sinon.spy();
/* eslint-disable-next-line jsx-a11y/no-static-element-interactions, jsx-a11y/click-events-have-key-events */
const renderedComponent = render(<div>
<ColorPickerPopup initialColor={colorDef} popupPosition={RelativePosition.BottomRight} colorInputType="RGB"
colorDefs={[ColorDef.green, ColorDef.black, ColorDef.red]} captureClicks={true} onClick={spyOnClick} onColorChange={spyOnChange} />
</div>);
const pickerButton = renderedComponent.getByTestId("components-colorpicker-popup-button");
fireEvent.click(pickerButton);
const popupDiv = renderedComponent.getByTestId("components-colorpicker-panel");
expect(popupDiv).not.to.be.undefined;
const redInput = renderedComponent.getByTestId("components-colorpicker-input-value-red");
fireEvent.change(redInput, { target: { value: "100" } });
expect((redInput as HTMLInputElement).value).to.eq("100");
fireEvent.keyDown(redInput, { key: SpecialKey.Enter });
spyOnChange.calledOnce.should.be.true;
spyOnChange.resetHistory();
const greenInput = renderedComponent.getByTestId("components-colorpicker-input-value-green");
fireEvent.change(greenInput, { target: { value: "100" } });
expect((greenInput as HTMLInputElement).value).to.eq("100");
fireEvent.keyDown(greenInput, { key: SpecialKey.Enter });
spyOnChange.calledOnce.should.be.true;
spyOnChange.resetHistory();
const blueInput = renderedComponent.getByTestId("components-colorpicker-input-value-blue");
fireEvent.change(blueInput, { target: { value: "100" } });
expect((blueInput as HTMLInputElement).value).to.eq("100");
fireEvent.keyDown(blueInput, { key: SpecialKey.Enter });
spyOnChange.calledOnce.should.be.true;
});
it("ensure hsl values are shown", async () => {
const spyOnClick = sinon.spy();
const spyOnChange = sinon.spy();
/* eslint-disable-next-line jsx-a11y/no-static-element-interactions, jsx-a11y/click-events-have-key-events */
const renderedComponent = render(<div>
<ColorPickerPopup initialColor={colorDef} popupPosition={RelativePosition.BottomRight} colorInputType="HSL"
colorDefs={[ColorDef.green, ColorDef.black, ColorDef.red]} captureClicks={true} onClick={spyOnClick} onColorChange={spyOnChange} />
</div>);
const pickerButton = renderedComponent.getByTestId("components-colorpicker-popup-button");
fireEvent.click(pickerButton);
const popupDiv = renderedComponent.getByTestId("components-colorpicker-panel");
expect(popupDiv).not.to.be.undefined;
const hueInput = renderedComponent.getByTestId("components-colorpicker-input-value-hue");
fireEvent.change(hueInput, { target: { value: "100" } });
expect((hueInput as HTMLInputElement).value).to.eq("100");
fireEvent.keyDown(hueInput, { key: SpecialKey.Enter });
spyOnChange.calledOnce.should.be.true;
spyOnChange.resetHistory();
const saturationInput = renderedComponent.getByTestId("components-colorpicker-input-value-saturation");
fireEvent.change(saturationInput, { target: { value: "50" } });
expect((saturationInput as HTMLInputElement).value).to.eq("50");
fireEvent.keyDown(saturationInput, { key: SpecialKey.Enter });
spyOnChange.calledOnce.should.be.true;
spyOnChange.resetHistory();
const lightnessInput = renderedComponent.getByTestId("components-colorpicker-input-value-lightness");
fireEvent.change(lightnessInput, { target: { value: "40" } });
expect((lightnessInput as HTMLInputElement).value).to.eq("40");
fireEvent.keyDown(lightnessInput, { key: SpecialKey.Enter });
spyOnChange.calledOnce.should.be.true;
});
}); | the_stack |
import { App } from '../app';
import { getStorage } from '../storage/index';
import { FirebaseError } from '../utils/error';
import * as validator from '../utils/validator';
import { deepCopy } from '../utils/deep-copy';
import * as utils from '../utils';
import {
MachineLearningApiClient, ModelResponse, ModelUpdateOptions, isGcsTfliteModelOptions,
ListModelsOptions, ModelOptions,
} from './machine-learning-api-client';
import { FirebaseMachineLearningError } from './machine-learning-utils';
/** Response object for a listModels operation. */
export interface ListModelsResult {
/** A list of models in your project. */
readonly models: Model[];
/**
* A token you can use to retrieve the next page of results. If null, the
* current page is the final page.
*/
readonly pageToken?: string;
}
/**
* A TensorFlow Lite Model output object
*
* One of either the `gcsTfliteUri` or `automlModel` properties will be
* defined.
*/
export interface TFLiteModel {
/** The size of the model. */
readonly sizeBytes: number;
/** The URI from which the model was originally provided to Firebase. */
readonly gcsTfliteUri?: string;
/**
* The AutoML model reference from which the model was originally provided
* to Firebase.
*/
readonly automlModel?: string;
}
/**
* The Firebase `MachineLearning` service interface.
*/
export class MachineLearning {
private readonly client: MachineLearningApiClient;
private readonly appInternal: App;
/**
* @param app - The app for this ML service.
* @constructor
* @internal
*/
constructor(app: App) {
if (!validator.isNonNullObject(app) || !('options' in app)) {
throw new FirebaseError({
code: 'machine-learning/invalid-argument',
message: 'First argument passed to admin.machineLearning() must be a ' +
'valid Firebase app instance.',
});
}
this.appInternal = app;
this.client = new MachineLearningApiClient(app);
}
/**
* The {@link firebase-admin.app#App} associated with the current `MachineLearning`
* service instance.
*/
public get app(): App {
return this.appInternal;
}
/**
* Creates a model in the current Firebase project.
*
* @param model - The model to create.
*
* @returns A Promise fulfilled with the created model.
*/
public createModel(model: ModelOptions): Promise<Model> {
return this.signUrlIfPresent(model)
.then((modelContent) => this.client.createModel(modelContent))
.then((operation) => this.client.handleOperation(operation))
.then((modelResponse) => new Model(modelResponse, this.client));
}
/**
* Updates a model's metadata or model file.
*
* @param modelId - The ID of the model to update.
* @param model - The model fields to update.
*
* @returns A Promise fulfilled with the updated model.
*/
public updateModel(modelId: string, model: ModelOptions): Promise<Model> {
const updateMask = utils.generateUpdateMask(model);
return this.signUrlIfPresent(model)
.then((modelContent) => this.client.updateModel(modelId, modelContent, updateMask))
.then((operation) => this.client.handleOperation(operation))
.then((modelResponse) => new Model(modelResponse, this.client));
}
/**
* Publishes a Firebase ML model.
*
* A published model can be downloaded to client apps.
*
* @param modelId - The ID of the model to publish.
*
* @returns A Promise fulfilled with the published model.
*/
public publishModel(modelId: string): Promise<Model> {
return this.setPublishStatus(modelId, true);
}
/**
* Unpublishes a Firebase ML model.
*
* @param modelId - The ID of the model to unpublish.
*
* @returns A Promise fulfilled with the unpublished model.
*/
public unpublishModel(modelId: string): Promise<Model> {
return this.setPublishStatus(modelId, false);
}
/**
* Gets the model specified by the given ID.
*
* @param modelId - The ID of the model to get.
*
* @returns A Promise fulfilled with the model object.
*/
public getModel(modelId: string): Promise<Model> {
return this.client.getModel(modelId)
.then((modelResponse) => new Model(modelResponse, this.client));
}
/**
* Lists the current project's models.
*
* @param options - The listing options.
*
* @returns A promise that
* resolves with the current (filtered) list of models and the next page
* token. For the last page, an empty list of models and no page token
* are returned.
*/
public listModels(options: ListModelsOptions = {}): Promise<ListModelsResult> {
return this.client.listModels(options)
.then((resp) => {
if (!validator.isNonNullObject(resp)) {
throw new FirebaseMachineLearningError(
'invalid-argument',
`Invalid ListModels response: ${JSON.stringify(resp)}`);
}
let models: Model[] = [];
if (resp.models) {
models = resp.models.map((rs) => new Model(rs, this.client));
}
const result: { models: Model[]; pageToken?: string } = { models };
if (resp.nextPageToken) {
result.pageToken = resp.nextPageToken;
}
return result;
});
}
/**
* Deletes a model from the current project.
*
* @param modelId - The ID of the model to delete.
*/
public deleteModel(modelId: string): Promise<void> {
return this.client.deleteModel(modelId);
}
private setPublishStatus(modelId: string, publish: boolean): Promise<Model> {
const updateMask = ['state.published'];
const options: ModelUpdateOptions = { state: { published: publish } };
return this.client.updateModel(modelId, options, updateMask)
.then((operation) => this.client.handleOperation(operation))
.then((modelResponse) => new Model(modelResponse, this.client));
}
private signUrlIfPresent(options: ModelOptions): Promise<ModelOptions> {
const modelOptions = deepCopy(options);
if (isGcsTfliteModelOptions(modelOptions)) {
return this.signUrl(modelOptions.tfliteModel.gcsTfliteUri)
.then((uri: string) => {
modelOptions.tfliteModel.gcsTfliteUri = uri;
return modelOptions;
})
.catch((err: Error) => {
throw new FirebaseMachineLearningError(
'internal-error',
`Error during signing upload url: ${err.message}`);
});
}
return Promise.resolve(modelOptions);
}
private signUrl(unsignedUrl: string): Promise<string> {
const MINUTES_IN_MILLIS = 60 * 1000;
const URL_VALID_DURATION = 10 * MINUTES_IN_MILLIS;
const gcsRegex = /^gs:\/\/([a-z0-9_.-]{3,63})\/(.+)$/;
const matches = gcsRegex.exec(unsignedUrl);
if (!matches) {
throw new FirebaseMachineLearningError(
'invalid-argument',
`Invalid unsigned url: ${unsignedUrl}`);
}
const bucketName = matches[1];
const blobName = matches[2];
const bucket = getStorage(this.app).bucket(bucketName);
const blob = bucket.file(blobName);
return blob.getSignedUrl({
action: 'read',
expires: Date.now() + URL_VALID_DURATION,
}).then((signUrl) => signUrl[0]);
}
}
/**
* A Firebase ML Model output object.
*/
export class Model {
private model: ModelResponse;
private readonly client?: MachineLearningApiClient;
/**
* @internal
*/
constructor(model: ModelResponse, client: MachineLearningApiClient) {
this.model = Model.validateAndClone(model);
this.client = client;
}
/** The ID of the model. */
get modelId(): string {
return extractModelId(this.model.name);
}
/**
* The model's name. This is the name you use from your app to load the
* model.
*/
get displayName(): string {
return this.model.displayName!;
}
/**
* The model's tags, which can be used to group or filter models in list
* operations.
*/
get tags(): string[] {
return this.model.tags || [];
}
/** The timestamp of the model's creation. */
get createTime(): string {
return new Date(this.model.createTime).toUTCString();
}
/** The timestamp of the model's most recent update. */
get updateTime(): string {
return new Date(this.model.updateTime).toUTCString();
}
/** Error message when model validation fails. */
get validationError(): string | undefined {
return this.model.state?.validationError?.message;
}
/** True if the model is published. */
get published(): boolean {
return this.model.state?.published || false;
}
/**
* The ETag identifier of the current version of the model. This value
* changes whenever you update any of the model's properties.
*/
get etag(): string {
return this.model.etag;
}
/**
* The hash of the model's `tflite` file. This value changes only when
* you upload a new TensorFlow Lite model.
*/
get modelHash(): string | undefined {
return this.model.modelHash;
}
/** Metadata about the model's TensorFlow Lite model file. */
get tfliteModel(): TFLiteModel | undefined {
// Make a copy so people can't directly modify the private this.model object.
return deepCopy(this.model.tfliteModel);
}
/**
* True if the model is locked by a server-side operation. You can't make
* changes to a locked model. See {@link Model.waitForUnlocked}.
*/
public get locked(): boolean {
return (this.model.activeOperations?.length ?? 0) > 0;
}
/**
* Return the model as a JSON object.
*/
public toJSON(): {[key: string]: any} {
// We can't just return this.model because it has extra fields and
// different formats etc. So we build the expected model object.
const jsonModel: {[key: string]: any} = {
modelId: this.modelId,
displayName: this.displayName,
tags: this.tags,
createTime: this.createTime,
updateTime: this.updateTime,
published: this.published,
etag: this.etag,
locked: this.locked,
};
// Also add possibly undefined fields if they exist.
if (this.validationError) {
jsonModel['validationError'] = this.validationError;
}
if (this.modelHash) {
jsonModel['modelHash'] = this.modelHash;
}
if (this.tfliteModel) {
jsonModel['tfliteModel'] = this.tfliteModel;
}
return jsonModel;
}
/**
* Wait for the model to be unlocked.
*
* @param maxTimeMillis - The maximum time in milliseconds to wait.
* If not specified, a default maximum of 2 minutes is used.
*
* @returns A promise that resolves when the model is unlocked
* or the maximum wait time has passed.
*/
public waitForUnlocked(maxTimeMillis?: number): Promise<void> {
if ((this.model.activeOperations?.length ?? 0) > 0) {
// The client will always be defined on Models that have activeOperations
// because models with active operations came back from the server and
// were constructed with a non-empty client.
return this.client!.handleOperation(this.model.activeOperations![0], { wait: true, maxTimeMillis })
.then((modelResponse) => {
this.model = Model.validateAndClone(modelResponse);
});
}
return Promise.resolve();
}
private static validateAndClone(model: ModelResponse): ModelResponse {
if (!validator.isNonNullObject(model) ||
!validator.isNonEmptyString(model.name) ||
!validator.isNonEmptyString(model.createTime) ||
!validator.isNonEmptyString(model.updateTime) ||
!validator.isNonEmptyString(model.displayName) ||
!validator.isNonEmptyString(model.etag)) {
throw new FirebaseMachineLearningError(
'invalid-server-response',
`Invalid Model response: ${JSON.stringify(model)}`);
}
const tmpModel = deepCopy(model);
// If tflite Model is specified, it must have a source consisting of
// oneof {gcsTfliteUri, automlModel}
if (model.tfliteModel &&
!validator.isNonEmptyString(model.tfliteModel.gcsTfliteUri) &&
!validator.isNonEmptyString(model.tfliteModel.automlModel)) {
// If we have some other source, ignore the whole tfliteModel.
delete (tmpModel as any).tfliteModel;
}
// Remove '@type' field. We don't need it.
if ((tmpModel as any)['@type']) {
delete (tmpModel as any)['@type'];
}
return tmpModel;
}
}
function extractModelId(resourceName: string): string {
return resourceName.split('/').pop()!;
} | the_stack |
import { PrpcClient } from '@chopsui/prpc-client';
import { assert } from '@open-wc/testing/index-no-side-effects';
import * as sinon from 'sinon';
import { genCacheKeyForPrpcRequest, removeDefaultProps } from './prpc_utils';
describe('genCacheKeyForPrpcRequest', () => {
it('should generate identical keys for identical requests', async () => {
const fetchStub = sinon.stub<[RequestInfo, RequestInit | undefined], Promise<Response>>();
const client = new PrpcClient({ fetchImpl: fetchStub });
client.call('service', 'method', { prop: 1 });
client.call('service', 'method', { prop: 1 });
const key1 = await genCacheKeyForPrpcRequest('prefix', new Request(...fetchStub.getCall(0).args));
const key2 = await genCacheKeyForPrpcRequest('prefix', new Request(...fetchStub.getCall(1).args));
assert.strictEqual(key1, key2);
});
it('should generate different keys for requests with different hosts', async () => {
const fetchStub = sinon.stub<[RequestInfo, RequestInit | undefined], Promise<Response>>();
const client1 = new PrpcClient({ host: 'host1', fetchImpl: fetchStub });
const client2 = new PrpcClient({ host: 'host2', fetchImpl: fetchStub });
client1.call('service', 'method', { prop: 1 });
client2.call('service', 'method', { prop: 1 });
const key1 = await genCacheKeyForPrpcRequest('prefix', new Request(...fetchStub.getCall(0).args));
const key2 = await genCacheKeyForPrpcRequest('prefix', new Request(...fetchStub.getCall(1).args));
assert.notStrictEqual(key1, key2);
});
it('should generate different keys for requests with different access tokens', async () => {
const fetchStub = sinon.stub<[RequestInfo, RequestInit | undefined], Promise<Response>>();
const client1 = new PrpcClient({ accessToken: 'token1', fetchImpl: fetchStub });
const client2 = new PrpcClient({ accessToken: 'token2', fetchImpl: fetchStub });
client1.call('service', 'method', { prop: 1 });
client2.call('service', 'method', { prop: 1 });
const key1 = await genCacheKeyForPrpcRequest('prefix', new Request(...fetchStub.getCall(0).args));
const key2 = await genCacheKeyForPrpcRequest('prefix', new Request(...fetchStub.getCall(1).args));
assert.notStrictEqual(key1, key2);
});
it('should generate different keys for requests with different secure modes', async () => {
const fetchStub = sinon.stub<[RequestInfo, RequestInit | undefined], Promise<Response>>();
const client1 = new PrpcClient({ insecure: true, fetchImpl: fetchStub });
const client2 = new PrpcClient({ insecure: false, fetchImpl: fetchStub });
client1.call('service', 'method', { prop: 1 });
client2.call('service', 'method', { prop: 1 });
const key1 = await genCacheKeyForPrpcRequest('prefix', new Request(...fetchStub.getCall(0).args));
const key2 = await genCacheKeyForPrpcRequest('prefix', new Request(...fetchStub.getCall(1).args));
assert.notStrictEqual(key1, key2);
});
it('should generate different keys for requests with different services', async () => {
const fetchStub = sinon.stub<[RequestInfo, RequestInit | undefined], Promise<Response>>();
const client = new PrpcClient({ fetchImpl: fetchStub });
client.call('service1', 'method', { prop: 1 });
client.call('service2', 'method', { prop: 1 });
const key1 = await genCacheKeyForPrpcRequest('prefix', new Request(...fetchStub.getCall(0).args));
const key2 = await genCacheKeyForPrpcRequest('prefix', new Request(...fetchStub.getCall(1).args));
assert.notStrictEqual(key1, key2);
});
it('should generate different keys for requests with different methods', async () => {
const fetchStub = sinon.stub<[RequestInfo, RequestInit | undefined], Promise<Response>>();
const client = new PrpcClient({ fetchImpl: fetchStub });
client.call('service', 'method1', { prop: 1 });
client.call('service', 'method2', { prop: 1 });
const key1 = await genCacheKeyForPrpcRequest('prefix', new Request(...fetchStub.getCall(0).args));
const key2 = await genCacheKeyForPrpcRequest('prefix', new Request(...fetchStub.getCall(1).args));
assert.notStrictEqual(key1, key2);
});
it('should generate different keys for requests with different bodies', async () => {
const fetchStub = sinon.stub<[RequestInfo, RequestInit | undefined], Promise<Response>>();
const client = new PrpcClient({ fetchImpl: fetchStub });
client.call('service', 'method', { prop: 1 });
client.call('service', 'method', { prop: 2 });
const key1 = await genCacheKeyForPrpcRequest('prefix', new Request(...fetchStub.getCall(0).args));
const key2 = await genCacheKeyForPrpcRequest('prefix', new Request(...fetchStub.getCall(1).args));
assert.notStrictEqual(key1, key2);
});
it('should generate different keys for requests with different critical headers', async () => {
const fetchStub = sinon.stub<[RequestInfo, RequestInit | undefined], Promise<Response>>();
const client = new PrpcClient({ fetchImpl: fetchStub });
client.call('service', 'method', { prop: 1 }, { 'header-key': 'header-value1' });
client.call('service', 'method', { prop: 1 }, { 'header-key': 'header-value2' });
const key1 = await genCacheKeyForPrpcRequest('prefix', new Request(...fetchStub.getCall(0).args), ['header-key']);
const key2 = await genCacheKeyForPrpcRequest('prefix', new Request(...fetchStub.getCall(1).args), ['header-key']);
assert.notStrictEqual(key1, key2);
});
it('should generate different keys for requests with different default critical headers', async () => {
const fetchStub = sinon.stub<[RequestInfo, RequestInit | undefined], Promise<Response>>();
const client = new PrpcClient({ fetchImpl: fetchStub });
client.call(
'service',
'method',
{ prop: 1 },
{ accept: 'accept', 'content-type': 'content-type', authorization: 'token' }
);
client.call(
'service',
'method',
{ prop: 1 },
{ accept: 'accept1', 'content-type': 'content-type', authorization: 'token' }
);
client.call(
'service',
'method',
{ prop: 1 },
{ accept: 'accept', 'content-type': 'content-type1', authorization: 'token' }
);
client.call(
'service',
'method',
{ prop: 1 },
{ accept: 'accept', 'content-type': 'content-type', authorization: 'token1' }
);
const key1 = await genCacheKeyForPrpcRequest('prefix', new Request(...fetchStub.getCall(0).args));
const key2 = await genCacheKeyForPrpcRequest('prefix', new Request(...fetchStub.getCall(1).args));
const key3 = await genCacheKeyForPrpcRequest('prefix', new Request(...fetchStub.getCall(2).args));
const key4 = await genCacheKeyForPrpcRequest('prefix', new Request(...fetchStub.getCall(3).args));
assert.notStrictEqual(key1, key2);
assert.notStrictEqual(key1, key3);
assert.notStrictEqual(key1, key4);
});
it('should generate identical keys for requests with different non-critical headers', async () => {
const fetchStub = sinon.stub<[RequestInfo, RequestInit | undefined], Promise<Response>>();
const client = new PrpcClient({ fetchImpl: fetchStub });
client.call('service', 'method', { prop: 1 }, { 'header-key': 'header-value1' });
client.call('service', 'method', { prop: 1 }, { 'header-key': 'header-value2' });
const key1 = await genCacheKeyForPrpcRequest('prefix', new Request(...fetchStub.getCall(0).args));
const key2 = await genCacheKeyForPrpcRequest('prefix', new Request(...fetchStub.getCall(1).args));
assert.strictEqual(key1, key2);
});
it('should generate identical keys for identical requests with different header key cases', async () => {
const fetchStub = sinon.stub<[RequestInfo, RequestInit | undefined], Promise<Response>>();
const client = new PrpcClient({ fetchImpl: fetchStub });
client.call('service', 'method', { prop: 1 }, { 'HEADER-KEY': 'header-value' });
client.call('service', 'method', { prop: 1 });
const key1 = await genCacheKeyForPrpcRequest('prefix', new Request(...fetchStub.getCall(0).args));
const key2 = await genCacheKeyForPrpcRequest('prefix', new Request(...fetchStub.getCall(1).args));
assert.strictEqual(key1, key2);
});
it('should generate different keys when prefix are different', async () => {
const fetchStub = sinon.stub<[RequestInfo, RequestInit | undefined], Promise<Response>>();
const client = new PrpcClient({ fetchImpl: fetchStub });
client.call('service', 'method', { prop: 1 });
client.call('service', 'method', { prop: 1 });
const key1 = await genCacheKeyForPrpcRequest('prefix1', new Request(...fetchStub.getCall(0).args));
const key2 = await genCacheKeyForPrpcRequest('prefix2', new Request(...fetchStub.getCall(1).args));
assert.notStrictEqual(key1, key2);
});
it('should generate identical keys when false-ish properties are omitted', async () => {
const fetchStub = sinon.stub<[RequestInfo, RequestInit | undefined], Promise<Response>>();
const client = new PrpcClient({ fetchImpl: fetchStub });
client.call('service', 'method', { prop: 1, pageToken: '', emptyArray: [] });
client.call('service', 'method', { prop: 1 });
const key1 = await genCacheKeyForPrpcRequest('prefix', new Request(...fetchStub.getCall(0).args));
const key2 = await genCacheKeyForPrpcRequest('prefix', new Request(...fetchStub.getCall(1).args));
assert.strictEqual(key1, key2);
});
});
describe('removeDefaultProps', () => {
it('should remove false-ish properties', async () => {
const original = {
prop: 1,
emptyString: '',
falseValue: false,
nullValue: null,
emptyArray: [],
emptyObj: {},
obj: {
deepEmptyString: '',
},
nonEmptyArray: [''],
};
const originalStr = JSON.stringify(original);
const processed = removeDefaultProps(original);
assert.deepStrictEqual(processed, {
prop: 1,
emptyObj: {},
obj: {},
nonEmptyArray: [''],
});
// The original object should not be modified.
assert.strictEqual(JSON.stringify(original), originalStr);
});
}); | the_stack |
* Fonoster
* No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
*
* The version of the OpenAPI document: v1beta1
* Contact: psanders@fonoster.com
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
import { Configuration } from './configuration';
import globalAxios, { AxiosPromise, AxiosInstance, AxiosRequestConfig } from 'axios';
// Some imports not used depending on template conditions
// @ts-ignore
import { DUMMY_BASE_URL, assertParamExists, setApiKeyToObject, setBasicAuthToObject, setBearerAuthToObject, setOAuthToObject, setSearchParams, serializeDataIfNeeded, toPathString, createRequestFunction } from './common';
// @ts-ignore
import { BASE_PATH, COLLECTION_FORMATS, RequestArgs, BaseAPI, RequiredError } from './base';
/**
*
* @export
* @interface Agent
*/
export interface Agent {
/**
*
* @type {string}
* @memberof Agent
*/
'ref'?: string;
/**
*
* @type {string}
* @memberof Agent
*/
'name': string;
/**
*
* @type {string}
* @memberof Agent
*/
'username': string;
/**
*
* @type {string}
* @memberof Agent
*/
'secret': string;
/**
*
* @type {Array<string>}
* @memberof Agent
*/
'domains': Array<string>;
/**
*
* @type {string}
* @memberof Agent
*/
'privacy'?: string;
/**
*
* @type {string}
* @memberof Agent
*/
'createTime'?: string;
/**
*
* @type {string}
* @memberof Agent
*/
'updateTime'?: string;
}
/**
*
* @export
* @interface CallRequest
*/
export interface CallRequest {
/**
*
* @type {string}
* @memberof CallRequest
*/
'from'?: string;
/**
*
* @type {string}
* @memberof CallRequest
*/
'to'?: string;
/**
*
* @type {string}
* @memberof CallRequest
*/
'webhook'?: string;
/**
*
* @type {boolean}
* @memberof CallRequest
*/
'ignoreE164Validation'?: boolean;
/**
*
* @type {string}
* @memberof CallRequest
*/
'metadata'?: string;
}
/**
*
* @export
* @interface CallResponse
*/
export interface CallResponse {
/**
*
* @type {string}
* @memberof CallResponse
*/
'ref'?: string;
}
/**
*
* @export
* @interface CreateAgentRequest
*/
export interface CreateAgentRequest {
/**
*
* @type {string}
* @memberof CreateAgentRequest
*/
'name': string;
/**
*
* @type {string}
* @memberof CreateAgentRequest
*/
'username': string;
/**
*
* @type {string}
* @memberof CreateAgentRequest
*/
'secret': string;
/**
*
* @type {Array<string>}
* @memberof CreateAgentRequest
*/
'domains': Array<string>;
/**
*
* @type {string}
* @memberof CreateAgentRequest
*/
'privacy'?: string;
}
/**
*
* @export
* @interface CreateDomainRequest
*/
export interface CreateDomainRequest {
/**
*
* @type {string}
* @memberof CreateDomainRequest
*/
'name': string;
/**
*
* @type {string}
* @memberof CreateDomainRequest
*/
'domainUri': string;
/**
*
* @type {string}
* @memberof CreateDomainRequest
*/
'egressRule'?: string;
/**
*
* @type {string}
* @memberof CreateDomainRequest
*/
'egressNumberRef'?: string;
/**
*
* @type {Array<string>}
* @memberof CreateDomainRequest
*/
'accessDeny'?: Array<string>;
/**
*
* @type {Array<string>}
* @memberof CreateDomainRequest
*/
'accessAllow'?: Array<string>;
}
/**
*
* @export
* @interface CreateNumberRequest
*/
export interface CreateNumberRequest {
/**
*
* @type {string}
* @memberof CreateNumberRequest
*/
'providerRef': string;
/**
*
* @type {string}
* @memberof CreateNumberRequest
*/
'e164Number': string;
/**
*
* @type {string}
* @memberof CreateNumberRequest
*/
'aorLink'?: string;
/**
*
* @type {IngressInfo}
* @memberof CreateNumberRequest
*/
'ingressInfo'?: IngressInfo;
}
/**
*
* @export
* @interface CreateProjectRequest
*/
export interface CreateProjectRequest {
/**
*
* @type {string}
* @memberof CreateProjectRequest
*/
'name': string;
/**
*
* @type {boolean}
* @memberof CreateProjectRequest
*/
'allowExperiments'?: boolean;
}
/**
*
* @export
* @interface CreateProviderRequest
*/
export interface CreateProviderRequest {
/**
*
* @type {string}
* @memberof CreateProviderRequest
*/
'name': string;
/**
*
* @type {string}
* @memberof CreateProviderRequest
*/
'username': string;
/**
*
* @type {string}
* @memberof CreateProviderRequest
*/
'secret': string;
/**
*
* @type {string}
* @memberof CreateProviderRequest
*/
'host': string;
/**
*
* @type {string}
* @memberof CreateProviderRequest
*/
'transport': string;
/**
*
* @type {number}
* @memberof CreateProviderRequest
*/
'expires'?: number;
}
/**
*
* @export
* @interface CreateRegistryTokenResponse
*/
export interface CreateRegistryTokenResponse {
/**
*
* @type {string}
* @memberof CreateRegistryTokenResponse
*/
'token'?: string;
/**
*
* @type {string}
* @memberof CreateRegistryTokenResponse
*/
'image'?: string;
}
/**
*
* @export
* @interface CreateSecretRequest
*/
export interface CreateSecretRequest {
/**
*
* @type {string}
* @memberof CreateSecretRequest
*/
'name'?: string;
/**
*
* @type {string}
* @memberof CreateSecretRequest
*/
'secret'?: string;
}
/**
*
* @export
* @interface CreateSecretResponse
*/
export interface CreateSecretResponse {
/**
*
* @type {string}
* @memberof CreateSecretResponse
*/
'name'?: string;
}
/**
*
* @export
* @interface CreateTokenRequest
*/
export interface CreateTokenRequest {
/**
*
* @type {string}
* @memberof CreateTokenRequest
*/
'roleName': string;
/**
*
* @type {string}
* @memberof CreateTokenRequest
*/
'accessKeyId': string;
/**
*
* @type {string}
* @memberof CreateTokenRequest
*/
'expiration'?: string;
}
/**
*
* @export
* @interface CreateTokenResponse
*/
export interface CreateTokenResponse {
/**
*
* @type {string}
* @memberof CreateTokenResponse
*/
'token'?: string;
}
/**
*
* @export
* @interface CreateUserCredentialsRequest
*/
export interface CreateUserCredentialsRequest {
/**
*
* @type {string}
* @memberof CreateUserCredentialsRequest
*/
'email'?: string;
/**
*
* @type {string}
* @memberof CreateUserCredentialsRequest
*/
'secret'?: string;
/**
*
* @type {string}
* @memberof CreateUserCredentialsRequest
*/
'expiration'?: string;
}
/**
*
* @export
* @interface CreateUserCredentialsResponse
*/
export interface CreateUserCredentialsResponse {
/**
*
* @type {string}
* @memberof CreateUserCredentialsResponse
*/
'accessKeyId'?: string;
/**
*
* @type {string}
* @memberof CreateUserCredentialsResponse
*/
'accessKeySecret'?: string;
}
/**
*
* @export
* @interface CreateUserRequest
*/
export interface CreateUserRequest {
/**
*
* @type {string}
* @memberof CreateUserRequest
*/
'email': string;
/**
*
* @type {string}
* @memberof CreateUserRequest
*/
'name': string;
/**
*
* @type {string}
* @memberof CreateUserRequest
*/
'secret': string;
/**
*
* @type {string}
* @memberof CreateUserRequest
*/
'avatar'?: string;
}
/**
*
* @export
* @interface DeployStream
*/
export interface DeployStream {
/**
*
* @type {string}
* @memberof DeployStream
*/
'text'?: string;
}
/**
*
* @export
* @interface Domain
*/
export interface Domain {
/**
*
* @type {string}
* @memberof Domain
*/
'ref'?: string;
/**
*
* @type {string}
* @memberof Domain
*/
'name': string;
/**
*
* @type {string}
* @memberof Domain
*/
'domainUri': string;
/**
*
* @type {string}
* @memberof Domain
*/
'egressRule'?: string;
/**
*
* @type {string}
* @memberof Domain
*/
'egressNumberRef'?: string;
/**
*
* @type {Array<string>}
* @memberof Domain
*/
'accessDeny'?: Array<string>;
/**
*
* @type {Array<string>}
* @memberof Domain
*/
'accessAllow'?: Array<string>;
/**
*
* @type {string}
* @memberof Domain
*/
'createTime'?: string;
/**
*
* @type {string}
* @memberof Domain
*/
'updateTime'?: string;
}
/**
*
* @export
* @interface ErrorResponse
*/
export interface ErrorResponse {
/**
*
* @type {number}
* @memberof ErrorResponse
*/
'status'?: number;
/**
*
* @type {string}
* @memberof ErrorResponse
*/
'message'?: string;
}
/**
*
* @export
* @interface Func
*/
export interface Func {
/**
*
* @type {string}
* @memberof Func
*/
'name'?: string;
/**
*
* @type {string}
* @memberof Func
*/
'image'?: string;
/**
*
* @type {number}
* @memberof Func
*/
'invocationCount'?: number;
/**
*
* @type {number}
* @memberof Func
*/
'replicas'?: number;
/**
*
* @type {number}
* @memberof Func
*/
'availableReplicas'?: number;
/**
*
* @type {Resource}
* @memberof Func
*/
'limits'?: Resource;
/**
*
* @type {Resource}
* @memberof Func
*/
'requests'?: Resource;
/**
*
* @type {string}
* @memberof Func
*/
'schedule'?: string;
}
/**
*
* @export
* @interface FuncLog
*/
export interface FuncLog {
/**
*
* @type {string}
* @memberof FuncLog
*/
'name'?: string;
/**
*
* @type {string}
* @memberof FuncLog
*/
'instance'?: string;
/**
*
* @type {string}
* @memberof FuncLog
*/
'timestamp'?: string;
/**
*
* @type {string}
* @memberof FuncLog
*/
'text'?: string;
}
/**
*
* @export
* @enum {string}
*/
export enum GetObjectURLRequestBucket {
Apps = 'APPS',
Recordings = 'RECORDINGS',
Public = 'PUBLIC',
Funcs = 'FUNCS'
}
/**
*
* @export
* @interface GetObjectURLResponse
*/
export interface GetObjectURLResponse {
/**
*
* @type {string}
* @memberof GetObjectURLResponse
*/
'url'?: string;
}
/**
*
* @export
* @interface GetSecretResponse
*/
export interface GetSecretResponse {
/**
*
* @type {string}
* @memberof GetSecretResponse
*/
'name'?: string;
/**
*
* @type {string}
* @memberof GetSecretResponse
*/
'secret'?: string;
}
/**
*
* @export
* @interface IngressInfo
*/
export interface IngressInfo {
/**
*
* @type {string}
* @memberof IngressInfo
*/
'accessKeyId'?: string;
/**
*
* @type {string}
* @memberof IngressInfo
*/
'webhook'?: string;
}
/**
*
* @export
* @interface InlineObject
*/
export interface InlineObject {
/**
*
* @type {string}
* @memberof InlineObject
*/
'name'?: string;
/**
*
* @type {string}
* @memberof InlineObject
*/
'username'?: string;
/**
*
* @type {string}
* @memberof InlineObject
*/
'secret'?: string;
/**
*
* @type {Array<string>}
* @memberof InlineObject
*/
'domains'?: Array<string>;
/**
*
* @type {string}
* @memberof InlineObject
*/
'privacy'?: string;
}
/**
*
* @export
* @interface InlineObject1
*/
export interface InlineObject1 {
/**
*
* @type {string}
* @memberof InlineObject1
*/
'name'?: string;
/**
*
* @type {string}
* @memberof InlineObject1
*/
'egressRule'?: string;
/**
*
* @type {string}
* @memberof InlineObject1
*/
'egressNumberRef'?: string;
/**
*
* @type {Array<string>}
* @memberof InlineObject1
*/
'accessDeny'?: Array<string>;
/**
*
* @type {Array<string>}
* @memberof InlineObject1
*/
'accessAllow'?: Array<string>;
}
/**
*
* @export
* @interface InlineObject2
*/
export interface InlineObject2 {
/**
*
* @type {string}
* @memberof InlineObject2
*/
'aorLink'?: string;
/**
*
* @type {IngressInfo}
* @memberof InlineObject2
*/
'ingressInfo'?: IngressInfo;
}
/**
*
* @export
* @interface InlineObject3
*/
export interface InlineObject3 {
/**
*
* @type {string}
* @memberof InlineObject3
*/
'name'?: string;
/**
*
* @type {boolean}
* @memberof InlineObject3
*/
'allowExperiments': boolean;
}
/**
*
* @export
* @interface InlineObject4
*/
export interface InlineObject4 {
/**
*
* @type {string}
* @memberof InlineObject4
*/
'name': string;
/**
*
* @type {string}
* @memberof InlineObject4
*/
'username': string;
/**
*
* @type {string}
* @memberof InlineObject4
*/
'secret': string;
/**
*
* @type {string}
* @memberof InlineObject4
*/
'host': string;
/**
*
* @type {string}
* @memberof InlineObject4
*/
'transport': string;
/**
*
* @type {number}
* @memberof InlineObject4
*/
'expires'?: number;
}
/**
*
* @export
* @interface InlineObject5
*/
export interface InlineObject5 {
/**
*
* @type {string}
* @memberof InlineObject5
*/
'name'?: string;
/**
*
* @type {string}
* @memberof InlineObject5
*/
'secret'?: string;
/**
*
* @type {string}
* @memberof InlineObject5
*/
'avatar'?: string;
}
/**
*
* @export
* @interface ListAgentsResponse
*/
export interface ListAgentsResponse {
/**
*
* @type {Array<Agent>}
* @memberof ListAgentsResponse
*/
'agents'?: Array<Agent>;
/**
*
* @type {string}
* @memberof ListAgentsResponse
*/
'nextPageToken'?: string;
}
/**
*
* @export
* @interface ListDomainsResponse
*/
export interface ListDomainsResponse {
/**
*
* @type {Array<Domain>}
* @memberof ListDomainsResponse
*/
'domains'?: Array<Domain>;
/**
*
* @type {string}
* @memberof ListDomainsResponse
*/
'nextPageToken'?: string;
}
/**
*
* @export
* @interface ListFuncsResponse
*/
export interface ListFuncsResponse {
/**
*
* @type {Array<Func>}
* @memberof ListFuncsResponse
*/
'funcs'?: Array<Func>;
/**
*
* @type {string}
* @memberof ListFuncsResponse
*/
'nextPageToken'?: string;
}
/**
*
* @export
* @interface ListNumbersResponse
*/
export interface ListNumbersResponse {
/**
*
* @type {Array<Number>}
* @memberof ListNumbersResponse
*/
'numbers'?: Array<Number>;
/**
* Token to retrieve the next page of results, or empty if there are no more results in the list.
* @type {string}
* @memberof ListNumbersResponse
*/
'nextPageToken'?: string;
}
/**
*
* @export
* @interface ListProjectsResponse
*/
export interface ListProjectsResponse {
/**
*
* @type {Array<Project>}
* @memberof ListProjectsResponse
*/
'projects'?: Array<Project>;
}
/**
*
* @export
* @interface ListProvidersResponse
*/
export interface ListProvidersResponse {
/**
*
* @type {Array<Provider>}
* @memberof ListProvidersResponse
*/
'providers'?: Array<Provider>;
/**
*
* @type {string}
* @memberof ListProvidersResponse
*/
'nextPageToken'?: string;
}
/**
*
* @export
* @interface ListSecretIdResponse
*/
export interface ListSecretIdResponse {
/**
*
* @type {Array<SecretName>}
* @memberof ListSecretIdResponse
*/
'secrets'?: Array<SecretName>;
/**
*
* @type {string}
* @memberof ListSecretIdResponse
*/
'nextPageToken'?: string;
}
/**
*
* @export
* @interface ListUsersResponse
*/
export interface ListUsersResponse {
/**
*
* @type {Array<User>}
* @memberof ListUsersResponse
*/
'users'?: Array<User>;
}
/**
*
* @export
* @interface Number
*/
export interface Number {
/**
*
* @type {string}
* @memberof Number
*/
'ref'?: string;
/**
*
* @type {string}
* @memberof Number
*/
'providerRef': string;
/**
*
* @type {string}
* @memberof Number
*/
'e164Number': string;
/**
*
* @type {string}
* @memberof Number
*/
'aorLink'?: string;
/**
*
* @type {IngressInfo}
* @memberof Number
*/
'ingressInfo'?: IngressInfo;
/**
*
* @type {string}
* @memberof Number
*/
'createTime'?: string;
/**
*
* @type {string}
* @memberof Number
*/
'updateTime'?: string;
}
/**
*
* @export
* @interface Project
*/
export interface Project {
/**
*
* @type {string}
* @memberof Project
*/
'name': string;
/**
*
* @type {string}
* @memberof Project
*/
'ref': string;
/**
*
* @type {string}
* @memberof Project
*/
'userRef': string;
/**
*
* @type {string}
* @memberof Project
*/
'accessKeyId': string;
/**
*
* @type {string}
* @memberof Project
*/
'accessKeySecret': string;
/**
*
* @type {boolean}
* @memberof Project
*/
'allowExperiments'?: boolean;
/**
*
* @type {string}
* @memberof Project
*/
'createTime'?: string;
/**
*
* @type {string}
* @memberof Project
*/
'updateTime'?: string;
}
/**
*
* @export
* @interface Provider
*/
export interface Provider {
/**
*
* @type {string}
* @memberof Provider
*/
'ref'?: string;
/**
*
* @type {string}
* @memberof Provider
*/
'name': string;
/**
*
* @type {string}
* @memberof Provider
*/
'username': string;
/**
*
* @type {string}
* @memberof Provider
*/
'secret': string;
/**
*
* @type {string}
* @memberof Provider
*/
'host': string;
/**
*
* @type {string}
* @memberof Provider
*/
'transport': string;
/**
*
* @type {number}
* @memberof Provider
*/
'expires'?: number;
/**
*
* @type {string}
* @memberof Provider
*/
'createTime'?: string;
/**
*
* @type {string}
* @memberof Provider
*/
'updateTime'?: string;
}
/**
*
* @export
* @interface RenewAccessKeySecretResponse
*/
export interface RenewAccessKeySecretResponse {
/**
*
* @type {string}
* @memberof RenewAccessKeySecretResponse
*/
'accessKeySecret'?: string;
}
/**
*
* @export
* @interface Resource
*/
export interface Resource {
/**
*
* @type {string}
* @memberof Resource
*/
'memory'?: string;
/**
*
* @type {string}
* @memberof Resource
*/
'cpu'?: string;
}
/**
*
* @export
* @interface Role
*/
export interface Role {
/**
*
* @type {string}
* @memberof Role
*/
'name'?: string;
/**
*
* @type {string}
* @memberof Role
*/
'description'?: string;
/**
*
* @type {Array<string>}
* @memberof Role
*/
'access'?: Array<string>;
}
/**
*
* @export
* @interface SecretName
*/
export interface SecretName {
/**
*
* @type {string}
* @memberof SecretName
*/
'name'?: string;
}
/**
*
* @export
* @enum {string}
*/
export enum UploadObjectRequestBucket {
Apps = 'APPS',
Recordings = 'RECORDINGS',
Public = 'PUBLIC',
Funcs = 'FUNCS'
}
/**
*
* @export
* @interface UploadObjectResponse
*/
export interface UploadObjectResponse {
/**
*
* @type {number}
* @memberof UploadObjectResponse
*/
'size'?: number;
}
/**
*
* @export
* @interface User
*/
export interface User {
/**
*
* @type {string}
* @memberof User
*/
'ref': string;
/**
*
* @type {string}
* @memberof User
*/
'accessKeyId': string;
/**
*
* @type {string}
* @memberof User
*/
'email': string;
/**
*
* @type {string}
* @memberof User
*/
'name': string;
/**
*
* @type {string}
* @memberof User
*/
'avatar'?: string;
/**
*
* @type {string}
* @memberof User
*/
'createTime'?: string;
/**
*
* @type {string}
* @memberof User
*/
'updateTime'?: string;
}
/**
*
* @export
* @interface ValidateTokenResponse
*/
export interface ValidateTokenResponse {
/**
*
* @type {boolean}
* @memberof ValidateTokenResponse
*/
'valid'?: boolean;
}
/**
*
* @export
* @enum {string}
*/
export enum View {
Basic = 'BASIC',
Standard = 'STANDARD',
Full = 'FULL'
}
/**
* AgentsApi - axios parameter creator
* @export
*/
export const AgentsApiAxiosParamCreator = function (configuration?: Configuration) {
return {
/**
*
* @summary Creates a new Agent resource
* @param {CreateAgentRequest} body
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
createAgent: async (body: CreateAgentRequest, options: AxiosRequestConfig = {}): Promise<RequestArgs> => {
// verify required parameter 'body' is not null or undefined
assertParamExists('createAgent', 'body', body)
const localVarPath = `/v1beta1/agents`;
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'POST', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
// authentication AccessKeyId required
await setApiKeyToObject(localVarHeaderParameter, "access_key_id", configuration)
// authentication AccessKeySecret required
await setApiKeyToObject(localVarHeaderParameter, "access_key_secret", configuration)
localVarHeaderParameter['Content-Type'] = 'application/json';
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
localVarRequestOptions.data = serializeDataIfNeeded(body, localVarRequestOptions, configuration)
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
*
* @summary Hard delete of an Agent resource
* @param {string} ref Agent\'s reference
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
deleteAgent: async (ref: string, options: AxiosRequestConfig = {}): Promise<RequestArgs> => {
// verify required parameter 'ref' is not null or undefined
assertParamExists('deleteAgent', 'ref', ref)
const localVarPath = `/v1beta1/agents/{ref}`
.replace(`{${"ref"}}`, encodeURIComponent(String(ref)));
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'DELETE', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
// authentication AccessKeyId required
await setApiKeyToObject(localVarHeaderParameter, "access_key_id", configuration)
// authentication AccessKeySecret required
await setApiKeyToObject(localVarHeaderParameter, "access_key_secret", configuration)
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
*
* @summary Gets Agent by reference
* @param {string} ref Agent\'s reference
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
getAgent: async (ref: string, options: AxiosRequestConfig = {}): Promise<RequestArgs> => {
// verify required parameter 'ref' is not null or undefined
assertParamExists('getAgent', 'ref', ref)
const localVarPath = `/v1beta1/agents/{ref}`
.replace(`{${"ref"}}`, encodeURIComponent(String(ref)));
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'GET', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
// authentication AccessKeyId required
await setApiKeyToObject(localVarHeaderParameter, "access_key_id", configuration)
// authentication AccessKeySecret required
await setApiKeyToObject(localVarHeaderParameter, "access_key_secret", configuration)
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
*
* @summary Lists Agents from the SIP Proxy subsystem
* @param {number} [pageSize] The maximum number of items in the list.
* @param {string} [pageToken] The next_page_token value returned from the previous request, if any.
* @param {'BASIC' | 'STANDARD' | 'FULL'} [view] Level of detail of the individual entities (reserved).
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
listAgents: async (pageSize?: number, pageToken?: string, view?: 'BASIC' | 'STANDARD' | 'FULL', options: AxiosRequestConfig = {}): Promise<RequestArgs> => {
const localVarPath = `/v1beta1/agents`;
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'GET', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
// authentication AccessKeyId required
await setApiKeyToObject(localVarHeaderParameter, "access_key_id", configuration)
// authentication AccessKeySecret required
await setApiKeyToObject(localVarHeaderParameter, "access_key_secret", configuration)
if (pageSize !== undefined) {
localVarQueryParameter['pageSize'] = pageSize;
}
if (pageToken !== undefined) {
localVarQueryParameter['pageToken'] = pageToken;
}
if (view !== undefined) {
localVarQueryParameter['view'] = view;
}
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
*
* @summary Change or update fields in a resource
* @param {string} ref Agent\'s reference
* @param {InlineObject} body
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
updateAgent: async (ref: string, body: InlineObject, options: AxiosRequestConfig = {}): Promise<RequestArgs> => {
// verify required parameter 'ref' is not null or undefined
assertParamExists('updateAgent', 'ref', ref)
// verify required parameter 'body' is not null or undefined
assertParamExists('updateAgent', 'body', body)
const localVarPath = `/v1beta1/agents/{ref}`
.replace(`{${"ref"}}`, encodeURIComponent(String(ref)));
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'PUT', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
// authentication AccessKeyId required
await setApiKeyToObject(localVarHeaderParameter, "access_key_id", configuration)
// authentication AccessKeySecret required
await setApiKeyToObject(localVarHeaderParameter, "access_key_secret", configuration)
localVarHeaderParameter['Content-Type'] = 'application/json';
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
localVarRequestOptions.data = serializeDataIfNeeded(body, localVarRequestOptions, configuration)
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
}
};
/**
* AgentsApi - functional programming interface
* @export
*/
export const AgentsApiFp = function(configuration?: Configuration) {
const localVarAxiosParamCreator = AgentsApiAxiosParamCreator(configuration)
return {
/**
*
* @summary Creates a new Agent resource
* @param {CreateAgentRequest} body
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async createAgent(body: CreateAgentRequest, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<Agent>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.createAgent(body, options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
},
/**
*
* @summary Hard delete of an Agent resource
* @param {string} ref Agent\'s reference
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async deleteAgent(ref: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<object>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.deleteAgent(ref, options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
},
/**
*
* @summary Gets Agent by reference
* @param {string} ref Agent\'s reference
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async getAgent(ref: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<Agent>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.getAgent(ref, options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
},
/**
*
* @summary Lists Agents from the SIP Proxy subsystem
* @param {number} [pageSize] The maximum number of items in the list.
* @param {string} [pageToken] The next_page_token value returned from the previous request, if any.
* @param {'BASIC' | 'STANDARD' | 'FULL'} [view] Level of detail of the individual entities (reserved).
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async listAgents(pageSize?: number, pageToken?: string, view?: 'BASIC' | 'STANDARD' | 'FULL', options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<ListAgentsResponse>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.listAgents(pageSize, pageToken, view, options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
},
/**
*
* @summary Change or update fields in a resource
* @param {string} ref Agent\'s reference
* @param {InlineObject} body
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async updateAgent(ref: string, body: InlineObject, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<Agent>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.updateAgent(ref, body, options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
},
}
};
/**
* AgentsApi - factory interface
* @export
*/
export const AgentsApiFactory = function (configuration?: Configuration, basePath?: string, axios?: AxiosInstance) {
const localVarFp = AgentsApiFp(configuration)
return {
/**
*
* @summary Creates a new Agent resource
* @param {CreateAgentRequest} body
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
createAgent(body: CreateAgentRequest, options?: any): AxiosPromise<Agent> {
return localVarFp.createAgent(body, options).then((request) => request(axios, basePath));
},
/**
*
* @summary Hard delete of an Agent resource
* @param {string} ref Agent\'s reference
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
deleteAgent(ref: string, options?: any): AxiosPromise<object> {
return localVarFp.deleteAgent(ref, options).then((request) => request(axios, basePath));
},
/**
*
* @summary Gets Agent by reference
* @param {string} ref Agent\'s reference
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
getAgent(ref: string, options?: any): AxiosPromise<Agent> {
return localVarFp.getAgent(ref, options).then((request) => request(axios, basePath));
},
/**
*
* @summary Lists Agents from the SIP Proxy subsystem
* @param {number} [pageSize] The maximum number of items in the list.
* @param {string} [pageToken] The next_page_token value returned from the previous request, if any.
* @param {'BASIC' | 'STANDARD' | 'FULL'} [view] Level of detail of the individual entities (reserved).
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
listAgents(pageSize?: number, pageToken?: string, view?: 'BASIC' | 'STANDARD' | 'FULL', options?: any): AxiosPromise<ListAgentsResponse> {
return localVarFp.listAgents(pageSize, pageToken, view, options).then((request) => request(axios, basePath));
},
/**
*
* @summary Change or update fields in a resource
* @param {string} ref Agent\'s reference
* @param {InlineObject} body
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
updateAgent(ref: string, body: InlineObject, options?: any): AxiosPromise<Agent> {
return localVarFp.updateAgent(ref, body, options).then((request) => request(axios, basePath));
},
};
};
/**
* AgentsApi - object-oriented interface
* @export
* @class AgentsApi
* @extends {BaseAPI}
*/
export class AgentsApi extends BaseAPI {
/**
*
* @summary Creates a new Agent resource
* @param {CreateAgentRequest} body
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof AgentsApi
*/
public createAgent(body: CreateAgentRequest, options?: AxiosRequestConfig) {
return AgentsApiFp(this.configuration).createAgent(body, options).then((request) => request(this.axios, this.basePath));
}
/**
*
* @summary Hard delete of an Agent resource
* @param {string} ref Agent\'s reference
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof AgentsApi
*/
public deleteAgent(ref: string, options?: AxiosRequestConfig) {
return AgentsApiFp(this.configuration).deleteAgent(ref, options).then((request) => request(this.axios, this.basePath));
}
/**
*
* @summary Gets Agent by reference
* @param {string} ref Agent\'s reference
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof AgentsApi
*/
public getAgent(ref: string, options?: AxiosRequestConfig) {
return AgentsApiFp(this.configuration).getAgent(ref, options).then((request) => request(this.axios, this.basePath));
}
/**
*
* @summary Lists Agents from the SIP Proxy subsystem
* @param {number} [pageSize] The maximum number of items in the list.
* @param {string} [pageToken] The next_page_token value returned from the previous request, if any.
* @param {'BASIC' | 'STANDARD' | 'FULL'} [view] Level of detail of the individual entities (reserved).
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof AgentsApi
*/
public listAgents(pageSize?: number, pageToken?: string, view?: 'BASIC' | 'STANDARD' | 'FULL', options?: AxiosRequestConfig) {
return AgentsApiFp(this.configuration).listAgents(pageSize, pageToken, view, options).then((request) => request(this.axios, this.basePath));
}
/**
*
* @summary Change or update fields in a resource
* @param {string} ref Agent\'s reference
* @param {InlineObject} body
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof AgentsApi
*/
public updateAgent(ref: string, body: InlineObject, options?: AxiosRequestConfig) {
return AgentsApiFp(this.configuration).updateAgent(ref, body, options).then((request) => request(this.axios, this.basePath));
}
}
/**
* AuthApi - axios parameter creator
* @export
*/
export const AuthApiAxiosParamCreator = function (configuration?: Configuration) {
return {
/**
*
* @summary Creates a new token for a given accessKeyId
* @param {CreateTokenRequest} body
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
createToken: async (body: CreateTokenRequest, options: AxiosRequestConfig = {}): Promise<RequestArgs> => {
// verify required parameter 'body' is not null or undefined
assertParamExists('createToken', 'body', body)
const localVarPath = `/v1beta1/auth/token`;
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'POST', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
// authentication AccessKeyId required
await setApiKeyToObject(localVarHeaderParameter, "access_key_id", configuration)
// authentication AccessKeySecret required
await setApiKeyToObject(localVarHeaderParameter, "access_key_secret", configuration)
localVarHeaderParameter['Content-Type'] = 'application/json';
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
localVarRequestOptions.data = serializeDataIfNeeded(body, localVarRequestOptions, configuration)
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
*
* @summary Gets a role by name
* @param {string} name
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
getRole: async (name: string, options: AxiosRequestConfig = {}): Promise<RequestArgs> => {
// verify required parameter 'name' is not null or undefined
assertParamExists('getRole', 'name', name)
const localVarPath = `/v1beta1/auth/role/{name}`
.replace(`{${"name"}}`, encodeURIComponent(String(name)));
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'GET', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
// authentication AccessKeyId required
await setApiKeyToObject(localVarHeaderParameter, "access_key_id", configuration)
// authentication AccessKeySecret required
await setApiKeyToObject(localVarHeaderParameter, "access_key_secret", configuration)
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
*
* @summary Verifies if a token was issue by Fonoster
* @param {string} token
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
validateToken: async (token: string, options: AxiosRequestConfig = {}): Promise<RequestArgs> => {
// verify required parameter 'token' is not null or undefined
assertParamExists('validateToken', 'token', token)
const localVarPath = `/v1beta1/auth/token/{token}`
.replace(`{${"token"}}`, encodeURIComponent(String(token)));
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'GET', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
// authentication AccessKeyId required
await setApiKeyToObject(localVarHeaderParameter, "access_key_id", configuration)
// authentication AccessKeySecret required
await setApiKeyToObject(localVarHeaderParameter, "access_key_secret", configuration)
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
}
};
/**
* AuthApi - functional programming interface
* @export
*/
export const AuthApiFp = function(configuration?: Configuration) {
const localVarAxiosParamCreator = AuthApiAxiosParamCreator(configuration)
return {
/**
*
* @summary Creates a new token for a given accessKeyId
* @param {CreateTokenRequest} body
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async createToken(body: CreateTokenRequest, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<CreateTokenResponse>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.createToken(body, options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
},
/**
*
* @summary Gets a role by name
* @param {string} name
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async getRole(name: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<Role>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.getRole(name, options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
},
/**
*
* @summary Verifies if a token was issue by Fonoster
* @param {string} token
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async validateToken(token: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<ValidateTokenResponse>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.validateToken(token, options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
},
}
};
/**
* AuthApi - factory interface
* @export
*/
export const AuthApiFactory = function (configuration?: Configuration, basePath?: string, axios?: AxiosInstance) {
const localVarFp = AuthApiFp(configuration)
return {
/**
*
* @summary Creates a new token for a given accessKeyId
* @param {CreateTokenRequest} body
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
createToken(body: CreateTokenRequest, options?: any): AxiosPromise<CreateTokenResponse> {
return localVarFp.createToken(body, options).then((request) => request(axios, basePath));
},
/**
*
* @summary Gets a role by name
* @param {string} name
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
getRole(name: string, options?: any): AxiosPromise<Role> {
return localVarFp.getRole(name, options).then((request) => request(axios, basePath));
},
/**
*
* @summary Verifies if a token was issue by Fonoster
* @param {string} token
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
validateToken(token: string, options?: any): AxiosPromise<ValidateTokenResponse> {
return localVarFp.validateToken(token, options).then((request) => request(axios, basePath));
},
};
};
/**
* AuthApi - object-oriented interface
* @export
* @class AuthApi
* @extends {BaseAPI}
*/
export class AuthApi extends BaseAPI {
/**
*
* @summary Creates a new token for a given accessKeyId
* @param {CreateTokenRequest} body
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof AuthApi
*/
public createToken(body: CreateTokenRequest, options?: AxiosRequestConfig) {
return AuthApiFp(this.configuration).createToken(body, options).then((request) => request(this.axios, this.basePath));
}
/**
*
* @summary Gets a role by name
* @param {string} name
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof AuthApi
*/
public getRole(name: string, options?: AxiosRequestConfig) {
return AuthApiFp(this.configuration).getRole(name, options).then((request) => request(this.axios, this.basePath));
}
/**
*
* @summary Verifies if a token was issue by Fonoster
* @param {string} token
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof AuthApi
*/
public validateToken(token: string, options?: AxiosRequestConfig) {
return AuthApiFp(this.configuration).validateToken(token, options).then((request) => request(this.axios, this.basePath));
}
}
/**
* CallManagerApi - axios parameter creator
* @export
*/
export const CallManagerApiAxiosParamCreator = function (configuration?: Configuration) {
return {
/**
*
* @summary Originates a call and pass channel to an application
* @param {CallRequest} body
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
call: async (body: CallRequest, options: AxiosRequestConfig = {}): Promise<RequestArgs> => {
// verify required parameter 'body' is not null or undefined
assertParamExists('call', 'body', body)
const localVarPath = `/v1beta1/call`;
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'POST', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
// authentication AccessKeyId required
await setApiKeyToObject(localVarHeaderParameter, "access_key_id", configuration)
// authentication AccessKeySecret required
await setApiKeyToObject(localVarHeaderParameter, "access_key_secret", configuration)
localVarHeaderParameter['Content-Type'] = 'application/json';
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
localVarRequestOptions.data = serializeDataIfNeeded(body, localVarRequestOptions, configuration)
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
}
};
/**
* CallManagerApi - functional programming interface
* @export
*/
export const CallManagerApiFp = function(configuration?: Configuration) {
const localVarAxiosParamCreator = CallManagerApiAxiosParamCreator(configuration)
return {
/**
*
* @summary Originates a call and pass channel to an application
* @param {CallRequest} body
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async call(body: CallRequest, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<CallResponse>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.call(body, options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
},
}
};
/**
* CallManagerApi - factory interface
* @export
*/
export const CallManagerApiFactory = function (configuration?: Configuration, basePath?: string, axios?: AxiosInstance) {
const localVarFp = CallManagerApiFp(configuration)
return {
/**
*
* @summary Originates a call and pass channel to an application
* @param {CallRequest} body
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
call(body: CallRequest, options?: any): AxiosPromise<CallResponse> {
return localVarFp.call(body, options).then((request) => request(axios, basePath));
},
};
};
/**
* CallManagerApi - object-oriented interface
* @export
* @class CallManagerApi
* @extends {BaseAPI}
*/
export class CallManagerApi extends BaseAPI {
/**
*
* @summary Originates a call and pass channel to an application
* @param {CallRequest} body
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof CallManagerApi
*/
public call(body: CallRequest, options?: AxiosRequestConfig) {
return CallManagerApiFp(this.configuration).call(body, options).then((request) => request(this.axios, this.basePath));
}
}
/**
* DomainsApi - axios parameter creator
* @export
*/
export const DomainsApiAxiosParamCreator = function (configuration?: Configuration) {
return {
/**
*
* @summary Creates a new Domain resource
* @param {CreateDomainRequest} body
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
createDomain: async (body: CreateDomainRequest, options: AxiosRequestConfig = {}): Promise<RequestArgs> => {
// verify required parameter 'body' is not null or undefined
assertParamExists('createDomain', 'body', body)
const localVarPath = `/v1beta1/domains`;
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'POST', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
// authentication AccessKeyId required
await setApiKeyToObject(localVarHeaderParameter, "access_key_id", configuration)
// authentication AccessKeySecret required
await setApiKeyToObject(localVarHeaderParameter, "access_key_secret", configuration)
localVarHeaderParameter['Content-Type'] = 'application/json';
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
localVarRequestOptions.data = serializeDataIfNeeded(body, localVarRequestOptions, configuration)
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
*
* @summary Hard delete of a domain resource
* @param {string} ref Domain\'s reference
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
deleteDomain: async (ref: string, options: AxiosRequestConfig = {}): Promise<RequestArgs> => {
// verify required parameter 'ref' is not null or undefined
assertParamExists('deleteDomain', 'ref', ref)
const localVarPath = `/v1beta1/domains/{ref}`
.replace(`{${"ref"}}`, encodeURIComponent(String(ref)));
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'DELETE', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
// authentication AccessKeyId required
await setApiKeyToObject(localVarHeaderParameter, "access_key_id", configuration)
// authentication AccessKeySecret required
await setApiKeyToObject(localVarHeaderParameter, "access_key_secret", configuration)
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
*
* @summary Gets a Domain by reference
* @param {string} ref Domain\'s reference
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
getDomain: async (ref: string, options: AxiosRequestConfig = {}): Promise<RequestArgs> => {
// verify required parameter 'ref' is not null or undefined
assertParamExists('getDomain', 'ref', ref)
const localVarPath = `/v1beta1/domains/{ref}`
.replace(`{${"ref"}}`, encodeURIComponent(String(ref)));
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'GET', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
// authentication AccessKeyId required
await setApiKeyToObject(localVarHeaderParameter, "access_key_id", configuration)
// authentication AccessKeySecret required
await setApiKeyToObject(localVarHeaderParameter, "access_key_secret", configuration)
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
*
* @summary Change or update fields in a resource
* @param {string} ref Domain\'s reference
* @param {InlineObject1} body
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
updateDomain: async (ref: string, body: InlineObject1, options: AxiosRequestConfig = {}): Promise<RequestArgs> => {
// verify required parameter 'ref' is not null or undefined
assertParamExists('updateDomain', 'ref', ref)
// verify required parameter 'body' is not null or undefined
assertParamExists('updateDomain', 'body', body)
const localVarPath = `/v1beta1/domains/{ref}`
.replace(`{${"ref"}}`, encodeURIComponent(String(ref)));
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'PUT', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
// authentication AccessKeyId required
await setApiKeyToObject(localVarHeaderParameter, "access_key_id", configuration)
// authentication AccessKeySecret required
await setApiKeyToObject(localVarHeaderParameter, "access_key_secret", configuration)
localVarHeaderParameter['Content-Type'] = 'application/json';
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
localVarRequestOptions.data = serializeDataIfNeeded(body, localVarRequestOptions, configuration)
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
}
};
/**
* DomainsApi - functional programming interface
* @export
*/
export const DomainsApiFp = function(configuration?: Configuration) {
const localVarAxiosParamCreator = DomainsApiAxiosParamCreator(configuration)
return {
/**
*
* @summary Creates a new Domain resource
* @param {CreateDomainRequest} body
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async createDomain(body: CreateDomainRequest, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<Domain>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.createDomain(body, options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
},
/**
*
* @summary Hard delete of a domain resource
* @param {string} ref Domain\'s reference
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async deleteDomain(ref: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<object>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.deleteDomain(ref, options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
},
/**
*
* @summary Gets a Domain by reference
* @param {string} ref Domain\'s reference
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async getDomain(ref: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<Domain>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.getDomain(ref, options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
},
/**
*
* @summary Change or update fields in a resource
* @param {string} ref Domain\'s reference
* @param {InlineObject1} body
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async updateDomain(ref: string, body: InlineObject1, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<Domain>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.updateDomain(ref, body, options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
},
}
};
/**
* DomainsApi - factory interface
* @export
*/
export const DomainsApiFactory = function (configuration?: Configuration, basePath?: string, axios?: AxiosInstance) {
const localVarFp = DomainsApiFp(configuration)
return {
/**
*
* @summary Creates a new Domain resource
* @param {CreateDomainRequest} body
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
createDomain(body: CreateDomainRequest, options?: any): AxiosPromise<Domain> {
return localVarFp.createDomain(body, options).then((request) => request(axios, basePath));
},
/**
*
* @summary Hard delete of a domain resource
* @param {string} ref Domain\'s reference
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
deleteDomain(ref: string, options?: any): AxiosPromise<object> {
return localVarFp.deleteDomain(ref, options).then((request) => request(axios, basePath));
},
/**
*
* @summary Gets a Domain by reference
* @param {string} ref Domain\'s reference
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
getDomain(ref: string, options?: any): AxiosPromise<Domain> {
return localVarFp.getDomain(ref, options).then((request) => request(axios, basePath));
},
/**
*
* @summary Change or update fields in a resource
* @param {string} ref Domain\'s reference
* @param {InlineObject1} body
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
updateDomain(ref: string, body: InlineObject1, options?: any): AxiosPromise<Domain> {
return localVarFp.updateDomain(ref, body, options).then((request) => request(axios, basePath));
},
};
};
/**
* DomainsApi - object-oriented interface
* @export
* @class DomainsApi
* @extends {BaseAPI}
*/
export class DomainsApi extends BaseAPI {
/**
*
* @summary Creates a new Domain resource
* @param {CreateDomainRequest} body
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof DomainsApi
*/
public createDomain(body: CreateDomainRequest, options?: AxiosRequestConfig) {
return DomainsApiFp(this.configuration).createDomain(body, options).then((request) => request(this.axios, this.basePath));
}
/**
*
* @summary Hard delete of a domain resource
* @param {string} ref Domain\'s reference
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof DomainsApi
*/
public deleteDomain(ref: string, options?: AxiosRequestConfig) {
return DomainsApiFp(this.configuration).deleteDomain(ref, options).then((request) => request(this.axios, this.basePath));
}
/**
*
* @summary Gets a Domain by reference
* @param {string} ref Domain\'s reference
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof DomainsApi
*/
public getDomain(ref: string, options?: AxiosRequestConfig) {
return DomainsApiFp(this.configuration).getDomain(ref, options).then((request) => request(this.axios, this.basePath));
}
/**
*
* @summary Change or update fields in a resource
* @param {string} ref Domain\'s reference
* @param {InlineObject1} body
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof DomainsApi
*/
public updateDomain(ref: string, body: InlineObject1, options?: AxiosRequestConfig) {
return DomainsApiFp(this.configuration).updateDomain(ref, body, options).then((request) => request(this.axios, this.basePath));
}
}
/**
* FuncsApi - axios parameter creator
* @export
*/
export const FuncsApiAxiosParamCreator = function (configuration?: Configuration) {
return {
/**
*
* @summary Peforms a hard delete of the function
* @param {string} name
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
deleteFunc: async (name: string, options: AxiosRequestConfig = {}): Promise<RequestArgs> => {
// verify required parameter 'name' is not null or undefined
assertParamExists('deleteFunc', 'name', name)
const localVarPath = `/v1beta1/funcs/{name}`
.replace(`{${"name"}}`, encodeURIComponent(String(name)));
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'DELETE', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
// authentication AccessKeyId required
await setApiKeyToObject(localVarHeaderParameter, "access_key_id", configuration)
// authentication AccessKeySecret required
await setApiKeyToObject(localVarHeaderParameter, "access_key_secret", configuration)
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
*
* @summary Gets a function by name
* @param {string} name
* @param {'BASIC' | 'STANDARD' | 'FULL'} [view] Requested level of detail.
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
getFunc: async (name: string, view?: 'BASIC' | 'STANDARD' | 'FULL', options: AxiosRequestConfig = {}): Promise<RequestArgs> => {
// verify required parameter 'name' is not null or undefined
assertParamExists('getFunc', 'name', name)
const localVarPath = `/v1beta1/funcs/{name}`
.replace(`{${"name"}}`, encodeURIComponent(String(name)));
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'GET', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
// authentication AccessKeyId required
await setApiKeyToObject(localVarHeaderParameter, "access_key_id", configuration)
// authentication AccessKeySecret required
await setApiKeyToObject(localVarHeaderParameter, "access_key_secret", configuration)
if (view !== undefined) {
localVarQueryParameter['view'] = view;
}
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
*
* @summary Gets a stream of logs
* @param {string} name
* @param {string} [since] Only return logs after a specific date (RFC3339).
* @param {number} [tail]
* @param {boolean} [follow]
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
getFuncLogs: async (name: string, since?: string, tail?: number, follow?: boolean, options: AxiosRequestConfig = {}): Promise<RequestArgs> => {
// verify required parameter 'name' is not null or undefined
assertParamExists('getFuncLogs', 'name', name)
const localVarPath = `/v1beta1/funcs/{name}/logs`
.replace(`{${"name"}}`, encodeURIComponent(String(name)));
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'GET', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
// authentication AccessKeyId required
await setApiKeyToObject(localVarHeaderParameter, "access_key_id", configuration)
// authentication AccessKeySecret required
await setApiKeyToObject(localVarHeaderParameter, "access_key_secret", configuration)
if (since !== undefined) {
localVarQueryParameter['since'] = since;
}
if (tail !== undefined) {
localVarQueryParameter['tail'] = tail;
}
if (follow !== undefined) {
localVarQueryParameter['follow'] = follow;
}
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
*
* @summary Shows a list of user functions
* @param {number} [pageSize] The maximum number of items in the list.
* @param {string} [pageToken] The next_page_token value returned from the previous request, if any.
* @param {'BASIC' | 'STANDARD' | 'FULL'} [view] Level of detail of the individual entities.
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
listFuncs: async (pageSize?: number, pageToken?: string, view?: 'BASIC' | 'STANDARD' | 'FULL', options: AxiosRequestConfig = {}): Promise<RequestArgs> => {
const localVarPath = `/v1beta1/funcs`;
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'GET', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
// authentication AccessKeyId required
await setApiKeyToObject(localVarHeaderParameter, "access_key_id", configuration)
// authentication AccessKeySecret required
await setApiKeyToObject(localVarHeaderParameter, "access_key_secret", configuration)
if (pageSize !== undefined) {
localVarQueryParameter['pageSize'] = pageSize;
}
if (pageToken !== undefined) {
localVarQueryParameter['pageToken'] = pageToken;
}
if (view !== undefined) {
localVarQueryParameter['view'] = view;
}
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
}
};
/**
* FuncsApi - functional programming interface
* @export
*/
export const FuncsApiFp = function(configuration?: Configuration) {
const localVarAxiosParamCreator = FuncsApiAxiosParamCreator(configuration)
return {
/**
*
* @summary Peforms a hard delete of the function
* @param {string} name
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async deleteFunc(name: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<object>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.deleteFunc(name, options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
},
/**
*
* @summary Gets a function by name
* @param {string} name
* @param {'BASIC' | 'STANDARD' | 'FULL'} [view] Requested level of detail.
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async getFunc(name: string, view?: 'BASIC' | 'STANDARD' | 'FULL', options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<Func>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.getFunc(name, view, options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
},
/**
*
* @summary Gets a stream of logs
* @param {string} name
* @param {string} [since] Only return logs after a specific date (RFC3339).
* @param {number} [tail]
* @param {boolean} [follow]
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async getFuncLogs(name: string, since?: string, tail?: number, follow?: boolean, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<FuncLog>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.getFuncLogs(name, since, tail, follow, options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
},
/**
*
* @summary Shows a list of user functions
* @param {number} [pageSize] The maximum number of items in the list.
* @param {string} [pageToken] The next_page_token value returned from the previous request, if any.
* @param {'BASIC' | 'STANDARD' | 'FULL'} [view] Level of detail of the individual entities.
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async listFuncs(pageSize?: number, pageToken?: string, view?: 'BASIC' | 'STANDARD' | 'FULL', options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<ListFuncsResponse>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.listFuncs(pageSize, pageToken, view, options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
},
}
};
/**
* FuncsApi - factory interface
* @export
*/
export const FuncsApiFactory = function (configuration?: Configuration, basePath?: string, axios?: AxiosInstance) {
const localVarFp = FuncsApiFp(configuration)
return {
/**
*
* @summary Peforms a hard delete of the function
* @param {string} name
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
deleteFunc(name: string, options?: any): AxiosPromise<object> {
return localVarFp.deleteFunc(name, options).then((request) => request(axios, basePath));
},
/**
*
* @summary Gets a function by name
* @param {string} name
* @param {'BASIC' | 'STANDARD' | 'FULL'} [view] Requested level of detail.
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
getFunc(name: string, view?: 'BASIC' | 'STANDARD' | 'FULL', options?: any): AxiosPromise<Func> {
return localVarFp.getFunc(name, view, options).then((request) => request(axios, basePath));
},
/**
*
* @summary Gets a stream of logs
* @param {string} name
* @param {string} [since] Only return logs after a specific date (RFC3339).
* @param {number} [tail]
* @param {boolean} [follow]
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
getFuncLogs(name: string, since?: string, tail?: number, follow?: boolean, options?: any): AxiosPromise<FuncLog> {
return localVarFp.getFuncLogs(name, since, tail, follow, options).then((request) => request(axios, basePath));
},
/**
*
* @summary Shows a list of user functions
* @param {number} [pageSize] The maximum number of items in the list.
* @param {string} [pageToken] The next_page_token value returned from the previous request, if any.
* @param {'BASIC' | 'STANDARD' | 'FULL'} [view] Level of detail of the individual entities.
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
listFuncs(pageSize?: number, pageToken?: string, view?: 'BASIC' | 'STANDARD' | 'FULL', options?: any): AxiosPromise<ListFuncsResponse> {
return localVarFp.listFuncs(pageSize, pageToken, view, options).then((request) => request(axios, basePath));
},
};
};
/**
* FuncsApi - object-oriented interface
* @export
* @class FuncsApi
* @extends {BaseAPI}
*/
export class FuncsApi extends BaseAPI {
/**
*
* @summary Peforms a hard delete of the function
* @param {string} name
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof FuncsApi
*/
public deleteFunc(name: string, options?: AxiosRequestConfig) {
return FuncsApiFp(this.configuration).deleteFunc(name, options).then((request) => request(this.axios, this.basePath));
}
/**
*
* @summary Gets a function by name
* @param {string} name
* @param {'BASIC' | 'STANDARD' | 'FULL'} [view] Requested level of detail.
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof FuncsApi
*/
public getFunc(name: string, view?: 'BASIC' | 'STANDARD' | 'FULL', options?: AxiosRequestConfig) {
return FuncsApiFp(this.configuration).getFunc(name, view, options).then((request) => request(this.axios, this.basePath));
}
/**
*
* @summary Gets a stream of logs
* @param {string} name
* @param {string} [since] Only return logs after a specific date (RFC3339).
* @param {number} [tail]
* @param {boolean} [follow]
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof FuncsApi
*/
public getFuncLogs(name: string, since?: string, tail?: number, follow?: boolean, options?: AxiosRequestConfig) {
return FuncsApiFp(this.configuration).getFuncLogs(name, since, tail, follow, options).then((request) => request(this.axios, this.basePath));
}
/**
*
* @summary Shows a list of user functions
* @param {number} [pageSize] The maximum number of items in the list.
* @param {string} [pageToken] The next_page_token value returned from the previous request, if any.
* @param {'BASIC' | 'STANDARD' | 'FULL'} [view] Level of detail of the individual entities.
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof FuncsApi
*/
public listFuncs(pageSize?: number, pageToken?: string, view?: 'BASIC' | 'STANDARD' | 'FULL', options?: AxiosRequestConfig) {
return FuncsApiFp(this.configuration).listFuncs(pageSize, pageToken, view, options).then((request) => request(this.axios, this.basePath));
}
}
/**
* NumbersApi - axios parameter creator
* @export
*/
export const NumbersApiAxiosParamCreator = function (configuration?: Configuration) {
return {
/**
*
* @summary Creates a new Number resource
* @param {CreateNumberRequest} body
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
createNumber: async (body: CreateNumberRequest, options: AxiosRequestConfig = {}): Promise<RequestArgs> => {
// verify required parameter 'body' is not null or undefined
assertParamExists('createNumber', 'body', body)
const localVarPath = `/v1beta1/numbers`;
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'POST', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
// authentication AccessKeyId required
await setApiKeyToObject(localVarHeaderParameter, "access_key_id", configuration)
// authentication AccessKeySecret required
await setApiKeyToObject(localVarHeaderParameter, "access_key_secret", configuration)
localVarHeaderParameter['Content-Type'] = 'application/json';
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
localVarRequestOptions.data = serializeDataIfNeeded(body, localVarRequestOptions, configuration)
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
*
* @summary Hard delete of a Number resource
* @param {string} ref Number\'s reference
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
deleteNumber: async (ref: string, options: AxiosRequestConfig = {}): Promise<RequestArgs> => {
// verify required parameter 'ref' is not null or undefined
assertParamExists('deleteNumber', 'ref', ref)
const localVarPath = `/v1beta1/numbers/{ref}`
.replace(`{${"ref"}}`, encodeURIComponent(String(ref)));
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'DELETE', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
// authentication AccessKeyId required
await setApiKeyToObject(localVarHeaderParameter, "access_key_id", configuration)
// authentication AccessKeySecret required
await setApiKeyToObject(localVarHeaderParameter, "access_key_secret", configuration)
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
*
* @summary Gets Number using its reference
* @param {string} ref Number\'s reference
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
getNumber: async (ref: string, options: AxiosRequestConfig = {}): Promise<RequestArgs> => {
// verify required parameter 'ref' is not null or undefined
assertParamExists('getNumber', 'ref', ref)
const localVarPath = `/v1beta1/numbers/{ref}`
.replace(`{${"ref"}}`, encodeURIComponent(String(ref)));
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'GET', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
// authentication AccessKeyId required
await setApiKeyToObject(localVarHeaderParameter, "access_key_id", configuration)
// authentication AccessKeySecret required
await setApiKeyToObject(localVarHeaderParameter, "access_key_secret", configuration)
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
*
* @summary Lists Numbers from the SIP Proxy subsystem
* @param {number} [pageSize] The maximum number of items in the list.
* @param {string} [pageToken] The next_page_token value returned from the previous request, if any.
* @param {'BASIC' | 'STANDARD' | 'FULL'} [view] Level of detail of the individual entities (reserved).
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
listNumbers: async (pageSize?: number, pageToken?: string, view?: 'BASIC' | 'STANDARD' | 'FULL', options: AxiosRequestConfig = {}): Promise<RequestArgs> => {
const localVarPath = `/v1beta1/numbers`;
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'GET', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
// authentication AccessKeyId required
await setApiKeyToObject(localVarHeaderParameter, "access_key_id", configuration)
// authentication AccessKeySecret required
await setApiKeyToObject(localVarHeaderParameter, "access_key_secret", configuration)
if (pageSize !== undefined) {
localVarQueryParameter['pageSize'] = pageSize;
}
if (pageToken !== undefined) {
localVarQueryParameter['pageToken'] = pageToken;
}
if (view !== undefined) {
localVarQueryParameter['view'] = view;
}
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
*
* @summary Change or update fields in a resource
* @param {string} ref Number\'s reference
* @param {InlineObject2} body
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
updateNumber: async (ref: string, body: InlineObject2, options: AxiosRequestConfig = {}): Promise<RequestArgs> => {
// verify required parameter 'ref' is not null or undefined
assertParamExists('updateNumber', 'ref', ref)
// verify required parameter 'body' is not null or undefined
assertParamExists('updateNumber', 'body', body)
const localVarPath = `/v1beta1/numbers/{ref}`
.replace(`{${"ref"}}`, encodeURIComponent(String(ref)));
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'PUT', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
// authentication AccessKeyId required
await setApiKeyToObject(localVarHeaderParameter, "access_key_id", configuration)
// authentication AccessKeySecret required
await setApiKeyToObject(localVarHeaderParameter, "access_key_secret", configuration)
localVarHeaderParameter['Content-Type'] = 'application/json';
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
localVarRequestOptions.data = serializeDataIfNeeded(body, localVarRequestOptions, configuration)
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
}
};
/**
* NumbersApi - functional programming interface
* @export
*/
export const NumbersApiFp = function(configuration?: Configuration) {
const localVarAxiosParamCreator = NumbersApiAxiosParamCreator(configuration)
return {
/**
*
* @summary Creates a new Number resource
* @param {CreateNumberRequest} body
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async createNumber(body: CreateNumberRequest, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<Number>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.createNumber(body, options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
},
/**
*
* @summary Hard delete of a Number resource
* @param {string} ref Number\'s reference
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async deleteNumber(ref: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<object>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.deleteNumber(ref, options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
},
/**
*
* @summary Gets Number using its reference
* @param {string} ref Number\'s reference
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async getNumber(ref: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<Number>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.getNumber(ref, options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
},
/**
*
* @summary Lists Numbers from the SIP Proxy subsystem
* @param {number} [pageSize] The maximum number of items in the list.
* @param {string} [pageToken] The next_page_token value returned from the previous request, if any.
* @param {'BASIC' | 'STANDARD' | 'FULL'} [view] Level of detail of the individual entities (reserved).
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async listNumbers(pageSize?: number, pageToken?: string, view?: 'BASIC' | 'STANDARD' | 'FULL', options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<ListNumbersResponse>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.listNumbers(pageSize, pageToken, view, options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
},
/**
*
* @summary Change or update fields in a resource
* @param {string} ref Number\'s reference
* @param {InlineObject2} body
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async updateNumber(ref: string, body: InlineObject2, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<Number>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.updateNumber(ref, body, options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
},
}
};
/**
* NumbersApi - factory interface
* @export
*/
export const NumbersApiFactory = function (configuration?: Configuration, basePath?: string, axios?: AxiosInstance) {
const localVarFp = NumbersApiFp(configuration)
return {
/**
*
* @summary Creates a new Number resource
* @param {CreateNumberRequest} body
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
createNumber(body: CreateNumberRequest, options?: any): AxiosPromise<Number> {
return localVarFp.createNumber(body, options).then((request) => request(axios, basePath));
},
/**
*
* @summary Hard delete of a Number resource
* @param {string} ref Number\'s reference
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
deleteNumber(ref: string, options?: any): AxiosPromise<object> {
return localVarFp.deleteNumber(ref, options).then((request) => request(axios, basePath));
},
/**
*
* @summary Gets Number using its reference
* @param {string} ref Number\'s reference
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
getNumber(ref: string, options?: any): AxiosPromise<Number> {
return localVarFp.getNumber(ref, options).then((request) => request(axios, basePath));
},
/**
*
* @summary Lists Numbers from the SIP Proxy subsystem
* @param {number} [pageSize] The maximum number of items in the list.
* @param {string} [pageToken] The next_page_token value returned from the previous request, if any.
* @param {'BASIC' | 'STANDARD' | 'FULL'} [view] Level of detail of the individual entities (reserved).
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
listNumbers(pageSize?: number, pageToken?: string, view?: 'BASIC' | 'STANDARD' | 'FULL', options?: any): AxiosPromise<ListNumbersResponse> {
return localVarFp.listNumbers(pageSize, pageToken, view, options).then((request) => request(axios, basePath));
},
/**
*
* @summary Change or update fields in a resource
* @param {string} ref Number\'s reference
* @param {InlineObject2} body
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
updateNumber(ref: string, body: InlineObject2, options?: any): AxiosPromise<Number> {
return localVarFp.updateNumber(ref, body, options).then((request) => request(axios, basePath));
},
};
};
/**
* NumbersApi - object-oriented interface
* @export
* @class NumbersApi
* @extends {BaseAPI}
*/
export class NumbersApi extends BaseAPI {
/**
*
* @summary Creates a new Number resource
* @param {CreateNumberRequest} body
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof NumbersApi
*/
public createNumber(body: CreateNumberRequest, options?: AxiosRequestConfig) {
return NumbersApiFp(this.configuration).createNumber(body, options).then((request) => request(this.axios, this.basePath));
}
/**
*
* @summary Hard delete of a Number resource
* @param {string} ref Number\'s reference
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof NumbersApi
*/
public deleteNumber(ref: string, options?: AxiosRequestConfig) {
return NumbersApiFp(this.configuration).deleteNumber(ref, options).then((request) => request(this.axios, this.basePath));
}
/**
*
* @summary Gets Number using its reference
* @param {string} ref Number\'s reference
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof NumbersApi
*/
public getNumber(ref: string, options?: AxiosRequestConfig) {
return NumbersApiFp(this.configuration).getNumber(ref, options).then((request) => request(this.axios, this.basePath));
}
/**
*
* @summary Lists Numbers from the SIP Proxy subsystem
* @param {number} [pageSize] The maximum number of items in the list.
* @param {string} [pageToken] The next_page_token value returned from the previous request, if any.
* @param {'BASIC' | 'STANDARD' | 'FULL'} [view] Level of detail of the individual entities (reserved).
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof NumbersApi
*/
public listNumbers(pageSize?: number, pageToken?: string, view?: 'BASIC' | 'STANDARD' | 'FULL', options?: AxiosRequestConfig) {
return NumbersApiFp(this.configuration).listNumbers(pageSize, pageToken, view, options).then((request) => request(this.axios, this.basePath));
}
/**
*
* @summary Change or update fields in a resource
* @param {string} ref Number\'s reference
* @param {InlineObject2} body
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof NumbersApi
*/
public updateNumber(ref: string, body: InlineObject2, options?: AxiosRequestConfig) {
return NumbersApiFp(this.configuration).updateNumber(ref, body, options).then((request) => request(this.axios, this.basePath));
}
}
/**
* ProjectsApi - axios parameter creator
* @export
*/
export const ProjectsApiAxiosParamCreator = function (configuration?: Configuration) {
return {
/**
*
* @summary Creates a new Project resource
* @param {CreateProjectRequest} body
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
createProject: async (body: CreateProjectRequest, options: AxiosRequestConfig = {}): Promise<RequestArgs> => {
// verify required parameter 'body' is not null or undefined
assertParamExists('createProject', 'body', body)
const localVarPath = `/v1beta1/projects`;
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'POST', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
// authentication AccessKeyId required
await setApiKeyToObject(localVarHeaderParameter, "access_key_id", configuration)
// authentication AccessKeySecret required
await setApiKeyToObject(localVarHeaderParameter, "access_key_secret", configuration)
localVarHeaderParameter['Content-Type'] = 'application/json';
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
localVarRequestOptions.data = serializeDataIfNeeded(body, localVarRequestOptions, configuration)
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
*
* @summary WARNING: Hard delete of a Project will remove all related resources
* @param {string} ref Project\'s reference
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
deleteProject: async (ref: string, options: AxiosRequestConfig = {}): Promise<RequestArgs> => {
// verify required parameter 'ref' is not null or undefined
assertParamExists('deleteProject', 'ref', ref)
const localVarPath = `/v1beta1/projects/{ref}`
.replace(`{${"ref"}}`, encodeURIComponent(String(ref)));
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'DELETE', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
// authentication AccessKeyId required
await setApiKeyToObject(localVarHeaderParameter, "access_key_id", configuration)
// authentication AccessKeySecret required
await setApiKeyToObject(localVarHeaderParameter, "access_key_secret", configuration)
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
*
* @summary Gets a Project by AccessKeyId
* @param {string} ref Project\'s reference
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
getProject: async (ref: string, options: AxiosRequestConfig = {}): Promise<RequestArgs> => {
// verify required parameter 'ref' is not null or undefined
assertParamExists('getProject', 'ref', ref)
const localVarPath = `/v1beta1/projects/{ref}`
.replace(`{${"ref"}}`, encodeURIComponent(String(ref)));
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'GET', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
// authentication AccessKeyId required
await setApiKeyToObject(localVarHeaderParameter, "access_key_id", configuration)
// authentication AccessKeySecret required
await setApiKeyToObject(localVarHeaderParameter, "access_key_secret", configuration)
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
*
* @summary Lists all the Projects for a given User
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
listProjects: async (options: AxiosRequestConfig = {}): Promise<RequestArgs> => {
const localVarPath = `/v1beta1/projects`;
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'GET', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
// authentication AccessKeyId required
await setApiKeyToObject(localVarHeaderParameter, "access_key_id", configuration)
// authentication AccessKeySecret required
await setApiKeyToObject(localVarHeaderParameter, "access_key_secret", configuration)
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
*
* @summary Regenerates the accessKeySecret
* @param {string} ref Project\'s reference
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
renewAccessKeySecret: async (ref: string, options: AxiosRequestConfig = {}): Promise<RequestArgs> => {
// verify required parameter 'ref' is not null or undefined
assertParamExists('renewAccessKeySecret', 'ref', ref)
const localVarPath = `/v1beta1/projects/{ref}/credentials`
.replace(`{${"ref"}}`, encodeURIComponent(String(ref)));
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'GET', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
// authentication AccessKeyId required
await setApiKeyToObject(localVarHeaderParameter, "access_key_id", configuration)
// authentication AccessKeySecret required
await setApiKeyToObject(localVarHeaderParameter, "access_key_secret", configuration)
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
*
* @summary Updates a given Project
* @param {string} ref Project\'s reference
* @param {InlineObject3} body
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
updateProject: async (ref: string, body: InlineObject3, options: AxiosRequestConfig = {}): Promise<RequestArgs> => {
// verify required parameter 'ref' is not null or undefined
assertParamExists('updateProject', 'ref', ref)
// verify required parameter 'body' is not null or undefined
assertParamExists('updateProject', 'body', body)
const localVarPath = `/v1beta1/projects/{ref}`
.replace(`{${"ref"}}`, encodeURIComponent(String(ref)));
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'PUT', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
// authentication AccessKeyId required
await setApiKeyToObject(localVarHeaderParameter, "access_key_id", configuration)
// authentication AccessKeySecret required
await setApiKeyToObject(localVarHeaderParameter, "access_key_secret", configuration)
localVarHeaderParameter['Content-Type'] = 'application/json';
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
localVarRequestOptions.data = serializeDataIfNeeded(body, localVarRequestOptions, configuration)
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
}
};
/**
* ProjectsApi - functional programming interface
* @export
*/
export const ProjectsApiFp = function(configuration?: Configuration) {
const localVarAxiosParamCreator = ProjectsApiAxiosParamCreator(configuration)
return {
/**
*
* @summary Creates a new Project resource
* @param {CreateProjectRequest} body
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async createProject(body: CreateProjectRequest, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<Project>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.createProject(body, options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
},
/**
*
* @summary WARNING: Hard delete of a Project will remove all related resources
* @param {string} ref Project\'s reference
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async deleteProject(ref: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<object>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.deleteProject(ref, options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
},
/**
*
* @summary Gets a Project by AccessKeyId
* @param {string} ref Project\'s reference
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async getProject(ref: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<Project>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.getProject(ref, options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
},
/**
*
* @summary Lists all the Projects for a given User
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async listProjects(options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<ListProjectsResponse>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.listProjects(options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
},
/**
*
* @summary Regenerates the accessKeySecret
* @param {string} ref Project\'s reference
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async renewAccessKeySecret(ref: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<RenewAccessKeySecretResponse>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.renewAccessKeySecret(ref, options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
},
/**
*
* @summary Updates a given Project
* @param {string} ref Project\'s reference
* @param {InlineObject3} body
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async updateProject(ref: string, body: InlineObject3, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<Project>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.updateProject(ref, body, options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
},
}
};
/**
* ProjectsApi - factory interface
* @export
*/
export const ProjectsApiFactory = function (configuration?: Configuration, basePath?: string, axios?: AxiosInstance) {
const localVarFp = ProjectsApiFp(configuration)
return {
/**
*
* @summary Creates a new Project resource
* @param {CreateProjectRequest} body
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
createProject(body: CreateProjectRequest, options?: any): AxiosPromise<Project> {
return localVarFp.createProject(body, options).then((request) => request(axios, basePath));
},
/**
*
* @summary WARNING: Hard delete of a Project will remove all related resources
* @param {string} ref Project\'s reference
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
deleteProject(ref: string, options?: any): AxiosPromise<object> {
return localVarFp.deleteProject(ref, options).then((request) => request(axios, basePath));
},
/**
*
* @summary Gets a Project by AccessKeyId
* @param {string} ref Project\'s reference
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
getProject(ref: string, options?: any): AxiosPromise<Project> {
return localVarFp.getProject(ref, options).then((request) => request(axios, basePath));
},
/**
*
* @summary Lists all the Projects for a given User
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
listProjects(options?: any): AxiosPromise<ListProjectsResponse> {
return localVarFp.listProjects(options).then((request) => request(axios, basePath));
},
/**
*
* @summary Regenerates the accessKeySecret
* @param {string} ref Project\'s reference
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
renewAccessKeySecret(ref: string, options?: any): AxiosPromise<RenewAccessKeySecretResponse> {
return localVarFp.renewAccessKeySecret(ref, options).then((request) => request(axios, basePath));
},
/**
*
* @summary Updates a given Project
* @param {string} ref Project\'s reference
* @param {InlineObject3} body
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
updateProject(ref: string, body: InlineObject3, options?: any): AxiosPromise<Project> {
return localVarFp.updateProject(ref, body, options).then((request) => request(axios, basePath));
},
};
};
/**
* ProjectsApi - object-oriented interface
* @export
* @class ProjectsApi
* @extends {BaseAPI}
*/
export class ProjectsApi extends BaseAPI {
/**
*
* @summary Creates a new Project resource
* @param {CreateProjectRequest} body
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof ProjectsApi
*/
public createProject(body: CreateProjectRequest, options?: AxiosRequestConfig) {
return ProjectsApiFp(this.configuration).createProject(body, options).then((request) => request(this.axios, this.basePath));
}
/**
*
* @summary WARNING: Hard delete of a Project will remove all related resources
* @param {string} ref Project\'s reference
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof ProjectsApi
*/
public deleteProject(ref: string, options?: AxiosRequestConfig) {
return ProjectsApiFp(this.configuration).deleteProject(ref, options).then((request) => request(this.axios, this.basePath));
}
/**
*
* @summary Gets a Project by AccessKeyId
* @param {string} ref Project\'s reference
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof ProjectsApi
*/
public getProject(ref: string, options?: AxiosRequestConfig) {
return ProjectsApiFp(this.configuration).getProject(ref, options).then((request) => request(this.axios, this.basePath));
}
/**
*
* @summary Lists all the Projects for a given User
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof ProjectsApi
*/
public listProjects(options?: AxiosRequestConfig) {
return ProjectsApiFp(this.configuration).listProjects(options).then((request) => request(this.axios, this.basePath));
}
/**
*
* @summary Regenerates the accessKeySecret
* @param {string} ref Project\'s reference
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof ProjectsApi
*/
public renewAccessKeySecret(ref: string, options?: AxiosRequestConfig) {
return ProjectsApiFp(this.configuration).renewAccessKeySecret(ref, options).then((request) => request(this.axios, this.basePath));
}
/**
*
* @summary Updates a given Project
* @param {string} ref Project\'s reference
* @param {InlineObject3} body
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof ProjectsApi
*/
public updateProject(ref: string, body: InlineObject3, options?: AxiosRequestConfig) {
return ProjectsApiFp(this.configuration).updateProject(ref, body, options).then((request) => request(this.axios, this.basePath));
}
}
/**
* ProvidersApi - axios parameter creator
* @export
*/
export const ProvidersApiAxiosParamCreator = function (configuration?: Configuration) {
return {
/**
*
* @summary Creates a new Provider resource.
* @param {CreateProviderRequest} body
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
createProvider: async (body: CreateProviderRequest, options: AxiosRequestConfig = {}): Promise<RequestArgs> => {
// verify required parameter 'body' is not null or undefined
assertParamExists('createProvider', 'body', body)
const localVarPath = `/v1beta1/providers`;
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'POST', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
// authentication AccessKeyId required
await setApiKeyToObject(localVarHeaderParameter, "access_key_id", configuration)
// authentication AccessKeySecret required
await setApiKeyToObject(localVarHeaderParameter, "access_key_secret", configuration)
localVarHeaderParameter['Content-Type'] = 'application/json';
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
localVarRequestOptions.data = serializeDataIfNeeded(body, localVarRequestOptions, configuration)
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
*
* @summary Hard delete of a Provider resource
* @param {string} ref Provider\'s reference
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
deleteProvider: async (ref: string, options: AxiosRequestConfig = {}): Promise<RequestArgs> => {
// verify required parameter 'ref' is not null or undefined
assertParamExists('deleteProvider', 'ref', ref)
const localVarPath = `/v1beta1/providers/{ref}`
.replace(`{${"ref"}}`, encodeURIComponent(String(ref)));
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'DELETE', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
// authentication AccessKeyId required
await setApiKeyToObject(localVarHeaderParameter, "access_key_id", configuration)
// authentication AccessKeySecret required
await setApiKeyToObject(localVarHeaderParameter, "access_key_secret", configuration)
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
*
* @summary Gets Provider using its reference
* @param {string} ref Provider\'s reference
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
getProvider: async (ref: string, options: AxiosRequestConfig = {}): Promise<RequestArgs> => {
// verify required parameter 'ref' is not null or undefined
assertParamExists('getProvider', 'ref', ref)
const localVarPath = `/v1beta1/providers/{ref}`
.replace(`{${"ref"}}`, encodeURIComponent(String(ref)));
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'GET', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
// authentication AccessKeyId required
await setApiKeyToObject(localVarHeaderParameter, "access_key_id", configuration)
// authentication AccessKeySecret required
await setApiKeyToObject(localVarHeaderParameter, "access_key_secret", configuration)
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
*
* @summary Lists Providers from the SIP Proxy subsystem
* @param {number} [pageSize] The maximum number of items in the list.
* @param {string} [pageToken] The next_page_token value returned from the previous request, if any.
* @param {'BASIC' | 'STANDARD' | 'FULL'} [view] Level of detail of the individual entities (reserved).
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
listProviders: async (pageSize?: number, pageToken?: string, view?: 'BASIC' | 'STANDARD' | 'FULL', options: AxiosRequestConfig = {}): Promise<RequestArgs> => {
const localVarPath = `/v1beta1/providers`;
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'GET', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
// authentication AccessKeyId required
await setApiKeyToObject(localVarHeaderParameter, "access_key_id", configuration)
// authentication AccessKeySecret required
await setApiKeyToObject(localVarHeaderParameter, "access_key_secret", configuration)
if (pageSize !== undefined) {
localVarQueryParameter['pageSize'] = pageSize;
}
if (pageToken !== undefined) {
localVarQueryParameter['pageToken'] = pageToken;
}
if (view !== undefined) {
localVarQueryParameter['view'] = view;
}
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
*
* @summary Change or update fields in a resource
* @param {string} ref Provider\'s reference
* @param {InlineObject4} body
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
updateProvider: async (ref: string, body: InlineObject4, options: AxiosRequestConfig = {}): Promise<RequestArgs> => {
// verify required parameter 'ref' is not null or undefined
assertParamExists('updateProvider', 'ref', ref)
// verify required parameter 'body' is not null or undefined
assertParamExists('updateProvider', 'body', body)
const localVarPath = `/v1beta1/providers/{ref}`
.replace(`{${"ref"}}`, encodeURIComponent(String(ref)));
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'PUT', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
// authentication AccessKeyId required
await setApiKeyToObject(localVarHeaderParameter, "access_key_id", configuration)
// authentication AccessKeySecret required
await setApiKeyToObject(localVarHeaderParameter, "access_key_secret", configuration)
localVarHeaderParameter['Content-Type'] = 'application/json';
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
localVarRequestOptions.data = serializeDataIfNeeded(body, localVarRequestOptions, configuration)
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
}
};
/**
* ProvidersApi - functional programming interface
* @export
*/
export const ProvidersApiFp = function(configuration?: Configuration) {
const localVarAxiosParamCreator = ProvidersApiAxiosParamCreator(configuration)
return {
/**
*
* @summary Creates a new Provider resource.
* @param {CreateProviderRequest} body
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async createProvider(body: CreateProviderRequest, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<Provider>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.createProvider(body, options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
},
/**
*
* @summary Hard delete of a Provider resource
* @param {string} ref Provider\'s reference
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async deleteProvider(ref: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<object>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.deleteProvider(ref, options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
},
/**
*
* @summary Gets Provider using its reference
* @param {string} ref Provider\'s reference
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async getProvider(ref: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<Provider>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.getProvider(ref, options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
},
/**
*
* @summary Lists Providers from the SIP Proxy subsystem
* @param {number} [pageSize] The maximum number of items in the list.
* @param {string} [pageToken] The next_page_token value returned from the previous request, if any.
* @param {'BASIC' | 'STANDARD' | 'FULL'} [view] Level of detail of the individual entities (reserved).
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async listProviders(pageSize?: number, pageToken?: string, view?: 'BASIC' | 'STANDARD' | 'FULL', options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<ListProvidersResponse>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.listProviders(pageSize, pageToken, view, options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
},
/**
*
* @summary Change or update fields in a resource
* @param {string} ref Provider\'s reference
* @param {InlineObject4} body
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async updateProvider(ref: string, body: InlineObject4, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<Provider>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.updateProvider(ref, body, options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
},
}
};
/**
* ProvidersApi - factory interface
* @export
*/
export const ProvidersApiFactory = function (configuration?: Configuration, basePath?: string, axios?: AxiosInstance) {
const localVarFp = ProvidersApiFp(configuration)
return {
/**
*
* @summary Creates a new Provider resource.
* @param {CreateProviderRequest} body
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
createProvider(body: CreateProviderRequest, options?: any): AxiosPromise<Provider> {
return localVarFp.createProvider(body, options).then((request) => request(axios, basePath));
},
/**
*
* @summary Hard delete of a Provider resource
* @param {string} ref Provider\'s reference
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
deleteProvider(ref: string, options?: any): AxiosPromise<object> {
return localVarFp.deleteProvider(ref, options).then((request) => request(axios, basePath));
},
/**
*
* @summary Gets Provider using its reference
* @param {string} ref Provider\'s reference
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
getProvider(ref: string, options?: any): AxiosPromise<Provider> {
return localVarFp.getProvider(ref, options).then((request) => request(axios, basePath));
},
/**
*
* @summary Lists Providers from the SIP Proxy subsystem
* @param {number} [pageSize] The maximum number of items in the list.
* @param {string} [pageToken] The next_page_token value returned from the previous request, if any.
* @param {'BASIC' | 'STANDARD' | 'FULL'} [view] Level of detail of the individual entities (reserved).
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
listProviders(pageSize?: number, pageToken?: string, view?: 'BASIC' | 'STANDARD' | 'FULL', options?: any): AxiosPromise<ListProvidersResponse> {
return localVarFp.listProviders(pageSize, pageToken, view, options).then((request) => request(axios, basePath));
},
/**
*
* @summary Change or update fields in a resource
* @param {string} ref Provider\'s reference
* @param {InlineObject4} body
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
updateProvider(ref: string, body: InlineObject4, options?: any): AxiosPromise<Provider> {
return localVarFp.updateProvider(ref, body, options).then((request) => request(axios, basePath));
},
};
};
/**
* ProvidersApi - object-oriented interface
* @export
* @class ProvidersApi
* @extends {BaseAPI}
*/
export class ProvidersApi extends BaseAPI {
/**
*
* @summary Creates a new Provider resource.
* @param {CreateProviderRequest} body
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof ProvidersApi
*/
public createProvider(body: CreateProviderRequest, options?: AxiosRequestConfig) {
return ProvidersApiFp(this.configuration).createProvider(body, options).then((request) => request(this.axios, this.basePath));
}
/**
*
* @summary Hard delete of a Provider resource
* @param {string} ref Provider\'s reference
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof ProvidersApi
*/
public deleteProvider(ref: string, options?: AxiosRequestConfig) {
return ProvidersApiFp(this.configuration).deleteProvider(ref, options).then((request) => request(this.axios, this.basePath));
}
/**
*
* @summary Gets Provider using its reference
* @param {string} ref Provider\'s reference
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof ProvidersApi
*/
public getProvider(ref: string, options?: AxiosRequestConfig) {
return ProvidersApiFp(this.configuration).getProvider(ref, options).then((request) => request(this.axios, this.basePath));
}
/**
*
* @summary Lists Providers from the SIP Proxy subsystem
* @param {number} [pageSize] The maximum number of items in the list.
* @param {string} [pageToken] The next_page_token value returned from the previous request, if any.
* @param {'BASIC' | 'STANDARD' | 'FULL'} [view] Level of detail of the individual entities (reserved).
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof ProvidersApi
*/
public listProviders(pageSize?: number, pageToken?: string, view?: 'BASIC' | 'STANDARD' | 'FULL', options?: AxiosRequestConfig) {
return ProvidersApiFp(this.configuration).listProviders(pageSize, pageToken, view, options).then((request) => request(this.axios, this.basePath));
}
/**
*
* @summary Change or update fields in a resource
* @param {string} ref Provider\'s reference
* @param {InlineObject4} body
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof ProvidersApi
*/
public updateProvider(ref: string, body: InlineObject4, options?: AxiosRequestConfig) {
return ProvidersApiFp(this.configuration).updateProvider(ref, body, options).then((request) => request(this.axios, this.basePath));
}
}
/**
* SecretsApi - axios parameter creator
* @export
*/
export const SecretsApiAxiosParamCreator = function (configuration?: Configuration) {
return {
/**
*
* @param {CreateSecretRequest} body
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
createSecret: async (body: CreateSecretRequest, options: AxiosRequestConfig = {}): Promise<RequestArgs> => {
// verify required parameter 'body' is not null or undefined
assertParamExists('createSecret', 'body', body)
const localVarPath = `/v1beta1/secrets`;
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'POST', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
// authentication AccessKeyId required
await setApiKeyToObject(localVarHeaderParameter, "access_key_id", configuration)
// authentication AccessKeySecret required
await setApiKeyToObject(localVarHeaderParameter, "access_key_secret", configuration)
localVarHeaderParameter['Content-Type'] = 'application/json';
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
localVarRequestOptions.data = serializeDataIfNeeded(body, localVarRequestOptions, configuration)
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
*
* @summary Peforms a hard delete of the Secret resource
* @param {string} name
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
deleteSecret: async (name: string, options: AxiosRequestConfig = {}): Promise<RequestArgs> => {
// verify required parameter 'name' is not null or undefined
assertParamExists('deleteSecret', 'name', name)
const localVarPath = `/v1beta1/secrets/{name}`
.replace(`{${"name"}}`, encodeURIComponent(String(name)));
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'DELETE', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
// authentication AccessKeyId required
await setApiKeyToObject(localVarHeaderParameter, "access_key_id", configuration)
// authentication AccessKeySecret required
await setApiKeyToObject(localVarHeaderParameter, "access_key_secret", configuration)
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
*
* @summary Gets Secret with the Secret-name
* @param {string} name
* @param {'BASIC' | 'STANDARD' | 'FULL'} [view]
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
getSecret: async (name: string, view?: 'BASIC' | 'STANDARD' | 'FULL', options: AxiosRequestConfig = {}): Promise<RequestArgs> => {
// verify required parameter 'name' is not null or undefined
assertParamExists('getSecret', 'name', name)
const localVarPath = `/v1beta1/secrets/{name}`
.replace(`{${"name"}}`, encodeURIComponent(String(name)));
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'GET', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
// authentication AccessKeyId required
await setApiKeyToObject(localVarHeaderParameter, "access_key_id", configuration)
// authentication AccessKeySecret required
await setApiKeyToObject(localVarHeaderParameter, "access_key_secret", configuration)
if (view !== undefined) {
localVarQueryParameter['view'] = view;
}
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
*
* @summary Lists Secret
* @param {number} [pageSize] The maximum number of items in the list.
* @param {string} [pageToken] The next_page_token value returned from the previous request, if any.
* @param {'BASIC' | 'STANDARD' | 'FULL'} [view] Level of detail of the individual entities (reserved).
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
listSecretsId: async (pageSize?: number, pageToken?: string, view?: 'BASIC' | 'STANDARD' | 'FULL', options: AxiosRequestConfig = {}): Promise<RequestArgs> => {
const localVarPath = `/v1beta1/secrets`;
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'GET', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
// authentication AccessKeyId required
await setApiKeyToObject(localVarHeaderParameter, "access_key_id", configuration)
// authentication AccessKeySecret required
await setApiKeyToObject(localVarHeaderParameter, "access_key_secret", configuration)
if (pageSize !== undefined) {
localVarQueryParameter['pageSize'] = pageSize;
}
if (pageToken !== undefined) {
localVarQueryParameter['pageToken'] = pageToken;
}
if (view !== undefined) {
localVarQueryParameter['view'] = view;
}
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
}
};
/**
* SecretsApi - functional programming interface
* @export
*/
export const SecretsApiFp = function(configuration?: Configuration) {
const localVarAxiosParamCreator = SecretsApiAxiosParamCreator(configuration)
return {
/**
*
* @param {CreateSecretRequest} body
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async createSecret(body: CreateSecretRequest, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<CreateSecretResponse>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.createSecret(body, options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
},
/**
*
* @summary Peforms a hard delete of the Secret resource
* @param {string} name
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async deleteSecret(name: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<object>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.deleteSecret(name, options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
},
/**
*
* @summary Gets Secret with the Secret-name
* @param {string} name
* @param {'BASIC' | 'STANDARD' | 'FULL'} [view]
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async getSecret(name: string, view?: 'BASIC' | 'STANDARD' | 'FULL', options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<GetSecretResponse>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.getSecret(name, view, options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
},
/**
*
* @summary Lists Secret
* @param {number} [pageSize] The maximum number of items in the list.
* @param {string} [pageToken] The next_page_token value returned from the previous request, if any.
* @param {'BASIC' | 'STANDARD' | 'FULL'} [view] Level of detail of the individual entities (reserved).
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async listSecretsId(pageSize?: number, pageToken?: string, view?: 'BASIC' | 'STANDARD' | 'FULL', options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<ListSecretIdResponse>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.listSecretsId(pageSize, pageToken, view, options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
},
}
};
/**
* SecretsApi - factory interface
* @export
*/
export const SecretsApiFactory = function (configuration?: Configuration, basePath?: string, axios?: AxiosInstance) {
const localVarFp = SecretsApiFp(configuration)
return {
/**
*
* @param {CreateSecretRequest} body
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
createSecret(body: CreateSecretRequest, options?: any): AxiosPromise<CreateSecretResponse> {
return localVarFp.createSecret(body, options).then((request) => request(axios, basePath));
},
/**
*
* @summary Peforms a hard delete of the Secret resource
* @param {string} name
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
deleteSecret(name: string, options?: any): AxiosPromise<object> {
return localVarFp.deleteSecret(name, options).then((request) => request(axios, basePath));
},
/**
*
* @summary Gets Secret with the Secret-name
* @param {string} name
* @param {'BASIC' | 'STANDARD' | 'FULL'} [view]
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
getSecret(name: string, view?: 'BASIC' | 'STANDARD' | 'FULL', options?: any): AxiosPromise<GetSecretResponse> {
return localVarFp.getSecret(name, view, options).then((request) => request(axios, basePath));
},
/**
*
* @summary Lists Secret
* @param {number} [pageSize] The maximum number of items in the list.
* @param {string} [pageToken] The next_page_token value returned from the previous request, if any.
* @param {'BASIC' | 'STANDARD' | 'FULL'} [view] Level of detail of the individual entities (reserved).
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
listSecretsId(pageSize?: number, pageToken?: string, view?: 'BASIC' | 'STANDARD' | 'FULL', options?: any): AxiosPromise<ListSecretIdResponse> {
return localVarFp.listSecretsId(pageSize, pageToken, view, options).then((request) => request(axios, basePath));
},
};
};
/**
* SecretsApi - object-oriented interface
* @export
* @class SecretsApi
* @extends {BaseAPI}
*/
export class SecretsApi extends BaseAPI {
/**
*
* @param {CreateSecretRequest} body
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof SecretsApi
*/
public createSecret(body: CreateSecretRequest, options?: AxiosRequestConfig) {
return SecretsApiFp(this.configuration).createSecret(body, options).then((request) => request(this.axios, this.basePath));
}
/**
*
* @summary Peforms a hard delete of the Secret resource
* @param {string} name
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof SecretsApi
*/
public deleteSecret(name: string, options?: AxiosRequestConfig) {
return SecretsApiFp(this.configuration).deleteSecret(name, options).then((request) => request(this.axios, this.basePath));
}
/**
*
* @summary Gets Secret with the Secret-name
* @param {string} name
* @param {'BASIC' | 'STANDARD' | 'FULL'} [view]
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof SecretsApi
*/
public getSecret(name: string, view?: 'BASIC' | 'STANDARD' | 'FULL', options?: AxiosRequestConfig) {
return SecretsApiFp(this.configuration).getSecret(name, view, options).then((request) => request(this.axios, this.basePath));
}
/**
*
* @summary Lists Secret
* @param {number} [pageSize] The maximum number of items in the list.
* @param {string} [pageToken] The next_page_token value returned from the previous request, if any.
* @param {'BASIC' | 'STANDARD' | 'FULL'} [view] Level of detail of the individual entities (reserved).
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof SecretsApi
*/
public listSecretsId(pageSize?: number, pageToken?: string, view?: 'BASIC' | 'STANDARD' | 'FULL', options?: AxiosRequestConfig) {
return SecretsApiFp(this.configuration).listSecretsId(pageSize, pageToken, view, options).then((request) => request(this.axios, this.basePath));
}
}
/**
* StorageApi - axios parameter creator
* @export
*/
export const StorageApiAxiosParamCreator = function (configuration?: Configuration) {
return {
/**
*
* @param {'APPS' | 'RECORDINGS' | 'PUBLIC' | 'FUNCS'} bucket
* @param {string} filename
* @param {string} [accessKeyId]
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
getObjectURL: async (bucket: 'APPS' | 'RECORDINGS' | 'PUBLIC' | 'FUNCS', filename: string, accessKeyId?: string, options: AxiosRequestConfig = {}): Promise<RequestArgs> => {
// verify required parameter 'bucket' is not null or undefined
assertParamExists('getObjectURL', 'bucket', bucket)
// verify required parameter 'filename' is not null or undefined
assertParamExists('getObjectURL', 'filename', filename)
const localVarPath = `/v1beta1/storage/{bucket}/{filename}`
.replace(`{${"bucket"}}`, encodeURIComponent(String(bucket)))
.replace(`{${"filename"}}`, encodeURIComponent(String(filename)));
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'GET', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
// authentication AccessKeyId required
await setApiKeyToObject(localVarHeaderParameter, "access_key_id", configuration)
// authentication AccessKeySecret required
await setApiKeyToObject(localVarHeaderParameter, "access_key_secret", configuration)
if (accessKeyId !== undefined) {
localVarQueryParameter['accessKeyId'] = accessKeyId;
}
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
}
};
/**
* StorageApi - functional programming interface
* @export
*/
export const StorageApiFp = function(configuration?: Configuration) {
const localVarAxiosParamCreator = StorageApiAxiosParamCreator(configuration)
return {
/**
*
* @param {'APPS' | 'RECORDINGS' | 'PUBLIC' | 'FUNCS'} bucket
* @param {string} filename
* @param {string} [accessKeyId]
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async getObjectURL(bucket: 'APPS' | 'RECORDINGS' | 'PUBLIC' | 'FUNCS', filename: string, accessKeyId?: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<GetObjectURLResponse>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.getObjectURL(bucket, filename, accessKeyId, options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
},
}
};
/**
* StorageApi - factory interface
* @export
*/
export const StorageApiFactory = function (configuration?: Configuration, basePath?: string, axios?: AxiosInstance) {
const localVarFp = StorageApiFp(configuration)
return {
/**
*
* @param {'APPS' | 'RECORDINGS' | 'PUBLIC' | 'FUNCS'} bucket
* @param {string} filename
* @param {string} [accessKeyId]
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
getObjectURL(bucket: 'APPS' | 'RECORDINGS' | 'PUBLIC' | 'FUNCS', filename: string, accessKeyId?: string, options?: any): AxiosPromise<GetObjectURLResponse> {
return localVarFp.getObjectURL(bucket, filename, accessKeyId, options).then((request) => request(axios, basePath));
},
};
};
/**
* StorageApi - object-oriented interface
* @export
* @class StorageApi
* @extends {BaseAPI}
*/
export class StorageApi extends BaseAPI {
/**
*
* @param {'APPS' | 'RECORDINGS' | 'PUBLIC' | 'FUNCS'} bucket
* @param {string} filename
* @param {string} [accessKeyId]
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof StorageApi
*/
public getObjectURL(bucket: 'APPS' | 'RECORDINGS' | 'PUBLIC' | 'FUNCS', filename: string, accessKeyId?: string, options?: AxiosRequestConfig) {
return StorageApiFp(this.configuration).getObjectURL(bucket, filename, accessKeyId, options).then((request) => request(this.axios, this.basePath));
}
}
/**
* UsersApi - axios parameter creator
* @export
*/
export const UsersApiAxiosParamCreator = function (configuration?: Configuration) {
return {
/**
*
* @summary Creates a new User resource
* @param {CreateUserRequest} body
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
createUser: async (body: CreateUserRequest, options: AxiosRequestConfig = {}): Promise<RequestArgs> => {
// verify required parameter 'body' is not null or undefined
assertParamExists('createUser', 'body', body)
const localVarPath = `/v1beta1/users`;
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'POST', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
// authentication AccessKeyId required
await setApiKeyToObject(localVarHeaderParameter, "access_key_id", configuration)
// authentication AccessKeySecret required
await setApiKeyToObject(localVarHeaderParameter, "access_key_secret", configuration)
localVarHeaderParameter['Content-Type'] = 'application/json';
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
localVarRequestOptions.data = serializeDataIfNeeded(body, localVarRequestOptions, configuration)
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
*
* @summary Creates a set of credentials
* @param {CreateUserCredentialsRequest} body
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
createUserCredentials: async (body: CreateUserCredentialsRequest, options: AxiosRequestConfig = {}): Promise<RequestArgs> => {
// verify required parameter 'body' is not null or undefined
assertParamExists('createUserCredentials', 'body', body)
const localVarPath = `/v1beta1/users/credentials`;
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'POST', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
// authentication AccessKeyId required
await setApiKeyToObject(localVarHeaderParameter, "access_key_id", configuration)
// authentication AccessKeySecret required
await setApiKeyToObject(localVarHeaderParameter, "access_key_secret", configuration)
localVarHeaderParameter['Content-Type'] = 'application/json';
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
localVarRequestOptions.data = serializeDataIfNeeded(body, localVarRequestOptions, configuration)
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
*
* @summary WARNING: Hard delete of an User will remove all related projects and its resources.
* @param {string} ref User\'s reference
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
deleteUser: async (ref: string, options: AxiosRequestConfig = {}): Promise<RequestArgs> => {
// verify required parameter 'ref' is not null or undefined
assertParamExists('deleteUser', 'ref', ref)
const localVarPath = `/v1beta1/users/{ref}`
.replace(`{${"ref"}}`, encodeURIComponent(String(ref)));
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'DELETE', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
// authentication AccessKeyId required
await setApiKeyToObject(localVarHeaderParameter, "access_key_id", configuration)
// authentication AccessKeySecret required
await setApiKeyToObject(localVarHeaderParameter, "access_key_secret", configuration)
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
*
* @summary Gets User by reference
* @param {string} ref User\'s reference
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
getUser: async (ref: string, options: AxiosRequestConfig = {}): Promise<RequestArgs> => {
// verify required parameter 'ref' is not null or undefined
assertParamExists('getUser', 'ref', ref)
const localVarPath = `/v1beta1/users/{ref}`
.replace(`{${"ref"}}`, encodeURIComponent(String(ref)));
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'GET', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
// authentication AccessKeyId required
await setApiKeyToObject(localVarHeaderParameter, "access_key_id", configuration)
// authentication AccessKeySecret required
await setApiKeyToObject(localVarHeaderParameter, "access_key_secret", configuration)
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
*
* @summary Lists all the Users you have access to
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
listUsers: async (options: AxiosRequestConfig = {}): Promise<RequestArgs> => {
const localVarPath = `/v1beta1/users`;
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'GET', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
// authentication AccessKeyId required
await setApiKeyToObject(localVarHeaderParameter, "access_key_id", configuration)
// authentication AccessKeySecret required
await setApiKeyToObject(localVarHeaderParameter, "access_key_secret", configuration)
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
*
* @summary Change or update fields in a resource
* @param {string} ref User\'s reference
* @param {InlineObject5} body
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
updateUser: async (ref: string, body: InlineObject5, options: AxiosRequestConfig = {}): Promise<RequestArgs> => {
// verify required parameter 'ref' is not null or undefined
assertParamExists('updateUser', 'ref', ref)
// verify required parameter 'body' is not null or undefined
assertParamExists('updateUser', 'body', body)
const localVarPath = `/v1beta1/users/{ref}`
.replace(`{${"ref"}}`, encodeURIComponent(String(ref)));
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}
const localVarRequestOptions = { method: 'PUT', ...baseOptions, ...options};
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;
// authentication AccessKeyId required
await setApiKeyToObject(localVarHeaderParameter, "access_key_id", configuration)
// authentication AccessKeySecret required
await setApiKeyToObject(localVarHeaderParameter, "access_key_secret", configuration)
localVarHeaderParameter['Content-Type'] = 'application/json';
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
localVarRequestOptions.data = serializeDataIfNeeded(body, localVarRequestOptions, configuration)
return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
}
};
/**
* UsersApi - functional programming interface
* @export
*/
export const UsersApiFp = function(configuration?: Configuration) {
const localVarAxiosParamCreator = UsersApiAxiosParamCreator(configuration)
return {
/**
*
* @summary Creates a new User resource
* @param {CreateUserRequest} body
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async createUser(body: CreateUserRequest, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<User>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.createUser(body, options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
},
/**
*
* @summary Creates a set of credentials
* @param {CreateUserCredentialsRequest} body
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async createUserCredentials(body: CreateUserCredentialsRequest, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<CreateUserCredentialsResponse>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.createUserCredentials(body, options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
},
/**
*
* @summary WARNING: Hard delete of an User will remove all related projects and its resources.
* @param {string} ref User\'s reference
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async deleteUser(ref: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<object>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.deleteUser(ref, options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
},
/**
*
* @summary Gets User by reference
* @param {string} ref User\'s reference
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async getUser(ref: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<User>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.getUser(ref, options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
},
/**
*
* @summary Lists all the Users you have access to
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async listUsers(options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<ListUsersResponse>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.listUsers(options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
},
/**
*
* @summary Change or update fields in a resource
* @param {string} ref User\'s reference
* @param {InlineObject5} body
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async updateUser(ref: string, body: InlineObject5, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<User>> {
const localVarAxiosArgs = await localVarAxiosParamCreator.updateUser(ref, body, options);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
},
}
};
/**
* UsersApi - factory interface
* @export
*/
export const UsersApiFactory = function (configuration?: Configuration, basePath?: string, axios?: AxiosInstance) {
const localVarFp = UsersApiFp(configuration)
return {
/**
*
* @summary Creates a new User resource
* @param {CreateUserRequest} body
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
createUser(body: CreateUserRequest, options?: any): AxiosPromise<User> {
return localVarFp.createUser(body, options).then((request) => request(axios, basePath));
},
/**
*
* @summary Creates a set of credentials
* @param {CreateUserCredentialsRequest} body
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
createUserCredentials(body: CreateUserCredentialsRequest, options?: any): AxiosPromise<CreateUserCredentialsResponse> {
return localVarFp.createUserCredentials(body, options).then((request) => request(axios, basePath));
},
/**
*
* @summary WARNING: Hard delete of an User will remove all related projects and its resources.
* @param {string} ref User\'s reference
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
deleteUser(ref: string, options?: any): AxiosPromise<object> {
return localVarFp.deleteUser(ref, options).then((request) => request(axios, basePath));
},
/**
*
* @summary Gets User by reference
* @param {string} ref User\'s reference
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
getUser(ref: string, options?: any): AxiosPromise<User> {
return localVarFp.getUser(ref, options).then((request) => request(axios, basePath));
},
/**
*
* @summary Lists all the Users you have access to
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
listUsers(options?: any): AxiosPromise<ListUsersResponse> {
return localVarFp.listUsers(options).then((request) => request(axios, basePath));
},
/**
*
* @summary Change or update fields in a resource
* @param {string} ref User\'s reference
* @param {InlineObject5} body
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
updateUser(ref: string, body: InlineObject5, options?: any): AxiosPromise<User> {
return localVarFp.updateUser(ref, body, options).then((request) => request(axios, basePath));
},
};
};
/**
* UsersApi - object-oriented interface
* @export
* @class UsersApi
* @extends {BaseAPI}
*/
export class UsersApi extends BaseAPI {
/**
*
* @summary Creates a new User resource
* @param {CreateUserRequest} body
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof UsersApi
*/
public createUser(body: CreateUserRequest, options?: AxiosRequestConfig) {
return UsersApiFp(this.configuration).createUser(body, options).then((request) => request(this.axios, this.basePath));
}
/**
*
* @summary Creates a set of credentials
* @param {CreateUserCredentialsRequest} body
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof UsersApi
*/
public createUserCredentials(body: CreateUserCredentialsRequest, options?: AxiosRequestConfig) {
return UsersApiFp(this.configuration).createUserCredentials(body, options).then((request) => request(this.axios, this.basePath));
}
/**
*
* @summary WARNING: Hard delete of an User will remove all related projects and its resources.
* @param {string} ref User\'s reference
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof UsersApi
*/
public deleteUser(ref: string, options?: AxiosRequestConfig) {
return UsersApiFp(this.configuration).deleteUser(ref, options).then((request) => request(this.axios, this.basePath));
}
/**
*
* @summary Gets User by reference
* @param {string} ref User\'s reference
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof UsersApi
*/
public getUser(ref: string, options?: AxiosRequestConfig) {
return UsersApiFp(this.configuration).getUser(ref, options).then((request) => request(this.axios, this.basePath));
}
/**
*
* @summary Lists all the Users you have access to
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof UsersApi
*/
public listUsers(options?: AxiosRequestConfig) {
return UsersApiFp(this.configuration).listUsers(options).then((request) => request(this.axios, this.basePath));
}
/**
*
* @summary Change or update fields in a resource
* @param {string} ref User\'s reference
* @param {InlineObject5} body
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof UsersApi
*/
public updateUser(ref: string, body: InlineObject5, options?: AxiosRequestConfig) {
return UsersApiFp(this.configuration).updateUser(ref, body, options).then((request) => request(this.axios, this.basePath));
}
} | the_stack |
import { Controller, Get, Post, Body, Query, Req } from "@nestjs/common";
import { ApiOperation, ApiBearerAuth, ApiTags } from "@nestjs/swagger";
import { Recaptcha } from "@nestlab/google-recaptcha";
import { appGitRepoInfo } from "@/main";
import { ConfigService } from "@/config/config.service";
import { UserService } from "@/user/user.service";
import { CurrentUser } from "@/common/user.decorator";
import { UserEntity } from "@/user/user.entity";
import { MailService, MailTemplate } from "@/mail/mail.service";
import { UserPrivilegeService, UserPrivilegeType } from "@/user/user-privilege.service";
import { GroupService } from "@/group/group.service";
import { AuditLogObjectType, AuditService } from "@/audit/audit.service";
import { UserMigrationService } from "@/migration/user-migration.service";
import { UserMigrationInfoEntity } from "@/migration/user-migration-info.entity";
import { delay, DELAY_FOR_SECURITY } from "@/common/delay";
import { AuthEmailVerificationCodeService, EmailVerificationCodeType } from "./auth-email-verification-code.service";
import { AuthSessionService } from "./auth-session.service";
import { AuthIpLocationService } from "./auth-ip-location.service";
import { RequestWithSession } from "./auth.middleware";
import { AuthService } from "./auth.service";
import {
LoginRequestDto,
RegisterRequestDto,
LoginResponseDto,
LoginResponseError,
CheckAvailabilityRequestDto,
CheckAvailabilityResponseDto,
SendEmailVerificationCodeRequestDto,
SendEmailVerificationCodeResponseDto,
SendEmailVerificationCodeResponseError,
RegisterResponseDto,
RegisterResponseError,
GetSessionInfoRequestDto,
GetSessionInfoResponseDto,
ResetPasswordRequestDto,
ResetPasswordResponseDto,
ResetPasswordResponseError,
ListUserSessionsRequestDto,
ListUserSessionsResponseDto,
ListUserSessionsResponseError,
RevokeUserSessionRequestDto,
RevokeUserSessionResponseDto,
RevokeUserSessionResponseError
} from "./dto";
// Refer to auth.middleware.ts for req.session
@ApiTags("Auth")
@Controller("auth")
export class AuthController {
constructor(
private readonly configService: ConfigService,
private readonly userService: UserService,
private readonly userPrivilegeService: UserPrivilegeService,
private readonly authService: AuthService,
private readonly groupService: GroupService,
private readonly authEmailVerificationCodeService: AuthEmailVerificationCodeService,
private readonly mailService: MailService,
private readonly authSessionService: AuthSessionService,
private readonly authIpLocationService: AuthIpLocationService,
private readonly auditService: AuditService,
private readonly userMigrationService: UserMigrationService
) {}
@Get("getSessionInfo")
@ApiOperation({
summary: "A (JSONP or JSON) request to get current user's info and server preference.",
description: "In order to support JSONP, this API doesn't use HTTP Authorization header."
})
async getSessionInfo(@Query() request: GetSessionInfoRequestDto): Promise<GetSessionInfoResponseDto> {
const [, user] = await this.authSessionService.accessSession(request.token);
const result: GetSessionInfoResponseDto = {
serverPreference: this.configService.preferenceConfigToBeSentToUser,
serverVersion: {
hash: appGitRepoInfo.abbreviatedSha,
date: appGitRepoInfo.committerDate
}
};
if (user) {
result.userMeta = await this.userService.getUserMeta(user, user);
result.joinedGroupsCount = await this.groupService.getUserJoinedGroupsCount(user);
result.userPrivileges = await this.userPrivilegeService.getUserPrivileges(user.id);
result.userPreference = await this.userService.getUserPreference(user);
}
if (request.jsonp)
return `(window.getSessionInfoCallback || (function (sessionInfo) { window.sessionInfo = sessionInfo; }))(${JSON.stringify(
result
// eslint-disable-next-line @typescript-eslint/no-explicit-any
)});` as any;
return result;
}
@Recaptcha()
@Post("login")
@ApiBearerAuth()
@ApiOperation({
summary: "Login with given credentials.",
description: "Recaptcha required. Return session token if success."
})
async login(
@Req() req: RequestWithSession,
@CurrentUser() currentUser: UserEntity,
@Body() request: LoginRequestDto
): Promise<LoginResponseDto> {
if (currentUser)
return {
error: LoginResponseError.ALREADY_LOGGEDIN
};
const checkNonMigratedUserPassword = async (
userMigrationInfo: UserMigrationInfoEntity
): Promise<LoginResponseDto> => {
if (!(await this.userMigrationService.checkOldPassword(userMigrationInfo, request.password))) {
await this.auditService.log(userMigrationInfo.userId, "auth.login_failed.wrong_password");
return { error: LoginResponseError.WRONG_PASSWORD };
}
return { error: LoginResponseError.USER_NOT_MIGRATED, username: userMigrationInfo.oldUsername };
};
const user = request.username
? await this.userService.findUserByUsername(request.username)
: await this.userService.findUserByEmail(request.email);
if (!user) {
if (request.username) {
// The username may be a non-migrated old user
const userMigrationInfo = await this.userMigrationService.findUserMigrationInfoByOldUsername(request.username);
if (userMigrationInfo) return await checkNonMigratedUserPassword(userMigrationInfo);
}
return {
error: LoginResponseError.NO_SUCH_USER
};
}
const userAuth = await this.authService.findUserAuthByUserId(user.id);
if (!this.authService.checkUserMigrated(userAuth))
return await checkNonMigratedUserPassword(await this.userMigrationService.findUserMigrationInfoByUserId(user.id));
if (!(await this.authService.checkPassword(userAuth, request.password))) {
await this.auditService.log(user.id, "auth.login_failed.wrong_password");
return {
error: LoginResponseError.WRONG_PASSWORD
};
}
await this.auditService.log(user.id, "auth.login");
return {
token: await this.authSessionService.newSession(user, req.ip, req.headers["user-agent"]),
username: user.username
};
}
@Post("logout")
@ApiBearerAuth()
@ApiOperation({
summary: "Logout the current session."
})
async logout(
@CurrentUser() currentUser: UserEntity,
@Req() req: RequestWithSession
): Promise<Record<string, unknown>> {
const sessionKey = req?.session?.sessionKey;
if (sessionKey) {
await this.authSessionService.endSession(sessionKey);
}
if (currentUser) await this.auditService.log("auth.logout");
return {};
}
@Get("checkAvailability")
@ApiBearerAuth()
@ApiOperation({
summary: "Check is a username or email is available."
})
async checkAvailability(@Query() request: CheckAvailabilityRequestDto): Promise<CheckAvailabilityResponseDto> {
const result: CheckAvailabilityResponseDto = {};
if (request.username != null) {
result.usernameAvailable = await this.userService.checkUsernameAvailability(request.username);
}
if (request.email != null) {
result.emailAvailable = await this.userService.checkEmailAvailability(request.email);
}
return result;
}
@Recaptcha()
@Post("sendEmailVerificationCode")
@ApiBearerAuth()
@ApiOperation({
summary: "Send email verification code for registering or changing email",
description: "Recaptcha required."
})
async sendEmailVerificationCode(
@CurrentUser() currentUser: UserEntity,
@Body() request: SendEmailVerificationCodeRequestDto
): Promise<SendEmailVerificationCodeResponseDto> {
if (request.type === EmailVerificationCodeType.Register) {
if (currentUser)
return {
error: SendEmailVerificationCodeResponseError.ALREADY_LOGGEDIN
};
if (!(await this.userService.checkEmailAvailability(request.email)))
return {
error: SendEmailVerificationCodeResponseError.DUPLICATE_EMAIL
};
} else if (request.type === EmailVerificationCodeType.ChangeEmail) {
if (!currentUser)
return {
error: SendEmailVerificationCodeResponseError.PERMISSION_DENIED
};
if (!(await this.userService.checkEmailAvailability(request.email)))
return {
error: SendEmailVerificationCodeResponseError.DUPLICATE_EMAIL
};
// No need to check old email === new email
} else if (request.type === EmailVerificationCodeType.ResetPassword) {
if (currentUser)
return {
error: SendEmailVerificationCodeResponseError.ALREADY_LOGGEDIN
};
const user = await this.userService.findUserByEmail(request.email);
if (!user)
return {
error: SendEmailVerificationCodeResponseError.NO_SUCH_USER
};
// Audit logging
await this.auditService.log(user.id, "auth.request_reset_password");
}
if (!this.configService.config.preference.security.requireEmailVerification)
return {
error: SendEmailVerificationCodeResponseError.FAILED_TO_SEND,
errorMessage: "Email verification code disabled."
};
const code = await this.authEmailVerificationCodeService.generate(request.email);
if (!code)
return {
error: SendEmailVerificationCodeResponseError.RATE_LIMITED
};
const sendMailErrorMessage = await this.mailService.sendMail(
{
[EmailVerificationCodeType.Register]: MailTemplate.RegisterVerificationCode,
[EmailVerificationCodeType.ChangeEmail]: MailTemplate.ChangeEmailVerificationCode,
[EmailVerificationCodeType.ResetPassword]: MailTemplate.ResetPasswordVerificationCode
}[request.type],
request.locale,
{
code
},
request.email
);
if (sendMailErrorMessage)
return {
error: SendEmailVerificationCodeResponseError.FAILED_TO_SEND,
errorMessage: sendMailErrorMessage
};
return {};
}
@Recaptcha()
@Post("register")
@ApiBearerAuth()
@ApiOperation({
summary: "Register then login.",
description: "Recaptcha required. Return the session token if success."
})
async register(
@Req() req: RequestWithSession,
@CurrentUser() currentUser: UserEntity,
@Body() request: RegisterRequestDto
): Promise<RegisterResponseDto> {
if (currentUser)
return {
error: RegisterResponseError.ALREADY_LOGGEDIN
};
const [error, user] = await this.authService.register(
request.username,
request.email,
request.emailVerificationCode,
request.password
);
if (error)
return {
error
};
await this.auditService.log(user.id, "auth.register", {
username: request.username,
email: request.email
});
return {
token: await this.authSessionService.newSession(user, req.ip, req.headers["user-agent"])
};
}
@Recaptcha()
@Post("resetPassword")
@ApiBearerAuth()
@ApiOperation({
summary: "Reset a user's password with email verification code and then login.",
description: "Recaptcha required."
})
async resetPassword(
@Req() req: RequestWithSession,
@CurrentUser() currentUser: UserEntity,
@Body() request: ResetPasswordRequestDto
): Promise<ResetPasswordResponseDto> {
if (currentUser)
return {
error: ResetPasswordResponseError.ALREADY_LOGGEDIN
};
const user = await this.userService.findUserByEmail(request.email);
if (!user)
return {
error: ResetPasswordResponseError.NO_SUCH_USER
};
const userAuth = await this.authService.findUserAuthByUserId(user.id);
// Delay for security
await delay(DELAY_FOR_SECURITY);
if (!(await this.authEmailVerificationCodeService.verify(request.email, request.emailVerificationCode)))
return {
error: ResetPasswordResponseError.INVALID_EMAIL_VERIFICATION_CODE
};
if (this.authService.checkUserMigrated(userAuth))
await this.authService.changePassword(userAuth, request.newPassword);
else {
// If the user has NOT been migrated, change its "password in old system"
const userMigrationInfo = await this.userMigrationService.findUserMigrationInfoByUserId(user.id);
await this.userMigrationService.changeOldPassword(userMigrationInfo, request.newPassword);
}
await this.authEmailVerificationCodeService.revoke(request.email, request.emailVerificationCode);
// Revoke ALL previous sessions
await this.authSessionService.revokeAllSessionsExcept(user.id, null);
await this.auditService.log(user.id, "auth.reset_password");
return {
token: await this.authSessionService.newSession(user, req.ip, req.headers["user-agent"])
};
}
@Post("listUserSessions")
@ApiBearerAuth()
@ApiOperation({
summary: "List a user's current logged-in sessions."
})
async listUserSessions(
@Req() req: RequestWithSession,
@CurrentUser() currentUser: UserEntity,
@Body() request: ListUserSessionsRequestDto
): Promise<ListUserSessionsResponseDto> {
if (
!(
(currentUser &&
(request.username ? currentUser.username === request.username : currentUser.id === request.userId)) ||
(await this.userPrivilegeService.userHasPrivilege(currentUser, UserPrivilegeType.ManageUser))
)
)
return {
error: ListUserSessionsResponseError.PERMISSION_DENIED
};
const userId = request.username
? (await this.userService.findUserByUsername(request.username))?.id
: request.userId;
const sessions = await this.authSessionService.listUserSessions(userId);
return {
sessions: sessions.map(sessionInfo => ({
...sessionInfo,
loginIpLocation: this.authIpLocationService.query(sessionInfo.loginIp)
})),
currentSessionId: userId === currentUser.id ? req.session.sessionId : null
};
}
@Post("revokeUserSession")
@ApiBearerAuth()
@ApiOperation({
summary: "Revoke a user's one session or sessions."
})
async revokeUserSession(
@Req() req: RequestWithSession,
@CurrentUser() currentUser: UserEntity,
@Body() request: RevokeUserSessionRequestDto
): Promise<RevokeUserSessionResponseDto> {
if (
!(
(currentUser && currentUser.id === request.userId) ||
(await this.userPrivilegeService.userHasPrivilege(currentUser, UserPrivilegeType.ManageUser))
)
)
return {
error: RevokeUserSessionResponseError.PERMISSION_DENIED
};
const user = request.userId === currentUser.id ? currentUser : await this.userService.findUserById(request.userId);
if (!user)
return {
error: RevokeUserSessionResponseError.NO_SUCH_USER
};
if (request.sessionId) {
await this.authSessionService.revokeSession(request.userId, request.sessionId);
if (request.userId === currentUser.id) await this.auditService.log("auth.session.revoke");
else await this.auditService.log("auth.session.revoke_others", AuditLogObjectType.User, request.userId);
} else {
if (request.userId === currentUser.id) {
await this.authSessionService.revokeAllSessionsExcept(request.userId, req.session.sessionId);
await this.auditService.log("auth.session.revoke_all_except_current");
} else {
await this.authSessionService.revokeAllSessionsExcept(request.userId, null);
await this.auditService.log("auth.session.revoke_others_all", AuditLogObjectType.User, request.userId);
}
}
return {};
}
} | the_stack |
import * as diff from 'diff';
import {AnnotatedText, TextAnnotation, ScopedText} from '../protocol';
export {ProofView, Goal, Hypothesis, AnnotatedText, HypothesisDifference, TextAnnotation, ScopedText} from '../protocol';
export interface Annotation {
/** the relationship this text has to the text of another state */
diff?: "added"|"removed",
/** what to display instead of this text */
substitution?: string,
}
export function isScopedText(text: AnnotatedText): text is ScopedText {
return text && text.hasOwnProperty('scope');
}
export function isTextAnnotation(text: AnnotatedText): text is TextAnnotation {
return text && typeof (text as any).text === 'string' && !text.hasOwnProperty('scope')
}
export function textToString(text: AnnotatedText) : string {
if(typeof text === 'string') {
return text;
} else if(text instanceof Array) {
return text.map(textToString).join('');
} else if(isScopedText(text)) {
return textToString(text.text);
} else {// TextAnnotation
return textToString(text.text);
}
}
export function textToDisplayString(text: AnnotatedText) : string {
if(typeof text === 'string') {
return text;
} else if(text instanceof Array) {
return text.map(textToDisplayString).join('');
} else if(isScopedText(text)) {
return textToDisplayString(text.text);
} else if(text.substitution) {// TextAnnotation
return textToDisplayString(text.substitution);
} else{// TextAnnotation
return text.substitution ? text.substitution : text.text;
}
}
export function textLength(text: AnnotatedText) : number {
if(typeof text === 'string') {
return text.length;
} else if(text instanceof Array) {
return text.reduce((c,t) => c+textLength(t),0);
} else if(isScopedText(text)) {
return textLength(text.text);
} else {// TextAnnotation
return text.text.length;
}
}
export function textDisplayLength(text: AnnotatedText) : number {
if(typeof text === 'string') {
return text.length;
} else if(text instanceof Array) {
return text.reduce((c,t) => c+textDisplayLength(t),0);
} else if(isScopedText(text)) {
return textDisplayLength(text.text);
} else {// TextAnnotation
return text.substitution ? text.substitution.length : text.text.length;
}
}
export function copyAnnotation(x: Annotation) : Annotation {
if(x.diff!==undefined && x.substitution!==undefined)
return {diff: x.diff, substitution: x.substitution};
if(x.diff!==undefined)
return {diff: x.diff};
if(x.substitution!==undefined)
return {substitution: x.substitution};
else
return {};
}
/**
* Splits the text into parts separated by `separator`.
*/
export function textSplit(text: AnnotatedText, separator: string|RegExp, limit?: number) : {splits: (string | TextAnnotation | ScopedText)[], rest: AnnotatedText} {
if(typeof text === 'string') {
const result = text.split(separator as any).filter((v) => v!=="");
return {splits: result.slice(0,limit), rest: limit===undefined ? [] : result.slice(limit)}
} else if(text instanceof Array) {
const splits : (string | TextAnnotation | ScopedText)[] = [];
let idx = 0;
let rest : AnnotatedText = [];
let count = 0;
for(/**/ ; (limit===undefined || count < limit) && idx < text.length; ++idx) {
const {splits: splits2, rest: rest2} = textSplit(text[idx], separator, limit===undefined? undefined : limit-count);
splits.push(...splits2);
count += splits2.length;
rest = rest2;
}
if(limit === undefined)
return {splits: splits, rest: []};
else {
if(rest instanceof Array)
return {splits: splits.slice(0,limit), rest: [...splits.slice(limit), ...rest, ...text.slice(idx)]};
else
return {splits: splits.slice(0,limit), rest: [...splits.slice(limit), rest, ...text.slice(idx)]};
}
} else if(isScopedText(text)) {
const {splits: splits, rest: rest} = textSplit(text.text, separator, limit);
const splitsResult = splits.map((s: AnnotatedText) => text.attributes ? {scope: text.scope, attributes: text.attributes, text: s} : {scope: text.scope, text: s} );
const restResult : ScopedText = {scope: text.scope, text: rest}
if(text.attributes)
restResult.attributes = text.attributes;
return {splits: splitsResult, rest: restResult};
} else {// TextAnnotation
const result = text.text.split(separator as any).filter((v) => v!=="");
return {
splits: result.slice(0,limit).map((s) =>
normalizeTextAnnotationOrString({diff:text.diff, substitution:text.substitution, text: s})),
rest: limit===undefined ? [] :
result.slice(limit).map((s) =>
normalizeTextAnnotationOrString({diff:text.diff, substitution:text.substitution, text: s}))}
}
}
function subtextHelper<T extends AnnotatedText>(text: T, pos: number, start: number, end?: number) : {result: T, length: number, next: number} {
if(typeof text === 'string') {
const t = text as string;
const s = t.substring(start-pos, end===undefined ? undefined : end-pos);
return {result: s as T, length: s.length, next: pos + t.length};
} else if(text instanceof Array) {
const strs : (string | TextAnnotation | ScopedText)[] = [];
let len = 0;
for(let idx = 0 ; idx < text.length && (end===undefined || pos < end); ++idx) {
const s = subtextHelper<string | TextAnnotation | ScopedText>(text[idx], pos, start, end);
if(s.length > 0) {
if(s.result instanceof Array)
strs.push(...s.result);
else
strs.push(s.result);
}
len+= s.length;
pos = s.next;
}
return {result: strs as T, length: len, next: pos}
} else if(isScopedText(text)) {
const s = subtextHelper(text.text, pos, start, end);
return {result: {scope: text.scope, attributes: text.attributes, text: s.result} as any as T, length: s.length, next: s.next};
} else {// TextAnnotation
const t = text as TextAnnotation;
const s = t.text.substring(start-pos, end===undefined ? undefined : end-pos);
return {result: {diff: t.diff, substitution: t.substitution, text: s} as any as T, length: s.length, next: pos+s.length};
}
}
export function subtext(text: AnnotatedText, start: number, end?: number) : AnnotatedText {
const s = subtextHelper(text, 0, start, end);
return normalizeText(s.result);
}
export function subtextCount(text: AnnotatedText, start: number, count: number) : AnnotatedText {
const s = subtextHelper(text, 0, start, start+count);
return normalizeText(s.result);
}
function mapAnnotationInternal(text: AnnotatedText, map: (text: string, annotation: Annotation, start: number, displayStart: number) => AnnotatedText, currentOffset: number, currentDisplayOffset: number) : {text: AnnotatedText, endOffset: number, endDisplayOffset: number } {
if(typeof text === 'string') {
const result = map(text,{},currentOffset,currentDisplayOffset);
return {text: result, endOffset: currentOffset + textLength(result), endDisplayOffset: currentDisplayOffset + textDisplayLength(result)};
} else if(text instanceof Array) {
const results : (string|TextAnnotation|ScopedText)[] = [];
for(let txt of text) {
const newText = mapAnnotationInternal(txt,map,currentOffset,currentDisplayOffset);
currentOffset = newText.endOffset;
currentDisplayOffset = newText.endDisplayOffset;
if(newText.text instanceof Array)
results.push(...newText.text);
else
results.push(newText.text);
}
return {text: results, endOffset: currentOffset, endDisplayOffset: currentDisplayOffset};
} else if(isScopedText(text)) {
const result = mapAnnotationInternal(text.text,map,currentOffset,currentDisplayOffset);
const resultText : ScopedText = {scope: text.scope, text: result.text};
if(text.attributes)
resultText.attributes = text.attributes;
return {text: resultText, endOffset: result.endOffset, endDisplayOffset: result.endDisplayOffset};
} else {// TextAnnotation
const newText = map(text.text,copyAnnotation(text),currentOffset,currentDisplayOffset);
return {text: newText, endOffset: currentOffset + textLength(newText), endDisplayOffset: currentDisplayOffset + textDisplayLength(newText)};
}
}
export function mapAnnotation(text: AnnotatedText, map: (text: string, annotation: Annotation, start: number, displayStart: number) => AnnotatedText) {
return mapAnnotationInternal(text,map,0,0).text;
}
/**
* Substitutions are compatible if either:
* 1) neither has a substitution or
* 2) both have substitutions and one will be substituted with ""
*/
export function compatibleAnnotations<T extends Annotation>(ann1: T, ann2: T) : boolean {
return ann1.diff === ann2.diff && ((ann1.substitution === undefined && ann2.substitution === undefined) || (ann1.substitution === "" || ann2.substitution === ""))
}
function concatText(text1: AnnotatedText, text2: AnnotatedText) : AnnotatedText {
if(typeof text1 === 'string' && typeof text2 === 'string')
return [text1 + text2];
else if(text1 instanceof Array)
return text1.concat(text2)
else if(text2 instanceof Array)
return [text1, ...text2]
else
return [text1,text2]
}
export function tryCombineText(text1: string|TextAnnotation|ScopedText, text2: string|TextAnnotation|ScopedText) : string|TextAnnotation|ScopedText|undefined {
if(typeof text1 === 'string' && typeof text2 === 'string')
return text1 + text2;
else if(text1 === '')
return text2;
else if(text2 === '')
return text1;
else if(isScopedText(text1) && isScopedText(text2) && text1.scope === text2.scope && text1.attributes === text2.attributes) {
if(text1.attributes)
return {scope: text1.scope, attributes: text1.attributes, text: normalizeText(concatText(text1.text,text2.text))};
else
return {scope: text1.scope, text: normalizeText(concatText(text1.text,text2.text))};
} else if(isTextAnnotation(text1) && isTextAnnotation(text2) && compatibleAnnotations(text1,text2)) {
return normalizeTextAnnotationOrString({diff: text1.diff, substitution: text1.substitution||text2.substitution, text: text1.text+text2.text});
} else
return undefined
}
export function normalizeTextAnnotationOrString(text: string) : string;
export function normalizeTextAnnotationOrString(text: TextAnnotation) : TextAnnotation|string;
export function normalizeTextAnnotationOrString(text: TextAnnotation|string) : TextAnnotation|string {
if(typeof text === 'string') {
return text;
} else {// TextAnnotation
let count = 0;
for(let key in text) {
if(text.hasOwnProperty(key) && text[key] !== undefined)
++count;
}
for(let key in text) {
if(text.hasOwnProperty(key) && text[key] === undefined)
delete text[key];
}
if(count > 1) // has annotations
return text;
else
return text.text
}
}
export function normalizeText(text: AnnotatedText) : AnnotatedText {
if(typeof text === 'string') {
return text;
} else if(text instanceof Array) {
if(text.length === 0)
return "";
const results : (string|TextAnnotation|ScopedText)[] = [];
const norm = normalizeText(text[0]);
if(norm instanceof Array)
results.push(...norm);
else
results.push(norm);
for(let idx = 1; idx < text.length; ++idx) {
const norm = normalizeText(text[idx]);
if(norm instanceof Array) {
if(norm.length === 0)
continue;
let first = norm.shift();
const merge = tryCombineText(results[results.length-1], first);
if(merge)
results[results.length-1] = merge;
else
results.push(merge);
results.push(...norm);
} else {
const merge = tryCombineText(results[results.length-1], norm);
if(merge)
results[results.length-1] = merge;
else
results.push(norm);
}
}
if(results.length === 1)
return results[0];
else
return results;
} else if(isScopedText(text)) {
const norm = normalizeText(text.text);
if(text.scope === "" || norm === "")
return norm;
else if(text.attributes && Object.keys(text.attributes).length > 0)
return {scope: text.scope, attributes: text.attributes, text: norm};
else
return {scope: text.scope, text: norm};
} else {// TextAnnotation
let count = 0;
for(let key in text) {
if(text.hasOwnProperty(key) && text[key] !== undefined)
++count;
else if(text.hasOwnProperty(key) && text[key] === undefined)
delete text[key];
}
if(count > 1) // has annotations
return text;
else
return text.text
}
}
export function combineAnnotationText(text: TextAnnotation|string, baseAnn: Annotation) : TextAnnotation|string {
let result : TextAnnotation;
if(typeof text === 'string')
result = Object.assign(copyAnnotation(baseAnn), {text:text});
else
result = Object.assign(copyAnnotation(baseAnn), text);
return normalizeTextAnnotationOrString(result);
}
function toDiff(d: diff.Change, mode: "old"|"new") : "added"|"removed"|undefined{
if(mode === "new" && d.added)
return "added";
else if(mode === "old" && d.removed)
return "removed";
else
return undefined;
}
/**
* @param mode - whether `text` is the old or new string
*/
export function annotateDiffAdded(text: AnnotatedText, differences: diff.Change[], options: {diffSubstitutions: boolean, mode: "old"|"new"}) : AnnotatedText {
let idx = 0; // the current diff
let offset = 0; // position of current diff w.r.t. textToString() (not textToDisplayString())
let diffOffset = 0; // the offset into the current diff; used when a diff spans multiple text parts
// we're only interested in unchanged parts and either added(mode="new") or removed(mode="old") parts
if(options.mode === "new")
differences = differences.filter((d) => !d.removed);
else
differences = differences.filter((d) => !d.added);
const result = mapAnnotation(text, (plainText, annotation, startOffset, startDisplayOffset) => {
let text: string;
let start: number;
let doSubst = false;
if(options.diffSubstitutions)
start = startDisplayOffset;
else
start = startOffset;
if(annotation.substitution && options.diffSubstitutions) {
text = annotation.substitution;
doSubst = true;
} else
text = plainText;
if(offset+diffOffset != start)
throw "invalid diff: does not line up with text position";
const parts: (TextAnnotation|string)[] = [];
for(; idx < differences.length && offset+differences[idx].value.length <= start + text.length; ++idx) {
const diff = differences[idx];
if(doSubst) {
parts.push(combineAnnotationText({ text: plainText
, substitution: diff.value.substr(diffOffset)
, diff: toDiff(diff, options.mode)
}, annotation));
plainText = ""; // remaining parts will have empty text
} else
parts.push(combineAnnotationText({text: diff.value.substr(diffOffset), diff: toDiff(diff, options.mode)},annotation))
offset+= diff.value.length;
// In case we are breaking a substitution into multiple parts,
// we only want the first part to apply the full substitution;
// the rest will be substituted with the empty string
if(annotation.substitution)
annotation.substitution = "";
diffOffset = 0;
}
// The diff spans this text and the next; add the *this* part
if(idx < differences.length && offset < start+text.length) {
// ASSUME: offset+differences[idx].value.length > start+text.length
// I.E. ASSUME: current-diff-end extends beyond text
if(doSubst) {
parts.push(combineAnnotationText(
{ text: plainText
, substitution: text.substring(offset+diffOffset-start)
, diff: toDiff(differences[idx], options.mode)
}, annotation));
} else
parts.push(combineAnnotationText({text: text.substring(offset+diffOffset-start), diff: toDiff(differences[idx], options.mode)},annotation))
// NOTE: do not advance idx or offset, but advance diffOffset
diffOffset+= text.length + start - offset - diffOffset;
}
// The diffs *should* be
if(idx > differences.length && offset < start+text.length)
throw "invalid diff: does not line up with text length";
if(parts.length === 0)
return "";
else if(parts.length === 1)
return parts[0];
else
return parts;
});
return result;
}
export function diffText(oldText: AnnotatedText, newText: AnnotatedText, normalize = true) : {text: AnnotatedText, different: boolean} {
if(!oldText)
return {text: newText, different: false};
const difference = diff.diffWords(textToDisplayString(oldText), textToDisplayString(newText));
const result = annotateDiffAdded(newText, difference, {diffSubstitutions: true, mode: "new"});
if(normalize)
return {text: normalizeText(result), different: difference.length > 1 }
else
return {text: result, different: difference.length > 1 }
}
export function append(...texts: AnnotatedText[]) : AnnotatedText {
const results : (string|TextAnnotation|ScopedText)[] = [];
for(let txt of texts) {
if(txt instanceof Array)
results.push(...txt);
else
results.push(txt);
}
if(results.length === 0)
return "";
else if(results.length === 1)
return results[0];
else
return results;
} | the_stack |
import { PagedAsyncIterableIterator } from "@azure/core-paging";
import { PollerLike, PollOperationState } from "@azure/core-lro";
import {
GremlinDatabaseGetResults,
GremlinResourcesListGremlinDatabasesOptionalParams,
GremlinGraphGetResults,
GremlinResourcesListGremlinGraphsOptionalParams,
GremlinResourcesGetGremlinDatabaseOptionalParams,
GremlinResourcesGetGremlinDatabaseResponse,
GremlinDatabaseCreateUpdateParameters,
GremlinResourcesCreateUpdateGremlinDatabaseOptionalParams,
GremlinResourcesCreateUpdateGremlinDatabaseResponse,
GremlinResourcesDeleteGremlinDatabaseOptionalParams,
GremlinResourcesGetGremlinDatabaseThroughputOptionalParams,
GremlinResourcesGetGremlinDatabaseThroughputResponse,
ThroughputSettingsUpdateParameters,
GremlinResourcesUpdateGremlinDatabaseThroughputOptionalParams,
GremlinResourcesUpdateGremlinDatabaseThroughputResponse,
GremlinResourcesGetGremlinGraphOptionalParams,
GremlinResourcesGetGremlinGraphResponse,
GremlinGraphCreateUpdateParameters,
GremlinResourcesCreateUpdateGremlinGraphOptionalParams,
GremlinResourcesCreateUpdateGremlinGraphResponse,
GremlinResourcesDeleteGremlinGraphOptionalParams,
GremlinResourcesGetGremlinGraphThroughputOptionalParams,
GremlinResourcesGetGremlinGraphThroughputResponse,
GremlinResourcesUpdateGremlinGraphThroughputOptionalParams,
GremlinResourcesUpdateGremlinGraphThroughputResponse
} from "../models";
/// <reference lib="esnext.asynciterable" />
/** Interface representing a GremlinResources. */
export interface GremlinResources {
/**
* Lists the Gremlin databases under an existing Azure Cosmos DB database account.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName Cosmos DB database account name.
* @param options The options parameters.
*/
listGremlinDatabases(
resourceGroupName: string,
accountName: string,
options?: GremlinResourcesListGremlinDatabasesOptionalParams
): PagedAsyncIterableIterator<GremlinDatabaseGetResults>;
/**
* Lists the Gremlin graph under an existing Azure Cosmos DB database account.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName Cosmos DB database account name.
* @param databaseName Cosmos DB database name.
* @param options The options parameters.
*/
listGremlinGraphs(
resourceGroupName: string,
accountName: string,
databaseName: string,
options?: GremlinResourcesListGremlinGraphsOptionalParams
): PagedAsyncIterableIterator<GremlinGraphGetResults>;
/**
* Gets the Gremlin databases under an existing Azure Cosmos DB database account with the provided
* name.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName Cosmos DB database account name.
* @param databaseName Cosmos DB database name.
* @param options The options parameters.
*/
getGremlinDatabase(
resourceGroupName: string,
accountName: string,
databaseName: string,
options?: GremlinResourcesGetGremlinDatabaseOptionalParams
): Promise<GremlinResourcesGetGremlinDatabaseResponse>;
/**
* Create or update an Azure Cosmos DB Gremlin database
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName Cosmos DB database account name.
* @param databaseName Cosmos DB database name.
* @param createUpdateGremlinDatabaseParameters The parameters to provide for the current Gremlin
* database.
* @param options The options parameters.
*/
beginCreateUpdateGremlinDatabase(
resourceGroupName: string,
accountName: string,
databaseName: string,
createUpdateGremlinDatabaseParameters: GremlinDatabaseCreateUpdateParameters,
options?: GremlinResourcesCreateUpdateGremlinDatabaseOptionalParams
): Promise<
PollerLike<
PollOperationState<GremlinResourcesCreateUpdateGremlinDatabaseResponse>,
GremlinResourcesCreateUpdateGremlinDatabaseResponse
>
>;
/**
* Create or update an Azure Cosmos DB Gremlin database
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName Cosmos DB database account name.
* @param databaseName Cosmos DB database name.
* @param createUpdateGremlinDatabaseParameters The parameters to provide for the current Gremlin
* database.
* @param options The options parameters.
*/
beginCreateUpdateGremlinDatabaseAndWait(
resourceGroupName: string,
accountName: string,
databaseName: string,
createUpdateGremlinDatabaseParameters: GremlinDatabaseCreateUpdateParameters,
options?: GremlinResourcesCreateUpdateGremlinDatabaseOptionalParams
): Promise<GremlinResourcesCreateUpdateGremlinDatabaseResponse>;
/**
* Deletes an existing Azure Cosmos DB Gremlin database.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName Cosmos DB database account name.
* @param databaseName Cosmos DB database name.
* @param options The options parameters.
*/
beginDeleteGremlinDatabase(
resourceGroupName: string,
accountName: string,
databaseName: string,
options?: GremlinResourcesDeleteGremlinDatabaseOptionalParams
): Promise<PollerLike<PollOperationState<void>, void>>;
/**
* Deletes an existing Azure Cosmos DB Gremlin database.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName Cosmos DB database account name.
* @param databaseName Cosmos DB database name.
* @param options The options parameters.
*/
beginDeleteGremlinDatabaseAndWait(
resourceGroupName: string,
accountName: string,
databaseName: string,
options?: GremlinResourcesDeleteGremlinDatabaseOptionalParams
): Promise<void>;
/**
* Gets the RUs per second of the Gremlin database under an existing Azure Cosmos DB database account
* with the provided name.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName Cosmos DB database account name.
* @param databaseName Cosmos DB database name.
* @param options The options parameters.
*/
getGremlinDatabaseThroughput(
resourceGroupName: string,
accountName: string,
databaseName: string,
options?: GremlinResourcesGetGremlinDatabaseThroughputOptionalParams
): Promise<GremlinResourcesGetGremlinDatabaseThroughputResponse>;
/**
* Update RUs per second of an Azure Cosmos DB Gremlin database
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName Cosmos DB database account name.
* @param databaseName Cosmos DB database name.
* @param updateThroughputParameters The RUs per second of the parameters to provide for the current
* Gremlin database.
* @param options The options parameters.
*/
beginUpdateGremlinDatabaseThroughput(
resourceGroupName: string,
accountName: string,
databaseName: string,
updateThroughputParameters: ThroughputSettingsUpdateParameters,
options?: GremlinResourcesUpdateGremlinDatabaseThroughputOptionalParams
): Promise<
PollerLike<
PollOperationState<
GremlinResourcesUpdateGremlinDatabaseThroughputResponse
>,
GremlinResourcesUpdateGremlinDatabaseThroughputResponse
>
>;
/**
* Update RUs per second of an Azure Cosmos DB Gremlin database
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName Cosmos DB database account name.
* @param databaseName Cosmos DB database name.
* @param updateThroughputParameters The RUs per second of the parameters to provide for the current
* Gremlin database.
* @param options The options parameters.
*/
beginUpdateGremlinDatabaseThroughputAndWait(
resourceGroupName: string,
accountName: string,
databaseName: string,
updateThroughputParameters: ThroughputSettingsUpdateParameters,
options?: GremlinResourcesUpdateGremlinDatabaseThroughputOptionalParams
): Promise<GremlinResourcesUpdateGremlinDatabaseThroughputResponse>;
/**
* Gets the Gremlin graph under an existing Azure Cosmos DB database account.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName Cosmos DB database account name.
* @param databaseName Cosmos DB database name.
* @param graphName Cosmos DB graph name.
* @param options The options parameters.
*/
getGremlinGraph(
resourceGroupName: string,
accountName: string,
databaseName: string,
graphName: string,
options?: GremlinResourcesGetGremlinGraphOptionalParams
): Promise<GremlinResourcesGetGremlinGraphResponse>;
/**
* Create or update an Azure Cosmos DB Gremlin graph
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName Cosmos DB database account name.
* @param databaseName Cosmos DB database name.
* @param graphName Cosmos DB graph name.
* @param createUpdateGremlinGraphParameters The parameters to provide for the current Gremlin graph.
* @param options The options parameters.
*/
beginCreateUpdateGremlinGraph(
resourceGroupName: string,
accountName: string,
databaseName: string,
graphName: string,
createUpdateGremlinGraphParameters: GremlinGraphCreateUpdateParameters,
options?: GremlinResourcesCreateUpdateGremlinGraphOptionalParams
): Promise<
PollerLike<
PollOperationState<GremlinResourcesCreateUpdateGremlinGraphResponse>,
GremlinResourcesCreateUpdateGremlinGraphResponse
>
>;
/**
* Create or update an Azure Cosmos DB Gremlin graph
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName Cosmos DB database account name.
* @param databaseName Cosmos DB database name.
* @param graphName Cosmos DB graph name.
* @param createUpdateGremlinGraphParameters The parameters to provide for the current Gremlin graph.
* @param options The options parameters.
*/
beginCreateUpdateGremlinGraphAndWait(
resourceGroupName: string,
accountName: string,
databaseName: string,
graphName: string,
createUpdateGremlinGraphParameters: GremlinGraphCreateUpdateParameters,
options?: GremlinResourcesCreateUpdateGremlinGraphOptionalParams
): Promise<GremlinResourcesCreateUpdateGremlinGraphResponse>;
/**
* Deletes an existing Azure Cosmos DB Gremlin graph.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName Cosmos DB database account name.
* @param databaseName Cosmos DB database name.
* @param graphName Cosmos DB graph name.
* @param options The options parameters.
*/
beginDeleteGremlinGraph(
resourceGroupName: string,
accountName: string,
databaseName: string,
graphName: string,
options?: GremlinResourcesDeleteGremlinGraphOptionalParams
): Promise<PollerLike<PollOperationState<void>, void>>;
/**
* Deletes an existing Azure Cosmos DB Gremlin graph.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName Cosmos DB database account name.
* @param databaseName Cosmos DB database name.
* @param graphName Cosmos DB graph name.
* @param options The options parameters.
*/
beginDeleteGremlinGraphAndWait(
resourceGroupName: string,
accountName: string,
databaseName: string,
graphName: string,
options?: GremlinResourcesDeleteGremlinGraphOptionalParams
): Promise<void>;
/**
* Gets the Gremlin graph throughput under an existing Azure Cosmos DB database account with the
* provided name.
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName Cosmos DB database account name.
* @param databaseName Cosmos DB database name.
* @param graphName Cosmos DB graph name.
* @param options The options parameters.
*/
getGremlinGraphThroughput(
resourceGroupName: string,
accountName: string,
databaseName: string,
graphName: string,
options?: GremlinResourcesGetGremlinGraphThroughputOptionalParams
): Promise<GremlinResourcesGetGremlinGraphThroughputResponse>;
/**
* Update RUs per second of an Azure Cosmos DB Gremlin graph
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName Cosmos DB database account name.
* @param databaseName Cosmos DB database name.
* @param graphName Cosmos DB graph name.
* @param updateThroughputParameters The RUs per second of the parameters to provide for the current
* Gremlin graph.
* @param options The options parameters.
*/
beginUpdateGremlinGraphThroughput(
resourceGroupName: string,
accountName: string,
databaseName: string,
graphName: string,
updateThroughputParameters: ThroughputSettingsUpdateParameters,
options?: GremlinResourcesUpdateGremlinGraphThroughputOptionalParams
): Promise<
PollerLike<
PollOperationState<GremlinResourcesUpdateGremlinGraphThroughputResponse>,
GremlinResourcesUpdateGremlinGraphThroughputResponse
>
>;
/**
* Update RUs per second of an Azure Cosmos DB Gremlin graph
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param accountName Cosmos DB database account name.
* @param databaseName Cosmos DB database name.
* @param graphName Cosmos DB graph name.
* @param updateThroughputParameters The RUs per second of the parameters to provide for the current
* Gremlin graph.
* @param options The options parameters.
*/
beginUpdateGremlinGraphThroughputAndWait(
resourceGroupName: string,
accountName: string,
databaseName: string,
graphName: string,
updateThroughputParameters: ThroughputSettingsUpdateParameters,
options?: GremlinResourcesUpdateGremlinGraphThroughputOptionalParams
): Promise<GremlinResourcesUpdateGremlinGraphThroughputResponse>;
} | the_stack |
import i18next from 'i18next';
import _ from 'lodash';
import { ControlResponseBuilder } from '../..';
import { ControlInput } from '../../controls/ControlInput';
import { AplContent, ListAPLComponentProps, ListControl, ListControlRenderedItem } from './ListControl';
/*
* Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "license" file accompanying this file. This file 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.
*/
export namespace ListControlAPLPropsBuiltIns {
export interface DefaultSelectValueAPLProps {
/**
* Default: 'Please select'
*/
title?: string;
/**
* Default: ''
*/
subtitle?: string;
/**
* Function that maps the ListControlState.value to rendered value that
* will be presented to the user as a list.
*
* Default: returns the value unchanged.
*/
valueRenderer: (value: string, input: ControlInput) => ListControlRenderedItem;
}
export function defaultSelectValueAPLContent(
props: DefaultSelectValueAPLProps,
): (control: ListControl, input: ControlInput) => AplContent {
return (control: ListControl, input: ControlInput) => {
return {
document: listDocumentGenerator(control, input),
dataSource: listDataSourceGenerator(control, input, props),
};
};
}
/**
* The APL dataSource to use when requesting a value
*
* Default: A TextListLayout data source to bind to an APL document.
* See
* https://developer.amazon.com/en-US/docs/alexa/alexa-presentation-language/apl-data-source.html
*/
export function listDataSourceGenerator(
control: ListControl,
input: ControlInput,
contentProps: DefaultSelectValueAPLProps,
) {
const listOfChoices = [];
const choices = control.getChoicesList(input);
for (const item of choices) {
listOfChoices.push({
primaryText: contentProps.valueRenderer(item, input).primaryText!,
});
}
return {
general: {
headerTitle: contentProps.title ?? i18next.t('LIST_CONTROL_DEFAULT_APL_HEADER_TITLE'),
headerSubtitle: contentProps.subtitle ?? '',
controlId: control.id,
},
choices: {
listItems: listOfChoices,
},
};
}
/**
* The APL document to use when requesting a value
*
* Default: A TextListLayout document with scrollable and clickable list.
* See
* https://developer.amazon.com/en-US/docs/alexa/alexa-presentation-language/apl-alexa-text-list-layout.html
*/
export function listDocumentGenerator(control: ListControl, input: ControlInput) {
return {
type: 'APL',
version: '1.3',
import: [
{
name: 'alexa-layouts',
version: '1.1.0',
},
],
mainTemplate: {
parameters: ['payload'],
items: [
{
type: 'AlexaTextList',
theme: '${viewport.theme}',
headerTitle: '${payload.general.headerTitle}',
headerDivider: true,
backgroundColor: 'transparent',
touchForward: true,
primaryAction: {
type: 'SendEvent',
arguments: ['${payload.general.controlId}', '${ordinal}'],
},
listItems: '${payload.choices.listItems}',
},
],
},
};
}
}
/**
* Namespace which define built-in renderers for APL Component Mode.
*/
export namespace ListControlComponentAPLBuiltIns {
/**
* Function which returns an APL component using ImageListLayout.
*
* @param control - ListControl
* @param props - Control context props e.g valueRenderer
* @param input - Input
* @param resultBuilder - Result builder
*/
export function renderImageList(
control: ListControl,
props: ListAPLComponentProps,
input: ControlInput,
resultBuilder: ControlResponseBuilder,
) {
// TODO: Offer customization of where the image is placed, highlight colors, etc
resultBuilder.addAPLDocumentLayout('ImageListSelector', {
parameters: [
{
name: 'controlId',
type: 'string',
},
{
name: 'listItems',
type: 'object',
},
],
items: [
{
type: 'Container',
width: '100%',
height: '100%',
paddingLeft: '20px',
item: {
type: 'Sequence',
data: '${listItems}',
width: '100%',
height: '100%',
numbered: true,
items: [
{
type: 'TouchWrapper',
width: '100%',
height: '170px',
onPress: [
{
type: 'Sequential',
commands: [
{
type: 'SendEvent',
arguments: ['${controlId}', '${ordinal}'],
},
{
type: 'SetValue',
componentId: 'root',
property: 'disableScreen',
value: true,
},
],
},
],
item: {
type: 'Container',
width: '100%',
height: '100%',
direction: 'column',
items: [
{
type: 'Text',
id: 'paddingPlaceholder',
height: '20px',
text: '',
},
{
type: 'Frame',
backgroundColor: '${data.backgroundColor}',
item: {
type: 'Container',
width: '100%',
height: '100%',
direction: 'row',
alignItems: 'center',
justifyContent: 'center',
items: [
{
width: '70%',
height: '100%',
type: 'Container',
direction: 'column',
justifyContent: 'center',
items: [
{
type: 'Text',
text: '${data.primaryText}',
fontSize: '@fontSizeSmall',
color: '${data.fontColor}',
},
{
type: 'Text',
text: '${data.secondaryText}',
fontSize: '@fontSizeXSmall',
color: '${data.fontColor}',
},
],
},
{
type: 'Container',
direction: 'column',
width: '30%',
height: '100%',
items: [
{
type: 'Image',
borderRadius: '90',
width: '150px',
height: '150px',
source: '${data.imageSource}',
},
],
},
],
},
},
],
},
},
],
},
},
],
});
const itemIds: string[] = control.getListItemIDs(input);
// Create the inline document, which instantiates the Layout
const listItems = itemIds.map((item) => {
const renderedItem: ListControlRenderedItem = props.valueRenderer!(item, input);
return {
primaryText: renderedItem.primaryText,
secondaryText: renderedItem.secondaryText ?? '',
imageSource: renderedItem.imageSource ?? 'Invalid Image Source',
fontColor:
props.highlightSelected !== undefined && props.highlightSelected
? control.state.value === item
? 'white'
: '#777777'
: 'white',
backgroundColor:
props.highlightSelected !== undefined && props.highlightSelected
? control.state.value === item
? 'blue'
: '#222222'
: '#222222',
};
});
return {
type: 'ImageListSelector',
controlId: control.id,
listItems,
};
}
/**
* Function which returns an APL component using TextListLayout.
*
* @param control - ListControl
* @param props - Control context props e.g valueRenderer
* @param input - Input
* @param resultBuilder - Result builder
*/
export function renderTextList(
control: ListControl,
props: ListAPLComponentProps,
input: ControlInput,
resultBuilder: ControlResponseBuilder,
) {
resultBuilder.addAPLDocumentLayout('TextListSelector', {
parameters: [
{
name: 'controlId',
type: 'string',
},
{
name: 'listItems',
type: 'array',
},
],
items: [
{
type: 'Sequence',
scrollDirection: 'vertical',
data: '${listItems}',
width: '100%',
height: '100%',
paddingLeft: '0',
numbered: true,
items: [
{
type: 'Container',
items: [
{
type: 'AlexaTextListItem',
touchForward: true,
hideOrdinal: false,
disabled: '${disableScreen}',
primaryText: '${data.primaryText}',
primaryAction: {
type: 'Sequential',
commands: [
{
type: 'SendEvent',
arguments: ['${controlId}', '${ordinal}'],
},
{
type: 'SetValue',
componentId: 'root',
property: 'disableScreen',
value: true,
},
{
type: 'SetValue',
componentId: 'root',
property: 'debugText',
value: 'Done Selected',
},
],
},
},
],
},
],
},
],
});
const itemIds: string[] = control.getListItemIDs(input);
// Create the inline document, which instantiates the Layout
const listItems = itemIds.map((x) => ({
primaryText: props.valueRenderer!(x, input).primaryText,
}));
return {
type: 'TextListSelector',
controlId: control.id,
listItems,
};
}
/**
* Defines TextListRenderer for APLComponentMode.
*/
export class TextListRenderer {
/**
* Provides a default implementation of textList with default props.
*
* @param control - ListControl
* @param defaultProps - props
* @param input - Input
* @param resultBuilder - Result builder
*/
static default = (
control: ListControl,
defaultProps: ListAPLComponentProps,
input: ControlInput,
resultBuilder: ControlResponseBuilder,
) => renderTextList(control, defaultProps, input, resultBuilder);
/**
* Provides customization over `renderTextList()` arguments where the input
* props overrides the defaults.
*
* @param props - props
*/
static of(props: ListAPLComponentProps) {
return (
control: ListControl,
defaultProps: ListAPLComponentProps,
input: ControlInput,
resultBuilder: ControlResponseBuilder,
) => {
// Merges the user-provided props with the default props.
// Any property defined by the user-provided data overrides the defaults.
const mergedProps = _.merge(defaultProps, props);
return renderTextList(control, mergedProps, input, resultBuilder);
};
}
}
/**
* Defines ImageListRenderer for APLComponentMode.
*/
export class ImageListRenderer {
/**
* Provides a default implementation of imageList with default props.
*
* @param control - ListControl
* @param defaultProps - props
* @param input - Input
* @param resultBuilder - Result builder
*/
static default = (
control: ListControl,
defaultProps: ListAPLComponentProps,
input: ControlInput,
resultBuilder: ControlResponseBuilder,
) => renderImageList(control, { ...defaultProps, highlightSelected: true }, input, resultBuilder);
/**
* Provides customization over `renderImageList()` arguments where the input
* props overrides the defaults.
*
* @param props - props
*/
static of(props: ListAPLComponentProps) {
return (
control: ListControl,
defaultProps: ListAPLComponentProps,
input: ControlInput,
resultBuilder: ControlResponseBuilder,
) => {
// Assign defaults to props.
defaultProps.highlightSelected = true;
// Merges the user-provided props with the default props.
// Any property defined by the user-provided data overrides the defaults.
const mergedProps = _.merge(defaultProps, props);
return renderImageList(control, mergedProps, input, resultBuilder);
};
}
}
} | the_stack |
import {TextChannel, User} from "discord.js";
import {DraftBotEmbed} from "../messages/DraftBotEmbed";
import {Translations} from "../Translations";
import {ChoiceItem, DraftBotListChoiceMessage} from "../messages/DraftBotListChoiceMessage";
import {DraftBotValidateReactionMessage} from "../messages/DraftBotValidateReactionMessage";
import {Constants} from "../Constants";
import {format} from "./StringFormatter";
import {Random} from "random-js";
import Armor, {Armors} from "../models/Armor";
import Weapon, {Weapons} from "../models/Weapon";
import Potion, {Potions} from "../models/Potion";
import ObjectItem, {ObjectItems} from "../models/ObjectItem";
import Entity, {Entities} from "../models/Entity";
import InventorySlot from "../models/InventorySlot";
import {MissionsController} from "../missions/MissionsController";
import {GenericItemModel} from "../models/GenericItemModel";
import Player from "../models/Player";
import {BlockingUtils} from "./BlockingUtils";
declare const JsonReader: any;
declare const draftbotRandom: Random;
// eslint-disable-next-line max-params
export const giveItemToPlayer = async function(
entity: Entity,
item: Weapon | ObjectItem | Armor | Potion,
language: string,
discordUser: User,
channel: TextChannel,
resaleMultiplierNew = 1,
resaleMultiplierActual = 1
): Promise<void> {
const resaleMultiplier = resaleMultiplierNew;
const tr = Translations.getModule("commands.inventory", language);
await channel.send({ embeds: [
new DraftBotEmbed()
.formatAuthor(tr.get("randomItemTitle"), discordUser)
.setDescription(item instanceof ObjectItem || item instanceof Potion ? item.toString(language, 0) : item.toString(language))
] });
if (await entity.Player.giveItem(item) === true) {
await MissionsController.update(entity.discordUserId, channel, language, "findOrBuyItem");
const entityForMC = (await Entities.getOrRegister(entity.discordUserId))[0];
await MissionsController.update(entityForMC.discordUserId, channel, language, "havePotions", countNbOfPotions(entityForMC.Player), null, true);
await MissionsController.update(entity.discordUserId, channel, language, "haveItemRarity", 1, {
rarity: item.rarity
}, true);
return;
}
const category = item.getCategory();
const maxSlots = entity.Player.InventoryInfo.slotLimitForCategory(category);
let itemToReplace: any;
let autoSell = false;
if (maxSlots === 1) {
itemToReplace = entity.Player.InventorySlots.filter((slot: { isEquipped: () => boolean; itemCategory: any; }) => slot.isEquipped() && slot.itemCategory === category)[0];
autoSell = itemToReplace.itemId === item.id;
}
else if (maxSlots === 2) {
itemToReplace = entity.Player.InventorySlots.filter((slot: { slot: number; itemCategory: any; }) => slot.slot === 1 && slot.itemCategory === category)[0];
autoSell = itemToReplace.itemId === item.id;
}
else {
const items = entity.Player.InventorySlots.filter((slot: { slot: number; itemCategory: any; isEquipped: () => boolean }) => slot.itemCategory === category && !slot.isEquipped());
if (items.length === items.filter((slot: { itemId: any; }) => slot.itemId === item.id).length) {
autoSell = true;
}
else {
const choiceList: ChoiceItem[] = [];
// eslint-disable-next-line @typescript-eslint/no-extra-parens
items.sort((a: any, b: any) => (a.slot > b.slot ? 1 : b.slot > a.slot ? -1 : 0));
for (const item of items) {
choiceList.push(new ChoiceItem(
(await item.getItem()).toString(language, -1),
item
));
}
const choiceMessage = await new DraftBotListChoiceMessage(
choiceList,
discordUser.id,
async (replacedItem: any) => {
[entity] = await Entities.getOrRegister(entity.discordUserId);
BlockingUtils.unblockPlayer(discordUser.id);
await sellOrKeepItem(
entity,
false,
discordUser,
channel,
language,
item,
replacedItem,
await replacedItem.getItem(),
resaleMultiplier,
resaleMultiplierActual,
false
);
},
async (endMessage: DraftBotListChoiceMessage) => {
BlockingUtils.unblockPlayer(discordUser.id);
if (endMessage.isCanceled()) {
await sellOrKeepItem(
entity,
true,
discordUser,
channel,
language,
item,
null,
null,
resaleMultiplier,
resaleMultiplierActual,
false
);
}
}
);
choiceMessage.formatAuthor(
tr.get("chooseItemToReplaceTitle"),
discordUser
);
choiceMessage.send(channel, (collector) => BlockingUtils.blockPlayerWithCollector(discordUser.id, "acceptItem", collector));
return;
}
}
if (autoSell) {
await sellOrKeepItem(
entity,
true,
discordUser,
channel,
language,
item,
null,
null,
resaleMultiplier,
resaleMultiplierActual,
true
);
return;
}
const itemToReplaceInstance = await itemToReplace.getItem();
const validateSell = new DraftBotValidateReactionMessage(
discordUser,
async (msg: DraftBotValidateReactionMessage) => {
[entity] = await Entities.getOrRegister(entity.discordUserId);
BlockingUtils.unblockPlayer(discordUser.id);
await sellOrKeepItem(
entity,
!msg.isValidated(),
discordUser,
channel,
language,
item,
itemToReplace,
itemToReplaceInstance,
resaleMultiplier,
resaleMultiplierActual,
false
);
}
)
.formatAuthor(tr.get(item.getCategory() === Constants.ITEM_CATEGORIES.POTION ? "randomItemFooterPotion" : "randomItemFooter"), discordUser)
.setDescription(tr.format("randomItemDesc", {
actualItem: itemToReplaceInstance.toString(language)
})) as DraftBotValidateReactionMessage;
await validateSell.send(channel, (collector) => BlockingUtils.blockPlayerWithCollector(discordUser.id, "acceptItem", collector));
};
// eslint-disable-next-line max-params
const sellOrKeepItem = async function(
entity: Entity,
keepOriginal: boolean,
discordUser: User,
channel: TextChannel,
language: string,
item: GenericItemModel,
itemToReplace: InventorySlot,
itemToReplaceInstance: GenericItemModel,
resaleMultiplier: number,
resaleMultiplierActual: number,
autoSell: boolean
) {
const tr = Translations.getModule("commands.inventory", language);
entity = await Entities.getById(entity.id);
if (!keepOriginal) {
const menuEmbed = new DraftBotEmbed();
menuEmbed.formatAuthor(tr.get("acceptedTitle"), discordUser)
.setDescription(item instanceof ObjectItem || item instanceof Potion ? item.toString(language, Infinity) : item.toString(language, -1));
await InventorySlot.update(
{
itemId: item.id
},
{
where: {
slot: itemToReplace.slot,
itemCategory: itemToReplace.itemCategory,
playerId: entity.Player.id
}
});
await channel.send({ embeds: [menuEmbed] });
item = itemToReplaceInstance;
resaleMultiplier = resaleMultiplierActual;
}
if (item.getCategory() === Constants.ITEM_CATEGORIES.POTION) {
await channel.send({ embeds: [
new DraftBotEmbed()
.formatAuthor(
autoSell ? JsonReader.commands.sell.getTranslation(language).soldMessageAlreadyOwnTitle
: JsonReader.commands.sell.getTranslation(language).potionDestroyedTitle,
discordUser)
.setDescription(
format(JsonReader.commands.sell.getTranslation(language).potionDestroyedMessage,
{
item: item.getName(language),
frenchMasculine: item.frenchMasculine
}
)
)] }
);
return;
}
const money = Math.round(getItemValue(item) * resaleMultiplier);
await entity.Player.addMoney(entity, money, channel, language);
await MissionsController.update(entity.discordUserId, channel, language, "sellItemWithGivenCost",1,{itemCost: money});
await entity.Player.save();
await channel.send({ embeds: [
new DraftBotEmbed()
.formatAuthor(
autoSell ? JsonReader.commands.sell.getTranslation(language).soldMessageAlreadyOwnTitle
: JsonReader.commands.sell.getTranslation(language).soldMessageTitle,
discordUser)
.setDescription(
format(JsonReader.commands.sell.getTranslation(language).soldMessage,
{
item: item.getName(language),
money: money
}
)
)
] });
await MissionsController.update(entity.discordUserId, channel, language, "findOrBuyItem");
[entity] = await Entities.getOrRegister(entity.discordUserId);
await MissionsController.update(entity.discordUserId, channel, language, "havePotions", countNbOfPotions(entity.Player),null,true);
if (!keepOriginal) {
await MissionsController.update(entity.discordUserId, channel, language, "haveItemRarity", 1, {
rarity: item.rarity
}, true);
}
};
export const getItemValue = function(item: any) {
let addedValue;
const category = item.getCategory();
if (category === Constants.ITEM_CATEGORIES.POTION || category === Constants.ITEM_CATEGORIES.OBJECT) {
addedValue = parseInt(item.power);
}
if (category === Constants.ITEM_CATEGORIES.WEAPON) {
addedValue = parseInt(item.rawAttack);
}
if (category === Constants.ITEM_CATEGORIES.ARMOR) {
addedValue = parseInt(item.rawDefense);
}
return Math.round(parseInt(JsonReader.values.raritiesValues[item.rarity]) + addedValue);
};
export const generateRandomItem = async function(maxRarity = Constants.RARITY.MYTHICAL, itemCategory: number = null, minRarity = Constants.RARITY.COMMON): Promise<any> {
const rarity = generateRandomRarity(minRarity, maxRarity);
if (itemCategory === null) {
itemCategory = generateRandomItemCategory();
}
let itemsIds;
switch (itemCategory) {
case Constants.ITEM_CATEGORIES.WEAPON:
itemsIds = await Weapons.getAllIdsForRarity(rarity);
return await Weapons.getById(itemsIds[draftbotRandom.integer(0, itemsIds.length - 1)].id);
case Constants.ITEM_CATEGORIES.ARMOR:
itemsIds = await Armors.getAllIdsForRarity(rarity);
return await Armors.getById(itemsIds[draftbotRandom.integer(0, itemsIds.length - 1)].id);
case Constants.ITEM_CATEGORIES.POTION:
itemsIds = await Potions.getAllIdsForRarity(rarity);
return await Potions.getById(itemsIds[draftbotRandom.integer(0, itemsIds.length - 1)].id);
case Constants.ITEM_CATEGORIES.OBJECT:
itemsIds = await ObjectItems.getAllIdsForRarity(rarity);
return await ObjectItems.getById(itemsIds[draftbotRandom.integer(0, itemsIds.length - 1)].id);
default:
return null;
}
};
/**
* Generate a random rarity. Legendary is very rare and common is not rare at all
* @param {number} minRarity
* @param {number} maxRarity
* @return {Number} generated rarity
*/
export const generateRandomRarity = function(minRarity = Constants.RARITY.COMMON, maxRarity = Constants.RARITY.MYTHICAL): number {
const randomValue = draftbotRandom.integer(
1 + (minRarity === Constants.RARITY.COMMON ? -1 : parseInt(JsonReader.values.raritiesGenerator[minRarity - 2],10)),
parseInt(JsonReader.values.raritiesGenerator.maxValue,10)
- (maxRarity === Constants.RARITY.MYTHICAL ? 0 : parseInt(JsonReader.values.raritiesGenerator.maxValue,10)
- parseInt(JsonReader.values.raritiesGenerator[maxRarity - 1],10))
);
if (randomValue <= JsonReader.values.raritiesGenerator["0"]) {
return Constants.RARITY.COMMON;
}
else if (randomValue <= JsonReader.values.raritiesGenerator["1"]) {
return Constants.RARITY.UNCOMMON;
}
else if (randomValue <= JsonReader.values.raritiesGenerator["2"]) {
return Constants.RARITY.EXOTIC;
}
else if (randomValue <= JsonReader.values.raritiesGenerator["3"]) {
return Constants.RARITY.RARE;
}
else if (randomValue <= JsonReader.values.raritiesGenerator["4"]) {
return Constants.RARITY.SPECIAL;
}
else if (randomValue <= JsonReader.values.raritiesGenerator["5"]) {
return Constants.RARITY.EPIC;
}
else if (randomValue <= JsonReader.values.raritiesGenerator["6"]) {
return Constants.RARITY.LEGENDARY;
}
return Constants.RARITY.MYTHICAL;
};
/**
* Generate a random itemType
* @return {Number}
*/
export const generateRandomItemCategory = function() {
return draftbotRandom.pick(Object.values(Constants.ITEM_CATEGORIES));
};
/**
* Generate a random potion
* @param {number} maxRarity
* @param {number} potionType
* @returns {Potions} generated potion
*/
export const generateRandomPotion = async function(potionType: number = null, maxRarity = Constants.RARITY.MYTHICAL) {
if (potionType === null) {
return this.generateRandomItem(maxRarity, Constants.ITEM_CATEGORIES.POTION);
}
const rarity = generateRandomRarity(Constants.RARITY.COMMON, maxRarity);
return await Potions.randomItem(potionType, rarity);
};
/**
* Generate a random object
* @param {number} maxRarity
* @param {number} objectType
* @param minRarity
* @returns {ObjectItem} generated object
*/
export const generateRandomObject = async function(objectType: number = null, minRarity = Constants.RARITY.COMMON, maxRarity = Constants.RARITY.MYTHICAL) {
if (objectType === null) {
return this.generateRandomItem(minRarity, maxRarity, Constants.ITEM_CATEGORIES.OBJECT);
}
const rarity = generateRandomRarity(minRarity, maxRarity);
return await ObjectItems.randomItem(objectType, rarity);
};
/**
* give a random item
* @param {User} discordUser
* @param {TextChannel} channel
* @param {("fr"|"en")} language - Language to use in the response
* @param {Entities} entity
*/
export const giveRandomItem = async function(discordUser: User, channel: TextChannel, language: string, entity: any) {
const item = await generateRandomItem();
return await giveItemToPlayer(entity, item, language, discordUser, channel);
};
/**
* Sort an item slots list by type then price
* @param items
*/
export const sortPlayerItemList = async function(items: any[]): Promise<any[]> {
let itemInstances = await Promise.all(items.map(async function(e) {
return [e, await e.getItem()];
}));
itemInstances = itemInstances.sort(
(a: any, b: any) => {
if (a[0].itemCategory < b[0].itemCategory) {
return -1;
}
if (a[0].itemCategory > b[0].itemCategory) {
return 1;
}
const aValue = getItemValue(a[1]);
const bValue = getItemValue(b[1]);
if (aValue > bValue) {
return -1;
}
else if (aValue < bValue) {
return 1;
}
return 0;
}
);
return itemInstances.map(function(e) {
return e[0];
});
};
export const haveRarityOrMore = async function(slots: InventorySlot[], rarity: number): Promise<boolean> {
for (const slot of slots) {
if ((await slot.getItem()).rarity >= rarity) {
return true;
}
}
return false;
};
export const countNbOfPotions = function(player: Player): number {
let nbPotions = player.getMainPotionSlot().itemId === 0 ? -1 : 0;
for (const slot of player.InventorySlots) {
nbPotions += slot.isPotion() ? 1 : 0;
}
return nbPotions;
}; | the_stack |
import { expect } from "chai";
import * as dfapi from "df/api";
import * as dbadapters from "df/api/dbadapters";
import { Sql } from "df/sql";
import { build, ISelectOrBuilder, ISelectSchema } from "df/sql/builders/select";
import { suite, test } from "df/testing";
suite("builders", { parallel: true }, ({ before, after }) => {
let bigquery: dbadapters.IDbAdapter;
let snowflake: dbadapters.IDbAdapter;
let redshift: dbadapters.IDbAdapter;
before("create bigquery", async () => {
bigquery = await dbadapters.create(
{ ...dfapi.credentials.read("bigquery", "test_credentials/bigquery.json"), location: "EU" },
"bigquery"
);
});
after("close bigquery", () => bigquery.close());
before("create snowflake", async () => {
snowflake = await dbadapters.create(
dfapi.credentials.read("snowflake", "test_credentials/snowflake.json"),
"snowflake"
);
});
after("close snowflake", () => snowflake.close());
before("create redshift", async () => {
redshift = await dbadapters.create(
dfapi.credentials.read("redshift", "test_credentials/redshift.json"),
"redshift"
);
});
after("close redshift", () => redshift.close());
for (const { name, dbadapter, sql } of [
{ name: "bigquery", dbadapter: () => bigquery, sql: new Sql("standard") },
{ name: "snowflake", dbadapter: () => snowflake, sql: new Sql("snowflake") }
]) {
suite(name, { parallel: true }, () => {
const execute = async <S extends ISelectSchema>(select: ISelectOrBuilder<S>) => {
const query = build(select).query;
try {
const rows = (await dbadapter().execute(query)).rows as S[];
// Snowflake upper cases column names. Turn them back to lowercase for easier testing.
return rows.map(row =>
Object.keys(row).reduce(
(acc, key) => ({ ...acc, [String(key).toLowerCase()]: row[key] }),
{}
)
);
} catch (e) {
throw new Error(`Error during query: ${e}\n${query}`);
}
};
test("timestamps", async () => {
const rows = [
{
millis: 1591786375000,
truncated_millis: 1591747200000
}
];
const query = sql.from(sql.json(rows)).select({
millis: sql.timestamps.toMillis(sql.asTimestamp(sql.timestamps.fromMillis("millis"))),
truncated_millis: sql.timestamps.toMillis(
sql.timestamps.truncate(sql.asTimestamp(sql.timestamps.fromMillis("millis")), "day")
)
});
const result = await execute(query);
expect(result).deep.equals(rows);
});
test("conditionals", async () => {
const rows = [
{
v: "a"
},
{
v: "b"
}
];
const query = sql.from(sql.json(rows)).select({
ifac: sql.conditional(sql.in("v", [sql.literal("a")]), sql.literal("c"), "v"),
ifbd: sql.conditional(sql.equals("v", sql.literal("b")), sql.literal("d"), "v")
});
const result = await execute(query);
expect(result).deep.equals([
{
ifac: "c",
ifbd: "a"
},
{
ifac: "b",
ifbd: "d"
}
]);
});
test("safe divide", async () => {
const rows = [
{
a: 4,
b: 2
},
{
a: 4,
b: 0
}
];
const query = sql.from(sql.json(rows)).select({
v: sql.safeDivide("a", "b")
});
const result = await execute(query);
expect(result).deep.equals([
{
v: 2
},
{
v: null
}
]);
});
test("safe divide", async () => {
const rows = [
{
a: 4,
b: 2
},
{
a: 4,
b: 0
}
];
const query = sql.from(sql.json(rows)).select({
v: sql.safeDivide("a", "b")
});
const result = await execute(query);
expect(result).deep.equals([
{
v: 2
},
{
v: null
}
]);
});
test("as string", async () => {
const rows = [
{
a: 1,
b: "b"
}
];
const query = sql.from(sql.json(rows)).select({
a: sql.asString("a"),
b: sql.asString("b")
});
const result = await execute(query);
expect(result).deep.equals([
{
a: "1",
b: "b"
}
]);
});
test("surrogate key", async () => {
const rows = [
{
a: 1,
b: "b"
},
{
a: 2,
b: "c"
}
];
const query = sql.from(sql.json(rows)).select({
key: sql.surrogateKey(["a", "b"])
});
const result: any = await execute(query);
expect(result.length).equals(2);
expect(result[0].key).not.equals(result[1].key);
});
test("window function", async () => {
const rows = [
{
key: 1,
sort: 1,
value: 1,
partition_field: "a"
},
{
key: 2,
sort: 2,
value: 1,
partition_field: "a"
},
{
key: 3,
sort: 3,
value: null,
partition_field: "b"
},
{
key: 4,
sort: 4,
value: 1,
partition_field: "b"
}
];
const query = sql.from(sql.json(rows)).select({
lag: sql.windowFunction("lag", "value", false, { orderFields: ["key"] }),
max: sql.windowFunction("max", "value", false, { partitionFields: ["partition_field"] }),
first_value: sql.windowFunction("first_value", "value", true, {
partitionFields: ["partition_field"],
orderFields: ["sort"]
})
});
const result: any = await execute(query);
expect(result.length).equals(4);
expect(result[1].lag).equals(1);
expect(result[0].max).equals(1);
expect(result[0].first_value).equals(1);
});
// skipping this test for redshift as the function is only supported on user-defined-tables
// i.e. not when just querying a select statement with no table
if (name !== "redshift") {
test("string agg", async () => {
const rows = [
{
a: "foo"
},
{
a: "bar"
}
];
const query = sql.from(sql.json(rows)).select({
agg: sql.stringAgg("a"),
agg_hyphen: sql.stringAgg("a", "-")
});
const result: any = await execute(query);
expect(result.length).equals(1);
expect(result[0]).deep.equals({
agg: "foo,bar",
agg_hyphen: "foo-bar"
});
});
}
test("timestamp diff", async () => {
const rows = [
{
millis: 1604575623426,
previous_day: 1604489223426,
previous_hour: 1604572023426,
previous_minute: 1604575563426,
previous_second: 1604575622426,
previous_millisecond: 1604575623425
}
];
const query = sql.from(sql.json(rows)).select({
day: sql.timestamps.diff(
"day",
sql.timestamps.fromMillis("previous_day"),
sql.timestamps.fromMillis("millis")
),
hour: sql.timestamps.diff(
"hour",
sql.timestamps.fromMillis("previous_hour"),
sql.timestamps.fromMillis("millis")
),
minute: sql.timestamps.diff(
"minute",
sql.timestamps.fromMillis("previous_minute"),
sql.timestamps.fromMillis("millis")
),
second: sql.timestamps.diff(
"second",
sql.timestamps.fromMillis("previous_second"),
sql.timestamps.fromMillis("millis")
),
millisecond: sql.timestamps.diff(
"millisecond",
sql.timestamps.fromMillis("previous_millisecond"),
sql.timestamps.fromMillis("millis")
)
});
const result: any = await execute(query);
expect(result[0]).deep.equals({
day: 1,
hour: 1,
minute: 1,
second: 1,
millisecond: 1
});
});
test("timestamp add", async () => {
const rows = [
{
previous_day: 1604489223000,
previous_hour: 1604572023000,
previous_minute: 1604575563000,
previous_second: 1604575622000
}
];
const query = sql.from(sql.json(rows)).select({
day: sql.timestamps.toMillis(
sql.timestamps.add(sql.timestamps.fromMillis("previous_day"), 1, "day")
),
hour: sql.timestamps.toMillis(
sql.timestamps.add(sql.timestamps.fromMillis("previous_hour"), 1, "hour")
),
minute: sql.timestamps.toMillis(
sql.timestamps.add(sql.timestamps.fromMillis("previous_minute"), 1, "minute")
),
second: sql.timestamps.toMillis(
sql.timestamps.add(sql.timestamps.fromMillis("previous_second"), 1, "second")
)
});
const result: any = await execute(query);
expect(result[0]).deep.equals({
day: 1604575623000,
hour: 1604575623000,
minute: 1604575623000,
second: 1604575623000
});
});
test("json", async () => {
const rows = [
{
d: "1",
m: 1
},
{
d: "2",
m: 2
}
];
const selectJson = sql.json(rows);
const result = await execute(selectJson);
expect(result).deep.equals(rows);
});
test("aggregate", async () => {
const source = sql.json([
{
d: "1",
m: 1
},
{
d: "2",
m: 2
},
{
d: "2",
m: 2
}
]);
const select = sql
.aggregate(source)
.dimensions({
d: "d"
})
.metrics({
m: sql.sum("m")
})
.ordering({
expression: "m",
descending: true
});
const result = await execute(select);
expect(result).deep.equals([
{
d: "2",
m: 4
},
{
d: "1",
m: 1
}
]);
});
test("union", async () => {
const union = sql.union(
sql.json([
{
v: "a"
}
]),
sql.json([
{
v: "b"
}
])
);
const result = await execute(union);
expect(result).deep.equals([
{
v: "a"
},
{
v: "b"
}
]);
});
test("join", async () => {
const sourceA = sql.json([
{
v1: "a"
}
]);
const sourceB = sql.json([
{
v2: "a"
}
]);
const join = sql.from(
sql.join({
a: {
select: sourceA,
type: "base"
},
b: {
select: sourceB,
type: "left",
on: ["v1", "v2"]
}
})
);
const result = await execute(join);
expect(result).deep.equals([
{
v1: "a",
v2: "a"
}
]);
});
test("with", async () => {
const source = sql.json([
{
v: "a"
}
]);
const select = sql
.with({
renamed: source
})
.select(sql.from("renamed").select({ v: "v" }));
const result = await execute(select);
expect(result).deep.equals([
{
v: "a"
}
]);
});
test("combination", async () => {
const source = sql.json([
{
d1: "a",
d2: "c",
m1: 1,
m2: 2
},
{
d1: "b",
d2: "c",
m1: 2,
m2: 2
}
]);
const aggregate = sql
.with({
filtered: sql.from(source).where(sql.equals("d2", sql.literal("c"))),
top_values: sql
.aggregate("filtered")
.dimensions({
d1t: "d1"
})
.metrics({
m1t: sql.sum("m1")
})
.ordering({
expression: "m1t",
descending: true
})
.limit(1)
})
.select(
sql.union(
sql
.aggregate(
sql.join({
top_values: {
select: "top_values",
type: "base"
},
vals: {
select: "filtered",
type: "right",
on: ["d1t", "d1"]
}
})
)
.dimensions({
d1: "d1t"
})
.metrics({
m1: sql.sum("m1")
}),
sql
.aggregate("filtered")
.dimensions({
d1: sql.literal("d")
})
.metrics({
m1: sql.sum("m1")
})
)
);
const result = await execute(aggregate);
expect(result).deep.members([
{
d1: "b",
m1: 2
},
{
d1: null,
m1: 1
},
{
d1: "d",
m1: 3
}
]);
});
});
}
}); | the_stack |
import type {Mutable, Proto, ObserverType} from "@swim/util";
import type {FastenerOwner, FastenerFlags} from "@swim/component";
import type {AnyModel, Model} from "./Model";
import {ModelRelationInit, ModelRelationClass, ModelRelation} from "./ModelRelation";
/** @internal */
export type ModelSetType<F extends ModelSet<any, any>> =
F extends ModelSet<any, infer M> ? M : never;
/** @public */
export interface ModelSetInit<M extends Model = Model> extends ModelRelationInit<M> {
extends?: {prototype: ModelSet<any, any>} | string | boolean | null;
key?(model: M): string | undefined;
compare?(a: M, b: M): number;
sorted?: boolean;
willSort?(parent: Model | null): void;
didSort?(parent: Model | null): void;
sortChildren?(parent: Model): void;
compareChildren?(a: Model, b: Model): number;
}
/** @public */
export type ModelSetDescriptor<O = unknown, M extends Model = Model, I = {}> = ThisType<ModelSet<O, M> & I> & ModelSetInit<M> & Partial<I>;
/** @public */
export interface ModelSetClass<F extends ModelSet<any, any> = ModelSet<any, any>> extends ModelRelationClass<F> {
/** @internal */
readonly SortedFlag: FastenerFlags;
/** @internal @override */
readonly FlagShift: number;
/** @internal @override */
readonly FlagMask: FastenerFlags;
}
/** @public */
export interface ModelSetFactory<F extends ModelSet<any, any> = ModelSet<any, any>> extends ModelSetClass<F> {
extend<I = {}>(className: string, classMembers?: Partial<I> | null): ModelSetFactory<F> & I;
define<O, M extends Model = Model>(className: string, descriptor: ModelSetDescriptor<O, M>): ModelSetFactory<ModelSet<any, M>>;
define<O, M extends Model = Model>(className: string, descriptor: {observes: boolean} & ModelSetDescriptor<O, M, ObserverType<M>>): ModelSetFactory<ModelSet<any, M>>;
define<O, M extends Model = Model, I = {}>(className: string, descriptor: {implements: unknown} & ModelSetDescriptor<O, M, I>): ModelSetFactory<ModelSet<any, M> & I>;
define<O, M extends Model = Model, I = {}>(className: string, descriptor: {implements: unknown; observes: boolean} & ModelSetDescriptor<O, M, I & ObserverType<M>>): ModelSetFactory<ModelSet<any, M> & I>;
<O, M extends Model = Model>(descriptor: ModelSetDescriptor<O, M>): PropertyDecorator;
<O, M extends Model = Model>(descriptor: {observes: boolean} & ModelSetDescriptor<O, M, ObserverType<M>>): PropertyDecorator;
<O, M extends Model = Model, I = {}>(descriptor: {implements: unknown} & ModelSetDescriptor<O, M, I>): PropertyDecorator;
<O, M extends Model = Model, I = {}>(descriptor: {implements: unknown; observes: boolean} & ModelSetDescriptor<O, M, I & ObserverType<M>>): PropertyDecorator;
}
/** @public */
export interface ModelSet<O = unknown, M extends Model = Model> extends ModelRelation<O, M> {
(model: AnyModel<M>): O;
/** @override */
get fastenerType(): Proto<ModelSet<any, any>>;
/** @internal */
readonly models: {readonly [modelId: number]: M | undefined};
readonly modelCount: number;
hasModel(model: Model): boolean;
addModel(model?: AnyModel<M>, target?: Model | null, key?: string): M;
attachModel(model?: AnyModel<M>, target?: Model | null): M;
detachModel(model: M): M | null;
insertModel(parent?: Model | null, model?: AnyModel<M>, target?: Model | null, key?: string): M;
removeModel(model: M): M | null;
deleteModel(model: M): M | null;
/** @internal @override */
bindModel(model: Model, target: Model | null): void;
/** @internal @override */
unbindModel(model: Model): void;
/** @override */
detectModel(model: Model): M | null;
/** @internal @protected */
key(model: M): string | undefined;
get sorted(): boolean;
/** @internal */
initSorted(sorted: boolean): void;
sort(sorted?: boolean): this;
/** @protected */
willSort(parent: Model | null): void;
/** @protected */
onSort(parent: Model | null): void;
/** @protected */
didSort(parent: Model | null): void;
/** @internal @protected */
sortChildren(parent: Model): void;
/** @internal */
compareChildren(a: Model, b: Model): number;
/** @internal @protected */
compare(a: M, b: M): number;
}
/** @public */
export const ModelSet = (function (_super: typeof ModelRelation) {
const ModelSet: ModelSetFactory = _super.extend("ModelSet");
Object.defineProperty(ModelSet.prototype, "fastenerType", {
get: function (this: ModelSet): Proto<ModelSet<any, any>> {
return ModelSet;
},
configurable: true,
});
ModelSet.prototype.hasModel = function (this: ModelSet, model: Model): boolean {
return this.models[model.uid] !== void 0;
};
ModelSet.prototype.addModel = function <M extends Model>(this: ModelSet<unknown, M>, newModel?: AnyModel<M>, target?: Model | null, key?: string): M {
if (newModel !== void 0 && newModel !== null) {
newModel = this.fromAny(newModel);
} else {
newModel = this.createModel();
}
if (target === void 0) {
target = null;
}
let parent: Model | null;
if (this.binds && (parent = this.parentModel, parent !== null)) {
if (key === void 0) {
key = this.key(newModel);
}
this.insertChild(parent, newModel, target, key);
}
const models = this.models as {[modelId: number]: M | undefined};
if (models[newModel.uid] === void 0) {
this.willAttachModel(newModel, target);
models[newModel.uid] = newModel;
(this as Mutable<typeof this>).modelCount += 1;
this.onAttachModel(newModel, target);
this.initModel(newModel);
this.didAttachModel(newModel, target);
}
return newModel;
};
ModelSet.prototype.attachModel = function <M extends Model>(this: ModelSet<unknown, M>, newModel?: AnyModel<M>, target?: Model | null): M {
if (newModel !== void 0 && newModel !== null) {
newModel = this.fromAny(newModel);
} else {
newModel = this.createModel();
}
const models = this.models as {[modelId: number]: M | undefined};
if (models[newModel.uid] === void 0) {
if (target === void 0) {
target = null;
}
this.willAttachModel(newModel, target);
models[newModel.uid] = newModel;
(this as Mutable<typeof this>).modelCount += 1;
this.onAttachModel(newModel, target);
this.initModel(newModel);
this.didAttachModel(newModel, target);
}
return newModel;
};
ModelSet.prototype.detachModel = function <M extends Model>(this: ModelSet<unknown, M>, oldModel: M): M | null {
const models = this.models as {[modelId: number]: M | undefined};
if (models[oldModel.uid] !== void 0) {
this.willDetachModel(oldModel);
(this as Mutable<typeof this>).modelCount -= 1;
delete models[oldModel.uid];
this.onDetachModel(oldModel);
this.deinitModel(oldModel);
this.didDetachModel(oldModel);
return oldModel;
}
return null;
};
ModelSet.prototype.insertModel = function <M extends Model>(this: ModelSet<unknown, M>, parent?: Model | null, newModel?: AnyModel<M>, target?: Model | null, key?: string): M {
if (newModel !== void 0 && newModel !== null) {
newModel = this.fromAny(newModel);
} else {
newModel = this.createModel();
}
if (parent === void 0 || parent === null) {
parent = this.parentModel;
}
if (target === void 0) {
target = null;
}
if (key === void 0) {
key = this.key(newModel);
}
if (parent !== null && (newModel.parent !== parent || newModel.key !== key)) {
this.insertChild(parent, newModel, target, key);
}
const models = this.models as {[modelId: number]: M | undefined};
if (models[newModel.uid] === void 0) {
this.willAttachModel(newModel, target);
models[newModel.uid] = newModel;
(this as Mutable<typeof this>).modelCount += 1;
this.onAttachModel(newModel, target);
this.initModel(newModel);
this.didAttachModel(newModel, target);
}
return newModel;
};
ModelSet.prototype.removeModel = function <M extends Model>(this: ModelSet<unknown, M>, model: M): M | null {
if (this.hasModel(model)) {
model.remove();
return model;
}
return null;
};
ModelSet.prototype.deleteModel = function <M extends Model>(this: ModelSet<unknown, M>, model: M): M | null {
const oldModel = this.detachModel(model);
if (oldModel !== null) {
oldModel.remove();
}
return oldModel;
};
ModelSet.prototype.bindModel = function <M extends Model>(this: ModelSet<unknown, M>, model: Model, target: Model | null): void {
if (this.binds) {
const newModel = this.detectModel(model);
const models = this.models as {[modelId: number]: M | undefined};
if (newModel !== null && models[newModel.uid] === void 0) {
this.willAttachModel(newModel, target);
models[newModel.uid] = newModel;
(this as Mutable<typeof this>).modelCount += 1;
this.onAttachModel(newModel, target);
this.initModel(newModel);
this.didAttachModel(newModel, target);
}
}
};
ModelSet.prototype.unbindModel = function <M extends Model>(this: ModelSet<unknown, M>, model: Model): void {
if (this.binds) {
const oldModel = this.detectModel(model);
const models = this.models as {[modelId: number]: M | undefined};
if (oldModel !== null && models[oldModel.uid] !== void 0) {
this.willDetachModel(oldModel);
(this as Mutable<typeof this>).modelCount -= 1;
delete models[oldModel.uid];
this.onDetachModel(oldModel);
this.deinitModel(oldModel);
this.didDetachModel(oldModel);
}
}
};
ModelSet.prototype.detectModel = function <M extends Model>(this: ModelSet<unknown, M>, model: Model): M | null {
if (typeof this.type === "function" && model instanceof this.type) {
return model as M;
}
return null;
};
ModelSet.prototype.key = function <M extends Model>(this: ModelSet<unknown, M>, model: M): string | undefined {
return void 0;
};
Object.defineProperty(ModelSet.prototype, "sorted", {
get(this: ModelSet): boolean {
return (this.flags & ModelSet.SortedFlag) !== 0;
},
configurable: true,
});
ModelSet.prototype.initInherits = function (this: ModelSet, sorted: boolean): void {
if (sorted) {
(this as Mutable<typeof this>).flags = this.flags | ModelSet.SortedFlag;
} else {
(this as Mutable<typeof this>).flags = this.flags & ~ModelSet.SortedFlag;
}
};
ModelSet.prototype.sort = function (this: ModelSet, sorted?: boolean): typeof this {
if (sorted === void 0) {
sorted = true;
}
const flags = this.flags;
if (sorted && (flags & ModelSet.SortedFlag) === 0) {
const parent = this.parentModel;
this.willSort(parent);
this.setFlags(flags | ModelSet.SortedFlag);
this.onSort(parent);
this.didSort(parent);
} else if (!sorted && (flags & ModelSet.SortedFlag) !== 0) {
this.setFlags(flags & ~ModelSet.SortedFlag);
}
return this;
};
ModelSet.prototype.willSort = function (this: ModelSet, parent: Model | null): void {
// hook
};
ModelSet.prototype.onSort = function (this: ModelSet, parent: Model | null): void {
if (parent !== null) {
this.sortChildren(parent);
}
};
ModelSet.prototype.didSort = function (this: ModelSet, parent: Model | null): void {
// hook
};
ModelSet.prototype.sortChildren = function <M extends Model>(this: ModelSet<unknown, M>, parent: Model): void {
parent.sortChildren(this.compareChildren.bind(this));
};
ModelSet.prototype.compareChildren = function <M extends Model>(this: ModelSet<unknown, M>, a: Model, b: Model): number {
const models = this.models;
const x = models[a.uid];
const y = models[b.uid];
if (x !== void 0 && y !== void 0) {
return this.compare(x, y);
} else {
return x !== void 0 ? 1 : y !== void 0 ? -1 : 0;
}
};
ModelSet.prototype.compare = function <M extends Model>(this: ModelSet<unknown, M>, a: M, b: M): number {
return a.uid < b.uid ? -1 : a.uid > b.uid ? 1 : 0;
};
ModelSet.construct = function <F extends ModelSet<any, any>>(fastenerClass: {prototype: F}, fastener: F | null, owner: FastenerOwner<F>): F {
if (fastener === null) {
fastener = function (newModel: AnyModel<ModelSetType<F>>): FastenerOwner<F> {
fastener!.addModel(newModel);
return fastener!.owner;
} as F;
delete (fastener as Partial<Mutable<F>>).name; // don't clobber prototype name
Object.setPrototypeOf(fastener, fastenerClass.prototype);
}
fastener = _super.construct(fastenerClass, fastener, owner) as F;
(fastener as Mutable<typeof fastener>).models = {};
(fastener as Mutable<typeof fastener>).modelCount = 0;
return fastener;
};
ModelSet.define = function <O, M extends Model>(className: string, descriptor: ModelSetDescriptor<O, M>): ModelSetFactory<ModelSet<any, M>> {
let superClass = descriptor.extends as ModelSetFactory | null | undefined;
const affinity = descriptor.affinity;
const inherits = descriptor.inherits;
const sorted = descriptor.sorted;
delete descriptor.extends;
delete descriptor.implements;
delete descriptor.affinity;
delete descriptor.inherits;
delete descriptor.sorted;
if (superClass === void 0 || superClass === null) {
superClass = this;
}
const fastenerClass = superClass.extend(className, descriptor);
fastenerClass.construct = function (fastenerClass: {prototype: ModelSet<any, any>}, fastener: ModelSet<O, M> | null, owner: O): ModelSet<O, M> {
fastener = superClass!.construct(fastenerClass, fastener, owner);
if (affinity !== void 0) {
fastener.initAffinity(affinity);
}
if (inherits !== void 0) {
fastener.initInherits(inherits);
}
if (sorted !== void 0) {
fastener.initSorted(sorted);
}
return fastener;
};
return fastenerClass;
};
(ModelSet as Mutable<typeof ModelSet>).SortedFlag = 1 << (_super.FlagShift + 0);
(ModelSet as Mutable<typeof ModelSet>).FlagShift = _super.FlagShift + 1;
(ModelSet as Mutable<typeof ModelSet>).FlagMask = (1 << ModelSet.FlagShift) - 1;
return ModelSet;
})(ModelRelation); | the_stack |
import { TimeEntity } from '../../utils/entity-utils';
import BaseTokenizer from './base';
import { WS, makeToken } from './helpers';
// This tokenizer is inspired by the PTBTokenizer in CoreNLP, and it is somewhat
// compatible with it.
//
// Important differences:
// - parenthesis, dashes and quotes are not transformed
// - hyphens are never split (no clever heuristics)
// - fractions are not recognized, and / are always split unless recognized as a filename
// - assimilations (cannot, don't) are not split
// - measurements without space ("5gb") are split (unless recognized as a time or postcode)
// - legacy processing needed for old datasets is not applied
// - no Americanization (colour -> color, € -> $)
// - whitespace is defined as per Unicode standard
// - handling of quoted strings, filenames, URLs, phone numbers and emails according to our rules
// - casing of quoted strings, filenames, URLs etc. is preserved
//
// NO CODE WAS COPIED FROM CORENLP
const NUMBERS : Record<string, number> = {
zero: 0,
zeroth: 0,
zeroeth: 0,
a: 1, // as in "a hundred"
one: 1,
first: 1,
two: 2,
second: 2,
three: 3,
third: 3,
four: 4,
// fourth not forth, despite the famous joke:
// And The Lord said unto John, "Come forth and receive eternal life"
// but John came fifth and won a toaster.
fourth: 4,
five: 5,
fifth: 5,
six: 6,
sixth: 6,
seven: 7,
seventh: 7,
eight: 8,
eighth: 8,
nine: 9,
ninth: 9,
ten: 10,
tenth: 10,
eleven: 11,
eleventh: 11,
twelve: 12,
twelfth: 13,
thirteen: 13,
thirteenth: 13,
fourteen: 14,
fourteeenth: 14,
fifteen: 15,
fifteenth: 15,
sixteen: 16,
sixteenth: 16,
seventeen: 17,
seventeenth: 17,
eighteen: 18,
eighteenth: 18,
nineteen: 19,
nineteenth: 19,
twenty: 20,
twentieth: 20,
thirty: 30,
thirtieth: 30,
forty: 40,
fourty: 40, // "fourty" is a typo, but a common one
fortieth: 40,
fifty: 50,
fiftieth: 50,
sixty: 60,
sixtieth: 60,
seventy: 70,
seventieth: 70,
eighty: 80,
eightieth: 80,
ninety: 90,
ninetieth: 90
};
// NOTE: this uses the American convention for interpreting billions
const MULTIPLIERS : Record<string, number> = {
hundred: 100,
hundreds: 100,
hundredth: 100,
thousand: 1000,
thousands: 1000,
thousandth: 1000,
million: 1e6,
millions: 1e6,
millionth: 1e6,
billion: 1e9,
billions: 1e9,
billionth: 1e9,
trillion: 1e12,
trillions: 1e12,
trillionth: 1e12,
quadrillion: 1e15,
quadrillions: 1e15,
quadrillionth: 1e15,
};
const MONTHS : Record<string, number> = {
jan: 1,
feb: 2,
mar: 3,
apr: 4,
may: 5,
jun: 6,
jul: 7,
aug: 8,
sep: 9,
oct: 10,
nov: 11,
dec: 12
};
const CURRENCIES : Record<string, string> = {
'dollars': 'usd',
'dollar': 'usd',
'bucks': 'usd',
'buck': 'usd',
'cents': '0.01usd',
'pounds': 'gbp',
'pound': 'gbp',
'pence': '0.01gbp',
'penny': '0.01gbp',
'yen': 'jpy',
'euros': 'eur',
'euro': 'eur',
'won': 'krw',
'yuan': 'cny',
'$': 'usd',
'C$': 'cad',
'A$': 'aud',
'£': 'gbp',
'€': 'eur',
'₩': 'krw',
// this is ambiguous, could be jpy or cny
'¥': 'jpy',
};
export default class EnglishTokenizer extends BaseTokenizer {
protected _initAbbrv() {
// words with apostrophes
this._addDefinition('APWORD', /(?:[a-z]+?n['’]t(?!{LETTER}))|o['’]clock(?!{LETTER})|o['’](?={WS}clock(?!{LETTER}))|['’]{LETTER}+/);
// note: this is not meant to be a comprehensive list
// if some abbreviation is added here, the period will become part of the abbreviation token
// if not, the period will become a token of its own
// there is really no hard rule of what should or should not be listed here
// but:
// - if it was in CoreNLP it probably should be here (for compat with existing string sets)
// - if the period is in the middle of a token (e.g. "e.g."), then it should be here
// pro of adding more abbrevations:
// - token-level handling (augmentation etc.) will be more accurate
// - we'll have fewer tokens with one/two letters
// - truecasing will not accidentally capitalize the word after the abbreviation
// con of adding more abbreviations:
// - it might not match the pretraining of BERT models (but it won't affect RoBERTa because it uses SentencePiece)
// - it will require more variants in the string sets
// - it will never be complete
// common abbreviations
this._addDefinition('ABBRV_STATE', /(?:ala|ariz|ark|calif|colo|conn|dak|del|fla|ill|kans?|mass|mich|minn|miss|mont|nev|okla|ore|penn|tenn|tex|wash|wisc?|wyo)\./);
this._addDefinition('ABBRV_COMPANY', /(?:inc|corp|ltd|univ|intl)\./);
this._addDefinition('ABBRV_TITLE', /ph\.d|ed\.d|esq\.|jr\.|sr\.|prof\.|dr\.|mr\.|ms\.|mrs\./);
this._addDefinition('ABBRV_LOCATION', /(?:st|ave|blvd|cyn|dr|ln|rd|apt|dept|tel|post)\./);
// (single letter followed by ".") potentially repeated
// this covers acronyms spelled with ".", and covers people's initials
// there is no ambiguity because the only single letter words in English are "a" and "i" and they cannot be at the end of a sentence
//
// (colloquial ambiguity could arise from "u" to mean "you", as "i love u." - we'll live with that)
this._addDefinition('INITIALISM', /(?:{LETTER}\.)+/);
// list from CoreNLP and from https://abbreviations.yourdictionary.com/articles/list-of-commonly-used-abbreviations.html
// "etc.", "incl.", "eg.", "wrt.", "ie.", "vs.", "misc.", "dept.", "appt.", "approx.", "est."
// note that "e.g." and "i.e." are covered by the initialism rule above
this._addDefinition('ABBRV_OTH', /(?:etc|incl|eg|wrt|ie|vs|misc|dept|appt|approx|est)\./);
this._addDefinition('ABBRV_SPECIAL', /c\/o(?!{LETTER})/);
this._lexer.addRule(/{ABBRV_STATE}|{ABBRV_COMPANY}|{ABBRV_TITLE}|{ABBRV_LOCATION}|{ABBRV_OTH}|{ABBRV_SPECIAL}|{INITIALISM}/,
(lexer) => makeToken(lexer.index, lexer.text, lexer.text.toLowerCase().replace(/’/g, "'")));
}
private _parseWordNumber(text : string) {
// note: this function will parse a bunch of things that are not valid, such a mixed ordinal and cardinal numbers
// this is ok because we only call it with good stuff
// the basic operation of this function is fairly simple:
// - you have additive numbers (one to nine, and ten, twenty, etc. to ninety)
// - you have multipliers (thousand, million, billion, and up)
// - numbers in between multipliers are added
// - multipliers take the current number, multiply it and add it to the total
//
// the special case is "hundred": it multiplies the current number and doesn't add to the total
// because it can be followed by another multiplier
// "value" is the total number, "current" is a single piece before a multiplier ("thousand", "billion", etc.)
let value = 0;
let current = 0;
// examples:
//
// "three hundred millions" (3e11)
// - "three" -> value = 0, current = 3
// - "hundred" -> value = 0, current = 300
// - "millions" -> value = 3e11, current = 0
//
// "three hundred twenty two thousands four hundred and five" (322405)
// - "three" -> value = 0, current = 3
// - "hundred" -> value = 0, current = 300
// - "twenty" -> value = 0, current = 320
// - "two" -> value = 0, current = 322
// - "thousands" -> value = 322000, current = 0
// - "four" -> value = 322000, current = 4
// - "hundred" -> value = 322000, current = 400
// - "five" -> value = 322000, current = 405
// final value is 322405
// split on "and", "-", and whitespace
const parts = text.toLowerCase().split(/[ \t\n\r\v\u180e\u2000-\u200b\u202f\u205f\u3000\ufeff-]+(?:and[ \t\n\r\v\u180e\u2000-\u200b\u202f\u205f\u3000\ufeff]+)*/g);
for (const part of parts) {
if (part in MULTIPLIERS) {
const multiplier = MULTIPLIERS[part];
if (current === 0)
current = 1;
if (multiplier === 100) {
current *= 100;
} else {
value += current * multiplier;
current = 0;
}
} else if (part in NUMBERS) {
current += NUMBERS[part];
} else {
current += this._parseDecimalNumber(part);
}
}
value += current;
return value;
}
protected _initSpecialNumbers() {
this._lexer.addRule(/911/, (lexer) => makeToken(lexer.index, lexer.text));
}
protected _initNumbers() {
// numbers in digit
this._addDefinition('DIGITS', /[0-9]+(,[0-9]+)*/);
this._addDefinition('DECIMAL_NUMBER', /\.{DIGITS}|{DIGITS}(?:\.{DIGITS})?/);
this._lexer.addRule(/[+-]?{DECIMAL_NUMBER}/, (lexer) => {
const value = this._parseDecimalNumber(lexer.text);
return makeToken(lexer.index, lexer.text, String(value));
});
// currencies
this._lexer.addRule(/{DECIMAL_NUMBER}{WS}(dollars?|bucks?|cents?|pounds?|pence|penny|yen|euros?|won|yuan|usd|cad|aud|chf|eur|gbp|cny|jpy|krw)/, (lexer) => {
const [num, unitword] = lexer.text.split(WS);
let value = this._parseDecimalNumber(num);
let unit = unitword;
if (unit in CURRENCIES)
unit = CURRENCIES[unit];
if (unit.startsWith('0.01')) {
value *= 0.01;
unit = unit.substring(4);
}
return makeToken(lexer.index, lexer.text, String(value) + ' ' + unit, 'CURRENCY', { value, unit });
});
this._lexer.addRule(/(?:C\$|A\$|[$£€₩¥]){WS}?{DECIMAL_NUMBER}/, (lexer) => {
let unit = lexer.text.match(/C\$|A\$|[$£€₩¥]/)![0];
unit = CURRENCIES[unit];
const num = lexer.text.replace(/(?:C\$|A\$|[$£€₩¥])/g, '').replace(WS, '');
const value = this._parseDecimalNumber(num);
return makeToken(lexer.index, lexer.text, String(value) + ' ' + unit, 'CURRENCY', { value, unit });
});
// numbers in words
// - "zero" is not a number (cannot be compounded with other number words)
// - "one" is not normalized when alone
// - small numbers (2 to 12) are normalized to digits
// - other numbers are converted to NUMBER tokens
// 2 to 9
this._addDefinition('ONE_DIGIT_NUMBER', /two|three|four|five|six|seven|eighth|nine/);
// 2 to 12
this._addDefinition('SMALL_NUMBER', /{ONE_DIGIT_NUMBER}|ten|eleven|twelve/);
this._lexer.addRule(/{SMALL_NUMBER}/, (lexer) => {
const value = this._parseWordNumber(lexer.text);
return makeToken(lexer.index, lexer.text, String(value));
});
// 13 to 19, or (20 to 90) optionally followed by ((- or whitespace) followed by 1 to 10)
this._addDefinition('MEDIUM_NUMBER', /thirteen|fourteen|fifteen|sixteen|seventeen|eighteen|nineteen|(?:(?:twenty|thirty|fou?rty|fifty|sixty|seventy|eighty|ninety)(?:(?:-|{WS})+(?:one|{ONE_DIGIT_NUMBER}))?)/);
this._addDefinition('NUMBER_SEP', /{WS}|{WS}and{WS}/);
// 1 to 99, as used by large and huge numbers
this._addDefinition('LARGE_NUMBER_TRAIL', /{NUMBER_SEP}(one|{MEDIUM_NUMBER}|{SMALL_NUMBER}|{DECIMAL_NUMBER})/);
// 100 to 999
this._addDefinition('LARGE_NUMBER', /(?:a|one|{MEDIUM_NUMBER}|{SMALL_NUMBER}|{DECIMAL_NUMBER}){WS}hundreds?{LARGE_NUMBER_TRAIL}?/);
// 1000 and above
this._addDefinition('HUGE_NUMBER_CHUNK', /(a|one|{LARGE_NUMBER}|{MEDIUM_NUMBER}|{SMALL_NUMBER}|{DECIMAL_NUMBER}){WS}(?:thousands?|(?:m|b|tr|quadr)illions?)/);
// note: this allows both "one million three hundred thousands" and "three hundred thousands one million" and "three thousands five thousands"
// the latter two are invalid, but it gets way too messy otherwise
this._addDefinition('HUGE_NUMBER', /{HUGE_NUMBER_CHUNK}(?:{NUMBER_SEP}{HUGE_NUMBER_CHUNK})*(?:{NUMBER_SEP}{LARGE_NUMBER}|{LARGE_NUMBER_TRAIL})?/);
// medium, large and huge numbers are normalized
this._lexer.addRule(/{HUGE_NUMBER}|{LARGE_NUMBER}|{MEDIUM_NUMBER}/, (lexer) => {
const value = this._parseWordNumber(lexer.text);
return makeToken(lexer.index, lexer.text, String(value));
});
}
private _normalizeOrdinal(value : number) {
let normalized;
if (value % 10 === 1 && value % 100 !== 11)
normalized = String(value) + 'st';
else if (value % 10 === 2 && value % 100 !== 12)
normalized = String(value) + 'nd';
else if (value % 10 === 3 && value % 100 !== 13)
normalized = String(value) + 'rd';
else
normalized = String(value) + 'th';
return normalized;
}
protected _initOrdinals() {
// ordinals in digit (1st, 2nd, 3rd, "4 th", 0-th, etc.
this._lexer.addRule(/[0-9]*?(?:1[123]{WS}?-?th|1{WS}?-?st|2{WS}?-?nd|3{WS}?-?rd|[4-90]{WS}?-?th)(?!{LETTER})/, (lexer) => {
const text = lexer.text.replace(/[^0-9]/g, '');
const value = parseInt(text);
const normalized = this._normalizeOrdinal(value);
return makeToken(lexer.index, lexer.text, normalized);
});
// ordinals in words
// - "zeroth" is not an ordinal (cannot be compounded with other number words)
// - small numbers (1st to 12th) are untouched
// - other numbers are converted to NUMBER tokens
// 1st to 9th
this._addDefinition('ONE_DIGIT_ORDINAL', /first|second|third|fourth|fifth|sixth|seventh|eighth|ninth/);
this._addDefinition('SMALL_ORDINAL', /{ONE_DIGIT_ORDINAL}|eleventh|twelfth/);
// 13th to 19th, or 20th, 30th, 40th, 50th, 60th, 70th, 80th, 90th, or (20 to 90) followed by (- or whitespace) followed by 1 to 10
this._addDefinition('MEDIUM_ORDINAL', /thirteenth|fourteenth|fifteenth|sixteenth|seventeenth|eighteenth|nineteenth|twentieth|thirthieth|fortieth|fiftieth|sixtieth|seventieth|eightieth|(?:(?:twenty|thirty|fou?rty|fifty|sixty|seventy|eighty|ninety)(?:-|{WS})+(?:{ONE_DIGIT_ORDINAL}))/);
// ending in 00th but not 000th: 100th, 200th, 300th, ... 1100th, 1200th, ...
this._addDefinition('HUNDRED_LARGE_ORDINAL', /(?:{HUGE_NUMBER_CHUNK}{NUMBER_SEP})*(?:(?:{SMALL_NUMBER}|{MEDIUM_NUMBER}){WS})?hundredth/);
// ending in 000th: 1000th, 2000th, 22000th, 300000th, 1000000th, 1500000th, ...
// (this allows both "one million three hundred thousandth" and "three thousand two thousandth"
// the latter is invalid, but it gets way too messy otherwise)
this._addDefinition('THOUSAND_LARGE_ORDINAL', /(?:(?:{HUGE_NUMBER}|{LARGE_NUMBER}|{SMALL_NUMBER}|{MEDIUM_NUMBER}){WS})?(?:thousandth|(?:m|b|tr|quadr)illionth)/);
// 101th and above, excluding those ending in 00th
this._addDefinition('OTHER_LARGE_ORDINAL', /(?:{HUGE_NUMBER}|{LARGE_NUMBER}){NUMBER_SEP}(?:{SMALL_ORDINAL}|{MEDIUM_ORDINAL})/);
// medium and large ordinals are normalized
this._lexer.addRule(/{HUNDRED_LARGE_ORDINAL}|{THOUSAND_LARGE_ORDINAL}|{OTHER_LARGE_ORDINAL}|{MEDIUM_ORDINAL}/, (lexer) => {
const value = this._parseWordNumber(lexer.text);
const normalized = this._normalizeOrdinal(value);
return makeToken(lexer.index, lexer.text, normalized);
});
}
protected _parseMilitaryTime(text : string) {
text = text.replace(/[^0-9]/g, '');
const hour = parseInt(text.substring(0, 2));
const minute = parseInt(text.substring(2, 4));
const second = parseInt(text.substring(4, 6)) || 0;
return { hour, minute, second };
}
protected _initTimes() {
// "we'll attack at 0700hrs"
this._addDefinition('MILITARY_TIME', /(?:[01][0-9]|2[0-4]):?[0-6][0-9](?::?[0-6][0-9])?(hrs?)?/);
// 12 hour clock (no subsecond allowed)
this._addDefinition('HALF_PLAIN_TIME', /(?:1[012]|0?[0-9]):[0-6][0-9](?::[0-6][0-9])?/);
this._lexer.addRule(/{MILITARY_TIME}/, (lexer) => {
const parsed = this._parseMilitaryTime(lexer.text);
return makeToken(lexer.index, lexer.text, this._normalizeTime(parsed.hour, parsed.minute, parsed.second), 'TIME', parsed);
});
// morning markers
this._addDefinition('TIME_12H_AM', /{HALF_PLAIN_TIME}(?:(?:{WS}?(?:am|a\.m\.))?(?={WS}in{WS}the{WS}morning(?!{LETTER}))|{WS}?(?:am(?!{LETTER})|a\.m\.))/);
this._lexer.addRule(/{TIME_12H_AM}/, (lexer) => {
const parsed = this._parse12HrTime(lexer.text, 'am');
return makeToken(lexer.index, lexer.text, this._normalizeTime(parsed.hour, parsed.minute, parsed.second), 'TIME', parsed);
});
this._addDefinition('TIME_OCLOCK_AM', /(?:1[012]|[0-9])(?:(?:{WS}?(?:am|a\.m\.))(?:{WS}o['’]{WS}?clock)?(?={WS}in{WS}the{WS}morning(?!{LETTER}))|{WS}?(?:am(?!{LETTER})|a\.m\.)(?:{WS}o['’]{WS}clock(?!{LETTER}))?)/);
this._lexer.addRule(/{TIME_OCLOCK_AM}/, (lexer) => {
const parsed = this._parseOClockTime(lexer.text, 'am');
return makeToken(lexer.index, lexer.text, this._normalizeTime(parsed.hour, parsed.minute, parsed.second), 'TIME', parsed);
});
// afternoon markers
this._addDefinition('TIME_12H_PM', /{HALF_PLAIN_TIME}(?:(?:{WS}?(?:pm|p\.m\.))?(?={WS}in{WS}the{WS}(?:afternoon|evening))|{WS}?(?:pm(?!{LETTER})|p\.m\.))/);
this._lexer.addRule(/{TIME_12H_PM}/, (lexer) => {
const parsed = this._parse12HrTime(lexer.text, 'pm');
return makeToken(lexer.index, lexer.text, this._normalizeTime(parsed.hour, parsed.minute, parsed.second), 'TIME', parsed);
});
this._addDefinition('TIME_OCLOCK_PM_EXPLICIT', /(?:1[012]|[0-9])(?:(?:{WS}?(?:pm|p\.m\.))(?:{WS}o['’]{WS}?clock)?(?={WS}in{WS}the{WS}(?:afternoon|evening))|{WS}?(?:pm(?!{LETTER})|p\.m\.)(?:{WS}o['’]{WS}clock(?!{LETTER}))?)/);
// only implicit marker ("7 o'clock in the afternoon")
this._addDefinition('TIME_OCLOCK_PM_IMPLICIT', /(?:1[012]|[0-9])(?:{WS}o['’]{WS}?clock)(?={WS}in{WS}the{WS}(?:afternoon|evening))/);
this._addDefinition('TIME_OCLOCK_PM', /{TIME_OCLOCK_PM_EXPLICIT}|{TIME_OCLOCK_PM_IMPLICIT}/);
this._lexer.addRule(/{TIME_OCLOCK_PM}/, (lexer) => {
const parsed = this._parseOClockTime(lexer.text, 'pm');
return makeToken(lexer.index, lexer.text, this._normalizeTime(parsed.hour, parsed.minute, parsed.second), 'TIME', parsed);
});
// no markers
this._addDefinition('TIME_OCLOCK', /(?:1[0-9]|2[0-4]|[0-9])(?:{WS}o['’]{WS}?clock(?!{LETTER}))/);
this._lexer.addRule(/{TIME_OCLOCK}/, (lexer) => {
const parsed = this._parseOClockTime(lexer.text, '');
return makeToken(lexer.index, lexer.text, this._normalizeTime(parsed.hour, parsed.minute, parsed.second), 'TIME', parsed);
});
// chain up last so our rules take priority over the defaults
super._initTimes();
}
private _extractWordMonth(text : string) {
const word = /jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec/.exec(text.toLowerCase())!;
return MONTHS[word[0]];
}
private _parseWordDate(text : string, parseDay : boolean, parseYear : boolean, parseTime : ((x : string) => TimeEntity)|null) {
const month = this._extractWordMonth(text);
const digitreg = /[0-9]+/g;
let day = -1;
if (parseDay) {
// find the first sequence of digits to get the day
day = parseInt(digitreg.exec(text)![0]);
}
let year = -1;
if (parseYear) {
// find the next sequence of digits to get the year
// (digitreg is a global regex so it will start matching from the end of the previous match)
year = parseInt(digitreg.exec(text)![0]);
}
if (parseTime) {
// if we have a time, pick the remaining of the string and parse it
const time = parseTime(text.substring(digitreg.lastIndex));
return { year, month, day, hour: time.hour, minute: time.minute, second: time.second, timezone: undefined };
} else {
return { year, month, day, hour: 0, minute: 0, second: 0, timezone: undefined };
}
}
protected _initDates() {
// init ISO date recognition
super._initDates();
// note: CoreNLP recognizes days, months and years on their own, using a POS tagger
// we opt to leave those alone
// - this reduces ambiguity (around the word "may" for example - its tagging is quite imprecise with CoreNLP)
// - avoids ambiguity with numbers and military time for years
//
// - days as number will be picked up as ordinals and turn into NUMBER
// - days as names will be left as words (so you can use an enum for weekdays, as in MultiWOZ)
// - months as number will be picked up as NUMBER (unlikely to appear in real usage)
// - months as names will be left as words
// - years will be picked up as NUMBER
//
// the neural network will pick up whatever it needs if those are actually day/month/years
//
// similarly, a day (in word, number or both) followed by a time will not be picked up as a DATE
// it will be tokenized to a word or number, followed by TIME
// (e.g. "tuesday at 3pm" will be "tuesday at TIME" but "tuesday may 3rd at 3pm" will be "DATE" with unspecified year)
// note: we don't recognize ordinals in words as days
// (i.e. "may first" will be parsed as "may first" instead of "DATE", and "may thirtieth" will be "may NUMBER")
// i don't think anyone would type those explicitly, and speech-to-text should convert "may first" to "may 1st"
// if STT doesn't do that, we'll revisit
// the rules for commas are taken from https://www.thepunctuationguide.com/comma.html (British English)
// and https://www.grammarly.com/blog/commas-in-dates/ (American English)
// but commas are made optional everywhere
// (that is, extra commas will prevent something from being recognized as a date, but lack of commas won't)
this._addDefinition('ABBRV_DAY', /(?:mon|tues?|wed|thur?|fri|sat|sun)\./);
this._addDefinition('LONG_DAY', /(?:mon|tues|wednes|thurs|fri|satur|sun)day/);
// a number between 1 and 31, followed by optional appropriate ordinal suffix (with space or - if any)
this._addDefinition('NUMERIC_DAY', /(?:[12](?:1(?:(?:{WS}-)?st)?|2(?:(?:{WS}-)?nd)?|3(?:(?:{WS}-)?rd)?|[04-9](?:(?:{WS}-)?th)?)|3(?:1(?:(?:{WS}-)?st)?|0(?:(?:{WS}-)?th)?)|(?:1(?:(?:{WS}-)?st)?|2(?:(?:{WS}-)?nd)?|3(?:(?:{WS}-)?rd)?|[4-9](?:(?:{WS}-)?th)?))(?![0-9])/);
// note: there is no abbreviation for May
this._addDefinition('ABBRV_MONTH', /(?:jan|feb|mar|apr|jun|jul|aug|sept?|oct|nov|dec)\.?/);
this._addDefinition('LONG_MONTH', /january|february|march|april|may|june|july|august|september|october|november|december/);
// optional (day name followed by comma followed by whitespace), followed by month and day
// "Tuesday, Jul. 7", "May 1st", "Apr. 30"
this._addDefinition('MONTH_DAY', /(?:(?:{ABBRV_DAY}|{LONG_DAY}),?{WS})?(?:{LONG_MONTH}|{ABBRV_MONTH}){WS}{NUMERIC_DAY}(?!{LETTER})/);
// optional (day name followed by comma followed by whitespace), followed by day, optional "of", month
// "Tuesday, 7 Jul", "1st May", "30 Apr.", "2nd of August"
this._addDefinition('DAY_MONTH', /(?:(?:{ABBRV_DAY}|{LONG_DAY}),?{WS})?{NUMERIC_DAY}{WS}(?:of{WS})?(?:{LONG_MONTH}|{ABBRV_MONTH})(?!{LETTER})/);
// dates with words
// day and month
this._lexer.addRule(/{MONTH_DAY}|{DAY_MONTH}/, (lexer) => {
const parsed = this._parseWordDate(lexer.text, true, false, null);
const normalized = this._normalizeDate(parsed);
return makeToken(lexer.index, lexer.text, normalized, 'DATE', parsed);
});
// day and month, followed by comma, followed by year
this._lexer.addRule(/(?:{MONTH_DAY}|{DAY_MONTH}),?{WS}[0-9]{4}(?![0-9])/, (lexer) => {
const parsed = this._parseWordDate(lexer.text, true, true, null);
const normalized = this._normalizeDate(parsed);
return makeToken(lexer.index, lexer.text, normalized, 'DATE', parsed);
});
// month and year
// XXX: CoreNLP/almond-tokenizer would parse this as today's date, in the given month
// but maybe it should parse as the first day of the given month instead?
this._lexer.addRule(/(?:{LONG_MONTH}|{ABBRV_MONTH}){WS}[0-9]{4}(?![0-9])/, (lexer) => {
const parsed = this._parseWordDate(lexer.text, false, true, null);
const normalized = this._normalizeDate(parsed);
return makeToken(lexer.index, lexer.text, normalized, 'DATE', parsed);
});
// day and month followed by comma, followed by optional "at", followed by a time
this._lexer.addRule(/(?:{MONTH_DAY}|{DAY_MONTH}),?(?:{WS}at)?{WS}{MILITARY_TIME}/, (lexer) => {
const parsed = this._parseWordDate(lexer.text, true, false, this._parseMilitaryTime.bind(this));
const normalized = this._normalizeDate(parsed);
return makeToken(lexer.index, lexer.text, normalized, 'DATE', parsed);
});
this._lexer.addRule(/(?:{MONTH_DAY}|{DAY_MONTH}),?(?:{WS}at)?{WS}{TIME_12H_AM}/, (lexer) => {
const parsed = this._parseWordDate(lexer.text, true, false, (text) => this._parse12HrTime(text, 'am'));
const normalized = this._normalizeDate(parsed);
return makeToken(lexer.index, lexer.text, normalized, 'DATE', parsed);
});
this._lexer.addRule(/(?:{MONTH_DAY}|{DAY_MONTH}),?(?:{WS}at)?{WS}{TIME_OCLOCK_AM}/, (lexer) => {
const parsed = this._parseWordDate(lexer.text, true, false, (text) => this._parseOClockTime(text, 'am'));
const normalized = this._normalizeDate(parsed);
return makeToken(lexer.index, lexer.text, normalized, 'DATE', parsed);
});
this._lexer.addRule(/(?:{MONTH_DAY}|{DAY_MONTH}),?(?:{WS}at)?{WS}{TIME_12H_PM}/, (lexer) => {
const parsed = this._parseWordDate(lexer.text, true, false, (text) => this._parse12HrTime(text, 'pm'));
const normalized = this._normalizeDate(parsed);
return makeToken(lexer.index, lexer.text, normalized, 'DATE', parsed);
});
this._lexer.addRule(/(?:{MONTH_DAY}|{DAY_MONTH}),?(?:{WS}at)?{WS}{TIME_OCLOCK_PM}/, (lexer) => {
const parsed = this._parseWordDate(lexer.text, true, false, (text) => this._parseOClockTime(text, 'pm'));
const normalized = this._normalizeDate(parsed);
return makeToken(lexer.index, lexer.text, normalized, 'DATE', parsed);
});
this._lexer.addRule(/(?:{MONTH_DAY}|{DAY_MONTH}),?(?:{WS}at)?{WS}{PLAIN_TIME}/, (lexer) => {
const parsed = this._parseWordDate(lexer.text, true, false, (text) => this._parse12HrTime(text, ''));
const normalized = this._normalizeDate(parsed);
return makeToken(lexer.index, lexer.text, normalized, 'DATE', parsed);
});
this._lexer.addRule(/(?:{MONTH_DAY}|{DAY_MONTH}),?(?:{WS}at)?{WS}{TIME_OCLOCK}/, (lexer) => {
const parsed = this._parseWordDate(lexer.text, true, false, (text) => this._parseOClockTime(text, ''));
const normalized = this._normalizeDate(parsed);
return makeToken(lexer.index, lexer.text, normalized, 'DATE', parsed);
});
// day and month, followed by comma, followed by year, followed by optional "at", followed by a time
this._lexer.addRule(/(?:{MONTH_DAY}|{DAY_MONTH}),?{WS}[0-9]{4}(?![0-9]),?(?:{WS}at)?{WS}{MILITARY_TIME}/, (lexer) => {
const parsed = this._parseWordDate(lexer.text, true, true, this._parseMilitaryTime.bind(this));
const normalized = this._normalizeDate(parsed);
return makeToken(lexer.index, lexer.text, normalized, 'DATE', parsed);
});
this._lexer.addRule(/(?:{MONTH_DAY}|{DAY_MONTH}),?{WS}[0-9]{4}(?![0-9]),?(?:{WS}at)?{WS}{TIME_12H_AM}/, (lexer) => {
const parsed = this._parseWordDate(lexer.text, true, true, (text) => this._parse12HrTime(text, 'am'));
const normalized = this._normalizeDate(parsed);
return makeToken(lexer.index, lexer.text, normalized, 'DATE', parsed);
});
this._lexer.addRule(/(?:{MONTH_DAY}|{DAY_MONTH}),?{WS}[0-9]{4}(?![0-9]),?(?:{WS}at)?{WS}{TIME_OCLOCK_AM}/, (lexer) => {
const parsed = this._parseWordDate(lexer.text, true, true, (text) => this._parseOClockTime(text, 'am'));
const normalized = this._normalizeDate(parsed);
return makeToken(lexer.index, lexer.text, normalized, 'DATE', parsed);
});
this._lexer.addRule(/(?:{MONTH_DAY}|{DAY_MONTH}),?{WS}[0-9]{4}(?![0-9]),?(?:{WS}at)?{WS}{TIME_12H_PM}/, (lexer) => {
const parsed = this._parseWordDate(lexer.text, true, true, (text) => this._parse12HrTime(text, 'pm'));
const normalized = this._normalizeDate(parsed);
return makeToken(lexer.index, lexer.text, normalized, 'DATE', parsed);
});
this._lexer.addRule(/(?:{MONTH_DAY}|{DAY_MONTH}),?{WS}[0-9]{4}(?![0-9]),?(?:{WS}at)?{WS}{TIME_OCLOCK_PM}/, (lexer) => {
const parsed = this._parseWordDate(lexer.text, true, true, (text) => this._parseOClockTime(text, 'pm'));
const normalized = this._normalizeDate(parsed);
return makeToken(lexer.index, lexer.text, normalized, 'DATE', parsed);
});
this._lexer.addRule(/(?:{MONTH_DAY}|{DAY_MONTH}),?{WS}[0-9]{4}(?![0-9]),?(?:{WS}at)?{WS}{PLAIN_TIME}/, (lexer) => {
const parsed = this._parseWordDate(lexer.text, true, true, (text) => this._parse12HrTime(text, ''));
const normalized = this._normalizeDate(parsed);
return makeToken(lexer.index, lexer.text, normalized, 'DATE', parsed);
});
this._lexer.addRule(/(?:{MONTH_DAY}|{DAY_MONTH}),?{WS}[0-9]{4}(?![0-9]),?(?:{WS}at)?{WS}{TIME_OCLOCK}/, (lexer) => {
const parsed = this._parseWordDate(lexer.text, true, true, (text) => this._parseOClockTime(text, ''));
const normalized = this._normalizeDate(parsed);
return makeToken(lexer.index, lexer.text, normalized, 'DATE', parsed);
});
// numeric dates
// month/day/year
this._addDefinition('NUMERIC_DATE_AMERICAN', /(?:1[012]|0?[1-9])\/(?:[12][0-9]|3[01]|0?[1-9])\/[0-9]{4}(?![0-9])/);
// day/month/year
this._addDefinition('NUMERIC_DATE_BRITISH', /(?:[12][0-9]|3[01]|0?[1-9])\/(?:1[012]|0?[1-9])\/[0-9]{4}(?![0-9])/);
// day.month.year
// month/day (only applicable with other signals that make it a date)
this._addDefinition('NUMERIC_DATE_SHORT_AMERICAN', /(?:1[012]|0?[1-9])\/(?:[12][0-9]|3[01]|0?[1-9])/);
this._addDefinition('NUMERIC_DATE_SHORT_BRITISH', /(?:[12][0-9]|3[01]|0?[1-9])\/(?:1[012]|0?[1-9])/);
this._addDefinition('NUMERIC_DATE_GERMAN', /(?:[12][0-9]|3[01]|0[1-9])\.(?:1[012]|0[1-9])(?:\.[0-9]{4})?(?![0-9])/);
// American before British, so in case ambiguity American wins
this._lexer.addRule(/{NUMERIC_DATE_AMERICAN}/, (lexer) => {
const parsed = this._parseNumericDate(lexer.text, 'mdy', null);
const normalized = this._normalizeDate(parsed);
return makeToken(lexer.index, lexer.text, normalized, 'DATE', parsed);
});
this._lexer.addRule(/{NUMERIC_DATE_BRITISH}|{NUMERIC_DATE_GERMAN}/, (lexer) => {
const parsed = this._parseNumericDate(lexer.text, 'dmy', null);
const normalized = this._normalizeDate(parsed);
return makeToken(lexer.index, lexer.text, normalized, 'DATE', parsed);
});
// with time
this._lexer.addRule(/(?:{NUMERIC_DATE_AMERICAN}|{NUMERIC_DATE_SHORT_AMERICAN}),?(?:{WS}at)?{WS}{MILITARY_TIME}/, (lexer) => {
const parsed = this._parseNumericDate(lexer.text, 'mdy', this._parseMilitaryTime.bind(this));
const normalized = this._normalizeDate(parsed);
return makeToken(lexer.index, lexer.text, normalized, 'DATE', parsed);
});
this._lexer.addRule(/(?:{NUMERIC_DATE_AMERICAN}|{NUMERIC_DATE_SHORT_AMERICAN}),?(?:{WS}at)?{WS}{TIME_12H_AM}/, (lexer) => {
const parsed = this._parseNumericDate(lexer.text, 'mdy', (text) => this._parse12HrTime(text, 'am'));
const normalized = this._normalizeDate(parsed);
return makeToken(lexer.index, lexer.text, normalized, 'DATE', parsed);
});
this._lexer.addRule(/(?:{NUMERIC_DATE_AMERICAN}|{NUMERIC_DATE_SHORT_AMERICAN}),?(?:{WS}at)?{WS}{TIME_OCLOCK_AM}/, (lexer) => {
const parsed = this._parseNumericDate(lexer.text, 'mdy', (text) => this._parseOClockTime(text, 'am'));
const normalized = this._normalizeDate(parsed);
return makeToken(lexer.index, lexer.text, normalized, 'DATE', parsed);
});
this._lexer.addRule(/(?:{NUMERIC_DATE_AMERICAN}|{NUMERIC_DATE_SHORT_AMERICAN}),?(?:{WS}at)?{WS}{TIME_12H_PM}/, (lexer) => {
const parsed = this._parseNumericDate(lexer.text, 'mdy', (text) => this._parse12HrTime(text, 'pm'));
const normalized = this._normalizeDate(parsed);
return makeToken(lexer.index, lexer.text, normalized, 'DATE', parsed);
});
this._lexer.addRule(/(?:{NUMERIC_DATE_AMERICAN}|{NUMERIC_DATE_SHORT_AMERICAN}),?(?:{WS}at)?{WS}{TIME_OCLOCK_PM}/, (lexer) => {
const parsed = this._parseNumericDate(lexer.text, 'mdy', (text) => this._parseOClockTime(text, 'pm'));
const normalized = this._normalizeDate(parsed);
return makeToken(lexer.index, lexer.text, normalized, 'DATE', parsed);
});
this._lexer.addRule(/(?:{NUMERIC_DATE_AMERICAN}|{NUMERIC_DATE_SHORT_AMERICAN}),?(?:{WS}at)?{WS}{PLAIN_TIME}/, (lexer) => {
const parsed = this._parseNumericDate(lexer.text, 'mdy', (text) => this._parse12HrTime(text, ''));
const normalized = this._normalizeDate(parsed);
return makeToken(lexer.index, lexer.text, normalized, 'DATE', parsed);
});
this._lexer.addRule(/(?:{NUMERIC_DATE_AMERICAN}|{NUMERIC_DATE_SHORT_AMERICAN}),?(?:{WS}at)?{WS}{TIME_OCLOCK}/, (lexer) => {
const parsed = this._parseNumericDate(lexer.text, 'mdy', (text) => this._parseOClockTime(text, ''));
const normalized = this._normalizeDate(parsed);
return makeToken(lexer.index, lexer.text, normalized, 'DATE', parsed);
});
this._lexer.addRule(/(?:{NUMERIC_DATE_BRITISH}|{NUMERIC_DATE_GERMAN}|{NUMERIC_DATE_SHORT_BRITISH}),?(?:{WS}at)?{WS}{MILITARY_TIME}/, (lexer) => {
const parsed = this._parseNumericDate(lexer.text, 'dmy', this._parseMilitaryTime.bind(this));
const normalized = this._normalizeDate(parsed);
return makeToken(lexer.index, lexer.text, normalized, 'DATE', parsed);
});
this._lexer.addRule(/(?:{NUMERIC_DATE_BRITISH}|{NUMERIC_DATE_GERMAN}|{NUMERIC_DATE_SHORT_BRITISH}),?(?:{WS}at)?{WS}{TIME_12H_AM}/, (lexer) => {
const parsed = this._parseNumericDate(lexer.text, 'dmy', (text) => this._parse12HrTime(text, 'am'));
const normalized = this._normalizeDate(parsed);
return makeToken(lexer.index, lexer.text, normalized, 'DATE', parsed);
});
this._lexer.addRule(/(?:{NUMERIC_DATE_BRITISH}|{NUMERIC_DATE_GERMAN}|{NUMERIC_DATE_SHORT_BRITISH}),?(?:{WS}at)?{WS}{TIME_OCLOCK_AM}/, (lexer) => {
const parsed = this._parseNumericDate(lexer.text, 'dmy', (text) => this._parseOClockTime(text, 'am'));
const normalized = this._normalizeDate(parsed);
return makeToken(lexer.index, lexer.text, normalized, 'DATE', parsed);
});
this._lexer.addRule(/(?:{NUMERIC_DATE_BRITISH}|{NUMERIC_DATE_GERMAN}|{NUMERIC_DATE_SHORT_BRITISH}),?(?:{WS}at)?{WS}{TIME_12H_PM}/, (lexer) => {
const parsed = this._parseNumericDate(lexer.text, 'dmy', (text) => this._parse12HrTime(text, 'pm'));
const normalized = this._normalizeDate(parsed);
return makeToken(lexer.index, lexer.text, normalized, 'DATE', parsed);
});
this._lexer.addRule(/(?:{NUMERIC_DATE_BRITISH}|{NUMERIC_DATE_GERMAN}|{NUMERIC_DATE_SHORT_BRITISH}),?(?:{WS}at)?{WS}{TIME_OCLOCK_PM}/, (lexer) => {
const parsed = this._parseNumericDate(lexer.text, 'dmy', (text) => this._parseOClockTime(text, 'pm'));
const normalized = this._normalizeDate(parsed);
return makeToken(lexer.index, lexer.text, normalized, 'DATE', parsed);
});
this._lexer.addRule(/(?:{NUMERIC_DATE_BRITISH}|{NUMERIC_DATE_GERMAN}|{NUMERIC_DATE_SHORT_BRITISH}),?(?:{WS}at)?{WS}{PLAIN_TIME}/, (lexer) => {
const parsed = this._parseNumericDate(lexer.text, 'dmy', (text) => this._parse12HrTime(text, ''));
const normalized = this._normalizeDate(parsed);
return makeToken(lexer.index, lexer.text, normalized, 'DATE', parsed);
});
this._lexer.addRule(/(?:{NUMERIC_DATE_BRITISH}|{NUMERIC_DATE_GERMAN}|{NUMERIC_DATE_SHORT_BRITISH}),?(?:{WS}at)?{WS}{TIME_OCLOCK}/, (lexer) => {
const parsed = this._parseNumericDate(lexer.text, 'dmy', (text) => this._parseOClockTime(text, ''));
const normalized = this._normalizeDate(parsed);
return makeToken(lexer.index, lexer.text, normalized, 'DATE', parsed);
});
}
} | the_stack |
declare module 'babylonjs-procedural-textures' {
export = BABYLON;
}
declare module BABYLON {
class WoodProceduralTexture extends ProceduralTexture {
private _ampScale;
private _woodColor;
constructor(name: string, size: number, scene: Scene, fallbackTexture?: Texture, generateMipMaps?: boolean);
updateShaderUniforms(): void;
ampScale: number;
woodColor: Color3;
/**
* Serializes this wood procedural texture
* @returns a serialized wood procedural texture object
*/
serialize(): any;
/**
* Creates a Wood Procedural Texture from parsed wood procedural texture data
* @param parsedTexture defines parsed texture data
* @param scene defines the current scene
* @param rootUrl defines the root URL containing wood procedural texture information
* @returns a parsed Wood Procedural Texture
*/
static Parse(parsedTexture: any, scene: Scene, rootUrl: string): WoodProceduralTexture;
}
}
declare module BABYLON {
class FireProceduralTexture extends ProceduralTexture {
private _time;
private _speed;
private _autoGenerateTime;
private _fireColors;
private _alphaThreshold;
constructor(name: string, size: number, scene: Scene, fallbackTexture?: Texture, generateMipMaps?: boolean);
updateShaderUniforms(): void;
render(useCameraPostProcess?: boolean): void;
static readonly PurpleFireColors: Color3[];
static readonly GreenFireColors: Color3[];
static readonly RedFireColors: Color3[];
static readonly BlueFireColors: Color3[];
autoGenerateTime: boolean;
fireColors: Color3[];
time: number;
speed: Vector2;
alphaThreshold: number;
/**
* Serializes this fire procedural texture
* @returns a serialized fire procedural texture object
*/
serialize(): any;
/**
* Creates a Fire Procedural Texture from parsed fire procedural texture data
* @param parsedTexture defines parsed texture data
* @param scene defines the current scene
* @param rootUrl defines the root URL containing fire procedural texture information
* @returns a parsed Fire Procedural Texture
*/
static Parse(parsedTexture: any, scene: Scene, rootUrl: string): FireProceduralTexture;
}
}
declare module BABYLON {
class CloudProceduralTexture extends ProceduralTexture {
private _skyColor;
private _cloudColor;
constructor(name: string, size: number, scene: Scene, fallbackTexture?: Texture, generateMipMaps?: boolean);
updateShaderUniforms(): void;
skyColor: Color4;
cloudColor: Color4;
/**
* Serializes this cloud procedural texture
* @returns a serialized cloud procedural texture object
*/
serialize(): any;
/**
* Creates a Cloud Procedural Texture from parsed cloud procedural texture data
* @param parsedTexture defines parsed texture data
* @param scene defines the current scene
* @param rootUrl defines the root URL containing cloud procedural texture information
* @returns a parsed Cloud Procedural Texture
*/
static Parse(parsedTexture: any, scene: Scene, rootUrl: string): CloudProceduralTexture;
}
}
declare module BABYLON {
class GrassProceduralTexture extends ProceduralTexture {
private _grassColors;
private _groundColor;
constructor(name: string, size: number, scene: Scene, fallbackTexture?: Texture, generateMipMaps?: boolean);
updateShaderUniforms(): void;
grassColors: Color3[];
groundColor: Color3;
/**
* Serializes this grass procedural texture
* @returns a serialized grass procedural texture object
*/
serialize(): any;
/**
* Creates a Grass Procedural Texture from parsed grass procedural texture data
* @param parsedTexture defines parsed texture data
* @param scene defines the current scene
* @param rootUrl defines the root URL containing grass procedural texture information
* @returns a parsed Grass Procedural Texture
*/
static Parse(parsedTexture: any, scene: Scene, rootUrl: string): GrassProceduralTexture;
}
}
declare module BABYLON {
class RoadProceduralTexture extends ProceduralTexture {
private _roadColor;
constructor(name: string, size: number, scene: Scene, fallbackTexture?: Texture, generateMipMaps?: boolean);
updateShaderUniforms(): void;
roadColor: Color3;
/**
* Serializes this road procedural texture
* @returns a serialized road procedural texture object
*/
serialize(): any;
/**
* Creates a Road Procedural Texture from parsed road procedural texture data
* @param parsedTexture defines parsed texture data
* @param scene defines the current scene
* @param rootUrl defines the root URL containing road procedural texture information
* @returns a parsed Road Procedural Texture
*/
static Parse(parsedTexture: any, scene: Scene, rootUrl: string): RoadProceduralTexture;
}
}
declare module BABYLON {
class BrickProceduralTexture extends ProceduralTexture {
private _numberOfBricksHeight;
private _numberOfBricksWidth;
private _jointColor;
private _brickColor;
constructor(name: string, size: number, scene: Scene, fallbackTexture?: Texture, generateMipMaps?: boolean);
updateShaderUniforms(): void;
numberOfBricksHeight: number;
numberOfBricksWidth: number;
jointColor: Color3;
brickColor: Color3;
/**
* Serializes this brick procedural texture
* @returns a serialized brick procedural texture object
*/
serialize(): any;
/**
* Creates a Brick Procedural Texture from parsed brick procedural texture data
* @param parsedTexture defines parsed texture data
* @param scene defines the current scene
* @param rootUrl defines the root URL containing brick procedural texture information
* @returns a parsed Brick Procedural Texture
*/
static Parse(parsedTexture: any, scene: Scene, rootUrl: string): BrickProceduralTexture;
}
}
declare module BABYLON {
class MarbleProceduralTexture extends ProceduralTexture {
private _numberOfTilesHeight;
private _numberOfTilesWidth;
private _amplitude;
private _jointColor;
constructor(name: string, size: number, scene: Scene, fallbackTexture?: Texture, generateMipMaps?: boolean);
updateShaderUniforms(): void;
numberOfTilesHeight: number;
amplitude: number;
numberOfTilesWidth: number;
jointColor: Color3;
/**
* Serializes this marble procedural texture
* @returns a serialized marble procedural texture object
*/
serialize(): any;
/**
* Creates a Marble Procedural Texture from parsed marble procedural texture data
* @param parsedTexture defines parsed texture data
* @param scene defines the current scene
* @param rootUrl defines the root URL containing marble procedural texture information
* @returns a parsed Marble Procedural Texture
*/
static Parse(parsedTexture: any, scene: Scene, rootUrl: string): MarbleProceduralTexture;
}
}
declare module BABYLON {
class StarfieldProceduralTexture extends ProceduralTexture {
private _time;
private _alpha;
private _beta;
private _zoom;
private _formuparam;
private _stepsize;
private _tile;
private _brightness;
private _darkmatter;
private _distfading;
private _saturation;
constructor(name: string, size: number, scene: Scene, fallbackTexture?: Texture, generateMipMaps?: boolean);
updateShaderUniforms(): void;
time: number;
alpha: number;
beta: number;
formuparam: number;
stepsize: number;
zoom: number;
tile: number;
brightness: number;
darkmatter: number;
distfading: number;
saturation: number;
/**
* Serializes this starfield procedural texture
* @returns a serialized starfield procedural texture object
*/
serialize(): any;
/**
* Creates a Starfield Procedural Texture from parsed startfield procedural texture data
* @param parsedTexture defines parsed texture data
* @param scene defines the current scene
* @param rootUrl defines the root URL containing startfield procedural texture information
* @returns a parsed Starfield Procedural Texture
*/
static Parse(parsedTexture: any, scene: Scene, rootUrl: string): StarfieldProceduralTexture;
}
}
declare module BABYLON {
class NormalMapProceduralTexture extends ProceduralTexture {
private _baseTexture;
constructor(name: string, size: number, scene: Scene, fallbackTexture?: Texture, generateMipMaps?: boolean);
updateShaderUniforms(): void;
render(useCameraPostProcess?: boolean): void;
resize(size: any, generateMipMaps: any): void;
baseTexture: Texture;
/**
* Serializes this normal map procedural texture
* @returns a serialized normal map procedural texture object
*/
serialize(): any;
/**
* Creates a Normal Map Procedural Texture from parsed normal map procedural texture data
* @param parsedTexture defines parsed texture data
* @param scene defines the current scene
* @param rootUrl defines the root URL containing normal map procedural texture information
* @returns a parsed Normal Map Procedural Texture
*/
static Parse(parsedTexture: any, scene: Scene, rootUrl: string): NormalMapProceduralTexture;
}
}
declare module BABYLON {
class PerlinNoiseProceduralTexture extends ProceduralTexture {
time: number;
timeScale: number;
translationSpeed: number;
private _currentTranslation;
constructor(name: string, size: number, scene: Scene, fallbackTexture?: Texture, generateMipMaps?: boolean);
updateShaderUniforms(): void;
render(useCameraPostProcess?: boolean): void;
resize(size: any, generateMipMaps: any): void;
/**
* Serializes this perlin noise procedural texture
* @returns a serialized perlin noise procedural texture object
*/
serialize(): any;
/**
* Creates a Perlin Noise Procedural Texture from parsed perlin noise procedural texture data
* @param parsedTexture defines parsed texture data
* @param scene defines the current scene
* @param rootUrl defines the root URL containing perlin noise procedural texture information
* @returns a parsed Perlin Noise Procedural Texture
*/
static Parse(parsedTexture: any, scene: Scene, rootUrl: string): PerlinNoiseProceduralTexture;
}
} | the_stack |
import {cssClasses, numbers, strings} from '../../mdc-ripple/constants';
import {MDCRippleFoundation} from '../../mdc-ripple/foundation';
import {captureHandlers, checkNumTimesSpyCalledWithArgs} from '../../../testing/helpers/foundation';
import {setUpMdcTestEnvironment} from '../../../testing/helpers/setup';
import {setupTest, testFoundation} from './helpers';
describe('MDCRippleFoundation - Activation Logic', () => {
setUpMdcTestEnvironment();
testFoundation(
'does nothing if component if isSurfaceDisabled is true',
({adapter,
foundation}: {adapter: any, foundation: MDCRippleFoundation}) => {
const handlers = captureHandlers(adapter, 'registerInteractionHandler');
foundation.init();
jasmine.clock().tick(1);
adapter.isSurfaceDisabled.and.returnValue(true);
handlers['mousedown']();
expect(adapter.addClass)
.not.toHaveBeenCalledWith(cssClasses.FG_ACTIVATION);
});
testFoundation(
'adds activation classes on mousedown',
({adapter,
foundation}: {adapter: any, foundation: MDCRippleFoundation}) => {
const handlers = captureHandlers(adapter, 'registerInteractionHandler');
foundation.init();
jasmine.clock().tick(1);
handlers['mousedown']();
jasmine.clock().tick(1);
expect(adapter.addClass).toHaveBeenCalledWith(cssClasses.FG_ACTIVATION);
});
testFoundation(
'sets FG position from the coords to the center within surface on mousedown',
({adapter,
foundation}: {adapter: any, foundation: MDCRippleFoundation}) => {
const handlers = captureHandlers(adapter, 'registerInteractionHandler');
const left = 50;
const top = 50;
const width = 200;
const height = 100;
const maxSize = Math.max(width, height);
const initialSize = maxSize * numbers.INITIAL_ORIGIN_SCALE;
const pageX = 100;
const pageY = 75;
adapter.computeBoundingRect.and.returnValue({width, height, left, top});
foundation.init();
jasmine.clock().tick(1);
handlers['mousedown']({pageX, pageY});
jasmine.clock().tick(1);
const startPosition = {
x: pageX - left - (initialSize / 2),
y: pageY - top - (initialSize / 2),
};
const endPosition = {
x: (width / 2) - (initialSize / 2),
y: (height / 2) - (initialSize / 2),
};
expect(adapter.updateCssVariable)
.toHaveBeenCalledWith(
strings.VAR_FG_TRANSLATE_START,
`${startPosition.x}px, ${startPosition.y}px`);
expect(adapter.updateCssVariable)
.toHaveBeenCalledWith(
strings.VAR_FG_TRANSLATE_END,
`${endPosition.x}px, ${endPosition.y}px`);
});
testFoundation(
'adds activation classes on touchstart',
({adapter,
foundation}: {adapter: any, foundation: MDCRippleFoundation}) => {
const handlers = captureHandlers(adapter, 'registerInteractionHandler');
foundation.init();
jasmine.clock().tick(1);
handlers['touchstart']({changedTouches: [{pageX: 0, pageY: 0}]});
jasmine.clock().tick(1);
expect(adapter.addClass).toHaveBeenCalledWith(cssClasses.FG_ACTIVATION);
});
testFoundation(
'sets FG position from the coords to the center within surface on touchstart',
({adapter,
foundation}: {adapter: any, foundation: MDCRippleFoundation}) => {
const handlers = captureHandlers(adapter, 'registerInteractionHandler');
const left = 50;
const top = 50;
const width = 200;
const height = 100;
const maxSize = Math.max(width, height);
const initialSize = maxSize * numbers.INITIAL_ORIGIN_SCALE;
const pageX = 100;
const pageY = 75;
adapter.computeBoundingRect.and.returnValue({width, height, left, top});
foundation.init();
jasmine.clock().tick(1);
handlers['touchstart']({changedTouches: [{pageX, pageY}]});
jasmine.clock().tick(1);
const startPosition = {
x: pageX - left - (initialSize / 2),
y: pageY - top - (initialSize / 2),
};
const endPosition = {
x: (width / 2) - (initialSize / 2),
y: (height / 2) - (initialSize / 2),
};
expect(adapter.updateCssVariable)
.toHaveBeenCalledWith(
strings.VAR_FG_TRANSLATE_START,
`${startPosition.x}px, ${startPosition.y}px`);
expect(adapter.updateCssVariable)
.toHaveBeenCalledWith(
strings.VAR_FG_TRANSLATE_END,
`${endPosition.x}px, ${endPosition.y}px`);
});
testFoundation(
'adds activation classes on pointerdown',
({adapter,
foundation}: {adapter: any, foundation: MDCRippleFoundation}) => {
const handlers = captureHandlers(adapter, 'registerInteractionHandler');
foundation.init();
jasmine.clock().tick(1);
handlers['pointerdown']();
jasmine.clock().tick(1);
expect(adapter.addClass).toHaveBeenCalledWith(cssClasses.FG_ACTIVATION);
});
testFoundation(
'sets FG position from the coords to the center within surface on pointerdown',
({adapter,
foundation}: {adapter: any, foundation: MDCRippleFoundation}) => {
const handlers = captureHandlers(adapter, 'registerInteractionHandler');
const left = 50;
const top = 50;
const width = 200;
const height = 100;
const maxSize = Math.max(width, height);
const initialSize = maxSize * numbers.INITIAL_ORIGIN_SCALE;
const pageX = 100;
const pageY = 75;
adapter.computeBoundingRect.and.returnValue({width, height, left, top});
foundation.init();
jasmine.clock().tick(1);
handlers['pointerdown']({pageX, pageY});
jasmine.clock().tick(1);
const startPosition = {
x: pageX - left - (initialSize / 2),
y: pageY - top - (initialSize / 2),
};
const endPosition = {
x: (width / 2) - (initialSize / 2),
y: (height / 2) - (initialSize / 2),
};
expect(adapter.updateCssVariable)
.toHaveBeenCalledWith(
strings.VAR_FG_TRANSLATE_START,
`${startPosition.x}px, ${startPosition.y}px`);
expect(adapter.updateCssVariable)
.toHaveBeenCalledWith(
strings.VAR_FG_TRANSLATE_END,
`${endPosition.x}px, ${endPosition.y}px`);
});
testFoundation(
'adds activation classes on keydown when surface is made active on same frame',
({adapter,
foundation}: {adapter: any, foundation: MDCRippleFoundation}) => {
const handlers = captureHandlers(adapter, 'registerInteractionHandler');
adapter.isSurfaceActive.and.returnValue(true);
foundation.init();
jasmine.clock().tick(1);
handlers['keydown']();
checkNumTimesSpyCalledWithArgs(
adapter.addClass, [cssClasses.FG_ACTIVATION], 1);
});
testFoundation(
'adds activation classes on keydown when surface only reflects :active on next frame for space keydown',
({adapter,
foundation}: {adapter: any, foundation: MDCRippleFoundation}) => {
const handlers = captureHandlers(adapter, 'registerInteractionHandler');
adapter.isSurfaceActive.and.returnValues(false, true);
foundation.init();
jasmine.clock().tick(1);
handlers['keydown']({key: ' '});
expect(adapter.addClass)
.not.toHaveBeenCalledWith(cssClasses.FG_ACTIVATION);
jasmine.clock().tick(1);
expect(adapter.addClass).toHaveBeenCalledWith(cssClasses.FG_ACTIVATION);
});
testFoundation(
'does not add activation classes on keydown when surface is not made active',
({adapter,
foundation}: {adapter: any, foundation: MDCRippleFoundation}) => {
const handlers = captureHandlers(adapter, 'registerInteractionHandler');
adapter.isSurfaceActive.and.returnValues(false, false);
foundation.init();
jasmine.clock().tick(1);
handlers['keydown']({key: ' '});
jasmine.clock().tick(1);
expect(adapter.addClass)
.not.toHaveBeenCalledWith(cssClasses.FG_ACTIVATION);
});
testFoundation(
'sets FG position to center on non-pointer activation',
({adapter,
foundation}: {adapter: any, foundation: MDCRippleFoundation}) => {
const handlers = captureHandlers(adapter, 'registerInteractionHandler');
const left = 50;
const top = 50;
const width = 200;
const height = 100;
const maxSize = Math.max(width, height);
const initialSize = maxSize * numbers.INITIAL_ORIGIN_SCALE;
adapter.computeBoundingRect.and.returnValue({width, height, left, top});
adapter.isSurfaceActive.and.returnValue(true);
foundation.init();
jasmine.clock().tick(1);
handlers['keydown']();
jasmine.clock().tick(1);
const position = {
x: (width / 2) - (initialSize / 2),
y: (height / 2) - (initialSize / 2),
};
expect(adapter.updateCssVariable)
.toHaveBeenCalledWith(
strings.VAR_FG_TRANSLATE_START,
`${position.x}px, ${position.y}px`);
expect(adapter.updateCssVariable)
.toHaveBeenCalledWith(
strings.VAR_FG_TRANSLATE_END,
`${position.x}px, ${position.y}px`);
});
testFoundation(
'adds activation classes on programmatic activation',
({adapter,
foundation}: {adapter: any, foundation: MDCRippleFoundation}) => {
adapter.isSurfaceActive.and.returnValue(true);
foundation.init();
jasmine.clock().tick(1);
foundation.activate();
jasmine.clock().tick(1);
expect(adapter.addClass).toHaveBeenCalledWith(cssClasses.FG_ACTIVATION);
});
testFoundation(
'programmatic activation immediately after interaction',
({adapter,
foundation}: {adapter: any, foundation: MDCRippleFoundation}) => {
const handlers = captureHandlers(adapter, 'registerInteractionHandler');
const documentHandlers =
captureHandlers(adapter, 'registerDocumentInteractionHandler');
adapter.isSurfaceActive.and.returnValue(true);
foundation.init();
jasmine.clock().tick(1);
handlers['touchstart']({changedTouches: [{pageX: 0, pageY: 0}]});
jasmine.clock().tick(1);
documentHandlers['touchend']();
jasmine.clock().tick(1);
foundation.activate();
jasmine.clock().tick(1);
checkNumTimesSpyCalledWithArgs(
adapter.addClass, [cssClasses.FG_ACTIVATION], 2);
});
testFoundation(
'sets FG position to center on non-pointer activation',
({adapter,
foundation}: {adapter: any, foundation: MDCRippleFoundation}) => {
const handlers = captureHandlers(adapter, 'registerInteractionHandler');
const left = 50;
const top = 50;
const width = 200;
const height = 100;
const maxSize = Math.max(width, height);
const initialSize = maxSize * numbers.INITIAL_ORIGIN_SCALE;
adapter.computeBoundingRect.and.returnValue({width, height, left, top});
adapter.isSurfaceActive.and.returnValue(true);
foundation.init();
jasmine.clock().tick(1);
handlers['keydown']();
jasmine.clock().tick(1);
const position = {
x: (width / 2) - (initialSize / 2),
y: (height / 2) - (initialSize / 2),
};
expect(adapter.updateCssVariable)
.toHaveBeenCalledWith(
strings.VAR_FG_TRANSLATE_START,
`${position.x}px, ${position.y}px`);
expect(adapter.updateCssVariable)
.toHaveBeenCalledWith(
strings.VAR_FG_TRANSLATE_END,
`${position.x}px, ${position.y}px`);
});
testFoundation(
'does not redundantly add classes on touchstart followed by mousedown',
({adapter,
foundation}: {adapter: any, foundation: MDCRippleFoundation}) => {
const handlers = captureHandlers(adapter, 'registerInteractionHandler');
foundation.init();
jasmine.clock().tick(1);
handlers['touchstart']({changedTouches: [{pageX: 0, pageY: 0}]});
jasmine.clock().tick(1);
handlers['mousedown']();
jasmine.clock().tick(1);
checkNumTimesSpyCalledWithArgs(
adapter.addClass, [cssClasses.FG_ACTIVATION], 1);
});
testFoundation(
'does not redundantly add classes on touchstart followed by pointerstart',
({adapter,
foundation}: {adapter: any, foundation: MDCRippleFoundation}) => {
const handlers = captureHandlers(adapter, 'registerInteractionHandler');
foundation.init();
jasmine.clock().tick(1);
handlers['touchstart']({changedTouches: [{pageX: 0, pageY: 0}]});
jasmine.clock().tick(1);
handlers['pointerdown']();
jasmine.clock().tick(1);
checkNumTimesSpyCalledWithArgs(
adapter.addClass, [cssClasses.FG_ACTIVATION], 1);
});
testFoundation(
'removes deactivation classes on activate to ensure ripples can be retriggered',
({adapter,
foundation}: {adapter: any, foundation: MDCRippleFoundation}) => {
const handlers = captureHandlers(adapter, 'registerInteractionHandler');
const documentHandlers =
captureHandlers(adapter, 'registerDocumentInteractionHandler');
foundation.init();
jasmine.clock().tick(1);
handlers['mousedown']();
jasmine.clock().tick(1);
documentHandlers['mouseup']();
jasmine.clock().tick(1);
handlers['mousedown']();
jasmine.clock().tick(1);
expect(adapter.removeClass)
.toHaveBeenCalledWith(cssClasses.FG_DEACTIVATION);
});
testFoundation(
'will not activate multiple ripples on same frame if one surface descends from another',
({adapter,
foundation}: {adapter: any, foundation: MDCRippleFoundation}) => {
const secondRipple = setupTest();
const firstHandlers =
captureHandlers(adapter, 'registerInteractionHandler');
const secondHandlers =
captureHandlers(secondRipple.adapter, 'registerInteractionHandler');
secondRipple.adapter.containsEventTarget.and.returnValue(true);
foundation.init();
secondRipple.foundation.init();
jasmine.clock().tick(1);
firstHandlers['mousedown']();
secondHandlers['mousedown']();
jasmine.clock().tick(1);
expect(adapter.addClass).toHaveBeenCalledWith(cssClasses.FG_ACTIVATION);
expect(secondRipple.adapter.addClass)
.not.toHaveBeenCalledWith(cssClasses.FG_ACTIVATION);
});
testFoundation(
'will not activate multiple ripples on same frame for parent surface w/ touch follow-on events',
({adapter,
foundation}: {adapter: any, foundation: MDCRippleFoundation}) => {
const secondRipple = setupTest();
const firstHandlers =
captureHandlers(adapter, 'registerInteractionHandler');
const secondHandlers =
captureHandlers(secondRipple.adapter, 'registerInteractionHandler');
secondRipple.adapter.containsEventTarget.and.returnValue(true);
foundation.init();
secondRipple.foundation.init();
jasmine.clock().tick(1);
firstHandlers['touchstart']({changedTouches: [{pageX: 0, pageY: 0}]});
secondHandlers['touchstart']({changedTouches: [{pageX: 0, pageY: 0}]});
// Simulated mouse events on touch devices always happen after a delay,
// not on the same frame
jasmine.clock().tick(1);
firstHandlers['mousedown']();
secondHandlers['mousedown']();
jasmine.clock().tick(1);
expect(adapter.addClass).toHaveBeenCalledWith(cssClasses.FG_ACTIVATION);
expect(secondRipple.adapter.addClass)
.not.toHaveBeenCalledWith(cssClasses.FG_ACTIVATION);
});
testFoundation(
'will activate multiple ripples on same frame for surfaces without an ancestor/descendant relationship',
({adapter,
foundation}: {adapter: any, foundation: MDCRippleFoundation}) => {
const secondRipple = setupTest();
const firstHandlers =
captureHandlers(adapter, 'registerInteractionHandler');
const secondHandlers =
captureHandlers(secondRipple.adapter, 'registerInteractionHandler');
secondRipple.adapter.containsEventTarget.and.returnValue(false);
foundation.init();
secondRipple.foundation.init();
jasmine.clock().tick(1);
firstHandlers['mousedown']();
secondHandlers['mousedown']();
jasmine.clock().tick(1);
expect(adapter.addClass).toHaveBeenCalledWith(cssClasses.FG_ACTIVATION);
expect(secondRipple.adapter.addClass)
.toHaveBeenCalledWith(cssClasses.FG_ACTIVATION);
});
testFoundation(
'displays the foreground ripple on activation when unbounded',
({adapter,
foundation}: {adapter: any, foundation: MDCRippleFoundation}) => {
const handlers = captureHandlers(adapter, 'registerInteractionHandler');
adapter.computeBoundingRect.and.returnValue(
{width: 100, height: 100, left: 0, top: 0});
adapter.isUnbounded.and.returnValue(true);
foundation.init();
jasmine.clock().tick(1);
handlers['mousedown']({pageX: 0, pageY: 0});
jasmine.clock().tick(1);
expect(adapter.addClass).toHaveBeenCalledWith(cssClasses.FG_ACTIVATION);
});
testFoundation(
'clears translation custom properties when unbounded in case ripple was switched from bounded',
({adapter,
foundation}: {adapter: any, foundation: MDCRippleFoundation}) => {
const handlers = captureHandlers(adapter, 'registerInteractionHandler');
adapter.isUnbounded.and.returnValue(true);
foundation.init();
jasmine.clock().tick(1);
handlers['pointerdown']({pageX: 100, pageY: 75});
jasmine.clock().tick(1);
expect(adapter.updateCssVariable)
.toHaveBeenCalledWith(strings.VAR_FG_TRANSLATE_START, '');
expect(adapter.updateCssVariable)
.toHaveBeenCalledWith(strings.VAR_FG_TRANSLATE_END, '');
});
}); | the_stack |
import type {
DeviceProps,
DeviceInfo,
DeviceLimits,
DeviceFeature,
CanvasContextProps,
TextureFormat
} from '@luma.gl/api';
import {Device, CanvasContext, log, assert} from '@luma.gl/api';
import {isBrowser} from '@probe.gl/env';
import {polyfillContext} from '../context/polyfill/polyfill-context';
import {trackContextState} from '../context/state-tracker/track-context-state';
import {ContextState} from '../context/context/context-state';
import {createBrowserContext} from '../context/context/create-context';
import {getDeviceInfo} from './device-helpers/get-device-info';
import {getDeviceFeatures} from './device-helpers/device-features';
import {getDeviceLimits, getWebGLLimits, WebGLLimits} from './device-helpers/device-limits';
import WebGLCanvasContext from './webgl-canvas-context';
import {loadSpectorJS, initializeSpectorJS} from '../context/debug/spector';
import {loadWebGLDeveloperTools, makeDebugContext} from '../context/debug/webgl-developer-tools';
import {
isTextureFormatSupported,
isTextureFormatRenderable,
isTextureFormatFilterable
} from './converters/texture-formats';
// WebGL classes
import type {
BufferProps,
ShaderProps,
Sampler,
SamplerProps,
TextureProps,
ExternalTexture,
ExternalTextureProps,
FramebufferProps,
RenderPipeline,
RenderPipelineProps,
ComputePipeline,
ComputePipelineProps,
RenderPass,
RenderPassProps,
ComputePass,
ComputePassProps
} from '@luma.gl/api';
import ClassicBuffer from '../classic/buffer';
import WEBGLBuffer from './resources/webgl-buffer';
import WEBGLShader from './resources/webgl-shader';
import WEBGLSampler from './resources/webgl-sampler';
import WEBGLTexture from './resources/webgl-texture';
import WEBGLFramebuffer from './resources/webgl-framebuffer';
import WEBGLRenderPass from './resources/webgl-render-pass';
import WEBGLRenderPipeline from './resources/webgl-render-pipeline';
const LOG_LEVEL = 1;
let counter = 0;
/** WebGPU style Device API for a WebGL context */
export default class WebGLDevice extends Device implements ContextState {
// Public API
static type: string = 'webgl';
static isSupported(): boolean {
return typeof WebGLRenderingContext !== 'undefined';
}
readonly info: DeviceInfo;
readonly canvasContext: WebGLCanvasContext;
readonly lost: Promise<{reason: 'destroyed'; message: string}>;
readonly handle: WebGLRenderingContext;
get features(): Set<DeviceFeature> {
this._features = this._features || getDeviceFeatures(this.gl);
return this._features;
}
get limits(): DeviceLimits {
this._limits = this._limits || getDeviceLimits(this.gl);
return this._limits;
}
// WebGL specific API
/** WebGL1 typed context. Can always be used. */
readonly gl: WebGLRenderingContext;
/** WebGL2 typed context. Need to check isWebGL2 or isWebGL1 before using. */
readonly gl2: WebGL2RenderingContext;
readonly debug: boolean = false;
/** `true` if this is a WebGL1 context. @note `false` if WebGL2 */
readonly isWebGL1: boolean;
/** `true` if this is a WebGL2 context. @note `false` if WebGL1 */
readonly isWebGL2: boolean;
get webglLimits(): WebGLLimits {
this._webglLimits = this._webglLimits || getWebGLLimits(this.gl);
return this._webglLimits;
}
private _features: Set<DeviceFeature>;
private _limits: DeviceLimits;
private _webglLimits: WebGLLimits;
/** State used by luma.gl classes: TODO - move to canvasContext*/
readonly _canvasSizeInfo = {clientWidth: 0, clientHeight: 0, devicePixelRatio: 1};
/** State used by luma.gl classes */
readonly _extensions: Record<string, any> = {};
_polyfilled: boolean = false;
/** Instance of Spector.js (if initialized) */
spector;
/**
* Get a device instance from a GL context
* Creates and instruments the device if not already created
* @param gl
* @returns
*/
static attach(gl: Device | WebGLRenderingContext | WebGL2RenderingContext): WebGLDevice {
if (gl instanceof WebGLDevice) {
return gl;
}
// @ts-expect-error
if (gl?.device instanceof Device) {
// @ts-expect-error
return gl.device as WebGLDevice;
}
if (!isWebGL(gl)) {
throw new Error('Invalid WebGLRenderingContext');
}
return new WebGLDevice({gl: gl as WebGLRenderingContext});
}
static async create(props?: DeviceProps): Promise<WebGLDevice> {
log.groupCollapsed(LOG_LEVEL, 'WebGLDevice created');
// Wait for page to load. Only wait when props. canvas is string
// to avoid setting page onload callback unless necessary
if (typeof props.canvas === 'string') {
await CanvasContext.pageLoaded;
}
// Load webgl and spector debug scripts from CDN if requested
if (props.debug) {
await loadWebGLDeveloperTools();
}
// @ts-expect-error spector not on props
if (props.spector) {
await loadSpectorJS();
}
log.probe(LOG_LEVEL, 'DOM is loaded')();
return new WebGLDevice(props);
}
constructor(props: DeviceProps) {
super(props);
// If attaching to an already attached context, return the attached device
// @ts-expect-error device is attached to context
const device: WebGLDevice | undefined = props.gl?.device;
if (device) {
log.warn(`WebGL context already attached to device ${device.id}`);
return device;
}
// Create and instrument context
this.canvasContext = new WebGLCanvasContext(this, props);
this.handle = props.gl || createBrowserContext(this.canvasContext.canvas, props);
this.gl = this.handle;
this.gl2 = this.gl as WebGL2RenderingContext;
this.isWebGL2 = isWebGL2(this.gl);
this.isWebGL1 = !this.isWebGL2;
// luma Device fields
this.info = getDeviceInfo(this.gl);
// @ts-expect-error Link webgl context back to device
this.gl.device = this;
// @ts-expect-error Annotate webgl context to handle
this.gl._version = this.isWebGL2 ? 2 : 1;
// Add subset of WebGL2 methods to WebGL1 context
polyfillContext(this.gl);
// Install context state tracking
trackContextState(this.gl, {copyState: false, log: (...args: any[]) => log.log(1, ...args)()});
// DEBUG contexts: Add debug instrumentation to the context, force log level to at least 1
if (isBrowser() && props.debug) {
this.gl = makeDebugContext(this.gl, {...props, webgl2: this.isWebGL2, throwOnError: true});
this.gl2 = this.gl as WebGL2RenderingContext;
this.debug = true;
log.level = Math.max(log.level, 1);
log.warn('WebGL debug mode activated. Performance reduced.')();
}
// @ts-expect-error spector not on props
if (isBrowser() && props.spector) {
const canvas = this.handle.canvas || (props.canvas as HTMLCanvasElement);
this.spector = initializeSpectorJS({...this.props, canvas});
}
// Log some debug info about the newly created context
const message = `\
Created ${this.info.type}${this.debug ? ' debug' : ''} context: \
${this.info.vendor}, ${this.info.renderer} for canvas: ${this.canvasContext.id}`;
log.probe(LOG_LEVEL, message)();
log.groupEnd(LOG_LEVEL)();
}
/**
* Destroys the context
* @note Has no effect for browser contexts, there is no browser API for destroying contexts
*/
destroy() {
let ext = this.gl.getExtension('STACKGL_destroy_context');
if (ext) {
ext.destroy();
}
// ext = this.gl.getExtension('WEBGL_lose_context');
// if (ext) {
// // TODO - disconnect context lost callbacks?
// ext.loseContext();
// }
}
get isLost(): boolean {
return this.gl.isContextLost();
}
getSize(): [number, number] {
return [this.gl.drawingBufferWidth, this.gl.drawingBufferHeight];
}
isTextureFormatSupported(format: TextureFormat): boolean {
return isTextureFormatSupported(this.gl, format);
}
isTextureFormatFilterable(format: TextureFormat): boolean {
return isTextureFormatFilterable(this.gl, format);
}
isTextureFormatRenderable(format: TextureFormat): boolean {
return isTextureFormatRenderable(this.gl, format);
}
// WEBGL SPECIFIC METHODS
/** Returns a WebGL2RenderingContext or throws an error */
assertWebGL2(): WebGL2RenderingContext {
assert(this.isWebGL2, 'Requires WebGL2');
return this.gl2;
}
// IMPLEMENTATION OF ABSTRACT DEVICE
createCanvasContext(props?: CanvasContextProps): CanvasContext {
throw new Error('WebGL only supports a single canvas');
}
_createBuffer(props: BufferProps): WEBGLBuffer {
return new ClassicBuffer(this, props);
}
_createTexture(props: TextureProps): WEBGLTexture {
return new WEBGLTexture(this, props);
}
createExternalTexture(props: ExternalTextureProps): ExternalTexture {
throw new Error('createExternalTexture() not implemented'); // return new Program(props);
}
createSampler(props: SamplerProps): WEBGLSampler {
return new WEBGLSampler(this, props);
}
createShader(props: ShaderProps): WEBGLShader {
return new WEBGLShader(this, props);
}
createFramebuffer(props: FramebufferProps): WEBGLFramebuffer {
return new WEBGLFramebuffer(this, props);
}
createRenderPipeline(props: RenderPipelineProps): WEBGLRenderPipeline {
return new WEBGLRenderPipeline(this, props);
}
beginRenderPass(props: RenderPassProps): WEBGLRenderPass {
return new WEBGLRenderPass(this, props);
}
createComputePipeline(props?: ComputePipelineProps): ComputePipeline {
throw new Error('ComputePipeline not supported in WebGL');
}
beginComputePass(props: ComputePassProps): ComputePass {
throw new Error('compute shaders not supported in WebGL');
}
private renderPass: WEBGLRenderPass;
getDefaultRenderPass(): WEBGLRenderPass {
this.renderPass =
this.renderPass ||
this.beginRenderPass({
framebuffer: this.canvasContext.getCurrentFramebuffer()
});
return this.renderPass;
}
/**
* Offscreen Canvas Support: Commit the frame
* https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/commit
* Chrome's offscreen canvas does not require gl.commit
*/
submit(): void {
this.renderPass.endPass();
this.renderPass = null;
// this.canvasContext.commit();
}
}
/** Check if supplied parameter is a WebGLRenderingContext */
function isWebGL(gl: any): boolean {
if (typeof WebGLRenderingContext !== 'undefined' && gl instanceof WebGLRenderingContext) {
return true;
}
if (typeof WebGL2RenderingContext !== 'undefined' && gl instanceof WebGL2RenderingContext) {
return true;
}
// Look for debug contexts, headless gl etc
return Boolean(gl && Number.isFinite(gl._version));
}
/** Check if supplied parameter is a WebGL2RenderingContext */
function isWebGL2(gl: any): boolean {
if (typeof WebGL2RenderingContext !== 'undefined' && gl instanceof WebGL2RenderingContext) {
return true;
}
// Look for debug contexts, headless gl etc
return Boolean(gl && gl._version === 2);
} | the_stack |
import * as path from "path";
import * as fs from "fs";
import * as md5 from "ts-md5";
import { IEntityAnnotationObject } from "../data/IEntityAnnotationObject";
import { IEntityObjectByPosition } from "../data/IEntityObjectByPosition";
import { IPartOfSpeechTagObjectByPosition } from "../data/IPartOfSpeechTagObjectByPosition";
import { ITextIntentSequenceLabelObjectByPosition} from "../data/ITextIntentSequenceLabelObjectByPosition";
import { Label } from "../label_structure/Label";
import { DictionaryMapUtility } from "../data_structure/DictionaryMapUtility";
import { StructValueCount } from "../label_structure/StructValueCount";
import { CryptoUtility } from "./CryptoUtility";
export class Utility {
public static toPrintDebuggingLogToConsole: boolean = false;
public static toPrintDetailedDebuggingLogToConsole: boolean = false;
public static toObfuscateLabelTextInReportUtility: boolean = true;
public static epsilon: number = 0.0001;
public static epsilonRough: number = 0.01;
public static readonly LanguageTokenPunctuationDelimiters: string[] = [
// ---- // ---- "\0",
// ---- // ---- "\u0001",
// ---- // ---- "\u0002",
// ---- // ---- "\u0003",
// ---- // ---- "\u0004",
// ---- // ---- "\u0005",
// ---- // ---- "\u0006",
// ---- // ---- "\a",
// ---- // ---- "\b",
// ---- // ---- "\t",
// ---- // ---- "\n",
// ---- // ---- "\v",
// ---- // ---- "\f",
// ---- // ---- "\r",
// ---- // ---- "\u000E",
// ---- // ---- "\u000F",
// ---- // ---- "\u0010",
// ---- // ---- "\u0011",
// ---- // ---- "\u0012",
// ---- // ---- "\u0013",
// ---- // ---- "\u0014",
// ---- // ---- "\u0015",
// ---- // ---- "\u0016",
// ---- // ---- "\u0017",
// ---- // ---- "\u0018",
// ---- // ---- "\u0019",
// ---- // ---- "\u001A",
// ---- // ---- "\u001B",
// ---- // ---- "\u001C",
// ---- // ---- "\u001D",
// ---- // ---- "\u001E",
// ---- // ---- "\u001F",
// ---- // ---- " ",
"!",
"\"",
"#",
"$",
"%",
"&",
"\"",
"(",
")",
"*",
"+",
",",
"-",
".",
"/",
":",
";",
"<",
"=",
">",
"?",
"@",
"[",
"\\",
"]",
"^",
"`",
"{",
"|",
"}",
"~",
// ---- // ---- "\u007F"
];
public static readonly LanguageTokenPunctuationDelimitersSet: Set<string> =
new Set(Utility.LanguageTokenPunctuationDelimiters);
public static readonly LanguageTokenPunctuationReplacementDelimiters: string[] = [
// ---- // ---- " \0 ",
// ---- // ---- " \u0001 ",
// ---- // ---- " \u0002 ",
// ---- // ---- " \u0003 ",
// ---- // ---- " \u0004 ",
// ---- // ---- " \u0005 ",
// ---- // ---- " \u0006 ",
// ---- // ---- " \a ",
// ---- // ---- " \b ",
// ---- // ---- " \t ",
// ---- // ---- " \n ",
// ---- // ---- " \v ",
// ---- // ---- " \f ",
// ---- // ---- " \r ",
// ---- // ---- " \u000E ",
// ---- // ---- " \u000F ",
// ---- // ---- " \u0010 ",
// ---- // ---- " \u0011 ",
// ---- // ---- " \u0012 ",
// ---- // ---- " \u0013 ",
// ---- // ---- " \u0014 ",
// ---- // ---- " \u0015 ",
// ---- // ---- " \u0016 ",
// ---- // ---- " \u0017 ",
// ---- // ---- " \u0018 ",
// ---- // ---- " \u0019 ",
// ---- // ---- " \u001A ",
// ---- // ---- " \u001B ",
// ---- // ---- " \u001C ",
// ---- // ---- " \u001D ",
// ---- // ---- " \u001E ",
// ---- // ---- " \u001F ",
// ---- // ---- " ",
" ! ",
" \" ",
" # ",
" $ ",
" % ",
" & ",
" \" ",
" ( ",
" ) ",
" * ",
" + ",
" , ",
" - ",
" . ",
" / ",
" : ",
" ; ",
" < ",
" = ",
" > ",
" ? ",
" @ ",
" [ ",
" \\ ",
" ] ",
" ^ ",
" ` ",
" { ",
" | ",
" } ",
" ~ ",
// ---- // ---- " \u007F "
];
public static readonly LanguageTokenSpaceDelimiters: string[] = [
"\0",
"\u0001",
"\u0002",
"\u0003",
"\u0004",
"\u0005",
"\u0006",
"\a",
"\b",
"\t",
"\n",
"\v",
"\f",
"\r",
"\u000E",
"\u000F",
"\u0010",
"\u0011",
"\u0012",
"\u0013",
"\u0014",
"\u0015",
"\u0016",
"\u0017",
"\u0018",
"\u0019",
"\u001A",
"\u001B",
"\u001C",
"\u001D",
"\u001E",
"\u001F",
" ",
// ---- // ---- "!",
// ---- // ---- "\"",
// ---- // ---- "#",
// ---- // ---- "$",
// ---- // ---- "%",
// ---- // ---- "&",
// ---- // ---- "\"",
// ---- // ---- "(",
// ---- // ---- ")",
// ---- // ---- "*",
// ---- // ---- "+",
// ---- // ---- ",",
// ---- // ---- "-",
// ---- // ---- ".",
// ---- // ---- "/",
// ---- // ---- ":",
// ---- // ---- ";",
// ---- // ---- "<",
// ---- // ---- "=",
// ---- // ---- ">",
// ---- // ---- "?",
// ---- // ---- "@",
// ---- // ---- "[",
// ---- // ---- "\\",
// ---- // ---- "]",
// ---- // ---- "^",
// ---- // ---- "`",
// ---- // ---- "{",
// ---- // ---- "|",
// ---- // ---- "}",
// ---- // ---- "~",
"\u007F",
];
public static LanguageTokenSpaceDelimitersSet: Set<string> =
new Set(Utility.LanguageTokenSpaceDelimiters);
public static incrementKeyValueNumberMap<K>(
keyNumberMap: Map<K, number>,
key: K,
value: number = 1): void {
if (keyNumberMap.has(key)) {
const existedValue: number = keyNumberMap.get(key) as number;
keyNumberMap.set(key, existedValue + value);
} else {
keyNumberMap.set(key, value);
}
}
public static addKeyValueToNumberMapSet<K>(
keyNumberMapSet: Map<K, Set<number>>,
key: K,
value: number): void {
if (keyNumberMapSet.has(key)) {
const numberSet: Set<number> = keyNumberMapSet.get(key) as Set<number>;
numberSet.add(value);
} else {
const numberSet: Set<number> = new Set<number>();
numberSet.add(value);
keyNumberMapSet.set(key, numberSet);
}
}
public static addToNumberMapSet<K>(
keyNumberMapSetTo: Map<K, Set<number>>,
keyNumberMapSetFrom: Map<K, Set<number>>,
limit: number = -1): void {
for (const key of keyNumberMapSetFrom.keys()) {
const valueSetFrom: Set<number> =
keyNumberMapSetFrom.get(key) as Set<number>;
for (const value of valueSetFrom) {
const valueSetTo: Set<number> =
keyNumberMapSetTo.get(key) as Set<number>;
if (limit >= 0) {
const existingNumbers: number =
valueSetTo.size;
if (existingNumbers < limit) {
valueSetTo.add(value);
}
} else {
valueSetTo.add(value);
}
}
}
}
public static addKeyValueToNumberMapArray<K>(
keyNumberMapArray: Map<K, number[]>,
key: K,
value: number): void {
if (keyNumberMapArray.has(key)) {
const numberArray: number[] = keyNumberMapArray.get(key) as number[];
numberArray.push(value);
} else {
const numberArray: number[] = [];
numberArray.push(value);
keyNumberMapArray.set(key, numberArray);
}
}
public static addToNumberMapArray<K>(
keyNumberMapArrayTo: Map<K, number[]>,
keyNumberMapArrayFrom: Map<K, number[]>,
limit: number = -1): void {
for (const key of keyNumberMapArrayFrom.keys()) {
const valueArrayFrom: number[] =
keyNumberMapArrayFrom.get(key) as number[];
for (const value of valueArrayFrom) {
const valueArrayTo: number[] =
keyNumberMapArrayTo.get(key) as number[];
if (limit >= 0) {
const existingNumbers: number =
valueArrayTo.length;
if (existingNumbers < limit) {
valueArrayTo.push(value);
}
} else {
valueArrayTo.push(value);
}
}
}
}
public static mapToJsonSerialization<K, V>(map: Map<K, V>): string {
return Utility.jsonStringify([...map]);
}
public static jsonSerializationToMap<K, V>(jsonString: string): Map<K, V> {
const jsonParsedObject: any = JSON.parse(jsonString);
return new Map<K, V>(jsonParsedObject);
}
public static setToJsonSerialization<T>(set: Set<T>): string {
return Utility.jsonStringify([...set]);
}
public static jsonSerializationToSet<T>(jsonString: string): Set<T> {
return new Set<T>(JSON.parse(jsonString));
}
public static arrayToJsonSerialization<T>(set: T[]): string {
return Utility.jsonStringify([...set]);
}
public static jsonSerializationToArray<T>(jsonString: string): T[] {
return new Array<T>(JSON.parse(jsonString));
}
public static stringMapToObject<V>(stringMap: Map<string, V>): any {
const obj = Object.create(null);
for (const [key, value] of stringMap) {
// ---- We don't escape the key '__proto__'
// ---- which can cause problems on older engines
obj[key] = value;
}
return obj;
}
public static objectToStringMap<V>(obj: any): Map<string, V> {
const stringMap = new Map<string, V>();
for (const key of Object.keys(obj)) {
stringMap.set(key, obj[key]);
}
return stringMap;
}
public static stringMapToJson<V>(stringMap: Map<string, V>): string {
return Utility.jsonStringify(Utility.stringMapToObject<V>(stringMap));
}
public static jsonToStringMap<V>(jsonString: string): Map<string, V> {
return Utility.objectToStringMap<V>(JSON.parse(jsonString));
}
public static stringMapSetToObject<V>(stringMapSet: Map<string, Set<V>>): any {
const obj = Object.create(null);
for (const key of stringMapSet.keys()) {
const value: Set<V> = stringMapSet.get(key) as Set<V>;
obj[key] = Utility.setToJsonSerialization(value);
}
return obj;
}
public static objectToStringMapSet<V>(obj: any): Map<string, Set<V>> {
const stringMapSet = new Map<string, Set<V>>();
for (const key of Object.keys(obj)) {
// ---- Utility.debuggingLog(`key=${key}`);
// ---- Utility.debuggingLog(`value=${obj[key]}`);
const valueSet: Set<V> = Utility.jsonSerializationToSet(obj[key]);
stringMapSet.set(key, valueSet);
}
return stringMapSet;
}
public static stringMapArrayToObject<V>(stringMapArray: Map<string, V[]>): any {
const obj = Object.create(null);
for (const key of stringMapArray.keys()) {
const value: V[] = stringMapArray.get(key) as V[];
obj[key] = Utility.arrayToJsonSerialization(value);
}
return obj;
}
public static objectToStringMapArray<V>(obj: any): Map<string, V[]> {
const stringMapArray = new Map<string, V[]>();
for (const key of Object.keys(obj)) {
const valueArray: V[] = Utility.jsonSerializationToArray(obj[key]);
stringMapArray.set(key, valueArray);
}
return stringMapArray;
}
public static stringMapSetToJson<V>(stringMapSet: Map<string, Set<V>>): string {
return Utility.jsonStringify(Utility.stringMapSetToObject<V>(stringMapSet));
}
public static jsonToStringMapSet<V>(jsonString: string): Map<string, Set<V>> {
return Utility.objectToStringMapSet<V>(JSON.parse(jsonString));
}
public static stringMapArrayToJson<V>(stringMapArray: Map<string, V[]>): string {
return Utility.jsonStringify(Utility.stringMapArrayToObject<V>(stringMapArray));
}
public static jsonToStringMapArray<V>(jsonString: string): Map<string, V[]> {
return Utility.objectToStringMapArray<V>(JSON.parse(jsonString));
}
// ---- NOTE-REFERENCE ----
// https://github.com/v8/v8/blob/085fed0fb5c3b0136827b5d7c190b4bd1c23a23e/src/base
// /utils/random-number-generator.h#L102
public static getXorshift128plusState0(): number {
return Utility.xorshift128plusState0;
}
public static getXorshift128plusState1(): number {
return Utility.xorshift128plusState1;
}
public static rngSeedXorshift128plus(
newState0: number,
newState1: number,
inputRngBurninIterations: number = -1): void {
if (inputRngBurninIterations < 0) {
inputRngBurninIterations = Utility.rngBurninIterations;
}
Utility.xorshift128plusState0 = newState0;
Utility.xorshift128plusState1 = newState1;
for (let i: number = 0; i < inputRngBurninIterations; i++) {
Utility.rngNextXorshift128plusDirect();
}
Utility.rngBurninDone = true;
}
public static rngNextXorshift128plusDirect(): number {
let s1: number = Utility.xorshift128plusState0;
const s0: number = Utility.xorshift128plusState1;
Utility.xorshift128plusState0 = s0;
Utility.xorshift128plusState0 %= Number.MAX_SAFE_INTEGER;
// tslint:disable-next-line: no-bitwise
s1 ^= s1 << 23;
// tslint:disable-next-line: no-bitwise
s1 ^= s1 >> 17;
// tslint:disable-next-line: no-bitwise
s1 ^= s0;
// tslint:disable-next-line: no-bitwise
s1 ^= s0 >> 26;
Utility.xorshift128plusState1 = s1;
Utility.xorshift128plusState1 %= Number.MAX_SAFE_INTEGER;
let result: number = Utility.xorshift128plusState0 + Utility.xorshift128plusState1;
result %= Number.MAX_SAFE_INTEGER;
return result;
}
public static rngNextXorshift128plus(
inputRngBurninIterations: number = -1): number {
if (inputRngBurninIterations < 0) {
inputRngBurninIterations = Utility.rngBurninIterations;
}
if (!Utility.rngBurninDone) {
for (let i: number = 0; i < inputRngBurninIterations; i++) {
Utility.rngNextXorshift128plusDirect();
}
Utility.rngBurninDone = true;
}
return Utility.rngNextXorshift128plusDirect();
}
public static rngNextXorshift128plusWithNumberStates(): number {
if (!Utility.rngBurninDone) {
for (let i: number = 0; i < Utility.rngBurninIterations; i++) {
Utility.rngNextXorshift128plusDirect();
}
Utility.rngBurninDone = true;
}
return Utility.rngNextXorshift128plusDirect();
}
public static rngNextXorshift128plusFloatWithNumberStates(): number {
const result: number = Utility.rngNextXorshift128plus();
return (result / Number.MAX_SAFE_INTEGER);
}
public static seedRandomNumberGeneratorWithNumberStates(
newState0: number,
newState1: number,
inputRngBurninIterationsForBigInt: number = -1): void {
Utility.rngSeedXorshift128plus(
newState0,
newState1,
inputRngBurninIterationsForBigInt);
}
public static getRandomNumberWithNumberStates(): number {
return Utility.rngNextXorshift128plusFloatWithNumberStates();
}
public static getRandomIntWithNumberStates(limit: number): number {
return Utility.getRandomIntFromIntLimitWithNumberStates(limit);
}
public static getRandomIntFromFloatLimitWithNumberStates(limit: number): number {
let randomFloat: number =
Utility.getRandomNumberWithNumberStates() * limit;
if (randomFloat >= limit) {
randomFloat = limit - Utility.epsilon;
}
const randomInt: number = Math.floor(
randomFloat);
return randomInt;
}
public static getRandomIntFromIntLimitWithNumberStates(limit: number): number {
let randomInt: number = Math.floor(
Utility.getRandomNumberWithNumberStates() * Math.floor(limit));
if (randomInt >= limit) {
randomInt = limit - 1;
}
return randomInt;
}
public static getXorshift128plusState0WithBigIntStates(): bigint {
return Utility.xorshift128plusState0BigInt;
}
public static getXorshift128plusState1WithBigIntStates(): bigint {
return Utility.xorshift128plusState1BigInt;
}
public static getXorshift128plusCycleWithBigIntStates(): bigint {
return Utility.xorshift128plusCycleBigInt;
}
public static getXorshift128plusCycleFloatWithBigIntStates(): number {
return Utility.xorshift128plusCycleFloatBigInt;
}
public static rngSeedXorshift128plusWithBigIntStatesWithNumberArguments(
newState0: number,
newState1: number,
inputRngBurninIterationsForBigInt: number = -1): void {
if (inputRngBurninIterationsForBigInt < 0) {
inputRngBurninIterationsForBigInt = Utility.rngBurninIterationsForBigInt;
}
Utility.xorshift128plusState0BigInt = BigInt(newState0);
Utility.xorshift128plusState1BigInt = BigInt(newState1);
for (let i: number = 0; i < inputRngBurninIterationsForBigInt; i++) {
Utility.rngNextXorshift128plusWithBigIntStatesDirect();
}
Utility.rngBurninDoneForBigInt = true;
}
public static rngSeedXorshift128plusWithBigIntStates(
newState0BigInt: bigint,
newState1BigInt: bigint,
newCycleBigInt: bigint,
inputRngBurninIterationsForBigInt: number = -1): void {
if (inputRngBurninIterationsForBigInt < 0) {
inputRngBurninIterationsForBigInt = Utility.rngBurninIterationsForBigInt;
}
Utility.xorshift128plusState0BigInt = newState0BigInt;
Utility.xorshift128plusState1BigInt = newState1BigInt;
Utility.xorshift128plusCycleBigInt = newCycleBigInt;
for (let i: number = 0; i < inputRngBurninIterationsForBigInt; i++) {
Utility.rngNextXorshift128plusWithBigIntStatesDirect();
}
Utility.rngBurninDoneForBigInt = true;
}
public static rngNextXorshift128plusWithBigIntStatesDirect(): bigint {
let s1: bigint =
Utility.xorshift128plusState0BigInt;
const s0: bigint =
Utility.xorshift128plusState1BigInt;
Utility.xorshift128plusState0BigInt =
s0;
// tslint:disable-next-line: no-bitwise
Utility.xorshift128plusState0BigInt %=
Utility.xorshift128plusCycleBigInt;
// tslint:disable-next-line: no-bitwise
s1 ^= s1 << Utility.bigint23;
// tslint:disable-next-line: no-bitwise
s1 ^= s1 >> Utility.bigint17;
// tslint:disable-next-line: no-bitwise
s1 ^= s0;
// tslint:disable-next-line: no-bitwise
s1 ^= s0 >> Utility.bigint26;
Utility.xorshift128plusState1BigInt =
s1;
// tslint:disable-next-line: no-bitwise
Utility.xorshift128plusState1BigInt %=
Utility.xorshift128plusCycleBigInt;
let result: bigint =
Utility.xorshift128plusState0BigInt + Utility.xorshift128plusState1BigInt;
// tslint:disable-next-line: no-bitwise
result %= Utility.xorshift128plusCycleBigInt;
return result;
}
public static rngNextXorshift128plusWithBigIntStates(): bigint {
if (!Utility.rngBurninDoneForBigInt) {
for (let i: number = 0; i < Utility.rngBurninIterationsForBigInt; i++) {
Utility.rngNextXorshift128plusWithBigIntStatesDirect();
}
Utility.rngBurninDoneForBigInt = true;
}
return Utility.rngNextXorshift128plusWithBigIntStatesDirect();
}
public static rngNextXorshift128plusFloatWithBigIntStates(): number {
const resultBigInt: bigint = Utility.rngNextXorshift128plusWithBigIntStates();
const resultNumber: number = Number(resultBigInt);
return (resultNumber / Utility.xorshift128plusCycleFloatBigInt);
}
public static seedRandomNumberGenerator(
newState0: number,
newState1: number,
inputRngBurninIterationsForBigInt: number = -1): void {
Utility.rngSeedXorshift128plusWithBigIntStatesWithNumberArguments(
newState0,
newState1,
inputRngBurninIterationsForBigInt);
}
public static getRandomNumber(): number {
return Utility.rngNextXorshift128plusFloatWithBigIntStates();
}
public static getRandomInt(limit: number): number {
return Utility.getRandomIntFromIntLimit(limit);
}
public static getRandomIntFromFloatLimit(limit: number): number {
let randomInt: number = Math.floor(
Utility.getRandomNumber() * limit);
if (randomInt >= limit) {
randomInt = limit - Utility.epsilon;
}
return randomInt;
}
public static getRandomIntFromIntLimit(limit: number): number {
let randomInt: number = Math.floor(
Utility.getRandomNumber() * Math.floor(limit));
if (randomInt >= limit) {
randomInt = limit - 1;
}
return randomInt;
}
public static shuffle<T>(array: T[]): T[] {
let currentIndex = array.length;
let randomIndex: number = -1;
// ---- While there remains elements to shuffle.
while (currentIndex > 0) {
// ---- Pick a remaining element.
randomIndex =
Utility.getRandomInt(currentIndex);
currentIndex--;
// ---- And swap it with the current element.
const temporaryValue: T = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
}
public static validateGenericArrayPairEquality<T>(
genericArrayFirst: T[],
genericArraySecond: T[],
throwIfNotLegal: boolean = true): boolean {
if ((genericArrayFirst == null) && (genericArraySecond == null)) {
return true;
}
if (genericArrayFirst == null) {
if (throwIfNotLegal) {
Utility.debuggingThrow("genericArrayFirst==null");
}
return false;
}
if (genericArraySecond == null) {
if (throwIfNotLegal) {
Utility.debuggingThrow("genericArraySecond==null");
}
return false;
}
if (genericArrayFirst.length !== genericArraySecond.length) {
if (throwIfNotLegal) {
Utility.debuggingThrow(
`genericArrayFirst.length|${genericArrayFirst.length}|` +
`!=genericArraySecond.length|${ genericArraySecond.length}|`);
}
return false;
}
for (let index = 0; index < genericArrayFirst.length; index++) {
const first: T = genericArrayFirst[index];
const second: T = genericArraySecond[index];
if (first !== second) {
if (throwIfNotLegal) {
Utility.debuggingThrow(
`index=${index}` +
`first|${first}|` +
`!=second|${second}|`);
}
return false;
}
}
return true;
}
public static validateGenericSetPairEquality<T>(
genericSetFirst: Set<T>,
genericSetSecond: Set<T>,
throwIfNotLegal: boolean = true): boolean {
if ((genericSetFirst == null) && (genericSetSecond == null)) {
return true;
}
if (genericSetFirst == null) {
if (throwIfNotLegal) {
Utility.debuggingThrow("genericSetFirst==null");
}
return false;
}
if (genericSetSecond == null) {
if (throwIfNotLegal) {
Utility.debuggingThrow("genericSetSecond==null");
}
return false;
}
const genericSetFirstLength: number = Utility.getSetLength(genericSetFirst);
const genericSetSecondLength: number = Utility.getSetLength(genericSetSecond);
if (genericSetFirstLength !== genericSetSecondLength) {
if (throwIfNotLegal) {
Utility.debuggingThrow(
`genericSetFirstLength|${genericSetFirstLength}|` +
`!=genericSetSecondLength|${genericSetSecondLength}|`);
}
return false;
}
for (const key of genericSetFirst) {
if (key) {
if (genericSetSecond.has(key)) {
continue;
} else {
if (throwIfNotLegal) {
Utility.debuggingThrow(
`key|${key}| is in genericSetFirst, but not in genericSetSecond`);
}
return false;
}
}
}
for (const key of genericSetSecond) {
if (key) {
if (genericSetFirst.has(key)) {
continue;
} else {
if (throwIfNotLegal) {
Utility.debuggingThrow(
`key|${key}| is in genericSetSecond, but not in genericSetFirst`);
}
return false;
}
}
}
return true;
}
public static validateStringArrayPairEquality(
stringArrayFirst: string[],
stringArraySecond: string[],
throwIfNotLegal: boolean = true): boolean {
if ((stringArrayFirst == null) && (stringArraySecond == null)) {
return true;
}
if (stringArrayFirst == null) {
if (throwIfNotLegal) {
Utility.debuggingThrow("stringArrayFirst==null");
}
return false;
}
if (stringArraySecond == null) {
if (throwIfNotLegal) {
Utility.debuggingThrow("stringArraySecond==null");
}
return false;
}
if (stringArrayFirst.length !== stringArraySecond.length) {
if (throwIfNotLegal) {
Utility.debuggingThrow(
`stringArrayFirst.length|${stringArrayFirst.length}|` +
`!=stringArraySecond.length|${ stringArraySecond.length}|`);
}
return false;
}
for (let index = 0; index < stringArrayFirst.length; index++) {
const first: string = stringArrayFirst[index];
const second: string = stringArraySecond[index];
if (first !== second) {
if (throwIfNotLegal) {
Utility.debuggingThrow(
`index=${index}` +
`first|${first}|` +
`!=second|${second}|`);
}
return false;
}
}
return true;
}
public static validateStringSetPairEquality(
stringSetFirst: Set<string>,
stringSetSecond: Set<string>,
throwIfNotLegal: boolean = true): boolean {
if ((stringSetFirst == null) && (stringSetSecond == null)) {
return true;
}
if (stringSetFirst == null) {
if (throwIfNotLegal) {
Utility.debuggingThrow("stringSetFirst==null");
}
return false;
}
if (stringSetSecond == null) {
if (throwIfNotLegal) {
Utility.debuggingThrow("stringSetSecond==null");
}
return false;
}
const stringSetFirstLength: number = Utility.getSetLength(stringSetFirst);
const stringSetSecondLength: number = Utility.getSetLength(stringSetSecond);
if (stringSetFirstLength !== stringSetSecondLength) {
if (throwIfNotLegal) {
Utility.debuggingThrow(
`stringSetFirstLength|${stringSetFirstLength}|` +
`!=stringSetSecondLength|${stringSetSecondLength}|`);
}
return false;
}
for (const key of stringSetFirst) {
if (key) {
if (stringSetSecond.has(key)) {
continue;
} else {
if (throwIfNotLegal) {
Utility.debuggingThrow(
`key|${key}| is in stringSetFirst, but not in stringSetSecond`);
}
return false;
}
}
}
for (const key of stringSetSecond) {
if (key) {
if (stringSetFirst.has(key)) {
continue;
} else {
if (throwIfNotLegal) {
Utility.debuggingThrow(
`key|${key}| is in stringSetSecond, but not in stringSetFirst`);
}
return false;
}
}
}
return true;
}
public static loadLabelTextScoreFile(
filename: string,
labelColumnIndex: number = 0,
textColumnIndex: number = 1,
weightColumnIndex: number = -1,
scoreColumnBeginIndex: number = 2,
numberOfScoreColumns: number = -1,
identifierColumnIndex: number = -1,
predictedLabelColumnIndex: number = -1,
revisedTextColumnIndex: number = -1,
lineIndexToStart: number = 0,
columnDelimiter: string = "\t",
rowDelimiter: string = "\n",
encoding: string = "utf8",
lineIndexToEnd: number = -1): {
"labels": string[],
"texts": string[],
"weights": number[],
"identifiers": string[],
"scoreArrays": number[][],
"predictedLabels": string[],
"revisedTexts": string[] } {
if (encoding == null) {
encoding = "utf8";
}
const fileContent: string = Utility.loadFile(
filename,
encoding);
return Utility.loadLabelTextScoreContent(
fileContent,
labelColumnIndex,
textColumnIndex,
weightColumnIndex,
scoreColumnBeginIndex,
numberOfScoreColumns,
identifierColumnIndex,
predictedLabelColumnIndex,
revisedTextColumnIndex,
lineIndexToStart,
columnDelimiter,
rowDelimiter,
lineIndexToEnd);
}
public static loadLabelTextScoreContent(
fileContent: string,
labelColumnIndex: number = 0,
textColumnIndex: number = 1,
weightColumnIndex: number = -1,
scoreColumnBeginIndex: number = 2,
numberOfScoreColumns: number = 0,
identifierColumnIndex: number = -1,
predictedLabelColumnIndex: number = -1,
revisedTextColumnIndex: number = -1,
lineIndexToStart: number = 0,
columnDelimiter: string = "\t",
rowDelimiter: string = "\n",
lineIndexToEnd: number = -1): {
"labels": string[],
"texts": string[],
"weights": number[],
"identifiers": string[],
"scoreArrays": number[][],
"predictedLabels": string[],
"revisedTexts": string[] } {
if (labelColumnIndex < 0) {
labelColumnIndex = 0;
}
if (textColumnIndex < 0) {
textColumnIndex = 1;
}
if (scoreColumnBeginIndex < 0) {
scoreColumnBeginIndex = 2;
}
if (lineIndexToStart < 0) {
lineIndexToStart = 0;
}
if (columnDelimiter == null) {
columnDelimiter = "\t";
}
if (rowDelimiter == null) {
rowDelimiter = "\n";
}
const labels: string[] = [];
const texts: string[] = [];
const weights: number[] = [];
const identifiers: string[] = [];
const scoreArrays: number[][] = [];
const predictedLabels: string[] = [];
const revisedTexts: string[] = [];
const fileLines: string[] = Utility.split(fileContent, rowDelimiter);
for (let lineIndex = lineIndexToStart;
(lineIndex < fileLines.length) && ((lineIndexToEnd < 0) || (lineIndex < lineIndexToEnd));
lineIndex++) {
// ---------------------------------------------------------------
const line: string = fileLines[lineIndex].trim();
if (Utility.isEmptyString(line)) {
continue;
}
const lineColumns: string[] = Utility.split(line, columnDelimiter);
// ---------------------------------------------------------------
const label: string = lineColumns[labelColumnIndex];
// ---------------------------------------------------------------
const text: string = lineColumns[textColumnIndex];
if (Utility.isEmptyString(label)) {
Utility.debuggingThrow(
`LINE - INDEX=${lineIndex}, label is empty` +
`, lineColumns.length=${lineColumns.length}` +
`, label=$${label}$` +
`, text=$${text}$` +
`, line=$${line}$`);
}
// ---------------------------------------------------------------
let weight: number = 1;
if (weightColumnIndex >= 0) {
weight = +lineColumns[weightColumnIndex];
}
// ---------------------------------------------------------------
let identifier: string = lineIndex.toString();
if (identifierColumnIndex >= 0) {
identifier = lineColumns[identifierColumnIndex];
}
let predictedLabel: string = "";
if (predictedLabelColumnIndex >= 0) {
predictedLabel = lineColumns[predictedLabelColumnIndex];
}
let revisedText: string = "";
if (revisedTextColumnIndex >= 0) {
revisedText = lineColumns[revisedTextColumnIndex];
}
// ---------------------------------------------------------------
if (numberOfScoreColumns <= 0) {
numberOfScoreColumns = lineColumns.length - scoreColumnBeginIndex;
}
if ((numberOfScoreColumns <= 0) || (numberOfScoreColumns > (lineColumns.length - scoreColumnBeginIndex))) {
Utility.debuggingThrow(
`(numberOfScoreColumns<=0)||(numberOfScoreColumns|${numberOfScoreColumns}|>lineColumns.length|${lineColumns.length}|))` +
`,scoreColumnBeginIndex=${scoreColumnBeginIndex}` +
`,line=${line}`);
}
const scoreArray: number[] = [];
let scoreIndex = scoreColumnBeginIndex;
for (let i: number = 0; i < numberOfScoreColumns; i++) {
const score: number = +lineColumns[scoreIndex++];
scoreArray.push(score);
}
// ---------------------------------------------------------------
// {
// Utility.debuggingLog(
// `LINE - INDEX=${lineIndex}` +
// `, lineColumns.length=${lineColumns.length}` +
// `, label=$${label}$` +
// `, text=$${text}$` +
// `, line=$${line}$`);
//
// }
// ---------------------------------------------------------------
labels.push(label);
texts.push(text);
weights.push(weight);
identifiers.push(identifier);
scoreArrays.push(scoreArray);
predictedLabels.push(predictedLabel);
revisedTexts.push(revisedText);
// ---------------------------------------------------------------
}
return { labels, texts, weights, identifiers, scoreArrays, predictedLabels, revisedTexts };
}
public static loadLabelUtteranceColumnarFile(
filename: string,
labelColumnIndex: number = 0,
textColumnIndex: number = 1,
weightColumnIndex: number = -1,
lineIndexToStart: number = 0,
columnDelimiter: string = "\t",
rowDelimiter: string = "\n",
encoding: string = "utf8",
lineIndexToEnd: number = -1): { "intents": string[], "utterances": string[], "weights": number[] } {
const intentsTextsWeights: { "intents": string[], "texts": string[], "weights": number[] } =
Utility.loadLabelTextColumnarFile(
filename,
labelColumnIndex,
textColumnIndex,
weightColumnIndex,
lineIndexToStart,
columnDelimiter,
rowDelimiter,
encoding,
lineIndexToEnd);
const intents: string[] = intentsTextsWeights.intents;
const utterances: string[] = intentsTextsWeights.texts;
const weights: number[] = intentsTextsWeights.weights;
const intentsUtterancesWeights: { "intents": string[], "utterances": string[], "weights": number[] } = {
intents,
utterances,
weights };
return intentsUtterancesWeights;
}
public static loadLabelTextColumnarFile(
filename: string,
labelColumnIndex: number = 0,
textColumnIndex: number = 1,
weightColumnIndex: number = -1,
lineIndexToStart: number = 0,
columnDelimiter: string = "\t",
rowDelimiter: string = "\n",
encoding: string = "utf8",
lineIndexToEnd: number = -1): { "intents": string[], "texts": string[], "weights": number[] } {
if (encoding == null) {
encoding = "utf8";
}
const fileContent: string = Utility.loadFile(
filename,
encoding);
return Utility.loadLabelTextColumnarContent(
fileContent,
labelColumnIndex,
textColumnIndex,
weightColumnIndex,
lineIndexToStart,
columnDelimiter,
rowDelimiter,
lineIndexToEnd);
}
public static loadLabelUtteranceColumnarContent(
fileContent: string,
labelColumnIndex: number = 0,
textColumnIndex: number = 1,
weightColumnIndex: number = -1,
lineIndexToStart: number = 0,
columnDelimiter: string = "\t",
rowDelimiter: string = "\n",
encoding: string = "utf8",
lineIndexToEnd: number = -1): { "intents": string[], "utterances": string[], "weights": number[] } {
const intentsTextsWeights: { "intents": string[], "texts": string[], "weights": number[] } =
Utility.loadLabelTextColumnarContent(
fileContent,
labelColumnIndex,
textColumnIndex,
weightColumnIndex,
lineIndexToStart,
columnDelimiter,
rowDelimiter,
lineIndexToEnd);
const intents: string[] = intentsTextsWeights.intents;
const utterances: string[] = intentsTextsWeights.texts;
const weights: number[] = intentsTextsWeights.weights;
const intentsUtterancesWeights: { "intents": string[], "utterances": string[], "weights": number[] } = {
intents,
utterances,
weights };
return intentsUtterancesWeights;
}
public static loadLabelTextColumnarContent(
fileContent: string,
labelColumnIndex: number = 0,
textColumnIndex: number = 1,
weightColumnIndex: number = -1,
lineIndexToStart: number = 0,
columnDelimiter: string = "\t",
rowDelimiter: string = "\n",
lineIndexToEnd: number = -1):
{ "intents": string[], "texts": string[], "weights": number[] } {
if (labelColumnIndex < 0) {
labelColumnIndex = 0;
}
if (textColumnIndex < 0) {
textColumnIndex = 1;
}
if (lineIndexToStart < 0) {
lineIndexToStart = 0;
}
if (columnDelimiter == null) {
columnDelimiter = "\t";
}
if (rowDelimiter == null) {
rowDelimiter = "\n";
}
const intents: string[] = [];
const texts: string[] = [];
const weights: number[] = [];
const fileLines: string[] = Utility.split(fileContent, rowDelimiter);
for (let lineIndex = lineIndexToStart;
(lineIndex < fileLines.length) && ((lineIndexToEnd < 0) || (lineIndex < lineIndexToEnd));
lineIndex++) {
const line: string = fileLines[lineIndex].trim();
if (Utility.isEmptyString(line)) {
continue;
}
const lineColumns: string[] = Utility.split(line, columnDelimiter);
const intent: string = lineColumns[labelColumnIndex];
const text: string = lineColumns[textColumnIndex];
let weight: number = 1;
if (weightColumnIndex >= 0) {
weight = +lineColumns[weightColumnIndex];
}
if (Utility.isEmptyString(intent)) {
Utility.debuggingThrow(
`LINE - INDEX=${lineIndex}, intent is empty` +
`, lineColumns.length=${lineColumns.length}` +
`, intent=$${intent}$` +
`, text=$${text}$` +
`, weight=$${weight}$` +
`, line=$${line}$`);
}
if (Utility.isEmptyString(text)) {
Utility.debuggingThrow(
`LINE - INDEX=${lineIndex}, text is empty` +
`, lineColumns.length=${lineColumns.length}` +
`, intent=$${intent}$` +
`, text=$${text}$` +
`, weight=$${weight}$` +
`, line=$${line}$`);
}
// {
// Utility.debuggingLog(
// `LINE - INDEX=${lineIndex}` +
// `, lineColumns.length=${lineColumns.length}` +
// `, intent=$${intent}$` +
// `, text=$${text}$` +
// `, weight=$${weight}$` +
// `, line=$${line}$`);
//
// }
intents.push(intent);
texts.push(text);
weights.push(weight);
}
return { intents, texts, weights };
}
public static processUtteranceEntityTsv(
lines: string[],
utterancesEntitiesMap: Map<string, Array<[string, number, number]>>,
utterancesEntitiesPredictedMap: Map<string, Array<[string, number, number]>>,
utteranceIndex: number = 2,
entitiesIndex: number = 0,
entitiesPredictedIndex: number = 1): boolean {
if (utteranceIndex < 0) {
Utility.debuggingThrow(`utteranceIndex|${utteranceIndex}| < 0`);
}
lines.forEach((line: string) => {
const items: string[] = line.split("\t");
if (utteranceIndex >= items.length) {
Utility.debuggingThrow(`utteranceIndex|${utteranceIndex}| >= items.length|${items.length}|`);
}
let utterance: string = items[utteranceIndex] ? items[utteranceIndex] : "";
let entities: string = "";
if ((entitiesIndex >= 0) && (entitiesIndex < items.length)) {
entities = items[entitiesIndex] ? items[entitiesIndex] : "";
}
let entitiesPredicted: string = "";
if ((entitiesPredictedIndex >= 0) && (entitiesPredictedIndex < items.length)) {
entitiesPredicted = items[entitiesPredictedIndex] ? items[entitiesPredictedIndex] : "";
}
entities = entities.trim();
utterance = utterance.trim();
entitiesPredicted = entitiesPredicted.trim();
const entityArray: string[] = entities.split(",");
for (const entityEntry of entityArray) {
Utility.addToEntitiesUtteranceStructure(
utterance,
entityEntry.trim(),
utterancesEntitiesMap);
}
const entityPredictedArray: string[] = entitiesPredicted.split(",");
for (const entityEntryPredicted of entityPredictedArray) {
Utility.addToEntitiesUtteranceStructure(
utterance,
entityEntryPredicted.trim(),
utterancesEntitiesPredictedMap);
}
});
return true;
}
public static addToEntitiesUtteranceStructure(
utterance: string,
entityEntry: string,
utterancesEntitiesMap: Map<string, Array<[string, number, number]>>) {
const entityComponentArray: string[] = entityEntry.split(";");
const entity: [string, number, number] = [
entityComponentArray[0],
+entityComponentArray[1],
+entityComponentArray[1]];
if (!utterancesEntitiesMap.has(utterance)) {
utterancesEntitiesMap.set(utterance, new Array<[string, number, number]>());
}
const existingEntities: Array<[string, number, number]> =
utterancesEntitiesMap.get(utterance) as Array<[string, number, number]>;
existingEntities.push(entity);
}
public static processUtteranceMultiLabelTsv(
lines: string[],
utteranceLabelsMap: Map<string, Set<string>>,
utterancesLabelsPredictedMap: Map<string, Set<string>>,
utteranceLabelDuplicateMap: Map<string, Set<string>>,
utteranceLabelDuplicatePredictedMap: Map<string, Set<string>>,
utteranceIndex: number = 2,
labelsIndex: number = 0,
labelsPredictedIndex: number = 1): boolean {
if (utteranceIndex < 0) {
Utility.debuggingThrow(`utteranceIndex|${utteranceIndex}| < 0`);
}
lines.forEach((line: string) => {
const items: string[] = line.split("\t");
if (utteranceIndex >= items.length) {
Utility.debuggingThrow(`utteranceIndex|${utteranceIndex}| >= items.length|${items.length}|`);
}
let utterance: string = items[utteranceIndex] ? items[utteranceIndex] : "";
let labels: string = "";
if ((labelsIndex >= 0) && (labelsIndex < items.length)) {
labels = items[labelsIndex] ? items[labelsIndex] : "";
}
let labelsPredicted: string = "";
if ((labelsPredictedIndex >= 0) && (labelsPredictedIndex < items.length)) {
labelsPredicted = items[labelsPredictedIndex] ? items[labelsPredictedIndex] : "";
}
labels = labels.trim();
utterance = utterance.trim();
labelsPredicted = labelsPredicted.trim();
const labelArray: string[] = labels.split(",");
for (const label of labelArray) {
Utility.addToMultiLabelUtteranceStructure(
utterance,
label.trim(),
utteranceLabelsMap,
utteranceLabelDuplicateMap);
}
const labelPredictedArray: string[] = labelsPredicted.split(",");
for (const labelPredicted of labelPredictedArray) {
Utility.addToMultiLabelUtteranceStructure(
utterance,
labelPredicted.trim(),
utterancesLabelsPredictedMap,
utteranceLabelDuplicatePredictedMap);
}
});
return true;
}
public static addToMultiLabelUtteranceStructure(
utterance: string,
label: string,
utteranceLabelsMap: Map<string, Set<string>>,
utteranceLabelDuplicateMap: Map<string, Set<string>>) {
const existingLabels: Set<string> = utteranceLabelsMap.get(utterance) as Set<string>;
if (existingLabels) {
if (!Utility.addIfNewLabel(label, existingLabels)) {
DictionaryMapUtility.insertStringPairToStringIdStringSetNativeMap(
utterance,
label,
utteranceLabelDuplicateMap);
}
} else {
utteranceLabelsMap.set(utterance, new Set<string>([label]));
}
}
public static addIfNewLabel(newLabel: string, labels: Set<string>): boolean {
if (labels.has(newLabel)) {
return false;
}
labels.add(newLabel);
return true;
}
public static addIfNewLabelToArray(newLabel: string, labels: string[]): boolean {
for (const label of labels) {
if (label === newLabel) {
return false;
}
}
labels.push(newLabel);
return true;
}
public static reverseUniqueKeyedArrayInMap(input: Map<string, Set<string>>): Map<string, Set<string>> {
const reversed: Map<string, Set<string>> = new Map<string, Set<string>>();
for (const key of input.keys()) {
if (key) {
const keyedSet: Set<string> = input.get(key) as Set<string>;
for (const keyedSetElement of keyedSet) {
if (reversed.has(keyedSetElement)) {
(reversed.get(keyedSetElement) as Set<string>).add(key);
} else {
reversed.set(keyedSetElement, new Set<string>([key]));
}
}
}
}
return reversed;
}
public static reverseUniqueKeyedArrayInDictionary(input: {[id: string]: string[]}): {[id: string]: string[]} {
const reversed: {[id: string]: string[]} = {};
for (const key in input) {
if (key) {
const keyedArray: string[] = input[key];
for (const keyedArrayElement of keyedArray) {
if (keyedArrayElement in reversed) {
reversed[keyedArrayElement].push(key);
} else {
reversed[keyedArrayElement] = [key];
}
}
}
}
return reversed;
}
public static storeDataArraysToTsvFile(
outputFilename: string,
outputEvaluationReportDataArrays: string[][],
outputDataArraryHeaders: string[] = [],
columnDelimiter: string = "\t",
recordDelimiter: string = "\n",
encoding: string = "utf8"): string {
if (Utility.isEmptyString(outputFilename)) {
Utility.debuggingThrow(
"outputFilename is empty");
}
if (Utility.isEmptyStringArrays(outputEvaluationReportDataArrays)) {
return "";
// ---- Utility.debuggingThrow(
// ---- "outputEvaluationReportDataArrays is empty");
}
const outputLines: string[] = [];
if (!Utility.isEmptyStringArray(outputDataArraryHeaders)) {
const outputLine: string = outputDataArraryHeaders.join(columnDelimiter);
outputLines.push(outputLine);
}
for (const outputEvaluationReportDataArray of outputEvaluationReportDataArrays) {
const outputLine: string = outputEvaluationReportDataArray.join(columnDelimiter);
outputLines.push(outputLine);
}
const outputContent: string = outputLines.join(recordDelimiter);
try {
return Utility.dumpFile(outputFilename, `${outputContent}${recordDelimiter}`, encoding);
} catch (e) {
Utility.debuggingThrow(
`storeTsvFile() cannout create an output file: ${outputFilename}, EXCEPTION=${e}`);
return "";
}
}
public static convertDataArraysToIndexedHtmlTable(
tableDescription: string,
outputEvaluationReportDataArrays: any[][],
outputDataArraryHeaders: string[] = [],
indentCumulative: string = " ",
indent: string = " "): string {
const outputLines: string[] = [];
if (!Utility.isEmptyString(tableDescription)) {
outputLines.push(indentCumulative + `<p><strong>${tableDescription}</strong></p>`);
}
outputLines.push(indentCumulative + "<table class=\"table\">");
if (!Utility.isEmptyStringArray(outputDataArraryHeaders)) {
outputLines.push(indentCumulative + indent + "<tr>");
outputLines.push(indentCumulative + indent + indent + "<th>");
outputLines.push(indentCumulative + indent + indent + "No");
outputLines.push(indentCumulative + indent + indent + "</th>");
for (const headerEntry of outputDataArraryHeaders) {
outputLines.push(indentCumulative + indent + indent + "<th>");
outputLines.push(indentCumulative + indent + indent + headerEntry);
outputLines.push(indentCumulative + indent + indent + "</th>");
}
outputLines.push(indentCumulative + indent + "<tr>");
}
if (!Utility.isEmptyStringArrays(outputEvaluationReportDataArrays)) {
let index: number = 0;
for (const outputEvaluationReportDataArray of outputEvaluationReportDataArrays) {
outputLines.push(indentCumulative + indent + "<tr>");
outputLines.push(indentCumulative + indent + indent + "<td>");
outputLines.push(indentCumulative + indent + indent + index++);
outputLines.push(indentCumulative + indent + indent + "</td>");
for (const dataEntry of outputEvaluationReportDataArray) {
outputLines.push(indentCumulative + indent + indent + "<td>");
outputLines.push(indentCumulative + indent + indent + dataEntry);
outputLines.push(indentCumulative + indent + indent + "</td>");
}
outputLines.push(indentCumulative + indent + "</tr>");
}
}
outputLines.push(indentCumulative + "</table>");
const outputContent: string = outputLines.join("\n");
return outputContent;
}
public static convertDataArraysToHtmlTable(
tableDescription: string,
outputEvaluationReportDataArrays: any[][],
outputDataArraryHeaders: string[] = [],
indentCumulative: string = " ",
indent: string = " "): string {
const outputLines: string[] = [];
if (!Utility.isEmptyString(tableDescription)) {
outputLines.push(indentCumulative + `<p><strong>${tableDescription}</strong></p>`);
}
outputLines.push(indentCumulative + "<table class=\"table\">");
if (!Utility.isEmptyStringArray(outputDataArraryHeaders)) {
outputLines.push(indentCumulative + indent + "<tr>");
for (const headerEntry of outputDataArraryHeaders) {
outputLines.push(indentCumulative + indent + indent + "<th>");
outputLines.push(indentCumulative + indent + indent + headerEntry);
outputLines.push(indentCumulative + indent + indent + "</th>");
}
outputLines.push(indentCumulative + indent + "<tr>");
}
if (Utility.isEmptyStringArrays(outputEvaluationReportDataArrays)) {
for (const outputEvaluationReportDataArray of outputEvaluationReportDataArrays) {
outputLines.push(indentCumulative + indent + "<tr>");
for (const dataEntry of outputEvaluationReportDataArray) {
outputLines.push(indentCumulative + indent + indent + "<td>");
outputLines.push(indentCumulative + indent + indent + dataEntry);
outputLines.push(indentCumulative + indent + indent + "</td>");
}
outputLines.push(indentCumulative + indent + "</tr>");
}
}
outputLines.push(indentCumulative + "</table>");
const outputContent: string = outputLines.join("\n");
return outputContent;
}
public static convertMapSetToHtmlTable(
tableDescription: string,
outputEvaluationMapSet: Map<any, Set<any>>,
outputDataArraryHeaders: string[] = [],
indentCumulative: string = " ",
indent: string = " "): string {
const outputLines: string[] = [];
if (!Utility.isEmptyString(tableDescription)) {
outputLines.push(indentCumulative + `<p><strong>${tableDescription}</strong></p>`);
}
outputLines.push(indentCumulative + "<table class=\"table\">");
if (!Utility.isEmptyStringArray(outputDataArraryHeaders)) {
outputLines.push(indentCumulative + indent + "<tr>");
for (const headerEntry of outputDataArraryHeaders) {
outputLines.push(indentCumulative + indent + indent + "<th>");
outputLines.push(indentCumulative + indent + indent + headerEntry);
outputLines.push(indentCumulative + indent + indent + "</th>");
}
outputLines.push(indentCumulative + indent + "<tr>");
}
if (!DictionaryMapUtility.isEmptyAnyKeyGenericSetMap<any>(outputEvaluationMapSet)) {
for (const outputEvaluationMapSetEntry of outputEvaluationMapSet) {
const key: any = outputEvaluationMapSetEntry[0];
for (const valueEntry of outputEvaluationMapSetEntry[1]) {
outputLines.push(indentCumulative + indent + "<tr>");
outputLines.push(indentCumulative + indent + indent + "<td>");
outputLines.push(indentCumulative + indent + indent + key);
outputLines.push(indentCumulative + indent + indent + "</td>");
outputLines.push(indentCumulative + indent + indent + "<td>");
outputLines.push(indentCumulative + indent + indent + valueEntry);
outputLines.push(indentCumulative + indent + indent + "</td>");
outputLines.push(indentCumulative + indent + "</tr>");
}
}
}
outputLines.push(indentCumulative + "</table>");
const outputContent: string = outputLines.join("\n");
return outputContent;
}
public static convertMapSetToIndexedHtmlTable(
tableDescription: string,
outputEvaluationMapSet: Map<any, Set<any>>,
outputDataArraryHeaders: string[] = [],
indentCumulative: string = " ",
indent: string = " "): string {
const outputLines: string[] = [];
if (!Utility.isEmptyString(tableDescription)) {
outputLines.push(indentCumulative + `<p><strong>${tableDescription}</strong></p>`);
}
outputLines.push(indentCumulative + "<table class=\"table\">");
if (!Utility.isEmptyStringArray(outputDataArraryHeaders)) {
outputLines.push(indentCumulative + indent + "<tr>");
outputLines.push(indentCumulative + indent + indent + "<th>");
outputLines.push(indentCumulative + indent + indent + "No");
outputLines.push(indentCumulative + indent + indent + "</th>");
for (const headerEntry of outputDataArraryHeaders) {
outputLines.push(indentCumulative + indent + indent + "<th>");
outputLines.push(indentCumulative + indent + indent + headerEntry);
outputLines.push(indentCumulative + indent + indent + "</th>");
}
outputLines.push(indentCumulative + indent + "<tr>");
}
if (!DictionaryMapUtility.isEmptyAnyKeyGenericSetMap<any>(outputEvaluationMapSet)) {
let index: number = 0;
for (const outputEvaluationMapSetEntry of outputEvaluationMapSet) {
const key: any = outputEvaluationMapSetEntry[0];
for (const valueSetEntry of outputEvaluationMapSetEntry[1]) {
outputLines.push(indentCumulative + indent + "<tr>");
outputLines.push(indentCumulative + indent + indent + "<td>");
outputLines.push(indentCumulative + indent + indent + index++);
outputLines.push(indentCumulative + indent + indent + "</td>");
outputLines.push(indentCumulative + indent + indent + "<td>");
outputLines.push(indentCumulative + indent + indent + key);
outputLines.push(indentCumulative + indent + indent + "</td>");
outputLines.push(indentCumulative + indent + indent + "<td>");
outputLines.push(indentCumulative + indent + indent + valueSetEntry);
outputLines.push(indentCumulative + indent + indent + "</td>");
outputLines.push(indentCumulative + indent + "</tr>");
}
}
}
outputLines.push(indentCumulative + "</table>");
const outputContent: string = outputLines.join("\n");
return outputContent;
}
public static luUtterancesToEntityAnnotatedCorpusTypes(
luUtterances: ITextIntentSequenceLabelObjectByPosition[],
utteranceReconstructionDelimiter: string = " ",
defaultEntityTag: string = "O",
defaultPartOfSpeechTag: string = "",
useIntentForId: boolean = false): IEntityAnnotationObject {
const ids: string[] = [];
const wordArrays: string[][] = [];
const partOfSpeechTagArrays: string[][] = [];
const entityTagArrays: string[][] = [];
const numberInstances = luUtterances.length;
for (let index: number = 0; index < numberInstances; index++) {
const luUtterance: ITextIntentSequenceLabelObjectByPosition = luUtterances[index];
const text: string = luUtterance.text;
const intent: string = luUtterance.intent;
const entities: IEntityObjectByPosition[] = luUtterance.entities;
const partOfSpeechTags: IPartOfSpeechTagObjectByPosition[] = luUtterance.partOfSpeechTags;
if (useIntentForId) {
ids.push(intent);
} else {
ids.push(index.toString());
}
const wordArray: string[] = Utility.splitByPunctuation(
text,
utteranceReconstructionDelimiter);
wordArrays.push(wordArray);
const numberWords: number = wordArrays.length;
const entityTagArray: string[] = [];
if (!Utility.isEmptyArray(entities)) {
let utteranceCurrentIndex: number = 0;
for (let wordIndex: number = 0; wordIndex < numberWords; wordIndex++) {
const wordCurrent: string = wordArray[wordIndex];
const currentWordInUtteranceIndex: number = text.substr(utteranceCurrentIndex).indexOf(wordCurrent);
const currentWordInUtteranceIndexEnd: number = currentWordInUtteranceIndex + wordCurrent.length;
let wordEntityTag: string = defaultEntityTag;
for (const entity of entities) {
const entityTag: string = entity.entity;
const entityStartPos: number = entity.startPos;
const entityEndPos: number = entity.endPos;
if ((currentWordInUtteranceIndex >= entityStartPos) &&
(currentWordInUtteranceIndexEnd <= entityEndPos)) {
wordEntityTag = entityTag;
break;
}
}
entityTagArray.push(wordEntityTag);
utteranceCurrentIndex = currentWordInUtteranceIndexEnd;
}
}
entityTagArrays.push(entityTagArray);
const partOfSpeechTagArray: string[] = [];
if (!Utility.isEmptyArray(partOfSpeechTags)) {
let utteranceCurrentIndex: number = 0;
for (let wordIndex: number = 0; wordIndex < numberWords; wordIndex++) {
const wordCurrent: string = wordArray[wordIndex];
const currentWordInUtteranceIndex: number = text.substr(utteranceCurrentIndex).indexOf(wordCurrent);
const currentWordInUtteranceIndexEnd: number = currentWordInUtteranceIndex + wordCurrent.length;
let wordPartOfSpeechTag: string = defaultPartOfSpeechTag;
for (const partOfSpeechTag of partOfSpeechTags) {
const partOfSpeechTagString: string = partOfSpeechTag.partOfSpeechTag;
const partOfSpeechStartPos: number = partOfSpeechTag.startPos;
const partOfSpeechEndPos: number = partOfSpeechTag.endPos;
if ((currentWordInUtteranceIndex >= partOfSpeechStartPos) &&
(currentWordInUtteranceIndexEnd <= partOfSpeechEndPos)) {
wordPartOfSpeechTag = partOfSpeechTagString;
break;
}
}
partOfSpeechTagArray.push(wordPartOfSpeechTag);
utteranceCurrentIndex = currentWordInUtteranceIndexEnd;
}
}
partOfSpeechTagArrays.push(partOfSpeechTagArray);
}
return {ids, wordArrays, partOfSpeechTagArrays, entityTagArrays};
}
public static entityAnnotatedCorpusTypesToEntityAnnotatedCorpusUtterances(
entityAnnotatedCorpusTypes: IEntityAnnotationObject,
includePartOfSpeechTagTagAsEntities: boolean = true,
utteranceReconstructionDelimiter: string = " ",
defaultEntityTag: string = "O",
useIdForIntent: boolean = true): ITextIntentSequenceLabelObjectByPosition[] {
if (Utility.isEmptyString(utteranceReconstructionDelimiter)) {
utteranceReconstructionDelimiter = " ";
}
const utteranceReconstructionDelimiterLength: number = utteranceReconstructionDelimiter.length;
const ids: string[] = entityAnnotatedCorpusTypes.ids;
const wordArrays: string[][] = entityAnnotatedCorpusTypes.wordArrays;
const partOfSpeechTagArrays: string[][] = entityAnnotatedCorpusTypes.partOfSpeechTagArrays;
const entityTagArrays: string[][] = entityAnnotatedCorpusTypes.entityTagArrays;
if (Utility.isEmptyStringArray(ids)) {
Utility.debuggingThrow("ids is empty");
}
if (Utility.isEmptyArray(wordArrays)) {
Utility.debuggingThrow("wordArrays is empty");
}
if (includePartOfSpeechTagTagAsEntities) {
if (Utility.isEmptyArray(partOfSpeechTagArrays)) {
Utility.debuggingThrow("partOfSpeechTagArrays is empty");
}
}
if (Utility.isEmptyArray(entityTagArrays)) {
Utility.debuggingThrow("entityTagArrays is empty");
}
const numberInstances: number = ids.length;
if (wordArrays.length !== numberInstances) {
Utility.debuggingThrow(
`wordArrays.length|${wordArrays.length}|!==numberInstances|${numberInstances}|`);
}
if (includePartOfSpeechTagTagAsEntities) {
if (partOfSpeechTagArrays.length !== numberInstances) {
Utility.debuggingThrow(`partOfSpeechTagArrays.length|${partOfSpeechTagArrays.length}|!==numberInstances|${numberInstances}|`);
}
}
if (entityTagArrays.length !== numberInstances) {
Utility.debuggingThrow(
`entityTagArrays.length|${entityTagArrays.length}|!==numberInstances|${numberInstances}|`);
}
const weight: number = 1;
const luUtterances: ITextIntentSequenceLabelObjectByPosition[] = [];
for (let index: number = 0; index < numberInstances; index++) {
let intent = "";
const id: string = ids[index];
if (useIdForIntent) {
intent = id;
}
const wordArray: string[] = wordArrays[index];
const numberWords: number = wordArray.length;
let partOfSpeechTagArray: string[] = [];
if (includePartOfSpeechTagTagAsEntities) {
partOfSpeechTagArray = partOfSpeechTagArrays[index];
if (partOfSpeechTagArray.length !== numberWords) {
Utility.debuggingThrow(
`partOfSpeechTagArray.length|${partOfSpeechTagArray.length}|!==numberWords|${numberWords}|`);
}
}
const entityTagArray: string[] = entityTagArrays[index];
if (entityTagArray.length !== numberWords) {
Utility.debuggingThrow(
`entityTagArray.length|${entityTagArray.length}|!==numberWords|${numberWords}|`);
}
const text: string = wordArray.join(utteranceReconstructionDelimiter);
const entities: IEntityObjectByPosition[] = [];
{
let currentUtteranceBeginIndex: number = 0;
for (let wordIndex: number = 0; wordIndex < numberWords; wordIndex++) {
const word: string = wordArray[wordIndex];
const wordLength: number = word.length;
const currentUtteranceEndIndex: number = currentUtteranceBeginIndex + wordLength;
{
const entityTag = entityTagArray[wordIndex];
if (entityTag !== defaultEntityTag) {
const entityStructure: IEntityObjectByPosition = {
entity: entityTag,
startPos: currentUtteranceBeginIndex,
endPos: currentUtteranceEndIndex,
};
entities.push(entityStructure);
}
}
currentUtteranceBeginIndex = currentUtteranceEndIndex + utteranceReconstructionDelimiterLength;
}
}
const partOfSpeechTags: IPartOfSpeechTagObjectByPosition[] = [];
if (includePartOfSpeechTagTagAsEntities) {
let currentUtteranceBeginIndex: number = 0;
for (let wordIndex: number = 0; wordIndex < numberWords; wordIndex++) {
const word: string = wordArray[wordIndex];
const wordLength: number = word.length;
const currentUtteranceEndIndex: number = currentUtteranceBeginIndex + wordLength;
const partOfSpeechTag: string = partOfSpeechTagArray[wordIndex];
const partOfSpeechStructure: IPartOfSpeechTagObjectByPosition = {
partOfSpeechTag,
startPos: currentUtteranceBeginIndex,
endPos: currentUtteranceEndIndex,
};
partOfSpeechTags.push(partOfSpeechStructure);
currentUtteranceBeginIndex = currentUtteranceEndIndex + utteranceReconstructionDelimiterLength;
}
}
const luUtterance: ITextIntentSequenceLabelObjectByPosition = {
entities,
partOfSpeechTags,
intent,
text,
weight,
};
luUtterances.push(luUtterance);
}
return luUtterances;
}
public static loadEntityAnnotatedCorpusFile(
filename: string,
lineIndexToStart: number = 0,
columnDelimiter: string = ",",
rowDelimiter: string = "\n",
encoding: string = "utf8",
lineIndexToEnd: number = -1): IEntityAnnotationObject {
if (encoding == null) {
encoding = "utf8";
}
const fileContent: string = Utility.loadFile(
filename,
encoding);
return Utility.loadEntityAnnotatedCorpusContent(
fileContent,
lineIndexToStart,
columnDelimiter,
rowDelimiter,
lineIndexToEnd);
}
public static loadEntityAnnotatedCorpusContent(
fileContent: string,
lineIndexToStart: number = 1,
columnDelimiter: string = ",",
rowDelimiter: string = "\n",
lineIndexToEnd: number = -1): IEntityAnnotationObject {
if (lineIndexToStart < 0) {
lineIndexToStart = 0;
}
if (columnDelimiter == null) {
columnDelimiter = ",";
}
if (rowDelimiter == null) {
rowDelimiter = "\n";
}
const ids: string[] = [];
const wordArrays: string[][] = [];
const partOfSpeechTagArrays: string[][] = [];
const entityTagArrays: string[][] = [];
let currentId: string = "";
let currentWordArray: string[] = [];
let currentPartOfSpeechTagArray: string[] = [];
let currentTagArray: string[] = [];
let isFirst: boolean = true;
const fileLines: string[] = Utility.split(fileContent, rowDelimiter);
for (let lineIndex = lineIndexToStart;
(lineIndex < fileLines.length) && ((lineIndexToEnd < 0) || (lineIndex < lineIndexToEnd));
lineIndex++) {
const line: string = fileLines[lineIndex].trim();
if (Utility.isEmptyString(line)) {
continue;
}
const lineColumns: string[] = Utility.splitStringWithColumnDelimitersFilteredByQuotingDelimiters(
line,
columnDelimiter,
"\"");
if (lineColumns.length !== 4) {
Utility.debuggingThrow(
`lineColumns.length|${lineColumns.length}|!=4` +
`,line=$${line}$` +
`,lineColumns=$${Utility.jsonStringify(lineColumns)}$`);
}
const id: string = lineColumns[0];
const word: string = lineColumns[1];
const partOfSpeechTag: string = lineColumns[2];
const entityTag: string = lineColumns[3];
const isWordEmpty: boolean = Utility.isEmptyString(word);
if (isWordEmpty) { // ---- NOTE: end of a sentence if the 'word' field is empty.
if (!Utility.isEmptyString(currentId)) {
{
ids.push(currentId);
wordArrays.push(currentWordArray);
partOfSpeechTagArrays.push(currentPartOfSpeechTagArray);
entityTagArrays.push(currentTagArray);
}
currentId = "";
}
continue;
}
const isIdEmpty: boolean = Utility.isEmptyString(id);
if (isIdEmpty) {
currentWordArray.push(word);
currentPartOfSpeechTagArray.push(partOfSpeechTag);
currentTagArray.push(entityTag);
} else {
if (isFirst) { // ---- NOTE: the first line is header, ignore it.
isFirst = false;
} else { // ---- NOTE: continue the current sentence if the 'id' field is empty.
ids.push(currentId);
wordArrays.push(currentWordArray);
partOfSpeechTagArrays.push(currentPartOfSpeechTagArray);
entityTagArrays.push(currentTagArray);
}
{ // ---- NOTE: start a new sentence if the 'id' field is not empty.
currentId = id;
currentWordArray = [word];
currentPartOfSpeechTagArray = [partOfSpeechTag];
currentTagArray = [entityTag];
}
}
}
if (currentWordArray.length > 0) {
if (!Utility.isEmptyString(currentId)) { // ---- NOTE: the very last sentence!
ids.push(currentId);
wordArrays.push(currentWordArray);
partOfSpeechTagArrays.push(currentPartOfSpeechTagArray);
entityTagArrays.push(currentTagArray);
}
}
return {ids, wordArrays, partOfSpeechTagArrays, entityTagArrays};
}
public static loadBinaryFile(
filename: string): Buffer|null {
Utility.debuggingLog(
`Utility.loadBinaryFile(): filename=${filename}`);
Utility.debuggingLog(
`Utility.loadBinaryFile(): process.cmd()=${process.cwd()}`);
try {
const fileContent: Buffer = fs.readFileSync(filename);
return fileContent;
} catch (e) {
Utility.debuggingThrow(
`Utility.loadBinaryFile(): filename=${filename}, exception=${e}`);
}
return null;
}
public static stringToLineArray(
stringContent: string): string[] {
const lineArray: string[] = Utility.split(stringContent, "\n");
const lineTrimedArray: string[] = lineArray.map((x) => x.trim());
return lineTrimedArray;
}
public static loadFile(
filename: string,
encoding: string = "utf8"): string {
Utility.debuggingLog(
`Utility.loadFile(): filename=${filename}`);
Utility.debuggingLog(
`Utility.loadFile(): process.cmd()=${process.cwd()}`);
try {
const fileContent: string = fs.readFileSync(filename, encoding);
return fileContent;
} catch (error) {
Utility.debuggingThrow(
`Utility.loadFile(): filename=${filename}, exception=${error}`);
}
return "";
}
public static dumpFile(
filename: string,
content: any,
encoding: string = "utf8"): string {
// Utility.debuggingLog(
// `Utility.dumpFile(): filename=${filename}`);
try {
fs.mkdirSync(path.dirname(filename), {recursive: true});
fs.writeFileSync(filename, content, encoding);
} catch (error) {
// ---- NOTE ---- An error occurred
Utility.debuggingThrow(`FAILED to dump a file: filename=${filename}, exception=${error}`);
return "";
}
return filename;
}
public static exists(pathToFileSystemEntry: string): boolean {
return fs.existsSync(pathToFileSystemEntry);
}
public static deleteFile(
filename: string,
ignoreEmptyFilename: boolean = true): string {
// Utility.debuggingLog(
// `Utility.deleteFile(): filename=${filename}`);
return Utility.unlink(filename, ignoreEmptyFilename);
}
public static moveFile(
filename: string, targetDir: string): string {
// Utility.debuggingLog(
// `Utility.moveFile(): filename=${filename}`);
// Utility.debuggingLog(
// `Utility.moveFile(): targetDir=${targetDir}`);
const filebasename: string = path.basename(filename);
const destination: string = path.resolve(targetDir, filebasename);
return Utility.rename(filename, destination);
}
public static unlink(
entryname: string,
ignoreEmptyEntryName: boolean = true): string {
// Utility.debuggingLog(
// `Utility.unlink(): entryname=${entryname}`);
try {
if (Utility.isEmptyString(entryname)) {
if (ignoreEmptyEntryName) {
return "";
}
}
fs.unlinkSync(entryname);
} catch (error) {
// ---- NOTE ---- An error occurred
Utility.debuggingThrow(`FAILED to unlink a entry: entryname=${entryname}, error=${error}`);
return "";
}
return entryname;
}
public static rename(
entryname: string, entrynameNew: string): string {
// Utility.debuggingLog(
// `Utility.rename(): entryname=${entryname}`);
// Utility.debuggingLog(
// `Utility.rename(): entrynameNew=${entrynameNew}`);
try {
fs.renameSync(entryname, entrynameNew);
} catch (error) {
// ---- NOTE ---- An error occurred
Utility.debuggingThrow(`FAILED to rename a entry system entry: entryname=${entrynameNew}, entryname=${entrynameNew}, error=${error}`);
return "";
}
return entryname;
}
public static carefullyAccessStringMap(stringMap: Map<string, number>, key: string): number {
if (stringMap === undefined) {
Utility.debuggingThrow(
"stringMap === undefined");
}
if (!stringMap.has(key)) {
Utility.debuggingThrow(
`FAIL to use a key ${key} to access a stringMap ${DictionaryMapUtility.jsonStringifyStringKeyGenericValueNativeMap(stringMap)}`);
}
const value: number = stringMap.get(key) as number;
return value;
}
public static carefullyAccessStringDictionary(stringMap: {[id: string]: number}, key: string): number {
if (stringMap === undefined) {
Utility.debuggingThrow(
"stringMap === undefined");
}
const value: number = stringMap[key];
if (value === undefined) {
Utility.debuggingThrow(
`FAIL to use a key ${key} to access a stringMap ${Utility.jsonStringify(stringMap)}`);
}
return value;
}
public static carefullyAccessAnyArray(anyArray: any[], index: number): any {
if (anyArray === undefined) {
Utility.debuggingThrow(
"anyArray === undefined");
}
if (index < 0) {
Utility.debuggingThrow(
`index ${index} not in range, anyArray.length=${anyArray.length}`);
}
if (index >= anyArray.length) {
Utility.debuggingThrow(
`index ${index} not in range, anyArray.length=${anyArray.length}`);
}
const value: any = anyArray[index];
if (value === undefined) {
Utility.debuggingThrow(
`FAIL to use a index ${index} to access a anyArray ${Utility.jsonStringify(anyArray)}`);
}
return value;
}
public static carefullyAccessStringArray(stringArray: string[], index: number): string {
if (stringArray === undefined) {
Utility.debuggingThrow(
"stringArray === undefined");
}
if (index < 0) {
Utility.debuggingThrow(
`index ${index} not in range, stringArray.length=${stringArray.length}`);
}
if (index >= stringArray.length) {
Utility.debuggingThrow(
`index ${index} not in range, stringArray.length=${stringArray.length}`);
}
const value: string = stringArray[index];
if (value === undefined) {
Utility.debuggingThrow(
`FAIL to use a index ${index} to access a stringArray ${Utility.jsonStringify(stringArray)}`);
}
return value;
}
public static carefullyAccessNumberArray(numberArray: number[], index: number): number {
if (numberArray === undefined) {
Utility.debuggingThrow(
"numberArray === undefined");
}
if (index < 0) {
Utility.debuggingThrow(
`index ${index} not in range, numberArray.length=${numberArray.length}`);
}
if (index >= numberArray.length) {
Utility.debuggingThrow(
`index ${index} not in range, numberArray.length=${numberArray.length}`);
}
const value: number = numberArray[index];
if (value === undefined) {
Utility.debuggingThrow(
`FAIL to use a index ${index} to access a numberArray ${Utility.jsonStringify(numberArray)}`);
}
return value;
}
public static safeAccessAnyArray(anyArray: any[], index: number): any {
if (anyArray === undefined) {
return undefined;
}
if (index < 0) {
return undefined;
}
if (index >= anyArray.length) {
return undefined;
}
const value: any = anyArray[index];
return value;
}
public static safeAccessStringArray(stringArray: string[], index: number): string|undefined {
if (stringArray === undefined) {
return undefined;
}
if (index < 0) {
return undefined;
}
if (index >= stringArray.length) {
return undefined;
}
const value: string = stringArray[index];
return value;
}
public static safeAccessNumberArray(numberArray: number[], index: number): number|undefined {
if (numberArray === undefined) {
return undefined;
}
if (index < 0) {
return undefined;
}
if (index >= numberArray.length) {
return undefined;
}
const value: number = numberArray[index];
return value;
}
public static canAccessAnyArray(anyArray: any[], index: number): boolean {
if (anyArray === undefined) {
return false;
}
if (index < 0) {
return false;
}
if (index >= anyArray.length) {
return false;
}
const value: any = anyArray[index];
if (value === undefined) {
return false;
}
return true;
}
public static canAccessStringArray(stringArray: string[], index: number): boolean {
if (stringArray === undefined) {
return false;
}
if (index < 0) {
return false;
}
if (index >= stringArray.length) {
return false;
}
const value: string = stringArray[index];
if (value === undefined) {
return false;
}
return true;
}
public static canAccessNumberArray(numberArray: number[], index: number): boolean {
if (numberArray === undefined) {
return false;
}
if (index < 0) {
return false;
}
if (index >= numberArray.length) {
return false;
}
const value: number = numberArray[index];
if (value === undefined) {
return false;
}
return true;
}
public static getObjectMd5Hash(objectValue: object): string|Int32Array {
return Utility.getStringMd5Hash(Utility.jsonStringify(objectValue));
}
public static getStringMd5Hash(feature: string): string | Int32Array {
return md5.Md5.hashStr(feature);
}
public static getPositiveObjectHashCode(objectValue: object): number {
return Math.abs(Utility.getObjectHashCode(objectValue));
}
public static getObjectHashCode(objectValue: object): number {
return Utility.getStringHashCode(Utility.jsonStringify(objectValue).toString());
}
public static getPositiveStringHashCode(feature: string): number {
return Math.abs(Utility.getStringHashCode(feature));
}
public static getStringHashCode(feature: string): number {
let hash: number = 0;
if (!feature) {
return hash;
}
if (feature.length === 0) {
return hash;
}
for (let i: number = 0; i < feature.length; i++) {
const char: number = feature.charCodeAt(i);
// tslint:disable-next-line: no-bitwise
hash = ((hash << 5) - hash) + char;
// tslint:disable-next-line: no-bitwise
hash |= 0; // ---- Convert to 32bit integer
}
return hash;
}
public static isEmptyValueCountPairArray(inputArray: StructValueCount[]): boolean {
return !(inputArray && inputArray.length > 0);
}
public static isEmptyNumberF32I32U8Arrays(inputArray: Float32Array[] | Int32Array[] | Uint8Array[]): boolean {
return !(inputArray && inputArray.length > 0);
}
public static isEmptyNumberF32I32U8Array(inputArray: Float32Array | Int32Array | Uint8Array): boolean {
return !(inputArray && inputArray.length > 0);
}
public static isEmptyGenericArrays<T>(inputArrays: boolean[][]): boolean {
return !(inputArrays && inputArrays.length > 0);
}
public static isEmptyBooleanArrays(inputArrays: boolean[][]): boolean {
return !(inputArrays && inputArrays.length > 0);
}
public static isEmptyNumberArrays(inputArrays: number[][]): boolean {
return !(inputArrays && inputArrays.length > 0);
}
public static isEmptyStringArrays(inputArrays: string[][]): boolean {
return !(inputArrays && inputArrays.length > 0);
}
public static isEmptyArrays(inputArrays: object[][]): boolean {
return !(inputArrays && inputArrays.length > 0);
}
public static isEmptyGenericArray<T>(inputArray: T[]): boolean {
return !(inputArray && inputArray.length > 0);
}
public static isEmptyAnyArray(inputArray: any[]): boolean {
return !(inputArray && inputArray.length > 0);
}
public static isEmptyBooleanArray(inputArray: boolean[]): boolean {
return !(inputArray && inputArray.length > 0);
}
public static isEmptyNumberArray(inputArray: number[]): boolean {
return !(inputArray && inputArray.length > 0);
}
public static isEmptyStringArray(inputArray: string[]): boolean {
return !(inputArray && inputArray.length > 0);
}
public static isEmptyArray(inputArray: object[]): boolean {
return !(inputArray && inputArray.length > 0);
}
public static isEmptyString(input: string): boolean {
return !(input && input.length > 0);
}
public static getSetLength<T>(set: Set<T>): number {
return (set.size);
}
public static getJsonStringified(jsonObject: any, indents: number = 4): string {
return Utility.jsonStringify(jsonObject, null, indents);
}
public static writeAnyJsonifiedToConsoleStdout(outputContents: any) {
const output: string = Utility.jsonStringify(outputContents, null, 2);
Utility.writeAnyLineToConsoleStdout(output);
}
public static writeAnyJsonifiedToConsoleStderr(outputContents: any) {
const output: string = Utility.jsonStringify(outputContents, null, 2);
Utility.writeAnyLineToConsoleStderr(output);
}
public static writeAnyLineToConsoleStdout(outputContents: any) {
Utility.writeAnyToConsoleStdout(outputContents);
Utility.writeStringToConsoleStdout("\n");
}
public static writeAnyLineToConsoleStderr(outputContents: any) {
Utility.writeAnyToConsoleStderr(outputContents);
Utility.writeStringToConsoleStderr("\n");
}
public static writeAnyToConsoleStdout(outputContents: any) {
process.stdout.write(outputContents);
}
public static writeAnyToConsoleStderr(outputContents: any) {
process.stderr.write(outputContents);
}
public static writeStringLineToConsoleStdout(outputContents: string) {
Utility.writeStringToConsoleStdout(outputContents);
Utility.writeStringToConsoleStdout("\n");
}
public static writeStringLineToConsoleStderr(outputContents: string) {
Utility.writeStringToConsoleStderr(outputContents);
Utility.writeStringToConsoleStderr("\n");
}
public static writeStringToConsoleStdout(outputContents: string) {
process.stdout.write(outputContents);
}
public static writeStringToConsoleStderr(outputContents: string) {
process.stderr.write(outputContents);
}
public static resetFlagToPrintDebuggingLogToConsole(flag: boolean) {
Utility.toPrintDebuggingLogToConsole = flag;
}
public static resetFlagToPrintDetailedDebuggingLogToConsole(flag: boolean) {
Utility.toPrintDetailedDebuggingLogToConsole = flag;
}
public static resetFlagToObfuscateLabelTextInReportUtility(flag: boolean) {
Utility.toObfuscateLabelTextInReportUtility = flag;
}
public static debuggingLog(
message: any): string {
const dateTimeString: string = (new Date()).toISOString();
const logMessage: string = `[${dateTimeString}] LOG-MESSAGE: ${Utility.jsonStringify(message)}`;
if (Utility.toPrintDebuggingLogToConsole) {
// eslint-disable-next-line no-console
// tslint:disable-next-line: no-console
console.log(logMessage);
}
return logMessage;
}
public static debuggingLog1(
message: any,
objectArgument0: any): string {
const dateTimeString: string = (new Date()).toISOString();
const logMessage: string =
`[${dateTimeString}] LOG-MESSAGE: ${Utility.jsonStringify(message)}` +
`, argument0=${Utility.jsonStringify(objectArgument0)}`;
if (Utility.toPrintDebuggingLogToConsole) {
// tslint:disable: no-console
// eslint-disable-next-line no-console
console.log(logMessage);
}
return logMessage;
}
public static debuggingLog2(
message: any,
objectArgument0: any,
objectArgument1: any): string {
const dateTimeString: string = (new Date()).toISOString();
const logMessage: string =
`[${dateTimeString}] LOG-MESSAGE: ${Utility.jsonStringify(message)}` +
`, argument0=${Utility.jsonStringify(objectArgument0)}` +
`, argument1=${Utility.jsonStringify(objectArgument1)}`;
if (Utility.toPrintDebuggingLogToConsole) {
// tslint:disable: no-console
// eslint-disable-next-line no-console
console.log(logMessage);
}
return logMessage;
}
public static debuggingLog3(
message: any,
objectArgument0: any,
objectArgument1: any,
objectArgument2: any): string {
const dateTimeString: string = (new Date()).toISOString();
const logMessage: string =
`[${dateTimeString}] LOG-MESSAGE: ${Utility.jsonStringify(message)}` +
`, argument0=${Utility.jsonStringify(objectArgument0)}` +
`, argument1=${Utility.jsonStringify(objectArgument1)}` +
`, argument2=${Utility.jsonStringify(objectArgument2)}`;
if (Utility.toPrintDebuggingLogToConsole) {
// tslint:disable: no-console
// eslint-disable-next-line no-console
console.log(logMessage);
}
return logMessage;
}
// eslint-disable-next-line max-params
public static debuggingLog4(
message: any,
objectArgument0: any,
objectArgument1: any,
objectArgument2: any,
objectArgument3: any): string {
const dateTimeString: string = (new Date()).toISOString();
const logMessage: string =
`[${dateTimeString}] LOG-MESSAGE: ${Utility.jsonStringify(message)}` +
`, argument0=${Utility.jsonStringify(objectArgument0)}` +
`, argument1=${Utility.jsonStringify(objectArgument1)}` +
`, argument2=${Utility.jsonStringify(objectArgument2)}` +
`, argument3=${Utility.jsonStringify(objectArgument3)}`;
if (Utility.toPrintDebuggingLogToConsole) {
// tslint:disable: no-console
// eslint-disable-next-line no-console
console.log(logMessage);
}
return logMessage;
}
public static debuggingNamedLog1(
message: any,
objectArgument0: any,
objectArgumentName0: string = ""): string {
const dateTimeString: string = (new Date()).toISOString();
const logMessage: string =
`[${dateTimeString}] LOG-MESSAGE: ${Utility.jsonStringify(message)}` +
`, ${objectArgumentName0}=${Utility.jsonStringify(objectArgument0)}`;
if (Utility.toPrintDebuggingLogToConsole) {
// tslint:disable: no-console
// eslint-disable-next-line no-console
console.log(logMessage);
}
return logMessage;
}
public static debuggingNamedLog2(
message: any,
objectArgument0: any,
objectArgument1: any,
objectArgumentName0: string = "",
objectArgumentName1: string = ""): string {
const dateTimeString: string = (new Date()).toISOString();
const logMessage: string =
`[${dateTimeString}] LOG-MESSAGE: ${Utility.jsonStringify(message)}` +
`, ${objectArgumentName0}=${Utility.jsonStringify(objectArgument0)}` +
`, ${objectArgumentName1}=${Utility.jsonStringify(objectArgument1)}`;
if (Utility.toPrintDebuggingLogToConsole) {
// tslint:disable: no-console
// eslint-disable-next-line no-console
console.log(logMessage);
}
return logMessage;
}
public static debuggingNamedLog3(
message: any,
objectArgument0: any,
objectArgument1: any,
objectArgument2: any,
objectArgumentName0: string = "",
objectArgumentName1: string = "",
objectArgumentName2: string = ""): string {
const dateTimeString: string = (new Date()).toISOString();
const logMessage: string =
`[${dateTimeString}] LOG-MESSAGE: ${Utility.jsonStringify(message)}` +
`, ${objectArgumentName0}=${Utility.jsonStringify(objectArgument0)}` +
`, ${objectArgumentName1}=${Utility.jsonStringify(objectArgument1)}` +
`, ${objectArgumentName2}=${Utility.jsonStringify(objectArgument2)}`;
if (Utility.toPrintDebuggingLogToConsole) {
// tslint:disable: no-console
// eslint-disable-next-line no-console
console.log(logMessage);
}
return logMessage;
}
// eslint-disable-next-line max-params
public static debuggingNamedLog4(
message: any,
objectArgument0: any,
objectArgument1: any,
objectArgument2: any,
objectArgument3: any,
objectArgumentName0: string = "",
objectArgumentName1: string = "",
objectArgumentName2: string = "",
objectArgumentName3: string = ""): string {
const dateTimeString: string = (new Date()).toISOString();
const logMessage: string =
`[${dateTimeString}] LOG-MESSAGE: ${Utility.jsonStringify(message)}` +
`, ${objectArgumentName0}=${Utility.jsonStringify(objectArgument0)}` +
`, ${objectArgumentName1}=${Utility.jsonStringify(objectArgument1)}` +
`, ${objectArgumentName2}=${Utility.jsonStringify(objectArgument2)}` +
`, ${objectArgumentName3}=${Utility.jsonStringify(objectArgument3)}`;
if (Utility.toPrintDebuggingLogToConsole) {
// tslint:disable: no-console
// eslint-disable-next-line no-console
console.log(logMessage);
}
return logMessage;
}
public static debuggingThrow(
message: any): void {
const dateTimeString: string = (new Date()).toISOString();
const logMessage: string = `[${dateTimeString}] ERROR-MESSAGE: ${Utility.jsonStringify(message)}`;
const error: Error = new Error(logMessage);
const stackTrace: string = error.stack as string;
Utility.debuggingLog(stackTrace);
throw error;
}
public static debuggingThrow1(
message: any,
objectArgument0: any): void {
const dateTimeString: string = (new Date()).toISOString();
const logMessage: string =
`[${dateTimeString}] ERROR-MESSAGE: ${Utility.jsonStringify(message)}` +
`, argument0:${Utility.jsonStringify(objectArgument0)}`;
const error: Error = new Error(logMessage);
const stackTrace: string = error.stack as string;
Utility.debuggingLog(stackTrace);
throw error;
}
public static debuggingThrow2(
message: any,
objectArgument0: any,
objectArgument1: any): void {
const dateTimeString: string = (new Date()).toISOString();
const logMessage: string =
`[${dateTimeString}] ERROR-MESSAGE: ${Utility.jsonStringify(message)}` +
`, argument0:${Utility.jsonStringify(objectArgument0)}` +
`, argument1:${Utility.jsonStringify(objectArgument1)}`;
const error: Error = new Error(logMessage);
const stackTrace: string = error.stack as string;
Utility.debuggingLog(stackTrace);
throw error;
}
public static debuggingThrow3(
message: any,
objectArgument0: any,
objectArgument1: any,
objectArgument2: any): void {
const dateTimeString: string = (new Date()).toISOString();
const logMessage: string =
`[${dateTimeString}] ERROR-MESSAGE: ${Utility.jsonStringify(message)}` +
`, argument0:${Utility.jsonStringify(objectArgument0)}` +
`, argument1:${Utility.jsonStringify(objectArgument1)}` +
`, argument2:${Utility.jsonStringify(objectArgument2)}`;
const error: Error = new Error(logMessage);
const stackTrace: string = error.stack as string;
Utility.debuggingLog(stackTrace);
throw error;
}
// eslint-disable-next-line max-params
public static debuggingThrow4(
message: any,
objectArgument0: any,
objectArgument1: any,
objectArgument2: any,
objectArgument3: any): void {
const dateTimeString: string = (new Date()).toISOString();
const logMessage: string =
`[${dateTimeString}] ERROR-MESSAGE: ${Utility.jsonStringify(message)}` +
`, argument0:${Utility.jsonStringify(objectArgument0)}` +
`, argument1:${Utility.jsonStringify(objectArgument1)}` +
`, argument2:${Utility.jsonStringify(objectArgument2)}` +
`, argument3:${Utility.jsonStringify(objectArgument3)}`;
const error: Error = new Error(logMessage);
const stackTrace: string = error.stack as string;
Utility.debuggingLog(stackTrace);
throw error;
}
public static debuggingNamedThrow1(
message: any,
objectArgument0: any,
objectArgumentName0: string = ""): void {
const dateTimeString: string = (new Date()).toISOString();
const logMessage: string =
`[${dateTimeString}] ERROR-MESSAGE: ${Utility.jsonStringify(message)}` +
`, ${objectArgumentName0}=${Utility.jsonStringify(objectArgument0)}`;
const error: Error = new Error(logMessage);
const stackTrace: string = error.stack as string;
Utility.debuggingLog(stackTrace);
throw error;
}
public static debuggingNamedThrow2(
message: any,
objectArgument0: any,
objectArgument1: any,
objectArgumentName0: string = "",
objectArgumentName1: string = ""): void {
const dateTimeString: string = (new Date()).toISOString();
const logMessage: string =
`[${dateTimeString}] ERROR-MESSAGE: ${Utility.jsonStringify(message)}` +
`, ${objectArgumentName0}=${Utility.jsonStringify(objectArgument0)}` +
`, ${objectArgumentName1}=${Utility.jsonStringify(objectArgument1)}`;
const error: Error = new Error(logMessage);
const stackTrace: string = error.stack as string;
Utility.debuggingLog(stackTrace);
throw error;
}
public static debuggingNamedThrow3(
message: any,
objectArgument0: any,
objectArgument1: any,
objectArgument2: any,
objectArgumentName0: string = "",
objectArgumentName1: string = "",
objectArgumentName2: string = ""): void {
const dateTimeString: string = (new Date()).toISOString();
const logMessage: string =
`[${dateTimeString}] ERROR-MESSAGE: ${Utility.jsonStringify(message)}` +
`, ${objectArgumentName0}=${Utility.jsonStringify(objectArgument0)}` +
`, ${objectArgumentName1}=${Utility.jsonStringify(objectArgument1)}` +
`, ${objectArgumentName2}=${Utility.jsonStringify(objectArgument2)}`;
const error: Error = new Error(logMessage);
const stackTrace: string = error.stack as string;
Utility.debuggingLog(stackTrace);
throw error;
}
// eslint-disable-next-line max-params
public static debuggingNamedThrow4(
message: any,
objectArgument0: any,
objectArgument1: any,
objectArgument2: any,
objectArgument3: any,
objectArgumentName0: string = "",
objectArgumentName1: string = "",
objectArgumentName2: string = "",
objectArgumentName3: string = ""): void {
const dateTimeString: string = (new Date()).toISOString();
const logMessage: string =
`[${dateTimeString}] ERROR-MESSAGE: ${Utility.jsonStringify(message)}` +
`, ${objectArgumentName0}=${Utility.jsonStringify(objectArgument0)}` +
`, ${objectArgumentName1}=${Utility.jsonStringify(objectArgument1)}` +
`, ${objectArgumentName2}=${Utility.jsonStringify(objectArgument2)}` +
`, ${objectArgumentName3}=${Utility.jsonStringify(objectArgument3)}`;
const error: Error = new Error(logMessage);
const stackTrace: string = error.stack as string;
Utility.debuggingLog(stackTrace);
throw error;
}
public static almostEqual(first: number, second: number): boolean {
const almostEqualPercentage: number = Utility.getAlmostEqualPercentage(first, second);
const isAlmostEqual: boolean = almostEqualPercentage < Utility.epsilon;
return isAlmostEqual;
}
public static almostEqualRough(first: number, second: number): boolean {
const almostEqualPercentage: number = Utility.getAlmostEqualPercentage(first, second);
const isAlmostEqual: boolean = almostEqualPercentage < Utility.epsilonRough;
return isAlmostEqual;
}
public static getAlmostEqualPercentage(first: number, second: number): number {
if (second === 0) {
return Math.abs(first);
}
const almostEqualPercentage: number = Math.abs((first - second) / second);
return almostEqualPercentage;
}
public static almostEqualAbsolute(first: number, second: number): boolean {
const almostEqualAbsolute: number = Utility.getAlmostEqualAbsolute(first, second);
const isAlmostEqualAbsolute: boolean = almostEqualAbsolute < Utility.epsilon;
return isAlmostEqualAbsolute;
}
public static almostEqualAbsoluteRough(first: number, second: number): boolean {
const almostEqualAbsolute: number = Utility.getAlmostEqualAbsolute(first, second);
const isAlmostEqualAbsolute: boolean = almostEqualAbsolute < Utility.epsilonRough;
return isAlmostEqualAbsolute;
}
public static getAlmostEqualAbsolute(first: number, second: number): number {
const almostEqualAbsolute: number = Math.abs(first - second);
return almostEqualAbsolute;
}
public static toBoolean(value: any): boolean {
if (typeof(value) === "string") {
value = (value as string).toLowerCase();
}
switch (value) {
case true:
return true;
case "true":
return true;
case 1:
return true;
case "1":
return true;
case "on":
return true;
case "yes":
return true;
case "positive":
return true;
case false:
return false;
case "false":
return false;
case 0:
return false;
case "0":
return false;
case "off":
return false;
case "no":
return false;
case "negative":
return false;
default:
return false;
}
}
public static iterableIteratorToArray<K>(iterator: IterableIterator<K>): K[] {
const anArray: K[] = [];
for (const element of iterator) {
anArray.push(element);
}
return anArray;
}
public static cleanStringOnTabs(input: string, replacement: string = " "): string {
return input.replace(/[\t]+/gm, replacement);
}
public static cleanStringOnSpaces(input: string, replacement: string = " "): string {
return input.replace(/[\r\n\t]+/gm, replacement);
}
public static cleanStringOnSpaceCommas(input: string, replacement: string = " "): string {
return input.replace(/[\r\n\t,]+/gm, replacement);
}
public static splitByPunctuation(
input: string,
splitDelimiter: string = " ",
toRemoveEmptyElements: boolean = true,
delimiters: string[] = Utility.LanguageTokenPunctuationDelimiters,
replacementDelimiters: string[] = Utility.LanguageTokenPunctuationReplacementDelimiters): string[] {
if (Utility.isEmptyStringArray(delimiters)) {
delimiters = Utility.LanguageTokenPunctuationDelimiters;
}
if (Utility.isEmptyStringArray(replacementDelimiters)) {
delimiters = Utility.LanguageTokenPunctuationReplacementDelimiters;
}
const numberDelimiters: number = delimiters.length;
for (let i = 0; i < numberDelimiters; i++) {
input = input.replace(delimiters[i], replacementDelimiters[i]);
}
let result: string[] = Utility.split(input, splitDelimiter);
if (toRemoveEmptyElements) {
result = result.filter((element: string) => {
return (element && (element !== ""));
});
}
return result;
}
public static splitStringWithCommaDelimitersFilteredByDoubleQuotes(input: string): string[] {
return Utility.splitStringWithColumnDelimitersFilteredByQuotingDelimiters(
input,
",",
"\"");
/** ---- NOTE-FOR-REFERENCE ----
* const splittedStrings: string[] = [];
* const commaIndexIndexes: number[] =
* Utility.getCommaIndexesFilteredByDoubleQuotes(input);
* let index: number = 0;
* for (const commaIndex of commaIndexIndexes) {
* splittedStrings.push(input.substring(index, commaIndex));
* index = commaIndex + 1;
* }
* splittedStrings.push(input.substring(index));
* return splittedStrings;
*/
}
public static splitStringWithColumnDelimitersFilteredByQuotingDelimiters(
input: string,
delimiter: string,
delimiterQuoting: string): string[] {
const splittedStrings: string[] = [];
const commaIndexIndexes: number[] = Utility.getColumnDelimiterIndexesFilteredByQuotingDelimiters(
input,
delimiter,
delimiterQuoting);
let index: number = 0;
for (const commaIndex of commaIndexIndexes) {
splittedStrings.push(input.substring(index, commaIndex));
index = commaIndex + 1;
}
splittedStrings.push(input.substring(index));
return splittedStrings;
}
public static getCommaIndexesFilteredByDoubleQuotes(input: string): number[] {
return Utility.getColumnDelimiterIndexesFilteredByQuotingDelimiters(
input,
",",
"\"");
/** ---- NOTE-FOR-REFERENCE ----
* const commaIndexes: number[] = Utility.getCommaIndexes(input);
* return Utility.filterOrderedNumberArrayFromOrderedRanges(
* commaIndexes,
* Utility.getDoubleQuoteIndexPairs(input));
*/
}
public static getColumnDelimiterIndexesFilteredByQuotingDelimiters(
input: string,
delimiter: string,
delimiterQuoting: string): number[] {
const delimiterIndexes: number[] = Utility.getDelimiterIndexes(input, delimiter);
return Utility.filterOrderedNumberArrayFromOrderedRanges(
delimiterIndexes,
Utility.getDelimiterIndexPairs(input, delimiterQuoting));
}
public static filterOrderedNumberArrayFromOrderedRanges(
anArray: number[],
filteringRanges: number[][]): number[] {
const filteredArray: number[] = [];
let indexArray: number = 0;
const arrayLength: number = anArray.length;
let indexfilteringRanges: number = 0;
const filteringRangesLength: number = filteringRanges.length;
while (indexArray < arrayLength) {
const element: number = anArray[indexArray++];
let filtered: boolean = false;
while (indexfilteringRanges < filteringRangesLength) {
const filteringRange: number[] = filteringRanges[indexfilteringRanges];
const filteringRangeBegin: number = filteringRange[0];
const filteringRangeEnd: number = filteringRange[1];
if (element < filteringRangeBegin) {
break;
}
if (element < filteringRangeEnd) {
filtered = true;
break;
}
if (element >= filteringRangeEnd) {
indexfilteringRanges++;
}
}
if (!filtered) {
filteredArray.push(element);
}
}
return filteredArray;
}
public static getDoubleQuoteIndexPairs(input: string): number[][] {
return Utility.arrayToPairArray(Utility.getDoubleQuoteIndexes(input), input.length);
}
public static getDelimiterIndexPairs(input: string, delimiter: string): number[][] {
return Utility.arrayToPairArray(Utility.getDelimiterIndexes(input, delimiter), input.length);
}
public static arrayToPairArray<T>(anArray: T[], lastElement: T): T[][] {
const pairArray: T[][] = [];
const arrayLength: number = anArray.length;
let index: number = 0;
while (index < arrayLength) {
const firstElement: T = anArray[index++];
let secondElement: T = lastElement;
if (index < arrayLength) {
secondElement = anArray[index++];
}
pairArray.push([firstElement, secondElement]);
}
return pairArray;
}
public static getCommaIndexes(input: string): number[] {
return Utility.getDelimiterIndexes(input, ",");
}
public static getDoubleQuoteIndexes(input: string): number[] {
return Utility.getDelimiterIndexes(input, "\"");
}
public static getDelimiterIndexes(input: string, delimiter: string): number[] {
const delimiterIndexes: number[] = [];
const inputLength: number = input.length;
let inputIndex: number = 0;
while (inputIndex < inputLength) {
const delimiterIndex: number = input.indexOf(delimiter, inputIndex);
if (delimiterIndex < 0) {
break;
}
delimiterIndexes.push(delimiterIndex);
inputIndex = delimiterIndex + 1;
}
return delimiterIndexes;
}
public static getFloorInteger(input: number): number {
return Math.floor(input);
}
public static getRoundInteger(input: number): number {
return Math.round(input);
}
public static cloneArray<T>(inputArray: T[]): T[] {
const clonedArray = Object.assign([], inputArray);
return clonedArray;
}
public static cloneGenericObject<T>(anObject: T): T {
const clonedObject = Object.assign({}, anObject);
return clonedObject;
}
public static cloneObject(anObject: object): object {
const clonedObject = Object.assign({}, anObject);
return clonedObject;
}
public static getFileBasename(filename: string): string {
return path.basename(filename);
}
public static getFileDirname(filename: string): string {
return path.dirname(filename);
}
public static getFileExtname(filename: string): string {
return path.extname(filename);
}
public static getFilenameWithoutExtension(filename: string): string {
const extension: string = Utility.getFileExtname(filename);
const filenameWithoutExtension: string = filename.substring(0, filename.length - extension.length);
return filenameWithoutExtension;
}
public static stringifyArray<T>(
anArray: T[],
delimiter: string = ","): string {
return "[" + anArray.join(delimiter) + "]";
}
public static jsonStringifyInLine(
value: any): string {
return Utility.jsonStringify(value, null, "");
}
public static jsonStringify(
value: any,
replacer: Array<number | string> | null = null,
space: string | number = 4): string {
return JSON.stringify(value, replacer, space);
}
public static split(input: string, delimiter: string): string[] {
return Utility.splitRaw(input, delimiter).map((x: string) => x.trim());
}
public static splitRaw(input: string, delimiter: string): string[] {
return input.split(delimiter);
}
public static normalizeArray<T>(array: T[], indexKey: keyof T): { [key: string]: T } {
const normalizedObject: { [key: string]: T } = {};
// tslint:disable-next-line: prefer-for-of
for (let i = 0; i < array.length; i++) {
const key: any = array[i][indexKey];
normalizedObject[key] = array[i];
}
return normalizedObject;
}
public static sparseArrayPairToMap<T>(indexArray: number[], valueArray: number[]): Map<number, number> {
const sparseIndexedMap: Map<number, number> = new Map<number, number>();
// tslint:disable-next-line: prefer-for-of
for (let i = 0; i < indexArray.length; i++) {
const key: number = indexArray[i];
const value: number = valueArray[i];
sparseIndexedMap.set(key, value);
}
return sparseIndexedMap;
}
public static sortAnyArray(inputAnyArray: any[]): any[] {
if (Utility.isEmptyAnyArray(inputAnyArray)) { return []; }
return inputAnyArray.sort(
(n1: any, n2: any) => {
if (n1 > n2) {
return 1;
}
if (n1 < n2) {
return -1;
}
return 0;
});
}
public static sortNumberArray(inputNumberArray: number[]): number[] {
if (Utility.isEmptyNumberArray(inputNumberArray)) { return []; }
return inputNumberArray.sort(
(n1: number, n2: number) => {
if (n1 > n2) {
return 1;
}
if (n1 < n2) {
return -1;
}
return 0;
});
}
public static sortStringArray(inputStringArray: string[]): string[] {
if (Utility.isEmptyStringArray(inputStringArray)) { return []; }
return inputStringArray.sort(
(n1: string, n2: string) => {
if (n1 > n2) {
return 1;
}
if (n1 < n2) {
return -1;
}
return 0;
});
}
public static sortValueCountPairArray(inputValueCountPairArray: StructValueCount[]): StructValueCount[] {
if (Utility.isEmptyValueCountPairArray(inputValueCountPairArray)) { return []; }
return inputValueCountPairArray.sort(
(valueCountPair1: StructValueCount, valueCountPair2: StructValueCount) => {
if (valueCountPair1.value > valueCountPair2.value) {
return 1;
}
if (valueCountPair1.value < valueCountPair2.value) {
return -1;
}
return 0;
});
}
public static findMedian(
inputNumberArray: number[]): number|undefined {
if (Utility.isEmptyNumberArray(inputNumberArray)) { return undefined; }
const sortedNumberArray: number[] =
Utility.sortNumberArray(inputNumberArray);
if (Utility.isEmptyNumberArray(sortedNumberArray)) { return undefined; }
const count: number = sortedNumberArray.length;
let median: number;
{
const middleIndex: number = Math.floor(count / 2);
if (count % 2 === 0) {
median = (sortedNumberArray[middleIndex] + sortedNumberArray[middleIndex - 1]) / 2;
} else {
median = sortedNumberArray[middleIndex];
}
}
return median;
}
public static findValueCountPairMedian(
inputValueCountPairArray: StructValueCount[]): number|undefined {
if (Utility.isEmptyValueCountPairArray(inputValueCountPairArray)) { return undefined; }
const sortedValueCountPairArray: StructValueCount[] =
Utility.sortValueCountPairArray(inputValueCountPairArray);
if (Utility.isEmptyValueCountPairArray(sortedValueCountPairArray)) { return undefined; }
const totalCount: number = sortedValueCountPairArray.reduce(
(accumulative: number, entry: StructValueCount) => accumulative + entry.count, 0);
if (totalCount > 0) {
const middleCount: number = Math.floor(totalCount / 2);
const isEven: boolean = (totalCount % 2) === 0;
let accumulativeCountPrevious: number = 0;
let accumulativeCount: number = 0;
// tslint:disable-next-line: prefer-for-of
for (let index: number = 0; index < sortedValueCountPairArray.length; index++) {
const count: number = sortedValueCountPairArray[index].count;
accumulativeCount += count;
if (accumulativeCount > middleCount) {
const value: number = sortedValueCountPairArray[index].value;
if (!isEven) {
return value;
}
if ((middleCount - accumulativeCountPrevious) > 0) {
return value;
}
const valuePrevious: number = sortedValueCountPairArray[index - 1].value;
return (value + valuePrevious) / 2;
}
accumulativeCountPrevious = accumulativeCount;
}
}
return undefined;
}
public static findQuantiles(
inputNumberArray: number[],
quantileConfiguration: number): number[]|undefined {
if (!quantileConfiguration || (quantileConfiguration < 2)) {
return undefined;
}
if (Utility.isEmptyNumberArray(inputNumberArray)) { return undefined; }
const sortedNumberArray: number[] =
Utility.sortNumberArray(inputNumberArray);
if (Utility.isEmptyNumberArray(sortedNumberArray)) { return undefined; }
const count: number = sortedNumberArray.length;
const step: number = count / quantileConfiguration;
if (step < 1) { return undefined; }
const quantiles: number[] = [sortedNumberArray[0]];
let currentQuantileIndex: number = 0;
for (let quantileIndex: number = 0; quantileIndex < quantileConfiguration - 1; quantileIndex ++) {
currentQuantileIndex += step;
quantiles.push(sortedNumberArray[Math.floor(currentQuantileIndex)]);
}
quantiles.push(sortedNumberArray[sortedNumberArray.length - 1]);
return quantiles;
}
public static findValueCountPairQuantiles(
inputValueCountPairArray: StructValueCount[],
quantileConfiguration: number): number[]|undefined {
if (!quantileConfiguration || (quantileConfiguration < 2)) {
return undefined;
}
if (Utility.isEmptyValueCountPairArray(inputValueCountPairArray)) { return undefined; }
const sortedValueCountPairArray: StructValueCount[] =
Utility.sortValueCountPairArray(inputValueCountPairArray);
if (Utility.isEmptyValueCountPairArray(sortedValueCountPairArray)) { return undefined; }
const totalCount: number = sortedValueCountPairArray.reduce(
(accumulative: number, entry: StructValueCount) => accumulative + entry.count, 0);
const step: number = totalCount / quantileConfiguration;
if (step < 1) { return undefined; }
const quantiles: number[] = [sortedValueCountPairArray[0].value];
let currentQuantileIndex: number = 0;
// ---- NOTE ---- the following nested-loop can be optimized.
for (let quantileIndex: number = 0; quantileIndex < quantileConfiguration - 1; quantileIndex ++) {
currentQuantileIndex += step;
let accumulativeCountPrevious: number = 0;
let accumulativeCount: number = 0;
// tslint:disable-next-line: prefer-for-of
for (let index: number = 0; index < sortedValueCountPairArray.length; index++) {
const count: number = sortedValueCountPairArray[index].count;
accumulativeCount += count;
if (accumulativeCount > currentQuantileIndex) {
const value: number = sortedValueCountPairArray[index].value;
quantiles.push(value);
break;
}
accumulativeCountPrevious = accumulativeCount;
}
}
quantiles.push(sortedValueCountPairArray[sortedValueCountPairArray.length - 1].value);
return quantiles;
}
// -----------------------------------------------------------------------
// ---- NOTE ---- string to Uint8Array
// -----------------------------------------------------------------------
public static stringToUtf8EncodedUint8Array(input: string): Uint8Array {
const uint8Array: Uint8Array = new TextEncoder().encode(input);
return uint8Array;
}
// -----------------------------------------------------------------------
// ---- NOTE ---- number processing
// -----------------------------------------------------------------------
public static round(input: number, digits: number = 10000): number {
if (digits > 0) {
input = Math.round(input * digits) / digits;
}
return input;
}
// -----------------------------------------------------------------------
// ---- NOTE ---- output processing
// -----------------------------------------------------------------------
public static getBolded(input: any): string {
return `<b>${input}</b>`;
}
// -------------------------------------------------------------------------
// ---- NOTE ---- Obfuscation
// -------------------------------------------------------------------------
public static outputLabelStringUtility(input: Label): string {
return input.toString(Utility.toObfuscateLabelTextInReportUtility);
}
public static outputLabelString(input: Label, toObfuscate: boolean = false): string {
if (toObfuscate) {
return input.toObfuscatedString();
}
return input.toSimpleString();
}
public static obfuscateLabel(input: Label): string {
const inputObfuscated: string = input.toObfuscatedString();
return inputObfuscated;
}
public static outputNumberUtility(input: number): number {
return Utility.outputNumber(input, Utility.toObfuscateLabelTextInReportUtility);
}
public static outputNumber(input: number, toObfuscate: boolean = false): number {
if (toObfuscate) {
return Utility.obfuscateNumber(input);
}
return input;
}
public static obfuscateNumber(input: number): number {
const inputObfuscated: number = CryptoUtility.getNumberObfuscated(input);
return inputObfuscated;
}
public static outputStringUtility(input: string): string {
return Utility.outputString(input, Utility.toObfuscateLabelTextInReportUtility);
}
public static outputString(input: string, toObfuscate: boolean = false): string {
if (toObfuscate) {
return Utility.obfuscateString(input);
}
return input;
}
public static obfuscateString(input: string): string {
const inputObfuscated: string = CryptoUtility.getStringObfuscated(input);
return inputObfuscated;
}
// -----------------------------------------------------------------------
// ---- NOTE ---- protected
// -----------------------------------------------------------------------
protected static rngBurninIterations: number = 16384;
protected static rngBurninDone: boolean = false;
protected static xorshift128plusState0: number = 1;
protected static xorshift128plusState1: number = 2;
protected static rngBurninIterationsForBigInt: number = 16384;
protected static rngBurninDoneForBigInt: boolean = false;
protected static bigIntNegativeOne: bigint = BigInt(-1);
protected static bigint23: bigint = BigInt(23);
protected static bigint17: bigint = BigInt(17);
protected static bigint26: bigint = BigInt(26);
protected static xorshift128plusState0BigInt: bigint = BigInt(1);
protected static xorshift128plusState1BigInt: bigint = BigInt(2);
protected static xorshift128plusCycleBigInt: bigint =
BigInt("0xffffffffffffffff"); // ---- NOTE: 2^64 - 1 === 18446744073709551615
protected static xorshift128plusCycleFloatBigInt: number =
Number(Utility.xorshift128plusCycleBigInt);
} | the_stack |
import { LuFilesStatus } from '../luFilesStatus';
import { EntityTypesObj } from '../entityEnum';
import * as util from '../util';
import * as path from 'path';
import * as matchingPattern from '../matchingPattern';
import {
CompletionItem, CompletionItemKind, TextDocumentPositionParams, Files, TextDocuments
} from 'vscode-languageserver';
import {
TextDocument
} from 'vscode-languageserver-textdocument';
// eslint-disable-next-line @typescript-eslint/no-var-requires
const parseFile = require('@microsoft/bf-lu/lib/parser/lufile/parseFileContents.js').parseFile;
/**
* Code completions provide context sensitive suggestions to the user.
* @see https://code.visualstudio.com/api/language-extensions/programmatic-language-features#show-code-completion-proposals
* @export
* @class LGCompletionItemProvider
* @implements [CompletionItemProvider](#vscode.CompletionItemProvider)
*/
export function provideCompletionItems(_textDocumentPosition: TextDocumentPositionParams, documents: TextDocuments<TextDocument>) {
const document = documents.get(_textDocumentPosition.textDocument.uri)!;
const fspath = Files.uriToFilePath(document.uri);
const position = _textDocumentPosition.position;
const curLineContent = document?.getText({
start: {
line: position.line,
character: 0
},
end: position
}).toString();
if(!util.isLuFile(path.basename(document.uri)) )
return;
const fullContent = document.getText();
const lines = fullContent.split('\n');
const textExceptCurLine = lines
.slice(0, position.line)
.concat(lines.slice(position.line + 1))
.join('\n');
const completionList: CompletionItem[] = [];
if (/\[[^\]]*\]\([^)]*$/.test(curLineContent)) {
// []() import suggestion
const paths = Array.from(new Set(LuFilesStatus.luFilesOfWorkspace));
return paths.filter(u => u !== fspath).reduce((prev : any[], curr: string) => {
const relativePath = path.relative(path.dirname(fspath!), curr);
const item = {
label: relativePath,
kind: CompletionItemKind.Reference,
detail: curr
};
prev.push(item);
return prev;
}, []);
}
// if (matchingPattern.isEntityType(curLineContent)) {
// const entityTypes: string[] = EntityTypesObj.EntityType;
// entityTypes.forEach(entity => {
// const item = {
// label: entity,
// kind: CompletionItemKind.Keyword,
// insertText: `${entity}`,
// documentation: `Enitity type: ${entity}`,
// };
// completionList.push(item);
// });
// }
if (matchingPattern.isPrebuiltEntity(curLineContent)) {
const prebuiltTypes: string[] = EntityTypesObj.Prebuilt;
prebuiltTypes.forEach(entity => {
const item = {
label: entity,
kind: CompletionItemKind.Keyword,
insertText: `${entity}`,
documentation: `Prebuilt enitity: ${entity}`,
};
completionList.push(item);
});
}
if (matchingPattern.isRegexEntity(curLineContent)) {
const item = {
label: 'RegExp Entity',
kind: CompletionItemKind.Keyword,
insertText: `//`,
documentation: `regex enitity`,
};
completionList.push(item);
}
if (matchingPattern.isEntityName(curLineContent)) {
const item = {
label: 'hasRoles?',
kind: CompletionItemKind.Keyword,
insertText: `hasRoles`,
documentation: `Entity name hasRole?`,
};
completionList.push(item);
const item2 = {
label: 'usesFeature?',
kind: CompletionItemKind.Keyword,
insertText: `usesFeature`,
documentation: `Entity name usesFeature?`,
};
completionList.push(item2);
}
if (matchingPattern.isPhraseListEntity(curLineContent)) {
const item = {
label: 'interchangeable synonyms?',
kind: CompletionItemKind.Keyword,
insertText: `interchangeable`,
documentation: `interchangeable synonyms as part of the entity definition`,
};
completionList.push(item);
}
if (matchingPattern.isEntityType(curLineContent)) {
// @ can be followed by entity like ml, regex or entity
const entityTypes: string[] = EntityTypesObj.EntityType;
entityTypes.forEach(entity => {
const item = {
label: entity,
kind: CompletionItemKind.Keyword,
insertText: `${entity}`,
documentation: `Enitity type: ${entity}`,
};
completionList.push(item);
});
return extractLUISContent(fullContent).then(
luisJson => {
if (!luisJson) {
return extractLUISContent(textExceptCurLine).then(
newluisJson => {
return addEntities(newluisJson, completionList);}
);
} else {
return addEntities(luisJson, completionList);
}
}
);
}
// completion for entities and patterns, use the text without current line due to usually it will cause parser errors, the luisjson will be undefined
if (completionList.length === 0){
return extractLUISContent(fullContent).then(
luisJson => {
if (!luisJson) {
extractLUISContent(textExceptCurLine).then(
newluisJson => {
return processSuggestions(newluisJson, curLineContent, fullContent);}
)
} else {
return processSuggestions(luisJson, curLineContent, fullContent)
}
}
);
}
return completionList;
}
function processSuggestions(luisJson: any, curLineContent: string, fullContent: string) {
const suggestionEntityList = matchingPattern.getSuggestionEntities(luisJson, matchingPattern.suggestionAllEntityTypes);
const regexEntityList = matchingPattern.getRegexEntities(luisJson);
const completionList: CompletionItem[] = []
//suggest a regex pattern for seperated line definition
if (matchingPattern.isSeperatedEntityDef(curLineContent)) {
const seperatedEntityDef = /^\s*@\s*([\w._]+|"[\w._\s]+")+\s*=\s*$/;
let entityName = '';
const matchGroup = curLineContent.match(seperatedEntityDef);
if (matchGroup && matchGroup.length >= 2) {
entityName = matchGroup[1].trim();
}
if (regexEntityList.includes(entityName)) {
const item = {
label: 'RegExp Entity',
kind: CompletionItemKind.Keyword,
insertText: `//`,
documentation: `regex enitity`,
};
completionList.push(item);
}
}
// auto suggest pattern
if (matchingPattern.matchedEnterPattern(curLineContent)) {
suggestionEntityList.forEach(name => {
const item = {
label: `Entity: ${name}`,
kind: CompletionItemKind.Property,
insertText: `${name}`,
documentation: `pattern suggestion for entity: ${name}`,
};
completionList.push(item);
});
}
// suggestions for entities in a seperated line
if (matchingPattern.isEntityType(curLineContent)) {
suggestionEntityList.forEach(entity => {
const item = {
label: entity,
kind: CompletionItemKind.Property,
insertText: `${entity}`,
documentation: `Enitity type: ${entity}`,
};
completionList.push(item);
});
}
if (matchingPattern.isCompositeEntity(curLineContent)) {
matchingPattern.getSuggestionEntities(luisJson, matchingPattern.suggestionNoCompositeEntityTypes).forEach(entity => {
const item = {
label: entity,
kind: CompletionItemKind.Property,
insertText: `${entity}`,
documentation: `Enitity type: ${entity}`,
};
completionList.push(item);
});
}
const suggestionRolesList = matchingPattern.getSuggestionRoles(luisJson, matchingPattern.suggestionAllEntityTypes);
// auto suggest roles
if (matchingPattern.matchedRolesPattern(curLineContent) || matchingPattern.matchedEntityPattern(curLineContent)) {
// {@ } or {entity: }
suggestionRolesList.forEach(name => {
const item = {
label: `Role: ${name}`,
kind: CompletionItemKind.Property,
insertText: `${name}`,
documentation: `roles suggestion for entity name: ${name}`,
};
completionList.push(item);
});
}
if (matchingPattern.matchedEntityPattern(curLineContent)) {
suggestionEntityList.forEach(name => {
const item = {
label: `Entity: ${name}`,
kind: CompletionItemKind.Property,
insertText: ` ${name}`,
documentation: `pattern suggestion for entity: ${name}`,
};
completionList.push(item);
});
}
if (matchingPattern.matchedEntityCanUsesFeature(curLineContent, fullContent, luisJson)) {
const enitityName = matchingPattern.extractEntityNameInUseFeature(curLineContent);
const suggestionFeatureList = matchingPattern.getSuggestionEntities(luisJson, matchingPattern.suggestionNoPatternAnyEntityTypes);
suggestionFeatureList.forEach(name => {
if (name !== enitityName) {
const item = {
label: `Entity: ${name}`,
kind: CompletionItemKind.Method,
insertText: `${name}`,
documentation: `Feature suggestion for current entity: ${name}`,
};
completionList.push(item);
}
});
}
if (matchingPattern.matchIntentInEntityDef(curLineContent)) {
const item = {
label: 'usesFeature?',
kind: CompletionItemKind.Keyword,
insertText: `usesFeature`,
documentation: `Does this intent usesFeature?`,
};
completionList.push(item);
}
if (matchingPattern.matchIntentUsesFeatures(curLineContent)) {
const suggestionFeatureList = matchingPattern.getSuggestionEntities(luisJson, matchingPattern.suggestionNoPatternAnyEntityTypes);
suggestionFeatureList.forEach(name => {
const item = {
label: `Entity: ${name}`,
kind: CompletionItemKind.Method,
insertText: `${name}`,
documentation: `Feature suggestion for current entity: ${name}`,
};
completionList.push(item);
});
}
return completionList;
}
async function extractLUISContent(text: string): Promise<any> {
let parsedContent: any;
const log = false;
const locale = 'en-us';
try {
parsedContent = await parseFile(text, log, locale);
} catch (e) {
//nothing to do in catch block
}
if (parsedContent !== undefined) {
return parsedContent.LUISJsonStructure;
} else {
return undefined;
}
}
function addEntities(luisJson: any, completionList: CompletionItem[]) : CompletionItem[] {
matchingPattern.getSuggestionEntities(luisJson, matchingPattern.suggestionAllEntityTypes).forEach(name => {
const item = {
label: `Entity: ${name}`,
kind: CompletionItemKind.Property,
insertText: `${name}`,
documentation: `pattern suggestion for entity: ${name}`,
};
completionList.push(item);
});
return completionList;
} | the_stack |
import * as R from 'ramda';
import {reduceTextToBitset} from '@compiler/core/utils/extractNthByte';
import {NodeLocation} from '@compiler/grammar/tree/NodeLocation';
import {TokensIterator} from '@compiler/grammar/tree/TokensIterator';
import {
NumberToken,
TokenType,
TokenKind,
Token,
} from '@compiler/lexer/tokens';
import {COMPILER_INSTRUCTIONS_SET} from '../../../constants/instructionSetSchema';
import {InstructionPrefix, MAX_COMPILER_REG_LENGTH} from '../../../constants';
import {
BRANCH_ADDRESSING_SIZE_MAPPING,
InstructionArgType,
BranchAddressingType,
X86TargetCPU,
InstructionArgSize,
} from '../../../types';
import {ParserError, ParserErrorCode} from '../../../shared/ParserError';
import {ASTAsmParser} from '../ASTAsmParser';
import {ASTNodeKind} from '../types';
import {ASTLabelAddrResolver} from './ASTResolvableArg';
import {ASTInstructionSchema} from './ASTInstructionSchema';
import {
ASTInstructionNumberArg,
ASTInstructionMemPtrArg,
ASTInstructionMemSegmentedArg,
ASTInstructionRegisterArg,
ASTInstructionArg,
} from './args';
import {KindASTAsmNode} from '../ASTAsmNode';
import {
RegisterToken,
SizeOverrideToken,
BranchAddressingTypeToken,
} from '../../lexer/tokens';
import {findMatchingInstructionSchemas} from './args/ASTInstructionArgMatchers';
import {isTokenInstructionBeginning} from './utils/isTokenInstructionBeginning';
import {
isJumpInstruction,
toStringArgsList,
fetchInstructionTokensArgsList,
assignLabelsToTokens,
isAnyLabelInTokensList,
isX87Instruction,
} from '../../utils';
/**
* Parser for:
* [opcode] [arg1] [arg2] [argX]
*
* @todo
* Maybe remove originalArgs and check if instruction
* has LABEL etc stuff in better way?
*
* @export
* @class ASTInstruction
* @extends {KindASTAsmNode(ASTNodeKind.INSTRUCTION)}
*/
export class ASTInstruction extends KindASTAsmNode(ASTNodeKind.INSTRUCTION) {
// initial args is constant, it is
// toggled on first pass, during AST tree analyze
// args might change in second phase
public args: ASTInstructionArg[];
// used for optimistic instruction size predictions
public originalArgsTokens: Token<any>[];
public unresolvedArgs: boolean;
public typedArgs: {[type in InstructionArgType]: (ASTInstructionArg|ASTInstructionMemPtrArg)[]};
// matched for args
public schemas: ASTInstructionSchema[];
// jump/branch related args
public branchAddressingType: BranchAddressingType = null;
public jumpInstruction: boolean;
public labeledInstruction: boolean;
public x87Instruction: boolean;
constructor(
public readonly opcode: string,
public argsTokens: Token<any>[],
public readonly prefixes: InstructionPrefix[] = [],
loc: NodeLocation,
) {
super(loc);
// optimized clone()
if (argsTokens) {
// decode FAR/NEAR JMP addressing type prefixes
if (argsTokens.length && argsTokens[0].kind === TokenKind.BRANCH_ADDRESSING_TYPE) {
this.branchAddressingType = (<BranchAddressingTypeToken> argsTokens[0]).value;
this.originalArgsTokens = R.tail(argsTokens);
} else
this.originalArgsTokens = argsTokens;
// check if instruction is branch instruction
this.jumpInstruction = isJumpInstruction(opcode);
this.x87Instruction = isX87Instruction(opcode);
// it is false for mov ax, [b] due to [b] is resolved later
// inside tryResolveSchema, labeledInstruction will be overriden
// inside labelResolver() anyway during first pass
this.originalArgsTokens = assignLabelsToTokens(
null,
this.originalArgsTokens,
{
preserveIfError: true,
preserveOriginalText: true,
},
);
this.labeledInstruction = isAnyLabelInTokensList(this.originalArgsTokens);
}
}
get memArgs() {
return <ASTInstructionMemPtrArg[]> this.typedArgs[InstructionArgType.MEMORY];
}
get numArgs() {
return <ASTInstructionNumberArg[]> this.typedArgs[InstructionArgType.NUMBER];
}
get segMemArgs() {
return <ASTInstructionMemSegmentedArg[]> this.typedArgs[InstructionArgType.SEGMENTED_MEMORY];
}
get regArgs() {
return <ASTInstructionRegisterArg[]> this.typedArgs[InstructionArgType.REGISTER];
}
get labelArgs() {
return this.typedArgs[InstructionArgType.LABEL];
}
clone(): ASTInstruction {
const {
opcode, argsTokens, prefixes, loc, args,
unresolvedArgs, typedArgs, schemas, branchAddressingType,
labeledInstruction, jumpInstruction, originalArgsTokens,
} = this;
const cloned = new ASTInstruction(
opcode,
null,
prefixes,
loc,
);
Object.assign(
cloned,
{
args,
argsTokens,
originalArgsTokens,
unresolvedArgs,
typedArgs,
schemas,
branchAddressingType,
jumpInstruction,
labeledInstruction,
},
);
return cloned;
}
/**
* Get Scale SIB byte
*
* @returns
* @memberof ASTInstruction
*/
getScale() {
return this.memArgs[0]?.addressDescription?.scale;
}
/**
* Determine if instruction needs to be recompiled
* in later passes
*
* @see X86Compiler
*
* @returns {boolean}
* @memberof ASTInstruction
*/
isConstantSize(): boolean {
const {labeledInstruction, unresolvedArgs, jumpInstruction} = this;
return !labeledInstruction && !unresolvedArgs && !jumpInstruction;
}
/**
* Used for matching instruction in jump labels
*
* @param {ASTInstructionSchema} schema
* @returns
* @memberof ASTInstruction
*/
getPredictedBinarySchemaSize(schema: ASTInstructionSchema = this.schemas[0]) {
return this.prefixes.length + schema.byteSize + +!!this.getScale();
}
/**
* Groups args into types
*
* @todo
* Find better solution, it is not memory friendly
*
* @private
* @memberof ASTInstruction
*/
private refreshTypedArgs(): void {
this.typedArgs = <any> R.reduce(
(acc, item) => {
acc[<any> item.type].push(item);
return acc;
},
{
[InstructionArgType.MEMORY]: [],
[InstructionArgType.SEGMENTED_MEMORY]: [],
[InstructionArgType.NUMBER]: [],
[InstructionArgType.REGISTER]: [],
[InstructionArgType.LABEL]: [],
},
this.args,
);
}
/**
* @todo
* Add prefixes
*
* @returns {string}
* @memberof ASTInstruction
*/
toString(): string {
const {schemas, args, prefixes, branchAddressingType} = this;
if (schemas.length > 0) {
let {mnemonic} = schemas[0];
if (branchAddressingType)
mnemonic = `${mnemonic} ${branchAddressingType}`;
if (prefixes) {
R.forEach(
(prefix) => {
const prefixName = InstructionPrefix[prefix];
if (prefixName)
mnemonic = `${prefixName} ${mnemonic}`;
},
prefixes,
);
}
return toStringArgsList(mnemonic, args);
}
return toStringArgsList(this.opcode, args);
}
/**
* Search for ModRM byte parameter, it might be register or memory,
* it is flagged using schema.rm boolean
*
* @returns {ASTInstructionArg}
* @memberof ASTInstruction
*/
findRMArg(): ASTInstructionMemPtrArg {
return <ASTInstructionMemPtrArg> R.find<ASTInstructionArg>(
(arg) => arg.schema?.rm,
this.args,
);
}
/**
* Iterates through args and watches which is unresolved
*
* @private
* @param {ASTLabelAddrResolver} labelResolver
* @param {ASTInstructionArg[]} newArgs
* @returns
* @memberof ASTInstruction
*/
private tryResolveArgs(labelResolver: ASTLabelAddrResolver, newArgs: ASTInstructionArg[]): void {
let unresolvedArgs = null;
this.args = R.map(
(arg) => {
if (arg.isResolved())
return arg;
if (labelResolver)
arg.tryResolve(labelResolver);
if (!unresolvedArgs && !arg.isResolved())
unresolvedArgs = true;
return arg;
},
newArgs,
);
this.unresolvedArgs = unresolvedArgs;
this.refreshTypedArgs();
}
/**
* Search if all labels are present
*
* @param {ASTLabelAddrResolver} labelResolver
* @param {number} absoluteAddress
* @param {X86TargetCPU} targetCPU
*
* @returns {ASTInstruction}
* @memberof ASTInstruction
*/
tryResolveSchema(
labelResolver?: ASTLabelAddrResolver,
absoluteAddress?: number,
targetCPU?: X86TargetCPU,
): ASTInstruction {
this.argsTokens = assignLabelsToTokens(labelResolver, this.originalArgsTokens);
// regenerate schema args
const {branchAddressingType, jumpInstruction, argsTokens} = this;
const [overridenBranchAddressingType, newArgs] = ASTInstruction.parseInstructionArgsTokens(
branchAddressingType,
argsTokens,
jumpInstruction
? InstructionArgSize.WORD
: null,
);
// assign labels resolver into not fully resolved args
this.branchAddressingType = overridenBranchAddressingType ?? branchAddressingType;
this.tryResolveArgs(labelResolver, newArgs);
// list all of schemas
this.schemas = findMatchingInstructionSchemas(
COMPILER_INSTRUCTIONS_SET,
targetCPU,
this,
absoluteAddress,
);
// assign matching schema
const {schemas, args} = this;
for (let i = 0; i < args.length; ++i)
args[i].schema = schemas.length > 0 ? schemas[0].argsSchema[i] : null;
// if not found any matching schema - resolving failed
return schemas.length ? this : null;
}
/**
* Transforms list of tokens into arguments
*
* @see
* BranchAddressingType might be overriden so return both values!
*
* @static
* @param {BranchAddressingType} branchAddressingType
* @param {Token[]} tokens
* @param {number} [defaultMemArgByteSize=null]
* @returns {ASTInstructionArg<any>[]}
* @memberof ASTInstruction
*/
static parseInstructionArgsTokens(
branchAddressingType: BranchAddressingType,
tokens: Token[],
defaultMemArgByteSize: number = null,
): [BranchAddressingType, ASTInstructionArg<any>[]] {
let byteSizeOverride: number = null;
let maxArgSize: number = null;
let branchSizeOverride: number = (
branchAddressingType
? BRANCH_ADDRESSING_SIZE_MAPPING[branchAddressingType] * 2
: null
);
/**
* Checks size of number, applies override and throw if error
*
* @param {Token} token
* @param {number} number
* @param {number} byteSize
* @returns {ASTInstructionNumberArg}
*/
function parseNumberArg(token: Token, number: number, byteSize: number): ASTInstructionNumberArg {
// if no - number
if (!R.isNil(byteSizeOverride) && byteSizeOverride < byteSize) {
throw new ParserError(
ParserErrorCode.EXCEEDING_CASTED_NUMBER_SIZE,
token.loc,
{
value: token.text,
size: byteSize,
maxSize: byteSizeOverride,
},
);
}
// detect if number token was really just replaced number
// used in jmp test_label
// it is translated into jmp 0x4
// 0x4 has originalToken test_label
const {originalToken} = token;
let assignedLabel: string = null;
if (originalToken?.type === TokenType.KEYWORD)
assignedLabel = originalToken.text;
return new ASTInstructionNumberArg(
number,
byteSizeOverride ?? byteSize,
null,
InstructionArgType.NUMBER,
assignedLabel,
);
}
/**
* Consumes token and product instruction arg
*
* @param {ASTInstructionArg} prevArgs
* @param {Token} token
* @param {TokensIterator} iterator
* @returns {ASTInstructionArg<any>}
*/
function parseToken(
prevArgs: ASTInstructionArg[],
token: Token,
iterator: TokensIterator,
): ASTInstructionArg<any> {
const nextToken = iterator.fetchRelativeToken(1, false);
const destinationArg = !prevArgs.length;
// check if next token is colon, if so - it is segmented arg
// do not pass it directly as SegmentedAddress into AST argument
// it can contain label, just ignore type of precceding token
// and throw error if not pass inside arg parser
if (nextToken?.type === TokenType.COLON) {
// sometimes instruction might be not prefixed with far or near prefix
// for example jmp 0x7C00:0x123, force detect addressing type
if (R.isNil(branchAddressingType)) {
branchAddressingType = BranchAddressingType.FAR;
branchSizeOverride = BRANCH_ADDRESSING_SIZE_MAPPING[branchAddressingType] * 2;
}
// eat colon
iterator.consume();
return new ASTInstructionMemSegmentedArg(
`${token.text}:${iterator.fetchRelativeToken()?.text}`,
byteSizeOverride ?? branchSizeOverride ?? token.value.byteSize,
);
}
// watch for other instruction arg types
switch (token.type) {
// Quotes are converted into digits
case TokenType.QUOTE: {
const {text} = token;
if (text.length > MAX_COMPILER_REG_LENGTH) {
throw new ParserError(
ParserErrorCode.INCORRECT_ARG_QUOTE_TEXT_LENGTH,
token.loc,
{
maxSize: MAX_COMPILER_REG_LENGTH,
text,
},
);
}
return parseNumberArg(token, reduceTextToBitset(text), text.length);
}
// Registers
case TokenType.KEYWORD:
if (token.kind === TokenKind.REGISTER) {
const {schema, byteSize} = (<RegisterToken> token).value;
return new ASTInstructionRegisterArg(schema, byteSize);
}
if (token.kind === TokenKind.BYTE_SIZE_OVERRIDE) {
let newByteSize = (<SizeOverrideToken> token).value.byteSize;
// not sure if it is ok but in nasm byte size in branch mode
// is as twice as big as override so multiply by 2
if (branchSizeOverride) {
if (newByteSize * 2 < branchSizeOverride)
throw new ParserError(ParserErrorCode.OPERAND_SIZES_MISMATCH, token.loc);
else
newByteSize *= 2;
}
byteSizeOverride = newByteSize;
return null;
}
// used for mem matching, in first phase
return new ASTInstructionArg(
InstructionArgType.LABEL,
token.text,
byteSizeOverride ?? branchSizeOverride,
);
// Numeric or address segmented address
case TokenType.FLOAT_NUMBER:
case TokenType.NUMBER: {
const {number, byteSize} = (<NumberToken> token).value;
return parseNumberArg(token, number, byteSize);
}
// Mem address ptr
case TokenType.BRACKET:
if (token.kind === TokenKind.SQUARE_BRACKET) {
let memSize = byteSizeOverride ?? branchSizeOverride ?? defaultMemArgByteSize;
// when read from memory size must be known
// try to deduce from previous args size of
// memory argument
if (R.isNil(memSize)) {
if (destinationArg) {
// if destination - next register should contain size
if (nextToken?.kind === TokenKind.REGISTER)
memSize = (<RegisterToken> nextToken).value.byteSize;
} else if (prevArgs.length) {
// if not destination - there should be some registers before
// try to find matching
const prevRegArg = R.find(
(arg) => arg.type === InstructionArgType.REGISTER,
prevArgs,
);
if (prevRegArg?.byteSize)
memSize = prevRegArg.byteSize;
else
throw new ParserError(ParserErrorCode.MISSING_MEM_OPERAND_SIZE, token.loc);
}
}
return new ASTInstructionMemPtrArg(<string> token.text, memSize);
}
// expresions such as (2+2), (dupa) etc
if (token.kind === TokenKind.PARENTHES_BRACKET) {
return new ASTInstructionArg(
InstructionArgType.LABEL,
token.text,
byteSizeOverride ?? branchSizeOverride,
);
}
break;
default:
}
// force throw error if not known format
throw new ParserError(
ParserErrorCode.INVALID_INSTRUCTION_OPERAND,
token.loc,
{
operand: token.text,
},
);
}
// a bit faster than transduce
const argsTokensIterator = new TokensIterator(tokens);
const acc: ASTInstructionArg[] = [];
argsTokensIterator.iterate(
(token: Token) => {
const result = parseToken(acc, token, argsTokensIterator);
if (!result)
return;
// used for mem operands size deduce
// numbers are ignored by nasm
// case: mov [0x0], 0x7C
if (result.byteSize
&& (result.type === InstructionArgType.MEMORY || result.type === InstructionArgType.REGISTER))
maxArgSize = Math.max(maxArgSize, result.byteSize);
const prevArg = acc[acc.length - 1];
const sizeMismatch = (
prevArg
&& result.type !== InstructionArgType.LABEL
&& (prevArg.type === InstructionArgType.REGISTER || prevArg.type === InstructionArgType.NUMBER)
&& result.byteSize !== prevArg.byteSize
);
// tell arg that size of argument is explicit overriden
// user does: mov word al, [0x1]
// so overriden has been [0x1]
if (byteSizeOverride
&& (result.type === InstructionArgType.MEMORY || result.type === InstructionArgType.NUMBER))
result.sizeExplicitOverriden = !!byteSizeOverride;
if (sizeMismatch) {
// handle something like this: mov ax, 2
// second argument has byteSize equal to 1, but ax is 2
// try to cast
const prevByteSize = prevArg.byteSize;
if (result.type === InstructionArgType.NUMBER && result.byteSize > prevByteSize)
throw new ParserError(ParserErrorCode.OPERAND_SIZES_MISMATCH, token.loc);
}
acc.push(result);
},
);
// handle case:
// add di,dword 16
if (maxArgSize && byteSizeOverride && byteSizeOverride > maxArgSize) {
throw new ParserError(
ParserErrorCode.OPERAND_SIZES_MISMATCH,
tokens[0].loc,
);
}
// add missing branch sizes for memory args
// mov [0x0], word 0x7C
// argument [0x0] initially has 1B of target size
// but after word override should be 2 byte
R.forEach(
(arg) => {
if (arg.type !== InstructionArgType.MEMORY)
return;
// handle mov ax, byte [ds:0xe620]
// size must be equal for mem param
if (maxArgSize && byteSizeOverride && byteSizeOverride !== maxArgSize) {
throw new ParserError(
ParserErrorCode.OPERAND_SIZES_MISMATCH,
tokens[0].loc,
);
}
if (byteSizeOverride)
arg.byteSize = byteSizeOverride;
else if (maxArgSize)
arg.byteSize = maxArgSize;
else {
throw new ParserError(
ParserErrorCode.MEM_OPERAND_SIZE_NOT_SPECIFIED,
tokens[0].loc,
{
operand: arg.toString(),
},
);
}
},
acc,
);
return [branchAddressingType, acc];
}
/**
* Returns instruction
*
* @static
* @param {Token} token
* @param {Object} recursiveParseParams
*
* @returns ASTInstruction
* @memberof ASTInstruction
*/
static parse(token: Token, parser: ASTAsmParser): ASTInstruction {
// if not opcode, ignore
if (!isTokenInstructionBeginning(token))
return null;
const savedParserTokenIndex = parser.getTokenIndex();
let opcode = token.lowerText;
// match prefixes
let prefixes: InstructionPrefix[] = [];
let prefixToken = token;
do {
const prefix = InstructionPrefix[prefixToken.upperText];
if (!prefix) {
// eat more empty lines
if (prefixToken.type === TokenType.EOF) {
opcode = null;
break;
} else if (prefixToken.type !== TokenType.EOL) {
opcode = prefixToken.lowerText;
break;
}
} else
prefixes.push(prefix);
prefixToken = parser.fetchRelativeToken();
} while (true);
// special case in parser when only prefixes are in line
// ignore fetching args tokens for them
// example:
// repz lock EOF
let argsTokens = null;
if (opcode === null) {
if (!prefixes.length)
return null;
// revert token index to start of prefixes
parser.setTokenIndex(savedParserTokenIndex);
// just treat as separate instruction
opcode = token.lowerText;
prefixes = [];
argsTokens = [];
} else {
// parse arguments
argsTokens = fetchInstructionTokensArgsList(parser);
}
// IMUL special case for NASM/FASM
// two operand instructions such as imul ax, 0x2 are compiled to imul ax, ax, 0x2
// todo: check why? other insutructions like shld works normal
if (opcode === 'imul'
&& argsTokens.length === 2
&& argsTokens[0].kind === TokenKind.REGISTER
&& argsTokens[1].kind === null
&& (argsTokens[1].type === TokenType.KEYWORD || argsTokens[1].type === TokenType.NUMBER)) {
argsTokens.unshift(argsTokens[0]);
}
const instruction = new ASTInstruction(
opcode,
argsTokens,
prefixes,
NodeLocation.fromTokenLoc(token.loc),
);
return instruction;
}
} | the_stack |
import { R, React } from '../libs';
import { isBlank, toNumber, isPlainObject } from '../util';
import {
IFormatCss,
IImageOptions,
IBackgroundImageStyles,
Falsy,
GlamorValue,
} from './types';
import { css as glamorCss } from 'glamor';
export const MEDIA_QUERY_RETINA = `@media (-webkit-min-device-pixel-ratio: 2), (min-resolution: 192dpi)`;
/**
* Constructs a style object for an image.
*
* For turning image files (PNG/JPG/SVG) into data-uri's see:
* https://github.com/webpack/url-loader
*
* @param {string} image1x: The normal image resolution (base64 encoded)
* @param {string} image2x: The retina image resolution (base64 encoded)
* @param {integer} width: Optional. The width of the image.
* @param {integer} height: Optional. The height of the image.
*/
export const image = (
image1x: string | undefined,
image2x: string | undefined,
options: IImageOptions = { width: 10, height: 10 },
): IBackgroundImageStyles => {
// Prepare image based on current screen density.
if (!image1x) {
throw new Error('Must have at least a 1x image.');
}
const { width, height } = options;
const result: any = {
width,
height,
backgroundImage: `url(${image1x})`,
backgroundSize: `${width}px ${height}px`,
backgroundRepeat: 'no-repeat',
};
if (image2x) {
result[MEDIA_QUERY_RETINA] = {
backgroundImage: `url(${image2x})`,
};
}
// Finish up.
return result;
};
const mergeAndReplace = (key: string, value: any, target: any) => {
Object.assign(target, value);
delete target[key];
return target;
};
const formatImage = (
key: string,
value: Array<string | number | undefined>,
target: any,
) => {
// Wrangle parameters.
let [image1x, image2x, width, height] = value; // tslint:disable-line
if (R.is(Number, image2x)) {
height = width;
width = image2x;
image2x = undefined;
}
const options = {
width: width as number,
height: height as number,
};
const style = image(image1x as string, image2x as string, options);
mergeAndReplace(key, style, target);
};
export const toPositionEdges = (
key: string,
value: any = undefined,
): {
position: string;
top: number | void;
right: number | void;
bottom: number | void;
left: number | void;
} | void => {
if (value === undefined || value === null) {
return undefined;
}
if (R.is(String, value) && isBlank(value)) {
return undefined;
}
if (R.is(Array, value) && value.length === 0) {
return undefined;
}
if (!R.is(Array, value)) {
value = value.toString().split(' ');
}
const edges = value.map((item: any) => toNumber(item));
let top: number | void;
let right: number | void;
let bottom: number | void;
let left: number | void;
const getEdge = (index: number): number | void => {
const edge = edges[index];
if (edge === null || edge === 'null' || edge === '') {
return undefined;
}
return edge;
};
switch (edges.length) {
case 1:
top = getEdge(0);
bottom = getEdge(0);
left = getEdge(0);
right = getEdge(0);
break;
case 2:
top = getEdge(0);
bottom = getEdge(0);
left = getEdge(1);
right = getEdge(1);
break;
case 3:
top = getEdge(0);
left = getEdge(1);
right = getEdge(1);
bottom = getEdge(2);
break;
default:
top = getEdge(0);
right = getEdge(1);
bottom = getEdge(2);
left = getEdge(3);
}
if (
top === undefined &&
right === undefined &&
bottom === undefined &&
left === undefined
) {
return undefined;
}
return {
position: key.toLowerCase(),
top,
right,
bottom,
left,
};
};
export const formatPositionEdges = (key: string, target: any) => {
const styles = toPositionEdges(key, target[key]);
mergeAndReplace(key, styles, target);
};
/**
* AbsoluteCenter
* - x
* - y
* - xy
*/
const formatAbsoluteCenter = (
key: string,
value: string | boolean | number,
target: any,
) => {
if (value === true) {
value = 'xy';
}
if (value === false || value === undefined || value === null) {
return;
}
const styles = {
position: 'absolute',
left: target.left,
top: target.top,
transform: '',
};
const stringValue = value
.toString()
.trim()
.toLowerCase();
if (stringValue.includes('x')) {
styles.left = '50%';
}
if (stringValue.includes('y')) {
styles.top = '50%';
}
let transform: string;
switch (value) {
case 'yx':
case 'xy':
transform = 'translate(-50%, -50%)';
break;
case 'x':
transform = 'translateX(-50%)';
break;
case 'y':
transform = 'translateY(-50%)';
break;
default:
throw new Error(`AbsoluteCenter value '${value}' not supported.`);
}
styles.transform = `${target.transform || ''} ${transform}`.trim();
mergeAndReplace(key, styles, target);
};
/**
* Spacing on the X:Y plane.
*/
function formatSpacingPlane(
plane: 'x' | 'y',
prefix: 'margin' | 'padding',
key: string,
value: any,
target: any,
) {
const styles = {};
switch (plane) {
case 'x':
styles[`${prefix}Left`] = value;
styles[`${prefix}Right`] = value;
break;
case 'y':
styles[`${prefix}Top`] = value;
styles[`${prefix}Bottom`] = value;
break;
default:
break; // Ignore.
}
mergeAndReplace(key, styles, target);
}
/**
* Sets up vertical scrolling including iOS momentum scrolling.
* See:
* https://css-tricks.com/snippets/css/momentum-scrolling-on-ios-overflow-elements/
*/
function formatScroll(key: string, value: any, target: any) {
if (value === true) {
const styles = {
overflowX: 'hidden',
overflowY: 'scroll',
WebkitOverflowScrolling: 'touch',
};
mergeAndReplace(key, styles, target);
}
if (value === false) {
const styles = {
overflow: 'hidden',
};
mergeAndReplace(key, styles, target);
}
}
// --------------------------------------------------
const AlignMap: { [k: string]: string } = {
center: 'center',
left: 'flex-start',
top: 'flex-start',
start: 'flex-start',
right: 'flex-end',
bottom: 'flex-end',
end: 'flex-end',
full: 'stretch',
stretch: 'stretch',
baseline: 'baseline',
};
function convertCrossAlignToFlex(token: string): string | undefined {
return AlignMap[token] || undefined; // undefined if not recognised;
}
const MainAlignMap: { [k: string]: string } = {
center: 'center',
left: 'flex-start',
top: 'flex-start',
start: 'flex-start',
right: 'flex-end',
bottom: 'flex-end',
end: 'flex-end',
spaceBetween: 'space-between',
spaceAround: 'space-around',
spaceEvenly: 'space-evenly',
};
function convertMainAlignToFlex(token: string): string | undefined {
return MainAlignMap[token] || undefined; // undefined if not recognised;
}
/**
* Format a flex css helper
* Format: [<direction>]-<crossAlignment>-<mainAlignment>
*/
function formatFlexPosition(
key: string,
value: string,
target: React.CSSProperties,
) {
let direction: 'row' | 'column' | undefined; // Assume horizontal
let mainAlignment: string | undefined;
let crossAlignment: string | undefined;
// Tokenize string
const tokens: string[] = value.split('-').map(token => token.trim());
tokens.map(token => {
const tokenIsOneOf = (options: string[]) => options.includes(token);
if (direction == null && tokenIsOneOf(['horizontal', 'vertical'])) {
direction = token === 'vertical' ? 'column' : 'row'; // tslint:disable-line
return;
}
if (
tokenIsOneOf([
'center',
'start',
'end',
'left',
'right',
'top',
'bottom',
'full',
'baseline',
])
) {
if (crossAlignment == null) {
if (direction == null && tokenIsOneOf(['left', 'right'])) {
direction = 'column';
}
if (direction == null && tokenIsOneOf(['top', 'bottom'])) {
direction = 'row';
}
crossAlignment = convertCrossAlignToFlex(token);
return;
}
mainAlignment = convertMainAlignToFlex(token);
return;
}
if (tokenIsOneOf(['spaceAround', 'spaceBetween', 'spaceEvenly'])) {
mainAlignment = convertMainAlignToFlex(token);
return;
}
});
const styles = {
display: 'flex',
flexDirection: direction,
alignItems: crossAlignment,
justifyContent: mainAlignment,
};
mergeAndReplace(key, styles, target);
}
export const transformStyle = (
style: React.CSSProperties | GlamorValue | Falsy = {},
): React.CSSProperties | GlamorValue => {
if (style == null) {
return {};
}
if (style === false) {
return {};
}
if (!R.is(Object, style)) {
return style;
}
Object.keys(style).forEach(key => {
const value = style[key];
if (value === false || R.isNil(value)) {
delete style[key];
} else if (isPlainObject(value)) {
// NB: This is not using formatCss, as we only want the transform, we don't want to convert it to a glamor value.
style[key] = transformStyle(value); // <== RECURSION.
} else {
switch (key) {
case 'Image':
formatImage(key, value, style);
break;
case 'Absolute':
formatPositionEdges(key, style);
break;
case 'Fixed':
formatPositionEdges(key, style);
break;
case 'AbsoluteCenter':
formatAbsoluteCenter(key, value, style);
break;
case 'MarginX':
formatSpacingPlane('x', 'margin', key, value, style);
break;
case 'MarginY':
formatSpacingPlane('y', 'margin', key, value, style);
break;
case 'PaddingX':
formatSpacingPlane('x', 'padding', key, value, style);
break;
case 'PaddingY':
formatSpacingPlane('y', 'padding', key, value, style);
break;
case 'Flex':
formatFlexPosition(key, value, style);
break;
case 'Scroll':
formatScroll(key, value, style);
break;
default:
// Ignore.
}
}
});
return style;
};
/**
* Helpers for constructing a CSS object.
* NB: This doesn't *actually* return React.CSSProperties, but
*/
const formatCss = (
...styles: Array<React.CSSProperties | GlamorValue | Falsy>
): GlamorValue => {
const newStyles = styles.map(transformStyle);
// Finish up.
return glamorCss(...newStyles) as {};
};
(formatCss as any).image = image;
export const format = formatCss as IFormatCss; | the_stack |
import { Component, Input, ChangeDetectionStrategy, ComponentFactoryResolver, NgZone,
SimpleChanges, Type, ViewChild, ElementRef, ViewContainerRef, ChangeDetectorRef } from "@angular/core"
import { css } from "@bosket/tools"
import { DisplayComponent } from "@bosket/angular"
import "self/common/styles/Planner.css"
type Plan = {
title: string,
content?: Type<any>,
subs?: Plan[],
editLink?: string
}
@Component({
selector: "planner-content",
template:`
<div [class]="depth === 1 ? 'chapter' : 'planner-section'">
<h1 *ngIf="depth === 1" [id]="id()" class="Planner heading">
<span>{{ plan.title }}</span>
<span class="icons">
<a [href]="'#' + id() "><i class="fa fa-link"></i></a>
<a *ngIf="plan.editLink" [href]="plan.editLink" target="_blank" rel=" noopener noreferrer">
<i class="fa fa-pencil"></i>
</a>
</span>
</h1>
<h2 *ngIf="depth === 2" [id]="id()" class="Planner heading">
<span>{{ plan.title }}</span>
<span class="icons">
<a [href]="'#' + id() "><i class="fa fa-link"></i></a>
<a *ngIf="plan.editLink" [href]="plan.editLink" target="_blank" rel=" noopener noreferrer">
<i class="fa fa-pencil"></i>
</a>
</span>
</h2>
<h3 *ngIf="depth === 3" [id]="id()" class="Planner heading">
<span>{{ plan.title }}</span>
<span class="icons">
<a [href]="'#' + id() "><i class="fa fa-link"></i></a>
<a *ngIf="plan.editLink" [href]="plan.editLink" target="_blank" rel=" noopener noreferrer">
<i class="fa fa-pencil"></i>
</a>
</span>
</h3>
<h4 *ngIf="depth === 4" [id]="id()" class="Planner heading">
<span>{{ plan.title }}</span>
<span class="icons">
<a [href]="'#' + id() "><i class="fa fa-link"></i></a>
<a *ngIf="plan.editLink" [href]="plan.editLink" target="_blank" rel=" noopener noreferrer">
<i class="fa fa-pencil"></i>
</a>
</span>
</h4>
<h5 *ngIf="depth === 5" [id]="id()" class="Planner heading">
<span>{{ plan.title }}</span>
<span class="icons">
<a [href]="'#' + id() "><i class="fa fa-link"></i></a>
<a *ngIf="plan.editLink" [href]="plan.editLink" target="_blank" rel=" noopener noreferrer">
<i class="fa fa-pencil"></i>
</a>
</span>
</h5>
<h6 *ngIf="depth === 6" [id]="id()" class="Planner heading">
<span>{{ plan.title }}</span>
<span class="icons">
<a [href]="'#' + id() "><i class="fa fa-link"></i></a>
<a *ngIf="plan.editLink" [href]="plan.editLink" target="_blank" rel=" noopener noreferrer">
<i class="fa fa-pencil"></i>
</a>
</span>
</h6>
<p *ngIf="depth > 6" [id]="id()" class="Planner heading">
<span>{{ plan.title }}</span>
<span class="icons">
<a [href]="'#' + id() "><i class="fa fa-link"></i></a>
<a *ngIf="plan.editLink" [href]="plan.editLink" target="_blank" rel=" noopener noreferrer">
<i class="fa fa-pencil"></i>
</a>
</span>
</p>
<div #content></div>
<div *ngIf="plan.subs">
<div *ngFor="let s of plan.subs">
<planner-content [plan]="s" [prefix]="prefix ? prefix+'#'+plan.title : plan.title" [depth]="depth + 1"></planner-content>
</div>
</div>
</div>`,
changeDetection: ChangeDetectionStrategy.OnPush
})
export class PlannerContent {
@Input() plan: Plan
@Input() prefix: string = ""
@Input() depth: number = 1
@ViewChild("content", { read: ViewContainerRef } ) content : ViewContainerRef
constructor(private _componentFactoryResolver: ComponentFactoryResolver, private _cdRef: ChangeDetectorRef) { }
ngOnChanges(changes: SimpleChanges) {
this.refresh()
}
ngAfterViewInit() {
this.refresh()
}
refresh() {
if(!this.plan || !this.content || !this.plan.content) return
this.content.clear()
let componentFactory = this._componentFactoryResolver.resolveComponentFactory(this.plan.content)
let componentRef = this.content.createComponent(componentFactory)
setTimeout(() => this._cdRef.markForCheck(), 0)
}
id() {
return this.prefix ? `${this.prefix}#${this.plan.title}` : this.plan.title
}
}
@Component({
template: `<a [href]="href()">{{ item.title }}</a>`,
changeDetection: ChangeDetectionStrategy.OnPush
})
export class PlannerInjector implements DisplayComponent<Plan> {
@Input() item : Plan
@Input() inputs: any
href() {
return `${this.inputs.ancestors.map(a => "#" + a.title).join("")}#${this.item.title}`
}
}
@Component({
selector: "planner",
template: `
<div class="Planner">
<div class="Planner opener" #opener>
<i class="fa" [ngClass]="{
'fa-bars': !opened,
'fa-times': opened
}"></i>
</div>
<aside #sidePanel class="Planner side-panel" [ngClass]="{ opened: opened }">
<div><h1>Table of contents</h1></div>
<TreeView
[model]="plan"
[css]="{ TreeView: 'PlannerTree' }"
category="subs"
[(selection)]="selection"
[strategies]="{ selection: ['ancestors'], click: ['select'], fold: [ foldDepth(), 'not-selected', 'no-child-selection' ]}"
[openerOpts]="{ position: 'none' }"
[displayComponent]="component">
</TreeView>
</aside>
<div #content class="Planner content">
<div *ngFor="let p of plan">
<planner-content [plan]="p"></planner-content>
</div>
</div>
</div>
`,
changeDetection: ChangeDetectionStrategy.OnPush,
host: {
'(document:scroll)': 'onDocumentScroll($event)',
'(document:click)': 'onDocumentClick($event)'
}
})
export class Planner {
@Input() plan : Object
@Input() maxDepth : number = 0
@Input() sticky : boolean = false
@ViewChild("sidePanel") sidePanel : ElementRef
@ViewChild("content") content : ElementRef
@ViewChild("opener") opener: ElementRef
public selection = []
public foldDepth = () => {
const max = this.maxDepth
return function() {
return this.inputs.get().depth >= max
}
}
public css = css
public component = PlannerInjector
public opened = false
private ticking = false
private stickTick = false
private sticking = false
constructor(private _ngZone: NgZone){}
ngAfterViewInit() { this.selection = this.findPosition() }
private nextFrame(_) {
return this._ngZone.runOutsideAngular(() => {
window.requestAnimationFrame(_)
})
}
private findPosition() {
const position = []
const loop = (arr, acc = []) => {
for(let i = 0; i < arr.length; i++) {
const elt = arr[i]
const domElt = document.getElementById(acc.length > 0 ? acc.join("#") + "#" + elt.title : elt.title)
if(domElt && domElt.parentElement &&
domElt.parentElement.getBoundingClientRect().top <= 50 &&
domElt.parentElement.getBoundingClientRect().bottom > 10) {
position.push(elt)
if(elt.subs)
loop(elt.subs, [ ...acc, elt.title ])
break
}
}
}
loop(this.plan)
return position
}
private onDocumentScroll(ev) {
if(!this.ticking) {
this.nextFrame(() => {
const result = this.findPosition()
const newHash = "#" + result.map(_ => _.title).join("#")
if(newHash !== (window.location.hash || "#")) {
this.selection = result
window.history && window.history.replaceState(
{},
document.title,
"#" + result.map(_ => _.title).join("#"))
}
// Prevents safari security exception (SecurityError (DOM Exception 18): Attempt to use history.replaceState() more than 100 times per 30.000000 seconds)
setTimeout(() => this.ticking = false, 100)
})
this.ticking = true
}
if(this.sticky && !this.stickTick) {
if(this.content.nativeElement.getBoundingClientRect().top > 0) {
this.nextFrame(() => {
this.sidePanel.nativeElement.style.position = "absolute"
this.sidePanel.nativeElement.style.top = ""
this.sticking = false
this.stickTick = false
})
} else {
this.nextFrame(() => {
this.sidePanel.nativeElement.style.position = "fixed"
this.sidePanel.nativeElement.style.top = "0px"
this.sticking = true
this.stickTick = false
})
}
this.stickTick = true
}
}
private onDocumentClick(ev) {
if(!(ev.target instanceof HTMLElement)) return
if(this.opener && this.opener.nativeElement.contains(ev.target)) {
this.opened = !this.opened
} else if(this.opened && this.sidePanel && !this.sidePanel.nativeElement.contains(ev.target))
this.opened = false
}
} | the_stack |
// The one and only module
export module TypeInference
{
// Turn on for debugging purposes
export var trace = false;
// Base class of a type: either a TypeArray, TypeVariable, or TypeConstant
export class Type {
// All type varible referenced somewhere by the type, or the type itself if it is a TypeVariable.
typeVars : TypeVariable[] = [];
clone(newTypes:ITypeLookup) : Type {
throw new Error("Clone must be overridden in derived class");
}
}
// A collection of a fixed number of types can be used to represent function types or tuple types.
// A list of types is usually encoded as a nested set of type pairs (TypeArrays with two elements).
// If a TypeArray has Type parameters, quantified unbound type variables, it is considered a "PolyType".
// Binding type variables is done through the clone function
export class TypeArray extends Type
{
constructor(
public types : Type[], computeParameters:boolean)
{
super();
// Compute all referenced types
for (var t of types)
this.typeVars = this.typeVars.concat(t.typeVars);
// Given just a type with type variables the sete of type parameters
// can be inferred based on where they occur in the type tree
if (computeParameters)
this.computeParameters();
}
// A helper function to copy a parameter list
cloneParameters(dest:TypeArray, from:TypeVariable[], newTypes:ITypeLookup) {
var params = [];
for (var tv of from) {
var param = newTypes[tv.name];
if (param == undefined)
throw new Error("Could not find type parameter: " + tv.name);
params.push(param);
}
dest.typeParameterVars = params;
}
// Returns a copy of the type array, substituting type variables using the lookup table.
clone(newTypes:ITypeLookup) : TypeArray {
var r = new TypeArray(this.types.map(t => t.clone(newTypes)), false);
this.cloneParameters(r, this.typeParameterVars, newTypes);
return r;
}
freshVariableNames(id:number) : TypeArray {
var newTypes:ITypeLookup = {};
for (var t of descendantTypes(this))
if (t instanceof TypeVariable)
newTypes[t.name] = new TypeVariable(t.name + "$" + id);
return this.clone(newTypes);
}
// Returns a copy of the type array creating new parameter names.
freshParamNames(id:number) : TypeArray {
// Create a lookup table for the type parameters with new names
var newTypes:ITypeLookup = {};
for (var tp of this.typeParameterNames)
newTypes[tp] = new TypeVariable(tp + "$" + id);
// Clone all of the types.
var types = this.types.map(t => t.clone(newTypes));
// Recursively call "freshParameterNames" on child type arrays as needed.
types = types.map(t => t instanceof TypeArray ? t.freshParamNames(id) : t);
var r = new TypeArray(types, false);
// Now recreate the type parameter list
this.cloneParameters(r, this.typeParameterVars, newTypes);
return r;
}
// A list of the parameter names (without repetition)
get typeParameterNames() : string[] {
return uniqueStrings(this.typeParameterVars.map(tv => tv.name)).sort();
}
// Infer which type variables are actually type parameters (universally quantified)
// based on their position.
computeParameters() {
this.typeParameterVars = [];
// Recursively compute the parameters for base types
this.types.forEach(t => { if (t instanceof TypeArray) t.computeParameters(); });
for (var i=0; i < this.types.length; ++i) {
var child = this.types[i];
// Individual type variables are part of this scheme
if (child instanceof TypeVariable)
_reassignAllTypeVars(child.name, this);
else
if (child instanceof TypeArray) {
// Get the vars of the child type.
// If any of them show up in multiple child arrays, then they
// are part of the parent's child
for (var childVar of child.typeVars)
if (_isTypeVarUsedElsewhere(this, childVar.name, i))
_reassignAllTypeVars(childVar.name, this);
}
}
// Implementation validation step:
// Assure that the type scheme variables are all in the typeVars
for (var v of this.typeParameterVars) {
var i = this.typeVars.indexOf(v);
if (i < 0)
throw new Error("Internal error: type scheme references a variable that is not marked as referenced by the type variable")
}
}
// The type variables that are bound to this TypeArray.
// Always a subset of typeVars. This could have the same type variable repeated twice.
typeParameterVars : TypeVariable[] = [];
// Provides a user friendly representation of the type scheme (list of type parameters)
get typeParametersToString() : string {
return this.isPolyType
? "!" + this.typeParameterNames.join("!") + "."
: "";
}
// Returns true if there is at least one type parameter associated with this type array
get isPolyType() : boolean {
return this.typeParameterVars.length > 0;
}
// A user friendly name
toString() : string {
return this.typeParametersToString + "(" + this.types.join(' ') + ")";
}
}
// A type variable is used for generics (e.g. T0, TR).
// The type variable must belong to a type scheme of a polytype. This is like a "scope" for type variables.
// Computing the type schema is done in an external function.
export class TypeVariable extends Type
{
constructor(
public name : string)
{
super();
this.typeVars.push(this);
}
clone(newTypes:ITypeLookup) : Type {
return this.name in newTypes
? newTypes[this.name] as TypeVariable
: newTypes[this.name] = new TypeVariable(this.name);
}
toString() : string {
return this.name;
}
}
// A type constant is a fixed type (e.g. int, function). Also called a MonoType.
export class TypeConstant extends Type
{
constructor(
public name : string)
{ super(); }
toString() : string {
return this.name;
}
clone(newTypes:ITypeLookup) : TypeConstant {
return new TypeConstant(this.name);
}
}
// A type unifier is a mapping from a type variable to a best-fit type
export class TypeUnifier
{
constructor(
public name:string,
public unifier:Type)
{ }
}
// Given a type variable name finds the type set
export interface ITypeUnifierLookup {
[typeVarName:string] : TypeUnifier;
}
// Associates variable names with type expressions
export interface ITypeLookup {
[varName:string] : Type;
}
// This is helper function helps determine whether a type variable should belong
export function _isTypeVarUsedElsewhere(t:TypeArray, varName:string, pos:number) : boolean {
for (var i=0; i < t.types.length; ++i)
if (i != pos && t.types[i].typeVars.some(v => v.name == varName))
return true;
return false;
}
// Associate the variable with a new type scheme. Removing it from the previous varScheme
export function _reassignVarScheme(v:TypeVariable, t:TypeArray) {
// Remove the variable from all other type schemes below the given one.
for (var x of descendantTypes(t))
if (x instanceof TypeArray)
x.typeParameterVars = x.typeParameterVars.filter(vd => vd.name != v.name);
t.typeParameterVars.push(v);
}
// Associate all variables of the given name in the TypeArray with the TypeArray's scheme
export function _reassignAllTypeVars(varName:string, t:TypeArray) {
t.typeVars.filter(v => v.name == varName).forEach(v => _reassignVarScheme(v, t));
}
// Use this class to unify types that are constrained together.
export class Unifier
{
// Used for generate fresh variable names
id : number = 0;
// Given a type variable name find the unifier. Multiple type variables will map to the same unifier
unifiers : ITypeUnifierLookup = {};
// Unify both types, returning the most specific type possible.
// When a type variable is unified with something the new unifier is stored.
// Note: TypeFunctions and TypePairs ar handled as TypeArrays
// * Constants are preferred over lists and variables
// * Lists are preferred over variables
// * Given two variables, the first one is chosen.
unifyTypes(t1:Type, t2:Type, depth:number=0) : Type {
if (trace)
console.log(`Unification depth ${depth} of ${t1} and ${t2}`);
if (!t1 || !t2)
throw new Error("Missing type expression");
if (t1 == t2)
return t1;
// Variables are least preferred.
if (t1 instanceof TypeVariable)
{
return this._updateUnifier(t1, t2, depth);
}
// If one is a variable its unifier with the new type.
else if (t2 instanceof TypeVariable)
{
return this._updateUnifier(t2, t1, depth);
}
// Constants are best preferred
else if (t1 instanceof TypeConstant && t2 instanceof TypeConstant)
{
if (t1.name != t2.name)
throw new Error("Can't unify: " + t1.name + " and " + t2.name);
else
return t1;
}
// We know by the time we got here, if only one type is a TypeConstant the other is not a variable or a constant
else if (t1 instanceof TypeConstant || t2 instanceof TypeConstant)
{
throw new Error("Can't unify: " + t1 + " and " + t2);
}
// Check for type list unification. We know that both should be type lists since other possibilities are exhausted.
else if (t1 instanceof TypeArray && t2 instanceof TypeArray)
{
return this._unifyLists(t1, t2, depth+1);
}
throw new Error("Internal error, unexpected code path: " + t1 + " and " + t2);
}
// Debug function that dumps prints out a representation of the engine state.
state() : string {
var results = [];
for (var k in this.unifiers) {
var u = this.unifiers[k];
var t = this.getUnifiedType(u.unifier, [], {});
results.push(`type unifier for ${ k }, unifier name ${ u.name }, unifying type ${t}`);
}
return results.join('\n');
}
// Replaces all variables in a type expression with the unified version
// The previousVars variable allows detection of cyclical references
getUnifiedType(expr:Type, previousVars:string[], unifiedVars:any) : Type {
if (expr instanceof TypeConstant)
return expr;
else if (expr instanceof TypeVariable) {
// If we encountered the type variable previously, it meant that there is a recursive relation
for (var i=0; i < previousVars.length; ++i)
if (previousVars[i] == expr.name)
return recursiveType(i);
var u = this.unifiers[expr.name];
if (!u)
return expr;
// If the unifier is a type variable, we are done.
else if (u.unifier instanceof TypeVariable)
return u.unifier;
else if (u.unifier instanceof TypeConstant)
return u.unifier;
else if (u.unifier instanceof TypeArray) {
if (u.name in unifiedVars) {
// We have already seen this unified var before
var u2 = u.unifier.freshParamNames(unifiedVars[u.name] += 1);
return this.getUnifiedType(u2, [expr.name].concat(previousVars), unifiedVars);
}
else {
unifiedVars[u.name] = 0;
return this.getUnifiedType(u.unifier, [expr.name].concat(previousVars), unifiedVars);
}
}
else
throw new Error("Unhandled kind of type " + expr);
}
else if (expr instanceof TypeArray) {
var types = expr.types.map(t => this.getUnifiedType(t, previousVars, unifiedVars));
var r = new TypeArray(types, false);
return r;
}
else
throw new Error("Unrecognized kind of type expression " + expr);
}
// Choose one of two unifiers, or continue the unification process if necessary
_chooseBestUnifier(t1:Type, t2:Type, depth:number) : Type {
var r:Type;
if (t1 instanceof TypeVariable && t2 instanceof TypeVariable)
r = t1;
else if (t1 instanceof TypeVariable)
r = t2;
else if (t2 instanceof TypeVariable)
r = t1;
else
r = this.unifyTypes(t1, t2, depth+1);
if (trace)
console.log(`Chose type for unification ${r} between ${t1} and ${t2} at depth ${depth}`)
return r;
}
// Unifying lists involves unifying each element
_unifyLists(list1:TypeArray, list2:TypeArray, depth:number) : TypeArray {
if (list1.types.length != list2.types.length)
throw new Error("Cannot unify differently sized lists: " + list1 + " and " + list2);
var rtypes : Type[] = [];
for (var i=0; i < list1.types.length; ++i)
rtypes.push(this.unifyTypes(list1.types[i], list2.types[i], depth));
// We just return the first list for now.
return list1;
}
// All unifiers that refer to varName as the unifier are pointed to the new unifier
_updateVariableUnifiers(varName:string, u:TypeUnifier) {
for (var x in this.unifiers) {
var t = this.unifiers[x].unifier;
if (t instanceof TypeVariable)
if (t.name == varName)
this.unifiers[x] = u;
}
}
// Computes the best unifier between the current unifier and the new variable.
// Updates all unifiers which point to a (or to t if t is a TypeVar) to use the new type.
_updateUnifier(a:TypeVariable, t:Type, depth:number) : Type {
var u = this._getOrCreateUnifier(a);
if (t instanceof TypeVariable)
t = this._getOrCreateUnifier(t).unifier;
u.unifier = this._chooseBestUnifier(u.unifier, t, depth);
this._updateVariableUnifiers(a.name, u);
if (t instanceof TypeVariable)
this._updateVariableUnifiers(t.name, u);
return u.unifier;
}
// Gets or creates a type unifiers for a type variables
_getOrCreateUnifier(t : TypeVariable) : TypeUnifier {
if (!(t.name in this.unifiers))
return this.unifiers[t.name] = new TypeUnifier(t.name, t);
else
return this.unifiers[t.name];
}
}
//======================================================================================
// Helper functions
// Creates a type list as nested pairs ("cons" cells ala lisp).
// The last type is assumed to be a row variable.
export function rowPolymorphicList(types:Type[]) : Type {
if (types.length == 0)
throw new Error("Expected a type list with at least one type variable")
else if (types.length == 1) {
if (types[0] instanceof TypeVariable)
return types[0];
else
throw new Error("Expected a row variable in the final position");
}
else
return typeArray([types[0], rowPolymorphicList(types.slice(1))]);
}
// Creates a row-polymorphic function type: adding the implicit row variable
export function rowPolymorphicFunction(inputs:Type[], outputs:Type[]) : TypeArray {
var row = typeVariable('_');
inputs.push(row);
outputs.push(row);
return functionType(rowPolymorphicList(inputs), rowPolymorphicList(outputs));
}
// Creates a type array from an array of types
export function typeArray(types:Type[]) : TypeArray {
return new TypeArray(types, true);
}
// Creates a type constant
export function typeConstant(name:string) : TypeConstant {
return new TypeConstant(name);
}
// Creates a type variable
export function typeVariable(name:string) : TypeVariable {
return new TypeVariable(name);
}
// Creates a function type, as a special kind of a TypeArray
export function functionType(input:Type, output:Type) : TypeArray {
return typeArray([input, typeConstant('->'), output]);
}
// Creates an array type, as a special kind of TypeArray
export function arrayType(element:Type) : TypeArray {
return typeArray([element, typeConstant('[]')]);
}
// Creates a list type, as a special kind of TypeArray
export function listType(element:Type) : TypeArray {
return typeArray([element, typeConstant('*')]);
}
// Creates a recursive type, as a special kind of TypeArray. The numberical value
// refers to the depth of the recursion: how many TypeArrays you have to go up
// to find the recurison base case.
export function recursiveType(depth:Number) : TypeArray {
return typeArray([typeConstant('rec'), typeConstant(depth.toString())]);
}
// Returns true if and only if the type is a type constant with the specified name
export function isTypeConstant(t:Type, name:string) : boolean {
return t instanceof TypeConstant && t.name === name;
}
// Returns true if and only if the type is a type constant with the specified name
export function isTypeVariable(t:Type, name:string) : boolean {
return t instanceof TypeVariable && t.name === name;
}
// Returns true if any of the types are the type variable
export function variableOccurs(name:string, type:Type) : boolean {
return descendantTypes(type).some(t => isTypeVariable(t, name));
}
// Returns true if and only if the type is a type constant with the specified name
export function isTypeArray(t:Type, name:string) : boolean {
return t instanceof TypeArray && t.types.length == 2 && isTypeConstant(t.types[1], '[]');
}
// Returns true iff the type is a TypeArary representing a function type
export function isFunctionType(t:Type) : boolean {
return t instanceof TypeArray && t.types.length == 3 && isTypeConstant(t.types[1], '->');
}
// Returns the input types (argument types) of a TypeArray representing a function type
export function functionInput(t:Type) : Type {
if (!isFunctionType(t)) throw new Error("Expected a function type");
return (t as TypeArray).types[0];
}
// Returns the output types (return types) of a TypeArray representing a function type
export function functionOutput(t:Type) : Type {
if (!isFunctionType(t)) throw new Error("Expected a function type");
return (t as TypeArray).types[2];
}
// Returns all types contained in this type
export function descendantTypes(t:Type, r:Type[] = []) : Type[] {
r.push(t);
if (t instanceof TypeArray)
t.types.forEach(t2 => descendantTypes(t2, r));
return r;
}
// Returns true if the type is a polytype
export function isPolyType(t:Type) {
return t instanceof TypeArray && t.typeParameterVars.length > 0;
}
// Returns true if the type is a function that generates a polytype.
export function generatesPolytypes(t:Type) : boolean {
if (!isFunctionType(t))
return false;
return descendantTypes(functionOutput(t)).some(isPolyType);
}
// Returns the type of the id function
export function idFunction() : TypeArray {
var s = typeVariable('_');
return functionType(s, s);
}
//========================================================
// Variable name functions
// Rename all type variables os that they follow T0..TN according to the order the show in the tree.
export function normalizeVarNames(t:Type) : Type {
var names = {};
var count = 0;
for (var dt of descendantTypes(t))
if (dt instanceof TypeVariable)
if (!(dt.name in names))
names[dt.name] = typeVariable("t" + count++);
return t.clone(names);
}
// Converts a number to a letter from 'a' to 'z'.
function numberToLetters(n:number) : string {
return String.fromCharCode(97 + n);
}
// Rename all type variables so that they are alphabetical in the order they occur in the tree
export function alphabetizeVarNames(t:Type) : Type {
var names = {};
var count = 0;
for (var dt of descendantTypes(t))
if (dt instanceof TypeVariable)
if (!(dt.name in names))
names[dt.name] = typeVariable(numberToLetters(count++));
return t.clone(names);
}
// Compares whether two types are the same after normalizing the type variables.
export function areTypesSame(t1:Type, t2:Type) {
var s1 = normalizeVarNames(t1).toString();
var s2 = normalizeVarNames(t2).toString();
return s1 === s2;
}
export function variableOccursOnInput(varName:string, type:TypeArray) {
for (var t of descendantTypes(type)) {
if (isFunctionType(t)) {
var input = functionInput(type);
if (variableOccurs(varName, input)) {
return true;
}
}
}
}
// Returns true if and only if the type is valid
export function isValid(type:Type) {
for (var t of descendantTypes(type)) {
if (isTypeConstant(t, "rec")) {
return false;
}
else if (t instanceof TypeArray) {
if (isFunctionType(t))
for (var p of t.typeParameterNames)
if (!variableOccursOnInput(p, t))
return false;
}
}
return true;
}
//==========================================================================================
// Type Environments
//
// This is the top-level implementation of a type inference algorithm that would be used in
// a programming language.
// Used to track equivalencies between types
class TypeConstraint
{
constructor(
public a:Type,
public b:Type,
public location:any)
{ }
}
// An example implementation of a type environment. Used to implement a type inference algorithm
// in a typical language with variable tracking and scopes.
export class TypeEnv
{
unifier : Unifier = new Unifier();
scopes : ITypeLookup[] = [{}]
history : ITypeLookup[] = [{}];
constraints : TypeConstraint[];
index : number = 0;
pushScope() {
var scope = {};
this.history.push(scope);
this.scopes.push(scope);
}
popScope() {
this.scopes.pop();
}
currentScope() : ITypeLookup {
return this.scopes[this.scopes.length-1];
}
getName(name:string) : Type {
for (var scope of this.scopes)
if (name in scope)
return scope[name];
throw new Error("Could not find name: " + name);
}
addName(name:string) {
var scope = this.currentScope();
if (name in scope) throw new Error("Name already defined in current scope: " + name);
return scope[name] = null;
}
findNameScope(name:string) : ITypeLookup {
for (var i=this.scopes.length-1; i >= 0; ++i) {
var scope = this.scopes[i];
if (name in scope)
return scope;
}
throw new Error("Could not find name in any of the scopes: "+ name)
}
addConstraint(a:Type, b:Type, location:any) {
this.constraints.push(new TypeConstraint(a, b, location));
}
addAssignment(name:string, type:Type, location:any = null) : Type {
var scope = this.findNameScope(name);
if (scope[name] == null)
scope[name] = type;
else
this.addConstraint(scope[name], type, location);
return type;
}
addFunctionCall(name:string, args:TypeArray, location:any = null) : Type {
var funcType = this.findNameScope(name)[name] as TypeArray;
if (!isFunctionType(funcType)) throw new Error("Not a function type associated with " + name);
var input = functionInput(funcType);
var output = functionOutput(funcType);
this.addConstraint(input, output, location);
return output;
}
}
//============================================================
// Top level type operations
// - Composition
// - Application
// - Quotation
// Returns the function type that results by composing two function types
export function composeFunctions(f:TypeArray, g:TypeArray) : TypeArray {
if (!isFunctionType(f)) throw new Error("Expected a function type for f");
if (!isFunctionType(g)) throw new Error("Expected a function type for g");
f = f.freshVariableNames(0) as TypeArray;
g = g.freshVariableNames(1) as TypeArray;
if (trace) {
console.log("f: " + f);
console.log("g: " + g);
}
var inF = functionInput(f);
var outF = functionOutput(f);
var inG = functionInput(g);
var outG = functionOutput(g);
var e = new Unifier();
e.unifyTypes(outF, inG);
var input = e.getUnifiedType(inF, [], {});
var output = e.getUnifiedType(outG, [], {});
var r = functionType(input, output);
if (trace) {
console.log(e.state());
console.log("Intermediate result: " + r)
}
//r = r.freshParameterNames(0);
// Recompute parameters.
r.computeParameters();
if (trace) {
console.log("Final result: " + r);
}
return r;
}
// Composes a chain of functions
export function composeFunctionChain(fxns:TypeArray[]) : TypeArray {
if (fxns.length == 0)
return idFunction();
var t = fxns[0];
for (var i=1; i < fxns.length; ++i)
t = composeFunctions(t, fxns[i]);
return t;
}
// Applies a function to input arguments and returns the result
export function applyFunction(fxn:TypeArray, args:Type) : Type {
var u = new Unifier();
fxn = fxn.clone({});
args = args.clone({});
var input = functionInput(fxn);
var output = functionOutput(fxn);
u.unifyTypes(input, args);
return u.getUnifiedType(output, [], {});
}
// Creates a function type that generates the given type
export function quotation(x:Type) : TypeArray {
var row = typeVariable('_');
return functionType(row, typeArray([x, row]));
}
//=========================================================
// A simple helper class for implementing scoped programming languages with names like the lambda calculus.
// This class is more intended as an example of usage of the algorithm than for use in production code
export class ScopedTypeInferenceEngine
{
id : number = 0;
names : string[] = [];
types : Type[] = [];
unifier : Unifier = new Unifier();
applyFunction(t:Type, args:Type) : Type {
if (!isFunctionType(t))
{
// Only variables and functions can be applied
if (!(t instanceof TypeVariable))
throw new Error("Type associated with " + name + " is neither a function type or a type variable: " + t);
// Generate a new function type
var newInputType = typeVariable(t.name + "_i");
var newOutputType = typeVariable(t.name + "_o");
var fxnType = functionType(newInputType, newOutputType);
// Unify the new function type with the old variable
this.unifier.unifyTypes(t, fxnType);
t = fxnType;
}
this.unifier.unifyTypes(functionInput(t), args);
var r = functionOutput(t);
return this.unifier.getUnifiedType(r, [], {});
}
introduceVariable(name:string) : Type {
var t = typeVariable(name + '$' + this.id++);
this.names.push(name);
this.types.push(t);
return t;
}
lookupOrIntroduceVariable(name:string) : Type {
var n = this.indexOfVariable(name);
return (n < 0) ? this.introduceVariable(name) : this.types[n];
}
assignVariable(name:string, t:Type) : Type {
return this.unifier.unifyTypes(this.lookupVariable(name), t);
}
indexOfVariable(name:string) : number {
return this.names.lastIndexOf(name);
}
lookupVariable(name:string) : Type {
var n = this.indexOfVariable(name);
if (n < 0) throw new Error("Could not find variable: " + name);
return this.types[n];
}
getUnifiedType(t:Type) : Type {
var r = this.unifier.getUnifiedType(t, [], {});
if (r instanceof TypeArray)
r.computeParameters();
return r;
}
popVariable() {
this.types.pop();
this.names.pop();
}
}
//=====================================================================
// General purpose utility functions
// Returns only the uniquely named strings
export function uniqueStrings(xs:string[]) : string[] {
var r = {};
for (var x of xs)
r[x] = true;
return Object.keys(r);
}
} | the_stack |
import { createStore } from "frontity";
import { Frontity, MergePackages } from "frontity/types";
import clone from "clone-deep";
import merge from "deepmerge";
import { transformLink } from "../transform-link";
import wpSource from "../../";
import WpSource from "../../../types";
type Packages = MergePackages<Frontity, WpSource>;
describe("transformLink (w/o subdirectory)", () => {
const initStore = () => {
const config = clone(merge(wpSource(), { state: { frontity: {} } }));
return createStore<Packages>(config);
};
it("should work for Free WP com - configured by state.source.url", () => {
const { state } = initStore();
// Define the options set by the user.
state.frontity.url = "https://final-domain.com";
state.source.url = "https://sub.wordpress.com";
const entity = { link: "/some-link/" };
transformLink({ entity, state });
expect(entity.link).toBe("/some-link/");
});
it("should work for Free WP com - configured by state.wpSource.api", () => {
const { state } = initStore();
// Define the options set by the user.
state.frontity.url = "https://final-domain.com";
state.wpSource.api =
"https://public-api.wordpress.com/wp/v2/sites/sub.wordpress.com";
const entity = { link: "/some-link/" };
transformLink({ entity, state });
expect(entity.link).toBe("/some-link/");
});
it("should work for Free WP com - configured by state.source.api", () => {
const { state } = initStore();
// Define the options set by the user.
state.frontity.url = "https://final-domain.com";
state.source.api =
"https://public-api.wordpress.com/wp/v2/sites/sub.wordpress.com";
const entity = { link: "/some-link/" };
transformLink({ entity, state });
expect(entity.link).toBe("/some-link/");
});
it("should work for Personal and Premium WP com - configured by state.source.url and state.wpSource.isWpCom", () => {
const { state } = initStore();
// Define the options set by the user.
state.frontity.url = "https://final-domain.com";
state.source.url = "https://wp-domain.com";
state.wpSource.isWpCom = true;
// Transform the link of an entity mock.
const entity = { link: "/some-link/" };
transformLink({ entity, state });
expect(entity.link).toBe("/some-link/");
});
it("should work for Personal and Premium WP com - configured by state.wpSource.api", () => {
const { state } = initStore();
// Define the options set by the user.
state.frontity.url = "https://final-domain.com";
state.wpSource.api =
"https://public-api.wordpress.com/wp/v2/sites/wp-domain.com";
// Transform the link of an entity mock.
const entity = { link: "/some-link/" };
transformLink({ entity, state });
expect(entity.link).toBe("/some-link/");
});
it("should work for Personal and Premium WP com - configured by state.source.api", () => {
const { state } = initStore();
// Define the options set by the user.
state.frontity.url = "https://final-domain.com";
state.source.api =
"https://public-api.wordpress.com/wp/v2/sites/wp-domain.com";
// Transform the link of an entity mock.
const entity = { link: "/some-link/" };
transformLink({ entity, state });
expect(entity.link).toBe("/some-link/");
});
it("should work for WP org and Business WP com - configured by state.source.url", () => {
const { state } = initStore();
// Define the options set by the user.
state.frontity.url = "https://final-domain.com";
state.source.url = "https://wp-domain.com";
// Transform the link of an entity mock.
const entity = { link: "/some-link/" };
transformLink({ entity, state });
expect(entity.link).toBe("/some-link/");
});
it("should work for WP org and Business WP com - configured by state.source.url (w/ subdirectory)", () => {
const { state } = initStore();
// Define the options set by the user.
state.frontity.url = "https://final-domain.com";
state.source.url = "https://wp-domain.com/subdir";
// Transform the link of an entity mock.
const entity = { link: "/subdir/some-link/" };
transformLink({ entity, state });
expect(entity.link).toBe("/some-link/");
});
it("should work for WP org and Business WP com - configured by state.wpSource.api", () => {
const { state } = initStore();
// Define the options set by the user.
state.frontity.url = "https://final-domain.com";
state.wpSource.api = "https://wp-domain.com/wp-json/";
// Transform the link of an entity mock.
const entity = { link: "/some-link/" };
transformLink({ entity, state });
expect(entity.link).toBe("/some-link/");
});
it("should work for WP org and Business WP com - configured by state.wpSource.api and custom prefix", () => {
const { state } = initStore();
// Define the options set by the user.
state.frontity.url = "https://final-domain.com";
state.wpSource.api = "https://wp-domain.com/api/";
state.wpSource.prefix = "/api";
// Transform the link of an entity mock.
const entity = { link: "/some-link/" };
transformLink({ entity, state });
expect(entity.link).toBe("/some-link/");
});
it("should work for WP org and Business WP com - configured by state.wpSource.api (w/ subdirectory)", () => {
const { state } = initStore();
// Define the options set by the user.
state.frontity.url = "https://final-domain.com";
state.wpSource.api = "https://wp-domain.com/subdir/wp-json/";
// Transform the link of an entity mock.
const entity = { link: "/subdir/some-link/" };
transformLink({ entity, state });
expect(entity.link).toBe("/some-link/");
});
it("should work for WP org and Business WP com - configured by state.wpSource.api and custom prefix (w/ subdirectory)", () => {
const { state } = initStore();
// Define the options set by the user.
state.frontity.url = "https://final-domain.com";
state.wpSource.api = "https://wp-domain.com/subdir/api/";
state.wpSource.prefix = "/api";
// Transform the link of an entity mock.
const entity = { link: "/subdir/some-link/" };
transformLink({ entity, state });
expect(entity.link).toBe("/some-link/");
});
it("should not add a trailing slash for links with hash part", () => {
const { state } = initStore();
// Define the options set by the user.
state.frontity.url = "https://final-domain.com";
// Transform the link of an entity mock.
const entity = { link: "/some-link/#element-id" };
transformLink({ entity, state });
expect(entity.link).toBe("/some-link/#element-id");
});
});
describe("transformLink (w/ subdirectory)", () => {
const initStore = () => {
const config = clone(merge(wpSource(), { state: { frontity: {} } }));
return createStore<Packages>(config);
};
const subdirectory = "subdir";
it("should work for Free WP com - configured by state.source.url", () => {
const { state } = initStore();
// Define the options set by the user.
state.frontity.url = "https://final-domain.com";
state.source.url = "https://sub.wordpress.com";
const entity = { link: "/some-link/" };
transformLink({ entity, state, subdirectory });
expect(entity.link).toBe("/subdir/some-link/");
});
it("should work for Free WP com - configured by state.wpSource.api", () => {
const { state } = initStore();
// Define the options set by the user.
state.frontity.url = "https://final-domain.com";
state.wpSource.api =
"https://public-api.wordpress.com/wp/v2/sites/sub.wordpress.com";
const entity = { link: "/some-link/" };
transformLink({ entity, state, subdirectory });
expect(entity.link).toBe("/subdir/some-link/");
});
it("should work for Free WP com - configured by state.source.api", () => {
const { state } = initStore();
// Define the options set by the user.
state.frontity.url = "https://final-domain.com";
state.source.api =
"https://public-api.wordpress.com/wp/v2/sites/sub.wordpress.com";
const entity = { link: "/some-link/" };
transformLink({ entity, state, subdirectory });
expect(entity.link).toBe("/subdir/some-link/");
});
it("should work for Personal and Premium WP com - configured by state.source.url and state.wpSource.isWpCom", () => {
const { state } = initStore();
// Define the options set by the user.
state.frontity.url = "https://final-domain.com";
state.source.url = "https://wp-domain.com";
state.wpSource.isWpCom = true;
// Transform the link of an entity mock.
const entity = { link: "/some-link/" };
transformLink({ entity, state, subdirectory });
expect(entity.link).toBe("/subdir/some-link/");
});
it("should work for Personal and Premium WP com - configured by state.wpSource.api", () => {
const { state } = initStore();
// Define the options set by the user.
state.frontity.url = "https://final-domain.com";
state.wpSource.api =
"https://public-api.wordpress.com/wp/v2/sites/wp-domain.com";
// Transform the link of an entity mock.
const entity = { link: "/some-link/" };
transformLink({ entity, state, subdirectory });
expect(entity.link).toBe("/subdir/some-link/");
});
it("should work for Personal and Premium WP com - configured by state.source.api", () => {
const { state } = initStore();
// Define the options set by the user.
state.frontity.url = "https://final-domain.com";
state.source.api =
"https://public-api.wordpress.com/wp/v2/sites/wp-domain.com";
// Transform the link of an entity mock.
const entity = { link: "/some-link/" };
transformLink({ entity, state, subdirectory });
expect(entity.link).toBe("/subdir/some-link/");
});
it("should work for WP org and Business WP com - configured by state.source.url", () => {
const { state } = initStore();
// Define the options set by the user.
state.frontity.url = "https://final-domain.com";
state.source.url = "https://wp-domain.com";
// Transform the link of an entity mock.
const entity = { link: "/some-link/" };
transformLink({ entity, state, subdirectory });
expect(entity.link).toBe("/subdir/some-link/");
});
it("should work for WP org and Business WP com - configured by state.source.url (w/ subdirectory)", () => {
const { state } = initStore();
// Define the options set by the user.
state.frontity.url = "https://final-domain.com";
state.source.url = "https://wp-domain.com/subdir";
// Transform the link of an entity mock.
const entity = { link: "/subdir/some-link/" };
transformLink({ entity, state, subdirectory });
expect(entity.link).toBe("/subdir/some-link/");
});
it("should work for WP org and Business WP com - configured by state.wpSource.api", () => {
const { state } = initStore();
// Define the options set by the user.
state.frontity.url = "https://final-domain.com";
state.wpSource.api = "https://wp-domain.com/wp-json/";
// Transform the link of an entity mock.
const entity = { link: "/some-link/" };
transformLink({ entity, state, subdirectory });
expect(entity.link).toBe("/subdir/some-link/");
});
it("should work for WP org and Business WP com - configured by state.wpSource.api and custom prefix", () => {
const { state } = initStore();
// Define the options set by the user.
state.frontity.url = "https://final-domain.com";
state.wpSource.api = "https://wp-domain.com/api/";
state.wpSource.prefix = "/api";
// Transform the link of an entity mock.
const entity = { link: "/some-link/" };
transformLink({ entity, state, subdirectory });
expect(entity.link).toBe("/subdir/some-link/");
});
it("should work for WP org and Business WP com - configured by state.wpSource.api (w/ subdirectory)", () => {
const { state } = initStore();
// Define the options set by the user.
state.frontity.url = "https://final-domain.com";
state.wpSource.api = "https://wp-domain.com/wp-subdir/wp-json/";
// Transform the link of an entity mock.
const entity = { link: "/wp-subdir/some-link/" };
transformLink({ entity, state, subdirectory });
expect(entity.link).toBe("/subdir/some-link/");
});
it("should work for WP org and Business WP com - configured by state.wpSource.api and custom prefix (w/ subdirectory)", () => {
const { state } = initStore();
// Define the options set by the user.
state.frontity.url = "https://final-domain.com";
state.wpSource.api = "https://wp-domain.com/wp-subdir/api/";
state.wpSource.prefix = "/api";
// Transform the link of an entity mock.
const entity = { link: "/wp-subdir/some-link/" };
transformLink({ entity, state, subdirectory });
expect(entity.link).toBe("/subdir/some-link/");
});
it("should not add a trailing slash for links with hash part", () => {
const { state } = initStore();
// Define the options set by the user.
state.frontity.url = "https://final-domain.com";
// Transform the link of an entity mock.
const entity = { link: "/some-link/#element-id" };
transformLink({ entity, state, subdirectory });
expect(entity.link).toBe("/subdir/some-link/#element-id");
});
});
describe("transformLink (state.source.subdirectory)", () => {
const initStore = () => {
const config = clone(merge(wpSource(), { state: { frontity: {} } }));
return createStore<Packages>(config);
};
it("should work for Free WP com - configured by state.source.url", () => {
const { state } = initStore();
// Define the options set by the user.
state.frontity.url = "https://final-domain.com/subdir";
state.source.subdirectory = "/subdir";
state.source.url = "https://sub.wordpress.com";
const entity = { link: "/some-link/" };
transformLink({ entity, state });
expect(entity.link).toBe("/subdir/some-link/");
});
it("should work for Free WP com - configured by state.wpSource.api", () => {
const { state } = initStore();
// Define the options set by the user.
state.frontity.url = "https://final-domain.com/subdir";
state.source.subdirectory = "/subdir";
state.wpSource.api =
"https://public-api.wordpress.com/wp/v2/sites/sub.wordpress.com";
const entity = { link: "/some-link/" };
transformLink({ entity, state });
expect(entity.link).toBe("/subdir/some-link/");
});
it("should work for Free WP com - configured by state.source.api", () => {
const { state } = initStore();
// Define the options set by the user.
state.frontity.url = "https://final-domain.com/subdir";
state.source.subdirectory = "/subdir";
state.source.api =
"https://public-api.wordpress.com/wp/v2/sites/sub.wordpress.com";
const entity = { link: "/some-link/" };
transformLink({ entity, state });
expect(entity.link).toBe("/subdir/some-link/");
});
it("should work for Personal and Premium WP com - configured by state.source.url and state.wpSource.isWpCom", () => {
const { state } = initStore();
// Define the options set by the user.
state.frontity.url = "https://final-domain.com/subdir";
state.source.subdirectory = "/subdir";
state.source.url = "https://wp-domain.com";
state.wpSource.isWpCom = true;
// Transform the link of an entity mock.
const entity = { link: "/some-link/" };
transformLink({ entity, state });
expect(entity.link).toBe("/subdir/some-link/");
});
it("should work for Personal and Premium WP com - configured by state.wpSource.api", () => {
const { state } = initStore();
// Define the options set by the user.
state.frontity.url = "https://final-domain.com/subdir";
state.source.subdirectory = "/subdir";
state.wpSource.api =
"https://public-api.wordpress.com/wp/v2/sites/wp-domain.com";
// Transform the link of an entity mock.
const entity = { link: "/some-link/" };
transformLink({ entity, state });
expect(entity.link).toBe("/subdir/some-link/");
});
it("should work for Personal and Premium WP com - configured by state.source.api", () => {
const { state } = initStore();
// Define the options set by the user.
state.frontity.url = "https://final-domain.com/subdir";
state.source.subdirectory = "/subdir";
state.source.api =
"https://public-api.wordpress.com/wp/v2/sites/wp-domain.com";
// Transform the link of an entity mock.
const entity = { link: "/some-link/" };
transformLink({ entity, state });
expect(entity.link).toBe("/subdir/some-link/");
});
it("should work for WP org and Business WP com - configured by state.source.url", () => {
const { state } = initStore();
// Define the options set by the user.
state.frontity.url = "https://final-domain.com/subdir";
state.source.subdirectory = "/subdir";
state.source.url = "https://wp-domain.com";
// Transform the link of an entity mock.
const entity = { link: "/some-link/" };
transformLink({ entity, state });
expect(entity.link).toBe("/subdir/some-link/");
});
it("should work for WP org and Business WP com - configured by state.source.url (w/ subdirectory)", () => {
const { state } = initStore();
// Define the options set by the user.
state.frontity.url = "https://final-domain.com/subdir";
state.source.subdirectory = "/subdir";
state.source.url = "https://wp-domain.com/subdir";
// Transform the link of an entity mock.
const entity = { link: "/subdir/some-link/" };
transformLink({ entity, state });
expect(entity.link).toBe("/subdir/some-link/");
});
it("should work for WP org and Business WP com - configured by state.wpSource.api", () => {
const { state } = initStore();
// Define the options set by the user.
state.frontity.url = "https://final-domain.com/subdir";
state.source.subdirectory = "/subdir";
state.wpSource.api = "https://wp-domain.com/wp-json/";
// Transform the link of an entity mock.
const entity = { link: "/some-link/" };
transformLink({ entity, state });
expect(entity.link).toBe("/subdir/some-link/");
});
it("should work for WP org and Business WP com - configured by state.wpSource.api and custom prefix", () => {
const { state } = initStore();
// Define the options set by the user.
state.frontity.url = "https://final-domain.com/subdir";
state.source.subdirectory = "/subdir";
state.wpSource.api = "https://wp-domain.com/api/";
state.wpSource.prefix = "/api";
// Transform the link of an entity mock.
const entity = { link: "/some-link/" };
transformLink({ entity, state });
expect(entity.link).toBe("/subdir/some-link/");
});
it("should work for WP org and Business WP com - configured by state.wpSource.api (w/ subdirectory)", () => {
const { state } = initStore();
// Define the options set by the user.
state.frontity.url = "https://final-domain.com";
state.source.subdirectory = "/subdir";
state.wpSource.api = "https://wp-domain.com/wp-subdir/wp-json/";
// Transform the link of an entity mock.
const entity = { link: "/wp-subdir/some-link/" };
transformLink({ entity, state });
expect(entity.link).toBe("/subdir/some-link/");
});
it("should work for WP org and Business WP com - configured by state.wpSource.api and custom prefix (w/ subdirectory)", () => {
const { state } = initStore();
// Define the options set by the user.
state.frontity.url = "https://final-domain.com";
state.source.subdirectory = "/subdir";
state.wpSource.api = "https://wp-domain.com/wp-subdir/api/";
state.wpSource.prefix = "/api";
// Transform the link of an entity mock.
const entity = { link: "/wp-subdir/some-link/" };
transformLink({ entity, state });
expect(entity.link).toBe("/subdir/some-link/");
});
it("should not add a trailing slash for links with hash part", () => {
const { state } = initStore();
// Define the options set by the user.
state.frontity.url = "https://final-domain.com";
state.source.subdirectory = "/subdir";
// Transform the link of an entity mock.
const entity = { link: "/some-link/#element-id" };
transformLink({ entity, state });
expect(entity.link).toBe("/subdir/some-link/#element-id");
});
});
describe("transformLink (state.frontity.url w/ subdirectory)", () => {
const initStore = () => {
const config = clone(merge(wpSource(), { state: { frontity: {} } }));
return createStore<Packages>(config);
};
it("should work for Free WP com - configured by state.source.url", () => {
const { state } = initStore();
// Define the options set by the user.
state.frontity.url = "https://final-domain.com/subdir";
state.source.url = "https://sub.wordpress.com";
const entity = { link: "/some-link/" };
transformLink({ entity, state });
expect(entity.link).toBe("/subdir/some-link/");
});
it("should work for Free WP com - configured by state.wpSource.api", () => {
const { state } = initStore();
// Define the options set by the user.
state.frontity.url = "https://final-domain.com/subdir";
state.wpSource.api =
"https://public-api.wordpress.com/wp/v2/sites/sub.wordpress.com";
const entity = { link: "/some-link/" };
transformLink({ entity, state });
expect(entity.link).toBe("/subdir/some-link/");
});
it("should work for Free WP com - configured by state.source.api", () => {
const { state } = initStore();
// Define the options set by the user.
state.frontity.url = "https://final-domain.com/subdir";
state.source.api =
"https://public-api.wordpress.com/wp/v2/sites/sub.wordpress.com";
const entity = { link: "/some-link/" };
transformLink({ entity, state });
expect(entity.link).toBe("/subdir/some-link/");
});
it("should work for Personal and Premium WP com - configured by state.source.url and state.wpSource.isWpCom", () => {
const { state } = initStore();
// Define the options set by the user.
state.frontity.url = "https://final-domain.com/subdir";
state.source.url = "https://wp-domain.com";
state.wpSource.isWpCom = true;
// Transform the link of an entity mock.
const entity = { link: "/some-link/" };
transformLink({ entity, state });
expect(entity.link).toBe("/subdir/some-link/");
});
it("should work for Personal and Premium WP com - configured by state.wpSource.api", () => {
const { state } = initStore();
// Define the options set by the user.
state.frontity.url = "https://final-domain.com/subdir";
state.wpSource.api =
"https://public-api.wordpress.com/wp/v2/sites/wp-domain.com";
// Transform the link of an entity mock.
const entity = { link: "/some-link/" };
transformLink({ entity, state });
expect(entity.link).toBe("/subdir/some-link/");
});
it("should work for Personal and Premium WP com - configured by state.source.api", () => {
const { state } = initStore();
// Define the options set by the user.
state.frontity.url = "https://final-domain.com/subdir";
state.source.api =
"https://public-api.wordpress.com/wp/v2/sites/wp-domain.com";
// Transform the link of an entity mock.
const entity = { link: "/some-link/" };
transformLink({ entity, state });
expect(entity.link).toBe("/subdir/some-link/");
});
it("should work for WP org and Business WP com - configured by state.source.url", () => {
const { state } = initStore();
// Define the options set by the user.
state.frontity.url = "https://final-domain.com/subdir";
state.source.url = "https://wp-domain.com";
// Transform the link of an entity mock.
const entity = { link: "/some-link/" };
transformLink({ entity, state });
expect(entity.link).toBe("/subdir/some-link/");
});
it("should work for WP org and Business WP com - configured by state.source.url (w/ subdirectory)", () => {
const { state } = initStore();
// Define the options set by the user.
state.frontity.url = "https://final-domain.com/subdir";
state.source.url = "https://wp-domain.com/subdir";
// Transform the link of an entity mock.
const entity = { link: "/subdir/some-link/" };
transformLink({ entity, state });
expect(entity.link).toBe("/subdir/some-link/");
});
it("should work for WP org and Business WP com - configured by state.wpSource.api", () => {
const { state } = initStore();
// Define the options set by the user.
state.frontity.url = "https://final-domain.com/subdir";
state.wpSource.api = "https://wp-domain.com/wp-json/";
// Transform the link of an entity mock.
const entity = { link: "/some-link/" };
transformLink({ entity, state });
expect(entity.link).toBe("/subdir/some-link/");
});
it("should work for WP org and Business WP com - configured by state.wpSource.api and custom prefix", () => {
const { state } = initStore();
// Define the options set by the user.
state.frontity.url = "https://final-domain.com/subdir";
state.wpSource.api = "https://wp-domain.com/api/";
state.wpSource.prefix = "/api";
// Transform the link of an entity mock.
const entity = { link: "/some-link/" };
transformLink({ entity, state });
expect(entity.link).toBe("/subdir/some-link/");
});
it("should work for WP org and Business WP com - configured by state.wpSource.api (w/ subdirectory)", () => {
const { state } = initStore();
// Define the options set by the user.
state.frontity.url = "https://final-domain.com/subdir";
state.wpSource.api = "https://wp-domain.com/wp-subdir/wp-json/";
// Transform the link of an entity mock.
const entity = { link: "/wp-subdir/some-link/" };
transformLink({ entity, state });
expect(entity.link).toBe("/subdir/some-link/");
});
it("should work for WP org and Business WP com - configured by state.wpSource.api and custom prefix (w/ subdirectory)", () => {
const { state } = initStore();
// Define the options set by the user.
state.frontity.url = "https://final-domain.com/subdir";
state.wpSource.api = "https://wp-domain.com/wp-subdir/api/";
state.wpSource.prefix = "/api";
// Transform the link of an entity mock.
const entity = { link: "/wp-subdir/some-link/" };
transformLink({ entity, state });
expect(entity.link).toBe("/subdir/some-link/");
});
it("should not add a trailing slash for links with hash part", () => {
const { state } = initStore();
// Define the options set by the user.
state.frontity.url = "https://final-domain.com/subdir";
state.source.url = "https://wp-domain.com/";
// Transform the link of an entity mock.
const entity = { link: "/some-link/#element-id" };
transformLink({ entity, state });
expect(entity.link).toBe("/subdir/some-link/#element-id");
});
}); | the_stack |
import { randomBytes } from 'crypto';
import * as path from 'path';
import {
ContainerImage,
RepositoryImage,
} from '@aws-cdk/aws-ecs';
import {
Code,
SingletonFunction,
Runtime,
} from '@aws-cdk/aws-lambda';
import { RetentionDays } from '@aws-cdk/aws-logs';
import {
Construct,
CustomResource,
Duration,
Stack,
Token,
} from '@aws-cdk/core';
import {
IVersion,
RenderQueueImages,
ThinkboxManagedDeadlineDockerRecipes,
UsageBasedLicensingImages,
VersionQuery,
} from '.';
/**
* Choices for signifying the user's stance on the terms of the AWS Thinkbox End-User License Agreement (EULA).
* See: https://www.awsthinkbox.com/end-user-license-agreement
*/
export enum AwsThinkboxEulaAcceptance {
/**
* The user signifies their explicit rejection of the tems of the AWS Thinkbox EULA.
*
* See: https://www.awsthinkbox.com/end-user-license-agreement
*/
USER_REJECTS_AWS_THINKBOX_EULA = 0,
/**
* The user signifies their explicit acceptance of the terms of the AWS Thinkbox EULA.
*
* See: https://www.awsthinkbox.com/end-user-license-agreement
*/
USER_ACCEPTS_AWS_THINKBOX_EULA = 1,
}
/**
* Interface to specify the properties when instantiating a {@link ThinkboxDockerImages} instnace.
*/
export interface ThinkboxDockerImagesProps {
/**
* The Deadline version to obtain images for.
* @default latest
*/
readonly version?: IVersion;
/**
* Deadline is licensed under the terms of the AWS Thinkbox End-User License Agreement (see: https://www.awsthinkbox.com/end-user-license-agreement).
* Users of ThinkboxDockerImages must explicitly signify their acceptance of the terms of the AWS Thinkbox EULA through this
* property before the {@link ThinkboxDockerImages} will be allowed to deploy Deadline.
*/
// Developer note: It is a legal requirement that the default be USER_REJECTS_AWS_THINKBOX_EULA.
readonly userAwsThinkboxEulaAcceptance: AwsThinkboxEulaAcceptance;
}
/**
* An API for interacting with publicly available Deadline container images published by AWS Thinkbox.
*
* This provides container images as required by RFDK's Deadline constructs such as
*
* * {@link @aws-rfdk/deadline#RenderQueue}
* * {@link @aws-rfdk/deadline#UsageBasedLicensing}
*
* Successful usage of the published Deadline container images with this class requires:
*
* 1) Explicit acceptance of the terms of the AWS Thinkbox End User License Agreement, under which Deadline is
* distributed; and
* 2) The lambda on which the custom resource looks up the Thinkbox container images is able to make HTTPS
* requests to the official AWS Thinbox download site: https://downloads.thinkboxsoftware.com
*
* Resources Deployed
* ------------------------
* - A Lambda function containing a script to look up the AWS Thinkbox container image registry
*
* Security Considerations
* ------------------------
* - CDK deploys the code for this lambda as an S3 object in the CDK bootstrap bucket. You must limit write access to
* your CDK bootstrap bucket to prevent an attacker from modifying the actions performed by these scripts. We strongly
* recommend that you either enable Amazon S3 server access logging on your CDK bootstrap bucket, or enable AWS
* CloudTrail on your account to assist in post-incident analysis of compromised production environments.
*
* For example, to construct a RenderQueue using the images:
*
* ```ts
* import { App, Stack, Vpc } from '@aws-rfdk/core';
* import { AwsThinkboxEulaAcceptance, RenderQueue, Repository, ThinkboxDockerImages, VersionQuery } from '@aws-rfdk/deadline';
* const app = new App();
* const stack = new Stack(app, 'Stack');
* const vpc = new Vpc(stack, 'Vpc');
* const version = new VersionQuery(stack, 'Version', {
* version: '10.1.12',
* });
* const images = new ThinkboxDockerImages(stack, 'Image', {
* version,
* // Change this to AwsThinkboxEulaAcceptance.USER_ACCEPTS_AWS_THINKBOX_EULA to accept the terms
* // of the AWS Thinkbox End User License Agreement
* userAwsThinkboxEulaAcceptance: AwsThinkboxEulaAcceptance.USER_REJECTS_AWS_THINKBOX_EULA,
* });
* const repository = new Repository(stack, 'Repository', {
* vpc,
* version,
* });
*
* const renderQueue = new RenderQueue(stack, 'RenderQueue', {
* images: images.forRenderQueue(),
* // ...
* });
* ```
*/
export class ThinkboxDockerImages extends Construct {
/**
* The AWS Thinkbox licensing message that is presented to the user if they create an instance of
* this class without explicitly accepting the AWS Thinkbox EULA.
*
* Note to developers: The text of this string is a legal requirement, and must not be altered
* witout approval.
*/
private static readonly AWS_THINKBOX_EULA_MESSAGE: string = `
The ThinkboxDockerImages will install Deadline onto one or more EC2 instances.
Deadline is provided by AWS Thinkbox under the AWS Thinkbox End User License
Agreement (EULA). By installing Deadline, you are agreeing to the terms of this
license. Follow the link below to read the terms of the AWS Thinkbox EULA.
https://www.awsthinkbox.com/end-user-license-agreement
By using the ThinkboxDockerImages to install Deadline you agree to the terms of
the AWS Thinkbox EULA.
Please set the userAwsThinkboxEulaAcceptance property to
USER_ACCEPTS_AWS_THINKBOX_EULA to signify your acceptance of the terms of the
AWS Thinkbox EULA.
`;
/**
* A {@link DockerImageAsset} that can be used to build Thinkbox's Deadline RCS Docker Recipe into a
* container image that can be deployed in CDK.
*
* @param scope The parent scope
* @param id The construct ID
*/
public readonly remoteConnectionServer: ContainerImage;
/**
* A {@link DockerImageAsset} that can be used to build Thinkbox's Deadline License Forwarder Docker Recipe into a
* container image that can be deployed in CDK.
*
* @param scope The parent scope
* @param id The construct ID
*/
public readonly licenseForwarder: ContainerImage;
/**
* The version of Deadline installed in the container images
*/
private readonly version?: IVersion;
/**
* The base URI for AWS Thinkbox published Deadline ECR images.
*/
private readonly ecrBaseURI: string;
/**
* Whether the user has accepted the AWS Thinkbox EULA
*/
private readonly userAwsThinkboxEulaAcceptance: AwsThinkboxEulaAcceptance;
constructor(scope: Construct, id: string, props: ThinkboxDockerImagesProps) {
super(scope, id);
this.userAwsThinkboxEulaAcceptance = props.userAwsThinkboxEulaAcceptance;
this.version = props?.version;
const lambdaCode = Code.fromAsset(path.join(__dirname, '..', '..', 'lambdas', 'nodejs'));
const lambdaFunc = new SingletonFunction(this, 'VersionProviderFunction', {
uuid: '08553416-1fc9-4be9-a818-609a31ae1b5b',
description: 'Used by the ThinkboxDockerImages construct to look up the ECR repositories where AWS Thinkbox publishes Deadline container images.',
code: lambdaCode,
runtime: Runtime.NODEJS_12_X,
handler: 'ecr-provider.handler',
timeout: Duration.seconds(30),
logRetention: RetentionDays.ONE_WEEK,
});
const ecrProvider = new CustomResource(this, 'ThinkboxEcrProvider', {
serviceToken: lambdaFunc.functionArn,
properties: {
// create a random string that will force the Lambda to "update" on each deployment. Changes to its output will
// be propagated to any CloudFormation resource providers that reference the output ARN
ForceRun: this.forceRun(),
},
resourceType: 'Custom::RFDK_EcrProvider',
});
this.node.defaultChild = ecrProvider;
this.ecrBaseURI = ecrProvider.getAtt('EcrURIPrefix').toString();
this.remoteConnectionServer = this.ecrImageForRecipe(ThinkboxManagedDeadlineDockerRecipes.REMOTE_CONNECTION_SERVER);
this.licenseForwarder = this.ecrImageForRecipe(ThinkboxManagedDeadlineDockerRecipes.LICENSE_FORWARDER);
}
protected onValidate() {
const errors: string[] = [];
// Users must accept the AWS Thinkbox EULA to use the container images
if (this.userAwsThinkboxEulaAcceptance !== AwsThinkboxEulaAcceptance.USER_ACCEPTS_AWS_THINKBOX_EULA) {
errors.push(ThinkboxDockerImages.AWS_THINKBOX_EULA_MESSAGE);
}
// Using the output of VersionQuery across stacks can cause issues. CloudFormation stack outputs cannot change if
// a resource in another stack is referencing it.
if (this.version instanceof VersionQuery) {
const versionStack = Stack.of(this.version);
const thisStack = Stack.of(this);
if (versionStack != thisStack) {
errors.push('A VersionQuery can not be supplied from a different stack');
}
}
return errors;
}
private ecrImageForRecipe(recipe: ThinkboxManagedDeadlineDockerRecipes): RepositoryImage {
let registryName = `${this.ecrBaseURI}${recipe}`;
if (this.versionString) {
registryName += `:${this.versionString}`;
}
return ContainerImage.fromRegistry(
registryName,
);
}
/**
* Returns container images for use with the {@link RenderQueue} construct
*/
public forRenderQueue(): RenderQueueImages {
return this;
}
/**
* Returns container images for use with the {@link UsageBasedLicensing} construct
*/
public forUsageBasedLicensing(): UsageBasedLicensingImages {
return this;
}
/**
* A string representation of the Deadline version to retrieve images for.
*
* This can be undefined - in which case the latest available version of Deadline is used.
*/
private get versionString(): string | undefined {
function numAsString(num: number): string {
return Token.isUnresolved(num) ? Token.asString(num) : num.toString();
}
const version = this.version;
if (version) {
const major = numAsString(version.majorVersion);
const minor = numAsString(version.minorVersion);
const release = numAsString(version.releaseVersion);
return `${major}.${minor}.${release}`;
}
return undefined;
}
private forceRun(): string {
return randomBytes(32).toString('base64').slice(0, 32);
}
} | the_stack |
declare module 'jscodeshift' {
import * as estree from 'estree';
function jscodeshift(source: string): estree.Program;
// Note: The following module is generated, then hand edited.
module jscodeshift {
export function sourceLocation(
start: estree.Position, end: estree.Position, source?: (string|null)):
estree.SourceLocation;
export function position(line: number, column: number): estree.Position;
// TODO(rictic): teach gen-ts-types to get this type union right.
export function program(
body: Array<estree.Statement|estree.ModuleDeclaration>): estree.Program;
export function identifier(name: string): estree.Identifier;
export function blockStatement(body: estree.Statement[]):
estree.BlockStatement;
export function emptyStatement(): estree.EmptyStatement;
export function expressionStatement(expression: estree.Expression):
estree.ExpressionStatement;
export function ifStatement(
test: estree.Expression,
consequent: estree.Statement,
alternate?: (estree.Statement|null)): estree.IfStatement;
export function labeledStatement(
label: estree.Identifier,
body: estree.Statement): estree.LabeledStatement;
export function breakStatement(label?: (estree.Identifier|null)):
estree.BreakStatement;
export function continueStatement(label?: (estree.Identifier|null)):
estree.ContinueStatement;
export function withStatement(
object: estree.Expression,
body: estree.Statement): estree.WithStatement;
export function switchStatement(
discriminant: estree.Expression,
cases: estree.SwitchCase[],
lexical?: boolean): estree.SwitchStatement;
export function switchCase(
test: (estree.Expression|null),
consequent: estree.Statement[]): estree.SwitchCase;
export function returnStatement(argument?: (estree.Expression|null)):
estree.ReturnStatement;
export function throwStatement(argument: estree.Expression):
estree.ThrowStatement;
export function tryStatement(
block: estree.BlockStatement,
handler?: (estree.CatchClause|null),
finalizer?: (estree.BlockStatement|null)): estree.TryStatement;
export function catchClause(
param: estree.Pattern,
guard: (estree.Expression|null),
body: estree.BlockStatement): estree.CatchClause;
export function whileStatement(
test: estree.Expression, body: estree.Statement): estree.WhileStatement;
export function doWhileStatement(
body: estree.Statement,
test: estree.Expression): estree.DoWhileStatement;
export function forStatement(
init: (estree.VariableDeclaration|estree.Expression|null),
test: (estree.Expression|null),
update: (estree.Expression|null),
body: estree.Statement): estree.ForStatement;
export function variableDeclaration(
kind: ('var'|'let'|'const'),
declarations: (estree.VariableDeclarator|estree.Identifier)[]):
estree.VariableDeclaration;
export function forInStatement(
left: (estree.VariableDeclaration|estree.Expression),
right: estree.Expression,
body: estree.Statement): estree.ForInStatement;
export function debuggerStatement(): estree.DebuggerStatement;
export function functionDeclaration(
id: estree.Identifier,
params: estree.Pattern[],
body: estree.BlockStatement,
generator?: boolean,
expression?: boolean): estree.FunctionDeclaration;
export function functionExpression(
id: (estree.Identifier|null),
params: estree.Pattern[],
body: estree.BlockStatement,
generator?: boolean,
expression?: boolean): estree.FunctionExpression;
export function variableDeclarator(
id: estree.Pattern,
init?: (estree.Expression|null)): estree.VariableDeclarator;
export function thisExpression(): estree.ThisExpression;
export function arrayExpression(
elements?: (estree.Expression|estree.SpreadElement|estree.RestElement|
null)[]): estree.ArrayExpression;
export function objectExpression(properties: estree.Property[]):
estree.ObjectExpression;
export function property(
kind: ('init'|'get'|'set'),
key: (estree.Literal|estree.Identifier|estree.Expression),
value: (estree.Expression|estree.Pattern)): estree.Property;
export function literal(value?: (string|boolean|null|number|RegExp)):
estree.Literal;
export function sequenceExpression(expressions: estree.Expression[]):
estree.SequenceExpression;
export function unaryExpression(
operator: ('-'|'+'|'!'|'~'|'typeof'|'void'|'delete'),
argument: estree.Expression,
prefix?: boolean): estree.UnaryExpression;
export function binaryExpression(
operator: ('=='|'!='|'==='|'!=='|'<'|'<='|'>'|'>='|'<<'|'>>'|'>>>'|'+'|
'-'|'*'|'/'|'%'|'&'|'|'|'^'|'in'|'instanceof'|'..'),
left: estree.Expression,
right: estree.Expression): estree.BinaryExpression;
export function assignmentExpression(
operator:
('='|'+='|'-='|'*='|'/='|'%='|'<<='|'>>='|'>>>='|'|='|'^='|'&='),
left: estree.Pattern,
right: estree.Expression): estree.AssignmentExpression;
export function updateExpression(
operator: ('++'|'--'), argument: estree.Expression, prefix: boolean):
estree.UpdateExpression;
export function logicalExpression(
operator: ('||'|'&&'),
left: estree.Expression,
right: estree.Expression): estree.LogicalExpression;
export function conditionalExpression(
test: estree.Expression,
consequent: estree.Expression,
alternate: estree.Expression): estree.ConditionalExpression;
export function newExpression(
callee: estree.Expression,
arguments: (estree.Expression|estree.SpreadElement)[]):
estree.NewExpression;
export function callExpression(
callee: estree.Expression,
arguments: (estree.Expression|estree.SpreadElement)[]):
estree.CallExpression;
export function memberExpression(
object: estree.Expression,
property: (estree.Identifier|estree.Expression),
computed?: boolean): estree.MemberExpression;
export function restElement(argument: estree.Pattern): estree.RestElement;
export function arrowFunctionExpression(
params: estree.Pattern[],
body: (estree.BlockStatement|estree.Expression),
expression?: boolean): estree.ArrowFunctionExpression;
export function forOfStatement(
left: (estree.VariableDeclaration|estree.Pattern),
right: estree.Expression,
body: estree.Statement): estree.ForOfStatement;
export function yieldExpression(
argument?: (estree.Expression|null),
delegate?: boolean): estree.YieldExpression;
export function objectPattern(properties: (estree.Property)[]):
estree.ObjectPattern;
export function arrayPattern(elements?: (
estree.Pattern|estree.SpreadElement|null)[]): estree.ArrayPattern;
export function methodDefinition(
kind: ('constructor'|'method'|'get'|'set'),
key: (estree.Literal|estree.Identifier|estree.Expression),
value: estree.Function,
static?: boolean): estree.MethodDefinition;
export function spreadElement(argument: estree.Expression):
estree.SpreadElement;
export function assignmentPattern(
left: estree.Pattern,
right: estree.Expression): estree.AssignmentPattern;
export function classBody(body: (
estree.MethodDefinition|estree.VariableDeclarator)[]): estree.ClassBody;
export function classDeclaration(
id: (estree.Identifier|null),
body: estree.ClassBody,
superClass?: (estree.Expression|null)): estree.ClassDeclaration;
export function classExpression(
id: (estree.Identifier|null),
body: estree.ClassBody,
superClass?: (estree.Expression|null)): estree.ClassExpression;
export function taggedTemplateExpression(
tag: estree.Expression,
quasi: estree.TemplateLiteral): estree.TaggedTemplateExpression;
export function templateLiteral(
quasis: estree.TemplateElement[],
expressions: estree.Expression[]): estree.TemplateLiteral;
export function templateElement(
value: {cooked: String, raw: String},
tail: boolean): estree.TemplateElement;
export function metaProperty(
meta: estree.Identifier,
property: estree.Identifier): estree.MetaProperty;
export function importSpecifier(
id?: (estree.Identifier|null),
name?: (estree.Identifier|null)): estree.ImportSpecifier;
export function importDefaultSpecifier(id?: (estree.Identifier|null)):
estree.ImportDefaultSpecifier;
export function importNamespaceSpecifier(id?: (estree.Identifier|null)):
estree.ImportNamespaceSpecifier;
export function exportDefaultDeclaration(declaration: (
estree.Declaration|estree.Expression)): estree.ExportDefaultDeclaration;
export function exportNamedDeclaration(
declaration?: (estree.Declaration|null),
specifiers?: estree.ExportSpecifier[],
source?: (estree.Literal|null)): estree.ExportNamedDeclaration;
export function exportSpecifier(
id?: (estree.Identifier|null),
name?: (estree.Identifier|null)): estree.ExportSpecifier;
export function exportAllDeclaration(
exported: (estree.Identifier|null),
source: estree.Literal): estree.ExportAllDeclaration;
export function importDeclaration(
specifiers: (estree.ImportSpecifier|
estree.ImportNamespaceSpecifier|
estree.ImportDefaultSpecifier)[],
source: estree.Literal,
importKind?: ('value'|'type')): estree.ImportDeclaration;
}
export = jscodeshift;
} | the_stack |
import { SpokAssertions } from './types'
class SpokAssertionsClass implements SpokAssertions {
/**
* Specifies that the given number is within the given range,
* i.e. `min<= x <=max`.
*
* ```js
* var spec = {
* x: spok.range(1, 2) // specifies that x should be >=1 and <=2
* }
* ```
*
* @function
* @param {Number} min minimum
* @param {Number} max maximum
*/
range = (min: number, max: number) => {
const checkRange = (x: number) => {
return this.number(x) && min <= x && x <= max
}
checkRange.$spec = 'spok.range(' + min + ', ' + max + ')'
checkRange.$description = min + ' <= value <= ' + max
return checkRange
}
/**
* Specifies that a number is greater than the given criteria.
*
* ```js
* var spec = {
* x: spok.gt(1) // specifies that x should be >1
* }
* ```
*
* @function
* @param {Number} n criteria
*/
gt = (n: number) => {
const checkgt = (x: number) => {
return this.number(x) && x > n
}
checkgt.$spec = 'spok.gt(' + n + ')'
checkgt.$description = 'value > ' + n
return checkgt
}
/**
* Specififies that a number is greater or equal the given criteria.
*
* ```js
* var spec = {
* x: spok.ge(1) // specifies that x should be >=1
* }
* ```
*
* @function
* @param {Number} n criteria
*/
ge = (n: number) => {
const checkge = (x: number) => {
return this.number(x) && x >= n
}
checkge.$spec = 'spok.ge(' + n + ')'
checkge.$description = 'value >= ' + n
return checkge
}
/**
* Specififies that a number is less than the given criteria.
*
* ```js
* var spec = {
* x: spok.lt(1) // specifies that x should be < 1
* }
* ```
*
* @function
* @param {Number} n criteria
*/
lt = (n: number) => {
const checklt = (x: number) => {
return this.number(x) && x < n
}
checklt.$spec = 'spok.lt(' + n + ')'
checklt.$description = 'value < ' + n
return checklt
}
/**
* Specififies that a number is less or equal the given criteria.
*
* ```js
* var spec = {
* x: spok.le(1) // specifies that x should be <=1
* }
* ```
*
* @function
* @param {Number} n criteria
*/
le = (n: number) => {
const checkle = (x: number) => {
return this.number(x) && x <= n
}
checkle.$spec = 'spok.le(' + n + ')'
checkle.$description = 'value <= ' + n
return checkle
}
/**
* Specifies that the value is not equal another.
*
* ```js
* var spec = {
* x: spok.ne(undefined) // specifies that x should be defined
* }
* ```
*
* @function
* @param {unknown} value criteria
*/
ne = (value: unknown) => {
function checkne(x: unknown) {
return value !== x
}
checkne.$spec = 'spok.ne(' + value + ')'
checkne.$description = 'value !== ' + value
return checkne
}
/**
* Specifies that the value is greater than zero
*
* ```js
* var spec = {
* x: spok.gtz
* }
* ```
* @function
*/
get gtz() {
const fn = this.gt(0)
fn.$spec = 'spok.gtz'
fn.$description = 'value > 0'
return fn
}
/**
* Specifies that the value is greater or equal zero
*
* ```js
* var spec = {
* x: spok.gez
* }
* ```
* @function
*/
get gez() {
const fn = this.ge(0)
fn.$spec = 'spok.gez'
fn.$description = 'value >= 0'
return fn
}
/**
* Specifies that the value is less than zero
*
* ```js
* var spec = {
* x: spok.ltz
* }
* ```
* @function
*/
get ltz() {
const fn = this.lt(0)
fn.$spec = 'spok.ltz'
fn.$description = 'value < 0'
return fn
}
/**
* Specifies that the value is less or equal zero
*
* ```js
* var spec = {
* x: spok.lez
* }
* ```
* @function
*/
get lez() {
const fn = this.le(0)
fn.$spec = 'spok.lez'
fn.$description = 'value <= 0'
return fn
}
/**
* Specifies that the input is of a given type.
*
* ```js
* var spec = {
* x: spok.type('number') // specifies that x should be a Number
* }
* ```
*
* @function
* @param {String} t expected type
*/
type = (t: string) => {
function checkType(x: unknown) {
return typeof x === t
}
checkType.$spec = 'spok.type(' + t + ')'
checkType.$description = 'value is of type ' + t
return checkType
}
/**
* Specifies that the input is an array.
*
* ```js
* var spec = {
* x: spok.array // specifies that x should be an Array
* }
* ```
*
* @function
*/
get array() {
const fn = function array(x: unknown[]) {
return Array.isArray(x)
}
fn.$spec = 'spok.array'
fn.$description = 'values is an Array'
return fn
}
/**
* Specifies that the input is an array with a specific number of elements
*
* var spec = {
* // specifies that x should be an Array with 2 elements
* x: spok.arrayElements(2)
* }
*
* @function
* @param {Number} n number of elements
*/
arrayElements = (n: number) => {
const checkCount = (array: unknown[]) => {
if (array == null) {
console.error('Expected %d, but found array to be null.', n)
return false
}
const pass = this.array(array) && array.length === n
if (!pass) {
console.error('Expected %d, but found %d elements.', n, array.length)
}
return pass
}
checkCount.$spec = 'spok.arrayElements(' + n + ')'
checkCount.$description = 'array has ' + n + ' element(s)'
return checkCount
}
/**
* Specifies that the input is an array with a number of elements
* in a given range
*
* var spec = {
* // specifies that x should be an Array with 2-4 elements
* x: spok.arrayElementsRange(2, 4)
* }
*
* @function
* @param {Number} min min number of elements
* @param {Number} max max number of elements
*/
arrayElementsRange = (min: number, max: number) => {
const checkCount = (array: unknown[]) => {
if (array == null) {
console.error(
'Expected between %d and %d, but found array to be null.',
min,
max
)
return false
}
const pass =
this.array(array) && array.length >= min && array.length <= max
if (!pass) {
console.error(
'Expected between %d and %d, but found %d elements.',
min,
max,
array.length
)
}
return pass
}
checkCount.$spec = 'spok.arrayElementsRange(' + min + ', ' + max + ')'
checkCount.$description =
'array has between' + min + ' and ' + max + ' elements'
return checkCount
}
/**
* Specifies that the input of type number and `isNaN(x)` returns `false`.
*
* ```js
* var spec = {
* x: spok.number // specifies that x should be a Number
* }
* ```
*
* @function
*/
get number() {
const fn = function number(x: unknown) {
return typeof x === 'number' && !isNaN(x)
}
fn.$spec = 'spok.number'
fn.$description = 'value is a number'
return fn
}
/**
* Specifies that the input is a string.
*
* ```
* var spec = {
* x: spok.string // specifies that x should be a String
* }
* ```
*
* @function
*/
get string() {
const fn = this.type('string')
fn.$spec = 'spok.string'
fn.$description = 'value is a string'
return fn
}
/**
* Specifies that the input is a function.
*
* ```
* var spec = {
* x: spok.function // specifies that x should be a function
* }
* ```
*
* @function
*/
get function() {
const fn = this.type('function')
fn.$spec = 'spok.function'
fn.$description = 'value is a function'
return fn
}
/**
* Specifies that the input is an object and it is not `null`.
*
* ```js
* var spec = {
* x: spok.definedObject // specifies that x is a non-null object
* }
* ```
*
* @function
*/
get definedObject() {
const fn = function definedObject(x: unknown) {
return x !== null && typeof x === 'object'
}
fn.$spec = 'spok.definedObject'
fn.$description = 'value is defined and of type object'
return fn
}
/**
* Specifies that the string starts with the specified substring.
*
* **NOTE**: only available with node.js which has an ES6 `startsWith` function
*
* ```js
* var spec = {
* x: spok.startsWith('hello') // specifies that x should start with 'hello'
* }
* ```
*
* @function
* @param {String} what substring the given string should start with
*/
startsWith = (what: string) => {
function checkStartsWith(x: string) {
const res =
x != null && typeof x.startsWith === 'function' && x.startsWith(what)
if (!res) console.error('"%s" does not start with "%s"', x, what)
return res
}
checkStartsWith.$spec = 'spok.startsWith(' + what + ')'
checkStartsWith.$description = 'string starts with ' + what
return checkStartsWith
}
/**
* Specifies that the string ends with the specified substring.
*
* **NOTE**: only available with node.js which has an ES6 `endsWith` function
*
* ```js
* var spec = {
* x: spok.endsWith('hello') // specifies that x should start with 'hello'
* }
* ```
*
* @function
* @param {String} what substring the given string should start with
*/
endsWith = (what: string) => {
function checkEndsWith(x: string) {
const res =
x != null && typeof x.endsWith === 'function' && x.endsWith(what)
if (!res) console.error('"%s" does not start with "%s"', x, what)
return res
}
checkEndsWith.$spec = 'spok.endsWith(' + what + ')'
checkEndsWith.$description = 'string ends with ' + what
return checkEndsWith
}
/**
* Specifies that the string needs to match the given regular expression.
*
* ```js
* var spec = {
* // specifies that x should match /hello$/
* x: spok.test(/hello$/)
* }
* ```
*
* @function
* @param {RegExp} regex regular expression against
* which the string is checked via `test`
*/
test = (regex: RegExp) => {
function checkTest(x: string) {
const res = regex.test(x)
if (!res) console.error('"%s" does not match \n%s', x, regex.toString())
return res
}
const s = regex.toString()
checkTest.$spec = 'spok.test(' + s + ')'
checkTest.$description = 'value matches ' + s + ' regex'
return checkTest
}
/**
* Specifies that a value is defined,
* i.e. it is neither `null` nor `undefined`.
*
* ```js
* var spec = {
* x: spok.defined
* }
* ```
*
* @function
*/
get defined() {
const fn = function defined(x: unknown) {
return x != null
}
fn.$spec = 'spok.defined'
fn.$description = 'value is neither null nor undefined'
return fn
}
/**
* Specifies that a value is notDefined,
* i.e. it is either `null` or `notDefined`.
*
* ```js
* var spec = {
* x: spok.notDefined
* }
* ```
*
* @function
*/
get notDefined() {
const fn = function notDefined(x: unknown) {
return x == null
}
fn.$spec = 'spok.notDefined'
fn.$description = 'value is either null or undefined'
return fn
}
}
const x = new SpokAssertionsClass()
// Make all getters _own_ properties so they get copied during
// `Object.assign` calls
const spokAssertions = Object.assign({}, x, {
gtz: x.gtz,
gez: x.gez,
ltz: x.ltz,
lez: x.lez,
array: x.array,
number: x.number,
string: x.string,
function: x.function,
definedObject: x.definedObject,
defined: x.defined,
notDefined: x.notDefined,
})
export default spokAssertions | the_stack |
import { Bounds, Epsg, NamedBounds, Tile, TileMatrixSet } from '@basemaps/geo';
import { compareName, fsa, Projection } from '@basemaps/shared';
import {
clipMultipolygon,
featuresToMultiPolygon,
intersection,
MultiPolygon,
toFeatureCollection,
toFeatureMultiPolygon,
union,
} from '@linzjs/geojson';
import { FeatureCollection } from 'geojson';
import { CoveringFraction, MaxImagePixelWidth } from './constants.js';
import { CogJob, FeatureCollectionWithCrs, SourceMetadata } from './types.js';
/** Padding to always apply to image boundies */
const PixelPadding = 100;
/** fraction to scale source imagery to avoid degenerate edges */
const SourceSmoothScale = 1 + 1e-8;
function findGeoJsonProjection(geojson: any | null): Epsg {
return Epsg.parse(geojson?.crs?.properties?.name ?? '') ?? Epsg.Wgs84;
}
function namedBounds(tms: TileMatrixSet, tile: Tile): NamedBounds {
return { name: TileMatrixSet.tileToName(tile), ...tms.tileToSourceBounds(tile).toJson() };
}
export function polyContainsBounds(poly: MultiPolygon, bounds: Bounds): boolean {
const clipped = clipMultipolygon(poly, bounds.toBbox());
if (clipped.length !== 1 || clipped[0].length !== 1 || clipped[0][0].length !== 5) return false;
return Bounds.fromMultiPolygon(clipped).containsBounds(bounds);
}
/**
* Filter out duplicate tiles
*/
function addNonDupes(list: Tile[], addList: Tile[]): void {
const len = list.length;
for (const add of addList) {
let i = 0;
for (; i < len; ++i) {
const curr = list[i];
if (curr.x === add.x && curr.y === add.y && curr.z === add.z) {
break;
}
}
if (i === len) {
list.push(add);
}
}
}
export class Cutline {
/** The polygon to clip source imagery to */
clipPoly: MultiPolygon;
tileMatrix: TileMatrixSet; // convience to targetPtms.tms
/** How much blending to apply at the clip line boundary */
blend: number;
/** For just one cog to cover the imagery */
oneCogCovering: boolean;
/** the polygon outlining a area covered by the source imagery and clip polygon */
srcPoly: MultiPolygon = [];
/**
* Create a Cutline instance from a `GeoJSON FeatureCollection`.
* @param tileMatrix the tileMatrix the COGs will be created in.
* @param clipPoly the optional cutline. The source imagery outline used by default. This
* `FeatureCollection` is converted to one `MultiPolygon` with any holes removed and the
* coordinates transposed from `Wgs84` to the target projection (unless already in target projection).
* @param blend How much blending to consider when working out boundaries.
*/
constructor(tileMatrix: TileMatrixSet, clipPoly?: FeatureCollection, blend = 0, oneCogCovering = false) {
this.tileMatrix = tileMatrix;
this.blend = blend;
this.oneCogCovering = oneCogCovering;
if (clipPoly == null) {
this.clipPoly = [];
return;
}
this.tileMatrix = tileMatrix;
const proj = findGeoJsonProjection(clipPoly);
const tmsProj = Projection.get(tileMatrix);
const needProj = proj !== tmsProj.epsg;
if (needProj && proj !== Epsg.Wgs84) throw new Error('Invalid geojson; CRS may not be set for cutline!');
const convert = needProj ? tmsProj.fromWgs84 : undefined;
this.clipPoly = featuresToMultiPolygon(clipPoly.features, true, convert).coordinates as MultiPolygon;
}
/**
* Load a geojson cutline from the file-system.
*
* @param path the path of the cutline to load. Can be `s3://` or local file path.
*/
static loadCutline(path: string): Promise<FeatureCollection> {
return fsa.readJson<FeatureCollection>(path);
}
/**
* For the given tile `name`, filter `job.source.files` and cutline polygons that are within bounds plus
* padding
*
* @param name
* @param job
* @returns names of source files required to render Cog
*/
filterSourcesForName(name: string, job: CogJob): string[] {
if (this.oneCogCovering) return job.source.files.map(({ name }) => name);
const tile = TileMatrixSet.nameToTile(name);
const sourceCode = Projection.get(job.source.epsg);
const targetCode = Projection.get(this.tileMatrix);
const tileBounds = this.tileMatrix.tileToSourceBounds(tile);
const tilePadded = this.padBounds(tileBounds, job.targetZoom);
let tileBoundsInSrcProj = tilePadded;
if (sourceCode !== targetCode) {
// convert the padded quadKey to source projection ensuring fully enclosed
const poly = targetCode.projectMultipolygon([tileBoundsInSrcProj.toPolygon()], sourceCode);
tileBoundsInSrcProj = Bounds.fromMultiPolygon(poly);
}
const paddedBbox = tilePadded.toBbox();
if (this.clipPoly.length > 0) {
const poly = clipMultipolygon(this.clipPoly, paddedBbox);
if (poly.length === 0) {
// this tile is not needed
this.clipPoly = [];
return [];
} else if (polyContainsBounds(poly, tileBounds)) {
// tile is completely surrounded; no cutline polygons needed
this.clipPoly = [];
} else {
// set the cutline polygons to just the area of interest (minus degenerate edges)
this.clipPoly = poly;
}
}
return job.source.files
.filter((image) => tileBoundsInSrcProj.intersects(Bounds.fromJson(image)))
.map(({ name }) => name);
}
/**
* Generate an optimized WebMercator tile cover for the supplied source images
* @param sourceMetadata contains images bounds and projection info
*/
optimizeCovering(sourceMetadata: SourceMetadata): NamedBounds[] {
if (this.oneCogCovering) {
const extent = this.tileMatrix.extent.toJson();
return [{ ...extent, name: '0-0-0' }];
}
this.findCovering(sourceMetadata);
const { resZoom } = sourceMetadata;
// Look for the biggest tile size we are allowed to create.
let minZ = resZoom - 1;
while (
minZ > 0 &&
Projection.getImagePixelWidth(this.tileMatrix, { x: 0, y: 0, z: minZ }, resZoom) < MaxImagePixelWidth
) {
--minZ;
}
minZ = Math.max(1, minZ + 1);
let tiles: Tile[] = [];
for (const tile of this.tileMatrix.topLevelTiles()) {
// Don't make COGs with a tile.z < minZ.
tiles = tiles.concat(this.makeTiles(tile, this.srcPoly, minZ, CoveringFraction).tiles);
}
if (tiles.length === 0) {
throw new Error('Source imagery does not overlap with project extent');
}
const covering = tiles.map((tile) => namedBounds(this.tileMatrix, tile));
// remove duplicate
return covering
.filter((curr) => {
for (const other of covering) {
if (other !== curr && Bounds.contains(other, curr)) return false;
}
return true;
})
.sort(compareName);
}
/**
* Convert JobCutline to geojson FeatureCollection
*/
toGeoJson(clipPoly = this.clipPoly): FeatureCollectionWithCrs {
const feature = toFeatureCollection([toFeatureMultiPolygon(clipPoly)]) as FeatureCollectionWithCrs;
feature.crs = {
type: 'name',
properties: { name: this.tileMatrix.projection.toUrn() },
};
return feature;
}
/**
* Merge child nodes that have at least a covering fraction
* @param tile the tile to descend
* @param srcArea the aread of interest
* @param minZ Only produce tiles for zoom levels at least `minZ` and no sibling tiles
* greater than `minZ +2`
* @param coveringFraction merge tiles that cover at least this fraction
* @return the tiles and fraction covered of the tile by this srcArea
*/
private makeTiles(
tile: Tile,
srcArea: MultiPolygon,
minZ: number,
coveringFraction: number,
): { tiles: Tile[]; fractionCovered: number } {
const clipBounds = this.tileMatrix.tileToSourceBounds(tile).toBbox();
srcArea = clipMultipolygon(srcArea, clipBounds);
if (srcArea.length === 0) {
return { tiles: [], fractionCovered: 0 };
}
if (tile.z === minZ + 4) {
return { tiles: [tile], fractionCovered: 1 };
}
const ans = { tiles: [] as Tile[], fractionCovered: 0 };
for (const child of this.tileMatrix.coverTile(tile)) {
const { tiles, fractionCovered } = this.makeTiles(child, srcArea, minZ, coveringFraction);
if (fractionCovered !== 0) {
ans.fractionCovered += fractionCovered * 0.25;
addNonDupes(ans.tiles, tiles);
}
}
if (
// tile too small OR children have enough coverage
(tile.z > minZ + 2 || ans.fractionCovered >= coveringFraction) &&
// AND more than one child tile
ans.tiles.length > 1 &&
// AND tile not too big
tile.z >= minZ
) {
ans.tiles = [tile]; // replace children with parent
}
return ans;
}
/**
* Find the polygon covering of source imagery and a (optional) clip cutline. Truncates the
* cutline to match.
* @param sourceMetadata
*/
private findCovering(sourceMetadata: SourceMetadata): void {
let srcPoly: MultiPolygon = [];
const { resZoom } = sourceMetadata;
// merge imagery bounds
for (const image of sourceMetadata.bounds) {
const poly = [Bounds.fromJson(image).scaleFromCenter(SourceSmoothScale).toPolygon()] as MultiPolygon;
srcPoly = union(srcPoly, poly);
}
// Convert polygon to target projection
const sourceProj = Projection.get(sourceMetadata.projection);
const targetProj = Projection.get(this.tileMatrix);
if (sourceProj !== targetProj) {
srcPoly = sourceProj.projectMultipolygon(srcPoly, targetProj) as MultiPolygon;
}
this.srcPoly = srcPoly;
if (this.clipPoly.length === 0) return;
const srcBounds = Bounds.fromMultiPolygon(srcPoly);
const boundsPadded = this.padBounds(srcBounds, resZoom).toBbox();
const poly = clipMultipolygon(this.clipPoly, boundsPadded);
if (poly.length === 0) {
throw new Error('No intersection between source imagery and cutline');
}
if (polyContainsBounds(poly, srcBounds)) {
// tile is completely surrounded; no cutline polygons needed
this.clipPoly = [];
} else {
// set the cutline polygons to just the area of interest (minus degenerate edges)
this.clipPoly = poly;
this.srcPoly = intersection(srcPoly, this.clipPoly) ?? [];
}
}
/**
* Pad the bounds to take in to consideration blending and 100 pixels of adjacent image data
* @param bounds
* @param resZoom the imagery resolution target zoom level
*/
private padBounds(bounds: Bounds, resZoom: number): Bounds {
const px = this.tileMatrix.pixelScale(resZoom);
// Ensure cutline blend does not interferre with non-costal edges
const widthScale = (bounds.width + px * (PixelPadding + this.blend) * 2) / bounds.width;
const heightScale = (bounds.height + px * (PixelPadding + this.blend) * 2) / bounds.height;
return bounds.scaleFromCenter(widthScale, heightScale);
}
} | the_stack |
import { isBoolean, isNumber, isString, isObject, isFunction, isIterable, isIterator, isAsyncIterable } from "@esfx/internal-guards";
namespace Debug {
interface ErrorConstructorWithStackTraceApi extends ErrorConstructor {
captureStackTrace(target: any, stackCrawlMark?: Function): void;
}
declare const Error: ErrorConstructorWithStackTraceApi;
export function captureStackTrace(error: any, stackCrawlMark?: Function) {
if (typeof error === "object" && error !== null && Error.captureStackTrace) {
Error.captureStackTrace(error, stackCrawlMark || captureStackTrace);
}
}
}
/* @internal */
export function fail(ErrorType: new (message?: string) => Error, paramName: string | undefined, message: string | undefined, stackCrawlMark: Function = fail): never {
const error = new ErrorType(typeof paramName === "string" ? message ? `${message}: ${paramName}` : `Invalid argument: ${paramName}` : message);
Debug.captureStackTrace(error, stackCrawlMark || assertType);
throw error;
}
/* @internal */
export function assert(condition: boolean, paramName?: string, message?: string, stackCrawlMark: Function = assert): asserts condition {
if (!condition) fail(Error, paramName, message, stackCrawlMark);
}
/* @internal */
export function assertType(condition: boolean, paramName?: string, message?: string, stackCrawlMark: Function = assertType): asserts condition {
if (!condition) fail(TypeError, paramName, message, stackCrawlMark);
}
/* @internal */
export function assertRange(condition: boolean, paramName?: string, message?: string, stackCrawlMark: Function = assertRange): asserts condition {
if (!condition) fail(RangeError, paramName, message, stackCrawlMark)
}
/* @internal */
export function mustBeType<T>(test: (value: unknown) => value is T, value: unknown, paramName?: string, message?: string, stackCrawlMark: Function = mustBeType): asserts value is T {
assertType(test(value), paramName, message, stackCrawlMark);
}
/* @internal */
export function mustBeInstanceOf<T>(C: new (...args: any[]) => T, value: unknown, paramName?: string, message?: string, stackCrawlMark: Function = mustBeType): asserts value is T {
assertType(value instanceof C, paramName, message, stackCrawlMark);
}
/* @internal */
export function mustBeTypeOrUndefined<T>(test: (value: unknown) => value is T, value: unknown, paramName?: string, message?: string, stackCrawlMark: Function = mustBeTypeOrUndefined): asserts value is T | undefined {
if (value !== undefined) mustBeType(test, value, paramName, message, stackCrawlMark);
}
/* @internal */
export function mustBeTypeOrNull<T>(test: (value: unknown) => value is T, value: unknown, paramName?: string, message?: string, stackCrawlMark: Function = mustBeTypeOrNull): asserts value is T | null {
if (value !== null) mustBeType(test, value, paramName, message, stackCrawlMark);
}
/* @internal */
export function mustBeTypeInRange<T>(test: (value: unknown) => value is T, rangeTest: (value: T) => boolean, value: unknown, paramName?: string, message?: string, stackCrawlMark: Function = mustBeTypeInRange): asserts value is T {
mustBeType(test, value, paramName, message, stackCrawlMark);
assertRange(rangeTest(value), paramName, message, stackCrawlMark);
}
/* @internal */
export function mustBeBoolean(value: unknown, paramName?: string, message?: string, stackCrawlMark: Function = mustBeBoolean): asserts value is boolean {
mustBeType(isBoolean, value, paramName, message, stackCrawlMark);
}
/* @internal */
export function mustBeNumber(value: unknown, paramName?: string, message?: string, stackCrawlMark: Function = mustBeNumber): asserts value is number {
mustBeType(isNumber, value, paramName, message, stackCrawlMark);
}
/* @internal */
export type tag_Finite = { tag_Finite: never };
/* @internal */
export type tag_Positive = { tag_Positive: never };
/* @internal */
export type tag_NonZero = { tag_NonZero: never };
/* @internal */
export type tag_Integer = { tag_Integer: never };
/* @internal */
export function mustBeFiniteNumber<T>(value: T, paramName?: string, message?: string, stackCrawlMark: Function = mustBeFiniteNumber): asserts value is Extract<T, number> & tag_Finite {
mustBeTypeInRange(isNumber, isFinite, value, paramName, message, stackCrawlMark);
}
function isPositiveFinite(x: number) { return isFinite(x) && x >= 0; }
/* @internal */
export function mustBePositiveFiniteNumber<T>(value: T, paramName?: string, message?: string, stackCrawlMark: Function = mustBePositiveFiniteNumber): asserts value is Extract<T, number> & tag_Positive & tag_Finite {
mustBeTypeInRange(isNumber, isPositiveFinite, value, paramName, message, stackCrawlMark);
}
function isPositiveNonZeroFinite(x: number) { return isFinite(x) && x > 0; }
/* @internal */
export function mustBePositiveNonZeroFiniteNumber<T>(value: T, paramName?: string, message?: string, stackCrawlMark: Function = mustBePositiveNonZeroFiniteNumber): asserts value is Exclude<Extract<T, number>, 0> & tag_Positive & tag_Finite & tag_NonZero {
mustBeTypeInRange(isNumber, isPositiveNonZeroFinite, value, paramName, message, stackCrawlMark);
}
function isInteger(x: number) { return Object.is(x, x | 0); }
/* @internal */
export function mustBeInteger<T>(value: T, paramName?: string, message?: string, stackCrawlMark: Function = mustBeInteger): asserts value is Extract<T, number> & tag_Integer {
mustBeTypeInRange(isNumber, isInteger, value, paramName, message, stackCrawlMark);
}
function isPositiveInteger(x: number) { return isInteger(x) && x >= 0; }
/* @internal */
export function mustBePositiveInteger<T>(value: T, paramName?: string, message?: string, stackCrawlMark: Function = mustBePositiveInteger): asserts value is Extract<T, number> & tag_Integer & tag_Positive {
mustBeTypeInRange(isNumber, isPositiveInteger, value, paramName, message, stackCrawlMark);
}
/* @internal */
export function mustBeString(value: unknown, paramName?: string, message?: string, stackCrawlMark: Function = mustBeString): asserts value is string {
mustBeType(isString, value, paramName, message, stackCrawlMark);
}
/* @internal */
export function mustBeObject(value: unknown, paramName?: string, message: string = "Object expected", stackCrawlMark: Function = mustBeObject): asserts value is object {
mustBeType(isObject, value, paramName, message, stackCrawlMark);
}
/* @internal */
export function mustBeObjectOrNull(value: unknown, paramName?: string, message?: string, stackCrawlMark: Function = mustBeObjectOrNull): asserts value is object | null {
mustBeTypeOrNull(isObject, value, paramName, message, stackCrawlMark);
}
/* @internal */
export function mustBeFunction(value: unknown, paramName?: string, message?: string, stackCrawlMark: Function = mustBeFunction): asserts value is Function {
mustBeType(isFunction, value, paramName, message, stackCrawlMark);
}
/* @internal */
export function mustBeFunctionOrUndefined(value: unknown, paramName?: string, message?: string, stackCrawlMark: Function = mustBeFunctionOrUndefined): asserts value is Function | undefined {
mustBeTypeOrUndefined(isFunction, value, paramName, message, stackCrawlMark);
}
/* @internal */
export function mustBeIterable(value: unknown, paramName?: string, message?: string, stackCrawlMark: Function = mustBeIterable): asserts value is Iterable<unknown> {
mustBeType(isIterable, value, paramName, message, stackCrawlMark);
}
function isIterableObject(value: unknown): value is Iterable<unknown> & object {
return isObject(value) && isIterable(value);
}
/* @internal */
export function mustBeIterableOrUndefined(value: unknown, paramName?: string, message?: string, stackCrawlMark: Function = mustBeIterableOrUndefined): asserts value is Iterable<unknown> | undefined {
mustBeTypeOrUndefined(isIterable, value, paramName, message, stackCrawlMark);
}
/* @internal */
export function mustBeIterableObject(value: unknown, paramName?: string, message?: string, stackCrawlMark: Function = mustBeIterable): asserts value is Iterable<unknown> & object {
mustBeType(isIterableObject, value, paramName, message, stackCrawlMark);
}
/* @internal */
export function mustBeIterableObjectOrUndefined(value: unknown, paramName?: string, message?: string, stackCrawlMark: Function = mustBeIterable): asserts value is Iterable<unknown> & object {
mustBeTypeOrUndefined(isIterableObject, value, paramName, message, stackCrawlMark);
}
/* @internal */
export function mustBeIterator(value: unknown, paramName?: string, message?: string, stackCrawlMark: Function = mustBeIterator): asserts value is Iterator<unknown, unknown, unknown> {
mustBeType(isIterator, value, paramName, message, stackCrawlMark);
}
function isAsyncIterableObject(value: unknown): value is AsyncIterable<unknown> & object {
return isObject(value) && isAsyncIterable(value);
}
/* @internal */
export function mustBeAsyncIterableObject(value: unknown, paramName?: string, message?: string, stackCrawlMark: Function = mustBeIterable): asserts value is AsyncIterable<unknown> & object {
mustBeType(isAsyncIterableObject, value, paramName, message, stackCrawlMark);
}
function isAsyncOrSyncIterableObject(value: unknown): value is (AsyncIterable<unknown> | Iterable<unknown>) & object {
return isObject(value) && (isAsyncIterable(value) || isIterable(value));
}
/* @internal */
export function mustBeAsyncOrSyncIterableObject(value: unknown, paramName?: string, message?: string, stackCrawlMark: Function = mustBeIterable): asserts value is (AsyncIterable<unknown> | Iterable<unknown>) & object {
mustBeType(isAsyncOrSyncIterableObject, value, paramName, message, stackCrawlMark);
}
/* @internal */
export function mustBeAsyncOrSyncIterableObjectOrUndefined(value: unknown, paramName?: string, message?: string, stackCrawlMark: Function = mustBeIterable): asserts value is (AsyncIterable<unknown> | Iterable<unknown>) & object | undefined {
if (value !== undefined) mustBeType(isAsyncOrSyncIterableObject, value, paramName, message, stackCrawlMark);
} | the_stack |
interface ArtyomWindow extends Window {
webkitSpeechRecognition: any;
SpeechRecognition: any;
SpeechSynthesisUtterance: any;
}
interface SpeechRecognition extends EventTarget {
grammars: SpeechGrammarList;
lang: string;
continuous: boolean;
interimResults: boolean;
maxAlternatives: number;
serviceURI: string;
start(): void;
stop(): void;
abort(): void;
onaudiostart: (ev: Event) => any;
onsoundstart: (ev: Event) => any;
onspeechstart: (ev: Event) => any;
onspeechend: (ev: Event) => any;
onsoundend: (ev: Event) => any;
onresult: (ev: SpeechRecognitionEvent) => any;
onnomatch: (ev: SpeechRecognitionEvent) => any;
onerror: (ev: SpeechRecognitionError) => any;
onstart: (ev: Event) => any;
onend: (ev: Event) => any;
}
interface SpeechRecognitionStatic {
prototype: SpeechRecognition;
new (): SpeechRecognition;
}
declare var SpeechRecognition: SpeechRecognitionStatic;
declare var webkitSpeechRecognition: SpeechRecognitionStatic;
interface SpeechRecognitionError extends Event {
error: string;
message: string;
}
interface SpeechRecognitionAlternative {
transcript: string;
confidence: number;
}
interface SpeechRecognitionResult {
length: number;
item(index: number): SpeechRecognitionAlternative;
[index: number]: SpeechRecognitionAlternative;
isFinal: boolean;
}
interface SpeechRecognitionResultList {
length: number;
item(index: number): SpeechRecognitionResult;
[index: number]: SpeechRecognitionResult;
}
interface SpeechRecognitionEvent extends Event {
resultIndex: number;
results: SpeechRecognitionResultList;
interpretation: any;
emma: Document;
}
interface SpeechGrammar {
src: string;
weight: number;
}
interface SpeechGrammarStatic {
prototype: SpeechGrammar;
new (): SpeechGrammar;
}
declare var SpeechGrammar: SpeechGrammarStatic;
declare var webkitSpeechGrammar: SpeechGrammarStatic;
interface SpeechGrammarList {
length: number;
item(index: number): SpeechGrammar;
[index: number]: SpeechGrammar;
addFromURI(src: string, weight: number): void;
addFromString(string: string, weight: number): void;
}
interface SpeechGrammarListStatic {
prototype: SpeechGrammarList;
new (): SpeechGrammarList;
}
declare var SpeechGrammarList: SpeechGrammarListStatic;
declare var webkitSpeechGrammarList: SpeechGrammarListStatic;
interface SpeechSynthesis extends EventTarget {
pending: boolean;
speaking: boolean;
paused: boolean;
onvoiceschanged: (ev: Event) => any;
speak(utterance: SpeechSynthesisUtterance): void;
cancel(): void;
pause(): void;
resume(): void;
getVoices(): SpeechSynthesisVoice[];
}
interface SpeechSynthesisGetter {
speechSynthesis: SpeechSynthesis;
}
declare var speechSynthesis: SpeechSynthesis;
interface SpeechSynthesisUtterance extends EventTarget {
text: string;
lang: string;
voice: SpeechSynthesisVoice;
volume: number;
rate: number;
pitch: number;
onstart: (ev: SpeechSynthesisEvent) => any;
onend: (ev: SpeechSynthesisEvent) => any;
onerror: (ev: SpeechSynthesisErrorEvent) => any;
onpause: (ev: SpeechSynthesisEvent) => any;
onresume: (ev: SpeechSynthesisEvent) => any;
onmark: (ev: SpeechSynthesisEvent) => any;
onboundary: (ev: SpeechSynthesisEvent) => any;
}
interface SpeechSynthesisUtteranceStatic {
prototype: SpeechSynthesisUtterance;
new (text?: string): SpeechSynthesisUtterance;
}
declare var SpeechSynthesisUtterance: SpeechSynthesisUtteranceStatic;
interface SpeechSynthesisEvent extends Event {
utterance: SpeechSynthesisUtterance;
charIndex: number;
elapsedTime: number;
name: string;
}
interface SpeechSynthesisErrorEvent extends SpeechSynthesisEvent {
error: string;
}
interface SpeechSynthesisVoice {
voiceURI: string;
name: string;
lang: string;
localService: boolean;
default: boolean;
}
/**
* Internal class to provie an implementation of soundex
*/
class ArtyomInternals {
/**
* Retrieve a single voice of the browser by it's language code.
* It will return the first voice available for the language on every device.
*
* @param {languageCode} String Language code
* @returns {Voice}
*/
static getVoice(languageCode: string) {
let voiceIdentifiersArray = [];
switch (languageCode) {
case 'de-DE':
voiceIdentifiersArray = ArtyomLanguages.german;
break;
case 'en-GB':
voiceIdentifiersArray = ArtyomLanguages.englishGB;
break;
case "pt-BR":case "pt-PT":
voiceIdentifiersArray = ArtyomLanguages.brasilian;
break;
case "ru-RU":
voiceIdentifiersArray = ArtyomLanguages.russia;
break;
case "nl-NL":
voiceIdentifiersArray = ArtyomLanguages.holand;
break;
case 'es-ES':
voiceIdentifiersArray = ArtyomLanguages.spanish;
break;
case 'en-US':
voiceIdentifiersArray = ArtyomLanguages.englishUSA;
break;
case 'fr-FR':
voiceIdentifiersArray = ArtyomLanguages.france;
break;
case 'it-IT':
voiceIdentifiersArray = ArtyomLanguages.italian;
break;
case 'ja-JP':
voiceIdentifiersArray = ArtyomLanguages.japanese;
break;
case 'id-ID':
voiceIdentifiersArray = ArtyomLanguages.indonesia;
break;
case 'hi-IN':
voiceIdentifiersArray = ArtyomLanguages.hindi;
break;
case 'pl-PL':
voiceIdentifiersArray = ArtyomLanguages.polski;
break;
case 'zh-CN':
voiceIdentifiersArray = ArtyomLanguages.mandarinChinese;
break;
case 'zh-HK':
voiceIdentifiersArray = ArtyomLanguages.cantoneseChinese;
break;
case 'native':
voiceIdentifiersArray = ArtyomLanguages.native;
break;
default:
console.warn("The given language '"+ languageCode +"' for artyom is not supported yet. Using native voice instead");
break;
}
let voice = undefined;
let voices = speechSynthesis.getVoices();
let voicesLength = voiceIdentifiersArray.length;
for(var i = 0;i < voicesLength; i++){
var foundVoice = voices.filter(function (voice) {
return ( (voice.name == voiceIdentifiersArray[i]) || (voice.lang == voiceIdentifiersArray[i]));
})[0];
if(foundVoice){
voice = foundVoice;
break;
}
}
return voice;
};
/**
* Soundex algorithm implementation
* @param {string} s
* @return {string}
*/
static soundex(s: string) {
let a = s.toLowerCase().split(''),
f = a.shift(),
r = '',
codes = {
a: '',
e: '',
i: '',
o: '',
u: '',
b: 1,
f: 1,
p: 1,
v: 1,
c: 2,
g: 2,
j: 2,
k: 2,
q: 2,
s: 2,
x: 2,
z: 2,
d: 3,
t: 3,
l: 4,
m: 5,
n: 5,
r: 6
};
r = f +
a
.map(function(v, i, a) {
return codes[v];
})
.filter(function(v, i, a) {
return ((i === 0) ? v !== codes[f] : v !== a[i - 1]);
})
.join('');
return (r + '000').slice(0, 4).toUpperCase();
}
}
/**
* Helper methods for Artyom core implementation
*/
class ArtyomHelpers {
/**
* Determine if the current browser is Google Chrome (static method)
* @return {boolean}
*/
static isChrome() {
return navigator.userAgent.indexOf("Chrome") !== -1;
}
/**
* Determine if the current device is a mobile (static method)
* @return {boolean}
*/
static isMobileDevice() {
return (navigator.userAgent.match(/Android/i) ||
navigator.userAgent.match(/webOS/i) ||
navigator.userAgent.match(/iPhone/i) ||
navigator.userAgent.match(/iPad/i) ||
navigator.userAgent.match(/iPod/i) ||
navigator.userAgent.match(/BlackBerry/i) ||
navigator.userAgent.match(/Windows Phone/i));
}
/**
* Trigger an event
* @param {string} name
* @param {any} param
* @return {event}
*/
static artyomTriggerEvent(name: string, param?: any) {
let event = new CustomEvent(name, {'detail': param});
document.dispatchEvent(event);
return event;
};
}
interface ArtyomDevice {
isChrome(): boolean;
isMobile(): boolean;
}
interface ArtyomBrowserVoiceObject {
default: boolean;
lang: string;
localService: false;
name: string;
voiceURI: string;
}
interface ArtyomConfigProperties {
lang?: string;
recognizing?: boolean;
continuous?: boolean;
speed?: number;
volume?: number;
listen: boolean;
mode?: string;
debug: boolean;
helpers?: {
redirectRecognizedTextOutput: any;
remoteProcessorHandler: any;
lastSay: any;
};
executionKeyword?: string;
obeyKeyword?: string;
speaking?: boolean;
obeying?: boolean;
soundex?: boolean;
}
interface ArtyomCommand {
indexes: string[];
action: (i: number, wildcard?: string, full?: string) => void;
description?: string;
smart?: boolean;
}
interface ArtyomFlags {
restartRecognition: boolean
}
interface ArtyomRecognizer {
lang: string;
continuous: boolean;
interimResults: boolean;
maxAlternatives: number;
start(): void;
stop(): void;
onstart(): void;
onresult(event: any): void;
onerror(event: any): void;
onend(): void;
}
const ArtyomGlobalEvents = {
ERROR: "ERROR",
SPEECH_SYNTHESIS_START: "SPEECH_SYNTHESIS_START",
SPEECH_SYNTHESIS_END: "SPEECH_SYNTHESIS_END",
TEXT_RECOGNIZED: "TEXT_RECOGNIZED",
COMMAND_RECOGNITION_START : "COMMAND_RECOGNITION_START",
COMMAND_RECOGNITION_END: "COMMAND_RECOGNITION_END",
COMMAND_MATCHED: "COMMAND_MATCHED",
NOT_COMMAND_MATCHED: "NOT_COMMAND_MATCHED"
};
const ArtyomLanguages = {
german: ["Google Deutsch","de-DE","de_DE"],
spanish: ["Google español","es-ES", "es_ES","es-MX","es_MX"],
italian: ["Google italiano","it-IT","it_IT"],
japanese: ["Google 日本人","ja-JP","ja_JP"],
englishUSA: ["Google US English","en-US","en_US"],
englishGB: ["Google UK English Male","Google UK English Female","en-GB","en_GB"],
brasilian: ["Google português do Brasil","pt-PT","pt-BR","pt_PT","pt_BR"],
russia: ["Google русский","ru-RU","ru_RU"],
holand: ["Google Nederlands","nl-NL","nl_NL"],
france: ["Google français","fr-FR","fr_FR"],
polski: ["Google polski","pl-PL","pl_PL"],
indonesia: ["Google Bahasa Indonesia","id-ID","id_ID"],
hindi: ["Google हिन्दी","hi-IN", "hi_IN"],
mandarinChinese: ["Google 普通话(中国大陆)","zh-CN","zh_CN"],
cantoneseChinese: ["Google 粤語(香港)","zh-HK","zh_HK"],
native: ["native"]
}
export interface ArtyomJS {
/**
* Contains some basic information that artyom needs to know as the type of device and browser
*
* @tutorial http://docs.ourcodeworld.com/projects/artyom-js/documentation/methods/device
* @since 0.5.1
* @type {Object}
*/
device: ArtyomDevice;
/**
*
*/
artyomProperties: ArtyomConfigProperties;
/**
*
*/
artyomWSR: ArtyomRecognizer;
/**
* Artyom can return inmediately the voices available in your browser.
*
* @readonly
* @tutorial http://docs.ourcodeworld.com/projects/artyom-js/documentation/methods/getvoices
* @returns {Array}
*/
getVoices(): Array<SpeechSynthesisVoice>;
/**
* Returns an array with all the available commands for artyom.
*
* @tutorial http://docs.ourcodeworld.com/projects/artyom-js/documentation/methods/getavailablecommands
* @readonly
* @returns {Array}
*/
getAvailableCommands(): ArtyomCommand[];
/**
* Set up artyom for the application.
*
* This function will set the default language used by artyom
* or notice the user if artyom is not supported in the actual
* browser
* @tutorial http://docs.ourcodeworld.com/projects/artyom-js/documentation/methods/initialize
* @param {Object} config
* @returns {Boolean}
*/
initialize(config: ArtyomConfigProperties): Promise<void>;
/**
* Force artyom to stop listen even if is in continuos mode.
*
* @tutorial http://docs.ourcodeworld.com/projects/artyom-js/documentation/methods/fatality
* @returns {Boolean}
*/
fatality(): boolean;
/**
* Add dinamically commands to artyom using
* You can even add commands while artyom is active.
*
* @tutorial http://docs.ourcodeworld.com/projects/artyom-js/documentation/methods/addcommands
* @since 0.6
* @param {Object | Array[Objects]} param
* @returns {undefined}
*/
addCommands(param: ArtyomCommand | ArtyomCommand[]): boolean;
/**
* Remove the commands of artyom with indexes that matches with the given text.
*
* @tutorial http://docs.ourcodeworld.com/projects/artyom-js/documentation/methods/removecommands
* @param {type} identifier
* @returns {array}
*/
removeCommands(identifier: string): Array<Number>;
/**
* Removes all the added commands of artyom.
*
* @tutorial http://docs.ourcodeworld.com/projects/artyom-js/documentation/methods/emptycommands
* @since 0.6
* @returns {Array}
*/
emptyCommands(): ArtyomCommand[];
/**
* Stops the actual and pendings messages that artyom have to say.
*
* @tutorial http://docs.ourcodeworld.com/projects/artyom-js/documentation/methods/shutup
* @returns {undefined}
*/
shutUp(): void;
/**
* Returns an object with the actual properties of artyom.
*
* @tutorial http://docs.ourcodeworld.com/projects/artyom-js/documentation/methods/getproperties
* @returns {object}
*/
getProperties(): ArtyomConfigProperties;
/**
* Create a listener when an artyom action is called.
*
* @tutorial http://docs.ourcodeworld.com/projects/artyom-js/documentation/methods/when
* @param {type} event
* @param {type} action
* @returns {undefined}
*/
when(event: Event, action: any): any;
/**
* Returns the code language of artyom according to initialize function.
* if initialize not used returns english GB.
*
* @tutorial http://docs.ourcodeworld.com/projects/artyom-js/documentation/methods/getlanguage
* @returns {String}
*/
getLanguage(): string;
/**
* Talks a text according to the given parameters.
*
* @private
* @param {String} text Text to be spoken
* @param {Int} actualChunk Number of chunk of the
* @param {Int} totalChunks
* @returns {undefined}
*/
artyomTalk(text: string, actualChunk: number, totalChunks: number, callbacks: any): any;
/**
* Splits a string into an array of strings with a limited size (chunk_length).
*
* @param {String} input text to split into chunks
* @param {Integer} chunk_length limit of characters in every chunk
*/
splitStringByChunks(input: string, chunkLength: number): string[];
/**
* Process the given text into chunks and execute the function artyomTalk
*
* @tutorial http://docs.ourcodeworld.com/projects/artyom-js/documentation/methods/say
* @param {String} message Text to be spoken
* @param {Object} callbacks
* @returns {undefined}
*/
say(message: string, callbacks?: any): void;
/**
* Repeats the last sentence that artyom said.
* Useful in noisy environments.
*
* @tutorial http://docs.ourcodeworld.com/projects/artyom-js/documentation/methods/repeatlastsay
* @param {Boolean} returnObject If set to true, an object with the text and the timestamp when was executed will be returned.
* @returns {Object}
*/
repeatLastSay(returnObject: any): void;
/**
* Verify if the browser supports speechSynthesis.
*
* @tutorial http://docs.ourcodeworld.com/projects/artyom-js/documentation/methods/speechsupported
* @returns {Boolean}
*/
speechSupported(): boolean;
/**
* Verify if the browser supports webkitSpeechRecognition.
*
* @tutorial http://docs.ourcodeworld.com/projects/artyom-js/documentation/methods/recognizingsupported
* @returns {Boolean}
*/
recognizingSupported(): boolean;
/**
* Simulate a voice command via JS
*
* @tutorial http://docs.ourcodeworld.com/projects/artyom-js/documentation/methods/simulateinstruction
* @param {type} sentence
* @returns {undefined}
*/
simulateInstruction(sentence: string): boolean;
/**
* Returns an object with data of the matched element
*
* @private
* @param {string} comando
* @returns {Boolean || Function}
*/
artyomExecute(voice: string);
/**
* Displays a message in the console if the artyom propery DEBUG is set to true.
*
* @tutorial http://docs.ourcodeworld.com/projects/artyom-js/documentation/methods/debug
* @param {type} e
* @param {type} o
* @returns {undefined}
*/
debug(stringEvent: string, traceLevel: string): void;
/**
* Allows to retrieve the recognized spoken text of artyom
* and do something with it everytime something is recognized
*
* @param {String} action
* @returns {Boolean}
*/
redirectRecognizedTextOutput(action: Function): boolean;
/**
* Says a random quote and returns it's object
*
* @param {type} data
* @returns {object}
*/
sayRandom(data);
/**
* Artyom provide an easy way to create a
* dictation for your user.
*
* Just create an instance and start and stop when you want
*
* @returns Object | newDictation
*/
newDictation(settings);
/**
* A voice prompt will be executed.
*
* @param {type} config
* @returns {undefined}
*/
newPrompt(config);
/**
* Artyom awaits for orders when this function
* is executed.
*
* If artyom gets a first parameter the instance will be stopped.
*
* @private
* @returns {undefined}
*/
artyomHey(resolve: any, reject: any);
/**
* This function will return the webkitSpeechRecognition object used by artyom
* retrieve it only to debug on it or get some values, do not make changes directly
*
* @readonly
* @since 0.9.2
* @summary Retrieve the native webkitSpeechRecognition object
* @returns {Object webkitSpeechRecognition}
*/
getNativeApi();
/**
* This function returns a boolean according to the SpeechRecognition status
* if artyom is listening, will return true.
*
* Note: This is not a feature of SpeechRecognition, therefore this value hangs on
* the fiability of the onStart and onEnd events of the SpeechRecognition
*
* @since 0.9.3
* @summary Returns true if SpeechRecognition is active
* @returns {Boolean}
*/
isRecognizing(): boolean;
/**
* This function returns a boolean according to the speechSynthesis status
* if artyom is speaking, will return true.
*
* Note: This is not a feature of speechSynthesis, therefore this value hangs on
* the fiability of the onStart and onEnd events of the speechSynthesis
*
* @since 0.9.3
* @summary Returns true if speechSynthesis is active
* @returns {Boolean}
*/
isSpeaking(): boolean;
/**
* The SpeechSynthesisUtterance objects are stored in the artyomGarbageCollector variable
* to prevent the wrong behaviour of artyom.say.
* Use this method to clear all spoken SpeechSynthesisUtterance unused objects.
*
* @returns {Boolean}
*/
clearGarbageCollection();
/**
* Returns the SpeechSynthesisUtterance garbageobjects.
*
* @returns {Array}
*/
getGarbageCollection();
/**
* Pause the processing of commands. Artyom still listening in the background and it can be resumed after a couple of seconds.
*
* @returns {Boolean}
*/
dontObey();
/**
* Allow artyom to obey commands again.
*
* @returns {Boolean}
*/
obey();
/**
* A boolean to check if artyom is obeying commands or not.
*
* @returns {Boolean}
*/
isObeying(): boolean;
/**
* Add commands like an artisan. If you use artyom for simple tasks
* then probably you don't like to write a lot to achieve it.
*
* Use the artisan syntax to write less, but with the same accuracy.
*
* @disclaimer Not a promise-based implementation, just syntax.
* @returns {Boolean}
*/
on(indexes, smart): any;
/**
* Returns a string with the actual version of Artyom script.
*
* @summary Returns the actual version of artyom
* @returns {String}
*/
getVersion(): string;
/**
* Process the recognized text if artyom is active in remote mode.
*
* @returns {Boolean}
*/
remoteProcessorService(action);
}
export class ArtyomJsImpl implements ArtyomJS {
artyomCommands: ArtyomCommand[] = [];
artyomGarbageCollector: SpeechSynthesisUtterance[] = [];
artyomVoice: Object;
artyomProperties: ArtyomConfigProperties;
artyomFlags: ArtyomFlags;
artyomWSR: ArtyomRecognizer;
constructor() {
// Load browser voices as soon as possible
if (window.hasOwnProperty('speechSynthesis')) {
speechSynthesis.getVoices();
}
if (window.hasOwnProperty('webkitSpeechRecognition')) {
const { webkitSpeechRecognition } : ArtyomWindow = <ArtyomWindow>window;
this.artyomWSR = new webkitSpeechRecognition();
}
// Default values
this.artyomProperties = {
lang: 'en-GB',
recognizing: false,
continuous: false,
speed: 1,
volume: 1,
listen: false,
mode: 'normal',
debug: false,
helpers: {
redirectRecognizedTextOutput: null,
remoteProcessorHandler: null,
lastSay: null
},
executionKeyword: null,
obeyKeyword: null,
speaking: false,
obeying: true,
soundex: false
};
// Recognition
this.artyomFlags = {
restartRecognition: false
};
// Default voice
this.artyomVoice = {
default:false,
lang: "en-GB",
localService: false,
name: "Google UK English Male",
voiceURI: "Google UK English Male"
};
}
device = {
isChrome: () => { return ArtyomHelpers.isChrome(); },
isMobile: () => { return !!ArtyomHelpers.isMobileDevice(); }
};
getVoices = (): Array<SpeechSynthesisVoice> => {
return (window['speechSynthesis']).getVoices();
};
getAvailableCommands = (): ArtyomCommand[] => {
return this.artyomCommands;
};
initialize = (config: ArtyomConfigProperties): Promise<void> => {
if (typeof (config) !== "object") {
return Promise.reject("You must give the configuration for start artyom properly.");
}
if (config.hasOwnProperty("lang")) {
this.artyomVoice = ArtyomInternals.getVoice(config.lang);
this.artyomProperties.lang = config.lang;
}
if (config.hasOwnProperty("continuous")) {
if (config.continuous) {
this.artyomProperties.continuous = true;
this.artyomFlags.restartRecognition = true;
} else {
this.artyomProperties.continuous = false;
this.artyomFlags.restartRecognition = false;
}
}
if (config.hasOwnProperty("speed")) {
this.artyomProperties.speed = config.speed;
}
if (config.hasOwnProperty("soundex")) {
this.artyomProperties.soundex = config.soundex;
}
if (config.hasOwnProperty("executionKeyword")) {
this.artyomProperties.executionKeyword = config.executionKeyword;
}
if (config.hasOwnProperty("obeyKeyword")) {
this.artyomProperties.obeyKeyword = config.obeyKeyword;
}
if (config.hasOwnProperty("volume")) {
this.artyomProperties.volume = config.volume;
}
if(config.hasOwnProperty("listen")){
this.artyomProperties.listen = config.listen;
}
if(config.hasOwnProperty("debug")){
this.artyomProperties.debug = config.debug;
}else{
console.warn("The initialization doesn't provide how the debug mode should be handled. Is recommendable to set this value either to true or false.");
}
if (config.mode) {
this.artyomProperties.mode = config.mode;
}
if (this.artyomProperties.listen === true) {
let hey = this.artyomHey;
return new Promise<void>((resolve: any, reject: any) => {
hey(resolve, reject);
});
}
return Promise.resolve(undefined);
};
fatality = (): boolean => {
try {
// if config is continuous mode, deactivate anyway.
this.artyomFlags.restartRecognition = false;
this.artyomWSR.stop();
return true;
} catch(e) {
console.log(e);
return false;
}
};
addCommands = (param: ArtyomCommand | ArtyomCommand[]): boolean => {
let _processObject = (obj: ArtyomCommand): void => {
if(obj.hasOwnProperty("indexes")) {
this.artyomCommands.push(obj);
} else {
console.error("The following command doesn't provide any index to execute :");
console.dir(obj);
}
};
if (param instanceof Array) {
const paramLength = param.length;
for (let i = 0; i < paramLength; i++) {
_processObject(param[i]);
}
} else {
_processObject(param);
}
return true;
};
removeCommands = (identifier: string): Array<Number> => {
let toDelete = [];
if (typeof (identifier) === "string") {
const commandsLength = this.artyomCommands.length;
for (let i = 0; i < commandsLength; i++) {
let command = this.artyomCommands[i];
if (command.indexes.indexOf(identifier)) {
toDelete.push(i);
}
}
const toDeleteLength = toDelete.length;
for (let o = 0; o < toDeleteLength; o++) {
this.artyomCommands.splice(o, 1);
}
}
return toDelete;
}
emptyCommands = (): ArtyomCommand[] => {
return this.artyomCommands = [];
};
shutUp = () => {
if ('speechSynthesis' in window) {
do {
(window['speechSynthesis']).cancel();
} while ((window['speechSynthesis']).pending === true);
}
this.artyomProperties.speaking = false;
this.clearGarbageCollection();
};
getProperties = (): ArtyomConfigProperties => {
return this.artyomProperties;
};
when = (event, action) => {
return document.addEventListener(event, (e) => {
action(e.detail);
}, false);
};
getLanguage = (): string => {
return this.artyomProperties.lang;
};
artyomTalk = (text, actualChunk, totalChunks, callbacks) => {
let msg = new SpeechSynthesisUtterance();
msg.text = text;
msg.volume = this.artyomProperties.volume;
msg.rate = this.artyomProperties.speed;
// Select the voice according to the selected
if (typeof(this.artyomVoice) != "undefined") {
var availableVoice = undefined;
if(callbacks){
// If the language to speak has been forced, use it
if(callbacks.hasOwnProperty("lang")){
availableVoice = ArtyomInternals.getVoice(callbacks.lang);
// Otherwise speak in the language of the initialization
}else{
availableVoice = ArtyomInternals.getVoice(this.artyomProperties.lang);
}
}else{
// Otherwise speak in the language of the initialization
availableVoice = ArtyomInternals.getVoice(this.artyomProperties.lang);
}
// If is a mobile device, provide only the language code in the lang property i.e "es_ES"
if(this.device.isMobile()){
// Try to set the voice only if exists, otherwise don't use anything to use the native voice
if(availableVoice){
msg.lang = availableVoice.lang;
}
// If browser provide the entire object
}else{
msg.voice = availableVoice;
}
}else{
console.warn("Using default voice because no voice was selected during the initialization probably because there were no voices available. Initialize artyom after the onload event of the window.");
}
// If is first text chunk (onStart)
if (actualChunk == 1) {
msg.addEventListener('start', () => {
// Set artyom is talking
this.artyomProperties.speaking = true;
// Trigger the onSpeechSynthesisStart event
this.debug("Event reached : " + ArtyomGlobalEvents.SPEECH_SYNTHESIS_START);
// The original library dismiss the second parameter
ArtyomHelpers.artyomTriggerEvent(ArtyomGlobalEvents.SPEECH_SYNTHESIS_START);
// Trigger the onStart callback if exists
if (callbacks) {
if (typeof(callbacks.onStart) == "function") {
callbacks.onStart.call(msg);
}
}
});
}
// If is final text chunk (onEnd)
if ((actualChunk) >= totalChunks) {
msg.addEventListener('end', () => {
// Set artyom is talking
this.artyomProperties.speaking = false;
// Trigger the onSpeechSynthesisEnd event
this.debug("Event reached : " + ArtyomGlobalEvents.SPEECH_SYNTHESIS_END);
ArtyomHelpers.artyomTriggerEvent(ArtyomGlobalEvents.SPEECH_SYNTHESIS_END);
// Trigger the onEnd callback if exists.
if(callbacks){
if(typeof(callbacks.onEnd) == "function"){
callbacks.onEnd.call(msg);
}
}
});
}
// Notice how many chunks were processed for the given text.
this.debug((actualChunk) + " text chunk processed succesfully out of " + totalChunks);
// Important : Save the SpeechSynthesisUtterance object in memory, otherwise it will get lost
// thanks to the Garbage collector of javascript
this.artyomGarbageCollector.push(msg);
(window['speechSynthesis']).speak(msg);
};
splitStringByChunks = (input, chunk_length): string[] => {
let prev = 0;
let output = [];
input = input || "";
chunk_length = chunk_length || 100;
let curr = chunk_length;
while (input[curr]) {
if (input[curr++] == ' ') {
output.push(input.substring(prev,curr));
prev = curr;
curr += chunk_length;
}
}
output.push(input.substr(prev));
return output;
};
say = (message: string, callbacks?): void => {
let artyom_say_max_chunk_length = 115;
if (this.speechSupported()) {
if (typeof(message) === 'string') {
if (message.length > 0) {
let definitive = [];
// If the providen text is long, proceed to split it
if(message.length > artyom_say_max_chunk_length) {
// Split the given text by pause reading characters [",",":",";","."] to provide a natural reading feeling.
let naturalReading = message.split(/,|:|\.|;/);
naturalReading.forEach((chunk, index) => {
// If the sentence is too long and could block the API, split it to prevent any errors.
if(chunk.length > artyom_say_max_chunk_length){
// Process the providen string into strings (withing an array) of maximum aprox. 115 characters to prevent any error with the API.
let temp_processed = this.splitStringByChunks(chunk, artyom_say_max_chunk_length);
// Add items of the processed sentence into the definitive chunk.
definitive.push.apply(definitive, temp_processed);
} else {
// Otherwise just add the sentence to being spoken.
definitive.push(chunk);
}
});
} else {
definitive.push(message);
}
// Clean any empty item in array
definitive = definitive.filter((e) => { return e; });
// Finally proceed to talk the chunks and assign the callbacks.
definitive.forEach((chunk, index) => {
let numberOfChunk = (index + 1);
if (chunk) {
this.artyomTalk(chunk, numberOfChunk, definitive.length, callbacks);
}
});
// Save the spoken text into the lastSay object of artyom
this.artyomProperties.helpers.lastSay = {
text: message,
date: new Date()
};
} else {
console.warn("Artyom expects a string to say ... none given.");
}
} else {
console.warn("Artyom expects a string to say ... " + typeof (message) + " given.");
}
}
};
repeatLastSay = (returnObject): void => {
let last = this.artyomProperties.helpers.lastSay;
if (returnObject) {
return last;
} else {
if (last != null) {
this.say(last.text);
}
}
};
speechSupported = (): boolean => {
return 'speechSynthesis' in window;
};
recognizingSupported = (): boolean => {
return 'webkitSpeechRecognition' in window;
};
simulateInstruction = (sentence: string): boolean => {
if ((!sentence) || (typeof (sentence) !== "string")) {
console.warn("Cannot execute a non string command");
return false;
}
let foundCommand = this.artyomExecute(sentence); // Command founded object
if(foundCommand.result && foundCommand.objeto) {
if (foundCommand.objeto.smart) {
this.debug('Smart command matches with simulation, executing', "info");
foundCommand.objeto.action(foundCommand.indice, foundCommand.wildcard.item, foundCommand.wildcard.full);
} else {
this.debug('Command matches with simulation, executing', "info");
foundCommand.objeto.action(foundCommand.indice); // Execute Normal command
}
return true;
} else {
console.warn("No command founded trying with " + sentence);
return false;
}
};
artyomExecute = (voice: string) => {
if (!voice) {
console.warn("Internal error: Execution of empty command");
return {
result: false,
indice: null,
objeto: null,
wildcard: {
item: null,
full: voice
}
};
}
let wildcard;
this.debug(">> " + voice);
// @3 Artyom needs time to think that
let artyomCommandsLength = this.artyomCommands.length;
for (let i = 0; i < artyomCommandsLength; i++) {
let instruction = this.artyomCommands[i];
let opciones = instruction.indexes;
let encontrado = -1;
const optionsLength = opciones.length;
for (let c = 0; c < optionsLength; c++) {
let opcion:any = opciones[c];
if (!instruction.smart) {
continue; // Jump if is not smart command
}
if(opcion instanceof RegExp){
// If RegExp matches
if(opcion.test(voice)){
this.debug(">> REGEX "+ opcion.toString() + " MATCHED AGAINST " + voice + " WITH INDEX " + c + " IN COMMAND ", "info");
encontrado = c;
}
// Otherwise just wildcards
}else{
if (opcion.indexOf("*") !== -1) {
// Logic here
let grupo = opcion.split("*");
if (grupo.length > 2) {
console.warn("Artyom found a smart command with " + (grupo.length - 1) + " wildcards. Artyom only support 1 wildcard for each command. Sorry");
continue;
}
// Start smart command
let before = grupo[0];
let latter = grupo[1];
// Wildcard in the end
//if ((latter === "") || (latter === " ")) {
if(latter.trim() === "") {
if ((voice.indexOf(before) !== -1) || ((voice.toLowerCase()).indexOf(before.toLowerCase()) !== -1)) {
let wildy = voice.replace(before, '');
wildy = (wildy.toLowerCase()).replace(before.toLowerCase(), '');
wildcard = wildy;
encontrado = c;
}
} else {
if ((voice.indexOf(before) != -1) || ((voice.toLowerCase()).indexOf(before.toLowerCase()) != -1)) {
if ((voice.indexOf(latter) != -1) || ((voice.toLowerCase()).indexOf(latter.toLowerCase()) != -1)) {
let wildy = voice.replace(before, '').replace(latter, '');
wildy = (wildy.toLowerCase())
.replace(before.toLowerCase(), '')
.replace(latter.toLowerCase(), '');
wildy = (wildy.toLowerCase()).replace(latter.toLowerCase(), '');
wildcard = wildy;
encontrado = c;
}
}
}
} else {
console.warn("Founded command marked as SMART but have no wildcard in the indexes, remove the SMART for prevent extensive memory consuming or add the wildcard *");
}
}
if ((encontrado >= 0)) {
encontrado = c;
break;
}
}
if (encontrado >= 0) {
ArtyomHelpers.artyomTriggerEvent(ArtyomGlobalEvents.COMMAND_MATCHED);
return {
result: true,
indice: encontrado,
objeto: instruction,
wildcard: {
item: wildcard,
full: voice
}
};
}
} // End @3
// @1 Search for IDENTICAL matches in the commands if nothing matches start with a index match in commands
artyomCommandsLength = this.artyomCommands.length;
for (let i = 0; i < artyomCommandsLength; i++) {
let instruction = this.artyomCommands[i];
let opciones = instruction.indexes;
let encontrado = -1;
// Execution of match with identical commands
for (let c = 0; c < opciones.length; c++) {
let opcion = opciones[c];
if (instruction.smart) {
continue; // Jump wildcard commands
}
if ((voice === opcion)) {
this.debug(">> MATCHED FULL EXACT OPTION " + opcion + " AGAINST " + voice + " WITH INDEX " + c + " IN COMMAND ", "info");
encontrado = c;
break;
} else if ((voice.toLowerCase() === opcion.toLowerCase())) {
this.debug(">> MATCHED OPTION CHANGING ALL TO LOWERCASE " + opcion + " AGAINST " + voice + " WITH INDEX " + c + " IN COMMAND ", "info");
encontrado = c;
break;
}
}
if (encontrado >= 0) {
ArtyomHelpers.artyomTriggerEvent(ArtyomGlobalEvents.COMMAND_MATCHED);
return {
result: true,
indice: encontrado,
objeto: instruction,
wildcard: null
};
}
} // End @1
// Step 3 Commands recognition. If the command is not smart, and any of the commands match exactly then try to find a command in all the quote.
artyomCommandsLength = this.artyomCommands.length;
for (let i = 0; i < artyomCommandsLength; i++) {
let instruction = this.artyomCommands[i];
let opciones = instruction.indexes;
let encontrado = -1;
// Execution of match with index
let optionsLength = opciones.length;
for (let c = 0; c < optionsLength; c++) {
if (instruction.smart) {
continue; // Jump wildcard commands
}
let opcion = opciones[c];
if ((voice.indexOf(opcion) >= 0)) {
this.debug(">> MATCHED INDEX EXACT OPTION " + opcion + " AGAINST " + voice + " WITH INDEX " + c + " IN COMMAND ", "info");
encontrado = c;
break;
} else if (((voice.toLowerCase()).indexOf(opcion.toLowerCase()) >= 0)) {
this.debug(">> MATCHED INDEX OPTION CHANGING ALL TO LOWERCASE " + opcion + " AGAINST " + voice + " WITH INDEX " + c + " IN COMMAND ", "info");
encontrado = c;
break;
}
}
if (encontrado >= 0) {
ArtyomHelpers.artyomTriggerEvent(ArtyomGlobalEvents.COMMAND_MATCHED);
return {
result: true,
indice: encontrado,
objeto: instruction,
wildcard: null
};
}
} // End Step 3
/**
* If the soundex options is enabled, proceed to process the commands in case that any of the previous
* ways of processing (exact, lowercase and command in quote) didn't match anything.
* Based on the soundex algorithm match a command if the spoken text is similar to any of the artyom commands.
* Example:
* If you have a command with "Open Wallmart" and "Open Willmar" is recognized, the open wallmart command will be triggered.
* soundex("Open Wallmart") == soundex("Open Willmar") <= true
*
*/
if(this.artyomProperties.soundex){
artyomCommandsLength = this.artyomCommands.length;
for (let i = 0; i < artyomCommandsLength; i++) {
let instruction = this.artyomCommands[i];
let opciones = instruction.indexes;
let encontrado = -1;
let optionsLength = opciones.length;
for (let c = 0; c < optionsLength; c++) {
let opcion = opciones[c];
if (instruction.smart) {
continue; // Jump wildcard commands
}
if(ArtyomInternals.soundex(voice) == ArtyomInternals.soundex(opcion)){
this.debug(">> Matched Soundex command '"+opcion+"' AGAINST '"+voice+"' with index "+ c , "info");
encontrado = c;
ArtyomHelpers.artyomTriggerEvent(ArtyomGlobalEvents.COMMAND_MATCHED);
return {
result: true,
indice: encontrado,
objeto: instruction,
wildcard: null
};
}
}
}
}
this.debug("Event reached : " + ArtyomGlobalEvents.NOT_COMMAND_MATCHED);
ArtyomHelpers.artyomTriggerEvent(ArtyomGlobalEvents.NOT_COMMAND_MATCHED);
return {
result: false,
indice: null,
objeto: null,
wildcard: null
};
};
debug = (stringEvent: string, traceLevel?: string): void => {
if (this.artyomProperties.debug === true) {
switch (traceLevel) {
case 'error':
console.log(' %cArtyom.js ' + " " + stringEvent, 'background: #C12127; color: #FFFFFF');
break;
case 'warn':
console.warn(stringEvent);
break;
case 'info':
console.log(' %cArtyom.js: ' + " " + stringEvent, 'background: #4285F4; color: #FFFFFF');
break;
default:
console.log(' %cArtyom.js %c ' + " " + stringEvent, 'background: #005454; color: #BFF8F8', 'color:black;');
break;
}
}
};
redirectRecognizedTextOutput = (action: Function): boolean => {
if (typeof (action) != "function") {
console.warn("Expected function to handle the recognized text ...");
return false;
}
this.artyomProperties.helpers.redirectRecognizedTextOutput = action;
return true;
};
sayRandom = (data) => {
if (data instanceof Array) {
var index = Math.floor(Math.random() * data.length);
this.say(data[index]);
return {
text: data[index],
index: index
};
} else {
console.error("Random quotes must be in an array !");
return null;
}
};
newDictation = (settings) => {
if (!this.recognizingSupported()) {
console.error("SpeechRecognition is not supported in this browser");
return false;
}
let dictado = new webkitSpeechRecognition();
dictado.continuous = true;
dictado.interimResults = true;
dictado.lang = this.artyomProperties.lang;
dictado.onresult = (event) => {
let temporal = "";
let interim = "";
let resultsLength = event.results.length;
for (let i = 0; i < resultsLength; ++i) {
if (event.results[i].isFinal) {
temporal += event.results[i][0].transcript;
} else {
interim += event.results[i][0].transcript;
}
}
if (settings.onResult) {
settings.onResult(interim, temporal);
}
};
return new function () {
let dictation = dictado;
let flagStartCallback = true;
let flagRestart = false;
this.onError = null;
this.start = () => {
if (settings.continuous === true) {
flagRestart = true;
}
dictation.onstart = () => {
if (typeof (settings.onStart) === "function") {
if (flagStartCallback === true) {
settings.onStart();
}
}
};
dictation.onend = () => {
if (flagRestart === true) {
flagStartCallback = false;
dictation.start();
} else {
flagStartCallback = true;
if (typeof (settings.onEnd) === "function") {
settings.onEnd();
}
}
};
dictation.start();
};
this.stop = () => {
flagRestart = false;
dictation.stop();
};
if (typeof (settings.onError) === "function") {
dictation.onerror = settings.onError;
}
};
};
newPrompt = (config) => {
if (typeof (config) !== "object") {
console.error("Expected the prompt configuration.");
}
let copyActualCommands = (<any>Object).assign([], this.artyomCommands);
this.emptyCommands();
let promptCommand: ArtyomCommand = {
description: 'Setting the artyom commands only for the prompt. The commands will be restored after the prompt finishes',
indexes: config.options,
smart: (config.smart) ? true : false,
action: (i, wildcard) => {
this.artyomCommands = copyActualCommands;
let toExe = config.onMatch(i, wildcard);
if (typeof (toExe) !== "function") {
console.error("onMatch function expects a returning function to be executed");
return;
}
toExe();
}
};
this.addCommands(promptCommand);
if (typeof (config.beforePrompt) !== "undefined") {
config.beforePrompt();
}
this.say(config.question, {
onStart: () => {
if (typeof (config.onStartPrompt) !== "undefined") {
config.onStartPrompt();
}
},
onEnd: () => {
if (typeof (config.onEndPrompt) !== "undefined") {
config.onEndPrompt();
}
}
});
};
artyomHey = (resolve: any, reject: any): any => {
let start_timestamp;
let artyom_is_allowed;
/**
* On mobile devices the recognized text is always thrown twice.
* By setting the following configuration, fixes the issue
*/
if(ArtyomHelpers.isMobileDevice){
this.artyomWSR.continuous = false;
this.artyomWSR.interimResults = false;
this.artyomWSR.maxAlternatives = 1;
}else{
this.artyomWSR.continuous = true;
this.artyomWSR.interimResults = true;
}
this.artyomWSR.lang = this.artyomProperties.lang;
this.artyomWSR.onstart = () => {
this.debug("Event reached : " + ArtyomGlobalEvents.COMMAND_RECOGNITION_START);
ArtyomHelpers.artyomTriggerEvent(ArtyomGlobalEvents.COMMAND_RECOGNITION_START);
this.artyomProperties.recognizing = true;
artyom_is_allowed = true;
resolve();
};
/**
* Handle all artyom posible exceptions
* @param {type} event
* @returns {undefined}
*/
this.artyomWSR.onerror = (event) => {
reject(event.error);
// Dispath error globally (artyom.when)
ArtyomHelpers.artyomTriggerEvent(ArtyomGlobalEvents.ERROR, {
code: event.error
});
if (event.error === 'audio-capture') {
artyom_is_allowed = false;
}
if (event.error === 'not-allowed') {
artyom_is_allowed = false;
if (event.timeStamp - start_timestamp < 100) {
ArtyomHelpers.artyomTriggerEvent(ArtyomGlobalEvents.ERROR, {
code: "info-blocked",
message: "Artyom needs the permision of the microphone, is blocked."
});
} else {
ArtyomHelpers.artyomTriggerEvent(ArtyomGlobalEvents.ERROR, {
code: "info-denied",
message: "Artyom needs the permision of the microphone, is denied"
});
}
}
};
/**
* Check if continuous mode is active and restart the recognition. Throw events too.
*/
this.artyomWSR.onend = () => {
if (this.artyomFlags.restartRecognition === true) {
if (artyom_is_allowed === true) {
this.artyomWSR.start();
this.debug("Continuous mode enabled, restarting", "info");
} else {
console.error("Verify the microphone and check for the table of errors in sdkcarlos.github.io/sites/artyom.html to solve your problem. If you want to give your user a message when an error appears add an artyom listener");
}
ArtyomHelpers.artyomTriggerEvent(ArtyomGlobalEvents.COMMAND_RECOGNITION_END,{
code: "continuous_mode_enabled",
message: "OnEnd event reached with continuous mode"
});
} else {
ArtyomHelpers.artyomTriggerEvent(ArtyomGlobalEvents.COMMAND_RECOGNITION_END,{
code: "continuous_mode_disabled",
message: "OnEnd event reached without continuous mode"
});
}
this.artyomProperties.recognizing = false;
};
/**
* Declare the processor dinamycally according to the mode of artyom to increase the performance.
*/
let onResultProcessor: Function;
// Process the recognition in normal mode
if(this.artyomProperties.mode === "normal"){
onResultProcessor = (event) => {
if (!this.artyomCommands.length) {
this.debug("No commands to process in normal mode.");
return;
}
ArtyomHelpers.artyomTriggerEvent(ArtyomGlobalEvents.TEXT_RECOGNIZED);
let cantidadResultados = event.results.length;
for (let i = event.resultIndex; i < cantidadResultados; ++i) {
let identificated = event.results[i][0].transcript;
if (event.results[i].isFinal) {
let comando = this.artyomExecute(identificated.trim());
// Redirect the output of the text if necessary
if (typeof (this.artyomProperties.helpers.redirectRecognizedTextOutput) === "function") {
this.artyomProperties.helpers.redirectRecognizedTextOutput(identificated, true);
}
if ((comando.result !== false) && (this.artyomProperties.recognizing === true)) {
this.debug("<< Executing Matching Recognition in normal mode >>", "info");
this.artyomWSR.stop();
this.artyomProperties.recognizing = false;
// Execute the command if smart
if (comando.wildcard) {
comando.objeto.action(comando.indice, comando.wildcard.item, comando.wildcard.full);
// Execute a normal command
} else {
comando.objeto.action(comando.indice);
}
break;
}
} else {
// Redirect output when necesary
if (typeof (this.artyomProperties.helpers.redirectRecognizedTextOutput) === "function") {
this.artyomProperties.helpers.redirectRecognizedTextOutput(identificated, false);
}
if (typeof (this.artyomProperties.executionKeyword) === "string") {
if (identificated.indexOf(this.artyomProperties.executionKeyword) !== -1) {
let comando = this.artyomExecute(identificated.replace(this.artyomProperties.executionKeyword, '').trim());
if ((comando.result !== false) && (this.artyomProperties.recognizing === true)) {
this.debug("<< Executing command ordered by ExecutionKeyword >>", 'info');
this.artyomWSR.stop();
this.artyomProperties.recognizing = false;
// Executing Command Action
if (comando.wildcard) {
comando.objeto.action(comando.indice, comando.wildcard.item, comando.wildcard.full);
} else {
comando.objeto.action(comando.indice);
}
break;
}
}
}
this.debug("Normal mode : " + identificated);
}
}
}
}
// Process the recognition in quick mode
if(this.artyomProperties.mode === "quick"){
onResultProcessor = (event) => {
if (!this.artyomCommands.length) {
this.debug("No commands to process.");
return;
}
ArtyomHelpers.artyomTriggerEvent(ArtyomGlobalEvents.TEXT_RECOGNIZED);
let cantidadResultados = event.results.length;
for (let i = event.resultIndex; i < cantidadResultados; ++i) {
let identificated = event.results[i][0].transcript;
if (!event.results[i].isFinal) {
let comando = this.artyomExecute(identificated.trim());
// Redirect output when necesary
if (typeof (this.artyomProperties.helpers.redirectRecognizedTextOutput) === "function") {
this.artyomProperties.helpers.redirectRecognizedTextOutput(identificated, true);
}
if ((comando.result !== false) && (this.artyomProperties.recognizing == true)) {
this.debug("<< Executing Matching Recognition in quick mode >>", "info");
this.artyomWSR.stop();
this.artyomProperties.recognizing = false;
// Executing Command Action
if (comando.wildcard) {
comando.objeto.action(comando.indice, comando.wildcard.item);
} else {
comando.objeto.action(comando.indice);
}
break;
}
} else {
let comando = this.artyomExecute(identificated.trim());
// Redirect output when necesary
if (this.artyomProperties.helpers && typeof (this.artyomProperties.helpers.redirectRecognizedTextOutput) === "function") {
this.artyomProperties.helpers.redirectRecognizedTextOutput(identificated, false);
}
if ((comando.result !== false) && (this.artyomProperties.recognizing == true)) {
this.debug("<< Executing Matching Recognition in quick mode >>", "info");
this.artyomWSR.stop();
this.artyomProperties.recognizing = false;
// Executing Command Action
if (comando.wildcard) {
if(comando.objeto && typeof(comando.indice) === 'number') {
comando.objeto.action(comando.indice, comando.wildcard.item);
}
} else {
if(comando.objeto && typeof(comando.indice) === 'number') {
comando.objeto.action(comando.indice);
}
}
break;
}
}
this.debug("Quick mode : " + identificated);
}
}
}
// Process the recognition in remote mode
if(this.artyomProperties.mode == "remote"){
onResultProcessor = (event: any) => {
ArtyomHelpers.artyomTriggerEvent(ArtyomGlobalEvents.TEXT_RECOGNIZED);
let cantidadResultados = event.results.length;
if (this.artyomProperties.helpers && typeof (this.artyomProperties.helpers.remoteProcessorHandler) !== "function") {
return this.debug("The remoteProcessorService is undefined.", "warn");
}
for (let i = event.resultIndex; i < cantidadResultados; ++i) {
let identificated = event.results[i][0].transcript;
if(this.artyomProperties.helpers) {
this.artyomProperties.helpers.remoteProcessorHandler({
text: identificated,
isFinal: event.results[i].isFinal
});
}
}
}
}
/**
* Process the recognition event with the previously declared processor function.
*/
this.artyomWSR.onresult = (event) => {
if(this.artyomProperties.obeying) {
onResultProcessor(event);
} else {
// Handle obeyKeyword if exists and artyom is not obeying
if(!this.artyomProperties.obeyKeyword) {
return;
}
let temporal = "";
let interim = "";
let resultsLength = event.results.length;
for (let i = 0; i < resultsLength; ++i) {
if (event.results[i].final) {
temporal += event.results[i][0].transcript;
} else {
interim += event.results[i][0].transcript;
}
}
this.debug("Artyom is not obeying","warn");
// If the obeyKeyword is found in the recognized text enable command recognition again
if(((interim).indexOf(this.artyomProperties.obeyKeyword) > -1) || (temporal).indexOf(this.artyomProperties.obeyKeyword) > -1){
this.artyomProperties.obeying = true;
}
}
};
if (this.artyomProperties.recognizing) {
this.artyomWSR.stop();
this.debug("Event reached : " + ArtyomGlobalEvents.COMMAND_RECOGNITION_END);
ArtyomHelpers.artyomTriggerEvent(ArtyomGlobalEvents.COMMAND_RECOGNITION_END);
} else {
try {
this.artyomWSR.start();
} catch (e) {
ArtyomHelpers.artyomTriggerEvent(ArtyomGlobalEvents.ERROR,{
code: "recognition_overlap",
message: "A webkitSpeechRecognition instance has been started while there's already running. Is recommendable to restart the Browser"
});
}
}
};
getNativeApi = () => {
return this.artyomWSR;
};
isRecognizing = (): boolean => {
return !!this.artyomProperties.recognizing;
};
isSpeaking = (): boolean => {
return !!this.artyomProperties.speaking;
};
clearGarbageCollection = () => {
// Review this return, because it will always return true
return this.artyomGarbageCollector = [];
};
getGarbageCollection = () => {
return this.artyomGarbageCollector;
};
dontObey = () => {
// Comprobar tipo devuelto -> siempre false?
return this.artyomProperties.obeying = false;
};
obey = () => {
// Check returned type ? alway true
return this.artyomProperties.obeying = true;
};
isObeying = (): boolean => {
return !!this.artyomProperties.obeying;
};
getVersion = () => {
return "1.0.5";
};
on = (indexes: any, smart: boolean): any => {
return {
then: (action: any) => {
var command = {
indexes: indexes,
action: action,
smart: false
};
if (smart) {
command.smart = true;
}
this.addCommands(command);
}
};
};
remoteProcessorService = (action: any): boolean => {
if(this.artyomProperties.helpers) {
this.artyomProperties.helpers.remoteProcessorHandler = action;
}
return true;
};
}
/**
* Artyom.js requires webkitSpeechRecognition and speechSynthesis APIs
*
* @license MIT
* @version 1.0.4
* @copyright 2017 Our Code World All Rights Reserved.
* @author semagarcia (TypeScript version) - https://github.com/semagarcia
* @see https://sdkcarlos.github.io/sites/artyom.html
* @see http://docs.ourcodeworld.com/projects/artyom-js
*/
export class ArtyomBuilder {
private static instance: ArtyomJS;
private constructor() {
let artyom: ArtyomJS;
let artyomVoice = 'Google UK English Male';
let artyom_garbage_collector = [];
let artyomCommands = [];
}
static getInstance(): ArtyomJS {
if (!ArtyomBuilder.instance) {
// Protect the instance to be inherited
ArtyomBuilder.instance = Object.preventExtensions(new ArtyomJsImpl());
}
// Return the instance
return ArtyomBuilder.instance;
}
} | the_stack |
import { buildSchema } from 'graphql';
import { plugin } from '../src/index';
describe('myzod', () => {
test.each([
[
'non-null and defined',
/* GraphQL */ `
input PrimitiveInput {
a: ID!
b: String!
c: Boolean!
d: Int!
e: Float!
}
`,
[
'export function PrimitiveInputSchema(): myzod.Type<PrimitiveInput> {',
'a: myzod.string()',
'b: myzod.string()',
'c: myzod.boolean()',
'd: myzod.number()',
'e: myzod.number()',
],
],
[
'nullish',
/* GraphQL */ `
input PrimitiveInput {
a: ID
b: String
c: Boolean
d: Int
e: Float
z: String! # no defined check
}
`,
[
'export function PrimitiveInputSchema(): myzod.Type<PrimitiveInput> {',
// alphabet order
'a: myzod.string().optional().nullable(),',
'b: myzod.string().optional().nullable(),',
'c: myzod.boolean().optional().nullable(),',
'd: myzod.number().optional().nullable(),',
'e: myzod.number().optional().nullable(),',
],
],
[
'array',
/* GraphQL */ `
input ArrayInput {
a: [String]
b: [String!]
c: [String!]!
d: [[String]]
e: [[String]!]
f: [[String]!]!
}
`,
[
'export function ArrayInputSchema(): myzod.Type<ArrayInput> {',
'a: myzod.array(myzod.string().nullable()).optional().nullable(),',
'b: myzod.array(myzod.string()).optional().nullable(),',
'c: myzod.array(myzod.string()),',
'd: myzod.array(myzod.array(myzod.string().nullable()).optional().nullable()).optional().nullable(),',
'e: myzod.array(myzod.array(myzod.string().nullable())).optional().nullable(),',
'f: myzod.array(myzod.array(myzod.string().nullable()))',
],
],
[
'ref input object',
/* GraphQL */ `
input AInput {
b: BInput!
}
input BInput {
c: CInput!
}
input CInput {
a: AInput!
}
`,
[
'export function AInputSchema(): myzod.Type<AInput> {',
'b: myzod.lazy(() => BInputSchema())',
'export function BInputSchema(): myzod.Type<BInput> {',
'c: myzod.lazy(() => CInputSchema())',
'export function CInputSchema(): myzod.Type<CInput> {',
'a: myzod.lazy(() => AInputSchema())',
],
],
[
'nested input object',
/* GraphQL */ `
input NestedInput {
child: NestedInput
childrens: [NestedInput]
}
`,
[
'export function NestedInputSchema(): myzod.Type<NestedInput> {',
'child: myzod.lazy(() => NestedInputSchema().optional().nullable()),',
'childrens: myzod.array(myzod.lazy(() => NestedInputSchema().nullable())).optional().nullable()',
],
],
[
'enum',
/* GraphQL */ `
enum PageType {
PUBLIC
BASIC_AUTH
}
input PageInput {
pageType: PageType!
}
`,
[
'export const PageTypeSchema = myzod.enum(PageType)',
'export function PageInputSchema(): myzod.Type<PageInput> {',
'pageType: PageTypeSchema',
],
],
[
'camelcase',
/* GraphQL */ `
input HTTPInput {
method: HTTPMethod
url: URL!
}
enum HTTPMethod {
GET
POST
}
scalar URL # unknown scalar, should be any (definedNonNullAnySchema)
`,
[
'export function HttpInputSchema(): myzod.Type<HttpInput> {',
'export const HttpMethodSchema = myzod.enum(HttpMethod)',
'method: HttpMethodSchema',
'url: definedNonNullAnySchema',
],
],
])('%s', async (_, textSchema, wantContains) => {
const schema = buildSchema(textSchema);
const result = await plugin(schema, [], { schema: 'myzod' }, {});
expect(result.prepend).toContain("import * as myzod from 'myzod'");
for (const wantContain of wantContains) {
expect(result.content).toContain(wantContain);
}
});
it('with scalars', async () => {
const schema = buildSchema(/* GraphQL */ `
input Say {
phrase: Text!
times: Count!
}
scalar Count
scalar Text
`);
const result = await plugin(
schema,
[],
{
schema: 'myzod',
scalars: {
Text: 'string',
Count: 'number',
},
},
{}
);
expect(result.content).toContain('phrase: myzod.string()');
expect(result.content).toContain('times: myzod.number()');
});
it('with importFrom', async () => {
const schema = buildSchema(/* GraphQL */ `
input Say {
phrase: String!
}
`);
const result = await plugin(
schema,
[],
{
schema: 'myzod',
importFrom: './types',
},
{}
);
expect(result.prepend).toContain("import { Say } from './types'");
expect(result.content).toContain('phrase: myzod.string()');
});
it('with enumsAsTypes', async () => {
const schema = buildSchema(/* GraphQL */ `
enum PageType {
PUBLIC
BASIC_AUTH
}
`);
const result = await plugin(
schema,
[],
{
schema: 'myzod',
enumsAsTypes: true,
},
{}
);
expect(result.content).toContain("export type PageTypeSchema = myzod.literals('PUBLIC', 'BASIC_AUTH')");
});
it('with notAllowEmptyString', async () => {
const schema = buildSchema(/* GraphQL */ `
input PrimitiveInput {
a: ID!
b: String!
c: Boolean!
d: Int!
e: Float!
}
`);
const result = await plugin(
schema,
[],
{
schema: 'myzod',
notAllowEmptyString: true,
},
{}
);
const wantContains = [
'export function PrimitiveInputSchema(): myzod.Type<PrimitiveInput> {',
'a: myzod.string().min(1),',
'b: myzod.string().min(1),',
'c: myzod.boolean(),',
'd: myzod.number(),',
'e: myzod.number()',
];
for (const wantContain of wantContains) {
expect(result.content).toContain(wantContain);
}
});
it('with scalarSchemas', async () => {
const schema = buildSchema(/* GraphQL */ `
input ScalarsInput {
date: Date!
email: Email
str: String!
}
scalar Date
scalar Email
`);
const result = await plugin(
schema,
[],
{
schema: 'myzod',
scalarSchemas: {
Date: 'myzod.date()',
Email: 'myzod.string()', // generate the basic type. User can later extend it using `withPredicate(fn: (val: string) => boolean), errMsg?: string }`
},
},
{}
);
const wantContains = [
'export function ScalarsInputSchema(): myzod.Type<ScalarsInput> {',
'date: myzod.date(),',
'email: myzod.string()', // TODO: Test implementation
'str: myzod.string()',
];
for (const wantContain of wantContains) {
expect(result.content).toContain(wantContain);
}
});
it('with typesPrefix', async () => {
const schema = buildSchema(/* GraphQL */ `
input Say {
phrase: String!
}
`);
const result = await plugin(
schema,
[],
{
schema: 'myzod',
typesPrefix: 'I',
importFrom: './types',
},
{}
);
expect(result.prepend).toContain("import { ISay } from './types'");
expect(result.content).toContain('export function ISaySchema(): myzod.Type<ISay> {');
});
it('with typesSuffix', async () => {
const schema = buildSchema(/* GraphQL */ `
input Say {
phrase: String!
}
`);
const result = await plugin(
schema,
[],
{
schema: 'myzod',
typesSuffix: 'I',
importFrom: './types',
},
{}
);
expect(result.prepend).toContain("import { SayI } from './types'");
expect(result.content).toContain('export function SayISchema(): myzod.Type<SayI> {');
});
describe('issues #19', () => {
it('string field', async () => {
const schema = buildSchema(/* GraphQL */ `
input UserCreateInput {
profile: String @constraint(minLength: 1, maxLength: 5000)
}
directive @constraint(minLength: Int!, maxLength: Int!) on INPUT_FIELD_DEFINITION
`);
const result = await plugin(
schema,
[],
{
schema: 'myzod',
directives: {
constraint: {
minLength: ['min', '$1', 'Please input more than $1'],
maxLength: ['max', '$1', 'Please input less than $1'],
},
},
},
{}
);
const wantContains = [
'export function UserCreateInputSchema(): myzod.Type<UserCreateInput> {',
'profile: myzod.string().min(1, "Please input more than 1").max(5000, "Please input less than 5000").optional().nullable()',
];
for (const wantContain of wantContains) {
expect(result.content).toContain(wantContain);
}
});
it('not null field', async () => {
const schema = buildSchema(/* GraphQL */ `
input UserCreateInput {
profile: String! @constraint(minLength: 1, maxLength: 5000)
}
directive @constraint(minLength: Int!, maxLength: Int!) on INPUT_FIELD_DEFINITION
`);
const result = await plugin(
schema,
[],
{
schema: 'myzod',
directives: {
constraint: {
minLength: ['min', '$1', 'Please input more than $1'],
maxLength: ['max', '$1', 'Please input less than $1'],
},
},
},
{}
);
const wantContains = [
'export function UserCreateInputSchema(): myzod.Type<UserCreateInput> {',
'profile: myzod.string().min(1, "Please input more than 1").max(5000, "Please input less than 5000")',
];
for (const wantContain of wantContains) {
expect(result.content).toContain(wantContain);
}
});
it('list field', async () => {
const schema = buildSchema(/* GraphQL */ `
input UserCreateInput {
profile: [String] @constraint(minLength: 1, maxLength: 5000)
}
directive @constraint(minLength: Int!, maxLength: Int!) on INPUT_FIELD_DEFINITION
`);
const result = await plugin(
schema,
[],
{
schema: 'myzod',
directives: {
constraint: {
minLength: ['min', '$1', 'Please input more than $1'],
maxLength: ['max', '$1', 'Please input less than $1'],
},
},
},
{}
);
const wantContains = [
'export function UserCreateInputSchema(): myzod.Type<UserCreateInput> {',
'profile: myzod.array(myzod.string().nullable()).min(1, "Please input more than 1").max(5000, "Please input less than 5000").optional().nullable()',
];
for (const wantContain of wantContains) {
expect(result.content).toContain(wantContain);
}
});
});
}); | the_stack |
import {
Address,
Algorithm,
Amount,
ChainId,
PubkeyBundle,
SendTransaction,
SwapAbortTransaction,
SwapClaimTransaction,
SwapOfferTransaction,
TimestampTimeout,
UnsignedTransaction,
} from "@iov/bcp";
import { As } from "type-tagger";
import * as codecImpl from "./generated/codecimpl";
export interface CashConfiguration {
readonly owner: Address;
readonly collectorAddress: Address;
readonly minimalFee: Amount | null;
}
export interface TxFeeConfiguration {
readonly owner: Address;
readonly freeBytes: number | null;
readonly baseFee: Amount | null;
}
export interface MsgFeeConfiguration {
readonly owner: Address;
readonly feeAdmin: Address | null;
}
export interface PreRegistrationConfiguration {
readonly owner: Address;
}
export interface QualityScoreConfiguration {
readonly owner: Address;
readonly c: Fraction;
readonly k: Fraction;
readonly kp: Fraction;
readonly q0: Fraction;
readonly x: Fraction;
readonly xInf: Fraction;
readonly xSup: Fraction;
readonly delta: Fraction;
}
export interface TermDepositStandardRate {
readonly lockinPeriod: number;
readonly rate: Fraction;
}
export interface TermDepositCustomRate {
readonly address: Address;
readonly rate: Fraction;
}
export interface TermDepositConfiguration {
readonly owner: Address;
readonly admin: Address | null;
readonly standardRates: readonly TermDepositStandardRate[];
readonly customRates: readonly TermDepositCustomRate[];
}
/**
* The message part of a bnsd.Tx
*
* @see https://htmlpreview.github.io/?https://github.com/iov-one/weave/blob/v0.24.0/docs/proto/index.html#bnsd.Tx
*/
export declare type BnsdTxMsg = Omit<codecImpl.bnsd.ITx, "fees" | "signatures" | "multisig">;
export interface ChainAddressPair {
readonly chainId: ChainId;
readonly address: Address;
}
export interface BnsAccountByNameQuery {
readonly name: string;
}
export interface BnsAccountsByOwnerQuery {
readonly owner: Address;
}
export interface BnsAccountsByDomainQuery {
readonly domain: string;
}
export declare type BnsAccountsQuery =
| BnsAccountByNameQuery
| BnsAccountsByOwnerQuery
| BnsAccountsByDomainQuery;
export declare function isBnsAccountByNameQuery(query: BnsAccountsQuery): query is BnsAccountByNameQuery;
export declare function isBnsAccountsByOwnerQuery(query: BnsAccountsQuery): query is BnsAccountsByOwnerQuery;
export declare function isBnsAccountsByDomainQuery(
query: BnsAccountsQuery,
): query is BnsAccountsByDomainQuery;
export interface BnsDomainByNameQuery {
readonly name: string;
}
export interface BnsDomainsByAdminQuery {
readonly admin: Address;
}
export declare type BnsDomainsQuery = BnsDomainByNameQuery | BnsDomainsByAdminQuery;
export declare function isBnsDomainByNameQuery(query: BnsDomainsQuery): query is BnsDomainByNameQuery;
export declare function isBnsDomainsByAdminQuery(query: BnsDomainsQuery): query is BnsDomainsByAdminQuery;
export interface AccountConfiguration {
readonly owner: Address;
readonly validDomain: string;
readonly validName: string;
readonly validBlockchainId: string;
readonly validBlockchainAddress: string;
readonly domainRenew: number;
readonly domainGracePeriod: number;
}
export interface AccountMsgFee {
readonly msgPath: string;
readonly fee: Amount;
}
export interface AccountNft {
readonly domain: string;
readonly name?: string;
readonly owner: Address;
readonly validUntil: number;
readonly targets: readonly ChainAddressPair[];
readonly certificates: readonly Uint8Array[];
}
export interface Domain {
readonly domain: string;
readonly admin: Address;
readonly broker: Address;
readonly validUntil: number;
readonly hasSuperuser: boolean;
readonly msgFees: readonly AccountMsgFee[];
readonly accountRenew: number;
}
export interface ValidatorProperties {
readonly power: number;
}
export interface Validator extends ValidatorProperties {
readonly pubkey: PubkeyBundle;
}
/**
* An unordered map from validator pubkey address to remaining properies
*
* The string key is in the form `ed25519_<pubkey_hex>`
*/
export interface Validators {
readonly [index: string]: ValidatorProperties;
}
/** Like Elector from the backend but without the address field */
export interface ElectorProperties {
/** The voting weight of this elector. Max value is 65535 (2^16-1). */
readonly weight: number;
}
export interface Elector extends ElectorProperties {
readonly address: Address;
}
/** An unordered map from elector address to remaining properies */
export interface Electors {
readonly [index: string]: ElectorProperties;
}
export interface Electorate {
readonly id: number;
readonly version: number;
readonly admin: Address;
readonly title: string;
readonly electors: Electors;
/** Sum of all electors' weights */
readonly totalWeight: number;
}
export interface Fraction {
readonly numerator: number;
readonly denominator: number;
}
export interface ElectionRule {
readonly id: number;
readonly version: number;
readonly admin: Address;
/**
* The eligible voters in this rule.
*
* This is an unversioned ID (see `id` field in weave's VersionedIDRef), meaning the
* electorate can change over time without changing this ID. When a proposal with this
* rule is created, the latest version of the electorate will be used.
*/
readonly electorateId: number;
readonly title: string;
/** Voting period in seconds */
readonly votingPeriod: number;
readonly threshold: Fraction;
readonly quorum: Fraction | null;
}
export interface VersionedId {
readonly id: number;
readonly version: number;
}
export declare enum ProposalExecutorResult {
NotRun = 0,
Succeeded = 1,
Failed = 2,
}
export declare enum ProposalResult {
Undefined = 0,
Accepted = 1,
Rejected = 2,
}
export declare enum ProposalStatus {
Submitted = 0,
Closed = 1,
Withdrawn = 2,
}
/**
* Raw values are used for the JSON representation (e.g. in the wallet to browser extension communication)
* and must remain unchanged across different semver compatible versions of IOV Core.
*/
export declare enum VoteOption {
Yes = "yes",
No = "no",
Abstain = "abstain",
}
export declare enum ActionKind {
CreateTextResolution = "gov_create_text_resolution",
ExecuteProposalBatch = "execute_proposal_batch",
ReleaseEscrow = "escrow_release",
Send = "cash_send",
SetMsgFee = "msgfee_set_msg_fee",
SetValidators = "validators_apply_diff",
UpdateElectionRule = "gov_update_election_rule",
UpdateElectorate = "gov_update_electorate",
ExecuteMigration = "datamigration_execute_migration",
UpgradeSchema = "migration_upgrade_schema",
SetMsgFeeConfiguration = "msgfee_update_configuration_msg",
SetPreRegistrationConfiguration = "preregistration_update_configuration_msg",
SetQualityScoreConfiguration = "qualityscore_update_configuration_msg",
SetTermDepositConfiguration = "termdeposit_update_configuration_msg",
SetTxFeeConfiguration = "txfee_update_configuration_msg",
SetCashConfiguration = "cash_update_configuration_msg",
SetAccountConfiguration = "account_update_configuration_msg",
RegisterDomain = "account_register_domain_msg",
RenewDomain = "account_renew_domain_msg",
SetAccountMsgFees = "account_replace_account_msg_fees_msg",
SetAccountTargets = "account_replace_account_targets_msg",
AddAccountCertificate = "account_add_account_certificate_msg",
DeleteAccountCertificate = "account_delete_account_certificate_msg",
}
export interface TallyResult {
readonly totalYes: number;
readonly totalNo: number;
readonly totalAbstain: number;
readonly totalElectorateWeight: number;
}
export interface CreateTextResolutionAction {
readonly kind: ActionKind.CreateTextResolution;
readonly resolution: string;
}
export declare function isCreateTextResolutionAction(
action: ProposalAction,
): action is CreateTextResolutionAction;
export interface ExecuteProposalBatchAction {
readonly kind: ActionKind.ExecuteProposalBatch;
readonly messages: readonly ProposalAction[];
}
export declare function isExecuteProposalBatchAction(
action: ProposalAction,
): action is ExecuteProposalBatchAction;
export interface ReleaseEscrowAction {
readonly kind: ActionKind.ReleaseEscrow;
readonly escrowId: number;
readonly amount: Amount;
}
export declare function isReleaseEscrowAction(action: ProposalAction): action is ReleaseEscrowAction;
export interface SendAction {
readonly kind: ActionKind.Send;
readonly sender: Address;
readonly recipient: Address;
readonly amount: Amount;
readonly memo?: string;
}
export declare function isSendAction(action: ProposalAction): action is SendAction;
export interface SetMsgFeeAction {
readonly kind: ActionKind.SetMsgFee;
readonly msgPath: string;
readonly fee: Amount;
}
export declare function isSetMsgFeeAction(action: ProposalAction): action is SetMsgFeeAction;
export interface SetValidatorsAction {
readonly kind: ActionKind.SetValidators;
readonly validatorUpdates: Validators;
}
export declare function isSetValidatorsAction(action: ProposalAction): action is SetValidatorsAction;
export interface UpdateElectionRuleAction {
readonly kind: ActionKind.UpdateElectionRule;
readonly electionRuleId: number;
readonly threshold?: Fraction;
readonly quorum?: Fraction | null;
readonly votingPeriod: number;
}
export declare function isUpdateElectionRuleAction(
action: ProposalAction,
): action is UpdateElectionRuleAction;
export interface UpdateElectorateAction {
readonly kind: ActionKind.UpdateElectorate;
readonly electorateId: number;
readonly diffElectors: Electors;
}
export declare function isUpdateElectorateAction(action: ProposalAction): action is UpdateElectorateAction;
export interface ExecuteMigrationAction {
readonly kind: ActionKind.ExecuteMigration;
readonly id: string;
}
export declare function isExecuteMigrationAction(action: ProposalAction): action is ExecuteMigrationAction;
export interface UpgradeSchemaAction {
readonly kind: ActionKind.UpgradeSchema;
readonly pkg: string;
readonly toVersion: number;
}
export declare function isUpgradeSchemaAction(action: ProposalAction): action is UpgradeSchemaAction;
export interface SetMsgFeeConfigurationAction {
readonly kind: ActionKind.SetMsgFeeConfiguration;
readonly patch: MsgFeeConfiguration;
}
export declare function isSetMsgFeeConfigurationAction(
action: ProposalAction,
): action is SetMsgFeeConfigurationAction;
export interface SetPreRegistrationConfigurationAction {
readonly kind: ActionKind.SetPreRegistrationConfiguration;
readonly patch: PreRegistrationConfiguration;
}
export declare function isSetPreRegistrationConfigurationAction(
action: ProposalAction,
): action is SetPreRegistrationConfigurationAction;
export interface SetQualityScoreConfigurationAction {
readonly kind: ActionKind.SetQualityScoreConfiguration;
readonly patch: QualityScoreConfiguration;
}
export declare function isSetQualityScoreConfigurationAction(
action: ProposalAction,
): action is SetQualityScoreConfigurationAction;
export interface SetTermDepositConfigurationAction {
readonly kind: ActionKind.SetTermDepositConfiguration;
readonly patch: TermDepositConfiguration;
}
export declare function isSetTermDepositConfigurationAction(
action: ProposalAction,
): action is SetTermDepositConfigurationAction;
export interface SetTxFeeConfigurationAction {
readonly kind: ActionKind.SetTxFeeConfiguration;
readonly patch: TxFeeConfiguration;
}
export declare function isSetTxFeeConfigurationAction(
action: ProposalAction,
): action is SetTxFeeConfigurationAction;
export interface SetCashConfigurationAction {
readonly kind: ActionKind.SetCashConfiguration;
readonly patch: CashConfiguration;
}
export declare function isSetCashConfigurationAction(
action: ProposalAction,
): action is SetCashConfigurationAction;
export interface SetAccountConfigurationAction {
readonly kind: ActionKind.SetAccountConfiguration;
readonly patch: AccountConfiguration;
}
export declare function isSetAccountConfigurationAction(
action: ProposalAction,
): action is SetAccountConfigurationAction;
export interface RegisterDomainAction {
readonly kind: ActionKind.RegisterDomain;
readonly domain: string;
readonly admin: Address;
readonly broker?: Address;
readonly hasSuperuser: boolean;
readonly msgFees: readonly AccountMsgFee[];
readonly accountRenew: number;
}
export declare function isRegisterDomainAction(action: ProposalAction): action is RegisterDomainAction;
export interface RenewDomainAction {
readonly kind: ActionKind.RenewDomain;
readonly domain: string;
}
export declare function isRenewDomainAction(action: ProposalAction): action is RenewDomainAction;
export interface SetAccountMsgFeesAction {
readonly kind: ActionKind.SetAccountMsgFees;
readonly domain: string;
readonly newMsgFees: readonly AccountMsgFee[];
}
export declare function isSetAccountMsgFeesAction(action: ProposalAction): action is SetAccountMsgFeesAction;
export interface SetAccountTargetsAction {
readonly kind: ActionKind.SetAccountTargets;
readonly domain: string;
readonly name: string;
readonly newTargets: readonly ChainAddressPair[];
}
export declare function isSetAccountTargetsAction(action: ProposalAction): action is SetAccountTargetsAction;
export interface AddAccountCertificateAction {
readonly kind: ActionKind.AddAccountCertificate;
readonly domain: string;
readonly name: string;
readonly certificate: Uint8Array;
}
export declare function isAddAccountCertificateAction(
action: ProposalAction,
): action is AddAccountCertificateAction;
export interface DeleteAccountCertificateAction {
readonly kind: ActionKind.DeleteAccountCertificate;
readonly domain: string;
readonly name: string;
readonly certificateHash: Uint8Array;
}
export declare function isDeleteAccountCertificateAction(
action: ProposalAction,
): action is DeleteAccountCertificateAction;
/** The action to be executed when the proposal is accepted */
export declare type ProposalAction =
| CreateTextResolutionAction
| ExecuteProposalBatchAction
| ReleaseEscrowAction
| SendAction
| SetMsgFeeAction
| SetValidatorsAction
| UpdateElectorateAction
| UpdateElectionRuleAction
| ExecuteMigrationAction
| UpgradeSchemaAction
| SetMsgFeeConfigurationAction
| SetPreRegistrationConfigurationAction
| SetQualityScoreConfigurationAction
| SetTermDepositConfigurationAction
| SetTxFeeConfigurationAction
| SetCashConfigurationAction
| SetAccountConfigurationAction
| RegisterDomainAction
| RenewDomainAction
| SetAccountMsgFeesAction
| SetAccountTargetsAction
| AddAccountCertificateAction
| DeleteAccountCertificateAction;
export interface Proposal {
readonly id: number;
readonly title: string;
/**
* The transaction to be executed when the proposal is accepted
*
* This is one of the actions from
* https://htmlpreview.github.io/?https://github.com/iov-one/weave/blob/v0.16.0/docs/proto/index.html#app.ProposalOptions
*/
readonly action: ProposalAction;
readonly description: string;
readonly electionRule: VersionedId;
readonly electorate: VersionedId;
/** Time when the voting on this proposal starts (Unix timestamp) */
readonly votingStartTime: number;
/** Time when the voting on this proposal starts (Unix timestamp) */
readonly votingEndTime: number;
/** Time of the block where the proposal was added to the chain (Unix timestamp) */
readonly submissionTime: number;
/** The author of the proposal must be included in the list of transaction signers. */
readonly author: Address;
readonly state: TallyResult;
readonly status: ProposalStatus;
readonly result: ProposalResult;
readonly executorResult: ProposalExecutorResult;
}
export interface Vote {
readonly proposalId: number;
readonly elector: Elector;
readonly selection: VoteOption;
}
export interface BnsUsernameNft {
readonly id: string;
readonly owner: Address;
readonly targets: readonly ChainAddressPair[];
}
export interface BnsUsernamesByUsernameQuery {
readonly username: string;
}
export interface BnsUsernamesByOwnerQuery {
readonly owner: Address;
}
export declare type BnsUsernamesQuery = BnsUsernamesByUsernameQuery | BnsUsernamesByOwnerQuery;
export declare function isBnsUsernamesByUsernameQuery(
query: BnsUsernamesQuery,
): query is BnsUsernamesByUsernameQuery;
export declare function isBnsUsernamesByOwnerQuery(
query: BnsUsernamesQuery,
): query is BnsUsernamesByOwnerQuery;
export declare type PrivkeyBytes = Uint8Array & As<"privkey-bytes">;
export interface PrivkeyBundle {
readonly algo: Algorithm;
readonly data: PrivkeyBytes;
}
export interface Result {
readonly key: Uint8Array;
readonly value: Uint8Array;
}
export interface Keyed {
readonly _id: Uint8Array;
}
export interface Decoder<T extends {}> {
readonly decode: (data: Uint8Array) => T;
}
export interface RegisterUsernameTx extends UnsignedTransaction {
readonly kind: "bns/register_username";
readonly username: string;
readonly targets: readonly ChainAddressPair[];
}
export declare function isRegisterUsernameTx(tx: UnsignedTransaction): tx is RegisterUsernameTx;
export interface UpdateTargetsOfUsernameTx extends UnsignedTransaction {
readonly kind: "bns/update_targets_of_username";
/** the username to be updated, must exist on chain */
readonly username: string;
readonly targets: readonly ChainAddressPair[];
}
export declare function isUpdateTargetsOfUsernameTx(tx: UnsignedTransaction): tx is UpdateTargetsOfUsernameTx;
export interface TransferUsernameTx extends UnsignedTransaction {
readonly kind: "bns/transfer_username";
/** the username to be transferred, must exist on chain */
readonly username: string;
readonly newOwner: Address;
}
export declare function isTransferUsernameTx(tx: UnsignedTransaction): tx is TransferUsernameTx;
export interface UpdateAccountConfigurationTx extends UnsignedTransaction {
readonly kind: "bns/update_account_configuration";
readonly configuration: AccountConfiguration;
}
export declare function isUpdateAccountConfigurationTx(
tx: UnsignedTransaction,
): tx is UpdateAccountConfigurationTx;
export interface RegisterDomainTx extends UnsignedTransaction {
readonly kind: "bns/register_domain";
readonly domain: string;
readonly admin: Address;
readonly hasSuperuser: boolean;
readonly broker?: Address;
readonly msgFees: readonly AccountMsgFee[];
readonly accountRenew: number;
}
export declare function isRegisterDomainTx(tx: UnsignedTransaction): tx is RegisterDomainTx;
export interface TransferDomainTx extends UnsignedTransaction {
readonly kind: "bns/transfer_domain";
readonly domain: string;
readonly newAdmin: Address;
}
export declare function isTransferDomainTx(tx: UnsignedTransaction): tx is TransferDomainTx;
export interface RenewDomainTx extends UnsignedTransaction {
readonly kind: "bns/renew_domain";
readonly domain: string;
}
export declare function isRenewDomainTx(tx: UnsignedTransaction): tx is RenewDomainTx;
export interface DeleteDomainTx extends UnsignedTransaction {
readonly kind: "bns/delete_domain";
readonly domain: string;
}
export declare function isDeleteDomainTx(tx: UnsignedTransaction): tx is DeleteDomainTx;
export interface RegisterAccountTx extends UnsignedTransaction {
readonly kind: "bns/register_account";
readonly domain: string;
readonly name: string;
readonly owner: Address;
readonly targets: readonly ChainAddressPair[];
readonly broker?: Address;
}
export declare function isRegisterAccountTx(tx: UnsignedTransaction): tx is RegisterAccountTx;
export interface TransferAccountTx extends UnsignedTransaction {
readonly kind: "bns/transfer_account";
readonly domain: string;
readonly name: string;
readonly newOwner: Address;
}
export declare function isTransferAccountTx(tx: UnsignedTransaction): tx is TransferAccountTx;
export interface ReplaceAccountTargetsTx extends UnsignedTransaction {
readonly kind: "bns/replace_account_targets";
readonly domain: string;
readonly name: string | undefined;
readonly newTargets: readonly ChainAddressPair[];
}
export declare function isReplaceAccountTargetsTx(tx: UnsignedTransaction): tx is ReplaceAccountTargetsTx;
export interface DeleteAccountTx extends UnsignedTransaction {
readonly kind: "bns/delete_account";
readonly domain: string;
readonly name: string;
}
export declare function isDeleteAccountTx(tx: UnsignedTransaction): tx is DeleteAccountTx;
export interface DeleteAllAccountsTx extends UnsignedTransaction {
readonly kind: "bns/delete_all_accounts";
readonly domain: string;
}
export declare function isDeleteAllAccountsTx(tx: UnsignedTransaction): tx is DeleteAllAccountsTx;
export interface RenewAccountTx extends UnsignedTransaction {
readonly kind: "bns/renew_account";
readonly domain: string;
readonly name: string;
}
export declare function isRenewAccountTx(tx: UnsignedTransaction): tx is RenewAccountTx;
export interface AddAccountCertificateTx extends UnsignedTransaction {
readonly kind: "bns/add_account_certificate";
readonly domain: string;
readonly name: string;
readonly certificate: Uint8Array;
}
export declare function isAddAccountCertificateTx(tx: UnsignedTransaction): tx is AddAccountCertificateTx;
export interface ReplaceAccountMsgFeesTx extends UnsignedTransaction {
readonly kind: "bns/replace_account_msg_fees";
readonly domain: string;
readonly newMsgFees: readonly AccountMsgFee[];
}
export declare function isReplaceAccountMsgFeesTx(tx: UnsignedTransaction): tx is ReplaceAccountMsgFeesTx;
export interface DeleteAccountCertificateTx extends UnsignedTransaction {
readonly kind: "bns/delete_account_certificate";
readonly domain: string;
readonly name: string;
readonly certificateHash: Uint8Array;
}
export declare function isDeleteAccountCertificateTx(
tx: UnsignedTransaction,
): tx is DeleteAccountCertificateTx;
export interface Participant {
readonly address: Address;
readonly weight: number;
}
export interface CreateMultisignatureTx extends UnsignedTransaction {
readonly kind: "bns/create_multisignature_contract";
readonly participants: readonly Participant[];
readonly activationThreshold: number;
readonly adminThreshold: number;
}
export declare function isCreateMultisignatureTx(tx: UnsignedTransaction): tx is CreateMultisignatureTx;
export interface UpdateMultisignatureTx extends UnsignedTransaction {
readonly kind: "bns/update_multisignature_contract";
readonly contractId: number;
readonly participants: readonly Participant[];
readonly activationThreshold: number;
readonly adminThreshold: number;
}
export declare function isUpdateMultisignatureTx(tx: UnsignedTransaction): tx is UpdateMultisignatureTx;
export interface CreateEscrowTx extends UnsignedTransaction {
readonly kind: "bns/create_escrow";
readonly sender: Address;
readonly arbiter: Address;
readonly recipient: Address;
readonly amounts: readonly Amount[];
readonly timeout: TimestampTimeout;
readonly memo?: string;
}
export declare function isCreateEscrowTx(tx: UnsignedTransaction): tx is CreateEscrowTx;
export interface ReleaseEscrowTx extends UnsignedTransaction {
readonly kind: "bns/release_escrow";
readonly escrowId: number;
readonly amounts: readonly Amount[];
}
export declare function isReleaseEscrowTx(tx: UnsignedTransaction): tx is ReleaseEscrowTx;
export interface ReturnEscrowTx extends UnsignedTransaction {
readonly kind: "bns/return_escrow";
readonly escrowId: number;
}
export declare function isReturnEscrowTx(tx: UnsignedTransaction): tx is ReturnEscrowTx;
export interface UpdateEscrowPartiesTx extends UnsignedTransaction {
readonly kind: "bns/update_escrow_parties";
readonly escrowId: number;
readonly sender?: Address;
readonly arbiter?: Address;
readonly recipient?: Address;
}
export declare function isUpdateEscrowPartiesTx(tx: UnsignedTransaction): tx is UpdateEscrowPartiesTx;
export interface CreateProposalTx extends UnsignedTransaction {
readonly kind: "bns/create_proposal";
readonly title: string;
/**
* The transaction to be executed when the proposal is accepted
*
* This is one of the actions from
* https://htmlpreview.github.io/?https://github.com/iov-one/weave/blob/v0.16.0/docs/proto/index.html#app.ProposalOptions
*/
readonly action: ProposalAction;
readonly description: string;
readonly electionRuleId: number;
/** Unix timestamp when the proposal starts */
readonly startTime: number;
/** The author of the proposal must be included in the list of transaction signers. */
readonly author: Address;
}
export declare function isCreateProposalTx(transaction: UnsignedTransaction): transaction is CreateProposalTx;
export interface VoteTx extends UnsignedTransaction {
readonly kind: "bns/vote";
readonly proposalId: number;
readonly selection: VoteOption;
/**
* Voter should be set explicitly to avoid falling back to the first signer,
* which is potentially insecure. When encoding a new transaction, this field
* is required. Not all transaction from blockchain history have a voter set.
*/
readonly voter: Address | null;
}
export declare function isVoteTx(transaction: UnsignedTransaction): transaction is VoteTx;
export declare type BnsTx =
| SendTransaction
| SwapOfferTransaction
| SwapClaimTransaction
| SwapAbortTransaction
| RegisterUsernameTx
| UpdateTargetsOfUsernameTx
| TransferUsernameTx
| UpdateAccountConfigurationTx
| RegisterDomainTx
| TransferDomainTx
| RenewDomainTx
| DeleteDomainTx
| RegisterAccountTx
| TransferAccountTx
| ReplaceAccountTargetsTx
| DeleteAccountTx
| DeleteAllAccountsTx
| RenewAccountTx
| AddAccountCertificateTx
| ReplaceAccountMsgFeesTx
| DeleteAccountCertificateTx
| CreateMultisignatureTx
| UpdateMultisignatureTx
| CreateEscrowTx
| ReleaseEscrowTx
| ReturnEscrowTx
| UpdateEscrowPartiesTx
| CreateProposalTx
| VoteTx;
export declare function isBnsTx(transaction: UnsignedTransaction): transaction is BnsTx;
export interface MultisignatureTx extends UnsignedTransaction {
readonly multisig: readonly number[];
}
export declare function isMultisignatureTx(transaction: UnsignedTransaction): transaction is MultisignatureTx; | the_stack |
import Graph from '../graph/Graph';
import { IObservable, ISubscriberFunction } from '../graph/IObservable';
import Observable from '../graph/Observable';
import Computed from '../graph/Computed';
import ObservableArray from '../graph/ObservableArray';
import ObservableHash from '../graph/ObservableHash';
import { IVirtualNode, IVirtualNodeProps } from '../dom/IVirtualNode';
import VirtualNode from '../dom/VirtualNode';
import Fragment from '../dom/Fragment';
import ComponentNode from '../dom/ComponentNode';
import { Component } from '../dom/Component';
import { CascadeError } from '../util/CascadeError';
export default class Cascade {
/**
* Dispose all Observables in a Graph
* @param obj
*/
static disposeAll<T>(obj: T) {
var graph: Graph<T> = obj['_graph'];
for (var name in obj) {
if (obj.hasOwnProperty(name)) {
// Only dispose non-observable properties here.
if (!graph || !graph.observables[name]) {
Cascade.disposeAll(obj[name] as any);
}
}
}
if (graph) {
for (var index in graph.observables) {
if (graph.observables.hasOwnProperty(index)) {
var value = graph.observables[index].value;
Cascade.disposeAll(value);
graph.observables[index].dispose();
}
}
}
}
/**
* Attach a Graph to an object
* @param obj the object on which to attach a Graph
*/
static attachGraph<T>(obj: T) {
if (!(obj as any)._graph) {
Object.defineProperty(obj, '_graph', {
configurable: true,
writable: true,
enumerable: false,
value: new Graph(obj),
});
}
return (obj as any)._graph as Graph<T>;
}
/**
*
* @param obj the object on which to define a property
* @param property the name of the property
* @param observable the IObservable to store the property value
*/
static createProperty<T, U extends keyof T>(
obj: T,
property: U,
observable: IObservable<T[U]>,
) {
var graph = Cascade.attachGraph(obj);
if (graph.observables[property as string]) {
// TODO: move or delete subscriptions?
observable.subscribers = graph.observables[property as string].subscribers;
}
graph.observables[property as string] = observable;
}
/**
*
* @param obj the object on which to define a property
* @param property the name of the property
* @param observable the IObservable to store the property value
* @param readOnly the Boolean specifying if this property is read only
*/
static attachObservable<T, U extends keyof T>(
obj: T,
property: U,
observable: IObservable<T[U]>,
readOnly: boolean = false,
) {
Cascade.createProperty(obj, property, observable);
Object.defineProperty(obj, property, {
enumerable: true,
configurable: true,
get: function () {
return observable.getValue();
},
set: readOnly
? undefined
: function (value: T[U] | Array<T[U]>) {
(observable as any).setValue(value);
},
});
}
/**
*
* @param obj
* @param property
* @param value
*/
static createObservable<T, U extends keyof T>(obj: T, property: U, value?: T[U]) {
Cascade.attachObservable(obj, property, new Observable(value));
}
/**
*
* @param obj
* @param property
* @param definition
* @param defer
* @param setter
*/
static createComputed<T, U extends keyof T>(
obj: T,
property: U,
definition: (n?: T[U]) => T[U],
defer?: boolean,
setter?: (n: T[U]) => any,
) {
Cascade.attachObservable(
obj,
property,
new Computed(definition, defer, undefined, setter),
true,
);
}
/**
*
* @param obj
* @param property
* @param value
*/
static createObservableArray<T, U extends keyof T>(obj: T, property: U, value?: T[U]) {
Cascade.attachObservable<T, U>(
obj,
property,
new ObservableArray<any>(value as any) as any,
);
}
/**
*
* @param obj
* @param property
* @param value
*/
static createObservableHash<T, U extends keyof T>(obj: T, property: U, value?: T[U]) {
Cascade.attachObservable<T, U>(
obj,
property,
new ObservableHash<T[U]>(value as any) as any,
);
}
/**
*
* @param obj
* @param property
* @param alwaysNotify
*/
static setAlwaysNotify<T, U extends keyof T>(obj: T, property: U, alwaysNotify: boolean) {
let graph = this.attachGraph(obj);
graph.setAlwaysNotify(property, alwaysNotify);
}
/**
*
* @param obj
* @param property
* @param subscriberFunction
*/
static subscribe<T, U extends keyof T>(
obj: T,
property: U,
subscriberFunction: ISubscriberFunction<T[U]>,
createDisposer: boolean = false,
) {
let graph = this.attachGraph(obj);
graph.subscribe(property, subscriberFunction);
return createDisposer
? function () {
graph.unsubscribe(property, subscriberFunction);
}
: undefined;
}
/**
*
* @param obj
* @param property
* @param subscriberFunction
*/
static subscribeOnly<T, U extends keyof T>(
obj: T,
property: U,
subscriberFunction: ISubscriberFunction<T[U]>,
createDisposer: boolean = false,
) {
let graph = this.attachGraph(obj);
graph.subscribeOnly(property, subscriberFunction);
return createDisposer
? function () {
graph.unsubscribe(property, subscriberFunction);
}
: undefined;
}
static unsubscribe<T, U extends keyof T>(
obj: T,
property: U,
subscriberFunction: ISubscriberFunction<T[U]>,
) {
var graph: Graph<T> = obj['_graph'];
if (graph) {
graph.unsubscribe(property, subscriberFunction);
}
}
static waitToEqual<T, U extends keyof T>(
obj: T,
property: U,
testValue: T[U],
timeout?: number,
) {
let graph = this.attachGraph(obj);
return new Promise<T[U]>((resolve, reject) => {
let resolved = false;
let subscriberFunction = (value: T[U]) => {
if (value === testValue) {
if (timerId) {
window.clearTimeout(timerId);
}
if (!resolved) {
resolved = true;
window.setTimeout(() => {
graph.unsubscribe(property, subscriberFunction);
});
resolve(value);
}
}
};
if (timeout) {
var timerId = window.setTimeout(() => {
graph.unsubscribe(property, subscriberFunction);
reject(new Error(CascadeError.TimeoutElapsed));
}, timeout);
}
graph.subscribeOnly(property, subscriberFunction);
});
}
/**
*
* @param obj
* @param property
*/
static peek<T, U extends keyof T>(obj: T, property: U) {
return obj['_graph'] ? (obj['_graph'] as Graph<T>).peek<U>(property) : undefined;
}
/**
*
* @param obj
* @param property
*/
static peekDirty<T, U extends keyof T>(obj: T, property: U) {
return obj['_graph'] ? (obj['_graph'] as Graph<T>).peekDirty<U>(property) : undefined;
}
/**
*
* @param obj
* @param property
*/
static track<T, U extends keyof T>(obj: T, property: U) {
let graph = this.attachGraph(obj);
let observable = graph.observables[property as string] as IObservable<T[U]>;
if (observable) {
return observable.track();
} else {
throw new Error(CascadeError.NoObservable + property);
}
}
/**
*
* @param obj
*/
static trackAll<T>(obj: T) {
let graph = this.attachGraph(obj);
return graph.trackAll();
}
/**
*
* @param obj
* @param property
*/
static update<T, U extends keyof T>(obj: T, property: U) {
let graph = this.attachGraph(obj);
let observable = graph.observables[property as string] as Computed<T[U]>;
if (observable && observable.update) {
return observable.update();
} else {
throw new Error(CascadeError.NoObservable + property);
}
}
static set<T, U extends keyof T>(obj: T, property: U, value: T[U]) {
let graph = this.attachGraph(obj);
let observable = graph.observables[property as string] as IObservable<T[U]>;
if (observable) {
return observable.setValue(value);
} else {
throw new Error(CascadeError.NoObservable + property);
}
}
/**
*
* @param obj
* @param property
*/
static run<T, U extends keyof T>(obj: T, property: U) {
let graph = this.attachGraph(obj);
let observable = graph.observables[property as string] as IObservable<T[U]>;
if (observable) {
if ((observable as Computed<T[U]>).runOnly) {
return (observable as Computed<T[U]>).runOnly();
} else {
return observable.peek();
}
} else {
throw new Error(CascadeError.NoObservable + property);
}
}
/**
*
* @param obj
* @param property
*/
static getObservable<T, U extends keyof T>(obj: T, property: U) {
let graph = this.attachGraph(obj);
return graph.observables[property as string] as IObservable<T[U]>;
}
/**
*
* @param obj
* @param property
*/
static getSubscribers<T, U extends keyof T>(obj: T, property: U) {
let graph = this.attachGraph(obj);
return graph.getSubscribers<U>(property);
}
/**
*
* @param obj
* @param property
*/
static getReferences<T, U extends keyof T>(obj: T, property: U) {
let graph = this.attachGraph(obj);
return graph.getReferences(property);
}
/**
*
* @param callback
* @param thisArg
*/
static wrapContext(callback: () => any, thisArg?: any) {
Observable.pushContext();
if (thisArg) {
callback.call(thisArg);
} else {
callback();
}
return Observable.popContext();
}
static createElement<T extends IVirtualNodeProps>(
type: string | (new (props: T, children: Array<any>) => Component<T>),
props: T,
...children: Array<any>
): IVirtualNode<T> {
children = VirtualNode.fixChildrenArrays(children);
if (typeof type === 'string') {
return new VirtualNode(type, props, children);
} else {
return new ComponentNode(type, props, children);
}
}
static render(node: HTMLElement | string, virtualNode: IVirtualNode<any>) {
var fixedNode = typeof node === 'string' ? document.getElementById(node) : node;
if (!fixedNode) {
throw new Error(CascadeError.NoRootNode);
}
var renderedComponent = virtualNode.toNode();
while (fixedNode.firstChild) {
fixedNode.removeChild(fixedNode.firstChild);
}
if (renderedComponent instanceof Node) {
fixedNode.appendChild(renderedComponent);
} else {
throw new Error(CascadeError.InvalidRootRender);
}
return renderedComponent;
}
static Fragment = Fragment;
static reflectAvailable: boolean =
typeof Reflect === 'object' && typeof Reflect.getMetadata === 'function';
// TODO: Remove once Safari fixes href
static xlinkDeprecated: boolean = (function () {
if (typeof SVGElement === 'undefined') {
return true;
} else {
let use = document.createElementNS('http://www.w3.org/2000/svg', 'use');
use.setAttribute('href', 'abcd');
return use.href?.baseVal === 'abcd';
}
})();
} | the_stack |
import {
assertArrayIncludes,
assertEquals,
assertObjectMatch,
assertStrictEquals,
assertThrows,
} from "std/testing/asserts.ts";
import {
DflowData,
DflowGraph,
DflowHost,
DflowNode,
DflowOutput,
DflowPinType,
DflowSerializedNode,
DflowValue,
} from "./engine.ts";
const num = 1;
const bool = true;
const str = "string";
const arr = [num, bool, str];
const obj = { foo: num, bar: str };
class EmptyNode extends DflowNode {
static kind = "Empty";
run() {}
}
class NumNode extends EmptyNode {
static kind = "Num";
}
class SumNode extends DflowNode {
static kind = "Sum";
run() {
let sum = 0;
for (const input of this.inputs) {
const inputData = input.data;
if (typeof inputData === "number") {
sum += inputData;
}
}
const output = this.output(0);
output.data = sum;
}
}
function sleep(seconds = 1) {
return new Promise<void>((resolve) => {
setTimeout(() => {
resolve();
}, seconds * 1000);
});
}
class SleepNode extends DflowNode {
static kind = "Sleep";
static isAsync = true;
constructor(arg: DflowSerializedNode, host: DflowHost) {
super(arg, host, { isAsync: SleepNode.isAsync });
}
async run() {
console.log("sleep node start");
await sleep();
console.log("sleep node end");
}
}
const nodesCatalog1 = {
[EmptyNode.kind]: EmptyNode,
};
const nodesCatalog2 = {
[NumNode.kind]: NumNode,
[SumNode.kind]: SumNode,
[SleepNode.kind]: SleepNode,
};
function sample01() {
const nodeId1 = "n1";
const nodeId2 = "n2";
const pinId1 = "p1";
const pinId2 = "p2";
const edgeId1 = "e2";
const dflow = new DflowHost(nodesCatalog1);
dflow.newNode({
id: nodeId1,
name: "Hello world",
kind: EmptyNode.kind,
outputs: [{ id: pinId1 }],
});
dflow.newNode({
id: nodeId2,
kind: EmptyNode.kind,
inputs: [{ id: pinId2 }],
});
dflow.newEdge({
id: edgeId1,
source: [nodeId1, pinId1],
target: [nodeId2, pinId2],
});
return { dflow, nodeId1, nodeId2, pinId1, pinId2, edgeId1 };
}
// DflowData
// ////////////////////////////////////////////////////////////////////////////
Deno.test("DflowData.isArray()", () => {
assertEquals(DflowData.isArray(arr), true);
assertEquals(DflowData.isArray(bool), false);
assertEquals(DflowData.isArray(num), false);
assertEquals(DflowData.isArray(null), false);
assertEquals(DflowData.isArray(obj), false);
assertEquals(DflowData.isArray(str), false);
assertEquals(DflowData.isArray(undefined), false);
});
Deno.test("DflowData.isBoolean()", () => {
assertEquals(DflowData.isBoolean(arr), false);
assertEquals(DflowData.isBoolean(bool), true);
assertEquals(DflowData.isBoolean(num), false);
assertEquals(DflowData.isBoolean(null), false);
assertEquals(DflowData.isBoolean(obj), false);
assertEquals(DflowData.isBoolean(str), false);
assertEquals(DflowData.isBoolean(undefined), false);
});
Deno.test("DflowData.isNull()", () => {
assertEquals(DflowData.isNull(arr), false);
assertEquals(DflowData.isNull(bool), false);
assertEquals(DflowData.isNull(num), false);
assertEquals(DflowData.isNull(null), true);
assertEquals(DflowData.isNull(obj), false);
assertEquals(DflowData.isNull(str), false);
assertEquals(DflowData.isNull(undefined), false);
});
Deno.test("DflowData.isNumber()", () => {
assertEquals(DflowData.isNumber(arr), false);
assertEquals(DflowData.isNumber(bool), false);
assertEquals(DflowData.isNumber(num), true);
assertEquals(DflowData.isNumber(null), false);
assertEquals(DflowData.isNumber(obj), false);
assertEquals(DflowData.isNumber(str), false);
assertEquals(DflowData.isNumber(undefined), false);
});
Deno.test("DflowData.isObject()", () => {
assertEquals(DflowData.isObject(arr), false);
assertEquals(DflowData.isObject(bool), false);
assertEquals(DflowData.isObject(num), false);
assertEquals(DflowData.isObject(null), false);
assertEquals(DflowData.isObject(obj), true);
assertEquals(DflowData.isObject(str), false);
assertEquals(DflowData.isObject(undefined), false);
});
Deno.test("DflowData.isString()", () => {
assertEquals(DflowData.isString(arr), false);
assertEquals(DflowData.isString(bool), false);
assertEquals(DflowData.isString(num), false);
assertEquals(DflowData.isString(null), false);
assertEquals(DflowData.isString(obj), false);
assertEquals(DflowData.isString(str), true);
assertEquals(DflowData.isString(undefined), false);
});
Deno.test("DflowData.isUndefined()", () => {
assertEquals(DflowData.isUndefined(arr), false);
assertEquals(DflowData.isUndefined(bool), false);
assertEquals(DflowData.isUndefined(num), false);
assertEquals(DflowData.isUndefined(null), false);
assertEquals(DflowData.isUndefined(obj), false);
assertEquals(DflowData.isUndefined(str), false);
assertEquals(DflowData.isUndefined(undefined), true);
});
Deno.test("DflowData.validate()", () => {
assertEquals(DflowData.validate(arr, ["array"]), true);
assertEquals(DflowData.validate(bool, ["boolean"]), true);
assertEquals(DflowData.validate(num, ["number"]), true);
assertEquals(DflowData.validate(null, ["null"]), true);
assertEquals(DflowData.validate(obj, ["object"]), true);
assertEquals(DflowData.validate(str, ["string"]), true);
assertEquals(DflowData.validate(arr, []), true);
assertEquals(DflowData.validate(bool, []), true);
assertEquals(DflowData.validate(num, []), true);
assertEquals(DflowData.validate(null, []), true);
assertEquals(DflowData.validate(obj, []), true);
assertEquals(DflowData.validate(str, []), true);
assertEquals(DflowData.validate(undefined, []), true);
assertEquals(DflowData.validate(arr, ["boolean"]), false);
assertEquals(DflowData.validate(arr, ["number"]), false);
assertEquals(DflowData.validate(arr, ["null"]), false);
assertEquals(DflowData.validate(arr, ["object"]), false);
assertEquals(DflowData.validate(arr, ["string"]), false);
assertEquals(DflowData.validate(bool, ["array"]), false);
assertEquals(DflowData.validate(bool, ["number"]), false);
assertEquals(DflowData.validate(bool, ["null"]), false);
assertEquals(DflowData.validate(bool, ["object"]), false);
assertEquals(DflowData.validate(bool, ["string"]), false);
assertEquals(DflowData.validate(null, ["array"]), false);
assertEquals(DflowData.validate(null, ["boolean"]), false);
assertEquals(DflowData.validate(null, ["number"]), false);
assertEquals(DflowData.validate(null, ["object"]), false);
assertEquals(DflowData.validate(null, ["string"]), false);
assertEquals(DflowData.validate(num, ["array"]), false);
assertEquals(DflowData.validate(num, ["boolean"]), false);
assertEquals(DflowData.validate(num, ["null"]), false);
assertEquals(DflowData.validate(num, ["object"]), false);
assertEquals(DflowData.validate(num, ["string"]), false);
assertEquals(DflowData.validate(obj, ["array"]), false);
assertEquals(DflowData.validate(obj, ["boolean"]), false);
assertEquals(DflowData.validate(obj, ["number"]), false);
assertEquals(DflowData.validate(obj, ["null"]), false);
assertEquals(DflowData.validate(obj, ["string"]), false);
assertEquals(DflowData.validate(str, ["array"]), false);
assertEquals(DflowData.validate(str, ["boolean"]), false);
assertEquals(DflowData.validate(str, ["number"]), false);
assertEquals(DflowData.validate(str, ["null"]), false);
assertEquals(DflowData.validate(str, ["object"]), false);
assertEquals(DflowData.validate(undefined, ["array"]), false);
assertEquals(DflowData.validate(undefined, ["boolean"]), false);
assertEquals(DflowData.validate(undefined, ["number"]), false);
assertEquals(DflowData.validate(undefined, ["null"]), false);
assertEquals(DflowData.validate(undefined, ["object"]), false);
assertEquals(DflowData.validate(undefined, ["string"]), false);
// No particular order her.
assertEquals(DflowData.validate(arr, ["boolean", "array"]), true);
assertEquals(DflowData.validate(bool, ["null", "number", "boolean"]), true);
assertEquals(
DflowData.validate(num, ["null", "number", "object", "string"]),
true,
);
assertEquals(DflowData.validate(null, ["object", "null"]), true);
assertEquals(DflowData.validate(obj, ["array", "object"]), true);
assertEquals(DflowData.validate(str, ["null", "string"]), true);
assertEquals(DflowData.validate(arr, ["boolean", "string"]), false);
assertEquals(DflowData.validate(bool, ["null", "number", "array"]), false);
assertEquals(DflowData.validate(num, ["null", "object", "string"]), false);
assertEquals(DflowData.validate(null, ["object", "string"]), false);
assertEquals(DflowData.validate(obj, ["array", "null"]), false);
assertEquals(DflowData.validate(str, ["null", "array"]), false);
});
// DflowGraph
// ////////////////////////////////////////////////////////////////////////////
Deno.test("DflowGraph.isDflowGraph", () => {
[{ id: "g1", nodes: [], edges: [] }].forEach((graph) => {
assertEquals(DflowGraph.isDflowGraph(graph), true);
});
});
Deno.test("DflowGraph.ancestorsOfNodeId", () => {
assertArrayIncludes(
DflowGraph.ancestorsOfNodeId("n", [
{ sourceId: "n1", targetId: "n" },
]),
["n1"],
);
assertArrayIncludes(
DflowGraph.ancestorsOfNodeId("n", [
{ sourceId: "n1", targetId: "n2" },
{ sourceId: "n2", targetId: "n" },
]),
["n1", "n2"],
);
});
// DflowHost
// ////////////////////////////////////////////////////////////////////////////
Deno.test("new DflowHost has an empty graph", () => {
const dflow = new DflowHost();
assertObjectMatch(JSON.parse(dflow.toJSON()), { nodes: [], edges: [] });
});
Deno.test("DflowHost#clearGraph()", () => {
const { dflow } = sample01();
dflow.clearGraph();
assertEquals(dflow.numNodes, 0);
assertEquals(dflow.numEdges, 0);
});
Deno.test("DflowHost#runStatusIsSuccess", () => {
const dflow = new DflowHost();
assertEquals(dflow.runStatusIsSuccess, true);
dflow.newNode({ id: "n1", kind: "EmptyNode" });
dflow.run();
assertEquals(dflow.runStatusIsSuccess, true);
});
Deno.test("DflowHost#run()", async () => {
const dflow = new DflowHost(nodesCatalog2);
// Num#out=2 -> Sum#in1 |
// |-> Sum#out=4
// Num#out=2 -> Sum#in2 |
dflow.newNode({
id: "num",
kind: NumNode.kind,
outputs: [{ id: "out", data: 2 }],
});
const sumNode = dflow.newNode({
id: "sum",
kind: SumNode.kind,
inputs: [{ id: "in1" }, { id: "in2" }],
outputs: [{ id: "out" }],
});
dflow.newEdge({
id: "e1",
source: ["num", "out"],
target: ["sum", "in1"],
});
dflow.newEdge({
id: "e2",
source: ["num", "out"],
target: ["sum", "in2"],
});
// Add also an async node.
dflow.newNode({ id: "sleep", kind: SleepNode.kind });
await dflow.run();
const sum = sumNode.output(0);
assertEquals(sum.data, 4);
});
Deno.test("DflowHost#newNode()", () => {
const nodeId1 = "n1";
const dflow = new DflowHost(nodesCatalog1);
dflow.newNode({ id: nodeId1, kind: EmptyNode.kind });
const node1 = dflow.getNodeById(nodeId1);
assertEquals(nodeId1, node1.id);
assertEquals(EmptyNode.kind, node1.kind);
});
Deno.test("DflowHost#newEdge()", () => {
const { dflow, edgeId1 } = sample01();
const edge1 = dflow.getEdgeById(edgeId1);
assertEquals(edgeId1, edge1.id);
});
Deno.test("DflowHost#deleteNode()", () => {
const { dflow, nodeId1, edgeId1 } = sample01();
dflow.deleteNode(nodeId1);
assertThrows(() => {
dflow.getNodeById(nodeId1);
});
assertThrows(() => {
dflow.getEdgeById(edgeId1);
});
});
Deno.test("DflowHost#deleteEdge()", () => {
const { dflow, edgeId1 } = sample01();
dflow.deleteEdge(edgeId1);
assertThrows(() => {
dflow.getEdgeById(edgeId1);
});
});
Deno.test("DflowHost#newInput()", () => {
const nodeId1 = "n1";
const inputId1 = "i1";
const dflow = new DflowHost();
dflow.newNode({ id: nodeId1, kind: "EmptyNode" });
const input1 = dflow.newInput(nodeId1, { id: inputId1 });
assertEquals(inputId1, input1.id);
});
Deno.test("DflowHost#newOutput()", () => {
const nodeId1 = "n1";
const outputId1 = "i1";
const dflow = new DflowHost();
dflow.newNode({ id: nodeId1, kind: "EmptyNode" });
const output1 = dflow.newOutput(nodeId1, { id: outputId1 });
assertEquals(outputId1, output1.id);
});
// DflowOutput
// ////////////////////////////////////////////////////////////////////////////
function testOutputSetData(data: DflowValue, types?: DflowPinType[]) {
const output = new DflowOutput({ id: "test", types });
output.data = data;
assertStrictEquals(data, output.data);
}
function testOutputSetDataThrows(data: DflowValue, types: DflowPinType[]) {
assertThrows(
() => {
const output = new DflowOutput({ id: "test", types });
output.data = data;
},
Error,
`could not set data pinTypes=${JSON.stringify(types)}`,
);
}
Deno.test("DflowOutput#clear()", () => {
const output = new DflowOutput({ id: "test" });
const data = 1;
output.data = data;
assertStrictEquals(data, output.data);
output.clear();
assertStrictEquals(undefined, output.data);
});
Deno.test("DflowOutput#set data", () => {
const pin = new DflowOutput({ id: "test" });
assertEquals(pin.id, "test");
assertEquals(pin.kind, "output");
assertEquals(typeof pin.data, "undefined");
testOutputSetData(str);
testOutputSetData(num);
testOutputSetData(bool);
testOutputSetData(null);
testOutputSetData(obj);
testOutputSetData(arr);
testOutputSetData(str, ["string"]);
testOutputSetDataThrows(num, ["string"]);
testOutputSetDataThrows(bool, ["string"]);
testOutputSetDataThrows(null, ["string"]);
testOutputSetDataThrows(obj, ["string"]);
testOutputSetDataThrows(arr, ["string"]);
testOutputSetDataThrows(str, ["number"]);
testOutputSetData(num, ["number"]);
testOutputSetDataThrows(bool, ["number"]);
testOutputSetDataThrows(null, ["number"]);
testOutputSetDataThrows(obj, ["number"]);
testOutputSetDataThrows(arr, ["number"]);
testOutputSetDataThrows(str, ["boolean"]);
testOutputSetDataThrows(num, ["boolean"]);
testOutputSetData(bool, ["boolean"]);
testOutputSetDataThrows(null, ["boolean"]);
testOutputSetDataThrows(obj, ["boolean"]);
testOutputSetDataThrows(arr, ["boolean"]);
testOutputSetDataThrows(str, ["null"]);
testOutputSetDataThrows(num, ["null"]);
testOutputSetDataThrows(bool, ["null"]);
testOutputSetData(null, ["null"]);
testOutputSetDataThrows(obj, ["null"]);
testOutputSetDataThrows(arr, ["null"]);
testOutputSetDataThrows(str, ["object"]);
testOutputSetDataThrows(num, ["object"]);
testOutputSetDataThrows(bool, ["object"]);
testOutputSetDataThrows(null, ["object"]);
testOutputSetData(obj, ["object"]);
testOutputSetDataThrows(arr, ["object"]);
testOutputSetDataThrows(str, ["array"]);
testOutputSetDataThrows(num, ["array"]);
testOutputSetDataThrows(bool, ["array"]);
testOutputSetDataThrows(null, ["array"]);
testOutputSetDataThrows(obj, ["array"]);
testOutputSetData(arr, ["array"]);
testOutputSetData(str, ["string", "number"]);
testOutputSetData(num, ["string", "number"]);
testOutputSetDataThrows(bool, ["string", "number"]);
testOutputSetDataThrows(null, ["string", "number"]);
testOutputSetDataThrows(obj, ["string", "number"]);
testOutputSetDataThrows(arr, ["string", "number"]);
testOutputSetData(str, ["string", "boolean"]);
testOutputSetDataThrows(num, ["string", "boolean"]);
testOutputSetData(bool, ["string", "boolean"]);
testOutputSetDataThrows(null, ["string", "boolean"]);
testOutputSetDataThrows(obj, ["string", "boolean"]);
testOutputSetDataThrows(arr, ["string", "boolean"]);
testOutputSetData(str, ["string", "null"]);
testOutputSetDataThrows(num, ["string", "null"]);
testOutputSetDataThrows(bool, ["string", "null"]);
testOutputSetData(null, ["string", "null"]);
testOutputSetDataThrows(obj, ["string", "null"]);
testOutputSetDataThrows(arr, ["string", "null"]);
testOutputSetData(str, ["string", "object"]);
testOutputSetDataThrows(num, ["string", "object"]);
testOutputSetDataThrows(bool, ["string", "object"]);
testOutputSetDataThrows(null, ["string", "object"]);
testOutputSetData(obj, ["string", "object"]);
testOutputSetDataThrows(arr, ["string", "object"]);
testOutputSetData(str, ["string", "array"]);
testOutputSetDataThrows(num, ["string", "array"]);
testOutputSetDataThrows(bool, ["string", "array"]);
testOutputSetDataThrows(null, ["string", "array"]);
testOutputSetDataThrows(obj, ["string", "array"]);
testOutputSetData(arr, ["string", "array"]);
testOutputSetDataThrows(str, ["number", "boolean"]);
testOutputSetData(num, ["number", "boolean"]);
testOutputSetData(bool, ["number", "boolean"]);
testOutputSetDataThrows(null, ["number", "boolean"]);
testOutputSetDataThrows(obj, ["number", "boolean"]);
testOutputSetDataThrows(arr, ["number", "boolean"]);
testOutputSetDataThrows(str, ["number", "null"]);
testOutputSetData(num, ["number", "null"]);
testOutputSetDataThrows(bool, ["number", "null"]);
testOutputSetData(null, ["number", "null"]);
testOutputSetDataThrows(obj, ["number", "null"]);
testOutputSetDataThrows(arr, ["number", "null"]);
testOutputSetDataThrows(str, ["number", "object"]);
testOutputSetData(num, ["number", "object"]);
testOutputSetDataThrows(bool, ["number", "object"]);
testOutputSetDataThrows(null, ["number", "object"]);
testOutputSetData(obj, ["number", "object"]);
testOutputSetDataThrows(arr, ["number", "object"]);
testOutputSetDataThrows(str, ["number", "array"]);
testOutputSetData(num, ["number", "array"]);
testOutputSetDataThrows(bool, ["number", "array"]);
testOutputSetDataThrows(null, ["number", "array"]);
testOutputSetDataThrows(obj, ["number", "array"]);
testOutputSetData(arr, ["number", "array"]);
testOutputSetDataThrows(str, ["boolean", "null"]);
testOutputSetDataThrows(num, ["boolean", "null"]);
testOutputSetData(bool, ["boolean", "null"]);
testOutputSetData(null, ["boolean", "null"]);
testOutputSetDataThrows(obj, ["boolean", "null"]);
testOutputSetDataThrows(arr, ["boolean", "null"]);
testOutputSetDataThrows(str, ["boolean", "object"]);
testOutputSetDataThrows(num, ["boolean", "object"]);
testOutputSetData(bool, ["boolean", "object"]);
testOutputSetDataThrows(null, ["boolean", "object"]);
testOutputSetData(obj, ["boolean", "object"]);
testOutputSetDataThrows(arr, ["boolean", "object"]);
testOutputSetDataThrows(str, ["boolean", "array"]);
testOutputSetDataThrows(num, ["boolean", "array"]);
testOutputSetData(bool, ["boolean", "array"]);
testOutputSetDataThrows(null, ["boolean", "array"]);
testOutputSetDataThrows(obj, ["boolean", "array"]);
testOutputSetData(arr, ["boolean", "array"]);
testOutputSetDataThrows(str, ["null", "object"]);
testOutputSetDataThrows(num, ["null", "object"]);
testOutputSetDataThrows(bool, ["null", "object"]);
testOutputSetData(null, ["null", "object"]);
testOutputSetData(obj, ["null", "object"]);
testOutputSetDataThrows(arr, ["null", "object"]);
testOutputSetDataThrows(str, ["null", "array"]);
testOutputSetDataThrows(num, ["null", "array"]);
testOutputSetDataThrows(bool, ["null", "array"]);
testOutputSetData(null, ["null", "array"]);
testOutputSetDataThrows(obj, ["null", "array"]);
testOutputSetData(arr, ["null", "array"]);
testOutputSetDataThrows(str, ["object", "array"]);
testOutputSetDataThrows(num, ["object", "array"]);
testOutputSetDataThrows(bool, ["object", "array"]);
testOutputSetDataThrows(null, ["object", "array"]);
testOutputSetData(obj, ["object", "array"]);
testOutputSetData(arr, ["object", "array"]);
}); | the_stack |
import { DisposableStore } from 'vs/base/common/lifecycle';
import { URI } from 'vs/base/common/uri';
import { ExtHostContext, IExtHostEditorTabsShape, IExtHostContext, MainContext, IEditorTabDto } from 'vs/workbench/api/common/extHost.protocol';
import { extHostNamedCustomer } from 'vs/workbench/api/common/extHostCustomers';
import { EditorResourceAccessor, IUntypedEditorInput, SideBySideEditor } from 'vs/workbench/common/editor';
import { DiffEditorInput } from 'vs/workbench/common/editor/diffEditorInput';
import { EditorInput } from 'vs/workbench/common/editor/editorInput';
import { SideBySideEditorInput } from 'vs/workbench/common/editor/sideBySideEditorInput';
import { columnToEditorGroup, EditorGroupColumn, editorGroupToColumn } from 'vs/workbench/services/editor/common/editorGroupColumn';
import { GroupChangeKind, GroupDirection, IEditorGroup, IEditorGroupsService } from 'vs/workbench/services/editor/common/editorGroupsService';
import { IEditorsChangeEvent, IEditorService } from 'vs/workbench/services/editor/common/editorService';
@extHostNamedCustomer(MainContext.MainThreadEditorTabs)
export class MainThreadEditorTabs {
private readonly _dispoables = new DisposableStore();
private readonly _proxy: IExtHostEditorTabsShape;
private readonly _tabModel: Map<number, IEditorTabDto[]> = new Map<number, IEditorTabDto[]>();
private _currentlyActiveTab: { groupId: number, tab: IEditorTabDto } | undefined = undefined;
constructor(
extHostContext: IExtHostContext,
@IEditorGroupsService private readonly _editorGroupsService: IEditorGroupsService,
@IEditorService editorService: IEditorService
) {
this._proxy = extHostContext.getProxy(ExtHostContext.ExtHostEditorTabs);
// Queue all events that arrive on the same event loop and then send them as a batch
this._dispoables.add(editorService.onDidEditorsChange((events) => this._updateTabsModel(events)));
this._editorGroupsService.whenReady.then(() => this._createTabsModel());
}
dispose(): void {
this._dispoables.dispose();
}
/**
* Creates a tab object with the correct properties
* @param editor The editor input represented by the tab
* @param group The group the tab is in
* @returns A tab object
*/
private _buildTabObject(editor: EditorInput, group: IEditorGroup): IEditorTabDto {
// Even though the id isn't a diff / sideBySide on the main side we need to let the ext host know what type of editor it is
const editorId = editor instanceof DiffEditorInput ? 'diff' : editor instanceof SideBySideEditorInput ? 'sideBySide' : editor.editorId;
const tab: IEditorTabDto = {
viewColumn: editorGroupToColumn(this._editorGroupsService, group),
label: editor.getName(),
resource: editor instanceof SideBySideEditorInput ? EditorResourceAccessor.getCanonicalUri(editor, { supportSideBySide: SideBySideEditor.PRIMARY }) : EditorResourceAccessor.getCanonicalUri(editor),
editorId,
additionalResourcesAndViewIds: [],
isActive: (this._editorGroupsService.activeGroup === group) && group.isActive(editor)
};
tab.additionalResourcesAndViewIds.push({ resource: tab.resource, viewId: tab.editorId });
if (editor instanceof SideBySideEditorInput) {
tab.additionalResourcesAndViewIds.push({ resource: EditorResourceAccessor.getCanonicalUri(editor, { supportSideBySide: SideBySideEditor.SECONDARY }), viewId: editor.primary.editorId ?? editor.editorId });
}
return tab;
}
private _tabToUntypedEditorInput(tab: IEditorTabDto): IUntypedEditorInput {
if (tab.editorId !== 'diff' && tab.editorId !== 'sideBySide') {
return { resource: URI.revive(tab.resource), options: { override: tab.editorId } };
} else if (tab.editorId === 'sideBySide') {
return {
primary: { resource: URI.revive(tab.resource), options: { override: tab.editorId } },
secondary: { resource: URI.revive(tab.additionalResourcesAndViewIds[1].resource), options: { override: tab.additionalResourcesAndViewIds[1].viewId } }
};
} else {
return {
modified: { resource: URI.revive(tab.resource), options: { override: tab.editorId } },
original: { resource: URI.revive(tab.additionalResourcesAndViewIds[1].resource), options: { override: tab.additionalResourcesAndViewIds[1].viewId } }
};
}
}
/**
* Builds the model from scratch based on the current state of the editor service.
*/
private _createTabsModel(): void {
this._tabModel.clear();
let tabs: IEditorTabDto[] = [];
for (const group of this._editorGroupsService.groups) {
for (const editor of group.editors) {
if (editor.isDisposed()) {
continue;
}
const tab = this._buildTabObject(editor, group);
if (tab.isActive) {
this._currentlyActiveTab = { groupId: group.id, tab };
}
tabs.push(tab);
}
this._tabModel.set(group.id, tabs);
}
this._proxy.$acceptEditorTabs(tabs);
}
private _onDidTabOpen(event: IEditorsChangeEvent): void {
if (event.kind !== GroupChangeKind.EDITOR_OPEN || !event.editor || event.editorIndex === undefined) {
return;
}
if (!this._tabModel.has(event.groupId)) {
this._tabModel.set(event.groupId, []);
}
const editor = event.editor;
const tab = this._buildTabObject(editor, this._editorGroupsService.getGroup(event.groupId) ?? this._editorGroupsService.activeGroup);
this._tabModel.get(event.groupId)?.splice(event.editorIndex, 0, tab);
// Update the currently active tab which may or may not be the opened one
if (tab.isActive) {
if (this._currentlyActiveTab) {
this._currentlyActiveTab.tab.isActive = (this._editorGroupsService.activeGroup.id === this._currentlyActiveTab.groupId) && this._editorGroupsService.activeGroup.isActive(this._tabToUntypedEditorInput(this._currentlyActiveTab.tab));
}
this._currentlyActiveTab = { groupId: event.groupId, tab };
}
}
private _onDidTabClose(event: IEditorsChangeEvent): void {
if (event.kind !== GroupChangeKind.EDITOR_CLOSE || event.editorIndex === undefined) {
return;
}
this._tabModel.get(event.groupId)?.splice(event.editorIndex, 1);
this._findAndUpdateActiveTab();
// Remove any empty groups
if (this._tabModel.get(event.groupId)?.length === 0) {
this._tabModel.delete(event.groupId);
}
}
private _onDidTabMove(event: IEditorsChangeEvent): void {
if (event.kind !== GroupChangeKind.EDITOR_MOVE || event.editorIndex === undefined || event.oldEditorIndex === undefined) {
return;
}
const movedTab = this._tabModel.get(event.groupId)?.splice(event.oldEditorIndex, 1);
if (movedTab === undefined) {
return;
}
this._tabModel.get(event.groupId)?.splice(event.editorIndex, 0, movedTab[0]);
movedTab[0].isActive = (this._editorGroupsService.activeGroup.id === event.groupId) && this._editorGroupsService.activeGroup.isActive(this._tabToUntypedEditorInput(movedTab[0]));
// Update the currently active tab
if (movedTab[0].isActive) {
if (this._currentlyActiveTab) {
this._currentlyActiveTab.tab.isActive = (this._editorGroupsService.activeGroup.id === this._currentlyActiveTab.groupId) && this._editorGroupsService.activeGroup.isActive(this._tabToUntypedEditorInput(this._currentlyActiveTab.tab));
}
this._currentlyActiveTab = { groupId: event.groupId, tab: movedTab[0] };
}
}
private _onDidGroupActivate(event: IEditorsChangeEvent): void {
if (event.kind !== GroupChangeKind.GROUP_INDEX && event.kind !== GroupChangeKind.EDITOR_ACTIVE) {
return;
}
this._findAndUpdateActiveTab();
}
/**
* Updates the currently active tab so that `this._currentlyActiveTab` is up to date.
*/
private _findAndUpdateActiveTab() {
// Go to the active group and update the active tab
const activeGroupId = this._editorGroupsService.activeGroup.id;
this._tabModel.get(activeGroupId)?.forEach(t => {
if (t.resource) {
t.isActive = this._editorGroupsService.activeGroup.isActive(this._tabToUntypedEditorInput(t));
}
if (t.isActive) {
if (this._currentlyActiveTab) {
this._currentlyActiveTab.tab.isActive = (this._editorGroupsService.activeGroup.id === this._currentlyActiveTab.groupId) && this._editorGroupsService.activeGroup.isActive(this._tabToUntypedEditorInput(this._currentlyActiveTab.tab));
}
this._currentlyActiveTab = { groupId: activeGroupId, tab: t };
return;
}
}, this);
}
// TODOD @lramos15 Remove this after done finishing the tab model code
// private _eventArrayToString(events: IEditorsChangeEvent[]): void {
// let eventString = '[';
// events.forEach(event => {
// switch (event.kind) {
// case GroupChangeKind.GROUP_INDEX: eventString += 'GROUP_INDEX, '; break;
// case GroupChangeKind.EDITOR_ACTIVE: eventString += 'EDITOR_ACTIVE, '; break;
// case GroupChangeKind.EDITOR_PIN: eventString += 'EDITOR_PIN, '; break;
// case GroupChangeKind.EDITOR_OPEN: eventString += 'EDITOR_OPEN, '; break;
// case GroupChangeKind.EDITOR_CLOSE: eventString += 'EDITOR_CLOSE, '; break;
// case GroupChangeKind.EDITOR_MOVE: eventString += 'EDITOR_MOVE, '; break;
// case GroupChangeKind.EDITOR_LABEL: eventString += 'EDITOR_LABEL, '; break;
// case GroupChangeKind.GROUP_ACTIVE: eventString += 'GROUP_ACTIVE, '; break;
// case GroupChangeKind.GROUP_LOCKED: eventString += 'GROUP_LOCKED, '; break;
// default: eventString += 'UNKNOWN, '; break;
// }
// });
// eventString += ']';
// console.log(eventString);
// }
/**
* The main handler for the tab events
* @param events The list of events to process
*/
private _updateTabsModel(events: IEditorsChangeEvent[]): void {
events.forEach(event => {
// Call the correct function for the change type
switch (event.kind) {
case GroupChangeKind.EDITOR_OPEN:
this._onDidTabOpen(event);
break;
case GroupChangeKind.EDITOR_CLOSE:
this._onDidTabClose(event);
break;
case GroupChangeKind.EDITOR_ACTIVE:
case GroupChangeKind.GROUP_ACTIVE:
if (this._editorGroupsService.activeGroup.id !== event.groupId) {
return;
}
this._onDidGroupActivate(event);
break;
case GroupChangeKind.GROUP_INDEX:
this._createTabsModel();
// Here we stop the loop as no need to process other events
break;
case GroupChangeKind.EDITOR_MOVE:
this._onDidTabMove(event);
break;
default:
break;
}
});
// Flatten the map into a singular array to send the ext host
let allTabs: IEditorTabDto[] = [];
this._tabModel.forEach((tabs) => allTabs = allTabs.concat(tabs));
this._proxy.$acceptEditorTabs(allTabs);
}
//#region Messages received from Ext Host
$moveTab(tab: IEditorTabDto, index: number, viewColumn: EditorGroupColumn): void {
const groupId = columnToEditorGroup(this._editorGroupsService, viewColumn);
let targetGroup: IEditorGroup | undefined;
const sourceGroup = this._editorGroupsService.getGroup(columnToEditorGroup(this._editorGroupsService, tab.viewColumn));
if (!sourceGroup) {
return;
}
// If group index is out of bounds then we make a new one that's to the right of the last group
if (this._tabModel.get(groupId) === undefined) {
targetGroup = this._editorGroupsService.addGroup(this._editorGroupsService.groups[this._editorGroupsService.groups.length - 1], GroupDirection.RIGHT, undefined);
} else {
targetGroup = this._editorGroupsService.getGroup(groupId);
}
if (!targetGroup) {
return;
}
// Similar logic to if index is out of bounds we place it at the end
if (index < 0 || index > targetGroup.editors.length) {
index = targetGroup.editors.length;
}
// Find the correct EditorInput using the tab info
const editorInput = sourceGroup.editors.find(editor => editor.matches(this._tabToUntypedEditorInput(tab)));
if (!editorInput) {
return;
}
// Move the editor to the target group
sourceGroup.moveEditor(editorInput, targetGroup, { index, preserveFocus: true });
}
async $closeTab(tab: IEditorTabDto): Promise<void> {
const group = this._editorGroupsService.getGroup(columnToEditorGroup(this._editorGroupsService, tab.viewColumn));
if (!group) {
return;
}
const editor = group.editors.find(editor => editor.matches(this._tabToUntypedEditorInput(tab)));
if (!editor) {
return;
}
return group.closeEditor(editor);
}
//#endregion
} | the_stack |
import { DOCUMENT } from '@angular/common';
import { Inject, Injectable } from '@angular/core';
import sdk from '@stackblitz/sdk';
import { getParameters } from 'codesandbox/lib/api/define';
import { deepCopy } from '@delon/util/other';
import type { NzSafeAny } from 'ng-zorro-antd/core/types';
import pkg from '../../../../package.json';
import { AppService } from '../app.service';
import angularJSON from './files/angular.json';
import appModuleTS from './files/app.module';
import delonABCModuleTS from './files/delon-abc.module';
import delonChartModuleTS from './files/delon-chart.module';
import environmentTS from './files/environment';
import globalConfigTS from './files/global-config.module';
import mainTS from './files/main';
import mainCliTS from './files/main-cli';
import nzZorroAntdModuleTS from './files/ng-zorro-antd.module';
import packageJSON from './files/package.json';
import polyfillTS from './files/polyfill';
import readme from './files/readme-cli';
import startupServiceTS from './files/startup.service';
import tsconfigJSON from './files/tsconfig.json';
@Injectable({ providedIn: 'root' })
export class CodeService {
private document: Document;
// private get dependencies(): { [key: string]: string } {
// const res: { [key: string]: string } = {};
// [
// '@angular/animations',
// '@angular/compiler',
// '@angular/common',
// '@angular/core',
// '@angular/forms',
// '@angular/platform-browser',
// '@angular/platform-browser-dynamic',
// '@angular/router',
// '@ant-design/icons-angular',
// 'core-js@3.8.3',
// 'rxjs',
// 'tslib',
// 'zone.js',
// 'date-fns',
// `@angular/cdk@^${MAX_MAIN_VERSION}.x`,
// 'ng-zorro-antd',
// '@delon/theme',
// '@delon/abc',
// '@delon/chart',
// '@delon/acl',
// '@delon/auth',
// '@delon/cache',
// '@delon/mock',
// '@delon/form',
// '@delon/util',
// 'ajv',
// 'ajv-formats'
// ].forEach(key => {
// const includeVersion = key.lastIndexOf(`@`);
// if (includeVersion > 1) {
// res[key.substr(0, includeVersion)] = key.substr(includeVersion + 1);
// return;
// }
// const version = key.startsWith('@delon')
// ? `~${pkg.version}`
// : (
// (pkg.dependencies || pkg.devDependencies) as {
// [key: string]: string;
// }
// )[key];
// res[key] = version || '*';
// });
// return res;
// }
private get themePath(): string {
return `node_modules/@delon/theme/${this.appSrv.theme}.css`;
}
private genPackage({
dependencies = [],
devDependencies = [],
includeCli = false
}: {
dependencies: string[];
devDependencies: string[];
includeCli: boolean;
}): Record<string, string | Record<string, string>> {
const ngCoreVersion = pkg.dependencies['@angular/core'];
const res = packageJSON as Record<string, NzSafeAny>;
[
`@angular/cdk`,
'ng-zorro-antd',
'date-fns',
'@delon/theme',
'@delon/abc',
'@delon/chart',
'@delon/acl',
'@delon/auth',
'@delon/cache',
'@delon/mock',
'@delon/form',
'@delon/util',
'ajv',
'ajv-formats',
'@ant-design/icons-angular',
...dependencies
].forEach(k => (res.dependencies[k] = '*'));
if (includeCli) {
devDependencies = [
...devDependencies,
'ng-alain',
'ng-alain-plugin-theme',
'@angular/cli',
'@angular/compiler-cli',
'@angular-devkit/build-angular'
];
}
devDependencies.forEach(k => (res.devDependencies[k] = '*'));
const fullLibs: Record<string, string> = { ...pkg.dependencies, ...pkg.devDependencies };
['dependencies', 'devDependencies'].forEach(type => {
Object.keys(res[type]).forEach(key => {
res[type][key] = key.startsWith('@delon') ? `~${pkg.version}` : fullLibs[key] || '*';
});
});
// fix @angular/cdk
res.dependencies['@angular/core'] = ngCoreVersion;
res.dependencies['core-js'] = `~3.8.3`;
if (!includeCli) res;
return res;
}
constructor(private appSrv: AppService, @Inject(DOCUMENT) document: NzSafeAny) {
this.document = document;
}
private get genStartupService(): string {
return startupServiceTS({ ajvVersion: pkg.dependencies.ajv.substr(1) });
}
private get genMock(): { [key: string]: string } {
return {
'_mock/user.ts': require('!!raw-loader!../../../../_mock/user.ts').default,
'_mock/index.ts': `export * from './user';`
};
}
private parseCode(code: string): { selector: string; componentName: string; html: string } {
let selector = '';
let componentName = '';
const selectorRe = /selector:[ ]?(['|"|`])([^'"`]+)/g.exec(code);
if (selectorRe) {
selector = selectorRe[2];
}
const componentNameRe = /export class ([^ {]+)/g.exec(code);
if (componentNameRe) {
componentName = componentNameRe[1];
}
return {
selector,
componentName,
html: [
`<base href="/">`,
`<${selector}>loading</${selector}>`,
`<div id="VERSION" style="position: fixed; bottom: 8px; right: 8px; z-index: 8888;"></div>`
].join('\n')
};
}
openOnStackBlitz(appComponentCode: string): void {
const res = this.parseCode(appComponentCode);
const json = deepCopy(angularJSON);
json.projects.demo.architect.build.options.styles.splice(0, 0, this.themePath);
const packageJson = this.genPackage({ dependencies: [], devDependencies: [], includeCli: false });
sdk.openProject(
{
title: 'NG-ALAIN',
description: 'NG-ZORRO admin panel front-end framework',
tags: ['ng-alain', '@delon', 'NG-ZORRO', 'ng-zorro-antd', 'Ant Design', 'Angular', 'ng'],
dependencies: {
...(packageJson.dependencies as Record<string, string>),
...(packageJson.devDependencies as Record<string, string>)
},
files: {
'angular.json': `${JSON.stringify(json, null, 2)}`,
'tsconfig.json': `${JSON.stringify(tsconfigJSON, null, 2)}`,
'package.json': `${JSON.stringify(packageJson, null, 2)}`,
'src/environments/environment.ts': environmentTS,
'src/index.html': res.html,
'src/main.ts': mainTS,
'src/polyfills.ts': polyfillTS,
'src/app/app.component.ts': appComponentCode,
'src/app/app.module.ts': appModuleTS(res.componentName),
'src/app/global-config.module.ts': globalConfigTS,
'src/app/ng-zorro-antd.module.ts': nzZorroAntdModuleTS,
'src/app/delon-abc.module.ts': delonABCModuleTS,
'src/app/delon-chart.module.ts': delonChartModuleTS,
'src/app/startup.service.ts': this.genStartupService,
'src/styles.css': ``,
...this.genMock
},
template: 'angular-cli'
},
{
openFile: `src/app/app.component.ts`
}
);
}
openOnCodeSandbox(appComponentCode: string, includeCli: boolean = false): void {
const res = this.parseCode(appComponentCode);
const mockObj = this.genMock;
const json = deepCopy(angularJSON);
json.projects.demo.architect.build.options.styles.splice(0, 0, this.themePath);
const packageJson = this.genPackage({ dependencies: [], devDependencies: [], includeCli });
const files: {
[key: string]: {
content: string;
isBinary: boolean;
};
} = {
'package.json': {
content: JSON.stringify(packageJson, null, 2),
isBinary: false
},
'angular.json': {
content: `${JSON.stringify(json, null, 2)}`,
isBinary: false
},
'tsconfig.json': {
content: `${JSON.stringify(tsconfigJSON, null, 2)}`,
isBinary: false
},
'src/environments/environment.ts': {
content: environmentTS,
isBinary: false
},
'src/index.html': {
content: res.html,
isBinary: false
},
'src/main.ts': {
content: includeCli ? mainCliTS : mainTS,
isBinary: false
},
'src/polyfills.ts': {
content: polyfillTS,
isBinary: false
},
'src/app/app.module.ts': {
content: appModuleTS(res.componentName),
isBinary: false
},
'src/app/global-config.module.ts': {
content: globalConfigTS,
isBinary: false
},
'src/app/app.component.ts': {
content: appComponentCode,
isBinary: false
},
'src/app/ng-zorro-antd.module.ts': {
content: nzZorroAntdModuleTS,
isBinary: false
},
'src/app/delon-abc.module.ts': {
content: delonABCModuleTS,
isBinary: false
},
'src/app/delon-chart.module.ts': {
content: delonChartModuleTS,
isBinary: false
},
'src/app/startup.service.ts': {
content: this.genStartupService,
isBinary: false
},
'src/styles.css': {
content: ``,
isBinary: false
},
'_mock/user.ts': {
content: mockObj['_mock/user.ts'],
isBinary: false
},
'_mock/index.ts': {
content: mockObj['_mock/index.ts'],
isBinary: false
}
};
if (includeCli) {
files['README.md'] = {
content: readme,
isBinary: false
};
files['sandbox.config.json'] = {
content: JSON.stringify(
{
template: 'node',
container: {
node: 14
}
},
null,
2
),
isBinary: false
};
}
const parameters = getParameters({
files
});
const form = this.document.createElement('form');
const parametersInput = this.document.createElement('input');
form.method = 'POST';
form.action = 'https://codesandbox.io/api/v1/sandboxes/define';
form.target = '_blank';
parametersInput.name = 'parameters';
parametersInput.value = parameters;
form.appendChild(parametersInput);
this.document.body.append(form);
form.submit();
this.document.body.removeChild(form);
}
} | the_stack |
import { generateUuid, stopWorkLogging, TaskItem, TaskStatus } from '../utils';
export function moveCommand(tasksToUpdate: any, state, ids, cmd) {
tasksToUpdate = state.tasks.map(t => {
if (ids.indexOf(t.id) !== -1) {
t.tag = cmd.tag;
}
return t;
});
return tasksToUpdate;
}
export function beginCommand(tasksToUpdate: any, state, ids) {
tasksToUpdate = state.tasks.map(t => {
if (ids.indexOf(t.id) !== -1) {
if (t.status !== TaskStatus.WIP) {
t.status = TaskStatus.WIP;
t.logs = (t.logs || []).concat({
start: Date.now(),
end: 0,
});
}
}
return t;
});
return tasksToUpdate;
}
export function checkCommand(tasksToUpdate: any, state, ids) {
tasksToUpdate = state.tasks.map(t => {
if (ids.indexOf(t.id) !== -1) {
t.status =
t.status === TaskStatus.DONE ? TaskStatus.WAIT : TaskStatus.DONE;
if (t.status === TaskStatus.DONE) {
t = stopWorkLogging(t);
}
}
return t;
});
return tasksToUpdate;
}
export function deleteCommand(tasksToUpdate: any, ids, cmd, state) {
if (!ids.length) {
// Delete by tag
const tag = (cmd.id.match(/^(@.*)/) || []).pop();
if (tag) {
return state.tasks.reduce((tasks, t: TaskItem) => {
if (t.tag === tag) {
t.status = TaskStatus.NONE;
}
tasks.push(t);
return tasks;
}, []);
}
// Delete by status
const status = (
cmd.id.match(/^(finished|done|flag|flagged|ongoing|wip|wait|pending)/) ||
[]
).pop();
if (status) {
let taskStatus = null;
switch (status) {
case 'finished':
case 'done':
taskStatus = TaskStatus.DONE;
break;
case 'flag':
case 'flagged':
taskStatus = TaskStatus.FLAG;
break;
case 'ongoing':
case 'wip':
taskStatus = TaskStatus.WIP;
break;
case 'wait':
case 'pending':
taskStatus = TaskStatus.WAIT;
break;
default:
break;
}
return state.tasks.reduce((tasks, t: TaskItem) => {
if (taskStatus) {
if (t.status === taskStatus && !t.archived) {
t.status = TaskStatus.NONE;
}
tasks.push(t);
}
return tasks;
}, []);
}
} else {
// Delete by id
return state.tasks.reduce((tasks, t) => {
if (ids.indexOf(t.id) !== -1) {
t.status = TaskStatus.NONE;
}
tasks.push(t);
return tasks;
}, []);
}
}
export function flagCommand(tasksToUpdate: any, state, ids) {
tasksToUpdate = state.tasks.map(t => {
if (ids.indexOf(t.id) !== -1) {
t.status =
t.status === TaskStatus.FLAG ? TaskStatus.WAIT : TaskStatus.FLAG;
t = stopWorkLogging(t);
}
return t;
});
return tasksToUpdate;
}
export function stopCommand(tasksToUpdate: any, state, ids) {
tasksToUpdate = state.tasks.map(t => {
if (ids.indexOf(t.id) !== -1) {
if (t.status === TaskStatus.WIP) {
t.status = TaskStatus.WAIT;
t = stopWorkLogging(t);
}
}
return t;
});
return tasksToUpdate;
}
// TODO: Remove the duplicate code here in beginCommand and stopCommand
export function switchCommand(tasksToUpdate: any, state, ids) {
if (Array.isArray(ids) && ids.length) {
const stopId = ids[0];
const startId = ids[1];
tasksToUpdate = state.tasks.map(t => {
if (t.id === stopId) {
if (t.status === TaskStatus.WIP) {
t.status = TaskStatus.WAIT;
t = stopWorkLogging(t);
}
}
if (t.id === startId) {
if (t.status !== TaskStatus.WIP) {
t.status = TaskStatus.WIP;
t.logs = (t.logs || []).concat({
start: Date.now(),
end: 0,
});
}
}
return t;
});
}
return tasksToUpdate;
}
export function archiveCommand(ids, cmd, tasksToUpdate: any, state) {
if (!ids.length) {
// Archive by tag
const tag = (cmd.id.match(/^(@.*)/) || []).pop();
if (tag) {
tasksToUpdate = state.tasks.map(t => {
if (t.tag === tag) {
t.archived = true;
}
return t;
});
}
} else {
// Archive by Ids
tasksToUpdate = state.tasks.map(t => {
if (ids.indexOf(t.id) !== -1) {
t.archived = true;
}
return t;
});
}
return tasksToUpdate;
}
export function restoreCommand(ids, cmd, tasksToUpdate: any, state) {
if (!ids.length) {
// Archive by tag
const tag = (cmd.id.match(/^(@.*)/) || []).pop();
if (tag) {
tasksToUpdate = state.tasks.map(t => {
if (t.tag === tag) {
t.archived = false;
}
return t;
});
}
} else {
// Archive by Ids
tasksToUpdate = state.tasks.map(t => {
if (ids.indexOf(t.id) !== -1) {
t.archived = false;
}
return t;
});
}
return tasksToUpdate;
}
export function insertTaskCommand(cmd, state, tasksToUpdate: any) {
const tag = cmd.tag || '@uncategorized';
const task = cmd.text;
if (task && task.length) {
const nextId = state.tasks.reduce((maxId: number, t: TaskItem) => {
if (t.status !== TaskStatus.NONE) {
if (t.id > maxId) {
maxId = t.id;
}
}
return maxId;
}, 0);
tasksToUpdate = state.tasks
.filter(t => t.id !== nextId + 1)
.concat({
uuid: generateUuid(),
id: nextId + 1,
tag: tag,
title: task,
status: TaskStatus.WAIT,
logs: [],
archived: false,
lastaction: Date.now(),
} as TaskItem);
}
return tasksToUpdate;
}
export function editTaskCommand(ids, cmd, tasksToUpdate: any, state) {
{
const id = ids[0];
const task = cmd.text;
if (task && task.length) {
tasksToUpdate = state.tasks.map(t => {
if (t.id === id) {
t.title = task;
}
return t;
});
}
}
return tasksToUpdate;
}
export function tagRenameCommand(cmd, tasksToUpdate: any, state) {
{
const [from, to] = cmd.tag.split(' ');
tasksToUpdate = state.tasks.map(t => {
if (t.tag.match(from)) {
t.tag = to;
}
return t;
});
}
return tasksToUpdate;
}
export function hideCommand(updateCandidate, cmd) {
updateCandidate = (() => {
switch (cmd.text) {
case 'finished':
case 'done':
return {
...updateCandidate,
taskVisibility: {
...updateCandidate.taskVisibility,
done: false,
},
};
case 'flag':
case 'flagged':
return {
...updateCandidate,
taskVisibility: {
...updateCandidate.taskVisibility,
flagged: false,
},
};
case 'ongoing':
case 'wip':
return {
...updateCandidate,
taskVisibility: {
...updateCandidate.taskVisibility,
wip: false,
},
};
case 'pending':
case 'wait':
return {
...updateCandidate,
taskVisibility: {
...updateCandidate.taskVisibility,
wait: false,
},
};
default:
return updateCandidate;
}
})();
return updateCandidate;
}
export function showCommand(updateCandidate, cmd) {
updateCandidate = (() => {
switch (cmd.text) {
case 'finished':
case 'done':
return {
...updateCandidate,
taskVisibility: {
...updateCandidate.taskVisibility,
done: true,
},
};
case 'flag':
case 'flagged':
return {
...updateCandidate,
taskVisibility: {
...updateCandidate.taskVisibility,
flagged: true,
},
};
case 'wip':
case 'ongoing':
return {
...updateCandidate,
taskVisibility: {
...updateCandidate.taskVisibility,
wip: true,
},
};
case 'pending':
case 'wait':
return {
...updateCandidate,
taskVisibility: {
...updateCandidate.taskVisibility,
wait: true,
},
};
default:
return updateCandidate;
}
})();
return updateCandidate;
}
export function searchCommand(updateCandidate: any, cmd) {
if (cmd.command.match(/search/i)) {
updateCandidate = {
...updateCandidate,
filterBy: cmd.text,
};
}
return updateCandidate;
}
export function otherCommand(updateCandidate, cmd, state) {
updateCandidate = (() => {
let commandText = cmd.command.toLowerCase();
if (commandText === 'help') {
return {
...updateCandidate,
showHelp: true,
};
} else if (commandText === 'quickhelp') {
return {
...updateCandidate,
showQuickHelp: true,
};
} else if (commandText === 'today') {
return {
...updateCandidate,
showToday: !state.showToday,
};
} else if (commandText === 'dark') {
return {
...updateCandidate,
darkMode: true,
};
} else if (commandText === 'light') {
return {
...updateCandidate,
darkMode: false,
};
} else if (commandText === 'setting') {
return {
...updateCandidate,
showSettings: true,
};
} else if (commandText === 'customize') {
return {
...updateCandidate,
showCustomCSS: !updateCandidate.showCustomCSS,
};
} else if (commandText === 'list-archived') {
return {
...updateCandidate,
showArchived: !updateCandidate.showArchived,
};
} else if (commandText === 'login') {
// OK, Let me explain the weird @demo stuff here:
// If the user is already has their data on another machine, and
// they opened this app on a new machine, then login right away,
// the tasks in the range of 1..12 will be conflict with the demo
// tasks. So, we will explicitly remove these demo tasks if they're
// actually a demo, when login.
return {
...updateCandidate,
tasks: updateCandidate.tasks.filter(t =>
(t.id - 1) * (t.id - 12) <= 0 ? t.tag !== '@demo' : true,
),
userWantToLogin: true,
};
} else if (commandText === 'logout') {
return {
...updateCandidate,
authToken: '',
userName: '',
userWantToLogin: true,
};
} else {
return updateCandidate;
}
})();
return updateCandidate;
} | the_stack |
import { createElement } from '@syncfusion/ej2-base';
import { Chart } from '../../../src/chart/chart';
import { LineSeries } from '../../../src/chart/series/line-series';
import '../../../node_modules/es6-promise/dist/es6-promise';
import { definition5, definition6, definition3, definition1, definition4 } from '../base/data.spec';
import { unbindResizeEvents } from '../base/data.spec';
import { EmitType } from '@syncfusion/ej2-base';
import { ILoadedEventArgs, IAnimationCompleteEventArgs, IPointRenderEventArgs } from '../../../src/chart/model/chart-interface';
import { Category } from '../../../src/chart/axis/category-axis';
import {profile , inMB, getMemoryProfile} from '../../common.spec';
Chart.Inject(LineSeries, Category);
describe('Chart Control', () => {
beforeAll(() => {
const isDef = (o: any) => o !== undefined && o !== null;
if (!isDef(window.performance)) {
console.log("Unsupported environment, window.performance.memory is unavailable");
this.skip(); //Skips test (in Chai)
return;
}
});
let ele: HTMLElement;
let svg: HTMLElement;
let loaded: EmitType<ILoadedEventArgs>;
describe('Checking Column Definition', () => {
let chartObj: Chart;
beforeAll((): void => {
ele = createElement('div', { id: 'chartContainer' });
document.body.appendChild(ele);
chartObj = new Chart(
{
primaryXAxis: { title: 'PrimaryXAxis' },
primaryYAxis: { title: 'PrimaryYAxis', rangePadding: 'None' },
axes: [
{
columnIndex: 1, name: 'yAxis1', title: 'Axis2', rangePadding: 'None',
titleStyle: { size: '14px', fontWeight: 'Regular', color: '#282828', fontStyle: 'Normal', fontFamily: 'Segoe UI' },
labelStyle: { size: '12px', fontWeight: 'Regular', color: '#282828', fontStyle: 'Normal', fontFamily: 'Segoe UI' }
}
],
series: [
{
name: 'series1', type: 'Line', fill: '#ACE5FF', width: 2,
dataSource: definition5, xName: 'x', yName: 'y', animation: { enable: false }
},
{
name: 'series2', type: 'Line', fill: 'red', width: 2, xAxisName: 'yAxis1',
dataSource: definition6, xName: 'x', yName: 'y', animation: { enable: false }
},
],
height: '600', width: '900', title: 'Chart TS Title',
columns: [
{
width: '400', border: { width: 4, color: 'red' }
},
{
width: '400', border: { width: 4, color: 'blue' }
}
], legendSettings: { visible: false }
});
});
afterAll((): void => {
chartObj.destroy();
ele.remove();
});
it('Checking the bottom line', (done: Function) => {
loaded = (args: Object): void => {
svg = document.getElementById('chartContainer_AxisBottom_Column0');
expect(svg.getAttribute('x1') == '57.5' || svg.getAttribute('x1') == '53.5').toBe(true);
expect(svg.getAttribute('stroke') == 'red').toBe(true);
svg = document.getElementById('chartContainer_AxisBottom_Column1');
expect(svg.getAttribute('x1') == '457.5' || svg.getAttribute('x1') == '453.5').toBe(true);
expect(svg.getAttribute('stroke') == 'blue').toBe(true);
done();
};
chartObj.loaded = loaded;
chartObj.appendTo('#chartContainer');
});
it('Checking column Definition with percentage', (done: Function) => {
chartObj.primaryXAxis.columnIndex = 1;
chartObj.axes[0].columnIndex = 0;
chartObj.columns[0].width = '50%'; chartObj.columns[1].width = '50%';
loaded = (args: Object): void => {
svg = document.getElementById('chartContainer_AxisTitle_1');
expect(svg.getAttribute('y') == '287.375' || svg.getAttribute('y') == '287.875').toBe(true);
svg = document.getElementById('chartContainer1_AxisLabel_0');
expect(svg.getAttribute('y') == '543' || svg.getAttribute('y') == '546.75').toBe(true);
expect(svg.getAttribute('x') == '37').toBe(true);
svg = document.getElementById('chartContainer_AxisTitle_2');
expect(svg.getAttribute('y') == '584.75' || svg.getAttribute('y') == '585.5').toBe(true);
svg = document.getElementById('chartContainer2_AxisLabel_3');
expect(svg.getAttribute('y') == '562' || svg.getAttribute('y') == '565.25').toBe(true);
expect(svg.getAttribute('x') == '363.1875' || svg.getAttribute('x') == '361.1875').toBe(true);
svg = document.getElementById('chartContainer_AxisTitle_0');
expect(svg.getAttribute('y') == '584.75' || svg.getAttribute('y') == '585.5').toBe(true);
expect(svg.getAttribute('x') == '681.875' || svg.getAttribute('x') == '680.875').toBe(true);
svg = document.getElementById('chartContainer0_AxisLabel_2');
expect(svg.getAttribute('y') == '562' || svg.getAttribute('y') == '565.25').toBe(true);
expect(svg.getAttribute('x') == '675.375' || svg.getAttribute('x') == '674.875').toBe(true);
svg = document.getElementById('chartContainer_AxisTitle_2');
expect(svg.getAttribute('y') == '584.75' || svg.getAttribute('y') == '585.5').toBe(true);
expect(svg.getAttribute('x') == '265.625' || svg.getAttribute('x') == '262.625').toBe(true);
svg = document.getElementById('chartContainer2_AxisLabel_4');
expect(svg.getAttribute('y') == '562' || svg.getAttribute('y') == '565.25').toBe(true);
expect(svg.getAttribute('x') == '467.25' || svg.getAttribute('x') == '465.75').toBe(true);
done();
};
chartObj.loaded = loaded;
chartObj.refresh();
});
});
describe('Checking Column Definition with Spanning', () => {
let chartElem: Chart;
beforeAll((): void => {
ele = createElement('div', { id: 'chartContainer' });
document.body.appendChild(ele);
chartElem = new Chart({
border: { width: 1, color: 'black' },
primaryXAxis: { title: '', span: 2 },
primaryYAxis: { title: 'Axis1', rangePadding: 'None' },
title: '',
axes: [
{
title: 'Axis2', titleStyle: { size: '14px', fontWeight: 'Regular', color: '#282828', fontStyle: 'Normal', fontFamily: 'Segoe UI' },
name: 'yAxis2', majorGridLines: { width: 0 }, columnIndex: 1, rangePadding: 'None'
},
{
title: 'Axis3', titleStyle: { size: '14px', fontWeight: 'Regular', color: '#282828', fontStyle: 'Normal', fontFamily: 'Segoe UI' },
name: 'yAxis3', majorGridLines: { width: 0 }, columnIndex: 1, span: 2, rangePadding: 'None'
},
{
title: 'Axis4', titleStyle: { size: '14px', fontWeight: 'Regular', color: '#282828', fontStyle: 'Normal', fontFamily: 'Segoe UI' },
name: 'yAxis4', majorGridLines: { width: 0 }, columnIndex: 2, plotOffset: 10, rangePadding: 'None'
}
],
series: [
{
name: 'series1', type: 'Line', fill: '#ACE5FF', width: 2,
dataSource: definition3, xName: 'x', yName: 'y', animation: { enable: false }
},
{
name: 'series2', type: 'Line', fill: 'pink', width: 2, xAxisName: 'yAxis2',
dataSource: definition1, xName: 'x', yName: 'y', animation: { enable: false }
},
{
name: 'series3', type: 'Line', fill: 'red', width: 2, xAxisName: 'yAxis3',
dataSource: definition4, xName: 'x', yName: 'y', animation: { enable: false }
},
{
name: 'series4', type: 'Line', fill: 'blue', width: 2, xAxisName: 'yAxis4',
dataSource: definition1, xName: 'x', yName: 'y', animation: { enable: false }
},
],
columns: [
{ width: '300' },
{ width: '300' },
{ width: '300' },
], height: '600', width: '900', legendSettings: { visible: false }
});
});
afterAll((): void => {
chartElem.destroy();
ele.remove();
});
it('Axis Spanning', (done: Function) => {
loaded = (args: Object): void => {
svg = document.getElementById('chartContainer_AxisTitle_2');
expect(svg.getAttribute('y') == '528' || svg.getAttribute('y') == '523.25').toBe(true);
expect(svg.getAttribute('x') == '513.5' || svg.getAttribute('x') == '509.5' ).toBe(true);
svg = document.getElementById('chartContainer_AxisTitle_3');
expect(svg.getAttribute('y') == '584.5' || svg.getAttribute('y') == '583.75').toBe(true);
expect(svg.getAttribute('x') == '626.25' || svg.getAttribute('x') == '624.25' ).toBe(true);
svg = document.getElementById('chartContainer_AxisTitle_4');
expect(svg.getAttribute('y') == '492.5' || svg.getAttribute('y') == '486.75').toBe(true);
expect(svg.getAttribute('x') == '776.25' || svg.getAttribute('x') == '774.25' ).toBe(true);
done();
};
chartElem.loaded = loaded;
chartElem.appendTo('#chartContainer');
});
it('Checking the Spanning axis with opposedPosition', (done: Function) => {
chartElem.primaryXAxis.opposedPosition = true;
chartElem.axes = [{ opposedPosition: true }, { opposedPosition: true, span: 3 }, { opposedPosition: true }];
loaded = (args: Object): void => {
done();
};
chartElem.loaded = loaded;
chartElem.refresh();
});
});
describe('Checking Column Definition with oppossed position', () => {
let chart: Chart;
beforeAll(() => {
ele = createElement('div', { id: 'chartContainer' });
document.body.appendChild(ele);
chart = new Chart(
{
primaryXAxis: { title: 'PrimaryXAxis', opposedPosition: true },
primaryYAxis: { title: 'PrimaryYAxis', rangePadding: 'None' },
axes: [
{
columnIndex: 2, opposedPosition: true, name: 'yAxis1', rangePadding: 'None',
title: 'Axis2', titleStyle: { size: '14px', fontWeight: 'Regular', color: '#282828', fontStyle: 'Normal', fontFamily: 'Segoe UI' },
labelStyle: { size: '12px', fontWeight: 'Regular', color: '#282828', fontStyle: 'Normal', fontFamily: 'Segoe UI' }
}
],
series: [
{
name: 'series1', type: 'Line', fill: '#ACE5FF', width: 2,
dataSource: definition5, xName: 'x', yName: 'y', animation: { enable: false }
},
{
name: 'series2', type: 'Line', fill: 'red', width: 2, xAxisName: 'yAxis1',
dataSource: definition6, xName: 'x', yName: 'y', animation: { enable: false }
},
], height: '600', width: '900', title: 'Chart TS Title',
columns: [
{
width: '400', border: { width: 4, color: 'red' }
},
{
width: '400', border: { width: 4, color: 'blue' }
}
], legendSettings: { visible: false }
});
});
afterAll((): void => {
chart.destroy();
ele.remove();
});
it('Checking the bottom line with opposed position', (done: Function) => {
loaded = (args: Object): void => {
svg = document.getElementById('chartContainer_AxisBottom_Column0');
expect(svg.getAttribute('x2') == '57.5' || svg.getAttribute('x2') == '53.5').toBe(true);
expect(svg.getAttribute('stroke') == 'red').toBe(true);
svg = document.getElementById('chartContainer_AxisBottom_Column1');
expect(svg.getAttribute('x2') == '457.5' || svg.getAttribute('x2') == '453.5').toBe(true);
expect(svg.getAttribute('stroke') == 'blue').toBe(true);
done();
};
chart.loaded = loaded;
chart.appendTo('#chartContainer');
});
});
describe('Checking the Calculating Column Size Method with Axis Crossing', () => {
let chartEle: Chart;
ele = createElement('div', { id: 'chartContainer' });
beforeAll(() => {
document.body.appendChild(ele);
chartEle = new Chart(
{
primaryXAxis : {valueType: 'Double', crossesAt: 30 },
series: [{type: 'Line', xName: 'x', width: 2,yName: 'y', marker : {visible: true},
dataSource: [{ x: 1, y: 46 }, { x: 2, y: 27 }, { x: 3, y: 26 }, { x: 4, y: 16 }, { x: 5, y: 31 }],
}],
width: '800',
height: '450'
},
'#chartContainer');
unbindResizeEvents(chartEle);
});
afterAll((): void => {
chartEle.destroy();
ele.remove();
});
it('Checking the axis size with far', (done: Function) => {
loaded = (args: Object): void => {
let xLine1: HTMLElement = document.getElementById('chartContainerAxisLine_0');
let area: HTMLElement = document.getElementById('chartContainer_ChartAreaBorder');
expect((xLine1.getAttribute('d').split(' ')[2] === area.getAttribute('y'))).toBe(true);
done();
};
chartEle.loaded = loaded;
chartEle.primaryXAxis.crossesAt = 60;
chartEle.refresh();
});
it('Checking the axis size for far with opposed position and axis cross ', (done: Function) => {
loaded = (args: Object): void => {
let xLine1: HTMLElement = document.getElementById('chartContainerAxisLine_0');
let value: string = xLine1.getAttribute('d').split(' ')[2];
expect((value === '195.05' || value.indexOf('194.45') > -1)).toBe(true);
done();
};
chartEle.loaded = loaded;
chartEle.primaryXAxis.crossesAt = 30;
chartEle.primaryXAxis.opposedPosition = true;
chartEle.primaryXAxis.placeNextToAxisLine = false;
chartEle.refresh();
});
});
describe('Checking line break axis labels with columns', () => {
let chart: Chart;
beforeAll(() => {
ele = createElement('div', { id: 'container' });
document.body.appendChild(ele);
chart = new Chart(
{
primaryXAxis: { valueType: 'Category' },
primaryYAxis: { },
axes: [
{
columnIndex: 1, name: 'xAxis1', valueType: 'Category'
}
],
series: [
{
name: 'series1', type: 'Line',
dataSource: [
{ x: "India", y: 61.3 },
{ x: "United<br>States<br>of<br>America", y: 31 },
{ x: "South<br>Korea", y: 39.4 },
{ x: "United<br>Arab<br>Emirates", y: 65.1 },
{ x: "United<br>Kingdom", y: 75.9 }
], xName: 'x', yName: 'y', animation: { enable: false }
},
{
name: 'series2', type: 'Line', xAxisName: 'xAxis1',
dataSource: [
{ x: "India", y: 61.3 },
{ x: "United<br>States<br>of<br>America", y: 31 },
{ x: "South<br>Korea", y: 39.4 },
{ x: "United<br>Arab<br>Emirates", y: 65.1 },
{ x: "United<br>Kingdom", y: 75.9 }
], xName: 'x', yName: 'y', animation: { enable: false }
},
],
columns: [
{
width: '50%',
},
{
width: '50%',
}
], legendSettings: { visible: false }
},'#container');
});
afterAll((): void => {
chart.destroy();
ele.remove();
});
it('Line break label checking ', (done: Function) => {
loaded = (args: Object): void => {
let label: HTMLElement = document.getElementById('containerAxisLabels0');
expect(label.childElementCount == 5).toBe(true);
label = document.getElementById("containerAxisLabels2");
expect(label.childElementCount == 5).toBe(true);
label = document.getElementById('container0_AxisLabel_1');
expect(label.childElementCount == 3).toBe(true);
done();
};
chart.loaded = loaded;
chart.refresh();
});
it('Line break label child element checking', (done: Function) => {
loaded = (args: Object): void => {
let label: HTMLElement = document.getElementById('container0_AxisLabel_1');
expect(label.childElementCount == 3).toBe(true);
label = document.getElementById("container2_AxisLabel_1");
expect(label.childElementCount == 3).toBe(true);
done();
};
chart.loaded = loaded;
chart.refresh();
});
it('Checking line break labels with inversed axis', (done: Function) => {
loaded = (args: Object): void => {
let label: HTMLElement = document.getElementById('containerAxisLabels0');
expect(label.childElementCount == 5).toBe(true);
label = document.getElementById("containerAxisLabels2");
expect(label.childElementCount == 5).toBe(true);
label = document.getElementById('container0_AxisLabel_1');
expect(label.childElementCount == 3).toBe(true);
done();
};
chart.loaded = loaded;
chart.primaryXAxis.isInversed = true;
chart.refresh();
});
});
it('memory leak', () => {
profile.sample();
let average: any = inMB(profile.averageChange)
//Check average change in memory samples to not be over 10MB
expect(average).toBeLessThan(10);
let memory: any = inMB(getMemoryProfile())
//Check the final memory usage against the first usage, there should be little change if everything was properly deallocated
expect(memory).toBeLessThan(profile.samples[0] + 0.25);
})
}); | the_stack |
/* eslint-disable @typescript-eslint/class-name-casing */
/* eslint-disable @typescript-eslint/no-unused-vars */
/* eslint-disable @typescript-eslint/no-empty-interface */
/* eslint-disable @typescript-eslint/no-namespace */
/* eslint-disable no-irregular-whitespace */
import {
OAuth2Client,
JWT,
Compute,
UserRefreshClient,
BaseExternalAccountClient,
GaxiosPromise,
GoogleConfigurable,
createAPIRequest,
MethodOptions,
StreamMethodOptions,
GlobalOptions,
GoogleAuth,
BodyResponseCallback,
APIRequestContext,
} from 'googleapis-common';
import {Readable} from 'stream';
export namespace trafficdirector_v2 {
export interface Options extends GlobalOptions {
version: 'v2';
}
interface StandardParameters {
/**
* Auth client or API Key for the request
*/
auth?:
| string
| OAuth2Client
| JWT
| Compute
| UserRefreshClient
| BaseExternalAccountClient
| GoogleAuth;
/**
* V1 error format.
*/
'$.xgafv'?: string;
/**
* OAuth access token.
*/
access_token?: string;
/**
* Data format for response.
*/
alt?: string;
/**
* JSONP
*/
callback?: string;
/**
* Selector specifying which fields to include in a partial response.
*/
fields?: string;
/**
* API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
*/
key?: string;
/**
* OAuth 2.0 token for the current user.
*/
oauth_token?: string;
/**
* Returns response with indentations and line breaks.
*/
prettyPrint?: boolean;
/**
* Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
*/
quotaUser?: string;
/**
* Legacy upload protocol for media (e.g. "media", "multipart").
*/
uploadType?: string;
/**
* Upload protocol for media (e.g. "raw", "multipart").
*/
upload_protocol?: string;
}
/**
* Traffic Director API
*
*
*
* @example
* ```js
* const {google} = require('googleapis');
* const trafficdirector = google.trafficdirector('v2');
* ```
*/
export class Trafficdirector {
context: APIRequestContext;
discovery: Resource$Discovery;
constructor(options: GlobalOptions, google?: GoogleConfigurable) {
this.context = {
_options: options || {},
google,
};
this.discovery = new Resource$Discovery(this.context);
}
}
/**
* Addresses specify either a logical or physical address and port, which are used to tell Envoy where to bind/listen, connect to upstream and find management servers.
*/
export interface Schema$Address {
pipe?: Schema$Pipe;
socketAddress?: Schema$SocketAddress;
}
/**
* BuildVersion combines SemVer version of extension with free-form build information (i.e. 'alpha', 'private-build') as a set of strings.
*/
export interface Schema$BuildVersion {
/**
* Free-form build information. Envoy defines several well known keys in the source/common/version/version.h file
*/
metadata?: {[key: string]: any} | null;
/**
* SemVer version of extension.
*/
version?: Schema$SemanticVersion;
}
/**
* All xds configs for a particular client.
*/
export interface Schema$ClientConfig {
/**
* Node for a particular client.
*/
node?: Schema$Node;
xdsConfig?: Schema$PerXdsConfig[];
}
/**
* Request for client status of clients identified by a list of NodeMatchers.
*/
export interface Schema$ClientStatusRequest {
/**
* Management server can use these match criteria to identify clients. The match follows OR semantics.
*/
nodeMatchers?: Schema$NodeMatcher[];
}
export interface Schema$ClientStatusResponse {
/**
* Client configs for the clients specified in the ClientStatusRequest.
*/
config?: Schema$ClientConfig[];
}
/**
* Envoy's cluster manager fills this message with all currently known clusters. Cluster configuration information can be used to recreate an Envoy configuration by populating all clusters as static clusters or by returning them in a CDS response.
*/
export interface Schema$ClustersConfigDump {
/**
* The dynamically loaded active clusters. These are clusters that are available to service data plane traffic.
*/
dynamicActiveClusters?: Schema$DynamicCluster[];
/**
* The dynamically loaded warming clusters. These are clusters that are currently undergoing warming in preparation to service data plane traffic. Note that if attempting to recreate an Envoy configuration from a configuration dump, the warming clusters should generally be discarded.
*/
dynamicWarmingClusters?: Schema$DynamicCluster[];
/**
* The statically loaded cluster configs.
*/
staticClusters?: Schema$StaticCluster[];
/**
* This is the :ref:`version_info ` in the last processed CDS discovery response. If there are only static bootstrap clusters, this field will be "".
*/
versionInfo?: string | null;
}
/**
* Specifies the way to match a double value.
*/
export interface Schema$DoubleMatcher {
/**
* If specified, the input double value must be equal to the value specified here.
*/
exact?: number | null;
/**
* If specified, the input double value must be in the range specified here. Note: The range is using half-open interval semantics [start, end).
*/
range?: Schema$DoubleRange;
}
/**
* Specifies the double start and end of the range using half-open interval semantics [start, end).
*/
export interface Schema$DoubleRange {
/**
* end of the range (exclusive)
*/
end?: number | null;
/**
* start of the range (inclusive)
*/
start?: number | null;
}
/**
* Describes a dynamically loaded cluster via the CDS API.
*/
export interface Schema$DynamicCluster {
/**
* The cluster config.
*/
cluster?: {[key: string]: any} | null;
/**
* The timestamp when the Cluster was last updated.
*/
lastUpdated?: string | null;
/**
* This is the per-resource version information. This version is currently taken from the :ref:`version_info ` field at the time that the cluster was loaded. In the future, discrete per-cluster versions may be supported by the API.
*/
versionInfo?: string | null;
}
/**
* Describes a dynamically loaded listener via the LDS API. [#next-free-field: 6]
*/
export interface Schema$DynamicListener {
/**
* The listener state for any active listener by this name. These are listeners that are available to service data plane traffic.
*/
activeState?: Schema$DynamicListenerState;
/**
* The listener state for any draining listener by this name. These are listeners that are currently undergoing draining in preparation to stop servicing data plane traffic. Note that if attempting to recreate an Envoy configuration from a configuration dump, the draining listeners should generally be discarded.
*/
drainingState?: Schema$DynamicListenerState;
/**
* Set if the last update failed, cleared after the next successful update.
*/
errorState?: Schema$UpdateFailureState;
/**
* The name or unique id of this listener, pulled from the DynamicListenerState config.
*/
name?: string | null;
/**
* The listener state for any warming listener by this name. These are listeners that are currently undergoing warming in preparation to service data plane traffic. Note that if attempting to recreate an Envoy configuration from a configuration dump, the warming listeners should generally be discarded.
*/
warmingState?: Schema$DynamicListenerState;
}
export interface Schema$DynamicListenerState {
/**
* The timestamp when the Listener was last successfully updated.
*/
lastUpdated?: string | null;
/**
* The listener config.
*/
listener?: {[key: string]: any} | null;
/**
* This is the per-resource version information. This version is currently taken from the :ref:`version_info ` field at the time that the listener was loaded. In the future, discrete per-listener versions may be supported by the API.
*/
versionInfo?: string | null;
}
export interface Schema$DynamicRouteConfig {
/**
* The timestamp when the Route was last updated.
*/
lastUpdated?: string | null;
/**
* The route config.
*/
routeConfig?: {[key: string]: any} | null;
/**
* This is the per-resource version information. This version is currently taken from the :ref:`version_info ` field at the time that the route configuration was loaded.
*/
versionInfo?: string | null;
}
export interface Schema$DynamicScopedRouteConfigs {
/**
* The timestamp when the scoped route config set was last updated.
*/
lastUpdated?: string | null;
/**
* The name assigned to the scoped route configurations.
*/
name?: string | null;
/**
* The scoped route configurations.
*/
scopedRouteConfigs?: Array<{[key: string]: any}> | null;
/**
* This is the per-resource version information. This version is currently taken from the :ref:`version_info ` field at the time that the scoped routes configuration was loaded.
*/
versionInfo?: string | null;
}
/**
* Version and identification for an Envoy extension. [#next-free-field: 6]
*/
export interface Schema$Extension {
/**
* Category of the extension. Extension category names use reverse DNS notation. For instance "envoy.filters.listener" for Envoy's built-in listener filters or "com.acme.filters.http" for HTTP filters from acme.com vendor. [#comment:
*/
category?: string | null;
/**
* Indicates that the extension is present but was disabled via dynamic configuration.
*/
disabled?: boolean | null;
/**
* This is the name of the Envoy filter as specified in the Envoy configuration, e.g. envoy.filters.http.router, com.acme.widget.
*/
name?: string | null;
/**
* [#not-implemented-hide:] Type descriptor of extension configuration proto. [#comment:
*/
typeDescriptor?: string | null;
/**
* The version is a property of the extension and maintained independently of other extensions and the Envoy API. This field is not set when extension did not provide version information.
*/
version?: Schema$BuildVersion;
}
/**
* Google's `RE2 `_ regex engine. The regex string must adhere to the documented `syntax `_. The engine is designed to complete execution in linear time as well as limit the amount of memory used. Envoy supports program size checking via runtime. The runtime keys `re2.max_program_size.error_level` and `re2.max_program_size.warn_level` can be set to integers as the maximum program size or complexity that a compiled regex can have before an exception is thrown or a warning is logged, respectively. `re2.max_program_size.error_level` defaults to 100, and `re2.max_program_size.warn_level` has no default if unset (will not check/log a warning). Envoy emits two stats for tracking the program size of regexes: the histogram `re2.program_size`, which records the program size, and the counter `re2.exceeded_warn_level`, which is incremented each time the program size exceeds the warn level threshold.
*/
export interface Schema$GoogleRE2 {
/**
* This field controls the RE2 "program size" which is a rough estimate of how complex a compiled regex is to evaluate. A regex that has a program size greater than the configured value will fail to compile. In this case, the configured max program size can be increased or the regex can be simplified. If not specified, the default is 100. This field is deprecated; regexp validation should be performed on the management server instead of being done by each individual client.
*/
maxProgramSize?: number | null;
}
export interface Schema$InlineScopedRouteConfigs {
/**
* The timestamp when the scoped route config set was last updated.
*/
lastUpdated?: string | null;
/**
* The name assigned to the scoped route configurations.
*/
name?: string | null;
/**
* The scoped route configurations.
*/
scopedRouteConfigs?: Array<{[key: string]: any}> | null;
}
/**
* Envoy's listener manager fills this message with all currently known listeners. Listener configuration information can be used to recreate an Envoy configuration by populating all listeners as static listeners or by returning them in a LDS response.
*/
export interface Schema$ListenersConfigDump {
/**
* State for any warming, active, or draining listeners.
*/
dynamicListeners?: Schema$DynamicListener[];
/**
* The statically loaded listener configs.
*/
staticListeners?: Schema$StaticListener[];
/**
* This is the :ref:`version_info ` in the last processed LDS discovery response. If there are only static bootstrap listeners, this field will be "".
*/
versionInfo?: string | null;
}
/**
* Specifies the way to match a list value.
*/
export interface Schema$ListMatcher {
/**
* If specified, at least one of the values in the list must match the value specified.
*/
oneOf?: Schema$ValueMatcher;
}
/**
* Identifies location of where either Envoy runs or where upstream hosts run.
*/
export interface Schema$Locality {
/**
* Region this :ref:`zone ` belongs to.
*/
region?: string | null;
/**
* When used for locality of upstream hosts, this field further splits zone into smaller chunks of sub-zones so they can be load balanced independently.
*/
subZone?: string | null;
/**
* Defines the local service zone where Envoy is running. Though optional, it should be set if discovery service routing is used and the discovery service exposes :ref:`zone data `, either in this message or via :option:`--service-zone`. The meaning of zone is context dependent, e.g. `Availability Zone (AZ) `_ on AWS, `Zone `_ on GCP, etc.
*/
zone?: string | null;
}
/**
* Identifies a specific Envoy instance. The node identifier is presented to the management server, which may use this identifier to distinguish per Envoy configuration for serving. [#next-free-field: 12]
*/
export interface Schema$Node {
/**
* This is motivated by informing a management server during canary which version of Envoy is being tested in a heterogeneous fleet. This will be set by Envoy in management server RPCs. This field is deprecated in favor of the user_agent_name and user_agent_version values.
*/
buildVersion?: string | null;
/**
* Client feature support list. These are well known features described in the Envoy API repository for a given major version of an API. Client features use reverse DNS naming scheme, for example `com.acme.feature`. See :ref:`the list of features ` that xDS client may support.
*/
clientFeatures?: string[] | null;
/**
* Defines the local service cluster name where Envoy is running. Though optional, it should be set if any of the following features are used: :ref:`statsd `, :ref:`health check cluster verification `, :ref:`runtime override directory `, :ref:`user agent addition `, :ref:`HTTP global rate limiting `, :ref:`CDS `, and :ref:`HTTP tracing `, either in this message or via :option:`--service-cluster`.
*/
cluster?: string | null;
/**
* List of extensions and their versions supported by the node.
*/
extensions?: Schema$Extension[];
/**
* An opaque node identifier for the Envoy node. This also provides the local service node name. It should be set if any of the following features are used: :ref:`statsd `, :ref:`CDS `, and :ref:`HTTP tracing `, either in this message or via :option:`--service-node`.
*/
id?: string | null;
/**
* Known listening ports on the node as a generic hint to the management server for filtering :ref:`listeners ` to be returned. For example, if there is a listener bound to port 80, the list can optionally contain the SocketAddress `(0.0.0.0,80)`. The field is optional and just a hint.
*/
listeningAddresses?: Schema$Address[];
/**
* Locality specifying where the Envoy instance is running.
*/
locality?: Schema$Locality;
/**
* Opaque metadata extending the node identifier. Envoy will pass this directly to the management server.
*/
metadata?: {[key: string]: any} | null;
/**
* Structured version of the entity requesting config.
*/
userAgentBuildVersion?: Schema$BuildVersion;
/**
* Free-form string that identifies the entity requesting config. E.g. "envoy" or "grpc"
*/
userAgentName?: string | null;
/**
* Free-form string that identifies the version of the entity requesting config. E.g. "1.12.2" or "abcd1234", or "SpecialEnvoyBuild"
*/
userAgentVersion?: string | null;
}
/**
* Specifies the way to match a Node. The match follows AND semantics.
*/
export interface Schema$NodeMatcher {
/**
* Specifies match criteria on the node id.
*/
nodeId?: Schema$StringMatcher;
/**
* Specifies match criteria on the node metadata.
*/
nodeMetadatas?: Schema$StructMatcher[];
}
/**
* NullMatch is an empty message to specify a null value.
*/
export interface Schema$NullMatch {}
/**
* Specifies the segment in a path to retrieve value from Struct.
*/
export interface Schema$PathSegment {
/**
* If specified, use the key to retrieve the value in a Struct.
*/
key?: string | null;
}
/**
* Detailed config (per xDS) with status. [#next-free-field: 6]
*/
export interface Schema$PerXdsConfig {
clusterConfig?: Schema$ClustersConfigDump;
listenerConfig?: Schema$ListenersConfigDump;
routeConfig?: Schema$RoutesConfigDump;
scopedRouteConfig?: Schema$ScopedRoutesConfigDump;
status?: string | null;
}
export interface Schema$Pipe {
/**
* The mode for the Pipe. Not applicable for abstract sockets.
*/
mode?: number | null;
/**
* Unix Domain Socket path. On Linux, paths starting with '@' will use the abstract namespace. The starting '@' is replaced by a null byte by Envoy. Paths starting with '@' will result in an error in environments other than Linux.
*/
path?: string | null;
}
/**
* A regex matcher designed for safety when used with untrusted input.
*/
export interface Schema$RegexMatcher {
/**
* Google's RE2 regex engine.
*/
googleRe2?: Schema$GoogleRE2;
/**
* The regex match string. The string must be supported by the configured engine.
*/
regex?: string | null;
}
/**
* Envoy's RDS implementation fills this message with all currently loaded routes, as described by their RouteConfiguration objects. Static routes that are either defined in the bootstrap configuration or defined inline while configuring listeners are separated from those configured dynamically via RDS. Route configuration information can be used to recreate an Envoy configuration by populating all routes as static routes or by returning them in RDS responses.
*/
export interface Schema$RoutesConfigDump {
/**
* The dynamically loaded route configs.
*/
dynamicRouteConfigs?: Schema$DynamicRouteConfig[];
/**
* The statically loaded route configs.
*/
staticRouteConfigs?: Schema$StaticRouteConfig[];
}
/**
* Envoy's scoped RDS implementation fills this message with all currently loaded route configuration scopes (defined via ScopedRouteConfigurationsSet protos). This message lists both the scopes defined inline with the higher order object (i.e., the HttpConnectionManager) and the dynamically obtained scopes via the SRDS API.
*/
export interface Schema$ScopedRoutesConfigDump {
/**
* The dynamically loaded scoped route configs.
*/
dynamicScopedRouteConfigs?: Schema$DynamicScopedRouteConfigs[];
/**
* The statically loaded scoped route configs.
*/
inlineScopedRouteConfigs?: Schema$InlineScopedRouteConfigs[];
}
/**
* Envoy uses SemVer (https://semver.org/). Major/minor versions indicate expected behaviors and APIs, the patch version field is used only for security fixes and can be generally ignored.
*/
export interface Schema$SemanticVersion {
majorNumber?: number | null;
minorNumber?: number | null;
patch?: number | null;
}
/**
* [#next-free-field: 7]
*/
export interface Schema$SocketAddress {
/**
* The address for this socket. :ref:`Listeners ` will bind to the address. An empty address is not allowed. Specify ``0.0.0.0`` or ``::`` to bind to any address. [#comment:TODO(zuercher) reinstate when implemented: It is possible to distinguish a Listener address via the prefix/suffix matching in :ref:`FilterChainMatch `.] When used within an upstream :ref:`BindConfig `, the address controls the source address of outbound connections. For :ref:`clusters `, the cluster type determines whether the address must be an IP (*STATIC* or *EDS* clusters) or a hostname resolved by DNS (*STRICT_DNS* or *LOGICAL_DNS* clusters). Address resolution can be customized via :ref:`resolver_name `.
*/
address?: string | null;
/**
* When binding to an IPv6 address above, this enables `IPv4 compatibility `_. Binding to ``::`` will allow both IPv4 and IPv6 connections, with peer IPv4 addresses mapped into IPv6 space as ``::FFFF:``.
*/
ipv4Compat?: boolean | null;
/**
* This is only valid if :ref:`resolver_name ` is specified below and the named resolver is capable of named port resolution.
*/
namedPort?: string | null;
portValue?: number | null;
protocol?: string | null;
/**
* The name of the custom resolver. This must have been registered with Envoy. If this is empty, a context dependent default applies. If the address is a concrete IP address, no resolution will occur. If address is a hostname this should be set for resolution other than DNS. Specifying a custom resolver with *STRICT_DNS* or *LOGICAL_DNS* will generate an error at runtime.
*/
resolverName?: string | null;
}
/**
* Describes a statically loaded cluster.
*/
export interface Schema$StaticCluster {
/**
* The cluster config.
*/
cluster?: {[key: string]: any} | null;
/**
* The timestamp when the Cluster was last updated.
*/
lastUpdated?: string | null;
}
/**
* Describes a statically loaded listener.
*/
export interface Schema$StaticListener {
/**
* The timestamp when the Listener was last successfully updated.
*/
lastUpdated?: string | null;
/**
* The listener config.
*/
listener?: {[key: string]: any} | null;
}
export interface Schema$StaticRouteConfig {
/**
* The timestamp when the Route was last updated.
*/
lastUpdated?: string | null;
/**
* The route config.
*/
routeConfig?: {[key: string]: any} | null;
}
/**
* Specifies the way to match a string. [#next-free-field: 7]
*/
export interface Schema$StringMatcher {
/**
* The input string must match exactly the string specified here. Examples: * *abc* only matches the value *abc*.
*/
exact?: string | null;
/**
* If true, indicates the exact/prefix/suffix matching should be case insensitive. This has no effect for the safe_regex match. For example, the matcher *data* will match both input string *Data* and *data* if set to true.
*/
ignoreCase?: boolean | null;
/**
* The input string must have the prefix specified here. Note: empty prefix is not allowed, please use regex instead. Examples: * *abc* matches the value *abc.xyz*
*/
prefix?: string | null;
/**
* The input string must match the regular expression specified here. The regex grammar is defined `here `_. Examples: * The regex ``\d{3\}`` matches the value *123* * The regex ``\d{3\}`` does not match the value *1234* * The regex ``\d{3\}`` does not match the value *123.456* .. attention:: This field has been deprecated in favor of `safe_regex` as it is not safe for use with untrusted input in all cases.
*/
regex?: string | null;
/**
* The input string must match the regular expression specified here.
*/
safeRegex?: Schema$RegexMatcher;
/**
* The input string must have the suffix specified here. Note: empty prefix is not allowed, please use regex instead. Examples: * *abc* matches the value *xyz.abc*
*/
suffix?: string | null;
}
/**
* StructMatcher provides a general interface to check if a given value is matched in google.protobuf.Struct. It uses `path` to retrieve the value from the struct and then check if it's matched to the specified value. For example, for the following Struct: .. code-block:: yaml fields: a: struct_value: fields: b: struct_value: fields: c: string_value: pro t: list_value: values: - string_value: m - string_value: n The following MetadataMatcher is matched as the path [a, b, c] will retrieve a string value "pro" from the Metadata which is matched to the specified prefix match. .. code-block:: yaml path: - key: a - key: b - key: c value: string_match: prefix: pr The following StructMatcher is matched as the code will match one of the string values in the list at the path [a, t]. .. code-block:: yaml path: - key: a - key: t value: list_match: one_of: string_match: exact: m An example use of StructMatcher is to match metadata in envoy.v*.core.Node.
*/
export interface Schema$StructMatcher {
/**
* The path to retrieve the Value from the Struct.
*/
path?: Schema$PathSegment[];
/**
* The StructMatcher is matched if the value retrieved by path is matched to this value.
*/
value?: Schema$ValueMatcher;
}
export interface Schema$UpdateFailureState {
/**
* Details about the last failed update attempt.
*/
details?: string | null;
/**
* What the component configuration would have been if the update had succeeded.
*/
failedConfiguration?: {[key: string]: any} | null;
/**
* Time of the latest failed update attempt.
*/
lastUpdateAttempt?: string | null;
}
/**
* Specifies the way to match a ProtobufWkt::Value. Primitive values and ListValue are supported. StructValue is not supported and is always not matched. [#next-free-field: 7]
*/
export interface Schema$ValueMatcher {
/**
* If specified, a match occurs if and only if the target value is a bool value and is equal to this field.
*/
boolMatch?: boolean | null;
/**
* If specified, a match occurs if and only if the target value is a double value and is matched to this field.
*/
doubleMatch?: Schema$DoubleMatcher;
/**
* If specified, a match occurs if and only if the target value is a list value and is matched to this field.
*/
listMatch?: Schema$ListMatcher;
/**
* If specified, a match occurs if and only if the target value is a NullValue.
*/
nullMatch?: Schema$NullMatch;
/**
* If specified, value match will be performed based on whether the path is referring to a valid primitive value in the metadata. If the path is referring to a non-primitive value, the result is always not matched.
*/
presentMatch?: boolean | null;
/**
* If specified, a match occurs if and only if the target value is a string value and is matched to this field.
*/
stringMatch?: Schema$StringMatcher;
}
export class Resource$Discovery {
context: APIRequestContext;
constructor(context: APIRequestContext) {
this.context = context;
}
/**
* @example
* ```js
* // Before running the sample:
* // - Enable the API at:
* // https://console.developers.google.com/apis/api/trafficdirector.googleapis.com
* // - Login into gcloud by running:
* // `$ gcloud auth application-default login`
* // - Install the npm module by running:
* // `$ npm install googleapis`
*
* const {google} = require('googleapis');
* const trafficdirector = google.trafficdirector('v2');
*
* async function main() {
* const auth = new google.auth.GoogleAuth({
* // Scopes can be specified either as an array or as a single, space-delimited string.
* scopes: ['https://www.googleapis.com/auth/cloud-platform'],
* });
*
* // Acquire an auth client, and bind it to all future calls
* const authClient = await auth.getClient();
* google.options({auth: authClient});
*
* // Do the magic
* const res = await trafficdirector.discovery.client_status({
* // Request body metadata
* requestBody: {
* // request body parameters
* // {
* // "nodeMatchers": []
* // }
* },
* });
* console.log(res.data);
*
* // Example response
* // {
* // "config": []
* // }
* }
*
* main().catch(e => {
* console.error(e);
* throw e;
* });
*
* ```
*
* @param params - Parameters for request
* @param options - Optionally override request options, such as `url`, `method`, and `encoding`.
* @param callback - Optional callback that handles the response.
* @returns A promise if used with async/await, or void if used with a callback.
*/
client_status(
params: Params$Resource$Discovery$Client_status,
options: StreamMethodOptions
): GaxiosPromise<Readable>;
client_status(
params?: Params$Resource$Discovery$Client_status,
options?: MethodOptions
): GaxiosPromise<Schema$ClientStatusResponse>;
client_status(
params: Params$Resource$Discovery$Client_status,
options: StreamMethodOptions | BodyResponseCallback<Readable>,
callback: BodyResponseCallback<Readable>
): void;
client_status(
params: Params$Resource$Discovery$Client_status,
options:
| MethodOptions
| BodyResponseCallback<Schema$ClientStatusResponse>,
callback: BodyResponseCallback<Schema$ClientStatusResponse>
): void;
client_status(
params: Params$Resource$Discovery$Client_status,
callback: BodyResponseCallback<Schema$ClientStatusResponse>
): void;
client_status(
callback: BodyResponseCallback<Schema$ClientStatusResponse>
): void;
client_status(
paramsOrCallback?:
| Params$Resource$Discovery$Client_status
| BodyResponseCallback<Schema$ClientStatusResponse>
| BodyResponseCallback<Readable>,
optionsOrCallback?:
| MethodOptions
| StreamMethodOptions
| BodyResponseCallback<Schema$ClientStatusResponse>
| BodyResponseCallback<Readable>,
callback?:
| BodyResponseCallback<Schema$ClientStatusResponse>
| BodyResponseCallback<Readable>
):
| void
| GaxiosPromise<Schema$ClientStatusResponse>
| GaxiosPromise<Readable> {
let params = (paramsOrCallback ||
{}) as Params$Resource$Discovery$Client_status;
let options = (optionsOrCallback || {}) as MethodOptions;
if (typeof paramsOrCallback === 'function') {
callback = paramsOrCallback;
params = {} as Params$Resource$Discovery$Client_status;
options = {};
}
if (typeof optionsOrCallback === 'function') {
callback = optionsOrCallback;
options = {};
}
const rootUrl =
options.rootUrl || 'https://trafficdirector.googleapis.com/';
const parameters = {
options: Object.assign(
{
url: (rootUrl + '/v2/discovery:client_status').replace(
/([^:]\/)\/+/g,
'$1'
),
method: 'POST',
},
options
),
params,
requiredParams: [],
pathParams: [],
context: this.context,
};
if (callback) {
createAPIRequest<Schema$ClientStatusResponse>(
parameters,
callback as BodyResponseCallback<unknown>
);
} else {
return createAPIRequest<Schema$ClientStatusResponse>(parameters);
}
}
}
export interface Params$Resource$Discovery$Client_status
extends StandardParameters {
/**
* Request body metadata
*/
requestBody?: Schema$ClientStatusRequest;
}
} | the_stack |
import { verifyTabbingOrder } from '../../helpers/accessibility/tabbing-order';
import { tabbingOrderConfig as config } from '../../helpers/accessibility/tabbing-order.config';
import * as orderCancellationReturn from '../../helpers/order-cancellations-returns';
import * as sampleData from '../../sample-data/order-cancellations-returns';
describe('Order Cancellations and Returns', () => {
before(() => {
cy.requireLoggedIn();
cy.saveLocalStorage();
});
beforeEach(() => {
cy.restoreLocalStorage();
});
describe('Should display cancel or return buttons in order details page', () => {
it('should display cancel button in order details page', () => {
orderCancellationReturn.getStubbedCancellableOrderDetails();
orderCancellationReturn.visitOrderDetailPage();
assertActionButtons('Cancel Items');
// Accessibility
verifyTabbingOrder(
'cx-order-details-actions',
config.orderDetailsCancelAction
);
});
it('should display return button in order details page', () => {
orderCancellationReturn.getStubbedReturnableOrderDetails();
orderCancellationReturn.visitOrderDetailPage();
assertActionButtons('Request a Return');
// Accessibility
verifyTabbingOrder(
'cx-order-details-actions',
config.orderDetailsReturnAction
);
});
});
describe('should cancel order', () => {
it('should cancel', () => {
orderCancellationReturn.getStubbedCancellableOrderDetails();
orderCancellationReturn.visitCancelOrderPage();
assertButtons();
assertOrderItems(sampleData.orderDetails);
// accessibility
verifyTabbingOrder(
'cx-page-layout.AccountPageTemplate',
config.cancelOrReturnOrder
);
// validate input
validateInput();
// cancel one item
cancelItem();
});
it('should confirm cancel', () => {
assertButtons(true);
assertOrderItems(sampleData.orderDetails, true);
// accessibility
verifyTabbingOrder(
'cx-page-layout.AccountPageTemplate',
config.confirmCancelOrReturnOrder
);
// confirm cancel
orderCancellationReturn.confirmCancelOrder();
cy.get('cx-amend-order-actions .btn-primary').eq(0).click();
cy.get('cx-global-message').should(
'contain',
`Your cancellation request was submitted (original order ${sampleData.ORDER_CODE} will be updated)`
);
cy.get('cx-breadcrumb').should('contain', 'Order History');
});
});
describe('should return order', () => {
it('should return', () => {
orderCancellationReturn.getStubbedReturnableOrderDetails();
orderCancellationReturn.visitReturnOrderPage();
assertButtons();
assertOrderItems(sampleData.orderDetails);
// accessibility
verifyTabbingOrder(
'cx-page-layout.AccountPageTemplate',
config.cancelOrReturnOrder
);
// validate input
validateInput();
// return one item
returnItem();
});
it('should confirm return', () => {
assertButtons(true);
assertOrderItems(sampleData.orderDetails, true);
// accessibility
verifyTabbingOrder(
'cx-page-layout.AccountPageTemplate',
config.confirmCancelOrReturnOrder
);
// confirm return
orderCancellationReturn.confirmReturnOrder();
cy.get('cx-amend-order-actions .btn-primary').eq(0).click();
cy.get('cx-global-message').should(
'contain',
`Your return request (${sampleData.RMA}) was submitted`
);
cy.get('cx-breadcrumb').should('contain', 'Return Request Details');
});
});
describe('Return request list and details', () => {
it('should display return request list', () => {
orderCancellationReturn.getStubbedReturnRequestList();
orderCancellationReturn.visitReturnRequestListPage();
cy.wait('@return_request_list')
.its('response.statusCode')
.should('eq', 200);
cy.get('cx-tab-paragraph-container button').eq(1).click();
const returnRequest = sampleData.returnRequestList.returnRequests[0];
cy.get('cx-order-return-request-list a.cx-order-history-value')
.eq(0)
.should('contain', returnRequest.rma);
cy.get('cx-order-return-request-list a.cx-order-history-value')
.eq(1)
.should('contain', returnRequest.order.code);
cy.get('cx-order-return-request-list .cx-order-history-placed').should(
'contain',
sampleData.REQUEST_CREATE_TIME
);
cy.get('cx-order-return-request-list .cx-order-history-status').should(
'contain',
sampleData.REQUEST_STATUS_PENDING
);
// test the sort dropdown
cy.get('.top cx-sorting .ng-select').ngSelect('Return Number');
cy.wait('@return_request_list')
.its('response.statusCode')
.should('eq', 200);
cy.get('@return_request_list')
.its('request.url')
.should('contain', 'sort=byRMA');
// accessibility
verifyTabbingOrder(
'cx-order-return-request-list',
config.returnRequestList
);
});
it('Should display return request detail page', () => {
orderCancellationReturn.getStubbedReturnRequestDetails();
orderCancellationReturn.visitReturnRequestDetailsPage();
// assert buttons
cy.get('cx-return-request-overview .btn-action').should(
'contain',
'Back'
);
cy.get('cx-return-request-overview .btn-primary').should(
'contain',
'Cancel Return Request'
);
// assert return request overview
assertReturnRequestOverview(0, 'Return Request #', sampleData.RMA);
assertReturnRequestOverview(1, 'For Order #', sampleData.ORDER_CODE);
assertReturnRequestOverview(
2,
'Return status',
sampleData.REQUEST_STATUS_PENDING
);
// assert returned items
assertReturnedItems(sampleData.returnRequestDetails);
// assert return totals
assertReturnTotals(sampleData.returnRequestDetails);
// accessibility
verifyTabbingOrder(
'cx-page-layout.AccountPageTemplate',
config.returnRequestDetails
);
});
it('should cancel a return request', () => {
orderCancellationReturn.getStubbedReturnRequestDetails();
orderCancellationReturn.visitReturnRequestDetailsPage();
orderCancellationReturn.cancelReturnRequest();
cy.get('cx-return-request-overview .btn-primary').click();
cy.get('cx-global-message').should(
'contain',
`Your return request (${sampleData.RMA}) was cancelled`
);
cy.get('cx-breadcrumb').should('contain', 'Order History');
// after cancelling one return request, go to list page to check the request status
orderCancellationReturn.getStubbedReturnRequestListAfterCancel();
cy.wait('@return_request_list_after_cancel')
.its('response.statusCode')
.should('eq', 200);
cy.get('cx-tab-paragraph-container button').eq(1).click();
cy.get('cx-order-return-request-list .cx-order-history-status').should(
'contain',
sampleData.REQUEST_STATUS_CANCELLING
);
// go to detail page to check the status and button
orderCancellationReturn.getStubbedReturnRequestDetailsAfterCancel();
cy.get('cx-order-return-request-list a.cx-order-history-value')
.eq(0)
.click();
assertReturnRequestOverview(
2,
'Return status',
sampleData.REQUEST_STATUS_CANCELLING
);
cy.get('cx-return-request-overview .btn-primary').should('not.exist');
});
});
function assertActionButtons(btnText: string) {
cy.get('cx-order-details-actions a.btn').should('contain', btnText);
}
function assertButtons(isConfirm = false) {
cy.get('cx-amend-order-actions a.btn').should('contain', 'Back');
if (isConfirm) {
cy.get('cx-amend-order-actions .btn-primary').should(
'contain',
'Submit Request'
);
} else {
cy.get('cx-amend-order-actions .btn-primary').should(
'contain',
'Continue'
);
}
}
function assertOrderItems(order: any, isConfirm = false) {
if (!isConfirm) {
cy.get('cx-amend-order-items button.cx-action-link').should(
'contain',
'Set all quantities to maximum '
);
}
cy.get('cx-amend-order-items').within(() => {
cy.get('.cx-item-list-row').should('have.length', order.entries.length);
});
order.entries.forEach((entry, index) => {
cy.get('cx-amend-order-items .cx-item-list-row')
.eq(index)
.within(() => {
cy.get('.cx-list-item-desc').should('contain', entry.product.name);
cy.get('.cx-list-item-desc').should('contain', entry.product.code);
cy.get('.cx-price').should('contain', entry.basePrice.formattedValue);
if (isConfirm) {
cy.get('.cx-quantity').should('contain', 1);
cy.get('.cx-total').should(
'contain',
entry.basePrice.formattedValue
);
} else {
cy.get('.cx-request-qty').should('contain', 1);
cy.get('cx-item-counter').should('exist');
}
});
});
}
function validateInput() {
cy.get('cx-amend-order-actions .btn-primary').eq(0).click();
cy.get('cx-form-errors').should('contain', 'Select at least one item');
cy.get('cx-item-counter button').eq(1).click();
cy.get('cx-form-errors').should('not.contain', 'Select at least one item');
}
function cancelItem() {
cy.get('cx-amend-order-actions .btn-primary').eq(0).click();
cy.get('cx-breadcrumb').should('contain', 'Cancel Order Confirmation');
}
function returnItem() {
cy.get('cx-amend-order-actions .btn-primary').eq(0).click();
cy.get('cx-breadcrumb').should('contain', 'Return Order Confirmation');
}
function assertReturnRequestOverview(
index: number,
label: string,
value: string
) {
cy.get('cx-return-request-overview .cx-detail')
.eq(index)
.get('.cx-detail-label')
.should('contain', label);
cy.get('cx-return-request-overview .cx-detail')
.eq(0)
.get('.cx-detail-value')
.should('contain', value);
}
function assertReturnedItems(returnRequestDetails) {
cy.get('cx-return-request-items').within(() => {
cy.get('.cx-item-list-row').should(
'have.length',
returnRequestDetails.returnEntries.length
);
});
returnRequestDetails.returnEntries.forEach((entry, index) => {
cy.get('cx-return-request-items .cx-item-list-row')
.eq(index)
.within(() => {
cy.get('.cx-info-container').should(
'contain',
entry.orderEntry.product.name
);
cy.get('.cx-info-container').should(
'contain',
entry.orderEntry.product.code
);
cy.get('.cx-price').should(
'contain',
entry.orderEntry.basePrice.formattedValue
);
cy.get('.cx-quantity').should('contain', entry.expectedQuantity);
cy.get('.cx-total').should(
'contain',
entry.refundAmount.formattedValue
);
});
});
}
function assertReturnTotals(returnRequestDetails) {
cy.get('cx-return-request-totals .cx-summary-row')
.eq(0)
.should('contain', returnRequestDetails.subTotal.formattedValue);
cy.get('cx-return-request-totals .cx-summary-row')
.eq(1)
.should('contain', returnRequestDetails.deliveryCost.formattedValue);
cy.get('cx-return-request-totals .cx-summary-row')
.eq(2)
.should('contain', returnRequestDetails.totalPrice.formattedValue);
}
}); | the_stack |
* OpenAPI Petstore
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
import {Api} from './';
import {List} from 'immutable';
import {all, fork, put, takeLatest} from "redux-saga/effects";
import {apiCall, createSagaAction as originalCreateSagaAction, BaseEntitySupportPayloadApiAction, BasePayloadApiAction, NormalizedRecordEntities, normalizedEntities} from "../runtimeSagasAndRecords";
import {Action} from "redux-ts-simple";
import {
DefaultMetaOnlyResponse,
DefaultMetaOnlyResponseRecord,
defaultMetaOnlyResponseRecordUtils,
User,
UserRecord,
userRecordUtils,
} from '../models';
const createSagaAction = <T>(type: string) => originalCreateSagaAction<T>(type, {namespace: "api_userApi"});
export const userApiSagaMap = new Map<string, () => Generator<any, any, any>>([
["createUser", createUserSaga],
["createUsersWithArrayInput", createUsersWithArrayInputSaga],
["createUsersWithListInput", createUsersWithListInputSaga],
["deleteUser", deleteUserSaga],
["getUserByName", getUserByNameSaga],
["loginUser", loginUserSaga],
["logoutUser", logoutUserSaga],
["updateUser", updateUserSaga],
]
);
export function *userApiAllSagas() {
yield all([...userApiSagaMap.values()].map(actionSaga => fork(actionSaga)));
}
//region createUser
export interface PayloadCreateUser extends PayloadCreateUserRequest, BasePayloadApiAction {
}
export interface PayloadCreateUserRequest {
body: UserRecord;
}
export const createUserRequest = createSagaAction<PayloadCreateUserRequest>("createUserRequest");
export const createUserSuccess = createSagaAction<void>("createUserSuccess");
export const createUserFailure = createSagaAction<{error: any, requestPayload: PayloadCreateUser}>("createUserFailure");
export const createUser = createSagaAction<PayloadCreateUser>("createUser");
export function *createUserSaga() {
yield takeLatest(createUser, createUserSagaImp);
}
export function *createUserSagaImp(_action_: Action<PayloadCreateUser>) {
const {markErrorsAsHandled, ..._payloadRest_} = _action_.payload;
try {
const {
body,
} = _payloadRest_;
yield put(createUserRequest(_action_.payload));
const response = yield apiCall(Api.userApi, Api.userApi.createUser,
userRecordUtils.toApi(body),
);
yield put(createUserSuccess());
return undefined;
} catch (error) {
if (markErrorsAsHandled) {error.wasHandled = true; }
yield put(createUserFailure({error, requestPayload: _action_.payload}));
return error;
}
}
//endregion
//region createUsersWithArrayInput
export interface PayloadCreateUsersWithArrayInput extends PayloadCreateUsersWithArrayInputRequest, BasePayloadApiAction {
}
export interface PayloadCreateUsersWithArrayInputRequest {
body: List<UserRecord>;
}
export const createUsersWithArrayInputRequest = createSagaAction<PayloadCreateUsersWithArrayInputRequest>("createUsersWithArrayInputRequest");
export const createUsersWithArrayInputSuccess = createSagaAction<void>("createUsersWithArrayInputSuccess");
export const createUsersWithArrayInputFailure = createSagaAction<{error: any, requestPayload: PayloadCreateUsersWithArrayInput}>("createUsersWithArrayInputFailure");
export const createUsersWithArrayInput = createSagaAction<PayloadCreateUsersWithArrayInput>("createUsersWithArrayInput");
export function *createUsersWithArrayInputSaga() {
yield takeLatest(createUsersWithArrayInput, createUsersWithArrayInputSagaImp);
}
export function *createUsersWithArrayInputSagaImp(_action_: Action<PayloadCreateUsersWithArrayInput>) {
const {markErrorsAsHandled, ..._payloadRest_} = _action_.payload;
try {
const {
body,
} = _payloadRest_;
yield put(createUsersWithArrayInputRequest(_action_.payload));
const response = yield apiCall(Api.userApi, Api.userApi.createUsersWithArrayInput,
userRecordUtils.toApiArray(body),
);
yield put(createUsersWithArrayInputSuccess());
return undefined;
} catch (error) {
if (markErrorsAsHandled) {error.wasHandled = true; }
yield put(createUsersWithArrayInputFailure({error, requestPayload: _action_.payload}));
return error;
}
}
//endregion
//region createUsersWithListInput
export interface PayloadCreateUsersWithListInput extends PayloadCreateUsersWithListInputRequest, BasePayloadApiAction {
}
export interface PayloadCreateUsersWithListInputRequest {
body: List<UserRecord>;
}
export const createUsersWithListInputRequest = createSagaAction<PayloadCreateUsersWithListInputRequest>("createUsersWithListInputRequest");
export const createUsersWithListInputSuccess = createSagaAction<void>("createUsersWithListInputSuccess");
export const createUsersWithListInputFailure = createSagaAction<{error: any, requestPayload: PayloadCreateUsersWithListInput}>("createUsersWithListInputFailure");
export const createUsersWithListInput = createSagaAction<PayloadCreateUsersWithListInput>("createUsersWithListInput");
export function *createUsersWithListInputSaga() {
yield takeLatest(createUsersWithListInput, createUsersWithListInputSagaImp);
}
export function *createUsersWithListInputSagaImp(_action_: Action<PayloadCreateUsersWithListInput>) {
const {markErrorsAsHandled, ..._payloadRest_} = _action_.payload;
try {
const {
body,
} = _payloadRest_;
yield put(createUsersWithListInputRequest(_action_.payload));
const response = yield apiCall(Api.userApi, Api.userApi.createUsersWithListInput,
userRecordUtils.toApiArray(body),
);
yield put(createUsersWithListInputSuccess());
return undefined;
} catch (error) {
if (markErrorsAsHandled) {error.wasHandled = true; }
yield put(createUsersWithListInputFailure({error, requestPayload: _action_.payload}));
return error;
}
}
//endregion
//region deleteUser
export interface PayloadDeleteUser extends PayloadDeleteUserRequest, BasePayloadApiAction {
}
export interface PayloadDeleteUserRequest {
username: string;
}
export const deleteUserRequest = createSagaAction<PayloadDeleteUserRequest>("deleteUserRequest");
export const deleteUserSuccess = createSagaAction<void>("deleteUserSuccess");
export const deleteUserFailure = createSagaAction<{error: any, requestPayload: PayloadDeleteUser}>("deleteUserFailure");
export const deleteUser = createSagaAction<PayloadDeleteUser>("deleteUser");
export function *deleteUserSaga() {
yield takeLatest(deleteUser, deleteUserSagaImp);
}
export function *deleteUserSagaImp(_action_: Action<PayloadDeleteUser>) {
const {markErrorsAsHandled, ..._payloadRest_} = _action_.payload;
try {
const {
username,
} = _payloadRest_;
yield put(deleteUserRequest(_action_.payload));
const response = yield apiCall(Api.userApi, Api.userApi.deleteUser,
username,
);
yield put(deleteUserSuccess());
return undefined;
} catch (error) {
if (markErrorsAsHandled) {error.wasHandled = true; }
yield put(deleteUserFailure({error, requestPayload: _action_.payload}));
return error;
}
}
//endregion
//region getUserByName
export interface PayloadGetUserByName extends PayloadGetUserByNameRequest, BaseEntitySupportPayloadApiAction {
}
export interface PayloadGetUserByNameRequest {
username: string;
}
export const getUserByNameRequest = createSagaAction<PayloadGetUserByNameRequest>("getUserByNameRequest");
export const getUserByNameSuccess = createSagaAction<UserRecord>("getUserByNameSuccess");
export const getUserByNameSuccess_Entities = createSagaAction<NormalizedRecordEntities>("getUserByNameSuccess_Entities");
export const getUserByNameFailure = createSagaAction<{error: any, requestPayload: PayloadGetUserByName}>("getUserByNameFailure");
export const getUserByName = createSagaAction<PayloadGetUserByName>("getUserByName");
export function *getUserByNameSaga() {
yield takeLatest(getUserByName, getUserByNameSagaImp);
}
export function *getUserByNameSagaImp(_action_: Action<PayloadGetUserByName>) {
const {markErrorsAsHandled, ..._payloadRest_} = _action_.payload;
try {
const {toEntities, toInlined = !toEntities, ...requestPayload} = _payloadRest_;
const {
username,
} = _payloadRest_;
yield put(getUserByNameRequest(requestPayload));
const response: Required<User> = yield apiCall(Api.userApi, Api.userApi.getUserByName,
username,
);
let successReturnValue: any = undefined;
if (toEntities) {
successReturnValue = userRecordUtils.fromApiArrayAsEntities([response]);
yield put(normalizedEntities(successReturnValue));
yield put(getUserByNameSuccess_Entities(successReturnValue));
}
if (toInlined) {
successReturnValue = userRecordUtils.fromApi(response);
yield put(getUserByNameSuccess(successReturnValue));
}
return successReturnValue;
} catch (error) {
if (markErrorsAsHandled) {error.wasHandled = true; }
yield put(getUserByNameFailure({error, requestPayload: _action_.payload}));
return error;
}
}
//endregion
//region loginUser
export interface PayloadLoginUser extends PayloadLoginUserRequest, BasePayloadApiAction {
}
export interface PayloadLoginUserRequest {
username: string;
password: string;
}
export const loginUserRequest = createSagaAction<PayloadLoginUserRequest>("loginUserRequest");
export const loginUserSuccess = createSagaAction<string>("loginUserSuccess");
export const loginUserFailure = createSagaAction<{error: any, requestPayload: PayloadLoginUser}>("loginUserFailure");
export const loginUser = createSagaAction<PayloadLoginUser>("loginUser");
export function *loginUserSaga() {
yield takeLatest(loginUser, loginUserSagaImp);
}
export function *loginUserSagaImp(_action_: Action<PayloadLoginUser>) {
const {markErrorsAsHandled, ..._payloadRest_} = _action_.payload;
try {
const {
username,
password,
} = _payloadRest_;
yield put(loginUserRequest(_action_.payload));
const response: Required<string> = yield apiCall(Api.userApi, Api.userApi.loginUser,
username,
password,
);
let successReturnValue: any = undefined;
yield put(loginUserSuccess(response));
return response;
} catch (error) {
if (markErrorsAsHandled) {error.wasHandled = true; }
yield put(loginUserFailure({error, requestPayload: _action_.payload}));
return error;
}
}
//endregion
//region logoutUser
export interface PayloadLogoutUser extends BasePayloadApiAction {
}
export const logoutUserRequest = createSagaAction<void>("logoutUserRequest");
export const logoutUserSuccess = createSagaAction<void>("logoutUserSuccess");
export const logoutUserFailure = createSagaAction<{error: any, requestPayload: PayloadLogoutUser}>("logoutUserFailure");
export const logoutUser = createSagaAction<PayloadLogoutUser>("logoutUser");
export function *logoutUserSaga() {
yield takeLatest(logoutUser, logoutUserSagaImp);
}
export function *logoutUserSagaImp(_action_: Action<PayloadLogoutUser>) {
const {markErrorsAsHandled, ..._payloadRest_} = _action_.payload;
try {
yield put(logoutUserRequest());
const response = yield apiCall(Api.userApi, Api.userApi.logoutUser,
);
yield put(logoutUserSuccess());
return undefined;
} catch (error) {
if (markErrorsAsHandled) {error.wasHandled = true; }
yield put(logoutUserFailure({error, requestPayload: _action_.payload}));
return error;
}
}
//endregion
//region updateUser
export interface PayloadUpdateUser extends PayloadUpdateUserRequest, BasePayloadApiAction {
}
export interface PayloadUpdateUserRequest {
username: string;
body: UserRecord;
}
export const updateUserRequest = createSagaAction<PayloadUpdateUserRequest>("updateUserRequest");
export const updateUserSuccess = createSagaAction<void>("updateUserSuccess");
export const updateUserFailure = createSagaAction<{error: any, requestPayload: PayloadUpdateUser}>("updateUserFailure");
export const updateUser = createSagaAction<PayloadUpdateUser>("updateUser");
export function *updateUserSaga() {
yield takeLatest(updateUser, updateUserSagaImp);
}
export function *updateUserSagaImp(_action_: Action<PayloadUpdateUser>) {
const {markErrorsAsHandled, ..._payloadRest_} = _action_.payload;
try {
const {
username,
body,
} = _payloadRest_;
yield put(updateUserRequest(_action_.payload));
const response: Required<DefaultMetaOnlyResponse> = yield apiCall(Api.userApi, Api.userApi.updateUser,
username,
userRecordUtils.toApi(body),
);
yield put(updateUserSuccess());
return undefined;
} catch (error) {
if (markErrorsAsHandled) {error.wasHandled = true; }
yield put(updateUserFailure({error, requestPayload: _action_.payload}));
return error;
}
}
//endregion | the_stack |
import React, { ChangeEvent, FocusEvent, RefCallback } from "react";
import { Button } from "../Button";
import { colors } from "../colors";
import { IconArrowDown } from "../icons/IconArrowDown";
import { List } from "../List";
import { ListItem } from "../ListItem";
import { ListHeading } from "../ListHeading";
import { ListDivider } from "../ListDivider";
import { Popover } from "../Popover";
import { useSelect, UseSelectPropGetters } from "downshift";
import { ClassNames, jsx } from "@emotion/core";
import {
reactNodeToDownshiftItems,
isHTMLOptionElement,
isHTMLOptgroupElement,
} from "./select/reactNodeToDownshiftItems";
import { ListConfigProvider, useListConfig } from "../ListConfig";
import { As, createElementFromAs } from "../shared/createElementFromAs";
import useDeepCompareEffect from "use-deep-compare-effect";
import { inputHeightDictionary } from "../shared/inputHeightDictionary";
import { useFormControlContext } from "../FormControl";
import { getEffectiveValueFromOptionElementProps } from "./select/getEffectiveValueFromOptionElementProps";
import { IconCheck } from "../icons/IconCheck";
export type OptionProps = React.DetailedHTMLProps<
React.OptionHTMLAttributes<HTMLOptionElement>,
HTMLOptionElement
>;
// This is defined in it's own interface so that both interfaces that will use
// it can `extend` this interface, therefore automatically including the jsdoc
// in both types.
interface RenderListItemProps {
/**
* Custom function to render each `ListItem`
*
* This is provided so you can render the `ListItem` on your own, with an `as`
* prop, for example, so you can render a `Link`.
*
* The function will be called and it's return value rendered; this does not
* use `React.createElement`, so an inline function is totally acceptable with
* no performance penalty.
*
* @default `(props) => <ListItem {...props} />`
*
*
* @param props - Props that were going to be passed to the underlying
*`ListItem`. You must merge this with whatever you are going to render.
* @param optionElement - The `option` element that is going to be parsed and
* rendered as a `ListItem`.
*
* You can use this to get the props you passed to the `option` element so you
* can customize behavior. For example, you can use this to extract the
* `option`'s `value` prop and generate a custom URL with `Link` element.
*/
renderListItem: (
props: React.ComponentProps<typeof ListItem>,
optionElement: React.ReactElement<
React.DetailedHTMLProps<
React.OptionHTMLAttributes<HTMLOptionElement>,
HTMLOptionElement
>,
"option"
>,
) => React.ReactElement<React.ComponentProps<typeof ListItem>>;
}
interface ListItemWrapperProps
extends Pick<Props, "selectionIndicator">,
RenderListItemProps {
/** `items` prop passed to `useSelect`
*
* We'll use this to get the index
*/
downshiftItems: OptionProps[];
element: React.ReactElement<OptionProps, "option">;
/** Passthrough downshift function to get the props for an item */
getItemProps: UseSelectPropGetters<OptionProps>["getItemProps"];
selected: boolean;
className?: string;
}
/**
* Abstraction to handle rendering `ListItem`s with downshift props
*/
const ListItemWrapper: React.FC<ListItemWrapperProps> = ({
downshiftItems,
element,
getItemProps,
renderListItem,
selected,
selectionIndicator,
className,
}) => {
const index = downshiftItems.indexOf(element.props);
if (index === -1) {
throw new Error(
"Development error: props must be passed by reference in `reactNodeToDownshiftItems` so they can be found with `Array.prototype.indexOf`",
);
}
const downshiftItemProps = getItemProps({
item: element.props,
index: downshiftItems.indexOf(element.props),
disabled: element.props.disabled,
});
return (
<ClassNames>
{({ css, cx }) => {
return renderListItem(
{
className: cx(css({ alignItems: "baseline" }), className),
key: element.props.value || element.props.children,
...downshiftItemProps,
highlighted: downshiftItemProps["aria-selected"] === "true",
selected,
startIcon:
selectionIndicator === "checkmark" ? (
selected ? (
<IconCheck css={{ height: "100%", width: "100%" }} />
) : null
) : undefined,
children: element.props.children,
},
element,
);
}}
</ClassNames>
);
};
interface Props
extends Pick<
React.ComponentProps<typeof Popover>,
| "disabled"
| "maxWidth"
| "placement"
| "popperOptions"
| "matchTriggerWidth"
>,
Pick<
React.ComponentProps<typeof Button>,
"aria-labelledby" | "aria-describedby" | "feel" | "style" | "color"
>,
Pick<
React.ComponentProps<typeof ListConfigProvider>,
"margin" | "truncate"
>,
Pick<
React.DetailedHTMLProps<
React.SelectHTMLAttributes<HTMLSelectElement>,
HTMLSelectElement
>,
"onBlur" | "onChange" | "name"
>,
Partial<RenderListItemProps> {
/**
* class name to apply to the trigger component
*/
className?: string;
/**
* `RefCallback` for props that should be spread onto a `label` component
* associated with this `Select`.
*
* The value will be calculated internally by `downshift`; so get the value
* and call this callback. This callback will only be called when the values
* change by a deep comparission (via
* [`use-deep-compare-effect`](https://github.com/kentcdodds/use-deep-compare-effect));
* not by `Object.is`. Therefore it's safe to save this entire value in state
* and spread it onto a label without fear of more than one re-render.
*
* Example:
*
* ```
* import * as React from 'react';
*
* export const SelectWithLabel: React.FC = () => {
* const [labelProps, setLabelProps] = React.useState();
*
* return (
* <React.Fragment>
* <label {...labelProps}>select label</label>
* <Select
* labelPropsCallbackRef={setLabelProps}
* ...
* >
* ...
* </Select>
* </React.Fragment>
* );
* }
* ```
*/
labelPropsCallbackRef?: RefCallback<
ReturnType<UseSelectPropGetters<OptionProps>["getLabelProps"]>
>;
/**
* ID is an optional field used to formulaicly add accessability props as
* follows:
*
* - The trigger button will be given the this `id`
* - The list will be given ```${id}-menu```
*
* If this field is not included or is `undefined`, the automatic downshift
* props will be used.
*
* The list and trigger button will also be assigned the value of
* `aria-labelledby`
*/
id?: string | undefined;
/**
* Used to override how the underlying `List` is rendered
*
* This is useful when need to customize the list behavior
*
* @default <List />
*/
listAs?: React.ReactElement<React.ComponentProps<typeof List>>;
/**
* Render prop function to generate a `React.ReactNode` based on the currently
* selected value.
*
* This is useful when you want some custom behavior with what is shown in the
* select in the unopened state.
*/
renderTriggerNode?: (value: OptionProps | null) => React.ReactNode;
triggerAs?: As;
/**
* Item currently selected
*
* While I believe it's also valid to use the `<option>`'s `selected` prop; we
* are not using that here. We _might_ use that if we render a native `select`
* element in the future.
*/
value?: NonNullable<OptionProps["value"]> | null;
/** Initial value for a non-controlled component */
defaultValue?: NonNullable<OptionProps["value"]> | null;
/**
* Indicates decoration for the selected item
*
* Note, this is for an item that is selected; _not_ the item that is
* highlighted.
*
* Options:
*
* * `checkmark` will place a checkmark to the left
*/
selectionIndicator?: "checkmark" | null;
size?: keyof typeof inputHeightDictionary;
}
export const Select: React.FC<Props> = ({
children,
className,
defaultValue,
disabled = false,
feel,
color = colors.white,
labelPropsCallbackRef,
listAs = <List startIconAs={<div css={{ alignSelf: "baseline" }} />} />,
margin = "auto",
matchTriggerWidth,
onBlur,
onChange,
placement = "bottom-start",
popperOptions,
renderListItem = (props) => <ListItem {...props} />,
renderTriggerNode = (value) => <>{value?.children || ""}</>,
selectionIndicator = null,
size = "standard",
triggerAs = <Button />,
truncate = true,
value: valueProp,
maxWidth,
...props
}) => {
const {
describedBy: formControlDescribedBy,
hasError,
id: formControlId,
labelledBy: formControlLabelledBy,
} = useFormControlContext();
const id = props.id ?? formControlId;
const describedBy = props["aria-describedby"] ?? formControlDescribedBy;
const labelledBy = props["aria-labelledby"] ?? formControlLabelledBy;
const [uncontrolledValue, setUncontrolledValue] = React.useState(
defaultValue ?? "",
);
// Validate controlled versus uncontrolled
if (
(typeof onChange !== "undefined" || typeof valueProp !== "undefined") &&
typeof defaultValue !== "undefined"
) {
// eslint-disable-next-line no-console
console.warn(
"Select component must be either controlled or uncontrolled. Pass either `defaultValue` for an uncontrolled component or `value` and optionally `onChange` for a controlled component.",
);
}
const value =
typeof valueProp !== "undefined" ? valueProp : uncontrolledValue;
/**
* Reference to the underlying popper instance
*
* We'll use this to control the popover's visbility based on events captured
* by downshift
*/
const instanceRef = React.useRef<
Parameters<NonNullable<React.ComponentProps<typeof Popover>["onCreate"]>>[0]
>();
const listConfig = useListConfig();
/**
* Items data represtented by the DOM structure in `children`
*/
const items = reactNodeToDownshiftItems(children);
/**
* Ref stored for a timeout that's initiated after a `ToggleButtonClick` state
* change. It'll automatically clear itself after the timeout. Use this ref
* containing a value to mean that there was a `ToggleButtonClick` state
* change in the last tick.
*/
const toggleButtonClickTimeout = React.useRef<number | undefined>();
/**
* Wrapper to call `onBlur`
*
* Will attempt to simulate a real event.
*/
const blur = () => {
const target = { ...props, value };
onBlur?.(({
type: "blur",
currentTarget: target,
target,
} as unknown) as FocusEvent<HTMLSelectElement>);
};
const {
getLabelProps,
getItemProps,
getMenuProps,
getToggleButtonProps,
selectedItem,
} = useSelect<OptionProps>({
stateReducer(state, actionAndChanges) {
switch (actionAndChanges.type) {
case useSelect.stateChangeTypes.MenuMouseLeave:
case useSelect.stateChangeTypes.MenuBlur: {
/**
* Indicates if the element that we "blur"'ed to is a descendent of
* the tooltip. If it is, then we should bypass the closing behavior.
*/
const popperContainsActiveElement = !!instanceRef.current?.popper?.contains(
document.activeElement,
);
return {
...actionAndChanges.changes,
isOpen: popperContainsActiveElement,
};
}
default:
return actionAndChanges.changes;
}
},
onStateChange(changes) {
switch (changes.type) {
case useSelect.stateChangeTypes.MenuMouseLeave:
case useSelect.stateChangeTypes.MenuBlur: {
/**
* Indicates if the element that we "blur"'ed to is a descendent of
* the tooltip. If it is, then we should bypass the closing behavior.
*/
const popperContainsActiveElement = !!instanceRef.current?.popper?.contains(
document.activeElement,
);
if (!popperContainsActiveElement) blur();
break;
}
case useSelect.stateChangeTypes.ToggleButtonClick:
window.clearTimeout(toggleButtonClickTimeout.current);
toggleButtonClickTimeout.current = window.setTimeout(() => {
toggleButtonClickTimeout.current = undefined;
}, 0);
break;
}
},
items,
scrollIntoView(node) {
// We have to defer this call until the popover has been created. I really
// don't have a great explanation for this; but this works and I can't see
// a downside because the extra complexity.
setTimeout(() => {
// It's silly to write code for our tests, but `scrollIntoView` doesn't
// exist in JSDOM, so we have to make sure we don't call it on tests or
// they'll break.
node.scrollIntoView?.({
behavior: "auto",
block: "nearest",
inline: "nearest",
});
}, 0);
},
selectedItem:
items.find((item) => {
return value === (item.value ?? item.children);
}) ?? null,
onSelectedItemChange: (event) => {
const newValue = event.selectedItem
? getEffectiveValueFromOptionElementProps(event.selectedItem)
: "";
if (onChange) {
// This is kind of hacky because there's no underlying `select` with
// native events firing. Maybe we should create them and then fire
// events?
const target = { ...props, value: newValue };
onChange(({
currentTarget: target,
target,
} as unknown) as ChangeEvent<HTMLSelectElement>);
} else {
setUncontrolledValue(newValue);
}
},
onIsOpenChange: (event) => {
if (event.isOpen) {
instanceRef.current?.show();
} else {
instanceRef.current?.hide();
}
},
});
// Get the label's props and call the callback ref when they change.
const labelProps = getLabelProps();
useDeepCompareEffect(() => {
labelPropsCallbackRef?.(labelProps);
}, [labelProps, labelPropsCallbackRef]);
return (
<ListConfigProvider {...listConfig} iconSize="small">
<ClassNames>
{({ css, cx }) => (
<Popover
popperOptions={popperOptions}
onCreate={(instance) => {
instanceRef.current = instance;
}}
content={React.cloneElement(
listAs,
{
margin,
truncate,
...getMenuProps(undefined, { suppressRefError: true }),
...(id && { id: `${id}-menu` }),
"aria-labelledby": labelledBy,
"aria-describedby": describedBy,
},
React.Children.toArray(children)
// Filter out falsy elements in `children`. We need to know if
// we're rendering the first actual element in `children` to
// know if we should add a divider or not. If the consumer uses
// conditional logic in their rendering then we could have
// `undefined` elements in `children`.
.filter(
(child): child is NonNullable<React.ReactNode> => !!child,
)
.map((child, topLevelIndex) => {
if (isHTMLOptionElement(child)) {
return (
<ListItemWrapper
className={child.props.className}
data-top-level-index={topLevelIndex}
downshiftItems={items}
element={child}
getItemProps={getItemProps}
renderListItem={renderListItem}
selected={selectedItem === child.props}
selectionIndicator={selectionIndicator}
key={getEffectiveValueFromOptionElementProps(
child.props,
)}
/>
);
} else if (isHTMLOptgroupElement(child)) {
return (
<React.Fragment key={child.props.label}>
{topLevelIndex > 0 && (
<ListDivider data-top-level-index={topLevelIndex} />
)}
{child.props.label && (
<ListHeading
aria-label={child.props.label}
role="group"
>
{child.props.label}
</ListHeading>
)}
{React.Children.map(
child.props.children as React.ReactElement<
OptionProps,
"option"
>[],
(optgroupChild) => {
return (
<ListItemWrapper
key={getEffectiveValueFromOptionElementProps(
optgroupChild.props,
)}
downshiftItems={items}
element={optgroupChild}
getItemProps={getItemProps}
renderListItem={renderListItem}
selectionIndicator={selectionIndicator}
selected={selectedItem === optgroupChild.props}
/>
);
},
)}
</React.Fragment>
);
}
return null;
}),
)}
hideOnClick={false}
placement={placement}
triggerEvents="manual"
matchTriggerWidth={matchTriggerWidth}
trigger={React.cloneElement(
createElementFromAs(triggerAs),
{
...getToggleButtonProps({ disabled }),
...props,
...(labelledBy && { "aria-labelledby": labelledBy }),
id,
className: cx(
css({
border: hasError
? `1px solid ${colors.red.base}`
: undefined,
textAlign: "left",
}),
className,
React.isValidElement(triggerAs) &&
(triggerAs.props as any).className,
),
color,
feel,
onBlur() {
if (toggleButtonClickTimeout.current) {
// There was a `ToggleButtonClick` state change in the last
// tick, so ignore this blur call.
return;
}
blur();
},
type: "button",
size,
endIcon: (
<IconArrowDown
className={css({ height: "70%" })}
weight="thin"
/>
),
},
<div
className={css({
flex: 1,
overflow: "hidden",
whiteSpace: "nowrap",
textOverflow: "ellipsis",
})}
>
{renderTriggerNode(selectedItem)}
</div>,
)}
maxWidth={maxWidth}
/>
)}
</ClassNames>
</ListConfigProvider>
);
}; | the_stack |
import { Component, OnInit, OnDestroy, ViewEncapsulation } from '@angular/core';
import * as d3 from 'd3';
import * as d3Sankey from 'd3-sankey';
import { DAG, SNode, GraphService, CategoryList, FilterCriteria } from '../graph.service';
import { DialogsService } from './../dialogs.service';
import { GraphTab } from "../GraphTab";
import { GraphFilter } from "../GraphFilter";
import { Searchable } from "../Searchable";
import { FullDocNode, Note } from '../standard-map';
import { DomSanitizer } from '@angular/platform-browser';
import { debounce } from 'rxjs/operators';
import * as Rx from 'rxjs';
import { TreeModel, TreeNode, ITreeState } from 'angular-tree-component';
import selection_attrs from 'd3-selection-multi/src/selection/attrs';
d3.selection.prototype.attrs = selection_attrs;
class TableData
{
constructor(
public headers: string[],
public rows: SNode[][]) {
}
}
@Component({
selector: 'app-graph',
templateUrl: './graph.component.html',
styleUrls: [ './graph.component.css' ],
encapsulation: ViewEncapsulation.None // Allow D3 to read styles through shadow DOM
})
export class GraphComponent implements OnInit, OnDestroy {
public graphType: number = 0;
public graphData: DAG;
public graphCategories: CategoryList = [];
public graphCriteria = new FilterCriteria();
public tableData: TableData = null;
public complianceColors = ["white", "green", "yellow", "red", "black"];
public svgbgElement: any;
private searchable: Searchable;
public hideFilter: boolean = false;
private graphColorScale = d3.scaleOrdinal().range(d3.schemeSet3);
constructor(
public graphService: GraphService,
public dialogService: DialogsService,
private sanitizer: DomSanitizer) {
this.graphService.updateSubject.pipe(debounce(() => Rx.timer(1))).subscribe({
next: (v) => this.updateGraph()
});
this.graphService.updateViewSubject.pipe(debounce(() => Rx.timer(1))).subscribe({
next: (v) => this.updateGraphView()
});
this.searchable = new Searchable();
};
ngOnInit(): void {
this.graphService.getDocTypes()
.subscribe(dt => {
this.graphCategories = dt;
});
}
ngOnDestroy(): void {
}
public getMenuOptions(): any[] {
var result = [];
if (this.graphService.canAdd)
{
for (var t of this.graphCategories)
if (!this.graphService.graphTabs.find(g => g.id == t.id))
result.push(t);
}
return result;
}
//private DrawTable(data: DAG) {
// var rowType = this.graphCriteria.categoryOrder ? this.graphCriteria.categoryOrder[0] : (data.nodes[0] as SNode).data.type;
// var headerTypes = this.graphCriteria.categoryOrder.filter(v => v != rowType);
// var headerNodes = [rowType].concat(headerTypes);
// var rowNodes = data.nodes.filter(v => v.data.type == rowType).map(d => {
// var links = headerTypes.map(h => {
// for (var l of data.links)
// {
// var node = null;
// if (l.source == d.nodeId && l.targetNode.data.type == h)
// node = l.targetNode;
// if (l.target == d.nodeId && l.sourceNode.data.type == h)
// node = l.sourceNode;
// if (node)
// return node;
// }
// return null;
// });
// return [d].concat(links);
// });
// var width = 960;
// var height = 500;
// // clear
// d3.selectAll("#d3").selectAll("*").remove();
// this.tableData = new TableData(headerNodes, rowNodes);
//}
//private DrawChart(energy: DAG) {
// var width = 960;
// var height = 500;
// // clear
// d3.selectAll("#d3").selectAll("*").remove();
// this.tableData = null;
// var svg = d3.selectAll("#d3").append("svg");
// svg.attr("width", width);
// svg.attr("height", height);
// var formatNumber = d3.format(",.0f"),
// format = function (d: any) { return formatNumber(d) + " TWh"; },
// color = d3.scaleOrdinal(d3.schemeCategory10);
// var sankey = d3Sankey.sankey()
// .nodeWidth(15)
// .nodePadding(10)
// .extent([[1, 1], [width - 1, height - 6]]);
// var link = svg.append("g")
// .attr("class", "links")
// .attr("fill", "none")
// .attr("stroke", "#000")
// .attr("stroke-opacity", 0.2)
// .selectAll("path");
// var node = svg.append("g")
// .attr("class", "nodes")
// .attr("font-family", "sans-serif")
// .attr("font-size", 10)
// .selectAll("g");
// sankey.nodeAlign(d3Sankey.sankeyLeft);
// //sankey.nodeAlign((n, d) => {
// // return this.graphCriteria.categoryOrder.indexOf(n.data.type);
// //});
// sankey.nodeSort((a: SNode, b: SNode) => a.name < b.name ? -1 : 1);
// sankey.nodeId((d: SNode) => d.nodeId);
// sankey.nodeWidth(250);
// sankey(energy);
// link = link
// .data(energy.links);
// link.enter().append("path")
// .attr("d", d3Sankey.sankeyLinkHorizontal())
// .attr("stroke-width", function (d: any) { return 10; }) //Math.max(1, d.width) * 0.; })
// .attr("stroke", d => "black") //color(d.source.name))
// .on('click', function(d, i) {
// console.log("clicked link", d);
// })
// .on("mouseover", function(d) {
// d3.select(this).style("cursor", "pointer");
// });
// link.append("title")
// .text(function (d: any) { return d.source.name + " → " + d.target.name + "\n" + format(d.value) + "\n" + d.uom; });
// node = node
// .data(energy.nodes)
// .enter().append("g");
// node.append("rect")
// .attr("x", function (d: any) { return d.x0; })
// .attr("y", function (d: any) { return d.y0; })
// .attr("height", function (d: any) { return d.y1 - d.y0; })
// .attr("width", function (d: any) { return d.x1 - d.x0; })
// .attr("fill", d => { return this.complianceColors[energy.nodes[d.index].data.compliance_level]; } ) //color(d.name.replace(/ .*/, "")); })
// .attr("stroke", "#000")
// .on('click', function(d, i) {
// console.log("clicked node", d);
// })
// .on("mouseover", function(d) {
// d3.select(this).style("cursor", "pointer");
// });
// node.append("text")
// .attr("x", function (d: any) { return d.x0 + 6; }) //{ return d.x0 - 6; })
// .attr("y", function (d: any) { return (d.y1 + d.y0) / 2; })
// .attr("dy", "0.35em")
// .attr("text-anchor", "start")
// .text(function (d: any) { return d.name + "\n" + d.data.getBody(); });
// //.filter(function (d: any) { return d.x0 < width / 2; })
// //.attr("x", function (d: any) { return d.x1 + 6; })
// //.attr("text-anchor", "start");
// node.append("title")
// .text(function (d: any) { return d.name + "\n" + d.data.getBody(); });
//}
//private DrawGraph(data: DAG) {
// var width = 960;
// var height = 500;
// // clear
// d3.selectAll("#d3").selectAll("*").remove();
// this.tableData = null;
// var svg = d3.selectAll("#d3").append("svg");
// svg.attr("width", width);
// svg.attr("height", height);
// var link, node, edgelabels, edgepaths;
// var colors = d3.scaleOrdinal(d3.schemeCategory10);
// svg.append('defs').append('marker')
// .attrs({'id':'arrowhead',
// 'viewBox':'-0 -5 10 10',
// 'refX':13,
// 'refY':0,
// 'orient':'auto',
// 'markerWidth':13,
// 'markerHeight':13,
// 'xoverflow':'visible'})
// .append('svg:path')
// .attr('d', 'M 0,-5 L 10 ,0 L 0,5')
// .attr('fill', '#999')
// .style('stroke','none');
// var simulation = d3.forceSimulation()
// .force("link", d3.forceLink().id(function (d) {return d.nodeId;}).distance(100).strength(1))
// .force("charge", d3.forceManyBody())
// .force("center", d3.forceCenter(width / 2, height / 2));
// update(data.links, data.nodes);
// function update(links, nodes) {
// link = svg.selectAll(".link")
// .data(links)
// .enter()
// .append("line")
// .attr("class", "link")
// .attr('marker-end','url(#arrowhead)');
// link.append("title")
// .text(function (d) {return ""; }); //d.type;});
// edgepaths = svg.selectAll(".edgepath")
// .data(links)
// .enter()
// .append('path')
// .attrs({
// 'class': 'edgepath',
// 'fill-opacity': 0,
// 'stroke-opacity': 0,
// 'id': function (d, i) {return 'edgepath' + i}
// })
// .style("pointer-events", "none");
// edgelabels = svg.selectAll(".edgelabel")
// .data(links)
// .enter()
// .append('text')
// .style("pointer-events", "none")
// .attrs({
// 'class': 'edgelabel',
// 'id': function (d, i) {return 'edgelabel' + i},
// 'font-size': 10,
// 'fill': '#aaa'
// });
// edgelabels.append('textPath')
// .attr('xlink:href', function (d, i) {return '#edgepath' + i})
// .style("text-anchor", "middle")
// .style("pointer-events", "none")
// .attr("startOffset", "50%")
// .text(function (d) {return ""; });
// node = svg.selectAll(".node")
// .data(nodes)
// .enter()
// .append("g")
// .attr("class", "node")
// .call(d3.drag()
// .on("start", dragstarted)
// .on("drag", dragged)
// //.on("end", dragended)
// );
// node.append("circle")
// .attr("r", 5)
// .style("fill", function (d, i) {return colors(i);})
// node.append("title")
// .text(function (d) {return d.nodeId;});
// node.append("text")
// .attr("dy", -3)
// .text(function (d) {return d.name;});
// simulation
// .nodes(nodes)
// .on("tick", ticked);
// simulation.force("link")
// .links(links);
// }
// function ticked() {
// link
// .attr("x1", function (d) {return d.source.x;})
// .attr("y1", function (d) {return d.source.y;})
// .attr("x2", function (d) {return d.target.x;})
// .attr("y2", function (d) {return d.target.y;});
// node
// .attr("transform", function (d) {return "translate(" + d.x + ", " + d.y + ")";});
// edgepaths.attr('d', function (d) {
// return 'M ' + d.source.x + ' ' + d.source.y + ' L ' + d.target.x + ' ' + d.target.y;
// });
// edgelabels.attr('transform', function (d) {
// if (d.target.x < d.source.x) {
// var bbox = this.getBBox();
// var rx = bbox.x + bbox.width / 2;
// var ry = bbox.y + bbox.height / 2;
// return 'rotate(180 ' + rx + ' ' + ry + ')';
// }
// else {
// return 'rotate(0)';
// }
// });
// }
// function dragstarted(d) {
// if (!d3.event.active) simulation.alphaTarget(0.3).restart()
// d.fx = d.x;
// d.fy = d.y;
// }
// function dragged(d) {
// d.fx = d3.event.x;
// d.fy = d3.event.y;
// }
//}
public tabChanged() {
this.graphService.tabChanged();
}
public activateNode(tab: GraphTab, event: any) {
if (tab.column.treeModel) {
var newSelection = {};
newSelection[tab.column.state.focusedNodeId] = true; // single select
tab.column.state.activeNodeIds = newSelection;
this.graphService.updateSubject.next(0);
}
}
public onResize(event) {
//event.target.innerWidth;
this.graphService.updateViewSubject.next(0);
}
private buildLinkSet(fromTab: GraphTab, toTab: GraphTab, rtl: boolean): void {
// For all the links that are not filtered already
var links = fromTab.visibleLinks;
// make a hash table from source _root_ node id, to list of links.
// The source _root_ node is the first node in the ascenstery that is visible (parent is not collpased)
var rollup = links.reduce((a, b) => {
var owner = b.fromNode;
// Iterate to root, keep track of highest collapsed node.
var iterator = owner;
while (iterator.realParent)
{
iterator = iterator.realParent;
if (iterator.isCollapsed)
owner = iterator;
}
// Create the list if it doesnt exist
if (!(owner.id in a))
a[owner.id] = [];
// add the link
a[owner.id].push(b);
return a;
}, { });
var destinationHits = { };
var fromTree = fromTab.treeModel;
var toTree = toTab.treeModel;
// for each source root node, aggregate links to destination root nodes
// destination _root_ nodes are the first node in the ascenstery that is visible (parent is not collpased)
var rollup2 = Object.keys(rollup).map(k => {
var collapsed = rollup[k].reduce((a, b) => {
var link = b.link;
var owner = toTree.getNodeById(link.id);
if (!owner) {
toTab.parent.errors["- node not found: " + link.id + ", Referenced from: " + b.fromNode.id] = true;
return a;
}
// Iterate to root, keep track of highest collapsed node.
var iterator = owner;
while (iterator.realParent)
{
iterator = iterator.realParent;
if (iterator.isCollapsed)
owner = iterator;
}
// Create the list if it doesnt exist
if (!(owner.id in a))
a[owner.id] = [];
// add the link
a[owner.id].push(link);
// Create the list if it doesnt exist
if (!(owner.id in destinationHits))
destinationHits[owner.id] = {};
// add the link
var hitsMap = destinationHits[owner.id];
if (!(k in hitsMap))
hitsMap[k] = { k: k, top: fromTree.getNodeById(k).elementRef2.getBoundingClientRect().top };
return a;
}, { });
return [k, collapsed];
});
for (var h in destinationHits) {
var list = destinationHits[h];
destinationHits[h] = Object.keys(list).map(v => list[v]).sort((a, b) => a.top - b.top);
}
// Create one aggregated list of links with all the necessary parameters for the view
// start with the links map from source root node, to destination root nodes
var flatten = rollup2.reduce((a, b) => {
var destinationMap = b[1];
var fromKey = b[0];
var fromNode: TreeNode = fromTree.getNodeById(fromKey);
// If the source node is hidden, continue.
if (fromNode.id in fromTree.hiddenNodeIds)
return a;
var srcNodes = Object.keys(destinationMap).map(v => {
var node = toTree.getNodeById(v);
var bounds = (node&&node.elementRef2) ? node.elementRef2.getBoundingClientRect().top : 0;
return { key: v, node: node, y: bounds };
});
//srcNodes.sort((a, b) => a.y - b.y);
var srcScale = 1/srcNodes.length;
var srcIndex = 0;
// one source node may map to many destination.
for (var destinationNode of srcNodes)
{
var toNode = destinationNode.node;
var destinationKey = destinationNode.key;
if (!(toNode.id in toTree.hiddenNodeIds))
{
var dstHitKeys = destinationHits[destinationKey];
//var destinationData = destinationMap[destinationKey];
//var dstHitKeys = Object.keys(destinationHit);
var dstScale = 1/dstHitKeys.length;
var dstIndex = dstHitKeys.findIndex(v => v.k == fromKey);
// store a refrence to the connections in the source node.
fromNode.data.connectedTo[destinationKey] = true;
a.push({
from: fromKey,
fromNode: fromNode,
to: destinationKey,
toNode: toNode,
fromTree: fromTree,
toTree: toTree,
rtl: rtl,
scale: rtl ? -1 : 1,
weight: (fromNode.isActive || toNode.isActive) ? 2 : 1,
x1: 0,
x2: 0,
x3: 0,
x4: 0,
y1: 0,
y2: 0,
d: "",
color: "#000",
srcScale: srcScale,
srcIndex: srcIndex++,
dstScale: dstScale,
dstIndex: dstIndex
});
}
}
return a;
}, []);
fromTab.displayLinks = flatten;
}
public updateGraph() {
var tabs = this.graphService.graphTabs;
// delay the rendering so dom can settle.
//setTimeout(a => {
var isoTab = tabs.find(t => t.isIso);
var isoIndex = tabs.indexOf(isoTab);
for (var t = 0; t < tabs.length; ++t)
{
var tab = tabs[t];
if (tab != isoTab)
this.buildLinkSet(tab.column, isoTab.column, t > isoIndex);
}
this.graphService.updateViewSubject.next(0);
//}, 1);
}
public updateGraphView() {
if (!this.svgbgElement)
return;
var tabs = this.graphService.graphTabs;
var startingGapLeft = 0;
var startingGapRight = 0;
var arrowLength = 0;
var svgBounds = this.svgbgElement.getBoundingClientRect();
var colorIndex = 0;
if (!this.graphService.visualStyle) {
// legacy style
startingGapRight = 10;
arrowLength = 10;
}
for (var tab of tabs)
{
for (var l of tab.column.displayLinks)
{
var fromBounds = l.fromNode.elementRef2.getBoundingClientRect();
var toBounds = l.toNode.elementRef2.getBoundingClientRect();
l.x1 = (l.rtl ? (fromBounds.left - startingGapRight) : (fromBounds.right + startingGapLeft)) - svgBounds.left;
l.x2 = (l.rtl ? (toBounds.right + arrowLength) : (toBounds.left - arrowLength)) - svgBounds.left;
l.y1 = fromBounds.top - svgBounds.top + fromBounds.height * 0.5;
l.y2 = toBounds.top - svgBounds.top + toBounds.height * 0.5;
// Locations for the arrow head
l.x3 = l.x2 - 2 * l.scale;
l.x4 = l.x2 + 0.1 * l.scale;
// bezier based path
var p1yDiff = fromBounds.height * l.srcScale;
var p2yDiff = toBounds.height * l.dstScale;
var horzSpan = l.x2 - l.x1;
var controlLength = horzSpan * 0.5;
var p1x = l.x1;
var p1y = fromBounds.top - svgBounds.top + fromBounds.height * l.srcScale * l.srcIndex;
var c1x = p1x + controlLength;
var c1y = p1y;
var p2x = l.x2;
var p2y = toBounds.top - svgBounds.top + toBounds.height * l.dstScale * l.dstIndex
var c2x = p2x - controlLength;
var c2y = p2y;
l.color = this.graphColorScale(colorIndex++);
l.d = `M ${p1x},${p1y} ` // Move to start
+ `C ${ c1x },${ c1y }, ${ c2x },${ c2y }, ${ p2x },${ p2y } ` // Bezier the top edge
+ `L ${ p2x },${ p2y + p2yDiff } ` // Line to the thickness
+ `C ${ c2x },${ c2y + p2yDiff }, ${ c1x },${ c1y + p1yDiff }, ${ p1x },${ p1y + p1yDiff }`; // Bezier back the bottom edge
}
}
}
public setup(data, treeElement) {
data.treeModel = treeElement.treeModel;
treeElement.viewportComponent.elementRef.nativeElement.addEventListener('scroll', t => this.updateGraphView());
}
public clickedLink(link: any) {
link.fromTree.getNodeById(link.from).expandAll();
link.toTree.getNodeById(link.to).expandAll();
}
public bindTogether(node, element, svgbg, checkBox, tab: GraphTab) {
node.elementRef2 = element;
this.svgbgElement = svgbg;
if (checkBox)
tab.inputObjectsMap[checkBox.id] = checkBox;
}
public openTab(url: string)
{
window.open(url, "_blank").focus();
}
public filterMapped(tab: GraphTab)
{
tab.filterMapped();
this.graphService.activateTab(tab);
}
public filterIsoCoverage(tab: GraphTab)
{
var isoTab = this.graphService.graphTabs[1];
isoTab.filterToIds(tab.coverage.uncoveredIds);
this.graphService.activateTab(isoTab);
}
private onKeyDown(tab: GraphTab, node: TreeNode, event: any) {
switch (event.code)
{
case "Digit1":
{
if (event.shiftKey)
this.toggleTree(0, tab);
}
break;
case "Digit2":
{
if (event.shiftKey)
this.toggleTree(1, tab);
}
break;
case "Digit3":
{
if (event.shiftKey)
this.toggleTree(2, tab);
}
break;
case "ArrowRight":
{
if (event.shiftKey)
this.nextTree(node, tab, event);
else
GraphComponent.descendTree(node, tab, event);
event.preventDefault();
event.stopPropagation();
}
break;
case "ArrowLeft":
{
if (event.shiftKey)
this.prevTree(node, tab, event);
else
GraphComponent.ascendTree(node, tab, event);
event.preventDefault();
event.stopPropagation();
}
break;
case "ArrowDown": GraphComponent.moveFocusUpDown(tab, node, 1); break;
case "ArrowUp": GraphComponent.moveFocusUpDown(tab, node, -1); break;
case "Home":
{
var root = node.treeModel.getVisibleRoots()[0];
if (root) {
GraphComponent.selectInputById(tab, root.id);
event.preventDefault();
}
}
break;
}
}
private nextTree(node: TreeNode, tab: GraphTab, event: any) {
if (!tab.parent) {
//we're in filter tab
this.activateTree(0, true);
}
else {
var currentIndex = this.graphService.graphTabs.indexOf(tab.parent);
if (currentIndex < this.graphService.graphTabs.length - 1) {
this.activateTree(currentIndex + 1, true);
}
}
}
private prevTree(node: TreeNode, tab: GraphTab, event: any) {
if (!tab.parent) {
//we're in filter tab
// no prev tree
}
else {
var currentIndex = this.graphService.graphTabs.indexOf(tab.parent);
if (currentIndex > 0) {
this.activateTree(currentIndex - 1, true);
}
else {
this.activateTree(this.graphService.selectedTab, false);
}
}
}
private activateTree(index: number, graph: boolean) {
var tab = this.graphService.graphTabs[index];
var finalize = Promise.resolve(true);
if (graph)
tab = tab.column;
else if (this.graphService.selectedTab != index)
finalize = this.graphService.activateTab(tab);
finalize.then(v => {
var nextId = tab.treeModel.getVisibleRoots()[0].id
GraphComponent.selectInputById(tab, nextId);
});
}
private toggleTree(index: number, tab: GraphTab) {
if (index > this.graphService.graphTabs.length - 1)
return; // invalid index
if (!tab.parent) {
//we're in filter tab
if (index != this.graphService.selectedTab)
this.activateTree(index, false); // jump to this tab in filter
else
this.activateTree(index, true); // jump to this tab in graph
}
else {
//we're in graph tab
var currentIndex = this.graphService.graphTabs.indexOf(tab.parent);
if (index != currentIndex)
this.activateTree(index, true); // jump to this tab in graph
else
this.activateTree(index, false); // jump to this tab in filter
}
}
static ascendTree(node: TreeNode, tab: GraphTab, event: any) {
if (node.parent) {
// dont let them keyboard expand if we have a tab.parent, ie we are in the graph.
// expand is disabled in that view
if (!tab.parent)
node.collapse();
GraphComponent.selectInputById(tab, node.parent.id);
}
}
static descendTree(node: TreeNode, tab: GraphTab, event: any) {
if (node.visibleChildren.length > 0) {
// dont let them keyboard expand if we have a tab.parent, ie we are in the graph.
// expand is disabled in that view
if (!tab.parent)
node.expand();
if (node.isExpanded) {
GraphComponent.selectInputById(tab, node.visibleChildren[0].id);
}
}
}
static moveFocusUpDown(tab: GraphTab, node: TreeNode, amount: number) {
var index = node.parent.visibleChildren.findIndex(f => f.id == node.id);
if (index > -1) {
var newIndex = index + amount;
var nextItem = node.parent.visibleChildren[newIndex];
if (nextItem) {
GraphComponent.selectInputById(tab, nextItem.id);
}
}
}
static selectInputById(tab: GraphTab, nextId: any) {
var selectedObject = tab.inputObjectsMap[tab.id + '.cb.' + nextId];
if (selectedObject)
selectedObject.focus();
}
public toggleShowFilter() {
this.hideFilter = !this.hideFilter;
}
public onSliderChange(event) {
// Update the value in real time
this.graphService.visualZoom = event.value;
this.graphService.updateViewSubject.next(0);
}
public onStyleChange(event) {
this.graphService.updateViewSubject.next(0);
}
} | the_stack |
import type {Mutable, Class} from "@swim/util";
import {Affinity, MemberFastenerClass, Property} from "@swim/component";
import {AnyLength, Length, R2Box} from "@swim/math";
import {AnyExpansion, Expansion} from "@swim/style";
import {
Look,
Feel,
ThemeAnimator,
ExpansionThemeAnimator,
ThemeConstraintAnimator,
} from "@swim/theme";
import {
ViewportInsets,
PositionGestureInput,
ViewContextType,
ViewContext,
ViewFlags,
View,
ViewRef,
ViewSet,
} from "@swim/view";
import {HtmlView} from "@swim/dom";
import {AnyTableLayout, TableLayout} from "../layout/TableLayout";
import type {LeafView} from "../leaf/LeafView";
import {RowView} from "../row/RowView";
import {HeaderView} from "../header/HeaderView";
import type {TableViewContext} from "./TableViewContext";
import type {TableViewObserver} from "./TableViewObserver";
/** @public */
export class TableView extends HtmlView {
constructor(node: HTMLElement) {
super(node);
this.visibleViews = [];
this.visibleFrame = new R2Box(0, 0, window.innerWidth, window.innerHeight);
this.initTable();
}
protected initTable(): void {
this.addClass("table");
this.position.setState("relative", Affinity.Intrinsic);
this.backgroundColor.setLook(Look.backgroundColor, Affinity.Intrinsic);
}
override readonly observerType?: Class<TableViewObserver>;
override readonly contextType?: Class<TableViewContext>;
@Property({type: TableLayout, inherits: true, value: null, updateFlags: View.NeedsLayout})
readonly layout!: Property<this, TableLayout | null, AnyTableLayout | null>;
@Property({type: Object, inherits: true, value: null, updateFlags: View.NeedsLayout})
readonly edgeInsets!: Property<this, ViewportInsets | null>;
@Property<TableView, number>({
type: Number,
inherits: true,
value: 0,
updateFlags: View.NeedsLayout,
didSetValue(newDepth: number, oldDepth: number): void {
this.owner.modifyTheme(Feel.default, [[Feel.nested, newDepth !== 0 ? 1 : void 0]], false);
},
})
readonly depth!: Property<this, number>;
@ThemeConstraintAnimator({type: Length, inherits: true, value: Length.zero(), updateFlags: View.NeedsLayout})
readonly rowSpacing!: ThemeConstraintAnimator<this, Length, AnyLength>;
@ThemeConstraintAnimator({type: Length, inherits: true, value: Length.px(24), updateFlags: View.NeedsLayout})
readonly rowHeight!: ThemeConstraintAnimator<this, Length, AnyLength>;
@Property({type: Boolean, inherits: true, value: false})
readonly hovers!: Property<this, boolean>;
@Property({type: Boolean, inherits: true, value: true})
readonly glows!: Property<this, boolean>;
@ThemeAnimator({type: Expansion, inherits: true, value: null})
readonly disclosure!: ExpansionThemeAnimator<this, Expansion | null, AnyExpansion | null>;
@ThemeAnimator({type: Expansion, inherits: true, value: null})
readonly disclosing!: ExpansionThemeAnimator<this, Expansion | null, AnyExpansion | null>;
@ThemeAnimator({type: Expansion, inherits: true, value: null, updateFlags: View.NeedsLayout})
readonly stretch!: ExpansionThemeAnimator<this, Expansion | null, AnyExpansion | null>;
@ViewRef<TableView, HeaderView>({
key: true,
type: HeaderView,
binds: true,
initView(headerView: HeaderView): void {
headerView.display.setState("none", Affinity.Intrinsic);
headerView.position.setState("absolute", Affinity.Intrinsic);
headerView.left.setState(0, Affinity.Intrinsic);
headerView.top.setState(null, Affinity.Intrinsic);
const layout = this.owner.layout.value;
headerView.width.setState(layout !== null ? layout.width : null, Affinity.Intrinsic);
headerView.setCulled(true);
},
willAttachView(headerView: HeaderView): void {
this.owner.callObservers("viewWillAttachHeader", headerView, this.owner);
},
didDetachView(headerView: HeaderView): void {
this.owner.callObservers("viewDidDetachHeader", headerView, this.owner);
},
insertChild(parent: View, child: HeaderView, target: View | number | null, key: string | undefined): void {
parent.prependChild(child, key);
}
})
readonly header!: ViewRef<this, HeaderView>;
static readonly header: MemberFastenerClass<TableView, "header">;
@ViewSet<TableView, RowView>({
type: RowView,
binds: true,
observes: true,
initView(rowView: RowView): void {
rowView.display.setState("none", Affinity.Intrinsic);
rowView.position.setState("absolute", Affinity.Intrinsic);
rowView.left.setState(0, Affinity.Intrinsic);
rowView.top.setState(null, Affinity.Intrinsic);
const layout = this.owner.layout.value;
rowView.width.setState(layout !== null ? layout.width : null, Affinity.Intrinsic);
rowView.setCulled(true);
},
willAttachView(rowView: RowView, target: View | null): void {
this.owner.callObservers("viewWillAttachRow", rowView, target, this.owner);
},
didDetachView(rowView: RowView): void {
this.owner.callObservers("viewDidDetachRow", rowView, this.owner);
},
viewWillAttachLeaf(leafView: LeafView, rowView: RowView): void {
this.owner.callObservers("viewWillAttachLeaf", leafView, rowView);
},
viewDidDetachLeaf(leafView: LeafView, rowView: RowView): void {
this.owner.callObservers("viewDidDetachLeaf", leafView, rowView);
},
viewDidEnterLeaf(leafView: LeafView, rowView: RowView): void {
this.owner.callObservers("viewDidEnterLeaf", leafView, rowView);
},
viewDidLeaveLeaf(leafView: LeafView, rowView: RowView): void {
this.owner.callObservers("viewDidLeaveLeaf", leafView, rowView);
},
viewDidPressLeaf(input: PositionGestureInput, event: Event | null, leafView: LeafView, rowView: RowView): void {
this.owner.callObservers("viewDidPressLeaf", input, event, leafView, rowView);
},
viewDidLongPressLeaf(input: PositionGestureInput, leafView: LeafView, rowView: RowView): void {
this.owner.callObservers("viewDidLongPressLeaf", input, leafView, rowView);
},
viewWillAttachTree(treeView: TableView, rowView: RowView): void {
this.owner.callObservers("viewWillAttachTree", treeView, rowView);
},
viewDidDetachTree(treeView: TableView, rowView: RowView): void {
this.owner.callObservers("viewDidDetachTree", treeView, rowView);
},
viewWillHighlightLeaf(leafView: LeafView, rowView: RowView): void {
this.owner.callObservers("viewWillHighlightLeaf", leafView, rowView);
},
viewDidHighlightLeaf(leafView: LeafView, rowView: RowView): void {
this.owner.callObservers("viewDidHighlightLeaf", leafView, rowView);
},
viewWillUnhighlightLeaf(leafView: LeafView, rowView: RowView): void {
this.owner.callObservers("viewWillUnhighlightLeaf", leafView, rowView);
},
viewDidUnhighlightLeaf(leafView: LeafView, rowView: RowView): void {
this.owner.callObservers("viewDidUnhighlightLeaf", leafView, rowView);
},
viewWillExpand(rowView: RowView): void {
this.owner.callObservers("viewWillExpandRow", rowView);
},
viewDidExpand(rowView: RowView): void {
this.owner.callObservers("viewDidExpandRow", rowView);
},
viewWillCollapse(rowView: RowView): void {
this.owner.callObservers("viewWillCollapseRow", rowView);
},
viewDidCollapse(rowView: RowView): void {
this.owner.callObservers("viewDidCollapseRow", rowView);
},
})
readonly rows!: ViewSet<this, RowView>;
static readonly rows: MemberFastenerClass<TableView, "rows">;
/** @internal */
readonly visibleViews: ReadonlyArray<View>;
/** @internal */
readonly visibleFrame: R2Box;
protected detectVisibleFrame(viewContext: ViewContext): R2Box {
const xBleed = 0;
const yBleed = this.rowHeight.getValueOr(Length.zero()).pxValue();
const parentVisibleFrame = (viewContext as TableViewContext).visibleFrame as R2Box | undefined;
if (parentVisibleFrame !== void 0) {
let left: Length | number | null = this.left.state;
left = left instanceof Length ? left.pxValue() : 0;
let top: Length | number | null = this.top.state;
top = top instanceof Length ? top.pxValue() : 0;
return new R2Box(parentVisibleFrame.xMin - left - xBleed, parentVisibleFrame.yMin - top - yBleed,
parentVisibleFrame.xMax - left + xBleed, parentVisibleFrame.yMax - top + yBleed);
} else {
const bounds = this.node.getBoundingClientRect();
const xMin = -bounds.x - xBleed;
const yMin = -bounds.y - yBleed;
const xMax = window.innerWidth - bounds.x + xBleed;
const yMax = window.innerHeight - bounds.y + yBleed;
return new R2Box(xMin, yMin, xMax, yMax);
}
}
override extendViewContext(viewContext: ViewContext): ViewContextType<this> {
const treeViewContext = Object.create(viewContext);
treeViewContext.visibleFrame = this.visibleFrame;
return treeViewContext;
}
override needsProcess(processFlags: ViewFlags, viewContext: ViewContextType<this>): ViewFlags {
if ((processFlags & View.NeedsResize) !== 0) {
processFlags |= View.NeedsScroll;
}
return processFlags;
}
protected override onResize(viewContext: ViewContextType<this>): void {
super.onResize(viewContext);
this.resizeTable();
}
protected resizeTable(): void {
const oldLayout = !this.layout.inherited ? this.layout.value : null;
if (oldLayout !== null) {
const superLayout = this.layout.superValue;
let width: Length | number | null = null;
if (superLayout !== void 0 && superLayout !== null && superLayout.width !== null) {
width = superLayout.width.pxValue();
}
if (width === null) {
width = this.width.state;
width = width instanceof Length ? width.pxValue() : this.node.offsetWidth;
}
const edgeInsets = this.edgeInsets.value;
let paddingLeft: Length | number | null = this.paddingLeft.state;
paddingLeft = paddingLeft instanceof Length ? paddingLeft.pxValue(width) : 0;
let paddingRight: Length | number | null = this.paddingRight.state;
paddingRight = paddingRight instanceof Length ? paddingRight.pxValue(width) : 0;
let left = edgeInsets !== null ? edgeInsets.insetLeft : 0;
left += paddingLeft;
let right = edgeInsets !== null ? edgeInsets.insetRight : 0;
right += paddingRight;
const newLayout = oldLayout.resized(width, left, right);
this.layout.setValue(newLayout);
}
}
protected processVisibleViews(processFlags: ViewFlags, viewContext: ViewContextType<this>,
processChild: (this: this, child: View, processFlags: ViewFlags,
viewContext: ViewContextType<this>) => void): void {
const visibleViews = this.visibleViews;
let i = 0;
while (i < visibleViews.length) {
const child = visibleViews[i]!;
processChild.call(this, child, processFlags, viewContext);
if ((child.flags & View.RemovingFlag) !== 0) {
child.setFlags(child.flags & ~View.RemovingFlag);
this.removeChild(child);
continue;
}
i += 1;
}
}
protected override processChildren(processFlags: ViewFlags, viewContext: ViewContextType<this>,
processChild: (this: this, child: View, processFlags: ViewFlags,
viewContext: ViewContextType<this>) => void): void {
if (!this.culled) {
if ((processFlags & View.NeedsScroll) !== 0) {
this.scrollChildViews(processFlags, viewContext, processChild);
} else {
this.processVisibleViews(processFlags, viewContext, processChild);
}
}
}
protected scrollChildViews(processFlags: ViewFlags, viewContext: ViewContextType<this>,
processChild: (this: this, child: View, processFlags: ViewFlags,
viewContext: ViewContextType<this>) => void): void {
const visibleViews = this.visibleViews as View[];
visibleViews.length = 0;
const visibleFrame = this.detectVisibleFrame(Object.getPrototypeOf(viewContext));
(viewContext as Mutable<ViewContextType<this>>).visibleFrame = visibleFrame;
(this as Mutable<this>).visibleFrame = visibleFrame;
type self = this;
function scrollChildView(this: self, child: View, processFlags: ViewFlags,
viewContext: ViewContextType<self>): void {
let isVisible: boolean;
if (child instanceof HtmlView) {
const top = child.top.state;
const height = child.height.state;
if (top instanceof Length && height instanceof Length) {
const yMin0 = visibleFrame.yMin;
const yMax0 = visibleFrame.yMax;
const yMin1 = top.pxValue();
const yMax1 = yMin1 + height.pxValue();
isVisible = yMin0 <= yMax1 && yMin1 <= yMax0;
child.display.setState(isVisible ? "flex" : "none", Affinity.Intrinsic);
child.setCulled(!isVisible);
} else {
isVisible = true;
}
} else {
isVisible = true;
}
if (isVisible) {
visibleViews.push(child);
processChild.call(this, child, processFlags, viewContext);
}
}
super.processChildren(processFlags, viewContext, scrollChildView);
}
protected displayVisibleViews(displayFlags: ViewFlags, viewContext: ViewContextType<this>,
displayChild: (this: this, child: View, displayFlags: ViewFlags,
viewContext: ViewContextType<this>) => void): void {
const visibleViews = this.visibleViews;
let i = 0;
while (i < visibleViews.length) {
const child = visibleViews[i]!;
displayChild.call(this, child, displayFlags, viewContext);
if ((child.flags & View.RemovingFlag) !== 0) {
child.setFlags(child.flags & ~View.RemovingFlag);
this.removeChild(child);
continue;
}
i += 1;
}
}
protected override displayChildren(displayFlags: ViewFlags, viewContext: ViewContextType<this>,
displayChild: (this: this, child: View, displayFlags: ViewFlags,
viewContext: ViewContextType<this>) => void): void {
if ((displayFlags & View.NeedsLayout) !== 0) {
this.layoutChildViews(displayFlags, viewContext, displayChild);
} else {
this.displayVisibleViews(displayFlags, viewContext, displayChild);
}
}
protected layoutChildViews(displayFlags: ViewFlags, viewContext: ViewContextType<this>,
displayChild: (this: this, child: View, displayFlags: ViewFlags,
viewContext: ViewContextType<this>) => void): void {
this.resizeTable();
const layout = this.layout.value;
const width = layout !== null ? layout.width : null;
const rowHeight = this.rowHeight.getValue();
const rowSpacing = this.rowSpacing.getValue().pxValue(rowHeight.pxValue());
const disclosingPhase = this.disclosing.getPhaseOr(1);
const visibleViews = this.visibleViews as View[];
visibleViews.length = 0;
const visibleFrame = this.detectVisibleFrame(Object.getPrototypeOf(viewContext));
(viewContext as Mutable<ViewContextType<this>>).visibleFrame = visibleFrame;
(this as Mutable<this>).visibleFrame = visibleFrame;
let yValue = 0;
let yState = 0;
let rowIndex = 0;
type self = this;
function layoutChildView(this: self, child: View, displayFlags: ViewFlags,
viewContext: ViewContextType<self>): void {
if (child instanceof RowView || child instanceof HeaderView) {
if (rowIndex !== 0) {
yValue += rowSpacing * disclosingPhase;
yState += rowSpacing;
}
if (child.top.hasAffinity(Affinity.Intrinsic)) {
child.top.setInterpolatedValue(Length.px(yValue), Length.px(yState));
}
child.width.setState(width, Affinity.Intrinsic);
}
let isVisible: boolean;
if (child instanceof HtmlView) {
const top = child.top.state;
const height = child.height.state;
if (top instanceof Length && height instanceof Length) {
const yMin0 = visibleFrame.yMin;
const yMax0 = visibleFrame.yMax;
const yMin1 = top.pxValue();
const yMax1 = yMin1 + height.pxValue();
isVisible = yMin0 <= yMax1 && yMin1 <= yMax0;
} else {
isVisible = true;
}
child.display.setState(isVisible ? "flex" : "none", Affinity.Intrinsic);
child.setCulled(!isVisible);
} else {
isVisible = true;
}
if (isVisible) {
visibleViews.push(child);
}
displayChild.call(this, child, displayFlags, viewContext);
if (child instanceof RowView || child instanceof HeaderView) {
let heightValue: Length | number | null = child.height.value;
heightValue = heightValue instanceof Length ? heightValue.pxValue() : child.node.offsetHeight;
let heightState: Length | number | null = child.height.state;
heightState = heightState instanceof Length ? heightState.pxValue() : heightValue;
yValue += heightValue * disclosingPhase;
yState += heightState;
rowIndex += 1;
}
}
super.displayChildren(displayFlags, viewContext, layoutChildView);
if (this.height.hasAffinity(Affinity.Intrinsic)) {
this.height.setInterpolatedValue(Length.px(yValue), Length.px(yState));
}
const disclosurePhase = this.disclosure.getPhaseOr(1);
this.opacity.setState(disclosurePhase, Affinity.Intrinsic);
}
} | the_stack |
import genPicks from "./genPicks";
import logLotteryChances from "./logLotteryChances";
import logLotteryWinners from "./logLotteryWinners";
import divideChancesOverTiedTeams from "./divideChancesOverTiedTeams";
import { idb } from "../../db";
import { g, helpers, random } from "../../util";
import type {
Conditions,
DraftLotteryResult,
DraftType,
DraftPickWithoutKey,
} from "../../../common/types";
import genOrderGetPicks from "./genOrderGetPicks";
import getTeamsByRound from "./getTeamsByRound";
import { bySport } from "../../../common";
import { league } from "..";
type ReturnVal = DraftLotteryResult & {
draftType: Exclude<
DraftType,
"random" | "noLottery" | "noLotteryReverse" | "freeAgents"
>;
};
// chances does not have to be the perfect length. If chances is too long for numLotteryTeams, it will be truncated. If it's too short, the last entry will be repeated until it's long enough.
export const getLotteryInfo = (
draftType: DraftType,
numLotteryTeams: number,
) => {
if (draftType === "coinFlip") {
return {
minNumTeams: 2,
numToPick: 2,
chances: [1, 1, 0],
};
}
if (draftType === "randomLottery") {
return {
minNumTeams: numLotteryTeams,
numToPick: numLotteryTeams,
chances: [1],
};
}
if (draftType === "randomLotteryFirst3") {
return {
minNumTeams: 3,
numToPick: 3,
chances: [1],
};
}
if (draftType === "nba1990") {
const chances = [];
for (let i = numLotteryTeams; i > 0; i--) {
chances.push(i);
}
return {
minNumTeams: 3,
numToPick: 3,
chances,
};
}
if (draftType === "nba1994") {
return {
minNumTeams: 3,
numToPick: 3,
chances: [250, 199, 156, 119, 88, 63, 43, 28, 17, 11, 8, 7, 6, 5],
};
}
if (draftType === "nba2019") {
return {
minNumTeams: 4,
numToPick: 4,
chances: [140, 140, 140, 125, 105, 90, 75, 60, 45, 30, 20, 15, 10, 5],
};
}
if (draftType === "nhl2017") {
return {
minNumTeams: 3,
numToPick: 3,
chances: [185, 135, 115, 95, 85, 75, 65, 60, 50, 35, 30, 25, 20, 15, 10],
};
}
throw new Error(`Unsupported draft type "${draftType}"`);
};
const LOTTERY_DRAFT_TYPES = [
"nba1994",
"nba2019",
"coinFlip",
"randomLottery",
"randomLotteryFirst3",
"nba1990",
"nhl2017",
] as const;
export const draftHasLottey = (
draftType: any,
): draftType is typeof LOTTERY_DRAFT_TYPES[number] => {
return LOTTERY_DRAFT_TYPES.includes(draftType);
};
const TIEBREAKER_AFTER_FIRST_ROUND = bySport<"swap" | "rotate" | "same">({
basketball: "swap",
football: "rotate",
hockey: "same",
});
/**
* Sets draft order and save it to the draftPicks object store.
*
* This is currently based on an NBA-like lottery, where the first 3 picks can be any of the non-playoff teams (with weighted probabilities).
*
* If mock is true, then nothing is actually saved to the database and no notifications are sent
*
* @memberOf core.draft
* @return {Promise}
*/
const genOrder = async (
mock: boolean = false,
conditions?: Conditions,
draftTypeOverride?: DraftType,
): Promise<ReturnVal | undefined> => {
// Sometimes picks just fail to generate or get lost. For example, if numSeasonsFutureDraftPicks is 0.
await genPicks();
const draftPicks = await genOrderGetPicks(mock);
const draftPicksIndexed: DraftPickWithoutKey[][] = [];
for (const dp of draftPicks) {
const tid = dp.originalTid; // Initialize to an array
if (draftPicksIndexed[tid] === undefined) {
draftPicksIndexed[tid] = [];
}
draftPicksIndexed[tid][dp.round] = dp;
}
const { allTeams, teamsByRound, ties } = await getTeamsByRound(
draftPicksIndexed,
);
const firstRoundTeams = teamsByRound[0] ?? [];
const draftType = draftTypeOverride ?? g.get("draftType");
const riggedLottery = g.get("godMode") ? g.get("riggedLottery") : undefined;
// Draft lottery
const firstN: number[] = [];
let numLotteryTeams = 0;
let chances: number[] = [];
if (draftHasLottey(draftType)) {
const numPlayoffTeams =
2 ** g.get("numGamesPlayoffSeries", "current").length -
g.get("numPlayoffByes", "current");
const info = getLotteryInfo(
draftType,
firstRoundTeams.length - numPlayoffTeams,
);
const minNumLotteryTeams = info.minNumTeams;
const numToPick = info.numToPick;
chances = info.chances;
if (firstRoundTeams.length < minNumLotteryTeams) {
const error = new Error(
`Number of teams with draft picks (${firstRoundTeams.length}) is less than the minimum required for draft type "${draftType}"`,
);
(error as any).notEnoughTeams = true;
throw error;
}
numLotteryTeams = helpers.bound(
firstRoundTeams.length - numPlayoffTeams,
minNumLotteryTeams,
draftType === "coinFlip" ? minNumLotteryTeams : firstRoundTeams.length,
);
if (numLotteryTeams < chances.length) {
chances = chances.slice(0, numLotteryTeams);
} else {
while (numLotteryTeams > chances.length) {
chances.push(chances.at(-1));
}
}
if (draftType.startsWith("nba")) {
divideChancesOverTiedTeams(chances, firstRoundTeams, true);
}
const chanceTotal = chances.reduce((a, b) => a + b, 0);
const chancePct = chances.map(c => (c / chanceTotal) * 100);
// Idenfity chances indexes protected by riggedLottery, and set to 0 in chancesCumsum
const riggedLotteryIndexes = riggedLottery
? riggedLottery.map(dpid => {
if (typeof dpid === "number") {
const originalTid = draftPicks.find(dp => {
return dp.dpid === dpid;
})?.originalTid;
if (originalTid !== undefined) {
const index = firstRoundTeams.findIndex(
({ tid }) => tid === originalTid,
);
if (index >= 0) {
return index;
}
}
}
return null;
})
: undefined;
const chancesCumsum = chances.slice();
if (riggedLotteryIndexes?.includes(0)) {
chancesCumsum[0] = 0;
}
for (let i = 1; i < chancesCumsum.length; i++) {
if (riggedLotteryIndexes?.includes(i)) {
chancesCumsum[i] = chancesCumsum[i - 1];
} else {
chancesCumsum[i] += chancesCumsum[i - 1];
}
}
const totalChances = chancesCumsum.at(-1);
// Pick first 3 or 4 picks based on chancesCumsum
let iterations = 0;
while (firstN.length < numToPick) {
if (riggedLotteryIndexes) {
const index = riggedLotteryIndexes[firstN.length];
if (typeof index === "number") {
firstN.push(index);
continue;
}
}
const draw = random.randInt(0, totalChances - 1);
const i = chancesCumsum.findIndex(chance => chance > draw);
if (
!firstN.includes(i) &&
i < firstRoundTeams.length &&
draftPicksIndexed[firstRoundTeams[i].tid]
) {
firstN.push(i);
}
iterations += 1;
if (iterations > 100000) {
break;
}
}
if (!mock) {
logLotteryChances(
chancePct,
firstRoundTeams,
draftPicksIndexed,
conditions,
);
}
} else {
for (const roundTeams of teamsByRound) {
if (draftType === "random") {
random.shuffle(roundTeams);
} else if (draftType === "noLotteryReverse") {
roundTeams.reverse();
}
}
}
const firstRoundOrderAfterLottery = [];
// First round - lottery winners
let pick = 1;
for (let i = 0; i < firstN.length; i++) {
const dp = draftPicksIndexed[firstRoundTeams[firstN[i]].tid][1];
if (dp !== undefined) {
dp.pick = pick;
firstRoundOrderAfterLottery.push(firstRoundTeams[firstN[i]]);
if (!mock) {
logLotteryWinners(
firstRoundTeams,
dp.tid,
firstRoundTeams[firstN[i]].tid,
pick,
conditions,
);
}
pick += 1;
}
}
// First round - everyone else
for (let i = 0; i < firstRoundTeams.length; i++) {
if (!firstN.includes(i)) {
const dp = draftPicksIndexed[firstRoundTeams[i].tid]?.[1];
if (dp) {
dp.pick = pick;
firstRoundOrderAfterLottery.push(firstRoundTeams[i]);
if (pick <= numLotteryTeams && !mock) {
logLotteryWinners(
firstRoundTeams,
dp.tid,
firstRoundTeams[i].tid,
pick,
conditions,
);
}
pick += 1;
}
}
}
let draftLotteryResult: ReturnVal | undefined;
if (draftHasLottey(draftType)) {
const usePts = g.get("pointsFormula", "current") !== "";
// Save draft lottery results separately
draftLotteryResult = {
season: g.get("season"),
draftType,
rigged: riggedLottery,
result: firstRoundTeams // Start with teams in lottery order
.map(({ tid }) => {
return draftPicks.find(dp => {
// Keep only lottery picks
return (
dp.originalTid === tid &&
dp.round === 1 &&
dp.pick > 0 &&
dp.pick <= chances.length
);
});
})
.filter(dp => dp !== undefined) // Keep only lottery picks
.map(dp => {
if (dp === undefined) {
throw new Error("Should never happen");
}
// For the team making the pick
const t = allTeams.find(t2 => t2.tid === dp.tid);
let won = 0;
let lost = 0;
let otl = 0;
let tied = 0;
let pts;
if (t) {
won = t.seasonAttrs.won;
lost = t.seasonAttrs.lost;
otl = t.seasonAttrs.otl;
tied = t.seasonAttrs.tied;
if (usePts) {
pts = t.seasonAttrs.pts;
}
}
// For the original team
const i = firstRoundTeams.findIndex(t2 => t2.tid === dp.originalTid);
return {
tid: dp.tid,
originalTid: dp.originalTid,
chances: chances[i],
pick: dp.pick,
won,
lost,
otl,
tied,
pts,
dpid: dp.dpid,
};
}),
};
if (!mock) {
await idb.cache.draftLotteryResults.put(draftLotteryResult);
await league.setGameAttributes({
riggedLottery: undefined,
});
}
}
for (let roundIndex = 1; roundIndex < teamsByRound.length; roundIndex++) {
const roundTeams = teamsByRound[roundIndex];
const round = roundIndex + 1;
// Handle tiebreakers for the 2nd+ round (1st is already done by getTeamsByRound, but 2nd can't be done until now because it depends on lottery results for basketball/football)
// Skip random drafts because this code assumes teams appear in the same order every round, which is not true there!
if (draftType !== "random" && TIEBREAKER_AFTER_FIRST_ROUND !== "same") {
for (const { rounds, teams } of Object.values(ties)) {
if (rounds.includes(round)) {
// From getTeamsByRound, teams is guaranteed to be a continuous section of roundTeams, so we can just figure out the correct order for them and then replace them in roundTeam
const start = roundTeams.findIndex(t => teams.includes(t));
const length = teams.length;
const firstRoundOrder = firstRoundOrderAfterLottery.filter(t =>
teams.includes(t),
);
// Handle case where a team did not appear in the 1st round but does now, which probably never happens
for (const t of teams) {
if (!firstRoundOrder.includes(t)) {
firstRoundOrder.push(t);
}
}
// Based on roundIndex and TIEBREAKER_AFTER_FIRST_ROUND, do some permutation of firstRoundOrder
const newOrder = firstRoundOrder;
if (TIEBREAKER_AFTER_FIRST_ROUND === "swap") {
if (roundIndex % 2 === 1) {
newOrder.reverse();
}
} else if (TIEBREAKER_AFTER_FIRST_ROUND === "rotate") {
for (let i = 0; i < roundIndex; i++) {
// Move 1st team to the end of the list
newOrder.push((newOrder as unknown as any).shift());
}
}
roundTeams.splice(start, length, ...newOrder);
}
}
}
let pick = 1;
for (const t of roundTeams) {
const dp = draftPicksIndexed[t.tid]?.[roundIndex + 1];
if (dp !== undefined) {
dp.pick = pick;
pick += 1;
}
}
}
if (!mock) {
for (const dp of draftPicks) {
await idb.cache.draftPicks.put(dp);
}
await league.setGameAttributes({
numDraftPicksCurrent: draftPicks.length,
});
}
return draftLotteryResult;
};
export default genOrder; | the_stack |
import {
Inject,
inject,
Injectable,
InjectionToken,
LOCALE_ID,
Optional,
} from '@angular/core';
import { Observable, Subject } from 'rxjs';
/**
* This code has been implemented based on the DateAdapter from Angular Material
* https://github.com/angular/components/blob/master/src/material/core/datetime/date-adapter.ts
*/
/** The default day of the week names to use if Intl API is not available. */
const DEFAULT_DAY_OF_WEEK_NAMES = {
long: [
'Sunday',
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday',
],
short: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
narrow: ['S', 'M', 'T', 'W', 'T', 'F', 'S'],
};
const DEFAULT_DATE_NAMES = fillArray(31, (i) => String(i + 1));
/** InjectionToken for datepicker that can be used to override default locale code. */
export const DT_DATE_LOCALE = new InjectionToken<string>('DT_DATE_LOCALE', {
providedIn: 'root',
factory: DT_DATE_LOCALE_FACTORY,
});
let SUPPORTS_INTL_API: boolean;
try {
SUPPORTS_INTL_API = typeof Intl != 'undefined';
} catch {
SUPPORTS_INTL_API = false;
}
/** @docs-private */
export function DT_DATE_LOCALE_FACTORY(): string {
return inject(LOCALE_ID);
}
/**
* This code has been implemented based on the NativeDateAdapter from Angular Material
* https://github.com/angular/components/blob/master/src/material/core/datetime/native-date-adapter.ts
* This class can be replaced by Angular's adapter if it is moved to the CDK.
*/
@Injectable()
export class DtNativeDateAdapter implements DtDateAdapter<Date> {
constructor(
@Optional() @Inject(DT_DATE_LOCALE) dtDateLocale?: string,
@Optional() @Inject(LOCALE_ID) locale?: string,
) {
this.setLocale(dtDateLocale ?? locale ?? 'en-US');
}
/** The locale to use for all dates. */
locale: any;
/** A stream that emits when the locale changes. */
get localeChanges(): Observable<void> {
return this._localeChanges.asObservable();
}
_localeChanges = new Subject<void>();
/** Sets the locale used for all dates. */
setLocale(locale: any): void {
this.locale = locale;
this._localeChanges.next();
}
/**
* Compares two dates.
* Returns 0 if the dates are equal,
* a number less than 0 if the first date is earlier,
* a number greater than 0 if the first date is later
*/
compareDate(first: Date, second: Date): number {
return (
this.getYear(first) - this.getYear(second) ||
this.getMonth(first) - this.getMonth(second) ||
this.getDate(first) - this.getDate(second)
);
}
/**
* Compares two dates only by comparing the month and year (ignoring the day).
* Returns 0 if the dates are equal,
* a number less than 0 if the first date is earlier,
* a number greater than 0 if the first date is later
*/
compareDateIgnoreDay(first: Date, second: Date): number {
return (
this.getYear(first) - this.getYear(second) ||
this.getMonth(first) - this.getMonth(second)
);
}
/** Clamp the given date between min and max dates. */
clampDate(date: Date, min?: Date | null, max?: Date | null): Date {
if (min && this.compareDate(date, min) < 0) {
return min;
}
if (max && this.compareDate(date, max) > 0) {
return max;
}
return date;
}
createDate(year: number, month: number, date: number): Date {
if (month < 0 || month > 11) {
throw Error(
`Invalid month index "${month}". Month index has to be between 0 and 11.`,
);
}
if (date < 1) {
throw Error(`Invalid date "${date}". Date has to be greater than 0.`);
}
const result = createDateWithOverflow(year, month, date);
if (result.getMonth() !== month) {
throw Error(`Invalid date "${date}" for month with index "${month}".`);
}
return result;
}
today(): Date {
return new Date();
}
getYear(date: Date): number {
return date.getFullYear();
}
getMonth(date: Date): number {
return date.getMonth();
}
getDate(date: Date): number {
return date.getDate();
}
getDayOfWeek(date: Date): number {
return date.getDay();
}
getFirstDayOfWeek(): number {
return 1; // Monday
}
getDayOfWeekNames(style: 'long' | 'short' | 'narrow'): string[] {
return DEFAULT_DAY_OF_WEEK_NAMES[style];
}
getNumDaysInMonth(date: Date): number {
return this.getDate(
createDateWithOverflow(this.getYear(date), this.getMonth(date) + 1, 0),
);
}
getDateNames(): string[] {
if (SUPPORTS_INTL_API) {
const dateFormat = new Intl.DateTimeFormat(this.locale, {
day: 'numeric',
timeZone: 'utc',
});
return fillArray(31, (i) =>
stripDirectionalityCharacters(
formatDate(dateFormat, new Date(2017, 0, i + 1)),
),
);
}
return DEFAULT_DATE_NAMES;
}
format(date: Date, displayFormat: Object): string {
displayFormat = { ...displayFormat, timeZone: 'utc' };
const dateFormat = new Intl.DateTimeFormat(this.locale, displayFormat);
return stripDirectionalityCharacters(formatDate(dateFormat, date));
}
isValid(date: Date): boolean {
return !isNaN(date.getTime());
}
isDateInstance(obj: any): obj is Date {
return obj instanceof Date;
}
addCalendarYears(date: Date, years: number): Date {
return this.addCalendarMonths(date, years * 12);
}
addCalendarMonths(date: Date, months: number): Date {
let newDate = createDateWithOverflow(
this.getYear(date),
this.getMonth(date) + months,
this.getDate(date),
);
// It's possible to wind up in the wrong month if the original month has more days than the new
// month. In this case we want to go to the last day of the desired month.
// Note: the additional + 12 % 12 ensures we end up with a positive number, since JS % doesn't
// guarantee this.
if (
this.getMonth(newDate) !=
(((this.getMonth(date) + months) % 12) + 12) % 12
) {
newDate = createDateWithOverflow(
this.getYear(newDate),
this.getMonth(newDate),
0,
);
}
return newDate;
}
addCalendarDays(date: Date, days: number): Date {
return createDateWithOverflow(
this.getYear(date),
this.getMonth(date),
this.getDate(date) + days,
);
}
}
function fillArray<T>(length: number, fillFn: (index: number) => T): T[] {
return new Array(length).fill(null).map((_, i) => fillFn(i));
}
/**
* Strip out unicode LTR and RTL characters. Edge and IE insert these into formatted dates while
* other browsers do not. We remove them to make output consistent and because they interfere with
* date parsing.
*/
function stripDirectionalityCharacters(str: string): string {
return str.replace(/[\u200e\u200f]/g, '');
}
/**
* When converting Date object to string, javascript built-in functions may return wrong
* results because it applies its internal DST rules. The DST rules around the world change
* very frequently, and the current valid rule is not always valid in previous years though.
* We work around this problem building a new Date object which has its internal UTC
* representation with the local date and time.
*/
function formatDate(dateFormat: Intl.DateTimeFormat, date: Date): string {
const d = new Date(
Date.UTC(
date.getFullYear(),
date.getMonth(),
date.getDate(),
date.getHours(),
date.getMinutes(),
date.getSeconds(),
date.getMilliseconds(),
),
);
return dateFormat.format(d);
}
/** Creates a date but allows the month and date to overflow. */
function createDateWithOverflow(
year: number,
month: number,
date: number,
): Date {
const result = new Date(year, month, date);
// We need to correct for the fact that JS native Date treats years in range [0, 99] as
// abbreviations for 19xx.
if (year >= 0 && year < 100) {
result.setFullYear(this.getYear(result) - 1900);
}
return result;
}
@Injectable({
providedIn: 'root',
useClass: DtNativeDateAdapter,
deps: [DT_DATE_LOCALE, LOCALE_ID],
})
export abstract class DtDateAdapter<T> {
/** The locale to use for all dates. */
abstract locale: any;
/** A stream that emits when the locale changes. */
abstract get localeChanges(): Observable<void>;
abstract _localeChanges = new Subject<void>();
/** Sets the locale used for all dates. */
abstract setLocale(locale: any): void;
/**
* Creates a date with the given year, month, and date. Does not allow over/under-flow of the
* month and date.
* @param year The full year of the date. (e.g. 89 means the year 89, not the year 1989).
* @param month The month of the date (0-indexed, 0 = January). Must be an integer 0 - 11.
* @param date The date of month of the date. Must be an integer 1 - length of the given month.
* @returns The new date, or throws an error if invalid.
*/
abstract createDate(year: number, month: number, date: number): T;
/** Gets today's date. */
abstract today(): T;
/** Gets the year component of the given date. */
abstract getYear(date: T): number;
/** Gets the month component of the given date. */
abstract getMonth(date: T): number;
/** Gets the date of the month component of the given date. */
abstract getDate(date: T): number;
/**
* Gets the day of the week component of the given date.
* @param date The date to extract the day of the week from.
* @returns The month component (0-indexed, 0 = Sunday).
*/
abstract getDayOfWeek(date: T): number;
/** Gets the first day of the week. */
abstract getFirstDayOfWeek(): number;
/**
* Gets a list of names for the days of the week.
* @param style The naming style (e.g. long = 'Sunday', short = 'Sun', narrow = 'S').
* @returns An ordered list of all weekday names.
*/
abstract getDayOfWeekNames(style: 'long' | 'short' | 'narrow'): string[];
/** Gets the number of days in the month of the given date. */
abstract getNumDaysInMonth(date: T): number;
/** Gets a list of names for the dates of the month. */
abstract getDateNames(): string[];
/** Checks whether the given object is considered a date instance by this DateAdapter. */
abstract isDateInstance(obj: any): obj is T;
/** Checks whether the given date is valid. */
abstract isValid(date: T): boolean;
/** Formats a date as a string according to the given format. */
abstract format(date: T, displayFormat: Object): string;
/**
* Adds the given number of years to the date. Years are counted as if flipping 12 pages on the
* calendar for each year and then finding the closest date in the new month. For example when
* adding 1 year to Feb 29, 2016, the resulting date will be Feb 28, 2017.
*/
abstract addCalendarYears(date: T, years: number): T;
/**
* Adds the given number of months to the date. Months are counted as if flipping a page on the
* calendar for each month and then finding the closest date in the new month. For example when
* adding 1 month to Jan 31, 2017, the resulting date will be Feb 28, 2017.
*/
abstract addCalendarMonths(date: T, months: number): T;
/** Adds the given number of days to the date. */
abstract addCalendarDays(date: T, days: number): T;
/**
* Compares two dates.
* Returns 0 if the dates are equal,
* a number less than 0 if the first date is earlier,
* a number greater than 0 if the first date is later
*/
abstract compareDate(first: T, second: T): number;
/**
* Compares two dates ignoring the day.
* Returns 0 if the dates are equal,
* a number less than 0 if the first date is earlier,
* a number greater than 0 if the first date is later
*/
abstract compareDateIgnoreDay(first: T, second: T): number;
// /** Clamp the given date between min and max dates. */
abstract clampDate(date: T, min?: T | null, max?: T | null): T;
} | the_stack |
import EmberObject, { set } from '@ember/object';
import { run } from '@ember/runloop';
import { settled } from '@ember/test-helpers';
import { module, test } from 'qunit';
import { all, resolve } from 'rsvp';
import { setupTest } from 'ember-qunit';
import Adapter from '@ember-data/adapter';
import JSONAPIAdapter from '@ember-data/adapter/json-api';
import Model, { attr, belongsTo } from '@ember-data/model';
import JSONAPISerializer from '@ember-data/serializer/json-api';
import Store, {
recordIdentifierFor,
setIdentifierForgetMethod,
setIdentifierGenerationMethod,
setIdentifierResetMethod,
setIdentifierUpdateMethod,
} from '@ember-data/store';
import { identifierCacheFor } from '@ember-data/store/-private';
import type {
IdentifierBucket,
ResourceData,
StableIdentifier,
StableRecordIdentifier,
} from '@ember-data/store/-private/ts-interfaces/identifier';
module('Integration | Identifiers - configuration', function (hooks) {
setupTest(hooks);
let store: Store;
hooks.beforeEach(function () {
const { owner } = this;
owner.register('adapter:application', JSONAPIAdapter.extend());
owner.register('serializer:application', JSONAPISerializer.extend());
class User extends Model {
@attr()
declare firstName: string;
@attr()
declare username: string;
@attr()
declare age: number;
}
owner.register('model:user', User);
owner.register('service:store', Store);
store = owner.lookup('service:store');
let localIdInc = 9000;
const generationMethod = (resource: ResourceData | { type: string }) => {
if (!('type' in resource) || typeof resource.type !== 'string' || resource.type.length < 1) {
throw new Error(`Cannot generate an lid for a record without a type`);
}
if ('lid' in resource && typeof resource.lid === 'string' && resource.lid.length > 0) {
return resource.lid;
}
if ('id' in resource && typeof resource.id === 'string' && resource.id.length > 0) {
return `remote:${resource.type}:${resource.id}`;
}
return `local:${resource.type}:${localIdInc++}`;
};
setIdentifierGenerationMethod(generationMethod);
});
hooks.afterEach(function () {
setIdentifierGenerationMethod(null);
setIdentifierResetMethod(null);
setIdentifierUpdateMethod(null);
setIdentifierForgetMethod(null);
});
test(`The configured generation method is used for pushed records`, async function (assert) {
const record = store.push({
data: {
type: 'user',
id: '1',
attributes: {
fistName: 'Chris',
username: '@runspired',
age: 31,
},
},
});
const identifier = recordIdentifierFor(record);
assert.strictEqual(identifier.lid, 'remote:user:1', 'We receive the expected identifier for an existing record');
});
test(`The configured generation method is used for newly created records`, async function (assert) {
let localIdInc = 9000;
const generationMethod = (resource: ResourceData | { type: string }) => {
if (!('type' in resource) || typeof resource.type !== 'string' || resource.type.length < 1) {
throw new Error(`Cannot generate an lid for a record without a type`);
}
if ('lid' in resource && typeof resource.lid === 'string' && resource.lid.length > 0) {
return resource.lid;
}
if ('id' in resource && typeof resource.id === 'string' && resource.id.length > 0) {
return `remote:${resource.type}:${resource.id}`;
}
return `local:${resource.type}:${localIdInc++}`;
};
setIdentifierGenerationMethod(generationMethod);
const newRecord = store.createRecord('user', {
firstName: 'James',
username: '@cthoburn',
});
const newIdentifier = recordIdentifierFor(newRecord);
assert.strictEqual(
newIdentifier.lid,
'local:user:9000',
'We receive the expected identifier for a newly created record'
);
});
test(`The configured update method is called when newly created records are committed`, async function (assert) {
class TestSerializer extends EmberObject {
normalizeResponse(_, __, payload) {
return payload;
}
}
class TestAdapter extends Adapter {
createRecord() {
return resolve({
data: {
id: '1',
type: 'user',
attributes: {
firstName: 'James',
username: '@runspired',
age: 31,
},
},
});
}
}
this.owner.register('adapter:application', TestAdapter);
this.owner.register('serializer:application', TestSerializer);
let updateMethodCalls = 0 as number;
let updateCallback: (...args: any[]) => void;
function updateMethod(
identifier: StableIdentifier | StableRecordIdentifier,
data: ResourceData | unknown,
bucket: IdentifierBucket
) {
switch (bucket) {
case 'record':
updateMethodCalls++;
updateCallback!(identifier, data);
break;
default:
throw new Error(`Identifier Updates for ${bucket} have not been implemented`);
}
}
setIdentifierUpdateMethod(updateMethod);
const record = store.createRecord('user', { firstName: 'Chris', username: '@runspired', age: 31 });
const identifier = recordIdentifierFor(record);
assert.strictEqual(
identifier.lid,
'local:user:9000',
'Precond: We receive the expected identifier for a new record'
);
assert.strictEqual(identifier.id, null, 'Precond: We have no id yet');
assert.ok(updateMethodCalls === 0, 'Precond: We have not updated the identifier yet');
updateCallback = (updatedIdentifier, resource) => {
assert.strictEqual(identifier, updatedIdentifier, 'We updated the expected identifier');
assert.strictEqual(resource.attributes!.firstName, 'James', 'We received the expected resource to update with');
};
await record.save();
assert.ok(updateMethodCalls === 1, 'We made a single call to our update method');
});
test(`The configured update method is called when newly created records with an id are committed`, async function (assert) {
class TestSerializer extends EmberObject {
normalizeResponse(_, __, payload) {
return payload;
}
}
class TestAdapter extends Adapter {
createRecord() {
return resolve({
data: {
id: '1',
type: 'user',
attributes: {
firstName: 'James',
username: '@runspired',
age: 31,
},
},
});
}
}
this.owner.register('adapter:application', TestAdapter);
this.owner.register('serializer:application', TestSerializer);
let updateMethodCalls = 0 as number;
let updateCallback: (...args: any[]) => void;
function updateMethod(
identifier: StableIdentifier | StableRecordIdentifier,
data: ResourceData | unknown,
bucket: IdentifierBucket
) {
switch (bucket) {
case 'record':
updateMethodCalls++;
updateCallback!(identifier, data);
break;
default:
throw new Error(`Identifier Updates for ${bucket} have not been implemented`);
}
}
setIdentifierUpdateMethod(updateMethod);
const record = store.createRecord('user', { id: '1', firstName: 'Chris', username: '@runspired', age: 31 });
const identifier = recordIdentifierFor(record);
assert.strictEqual(
identifier.lid,
'remote:user:1',
'Precond: We receive the expected identifier for the new record'
);
assert.strictEqual(identifier.id, '1', 'Precond: We have an id already');
assert.ok(updateMethodCalls === 0, 'Precond: We have not updated the identifier yet');
updateCallback = (updatedIdentifier, resource) => {
assert.strictEqual(identifier, updatedIdentifier, 'We updated the expected identifier');
assert.strictEqual(resource.attributes!.firstName, 'James', 'We received the expected resource to update with');
};
await record.save();
assert.ok(updateMethodCalls === 1, 'We made a single call to our update method after save');
});
test(`The configured update method is called when existing records are saved successfully`, async function (assert) {
class TestSerializer extends EmberObject {
normalizeResponse(_, __, payload) {
return payload;
}
}
class TestAdapter extends Adapter {
updateRecord() {
return resolve({
data: {
id: '1',
type: 'user',
attributes: {
firstName: 'Chris',
username: '@runspired',
age: 23,
},
},
});
}
}
this.owner.register('adapter:application', TestAdapter);
this.owner.register('serializer:application', TestSerializer);
let updateMethodCalls = 0 as number;
let updateCallback: (...args: any[]) => void;
function updateMethod(
identifier: StableIdentifier | StableRecordIdentifier,
data: ResourceData | unknown,
bucket: IdentifierBucket
) {
switch (bucket) {
case 'record':
updateMethodCalls++;
updateCallback!(identifier, data);
break;
default:
throw new Error(`Identifier Updates for ${bucket} have not been implemented`);
}
}
setIdentifierUpdateMethod(updateMethod);
const record: any = store.push({
data: {
id: '1',
type: 'user',
attributes: {
firstName: 'James',
username: '@runspired',
age: 22,
},
},
});
const identifier = recordIdentifierFor(record);
assert.strictEqual(
identifier.lid,
'remote:user:1',
'Precond: We receive the expected identifier for the new record'
);
assert.strictEqual(identifier.id, '1', 'Precond: We have an id already');
assert.ok(updateMethodCalls === 0, 'Precond: We have not updated the identifier yet');
updateCallback = (updatedIdentifier, resource) => {
assert.strictEqual(identifier, updatedIdentifier, 'We updated the expected identifier');
assert.strictEqual(resource.attributes!.firstName, 'Chris', 'We received the expected resource to update with');
};
set(record, 'age', 23);
await record.save();
assert.ok(updateMethodCalls === 1, 'We made a single call to our update method after save');
});
test(`The reset method is called when the application is destroyed`, async function (assert) {
let resetMethodCalled = false;
setIdentifierResetMethod(() => {
resetMethodCalled = true;
});
run(() => store.destroy());
assert.ok(resetMethodCalled, 'We called the reset method when the application was torn down');
});
test(`The forget method is called when an identifier is "merged" with another`, async function (assert) {
class TestSerializer extends EmberObject {
normalizeResponse(_, __, payload) {
return payload;
}
}
class TestAdapter extends Adapter {
findRecord() {
return resolve({
data: {
id: '1',
type: 'user',
attributes: {
firstName: 'Chris',
username: '@runspired',
age: 31,
},
},
});
}
}
this.owner.register('adapter:application', TestAdapter);
this.owner.register('serializer:application', TestSerializer);
let generateLidCalls = 0;
setIdentifierGenerationMethod((resource: ResourceData | { type: string }) => {
if (!('id' in resource)) {
throw new Error(`Unexpected generation of new resource identifier`);
}
generateLidCalls++;
return `${resource.type}:${resource.id}`;
});
let forgetMethodCalls = 0;
let expectedIdentifier;
let testMethod = (identifier) => {
forgetMethodCalls++;
assert.ok(expectedIdentifier === identifier, `We forgot the expected identifier ${expectedIdentifier}`);
};
setIdentifierForgetMethod((identifier) => {
testMethod(identifier);
});
const userByUsernamePromise = store.findRecord('user', '@runspired');
const userByIdPromise = store.findRecord('user', '1');
assert.strictEqual(generateLidCalls, 2, 'We generated two lids');
generateLidCalls = 0;
const originalUserByUsernameIdentifier = identifierCacheFor(store).getOrCreateRecordIdentifier({
type: 'user',
id: '@runspired',
});
const originalUserByIdIdentifier = identifierCacheFor(store).getOrCreateRecordIdentifier({
type: 'user',
id: '1',
});
assert.strictEqual(generateLidCalls, 0, 'We generated no new lids when we looked up the originals');
generateLidCalls = 0;
// we expect that the username based identifier will be abandoned
expectedIdentifier = originalUserByUsernameIdentifier;
const [userByUsername, userById] = await all([userByUsernamePromise, userByIdPromise]);
const finalUserByUsernameIdentifier = recordIdentifierFor(userByUsername);
const finalUserByIdIdentifier = recordIdentifierFor(userById);
assert.strictEqual(generateLidCalls, 0, 'We generated no new lids when we looked up the final by record');
assert.strictEqual(forgetMethodCalls, 1, 'We abandoned an identifier');
assert.ok(
finalUserByUsernameIdentifier !== originalUserByUsernameIdentifier,
'We are not using the original identifier by username for the result of findRecord with username'
);
assert.strictEqual(
originalUserByIdIdentifier,
finalUserByIdIdentifier,
'We are using the identifier by id for the result of findRecord with id'
);
assert.strictEqual(
finalUserByUsernameIdentifier,
finalUserByIdIdentifier,
'We are using the identifier by id for the result of findRecord with username'
);
// end test before store teardown
testMethod = () => {};
});
test(`The forget method is called when a record deletion is fully persisted and the record unloaded`, async function (assert) {
const adapter = store.adapterFor('application');
adapter.deleteRecord = () => {
return resolve({
data: null,
});
};
let forgetMethodCalls = 0;
let expectedIdentifier;
setIdentifierForgetMethod((identifier) => {
forgetMethodCalls++;
assert.ok(expectedIdentifier === identifier, `We forgot the expected identifier ${expectedIdentifier}`);
});
const user: any = store.push({
data: {
type: 'user',
id: '1',
attributes: {
username: '@runspired',
firstName: 'Chris',
},
},
});
const userIdentifier = recordIdentifierFor(user);
user.deleteRecord();
assert.strictEqual(forgetMethodCalls, 0, 'We have not called the forget method');
forgetMethodCalls = 0;
await user.save();
assert.strictEqual(forgetMethodCalls, 0, 'We still have not called the forget method');
forgetMethodCalls = 0;
expectedIdentifier = userIdentifier;
user.unloadRecord();
await settled();
assert.strictEqual(forgetMethodCalls, 1, 'We called the forget method');
});
test(`The forget method is called when a record unload results in full removal`, async function (assert) {
let forgetMethodCalls = 0;
const expectedIdentifiers: StableRecordIdentifier[] = [];
class Container extends Model {
@belongsTo('retainer', { async: false, inverse: 'container' })
retainer;
@attr() name;
}
class Retainer extends Model {
@belongsTo('container', { async: false, inverse: 'retainer' })
container;
@belongsTo('retained-record', { async: true, inverse: 'retainer' })
retained;
@attr() name;
}
class RetainedRecord extends Model {
@belongsTo('retainer', { async: true, inverse: 'retained' })
retainer;
@attr() name;
}
const { owner } = this;
owner.register('model:container', Container);
owner.register('model:retainer', Retainer);
owner.register('model:retained-record', RetainedRecord);
setIdentifierForgetMethod((identifier) => {
forgetMethodCalls++;
let expectedIdentifier = expectedIdentifiers.shift();
assert.ok(expectedIdentifier === identifier, `We forgot the expected identifier ${expectedIdentifier}`);
});
// no retainers
const freeWillie: any = store.push({
data: {
type: 'user',
id: '1',
attributes: {
username: '@runspired',
firstName: 'Chris',
},
},
});
const freeWillieIdentifier = recordIdentifierFor(freeWillie);
expectedIdentifiers.push(freeWillieIdentifier);
freeWillie.unloadRecord();
await settled();
assert.strictEqual(forgetMethodCalls, 1, 'We called the forget method once');
forgetMethodCalls = 0;
// an async relationship retains
const jailBird: any = store.push({
data: {
type: 'retained-record',
id: '1',
attributes: {
name: "It's a Trap!",
},
relationships: {
retainer: {
data: { type: 'retainer', id: '1' },
},
},
},
});
// the aforementioned async retainer
const gatekeeper: any = store.push({
data: {
type: 'retainer',
id: '1',
attributes: {
name: 'Imperative Storm Trapper',
},
relationships: {
retained: {
data: { type: 'retained-record', id: '1' },
},
container: {
data: { type: 'container', id: '1' },
},
},
},
});
// a sync reference to a record we will unload
const jailhouse: any = store.push({
data: {
type: 'container',
id: '1',
attributes: {
name: 'callback-hell',
},
relationships: {
retainer: { data: { type: 'retainer', id: '1' } },
},
},
});
const jailBirdIdentifier = recordIdentifierFor(jailBird);
const gatekeeperIdentifier = recordIdentifierFor(gatekeeper);
const jailhouseIdentifier = recordIdentifierFor(jailhouse);
jailBird.unloadRecord();
await settled();
assert.strictEqual(forgetMethodCalls, 0, 'We have not yet called the forget method');
forgetMethodCalls = 0;
expectedIdentifiers.push(gatekeeperIdentifier, jailBirdIdentifier);
gatekeeper.unloadRecord();
await settled();
assert.strictEqual(forgetMethodCalls, 2, 'We cleaned up both identifiers');
forgetMethodCalls = 0;
expectedIdentifiers.push(jailhouseIdentifier);
jailhouse.unloadRecord();
await settled();
assert.strictEqual(forgetMethodCalls, 1, 'We clean up records with sync relationships');
});
}); | the_stack |
import { createElement, remove } from '@syncfusion/ej2-base';
import { Chart } from '../../../src/chart/chart';
import { ChartSeriesType, ChartRangePadding, ValueType, LabelPlacement, } from '../../../src/chart/utils/enum';
import { LineSeries } from '../../../src/chart/series/line-series';
import { ColumnSeries } from '../../../src/chart/series/column-series';
import { AreaSeries } from '../../../src/chart/series/area-series';
import { Crosshair } from '../../../src/chart/user-interaction/crosshair';
import { Tooltip } from '../../../src/chart/user-interaction/tooltip';
import { MouseEvents } from '../base/events.spec';
import { categoryData, categoryData1, tooltipData1, datetimeData } from '../base/data.spec';
import { DateTime } from '../../../src/chart/axis/date-time-axis';
import { Category } from '../../../src/chart/axis/category-axis';
import { DataEditing } from '../../../src/chart/user-interaction/data-editing';
import '../../../node_modules/es6-promise/dist/es6-promise';
import { unbindResizeEvents } from '../base/data.spec';
import { EmitType } from '@syncfusion/ej2-base';
import {profile , inMB, getMemoryProfile} from '../../common.spec';
import { ILoadedEventArgs, } from '../../../src/chart/model/chart-interface';
Chart.Inject(LineSeries, ColumnSeries, DateTime, Category, Tooltip, DataEditing);
Chart.Inject(Crosshair, AreaSeries);
describe('Chart Crosshair', () => {
beforeAll(() => {
const isDef = (o: any) => o !== undefined && o !== null;
if (!isDef(window.performance)) {
console.log("Unsupported environment, window.performance.memory is unavailable");
this.skip(); //Skips test (in Chai)
return;
}
});
describe('Chart Crosshair Default', () => {
let chartObj: Chart;
let elem: HTMLElement = createElement('div', { id: 'container' });
let targetElement: HTMLElement;
let loaded: EmitType<ILoadedEventArgs>; let loaded1: Function;
let trigger: MouseEvents = new MouseEvents();
let x: number;
let y: number;
beforeAll(() => {
if (document.getElementById('container')) {
document.getElementById('container').remove();
}
document.body.appendChild(elem);
chartObj = new Chart(
{
primaryXAxis: { title: 'PrimaryXAxis', valueType: 'Category', labelPlacement: 'OnTicks', crosshairTooltip: { enable: true } },
primaryYAxis: { title: 'PrimaryYAxis', rangePadding: 'Normal', labelFormat: 'C', crosshairTooltip: { enable: true } },
series: [{
dataSource: categoryData, xName: 'x', yName: 'y', animation: { enable: false },
name: 'Japan', fill: '#B82E3D', width: 2,
type: 'Column', marker: { visible: true, height: 8, width: 8 },
}, {
dataSource: categoryData1, xName: 'x', yName: 'y', animation: { enable: false },
name: 'Japan', fill: 'blue', width: 2,
type: 'Column', marker: { visible: true, height: 8, width: 8 },
}
], width: '1000',
crosshair: { enable: true },
title: 'Export', loaded: loaded, legendSettings: { visible: false }
});
chartObj.appendTo('#container');
});
afterAll((): void => {
chartObj.destroy();
elem.remove();
});
it('Default Crosshair', (done: Function) => {
loaded = (args: Object): void => {
let chartArea: HTMLElement = document.getElementById('container_ChartAreaBorder');
y = parseFloat(chartArea.getAttribute('y')) + parseFloat(chartArea.getAttribute('height')) / 2 + elem.offsetTop;
x = parseFloat(chartArea.getAttribute('x')) + parseFloat(chartArea.getAttribute('width')) / 2 + elem.offsetLeft;
trigger.mousemovetEvent(chartArea, Math.ceil(x), Math.ceil(y));
let crosshair: Element = <Element>document.getElementById('container_svg').lastChild;
let element1: HTMLElement;
expect(crosshair.childNodes.length == 3).toBe(true);
element1 = <HTMLElement>crosshair.childNodes[0];
expect(element1.getAttribute('d').indexOf(chartArea.getAttribute('x')) > 0).toBe(true);
element1 = <HTMLElement>crosshair.childNodes[1];
expect(element1.getAttribute('d').indexOf(chartArea.getAttribute('y')) > 0).toBe(true);
expect(crosshair.childNodes[2].childNodes.length == 4).toBe(true);
element1 = <HTMLElement>crosshair.childNodes[2].childNodes[0];
expect(element1.getAttribute('d') !== '').toBe(true);
element1 = <HTMLElement>crosshair.childNodes[2].childNodes[2];
expect(element1.getAttribute('d') !== '').toBe(true);
element1 = <HTMLElement>crosshair.childNodes[2].childNodes[1];
expect(element1.textContent == 'France').toBe(true);
element1 = <HTMLElement>crosshair.childNodes[2].childNodes[3];
expect(element1.textContent == '$39.97' || element1.textContent == '$39.85').toBe(true);
chartArea = document.getElementById('container_ChartAreaBorder');
y = parseFloat(chartArea.getAttribute('y')) + elem.offsetTop + 1;
x = parseFloat(chartArea.getAttribute('x')) + elem.offsetLeft + 1;
trigger.mousemovetEvent(chartArea, Math.ceil(x), Math.ceil(y));
crosshair = <Element>document.getElementById('container_svg').lastChild;
expect(crosshair.childNodes.length == 3).toBe(true);
done();
};
chartObj.loaded = loaded;
chartObj.refresh();
});
it('Customizing Axis Tooltip', (done: Function) => {
loaded = (args: Object): void => {
let chartArea: HTMLElement = document.getElementById('container_ChartAreaBorder');
y = parseFloat(chartArea.getAttribute('y')) + parseFloat(chartArea.getAttribute('height')) / 4 + elem.offsetTop;
x = parseFloat(chartArea.getAttribute('x')) + parseFloat(chartArea.getAttribute('width')) / 4 + elem.offsetLeft;
trigger.mousemovetEvent(chartArea, Math.ceil(x), Math.ceil(y));
let crosshair: Element = <Element>document.getElementById('container_svg').lastChild;
let element1: HTMLElement;
expect(crosshair.childNodes.length == 3).toBe(true);
expect(crosshair.childNodes[2].childNodes.length == 2).toBe(true);
element1 = <HTMLElement>crosshair.childNodes[2].childNodes[1];
expect(element1.getAttribute('fill') == 'red').toBe(true);
expect(element1.getAttribute('font-size') == '16px').toBe(true);
expect(element1.textContent == 'Japan').toBe(true);
done();
};
chartObj.primaryYAxis.crosshairTooltip.enable = false;
chartObj.primaryXAxis.crosshairTooltip.textStyle.color = 'red';
chartObj.primaryXAxis.crosshairTooltip.textStyle.size = '16px';
chartObj.primaryXAxis.opposedPosition = true;
chartObj.loaded = loaded;
chartObj.refresh();
});
it('OnTicks and BetweenTicks', (done: Function) => {
let chartArea: HTMLElement = document.getElementById('container_ChartAreaBorder');
y = parseFloat(chartArea.getAttribute('y')) + parseFloat(chartArea.getAttribute('height')) / 4 + elem.offsetTop;
x = parseFloat(chartArea.getAttribute('x')) + parseFloat(chartArea.getAttribute('width')) + elem.offsetLeft - 10;
trigger.mousemovetEvent(chartArea, Math.ceil(x), Math.ceil(y));
let crosshair: Element = <Element>document.getElementById('container_svg').lastChild;
let element1: HTMLElement;
element1 = <HTMLElement>crosshair.childNodes[2].childNodes[1];
expect(element1.textContent == 'France1').toBe(true);
loaded = (args: Object): void => {
let chartArea: HTMLElement = document.getElementById('container_ChartAreaBorder');
y = parseFloat(chartArea.getAttribute('y')) + parseFloat(chartArea.getAttribute('height')) / 4 + elem.offsetTop;
x = parseFloat(chartArea.getAttribute('x')) + parseFloat(chartArea.getAttribute('width')) + elem.offsetLeft - 10;
trigger.mousemovetEvent(chartArea, Math.ceil(x), Math.ceil(y));
let crosshair: Element = <Element>document.getElementById('container_svg').lastChild;
element1 = <HTMLElement>crosshair.childNodes[2].childNodes[1];
expect(element1.textContent == 'Germany1').toBe(true);
done();
};
chartObj.primaryXAxis.labelPlacement = 'BetweenTicks';
chartObj.loaded = loaded;
chartObj.refresh();
});
it('Crosshair tooltip inside position', (done: Function) => {
let element1: HTMLElement;
loaded = (args: Object): void => {
let chartArea: HTMLElement = document.getElementById('container_ChartAreaBorder');
y = parseFloat(chartArea.getAttribute('y')) + parseFloat(chartArea.getAttribute('height')) / 4 + elem.offsetTop;
x = parseFloat(chartArea.getAttribute('x')) + parseFloat(chartArea.getAttribute('width')) + elem.offsetLeft - 10;
trigger.mousemovetEvent(chartArea, Math.ceil(x), Math.ceil(y));
let crosshair: Element = <Element>document.getElementById('container_svg').lastChild;
element1 = <HTMLElement>crosshair.childNodes[2].childNodes[1];
expect(element1.textContent == 'USA').toBe(true);
done();
};
chartObj.primaryXAxis.labelPosition = 'Inside';
chartObj.primaryYAxis.labelPosition = 'Inside';
chartObj.primaryXAxis.isInversed = true;
chartObj.primaryYAxis.isInversed = true;
chartObj.primaryYAxis.crosshairTooltip.enable = true;
chartObj.loaded = loaded;
chartObj.refresh();
});
it('Crosshair tooltip opposed label inside position', (done: Function) => {
let element1: HTMLElement;
loaded = (args: Object): void => {
let chartArea: HTMLElement = document.getElementById('container_ChartAreaBorder');
y = parseFloat(chartArea.getAttribute('y')) + parseFloat(chartArea.getAttribute('height')) / 4 + elem.offsetTop;
x = parseFloat(chartArea.getAttribute('x')) + parseFloat(chartArea.getAttribute('width')) + elem.offsetLeft - 10;
trigger.mousemovetEvent(chartArea, Math.ceil(x), Math.ceil(y));
let crosshair: Element = <Element>document.getElementById('container_svg').lastChild;
element1 = <HTMLElement>crosshair.childNodes[2].childNodes[1];
expect(element1.textContent == 'USA').toBe(true);
done();
};
chartObj.primaryXAxis.labelPosition = 'Inside';
chartObj.primaryYAxis.labelPosition = 'Inside';
chartObj.primaryXAxis.isInversed = true;
chartObj.primaryYAxis.isInversed = true;
chartObj.primaryYAxis.crosshairTooltip.enable = true;
chartObj.primaryYAxis.opposedPosition = true;
chartObj.loaded = loaded;
chartObj.refresh();
});
it('Inversed Axis', (done: Function) => {
let element1: HTMLElement;
loaded = (args: Object): void => {
let chartArea: HTMLElement = document.getElementById('container_ChartAreaBorder');
y = parseFloat(chartArea.getAttribute('y')) + parseFloat(chartArea.getAttribute('height')) / 4 + elem.offsetTop;
x = parseFloat(chartArea.getAttribute('x')) + parseFloat(chartArea.getAttribute('width')) + elem.offsetLeft - 10;
trigger.mousemovetEvent(chartArea, Math.ceil(x), Math.ceil(y));
let crosshair: Element = <Element>document.getElementById('container_svg').lastChild;
element1 = <HTMLElement>crosshair.childNodes[2].childNodes[1];
expect(element1.textContent == 'USA').toBe(true);
done();
};
chartObj.primaryXAxis.isInversed = true;
chartObj.primaryYAxis.isInversed = true;
chartObj.primaryYAxis.crosshairTooltip.enable = true;
chartObj.loaded = loaded;
chartObj.refresh();
});
it('Inversed Axis with tooltip', (done: Function) => {
let element1: HTMLElement;
loaded = (args: Object): void => {
let chartArea: HTMLElement = document.getElementById('container_ChartAreaBorder');
y = parseFloat(chartArea.getAttribute('y')) + parseFloat(chartArea.getAttribute('height')) / 4 + elem.offsetTop;
x = parseFloat(chartArea.getAttribute('x')) + parseFloat(chartArea.getAttribute('width')) + elem.offsetLeft - 20;
trigger.mousemovetEvent(chartArea, Math.ceil(x), Math.ceil(y));
element1 = <HTMLElement>document.getElementById('container_axis_tooltip_text_0');
expect(element1.textContent == 'USA').toBe(true);
done();
};
chartObj.primaryXAxis.isInversed = true;
chartObj.primaryYAxis.isInversed = true;
chartObj.primaryYAxis.crosshairTooltip.enable = true;
chartObj.tooltip.enable = true;
chartObj.loaded = loaded;
chartObj.refresh();
});
it('Inversed Axis with tooltip enable crosshair at other than series regions', (done: Function) => {
let element1: HTMLElement;
loaded = (args: Object): void => {
let chartArea: HTMLElement = document.getElementById('container_ChartAreaBorder');
y = parseFloat(chartArea.getAttribute('y')) + parseFloat(chartArea.getAttribute('height')) / 4 + elem.offsetTop;
x = parseFloat(chartArea.getAttribute('x')) + parseFloat(chartArea.getAttribute('width')) + elem.offsetLeft - 10;
trigger.mousemovetEvent(chartArea, Math.ceil(x), Math.ceil(y));
element1 = <HTMLElement>document.getElementById('container_axis_tooltip_text_0');
expect(element1.textContent !== null).toBe(true);
let change : any = {changedTouches :[{clientX : 200, clientY :200}]};
chartObj.longPress({originalEvent: change });
trigger.mousemovetEvent(chartArea, 250, 250);
trigger.mouseupEvent(chartArea, 100, 100, 150, 150);
chartObj.longPress();
done();
};
chartObj.primaryXAxis.isInversed = true;
chartObj.primaryYAxis.isInversed = true;
chartObj.primaryYAxis.crosshairTooltip.enable = true;
chartObj.tooltip.enable = true;
chartObj.loaded = loaded;
chartObj.refresh();
});
});
describe('Chart Crosshair Default', () => {
let chartObj1: Chart;
let elem: HTMLElement = createElement('div', { id: 'container' });
let targetElement: HTMLElement;
let loaded: EmitType<ILoadedEventArgs>; let loaded1: Function;
let trigger: MouseEvents = new MouseEvents();
let x: number;
let y: number;
beforeAll(() => {
if (document.getElementById('container')) {
document.getElementById('container').remove();
}
document.body.appendChild(elem);
chartObj1 = new Chart(
{
primaryXAxis: { title: 'PrimaryXAxis', valueType: 'Category', labelPlacement: 'OnTicks', crosshairTooltip: { enable: true} },
primaryYAxis: { title: 'PrimaryYAxis', rangePadding: 'Normal', labelFormat: 'C', crosshairTooltip: { enable: true } },
axes: [
{ name: 'xAxis1', opposedPosition: true, crosshairTooltip: { enable: true } },
{ name: 'yAxis1', crosshairTooltip: { enable: true } }, { name: 'yAxis2', opposedPosition: true },
{ name: 'xAxis2', valueType: 'DateTime', crosshairTooltip: { enable: true } },
],
series: [{
dataSource: categoryData, xName: 'x', yName: 'y', animation: { enable: false },
name: 'China', fill: '#B82E3D', width: 2, type: 'Line',
}, {
dataSource: tooltipData1, xName: 'x', yName: 'y', animation: { enable: false },
name: 'Japan', fill: 'red', width: 2, type: 'Line', xAxisName: 'xAxis1', yAxisName: 'yAxis1'
},
{
dataSource: datetimeData, xName: 'x', yName: 'y', animation: { enable: false },
name: 'Japan', fill: 'blue', width: 2, type: 'Line', xAxisName: 'xAxis2', yAxisName: 'yAxis2'
}
], width: '1000',
crosshair: { enable: true },
title: 'Export', loaded: loaded, legendSettings: { visible: false }
});
chartObj1.appendTo('#container');
});
afterAll((): void => {
chartObj1.destroy();
elem.remove();
});
it('Default Crosshair with different type of axis', (done: Function) => {
loaded = (args: Object): void => {
let chartArea: HTMLElement = document.getElementById('container_ChartAreaBorder');
y = parseFloat(chartArea.getAttribute('y')) + parseFloat(chartArea.getAttribute('height')) / 4 + elem.offsetTop;
x = parseFloat(chartArea.getAttribute('x')) + parseFloat(chartArea.getAttribute('width')) / 2 + elem.offsetLeft;
trigger.mousemovetEvent(chartArea, Math.ceil(x), Math.ceil(y));
let crosshair: Element = <Element>document.getElementById('container_svg').lastChild;
let element1: HTMLElement;
expect((crosshair as HTMLElement).style.pointerEvents).toBe('none');
expect(crosshair.childNodes.length == 3).toBe(true);
element1 = <HTMLElement>crosshair.childNodes[0];
expect(element1.getAttribute('d').indexOf(chartArea.getAttribute('x')) > 0).toBe(true);
element1 = <HTMLElement>crosshair.childNodes[1];
expect(element1.getAttribute('d').indexOf(chartArea.getAttribute('y')) > 0).toBe(true);
expect(crosshair.childNodes[2].childNodes.length == 10).toBe(true);
element1 = <HTMLElement>crosshair.childNodes[2].childNodes[0];
expect(element1.getAttribute('d') !== '').toBe(true);
element1 = <HTMLElement>crosshair.childNodes[2].childNodes[2];
expect(element1.getAttribute('d') !== '').toBe(true);
element1 = <HTMLElement>crosshair.childNodes[2].childNodes[1];
expect(element1.textContent == 'Australia').toBe(true);
element1 = <HTMLElement>crosshair.childNodes[2].childNodes[3];
expect(element1.textContent == '$59.81' || element1.textContent == '$59.73').toBe(true);
element1 = <HTMLElement>crosshair.childNodes[2].lastChild;
expect(element1.textContent == '2005').toBe(true);
done();
};
chartObj1.loaded = loaded;
chartObj1.refresh();
});
it('Changing the Visibility different axis', (done: Function) => {
loaded = (args: Object): void => {
let chartArea: HTMLElement = document.getElementById('container_ChartAreaBorder');
y = parseFloat(chartArea.getAttribute('y')) + parseFloat(chartArea.getAttribute('height')) / 4 + elem.offsetTop;
x = parseFloat(chartArea.getAttribute('x')) + parseFloat(chartArea.getAttribute('width')) / 2 + elem.offsetLeft;
trigger.mousemovetEvent(chartArea, Math.ceil(x), Math.ceil(y));
let crosshair: Element = <Element>document.getElementById('container_svg').lastChild;
let element1: HTMLElement;
expect(crosshair.childNodes.length == 3).toBe(true);
element1 = <HTMLElement>crosshair.childNodes[0];
expect(element1.getAttribute('d').indexOf(chartArea.getAttribute('x')) > 0).toBe(true);
element1 = <HTMLElement>crosshair.childNodes[1];
expect(element1.getAttribute('d').indexOf(chartArea.getAttribute('y')) > 0).toBe(true);
expect(crosshair.childNodes[2].childNodes.length == 8).toBe(true);
element1 = <HTMLElement>crosshair.childNodes[2].childNodes[0];
expect(element1.getAttribute('d') !== '').toBe(true);
expect(element1.getAttribute('fill') == 'blue').toBe(true);
element1 = <HTMLElement>crosshair.childNodes[2].childNodes[2];
expect(element1.getAttribute('d') !== '').toBe(true);
element1 = <HTMLElement>crosshair.childNodes[2].childNodes[1];
expect(element1.textContent == '$59.81' || element1.textContent == '$59.73').toBe(true);
let elem1: HTMLElement = <HTMLElement>crosshair.childNodes[2].lastChild;
expect(elem1.getAttribute('fill') == 'red').toBe(true);
crosshair.innerHTML = '';
done();
};
chartObj1.axes[0].crosshairTooltip.enable = false;
chartObj1.axes[2].crosshairTooltip.enable = true;
chartObj1.axes[3].crosshairTooltip.textStyle.color = 'red';
chartObj1.primaryXAxis.crosshairTooltip.enable = false;
chartObj1.primaryYAxis.crosshairTooltip.fill = 'blue';
chartObj1.loaded = loaded;
chartObj1.refresh();
});
it('Changing the Visibility different axis', (done: Function) => {
loaded = (args: Object): void => {
let chartArea: HTMLElement = document.getElementById('container_ChartAreaBorder');
y = parseFloat(chartArea.getAttribute('y')) + parseFloat(chartArea.getAttribute('height')) / 3 + elem.offsetTop;
x = parseFloat(chartArea.getAttribute('x')) + parseFloat(chartArea.getAttribute('width')) / 3 + elem.offsetLeft;
trigger.mousemovetEvent(chartArea, Math.ceil(x), Math.ceil(y));
let crosshair: Element = <Element>document.getElementById('container_svg').lastChild;
let element1: HTMLElement;
expect(crosshair.childNodes.length == 3).toBe(true);
element1 = <HTMLElement>crosshair.childNodes[2].childNodes[1];
expect(element1.textContent.indexOf('#') > -1).toBe(true);
element1 = <HTMLElement>crosshair.childNodes[2].childNodes[3];
expect(element1.textContent.indexOf('$') > -1).toBe(true);
done();
};
chartObj1.axes[0].crosshairTooltip.enable = true;
chartObj1.axes[0].labelFormat = '{value}$';
chartObj1.primaryYAxis.labelFormat = '#{value}';
chartObj1.loaded = loaded;
chartObj1.refresh();
});
it('crosshair with multiple axes', (done: Function) => {
loaded = (args: Object): void => {
let chartArea: HTMLElement = document.getElementById('container_ChartAreaBorder');
y = parseFloat(chartArea.getAttribute('y')) + parseFloat(chartArea.getAttribute('height')) / 2 + elem.offsetTop;
x = parseFloat(chartArea.getAttribute('x')) + parseFloat(chartArea.getAttribute('width')) / 2 + elem.offsetLeft;
trigger.mousemovetEvent(chartArea, Math.ceil(x), Math.ceil(y));
let crosshair: Element = <Element>document.getElementById('container_svg').lastChild;
let element1: HTMLElement;
element1 = <HTMLElement>crosshair.childNodes[2].childNodes[1];
expect(element1.textContent == '105.3' || element1.textContent == '102.9').toBe(true);
done();
};
chartObj1.primaryXAxis.crosshairTooltip.enable = true;
chartObj1.axes = [{
columnIndex: 1, valueType: 'DateTime', name: 'xAxis1',
crosshairTooltip: { enable: true }
}, {
rowIndex: 1, name: 'yAxis1',
crosshairTooltip: { enable: true }
}, {
rowIndex: 1, columnIndex: 1, name: 'yAxis2',
crosshairTooltip: { enable: true }
}];
chartObj1.series = [{
dataSource: datetimeData, xName: 'x', yName: 'y', animation: { enable: false },
name: 'China', fill: '#B82E3D', width: 2, type: 'Line',
}, {
dataSource: datetimeData, xName: 'x', yName: 'y', animation: { enable: false },
name: 'Japan', fill: 'red', width: 2, type: 'Line', yAxisName: 'yAxis2', xAxisName: 'xAxis1'
},
{
dataSource: datetimeData, xName: 'x', yName: 'y', animation: { enable: false },
name: 'Japan', fill: 'blue', width: 2, type: 'Line', yAxisName: 'yAxis1',
}
];
chartObj1.rows = [{ height: '200', border: { width: 2, color: 'red' } },
{ height: '100', border: { width: 2, color: 'red' } }];
chartObj1.columns = [{ width: '300', border: { width: 2, color: 'black' } },
{ width: '300', border: { width: 2, color: 'black' } }];
chartObj1.primaryXAxis.valueType = 'DateTime';
chartObj1.axes[0].labelFormat = '';
chartObj1.primaryYAxis.labelFormat = '';
chartObj1.loaded = loaded;
chartObj1.refresh();
});
/*it('Changing the Visibility of crosshair', (done: Function) => {
chartObj1.crosshair.visible = false;
let chartArea: HTMLElement = document.getElementById('container_ChartAreaBorder');
y = parseFloat(chartArea.getAttribute('y')) + parseFloat(chartArea.getAttribute('height')) / 4 + elem.offsetTop;
x = parseFloat(chartArea.getAttribute('x')) + parseFloat(chartArea.getAttribute('width')) / 2 + elem.offsetLeft;
trigger.mousemovetEvent(chartArea, Math.ceil(x), Math.ceil(y));
let crosshair: Element = <Element>document.getElementById('container_svg').lastChild;
expect(crosshair.children.length == 0).toBe(true);
});*/
});
/**
* Cheacking point drag and drop with crosshair
*/
describe('Line series point drag and drop with crosshair', () => {
let chartObj: Chart; let x: number; let y: number;
let loaded: EmitType<ILoadedEventArgs>;
let trigger: MouseEvents = new MouseEvents();
let element1: HTMLElement = createElement('div', { id: 'container' });
beforeAll(() => {
document.body.appendChild(element1);
chartObj = new Chart(
{
primaryXAxis: {
valueType: 'DateTime',
labelFormat: 'y',
intervalType: 'Years',
crosshairTooltip: { enable: true },
edgeLabelPlacement: 'Shift',
majorGridLines: { width: 0 }
},
//Initializing Primary Y Axis
primaryYAxis:
{
labelFormat: '{value}%',
rangePadding: 'None',
minimum: 0,
maximum: 100,
interval: 20,
crosshairTooltip: { enable: true },
lineStyle: { width: 0 },
majorTickLines: { width: 0 },
minorTickLines: { width: 0 }
},
chartArea: {
border: {
width: 0
}
},
//Initializing Chart Series
series: [
{
type: 'Line',
dataSource: [
{ x: new Date(2005, 0, 1), y: 21 }, { x: new Date(2006, 0, 1), y: 24 },
{ x: new Date(2007, 0, 1), y: 36 }, { x: new Date(2008, 0, 1), y: 38 },
{ x: new Date(2009, 0, 1), y: 54 }, { x: new Date(2010, 0, 1), y: 57 },
{ x: new Date(2011, 0, 1), y: 70 }
],
animation: { enable: false },
xName: 'x', width: 2, marker: {
visible: true,
width: 20,
height: 20
},
yName: 'y', name: 'Germany', dragSettings: { enable: true }
},
{
type: 'Line',
dataSource: [
{ x: new Date(2005, 0, 1), y: 28 }, { x: new Date(2006, 0, 1), y: 44 },
{ x: new Date(2007, 0, 1), y: 48 }, { x: new Date(2008, 0, 1), y: 50 },
{ x: new Date(2009, 0, 1), y: 66 }, { x: new Date(2010, 0, 1), y: 78 }, { x: new Date(2011, 0, 1), y: 84 }
],
animation: { enable: false },
xName: 'x', width: 2, marker: {
visible: true,
width: 20,
height: 20
},
yName: 'y', name: 'England', dragSettings: { enable: true }
}
],
//Initializing Chart title
title: 'Inflation - Consumer Price',
//Initializing User Interaction Tooltip
tooltip: { enable: true},
crosshair: { enable: true},
});
chartObj.appendTo('#container');
});
afterAll((): void => {
chartObj.destroy();
element1.remove();
});
it('line series drag and drop with crosshair', (done: Function) => {
loaded = (): void => {
let target: HTMLElement = document.getElementById('container_Series_1_Point_0_Symbol');
let chartArea: HTMLElement = document.getElementById('container_ChartAreaBorder');
y = parseFloat(target.getAttribute('cy')) + parseFloat(chartArea.getAttribute('y')) + element1.offsetTop;
x = parseFloat(target.getAttribute('cx')) + parseFloat(chartArea.getAttribute('x')) + element1.offsetLeft;
trigger.mousemovetEvent(target, Math.ceil(x), Math.ceil(y));
trigger.draganddropEvent(element1, Math.ceil(x), Math.ceil(y), Math.ceil(x), Math.ceil(y) - 108);
let yValue: number = chartObj.visibleSeries[1].points[0].yValue;
expect(yValue == 60.24 || yValue == 59.65).toBe(true);
chartObj.loaded = null;
done();
};
chartObj.loaded = loaded;
chartObj.refresh();
});
});
describe('Crosshair customization', () => {
let chartObj: Chart; let x: number; let y: number;
let loaded: EmitType<ILoadedEventArgs>;
let trigger: MouseEvents = new MouseEvents();
let elem: HTMLElement = createElement('div', { id: 'crosshairContainer' });
let series1: Object[] = [];
let point1: Object;
let value: number = 80;
let i: number;
for (i = 1; i < 500; i++) {
if (Math.random() > .5) {
value += Math.random();
} else {
value -= Math.random();
}
point1 = { x: new Date(1910, i + 2, i), y: value.toFixed(1) };
series1.push(point1);
}
beforeAll(() => {
document.body.appendChild(elem);
chartObj = new Chart(
{
//Initializing Primary X Axis
primaryXAxis: {
majorGridLines: { width: 0 },
valueType: 'DateTime',
crosshairTooltip: { enable: true },
},
primaryYAxis:
{
minimum: 83, maximum: 95, interval: 1,
title: 'Millions in USD',
labelFormat: '{value}M',
rowIndex: 0,
crosshairTooltip: {
enable: true
}
},
//Initializing Chart Series
series: [
{
type: 'Area',
dataSource: series1,
name: 'Product X',
xName: 'x',
yName: 'y',
border: { width: 0.5, color: 'black' },
},
],
//Initializing Zooming
//Initializing Chart title
title: 'Sales History of Product X',
crosshair: { enable: true },
});
chartObj.appendTo('#crosshairContainer');
});
afterAll((): void => {
chartObj.destroy();
elem.remove();
});
it('X axis crosshair opacity checking', (done: Function) => {
loaded = (args: Object): void => {
let chartArea: HTMLElement = document.getElementById('crosshairContainer_ChartAreaBorder');
y = parseFloat(chartArea.getAttribute('y')) + parseFloat(chartArea.getAttribute('height')) / 4 + elem.offsetTop;
x = parseFloat(chartArea.getAttribute('x')) + parseFloat(chartArea.getAttribute('width')) / 4 + elem.offsetLeft;
trigger.mousemovetEvent(chartArea, Math.ceil(x), Math.ceil(y));
let crosshair: Element = <Element>document.getElementById('crosshairContainer_svg').lastChild;
let element1: HTMLElement;
let element2: HTMLElement;
expect(crosshair.childNodes.length == 3 || crosshair.childNodes.length == 2).toBe(true);
element1 = <HTMLElement>crosshair.childNodes[0];
expect(element1.getAttribute('opacity') == '0.5' || element1.getAttribute('opacity') == '1').toBe(true);
element2 = <HTMLElement>crosshair.childNodes[1];
expect(element2.getAttribute('opacity') == '0.5' || element2.getAttribute('opacity') == null).toBe(true);
done();
};
chartObj.crosshair.opacity = 0.5;
chartObj.loaded = loaded;
chartObj.refresh();
});
it('Customizing crosshair color', (done: Function) => {
loaded = (args: Object): void => {
let chartArea: HTMLElement = document.getElementById('crosshairContainer_ChartAreaBorder');
y = parseFloat(chartArea.getAttribute('y')) + parseFloat(chartArea.getAttribute('height')) / 4 + elem.offsetTop;
x = parseFloat(chartArea.getAttribute('x')) + parseFloat(chartArea.getAttribute('width')) / 4 + elem.offsetLeft;
trigger.mousemovetEvent(chartArea, Math.ceil(x), Math.ceil(y));
let crosshair: Element = <Element>document.getElementById('crosshairContainer_svg').lastChild;
let element1: HTMLElement;
let element2: HTMLElement;
expect(crosshair.childNodes.length == 3 || crosshair.childNodes.length == 2).toBe(true);
element1 = <HTMLElement>crosshair.childNodes[0];
element2 = <HTMLElement>crosshair.childNodes[1];
expect(element1.getAttribute('fill') == 'red' || element1.getAttribute('fill') == 'transparent' ).toBe(true);
expect(element2.getAttribute('fill') == 'green' || element2.getAttribute('fill') == null ).toBe(true);
done();
};
chartObj.crosshair.horizontalLineColor = 'red';
chartObj.crosshair.verticalLineColor = 'green';
chartObj.loaded = loaded;
chartObj.refresh();
});
});
it('memory leak', () => {
profile.sample();
let average: any = inMB(profile.averageChange)
//Check average change in memory samples to not be over 10MB
expect(average).toBeLessThan(10);
let memory: any = inMB(getMemoryProfile())
//Check the final memory usage against the first usage, there should be little change if everything was properly deallocated
expect(memory).toBeLessThan(profile.samples[0] + 0.25);
})
}); | the_stack |
module WinJSTests {
"use strict";
var ITEMS_COUNT = 5;
var Key = WinJS.Utilities.Key;
var ListView = <typeof WinJS.UI.PrivateListView> WinJS.UI.ListView;
function getDataSource(count?) {
var rawData = [];
for (var i = 0; i < (count ? count : ITEMS_COUNT); i++) {
rawData.push({ itemInfo: "Tile" + i });
}
return new WinJS.Binding.List(rawData).dataSource;
}
function basicRenderer(itemPromise) {
var element = document.createElement("div");
element.style.width = "50px";
element.style.height = "50px";
return {
element: element,
renderComplete: itemPromise.then(function (item) {
element.textContent = item.data.itemInfo;
if (item.data.markUndraggable) {
element.className += " " + WinJS.UI._nonDraggableClass;
}
if (item.data.markUnselectable) {
element.className += " " + WinJS.UI._nonSelectableClass;
}
})
};
}
function eventOnElement(element, useShift?) {
var rect = element.getBoundingClientRect();
return {
target: element,
clientX: (rect.left + rect.right) / 2,
clientY: (rect.top + rect.bottom) / 2,
preventDefault: function () { },
shiftKey: !!useShift,
button: undefined
};
}
function click(listView, index, useRight, useShift?) {
var mode = listView._currentMode();
var item = listView.elementFromIndex(index);
item.scrollIntoView(true);
var eventObject = eventOnElement(item, useShift);
eventObject.button = (useRight ? WinJS.UI._RIGHT_MSPOINTER_BUTTON : WinJS.UI._LEFT_MSPOINTER_BUTTON);
mode.onPointerDown(eventObject);
mode.onPointerUp(eventObject);
mode.onclick();
}
function generateKeyEventInListView(listView, keyPressed, ctrlDown, altDown, shiftDown) {
var fakeEventObject = {
ctrlKey: !!ctrlDown,
altKey: !!altDown,
shiftKey: !!shiftDown,
keyCode: keyPressed,
preventDefault: function () { },
stopPropagation: function () { },
target: listView.element
};
listView._currentMode()["onKeyDown"](fakeEventObject);
}
function changeListViewFocus(listView, focusedIndex) {
listView._selection._setFocused({ type: "item", index: focusedIndex }, false);
}
export class NonDragAndSelectTests {
setUp() {
LiveUnit.LoggingCore.logComment("In setup");
var newNode = document.createElement("div");
newNode.id = "NonDragAndSelectTests";
newNode.style.width = "500px";
newNode.style.height = "500px";
document.body.appendChild(newNode);
}
tearDown() {
LiveUnit.LoggingCore.logComment("In tearDown");
var element = document.getElementById("NonDragAndSelectTests");
document.body.removeChild(element);
}
}
function generate(name, undraggableIndices, unselectableIndicies, testFunction) {
NonDragAndSelectTests.prototype[name] = function (complete) {
LiveUnit.LoggingCore.logComment("in " + name);
var element = document.getElementById("NonDragAndSelectTests");
var data = getDataSource();
var list = data['_list'];
for (var i in undraggableIndices) {
list.getItem(undraggableIndices[i]).data.markUndraggable = true;
}
for (var i in unselectableIndicies) {
list.getItem(unselectableIndicies[i]).data.markUnselectable = true;
}
var listView = new ListView(element, {
itemTemplate: basicRenderer,
itemDataSource: data
});
Helper.ListView.waitForAllContainers(listView).done(function () {
listView._currentMode()._itemEventsHandler._getCurrentPoint = function (eventObject) {
return {
properties: {
isRightButtonPressed: eventObject.button === WinJS.UI._RIGHT_MSPOINTER_BUTTON,
isLeftButtonPressed: eventObject.button === WinJS.UI._LEFT_MSPOINTER_BUTTON
}
};
};
testFunction(listView, complete);
});
};
}
generate("testSelectAllWithNonSelectableItems", [], [1, 2], function (listView, complete) {
listView.selectionMode = WinJS.UI.SelectionMode.multi;
generateKeyEventInListView(listView, Key.a, true, false, false);
LiveUnit.Assert.isTrue(listView.selection._isIncluded(0));
LiveUnit.Assert.isFalse(listView.selection._isIncluded(1));
LiveUnit.Assert.isFalse(listView.selection._isIncluded(2));
LiveUnit.Assert.isTrue(listView.selection._isIncluded(3));
LiveUnit.Assert.isTrue(listView.selection._isIncluded(4));
complete();
});
generate("testRangeSelectionViaKeyboardWithNonSelectableItems", [], [1, 2], function (listView, complete) {
listView.selectionMode = WinJS.UI.SelectionMode.multi;
changeListViewFocus(listView, 0);
generateKeyEventInListView(listView, Key.pageDown, false, false, true);
LiveUnit.Assert.isTrue(listView.selection._isIncluded(0));
LiveUnit.Assert.isFalse(listView.selection._isIncluded(1));
LiveUnit.Assert.isFalse(listView.selection._isIncluded(2));
LiveUnit.Assert.isTrue(listView.selection._isIncluded(3));
LiveUnit.Assert.isTrue(listView.selection._isIncluded(4));
complete();
});
generate("testRangeSelectionViaMouseWithNonSelectableItems", [], [1, 2], function (listView, complete) {
listView.selectionMode = WinJS.UI.SelectionMode.multi;
listView.tapBehavior = WinJS.UI.TapBehavior.toggleSelect;
click(listView, 0, false, false);
click(listView, 4, false, true);
LiveUnit.Assert.isTrue(listView.selection._isIncluded(0));
LiveUnit.Assert.isFalse(listView.selection._isIncluded(1));
LiveUnit.Assert.isFalse(listView.selection._isIncluded(2));
LiveUnit.Assert.isTrue(listView.selection._isIncluded(3));
LiveUnit.Assert.isTrue(listView.selection._isIncluded(4));
listView.selection.clear();
click(listView, 0, false, false);
click(listView, 2, false, true);
LiveUnit.Assert.isTrue(listView.selection._isIncluded(0));
LiveUnit.Assert.isFalse(listView.selection._isIncluded(1));
LiveUnit.Assert.isFalse(listView.selection._isIncluded(2));
complete();
});
generate("testSelectionViaKeyboardWithNonSelectableItems", [], [1, 2], function (listView, complete) {
listView.selectionMode = WinJS.UI.SelectionMode.multi;
changeListViewFocus(listView, 0);
generateKeyEventInListView(listView, Key.space, false, false, false);
LiveUnit.Assert.isTrue(listView.selection._isIncluded(0));
listView.selection.clear();
changeListViewFocus(listView, 1);
generateKeyEventInListView(listView, Key.space, false, false, false);
LiveUnit.Assert.isFalse(listView.selection._isIncluded(1));
listView.selection.clear();
changeListViewFocus(listView, 2);
generateKeyEventInListView(listView, Key.space, false, false, false);
LiveUnit.Assert.isFalse(listView.selection._isIncluded(2));
listView.selection.clear();
changeListViewFocus(listView, 3);
generateKeyEventInListView(listView, Key.space, false, false, false);
LiveUnit.Assert.isTrue(listView.selection._isIncluded(3));
complete();
});
generate("testSelectionViaMouseWithNonSelectableItems", [], [1, 2], function (listView, complete) {
listView.selectionMode = WinJS.UI.SelectionMode.multi;
click(listView, 0, true);
LiveUnit.Assert.isFalse(listView.selection._isIncluded(0));
complete();
});
generate("testSelectionViaAriaWithNonSelectableItems", [], [1, 2], function (listView, complete) {
function setAriaSelected(index, selected) {
listView.elementFromIndex(index).setAttribute("aria-selected", selected);
}
function verifySelection(expectedSelection) {
var verifiedSelectedCount = 0;
for (var i = 0; i < 5; i++) {
var selected = (expectedSelection.indexOf(i) !== -1);
var item = listView.elementFromIndex(i);
LiveUnit.Assert.areEqual(selected, WinJS.Utilities.hasClass(item.parentNode, WinJS.UI._selectedClass),
"Item " + i + ": win-itembox's selected class is in the wrong state");
LiveUnit.Assert.areEqual(selected, item.getAttribute("aria-selected") === "true",
"Item " + i + ": aria-selected is incorrect");
LiveUnit.Assert.areEqual(selected, listView.selection._isIncluded(i),
"Item " + i + ": ListView's selection manager is incorrect");
if (selected) verifiedSelectedCount++;
}
LiveUnit.Assert.areEqual(expectedSelection.length, verifiedSelectedCount,
"Didn't verify the selection state for all items");
}
listView.selectionMode = WinJS.UI.SelectionMode.multi;
WinJS.Promise.wrap().then(function () {
setAriaSelected(0, true);
return WinJS.Promise.timeout();
}).then(function () {
verifySelection([0]);
setAriaSelected(1, true);
return WinJS.Promise.timeout();
}).then(function () {
verifySelection([0]);
setAriaSelected(2, true);
return WinJS.Promise.timeout();
}).then(function () {
verifySelection([0]);
setAriaSelected(3, true);
return WinJS.Promise.timeout();
}).then(function () {
verifySelection([0, 3]);
// Simulate UIA SelectionItem.Select on item 4
setAriaSelected(0, false);
setAriaSelected(3, false);
setAriaSelected(4, true);
return WinJS.Promise.timeout();
}).then(function () {
verifySelection([4]);
// Verify that for a bulk selection change, selectable items get updated
// while unselectable items are reverted back to their old aria-selected values
setAriaSelected(0, true);
setAriaSelected(1, true);
setAriaSelected(2, true);
setAriaSelected(3, true);
setAriaSelected(4, false);
return WinJS.Promise.timeout();
}).then(function () {
verifySelection([0, 3]);
complete();
});
});
generate("testSingleSelectionModeWithNonSelectableItems", [], [1, 2], function (listView, complete) {
listView.selectionMode = WinJS.UI.SelectionMode.single;
changeListViewFocus(listView, 0);
generateKeyEventInListView(listView, Key.space, false, false, false);
LiveUnit.Assert.isTrue(listView.selection._isIncluded(0));
changeListViewFocus(listView, 1);
generateKeyEventInListView(listView, Key.space, false, false, false);
LiveUnit.Assert.isTrue(listView.selection._isIncluded(0));
LiveUnit.Assert.isFalse(listView.selection._isIncluded(1));
click(listView, 1, true);
LiveUnit.Assert.isTrue(listView.selection._isIncluded(0));
LiveUnit.Assert.isFalse(listView.selection._isIncluded(1));
complete();
});
}
LiveUnit.registerTestClass("WinJSTests.NonDragAndSelectTests"); | the_stack |
import * as moment from 'moment';
import * as cytoscape from 'cytoscape';
import { HTTPCommandQuery, GraphQueryResult, OrientErrorMessage, Rid } from './db_types';
import { BundleType, Id, Identifier, SDO, SRO, StixNodeData, StixObject } from '../stix';
// import { } from './stixnode';
import * as _ from 'lodash';
import * as diffpatch from 'jsondiffpatch';
import { DiffDialog } from '../ui/diff-dialog';
import * as http_codes from 'http-status-codes';
import { ErrorWidget } from '../ui/errorWidget';
import * as orientjs from 'orientjs';
import { PropertyCreateConfig, QueryOptions } from 'orientjs';
import { DatabaseConfigurationStorage } from '../storage';
import { ipcRenderer } from 'electron';
import { IDatabaseConfigOptions } from '../storage/database-configuration-storage';
import { openDatabaseConfiguration } from '../ui/database-config-widget';
export class DBConnectionError implements Error {
public message: string;
public name: string;
constructor(message: string, stack: string) {
const dialog = new ErrorWidget($('#error-anchor'));
$('#query-status').html('Database Connection Error!');
this.message = message;
dialog.populate("Error Connecting to database", `
<p>Message: ${message}</p>
<p>Stack: ${stack}</p>`);
}
public display() {
const dialog = new ErrorWidget($('#error-anchor'));
dialog.open();
}
}
export class HTTPQueryError implements Error {
public props: any;
public code: number;
public name: string = "QueryError";
public message: string;
public json: OrientErrorMessage;
public statusCode = this.code;
public statusMessage = this.message;
constructor(code: string | number, msg: string, props?: any) {
if (typeof code === "string") { (this.isCodeString(code)) ? code = http_codes[code] : code = +code; }
if (typeof code !== "number") { throw new TypeError(`unsupported HTTP Code: ${code}`); }
if (typeof msg === "object" && msg !== null) { props = msg; msg = null; }
this.code = code;
try {
this.json = JSON.parse(msg);
this.message = JSON.stringify(this.json);
} catch (e) {
this.json = undefined;
this.message = msg;
}
this.props = props;
$('#query-status').html('Query Error!');
}
private isCodeString(code: string) {
// tslint:disable-next-line:use-isnan
return +code === NaN;
}
public toHtml() {
let msg = '<h3> Query Error </h3>';
if (this.json !== undefined && this.json.errors && this.json.errors.length > 0) {
this.json.errors.forEach((e) => {
msg += `<p><b>Status Code:</b> ${e.code}
${http_codes.getStatusText(e.code)}<\p>
<b>Error: </b>`;
msg += `<p>${e.content.replace(/</g, '<').replace(/>/g, '>').replace(/\n/g, '<br>')}</p>`;
});
} else {
msg += this.message;
}
// console.log(msg);
return msg;
}
public display() {
const dialog = new ErrorWidget($('#error-anchor'));
dialog.populate('Query Error', this.toHtml());
dialog.open();
}
}
export class StigDB {
public db_config: IDatabaseConfigOptions;
public headersLocal: { "Authorization": string; "Content-Type": string; };
public ojs: orientjs.ODatabase;
public odb: orientjs.Db;
public diff_dialog: DiffDialog;
public dbhost: string;
public dbname: string;
public commandurl: string;
public gremlinurl: string;
public baseurl: string;
public _properties_cache: { [k: string]: orientjs.Property[] } = {};
constructor(dbname: string) {
ipcRenderer.on('database_reconfigured', (_event: Event, options: IDatabaseConfigOptions) => this.changeConfig(options));
this.diff_dialog = new DiffDialog($('#diff-anchor'));
if (dbname === undefined) {
this.configure();
} else {
this.changeConfig(DatabaseConfigurationStorage.Instance.get(dbname));
}
}
private configure() {
// const sleep = (time: number) => new Promise((resolve) => setTimeout(resolve, time));
// try {
openDatabaseConfiguration();
// // tslint:disable-next-line:no-empty
// } catch (e) {
// const err = new DBConnectionError(e.message, e.stack);
// await err.display();
// }
// return;
}
private changeConfig(options: IDatabaseConfigOptions): void {
this.db_config = options;
this.headersLocal = {
"Authorization": "Basic " + Buffer.from(`${options.username}:${options.password}`).toString('base64'),
"Content-Type": "application/json;charset=utf-8",
};
this.dbname = options.name;
this.commandurl = `http://${this.db_config.host}:2480/command/${this.dbname}/sql/-/-1`;
this.gremlinurl = `http://${this.db_config.host}:2480/command/${this.dbname}/gremlin/-/-1`;
this.baseurl = 'http://' + this.db_config.host + ':2480';
this.diff_dialog = new DiffDialog($('#diff-anchor'));
if (this.ojs !== undefined) {
this.ojs.close();
}
try {
this.ojs = new orientjs.ODatabase(options);
this.ojs.open().then((db) => this.odb = db);
} catch (e) {
alert(`Error Opening Database: \n\t${e.name}\nMessage: \n\t${e.message}\n\nOpening Configuration`);
openDatabaseConfiguration();
console.error(e.name, e.message);
}
DatabaseConfigurationStorage.Instance.current = options.name;
}
// private _aliases = {
// "attack-pattern": "attackpattern",
// "course-of-action": "courseofaction",
// "intrusion-set": "intrusionset",
// "marking-definition": "markingdefinition",
// "observed-data": "observeddata",
// "threat-actor": "threatactor",
// };
/**
* @description
* @param {string} clazz
* @returns {Promise<orientjs.Property[]>}
* @memberof StigDB
*/
public async listPropertiesForClass(clazz: string): Promise<orientjs.Property[]> {
// let classes = this.metadata['classes'];
// if (clazz in this._aliases) {
// clazz = this._aliases[clazz];
// }
if (clazz in this._properties_cache) {
return this._properties_cache[clazz];
}
const fields: orientjs.Property[] = [];
try {
const regex = /-/g;
const cls = await this.ojs.class.get(clazz.replace(regex, ''));
const props = await cls.property.list();
for (const f in props) {
if (props[f]) {
fields.push(props[f]);
}
}
if (cls.superClass) {
fields.push(...await this.listPropertiesForClass(cls.superClass));
}
this._properties_cache[clazz] = fields;
return fields;
} catch (err) {
// tslint:disable-next-line:no-console
console.error(`Error in listPropertiesForClass:
${err}`);
err.stack += (new Error()).stack;
throw err;
}
}
public async OJSQuery(query: string, options: QueryOptions): Promise<StixObject[]> {
let ret;
try {
// options.mode = 'graph';
ret = await this.ojs.query(query, options);
return ret;
} catch (err) {
// console.error(`OJSQuery Error:\n${err}`);
err.stack += (new Error()).stack;
throw err;
}
}
public async doQuery(query: HTTPCommandQuery): Promise<GraphQueryResult> {
const fetchData: RequestInit = {
method: 'POST',
body: JSON.stringify(query),
mode: "cors" as RequestMode,
headers: this.headersLocal,
};
if (query.command.length === 0) {
const ret: GraphQueryResult = {
graph: {
edges: [],
vertices: [],
},
};
return ret;
}
let url;
if (query.command.startsWith('g.')) { url = this.gremlinurl; } else { url = this.commandurl; }
let result;
try {
result = await fetch(url, fetchData);
if (result.ok) {
const ret = result.json();
return ret as Promise<GraphQueryResult>;
} else {
const error = new HTTPQueryError(result.status, await result.text(), { response: result });
error.display();
return {
graph: {
edges: [],
vertices: [],
},
};
// throw error;
}
} catch (e) {
const ee: Error = e;
const error = new HTTPQueryError(ee.name, ee.message, ee.stack);
error.display();
return {
graph: {
edges: [],
vertices: [],
},
};
}
}
public async doGraphQuery(query: HTTPCommandQuery): Promise<GraphQueryResult> {
query.mode = 'graph';
let url: string;
if (query.command.startsWith('g.')) { url = this.gremlinurl; } else { url = this.commandurl; }
const fetchData: RequestInit = {
method: 'POST',
body: JSON.stringify(query),
mode: "cors" as RequestMode,
headers: this.headersLocal,
};
let result;
try {
result = await fetch(url, fetchData);
if (result.status === 200) {
const ret = result.json();
return ret as Promise<GraphQueryResult>;
} else {
const error = new HTTPQueryError(result.status, await result.text(), { response: result });
error.display();
return {
graph: {
edges: [],
vertices: [],
},
};
}
} catch (e) {
alert(`Error Running Query: \n\t${e.name}\nMessage: \n\t${e.message}\n\nOpening Configuration`);
openDatabaseConfiguration();
console.error(e.name, e.message);
return {
graph: {
edges: [],
vertices: [],
},
};
}
}
/**
* @description For a given Stix identifier, returns the Orient record ID, or undefined if it is not in the database
* @param {Identifier} identifier
* @returns {Promise<Rid>}
* @memberof StigDB
*/
public async getRID(identifier: Identifier): Promise<Rid | undefined> {
let rid: Rid;
let query;
try {
if (identifier.startsWith('relationship') || identifier.startsWith('sighting')) {
query = "select from E where id_=:id order by modified desc limit 1";
} else {
query = "select from V where id_=:id order by modified desc limit 1";
}
const result = await this.ojs.query(query, { params: { id: identifier } });
if (result && result.length > 0) {
rid = result[0]['@rid'];
return rid;
} else {
return undefined;
}
} catch (e) {
console.error('getRid error: ' + identifier);
e.stack += (new Error()).stack;
throw e;
}
}
/**
* @description Returns the modified date for the most recent record, returns undefined if no record is found
* @param {Identifier} identifier
* @returns {Promise<string>}
* @memberof StigDB
*/
public async getModified(identifier: Identifier): Promise<string | undefined> {
let command: string;
if (identifier.startsWith('relation') || identifier.startsWith('sighting')) {
command = "select from E where id_= :id ORDER By modified DESC LIMIT 1";
} else {
command = "select from V where id_= :id ORDER By modified DESC LIMIT 1";
}
const options: QueryOptions = {
params: { id: identifier },
};
let result: StixObject[];
try {
result = await this.ojs.query(command, options);
if (result && result.length > 0) {
return result[0].modified as string;
} else {
return undefined;
}
} catch (e) {
console.error('Excpetion running query:', command);
e.stack += (new Error()).stack;
throw e;
}
}
/**
* @description Gets SDO or SCO from db.
* @param {Identifier} identifier
* @returns {Promise<SDO>}
* @memberof StigDB
*/
public async getSDO(identifier: Identifier): Promise<SDO | undefined> {
const query = "select from V where id_=:id ORDER BY modified DESC limit 1";
const options: QueryOptions = {
params: {
id: identifier,
},
};
let result: StixObject[];
try {
result = await this.ojs.query(query, options);
if (result.length > 0) {
return result[0] as SDO;
} else {
return undefined;
}
} catch (e) {
console.error('Exception in getSDO: ' + query);
e.stack += (new Error()).stack;
throw e;
}
}
/**
* @description
* @param {Identifier} identifier
* @returns {Promise<SRO>}
* @memberof StigDB
*/
public async getEdge(identifier: Identifier): Promise<SRO | undefined> {
const query = "select from E where id_=:id ORDER BY modified DESC limit 1";
const options: QueryOptions = {
params: {
id: identifier,
},
};
let result: StixObject[];
let ret: SRO | undefined;
try {
result = await this.ojs.query(query, options);
(result.length > 0) ? ret = result[0] as SRO : ret = undefined;
return ret;
} catch (e) {
console.error('Exception in getSDO:' + query);
e.stack += (new Error()).stack;
throw e;
}
}
public async exists(identifier: Identifier): Promise<boolean> {
let query = "select from V where id_= :id";
const options: QueryOptions = {
params: {
id: identifier,
},
};
let v_result;
let e_result;
try {
// vertex?
v_result = await this.OJSQuery(query, options);
if (v_result && v_result.length > 0) { return true; }
// edge?
query = "select from E where id_= :id";
e_result = await this.OJSQuery(query, options);
if (e_result && e_result.length > 0) { return true; }
// nuthin
return false;
} catch (e) {
console.error('Exception in exists:' + query);
e.stack += (new Error()).stack;
throw e;
}
}
/**
* @description Get the database class for the named class
* @param {string} cls_name
* @returns {Promise<orientjs.Class>}
* @memberof StigDB
*/
public async getClass(cls_name: string): Promise<orientjs.Class> {
let ret: orientjs.Class;
try {
const regex = /-/g;
ret = await this.ojs.class.get(cls_name.replace(regex, ''));
return ret;
} catch (e) {
console.error('Exception in getClass:');
e.stack += (new Error()).stack;
throw e;
}
}
/**
* @description Get the database properties list for a named class
* @param {string} cls_name
* @returns {Promise<orientjs.Property[]>}
* @memberof StigDB
*/
public async getClassProperties(cls_name: string): Promise<orientjs.Property[] | undefined> {
let cls;
try {
const regex = /-/g;
cls = await this.ojs.class.get(cls_name.replace(regex, ''));
if (cls === undefined) { return undefined; }
return cls.property.list();
} catch (e) {
console.error('Exception in getClass:');
e.stack += (new Error()).stack;
throw e;
}
}
/**
* @description
* @param {string} className
* @param {PropertyCreateConfig[]} props
* @returns {Promise<orientjs.Class>}
* @memberof StigDB
*/
public async createVertexClass(className: string, props: PropertyCreateConfig[]): Promise<orientjs.Class> {
let cls;
try {
cls = await this.ojs.class.create(className, 'V.Core', undefined, false, true); // create the class
for (const p of props) {
cls.property.create(p);
}
return cls;
} catch (e) {
e.stack += (new Error()).stack;
throw e;
}
}
/**
* @description
* @param {string} className
* @param {string} propertyName
* @param {string} propertyType
* @returns {Promise<orientjs.Property>}
* @memberof StigDB
*/
public async addPropertyToClass(className: string, propertyName: string, propertyType: string): Promise<orientjs.Property> {
let cls;
let property;
try {
const regex = /-/g;
cls = await this.ojs.class.get(className.replace(regex, ''));
property = await cls.property.create({ name: propertyName, type: propertyType } as PropertyCreateConfig);
return property;
} catch (e) {
e.stack += (new Error()).stack;
throw e;
}
}
/**
* @description
* @param {string} className
* @param {PropertyCreateConfig[]} props
* @returns {Promise<orientjs.Class>}
* @memberof StigDB
*/
public async createEdgeClass(className: string, props: PropertyCreateConfig[]): Promise<orientjs.Class> {
let cls;
try {
cls = await this.ojs.class.create(className, 'E.relationship', undefined, false, true); // create the class
for (const p of props) {
cls.property.create(p);
}
return cls;
} catch (e) {
e.stack += (new Error()).stack;
throw e;
}
}
/**
* @description User deleted an edge from the graph in the UI
* @param {SRO} sro
* @returns {Promise<StixObject[]>}
* @memberof StigDB
*/
public async sroDestroyedUI(sro: SRO): Promise<StixObject[]> {
let rid = await this.getRID(sro.id);
const q = `DELETE EDGE E WHERE @rid == "${rid}"`;
const options: QueryOptions = {};
let result: StixObject[];
try {
result = await this.OJSQuery(q, options);
return result;
} catch (e) {
e.stack += (new Error()).stack;
throw e;
}
}
/**
* @descriptionUer User deleted a node from the graph in the UI
* @param {SDO} sdo
* @returns {Promise<StixObject[]>}
* @memberof StigDB
*/
public async sdoDestroyedUI(sdo: SDO): Promise<StixObject[]> {
const q = `DELETE VERTEX FROM (SELECT FROM V where id_="${sdo.id}")`;
const options: QueryOptions = {};
let result: StixObject[];
try {
result = await this.OJSQuery(q, options);
return result;
} catch (e) {
e.stack += (new Error()).stack;
throw e;
}
}
/**
* @description Find neighbors for a given sdo node
* @param {string} identifier
* @param {Array<string>} [relationship_types]
* @returns {Promise<{ nodes: StixObject[], edges: StixObject[] }>}
* @memberof StigDB
*/
public async getChildren(identifier: string, relationship_type?: string): Promise<{ nodes: StixObject[], edges: StixObject[] }> {
let query: string;
if (relationship_type === undefined) {
query = "select expand(out()) from V where id_= :id";
} else {
query = `select expand(out('${relationship_type}')) from V where id_= :id`;
}
const options: QueryOptions = {
params: {
id: identifier,
},
};
let vtx_results: StixObject[];
let edge_results: StixObject[];
try {
vtx_results = await this.OJSQuery(query, options);
if (relationship_type === undefined) {
query = "select expand(outE()) from V where id_= :id";
} else {
query = `select expand(outE('${relationship_type}')) from V where id_= :id`;
}
edge_results = await this.OJSQuery(query, options);
return { nodes: vtx_results, edges: edge_results };
} catch (e) {
e.stack += (new Error()).stack;
throw e;
}
}
/**
* @description
* @param {Identifier} id
* @returns {Promise<GraphQueryResult>}
* @memberof StigDB
*/
public async traverseNodeIn(id: Identifier): Promise<GraphQueryResult> {
const query = {
command: "traverse in() from (select from V where id_=? ORDER BY modified DESC limit 1) while $depth < 2 ",
mode: "graph",
parameters: [id],
};
let results;
try {
results = await this.doGraphQuery(query);
return results;
} catch (e) {
e.stack += (new Error()).stack;
throw e;
}
}
public async traverseNodeOut(id: Identifier): Promise<GraphQueryResult> {
const query = {
command: "traverse out() from (select from V where id_=? ORDER BY modified DESC limit 1) while $depth < 2 ",
mode: "graph",
// parameters:(relationship_type)?[relationship_type, id]: ['', id]
parameters: [id],
};
let results;
try {
results = await this.doGraphQuery(query);
return results;
} catch (e) {
e.stack += (new Error()).stack;
throw e;
}
}
public async getParents(id: string): Promise<GraphQueryResult> {
// get the parents for a given node{
// this should include the ability to filter by SDO type or relationship type
const query: HTTPCommandQuery = {
command: "select expand(in()) from V where id_= :?",
mode: "graph",
parameters: [id],
};
try {
const vtx_results = await this.doGraphQuery(query);
query.command = "select expand(inE()) from V where id_=:id";
const edge_results = await this.doGraphQuery(query);
return { graph: { vertices: vtx_results.graph.vertices, edges: edge_results.graph.edges } };
} catch (e) {
e.stack += (new Error()).stack;
throw e;
}
}
public async isEqualToDB(changedNodeData: StixObject): Promise<boolean> {
// see if the item in the UI is really different from the one in the DB
// Being explicit about this to avoid having different versions of a node
// that onyl differ by timestamp
let db_instance;
try {
db_instance = await this.getSDO(changedNodeData.id);
if (db_instance === undefined) { return false; }
return _.isEqual(db_instance, changedNodeData);
} catch (e) {
e.stack += (new Error()).stack;
throw e;
}
}
/**
* TODO: FIX DUPLICATE IDS, check GetSDO
* @description
* @param {StixObject} stix_obj
* @returns {Promise<Rid>}
* @memberof StigDB
*/
public async createVertex(stix_obj: StixObject): Promise<StixObject[]> {
let result: StixObject[];
try {
if (stix_obj.type.startsWith('relation')) {
throw new Error("Attempt to create a relation, use createEdge instead!");
}
const existing_node = await this.getSDO(stix_obj.id);
if (existing_node !== undefined) {
return existing_node["@rid"];
}
let query: string;
let q_action: string;
let q_class: string;
q_class = "`" + stix_obj.type + "`";
q_action = 'Create VERTEX ';
query = q_action + q_class + ' CONTENT ' + JSON.stringify(transform_to_db(stix_obj));
// console.log(query);
result = await this.OJSQuery(query, {});
// console.log('Query result:');
// console.log(result);
return result;
} catch (e) {
e.stack += (new Error()).stack;
throw e;
}
}
/**
* @description
* @param {Rid} from_RID
* @param {Rid} to_RID
* @param {StixObject} data
* @returns {Promise<SRO[]>}
* @memberof StigDB
*/
public async createEdgeRID(from_RID: Rid, to_RID: Rid, data: StixObject): Promise<StixObject[]> {
let result: StixObject[];
try {
const query = "CREATE EDGE `" + data.type + "` FROM :from_rid to :to_rid CONTENT :content";
const parameters = {
params: {
from_rid: from_RID,
to_rid: to_RID,
content: data,
},
};
result = await this.OJSQuery(query, parameters);
return result;
} catch (e) {
e.stack += (new Error()).stack;
throw e;
}
}
/**
* @description
* @param {Identifier} from_node
* @param {Identifier} to_node
* @param {StixObject} data
* @returns {Promise<SRO[]>}
* @memberof StigDB
*/
public async createEdge(from_node: Identifier, to_node: Identifier, data: StixObject): Promise<StixObject[]> {
let result;
let to_RID: Rid;
let from_RID: Rid;
try {
if (from_node.includes('--')) {
from_RID = await this.getRID(from_node);
to_RID = await this.getRID(to_node);
} else {
from_RID = from_node;
to_RID = to_node;
}
if (from_RID === undefined) {
console.debug(`createEdge saving ${from_node} to database`);
const node_data = window.cycore.getElementById(from_node);
from_RID = await this.createVertex(node_data.data('raw_data'))[0].RID;
}
if (to_RID === undefined) {
console.debug(`createEdge saving ${to_node} to database`);
const node_data = window.cycore.getElementById(to_node);
to_RID = await this.createVertex(node_data.data('raw_data'))[0].RID;
}
result = this.createEdgeRID(from_RID, to_RID, data);
return result;
} catch (e) {
e.stack += (new Error()).stack;
throw e;
}
}
/**
* @description
* @param {Identifier} id
* @param {cytoscape.Core} cy
* @returns {Promise<boolean>}
* @memberof StigDB
*/
public async needs_save(id: Identifier, cy: cytoscape.Core): Promise<boolean> {
let ret: StixObject;
let retval = true;
try {
const graph_node = cy.getElementById(id);
// if (graph_node.length == 0){return true;}
const db = this;
const exists = await db.exists(id);
if (!exists) {
graph_node.data('saved', false);
return true;
}
let db_copy;
const node_data = graph_node.data().raw_data as StixObject;
switch (node_data.type) {
case 'relationship':
case 'sighting':
ret = await db.getEdge(node_data.id);
break;
default:
ret = await db.getSDO(node_data.id);
break;
}
const diffpatcher = new diffpatch.DiffPatcher({
arrays: {
detectMove: true,
includeValueOnMove: false,
},
propertyFilter: (name: string) => {
if (name.startsWith('@', 0)) {
return false;
}
return true;
},
});
if (ret === undefined) {
graph_node.data('saved', false);
const dif = diffpatcher.diff(node_data, { id: ' ' });
if (dif !== undefined) {
// tslint:disable-next-line:no-string-literal
this.diff_dialog.addDiff(node_data.id, dif, {} as StixObject, node_data['name'] || '');
}
return true;
}
db_copy = ret as StixObject;
// const class_props: orientjs.Property[] = await db.listPropertiesForClass(node_data.type.replace(/-/g, ''));
const class_props: orientjs.Property[] = await db.listPropertiesForClass(node_data.type);
const db_tmp = {};
for (const p in class_props) {
if (class_props[p]) {
const n = class_props[p].name;
const db_type = class_props[p].type;
// const cp_n = db_copy[n];
// console.log(n)
if (db_copy[n] === undefined) {
if (node_data[n] !== undefined) {
retval = false;
continue;
}
}
if (n.endsWith('_')) {
db_tmp[n.replace(/_$/, '')] = db_copy[n];
} else if (+db_type === 6 && db_copy[n] !== undefined) {
db_tmp[n] = db_copy[n].toISOString();
} else if (db_copy[n] !== undefined) {
if (!n.startsWith('@', 0)) {
db_tmp[n] = db_copy[n];
}
}
}
}
// if (db_tmp.hasOwnProperty('revoked') && !node_data.hasOwnProperty('revoked')) {
// node_data['revoked'] = db_tmp['revoked'];
// }
// if (retval && _.isEqual(node_data, db_tmp)) {
const diff = diffpatcher.diff(node_data, db_tmp);
if (retval && diff === undefined) {
graph_node.data('saved', true);
retval = false;
} else {
graph_node.data('saved', false);
retval = true;
if (node_data !== undefined && db_tmp !== undefined) {
if (diff !== undefined) {
// tslint:disable-next-line:no-string-literal
this.diff_dialog.addDiff(node_data.id, diff, db_tmp as StixObject, node_data['name'] || '');
}
}
}
return retval;
} catch (e) {
e.stack += (new Error()).stack;
throw e;
}
}
/**
* @description Updates the database from the editor form
* @param {StixObject} formdata
* @returns Promise<string>
* @memberof StigDB
*/
public async updateDB(formdata: StixObject): Promise<StixObject[]> {
const db_obj = transform_to_db(formdata);
const old_modified = await this.getModified(formdata.id);
if (old_modified === undefined) {
// New node, make sure dates are good
if (!moment(db_obj.created).isValid()) {
db_obj.created = moment().utc().format('YYYY-MM-DDTHH:mm:ss.SSS[Z]');
}
if (!moment(db_obj.modified).isValid()) {
db_obj.modified = moment().utc().format('YYYY-MM-DDTHH:mm:ss.SSS[Z]');
}
} else if (old_modified !== undefined && moment(old_modified).isSame(db_obj.modified)) {
// Existing node, must create a new modified date and create a new object in the datyabase
db_obj.modified = moment().utc().format('YYYY-MM-DDTHH:mm:ss.SSS[Z]');
}
let result;
try {
if (db_obj.type.startsWith('relation') || db_obj.type.startsWith('sighting')) {
// tslint:disable-next-line:no-string-literal
result = await this.createEdge(db_obj['source_ref'], db_obj['target_ref'], db_obj);
} else {
result = await this.createVertex(db_obj);
}
return result;
} catch (e) {
e.stack += (new Error()).stack;
throw e;
}
}
/**
* @description Updates modified timestamp for edge
* @param {SRO} edge
* @param {string} old_modified
* @returns
* @memberof StigDB
*/
public async updateEdge(edge: SRO): Promise<string> {
// let command: CommandQuery = {
// command: "UPDATE EDGE `" + `${edge['relationship_type']}` + "` CONTENT ? WHERE id_ = ?",
// mode: "graph",
// parameters: [JSON.stringify(transform_to_db(edge)), edge.id]
// }
// let result = await this.doQuery(command);
let result;
try {
// tslint:disable-next-line:no-string-literal
result = await this.ojs.update(`${edge['relationship_type']}`).set(transform_to_db(edge)).where({ id_: `${edge.id}` }).exec<string>();
return result;
} catch (e) {
e.stack += (new Error()).stack;
throw e;
}
}
/**
* @description Updates modified timestamp for vertex
* @param {SDO} vertex
* @param {string} old_modified
* @returns
* @memberof StigDB
*/
public async updateVertex(vertex: SDO, old_modified: string): Promise<string> {
let result;
try {
result = await this.ojs.update(`\`${vertex.type}\``).set(transform_to_db(vertex)).where({ id_: `${vertex.id}`, modified: `${old_modified}` }).exec<string>();
return result;
} catch (e) {
e.stack += (new Error()).stack;
throw e;
}
}
/**
* @description
* @param {("VERTEX" | "EDGE")} type
* @param {Id} identifier
* @returns {Promise<StixObject[]>}
* @memberof StigDB
*/
public async revokeID(type: "VERTEX" | "EDGE", identifier: Id): Promise<StixObject[]> {
let query: string;
type === "EDGE" ? query = "UPDATE EDGE E SET revoked = 'True' where id_=? " : query = "UPDATE V SET revoked = 'True' where id_=?";
let result: StixObject[];
try {
result = await this.OJSQuery(query, { params: { id: identifier } });
return result;
} catch (e) {
e.stack += (new Error()).stack;
throw e;
}
}
/**
* @description
* @param {GraphQueryResult} records
* @returns {Promise<BundleType>}
* @memberof StigDB
*/
public async handleResponse(records: GraphQueryResult): Promise<BundleType> {
// response handler
let resp: StixObject[] = [];
resp = resp.concat(records.graph.vertices, records.graph.edges);
// resp = resp.concat(records.graph.edges);
const bundle: BundleType = {
type: "bundle",
objects: [],
};
try {
for (const record of resp) {
const sdo = {} as StixObject;
for (const prop of Object.keys(record)) {
if (prop === undefined || prop === null) {
continue;
}
if (record.type.toLowerCase() === "relationship" && (prop === 'in' || prop === 'out')) {
continue;
}
if (!prop.startsWith('@')) {
if (prop.endsWith('_')) {
sdo[prop.replace(/_$/, '')] = record[prop];
} else {
sdo[prop] = record[prop];
}
}
}
bundle.objects.push(sdo);
}
return bundle;
} catch (e) {
e.stack += (new Error()).stack;
throw e;
}
}
}
/**
*
*
* @export
* @param {string} timestamp
* @returns {string}
*/
export function toDBTime(timestamp: string): string {
return moment.parseZone(timestamp).utc().format('YYYY-MM-DD HH:mm:ss.SSS');
}
/**
*
*
* @export
* @param {string} timestamp
* @returns {string}
*/
export function toStixTime(timestamp: string): string {
return moment.parseZone(timestamp).utc().format('YYYY-MM-DDTHH:mm:ss.SSS[Z]');
}
/**
*
*
* @export
* @param {StixObject} stix_record
* @returns {StixObject}
*/
export function transform_to_db(stix_record: StixObject): StixObject {
const ret = {} as StixObject;
Object.keys(stix_record).forEach((prop) => {
switch (prop) {
case "id":
// tslint:disable-next-line:no-string-literal
ret['id_'] = stix_record.id;
break;
default:
ret[prop] = stix_record[prop];
}
});
return ret;
}
/**
*
*
* @param {StixObject[]} stix_records
* @returns {StixObject[]}
*/
export function transform_records_to_db(stix_records: StixObject[]): StixObject[] {
const ret = [] as StixObject[];
stix_records.forEach((r) => {
const revised = transform_to_db(r);
ret.push(revised);
});
return ret;
} | the_stack |
import EventEmitter from 'eventemitter3';
import sleep from 'sleep-promise';
import Terminal from 'terminal.js';
import {Line} from '../../common/Line';
import Config from '../../config';
import Socket from '../../socket';
import {
decode,
encode,
keymap as key,
} from '../../utils';
import {
getWidth,
indexOfWidth,
substrWidth,
} from '../../utils/char';
import defaultConfig from './config';
import {Article, Board} from './model';
class Bot extends EventEmitter {
static initialState = {
connect: false,
login: false,
};
static forwardEvents = [
'message',
'error',
];
private config: Config;
private term: Terminal;
private _state: any;
private currentCharset: string;
private socket: Socket;
private preventIdleHandler: ReturnType<typeof setTimeout>;
get line(): Line[] {
const lines = [];
for(let i = 0; i < this.term.state.rows; i++) {
const { str, attr } = this.term.state.getLine(i);
lines.push({ str, attr: Object.assign({}, attr) });
}
return lines;
}
get screen(): string {
return this.line.map(line => line.str).join('\n');
}
constructor(config?: Config) {
super();
this.config = {...defaultConfig, ...config};
this.init();
}
async init(): Promise<void> {
const { config } = this;
this.term = new Terminal(config.terminal);
this._state = { ...Bot.initialState };
this.term.state.setMode('stringWidth', 'dbcs');
this.currentCharset = 'big5';
switch (config.protocol.toLowerCase()) {
case 'websocket':
case 'ws':
case 'wss':
break;
case 'telnet':
case 'ssh':
default:
throw new Error(`Invalid protocol: ${config.protocol}`);
break;
}
const socket = new Socket(config);
socket.connect();
Bot.forwardEvents.forEach(e => {
socket.on(e, this.emit.bind(this, e));
});
socket
.on('connect', (...args) => {
this._state.connect = true;
this.emit('connect', ...args);
this.emit('stateChange', this.state);
})
.on('disconnect', (closeEvent, ...args) => {
this._state.connect = false;
this.emit('disconnect', closeEvent, ...args);
this.emit('stateChange', this.state);
})
.on('message', (data) => {
if (this.currentCharset !== this.config.charset && !this.state.login &&
decode(data, 'utf8').includes('登入中,請稍候...')) {
this.currentCharset = this.config.charset;
}
const msg = decode(data, this.currentCharset);
this.term.write(msg);
this.emit('redraw', this.term.toString());
})
.on('error', (err) => {
});
this.socket = socket;
}
get state(): any {
return {...this._state};
}
getLine = (n) => {
return this.term.state.getLine(n);
}
async getContent(): Promise<Line[]> {
const lines = [];
lines.push(this.line[0]);
let sentPgDown = false;
while (!this.line[23].str.includes('100%')
&& !this.line[23].str.includes('此文章無內容')) {
for (let i = 1; i < 23; i++) {
lines.push(this.line[i]);
}
await this.send(key.PgDown);
sentPgDown = true;
}
const lastLine = lines[lines.length - 1];
for (let i = 0; i < 23; i++) {
if (this.line[i].str === lastLine.str) {
for (let j = i + 1; j < 23; j++) {
lines.push(this.line[j]);
}
break;
}
}
while (lines.length > 0 && lines[lines.length - 1].str === '') {
lines.pop();
}
if (sentPgDown) {
await this.send(key.Home);
}
return lines;
}
/**
* @deprecated
*/
async getLines() {
const lines = await this.getContent();
return lines.map(line => line.str);
}
send(msg: string): Promise<boolean> {
if (this.config.preventIdleTimeout) {
this.preventIdle(this.config.preventIdleTimeout);
}
return new Promise((resolve, reject) => {
let autoResolveHandler;
const cb = message => {
clearTimeout(autoResolveHandler);
resolve(true);
};
if (this.state.connect) {
if (msg.length > 0) {
this.socket.send(encode(msg, this.currentCharset));
this.once('message', cb);
autoResolveHandler = setTimeout(() => {
this.removeListener('message', cb);
resolve(false);
}, this.config.timeout * 10);
} else {
console.info(`Sending message with 0-length. Skipped.`);
resolve(true);
}
} else {
reject();
}
});
}
preventIdle(timeout: number): void {
clearTimeout(this.preventIdleHandler);
if (this.state.login) {
this.preventIdleHandler = setTimeout(async () => {
await this.send(key.CtrlU);
await this.send(key.ArrowLeft);
}, timeout * 1000);
}
}
async login(username: string, password: string, kick: boolean= true): Promise<any> {
if (this.state.login) { return; }
username = username.replace(/,/g, '');
if (this.config.charset === 'utf8') {
username += ',';
}
await this.send(`${username}${key.Enter}${password}${key.Enter}`);
let ret = await this.checkLogin(kick);
if (ret) {
const { _state: state } = this;
state.login = true;
state.position = {
boardname: '',
};
this.emit('stateChange', this.state);
}
return ret;
}
async logout(): Promise<boolean> {
if (!this.state.login) { return; }
await this.send(`G${key.Enter}Y${key.Enter}`);
this._state.login = false;
this.emit('stateChange', this.state);
this.send(key.Enter);
return true;
}
private async checkLogin(kick: boolean): Promise<boolean> {
if (this.line[21].str.includes('密碼不對或無此帳號')) {
this.emit('login.failed');
return false;
} else if (this.line[23].str.includes('請稍後再試')) {
this.emit('login.failed');
return false;
} else {
let state = 0;
while (true) {
await sleep(400);
const lines = this.line;
if (lines[22].str.includes('登入中,請稍候...')) {
/* no-op */
} else if (lines[22].str.includes('您想刪除其他重複登入的連線嗎')) {
if (state === 1) continue;
await this.send(`${kick ? 'y' : 'n'}${key.Enter}`);
state = 1;
continue;
} else if (lines[23].str.includes('請勿頻繁登入以免造成系統過度負荷')) {
if (state === 2) continue;
await this.send(`${key.Enter}`);
state = 2;
} else if (lines[23].str.includes('您要刪除以上錯誤嘗試的記錄嗎')) {
if (state === 3) continue;
await this.send(`y${key.Enter}`);
state = 3;
} else if (lines[23].str.includes('按任意鍵繼續')) {
await this.send(`${key.Enter}`);
} else if ((lines[22].str + lines[23].str).toLowerCase().includes('y/n')) {
console.info(`Unknown login state: \n${this.screen}`);
await this.send(`y${key.Enter}`);
} else if (lines[23].str.includes('我是')) {
break;
} else {
console.info(`Unknown login state: \n${this.screen}`);
}
}
this.emit('login.success');
return true;
}
}
/**
* @deprecated
*/
private checkArticleWithHeader(): boolean {
const authorArea = substrWidth('dbcs', this.line[0].str, 0, 6).trim();
return authorArea === '作者';
}
select(model) {
return model.select(this);
}
/**
* @deprecated
*/
async getMails(offset: number= 0) {
await this.enterMail();
if (offset > 0) {
offset = Math.max(offset - 9, 1);
await this.send(`${key.End}${key.End}${offset}${key.Enter}`);
}
const { getLine } = this;
const mails = [];
for (let i = 3; i <= 22; i++) {
const line = getLine(i).str;
const mail = {
sn: +substrWidth('dbcs', line, 1, 5).trim(),
date: substrWidth('dbcs', line, 9, 5).trim(),
author: substrWidth('dbcs', line, 15, 12).trim(),
status: substrWidth('dbcs', line, 30, 2).trim(),
title: substrWidth('dbcs', line, 33 ).trim(),
};
mails.push(mail);
}
await this.enterIndex();
return mails.reverse();
}
/**
* @deprecated
*/
async getMail(sn: number) {
await this.enterMail();
const { getLine } = this;
await this.send(`${sn}${key.Enter}${key.Enter}`);
const hasHeader = this.checkArticleWithHeader();
const mail = {
sn,
author: '',
title: '',
timestamp: '',
lines: [],
};
if (this.checkArticleWithHeader()) {
mail.author = substrWidth('dbcs', getLine(0).str, 7, 50).trim();
mail.title = substrWidth('dbcs', getLine(1).str, 7 ).trim();
mail.timestamp = substrWidth('dbcs', getLine(2).str, 7 ).trim();
}
mail.lines = await this.getLines();
await this.enterIndex();
return mail;
}
async enterIndex(): Promise<boolean> {
await this.send(`${key.ArrowLeft.repeat(10)}`);
return true;
}
get currentBoardname(): string|undefined {
const boardRe = /【(?!看板列表).*】.*《(?<boardname>.*)》/;
const match = boardRe.exec(this.line[0].str);
if (match) {
return match.groups.boardname;
} else {
return void 0;
}
}
async enterBoardByName(boardname: string): Promise<boolean> {
await this.send(`s${boardname}${key.Enter} ${key.Home}${key.End}`);
if (this.currentBoardname.toLowerCase() === boardname.toLowerCase()) {
this._state.position.boardname = this.currentBoardname;
this.emit('stateChange', this.state);
return true;
} else {
await this.enterIndex();
return false;
}
}
async enterByOffset(offsets: number[]= []): Promise<boolean> {
let result = true;
offsets.forEach(async offset => {
if (offset === 0) {
result = false;
}
if (offset < 0) {
for (let i = 22; i >= 3; i--) {
let lastOffset = substrWidth('dbcs', this.line[i].str, 3, 4).trim();
if (lastOffset.length > 0) {
offset += +lastOffset + 1;
break;
}
lastOffset = substrWidth('dbcs', this.line[i].str, 15, 2).trim();
if (lastOffset.length > 0) {
offset += +lastOffset + 1;
break;
}
}
}
if (offset < 0) {
result = false;
}
if (!result) {
return;
}
await this.send(`${offset}${key.Enter.repeat(2)} ${key.Home}${key.End}`);
});
if (result) {
this._state.position.boardname = this.currentBoardname;
this.emit('stateChange', this.state);
await this.send(key.Home);
return true;
} else {
await this.enterIndex();
return false;
}
}
async enterBoardByOffset(offsets: number[]= []): Promise<boolean> {
await this.send(`C${key.Enter}`);
return await this.enterByOffset(offsets);
}
async enterFavorite(offsets: number[]= []): Promise<boolean> {
await this.send(`F${key.Enter}`);
return await this.enterByOffset(offsets);
}
async enterMail(): Promise<boolean> {
await this.send(`M${key.Enter}R${key.Enter}${key.Home}${key.End}`);
return true;
}
}
export default Bot; | the_stack |
import { expect } from "chai";
import { SharedPropertyTree, IPropertyTreeMessage, IRemotePropertyTreeMessage, OpKind } from "../propertyTree";
describe("PropertyTree", () => {
describe("Pruning History", () => {
it("Prune does nothing if sequence number is too low to prune", () => {
/**
* REMOTE CHANGES: (A,0) - (B,1)
* UNREBASED CHANGES: \-(C,2)
* minimum sequence number: 0
*/
const msn = 0;
const remoteChanges: IPropertyTreeMessage[] = [
{
op: OpKind.ChangeSet,
metadata: {},
changeSet: {},
guid: "A",
referenceGuid: "",
remoteHeadGuid: "",
localBranchStart: undefined,
},
{
op: OpKind.ChangeSet,
metadata: {},
changeSet: {},
guid: "B",
referenceGuid: "A",
remoteHeadGuid: "A",
localBranchStart: undefined,
},
];
const unrebasedRemoteChanges: Record<string, IRemotePropertyTreeMessage> = {};
unrebasedRemoteChanges.C = {
op: OpKind.ChangeSet,
metadata: {},
changeSet: {},
guid: "C",
referenceGuid: "A",
remoteHeadGuid: "A",
localBranchStart: undefined,
sequenceNumber: 2,
};
const prundedData = SharedPropertyTree.prune(msn, remoteChanges, unrebasedRemoteChanges);
expect(remoteChanges).to.deep.equal(prundedData.remoteChanges);
expect(unrebasedRemoteChanges).to.deep.equal(prundedData.unrebasedRemoteChanges);
});
it("Prune does nothing if sequence number is equivalent to the sole unrebased commit", () => {
/**
* REMOTE CHANGES: (A,0) - (B,1)
* UNREBASED CHANGES: \-(C,2)
* minimum sequence number: 2
*/
const msn = 2;
const remoteChanges: IPropertyTreeMessage[] = [
{
op: OpKind.ChangeSet,
metadata: {},
changeSet: {},
guid: "A",
referenceGuid: "",
remoteHeadGuid: "",
localBranchStart: undefined,
},
{
op: OpKind.ChangeSet,
metadata: {},
changeSet: {},
guid: "B",
referenceGuid: "A",
remoteHeadGuid: "A",
localBranchStart: undefined,
},
];
const unrebasedRemoteChanges: Record<string, IRemotePropertyTreeMessage> = {};
unrebasedRemoteChanges.C = {
op: OpKind.ChangeSet,
metadata: {},
changeSet: {},
guid: "C",
referenceGuid: "A",
remoteHeadGuid: "A",
localBranchStart: undefined,
sequenceNumber: 2,
};
const prundedData = SharedPropertyTree.prune(msn, remoteChanges, unrebasedRemoteChanges);
expect(prundedData.prunedCount).to.equal(0);
expect(remoteChanges).to.deep.equal(prundedData.remoteChanges);
expect(unrebasedRemoteChanges).to.deep.equal(prundedData.unrebasedRemoteChanges);
});
it("Prune does nothing if all unrebased changes with leq sqn than msn are ref'ing all remote changes", () => {
/**
* REMOTE CHANGES: (A,0) - (B,1)
* UNREBASED CHANGES: | \-(C,2)
* UNREBASED CHANGES: \-(D,3)
* minimum sequence number: 2
*/
const msn = 2;
const remoteChanges: IPropertyTreeMessage[] = [
{
op: OpKind.ChangeSet,
metadata: {},
changeSet: {},
guid: "A",
referenceGuid: "",
remoteHeadGuid: "",
localBranchStart: undefined,
},
{
op: OpKind.ChangeSet,
metadata: {},
changeSet: {},
guid: "B",
referenceGuid: "A",
remoteHeadGuid: "A",
localBranchStart: undefined,
},
];
const unrebasedRemoteChanges: Record<string, IRemotePropertyTreeMessage> = {};
unrebasedRemoteChanges.C = {
op: OpKind.ChangeSet,
metadata: {},
changeSet: {},
guid: "C",
referenceGuid: "B",
remoteHeadGuid: "B",
localBranchStart: undefined,
sequenceNumber: 2,
};
unrebasedRemoteChanges.D = {
op: OpKind.ChangeSet,
metadata: {},
changeSet: {},
guid: "D",
referenceGuid: "A",
remoteHeadGuid: "A",
localBranchStart: undefined,
sequenceNumber: 3,
};
const prundedData = SharedPropertyTree.prune(msn, remoteChanges, unrebasedRemoteChanges);
expect(prundedData.prunedCount).to.equal(0);
expect(remoteChanges).to.deep.equal(prundedData.remoteChanges);
expect(unrebasedRemoteChanges).to.deep.equal(prundedData.unrebasedRemoteChanges);
});
it("Prune deletes the initial commit since its not referenced by unrebased change", () => {
/**
* REMOTE CHANGES: (A,0) - (B,1)
* UNREBASED CHANGES: \-(C,2)
*/
const msn = 2;
const remoteChanges: IPropertyTreeMessage[] = [
{
op: OpKind.ChangeSet,
metadata: {},
changeSet: {},
guid: "A",
referenceGuid: "",
remoteHeadGuid: "",
localBranchStart: undefined,
},
{
op: OpKind.ChangeSet,
metadata: {},
changeSet: {},
guid: "B",
referenceGuid: "A",
remoteHeadGuid: "A",
localBranchStart: undefined,
},
];
const unrebasedRemoteChanges: Record<string, IRemotePropertyTreeMessage> = {};
unrebasedRemoteChanges.C = {
op: OpKind.ChangeSet,
metadata: {},
changeSet: {},
guid: "C",
referenceGuid: "B",
remoteHeadGuid: "B",
localBranchStart: undefined,
sequenceNumber: 2,
};
const prundedData = SharedPropertyTree.prune(msn, remoteChanges, unrebasedRemoteChanges);
expect(prundedData.prunedCount).to.equal(1);
expect(prundedData.remoteChanges.length).to.be.equal(1);
expect(remoteChanges[1]).to.equal(prundedData.remoteChanges[0]);
expect(unrebasedRemoteChanges).to.deep.equal(prundedData.unrebasedRemoteChanges);
});
it("Prune deletes the initial commit since its not indirectly referenced by unrebased change", () => {
/**
* REMOTE CHANGES: (A,0) <- (B,1)
* UNREBASED CHANGES: \-(D,2) <-(C,3)
* minimum sequence number: 3
*/
const msn = 3;
const remoteChanges: IPropertyTreeMessage[] = [
{
op: OpKind.ChangeSet,
metadata: {},
changeSet: {},
guid: "A",
referenceGuid: "",
remoteHeadGuid: "",
localBranchStart: undefined,
},
{
op: OpKind.ChangeSet,
metadata: {},
changeSet: {},
guid: "B",
referenceGuid: "A",
remoteHeadGuid: "A",
localBranchStart: undefined,
},
];
const unrebasedRemoteChanges: Record<string, IRemotePropertyTreeMessage> = {};
unrebasedRemoteChanges.C = {
op: OpKind.ChangeSet,
metadata: {},
changeSet: {},
guid: "C",
referenceGuid: "D",
remoteHeadGuid: "B",
localBranchStart: undefined,
sequenceNumber: 3,
};
unrebasedRemoteChanges.D = {
op: OpKind.ChangeSet,
metadata: {},
changeSet: {},
guid: "D",
referenceGuid: "B",
remoteHeadGuid: "B",
localBranchStart: undefined,
sequenceNumber: 2,
};
const prundedData = SharedPropertyTree.prune(msn, remoteChanges, unrebasedRemoteChanges);
expect(prundedData.prunedCount).to.equal(1);
expect(prundedData.remoteChanges.length).to.be.equal(1);
expect(remoteChanges[1]).to.equal(prundedData.remoteChanges[0]);
expect(unrebasedRemoteChanges).to.deep.equal(prundedData.unrebasedRemoteChanges);
});
it("Prune deletes multiple changes since msn is higher than one of the unrebased changes chain sqn", () => {
/**
* REMOTE CHANGES: (A,0) <- (B,1)
* UNREBASED CHANGES: | \-(E,4)
* UNREBASED CHANGES: \-(D,2) <- (C,3)
*/
const msn = 4;
const remoteChanges: IPropertyTreeMessage[] = [
{
op: OpKind.ChangeSet,
metadata: {},
changeSet: {},
guid: "A",
referenceGuid: "",
remoteHeadGuid: "",
localBranchStart: undefined,
},
{
op: OpKind.ChangeSet,
metadata: {},
changeSet: {},
guid: "B",
referenceGuid: "A",
remoteHeadGuid: "A",
localBranchStart: undefined,
},
];
const unrebasedRemoteChanges: Record<string, IRemotePropertyTreeMessage> = {};
unrebasedRemoteChanges.C = {
op: OpKind.ChangeSet,
metadata: {},
changeSet: {},
guid: "C",
referenceGuid: "D",
remoteHeadGuid: "A",
localBranchStart: undefined,
sequenceNumber: 3,
};
unrebasedRemoteChanges.D = {
op: OpKind.ChangeSet,
metadata: {},
changeSet: {},
guid: "D",
referenceGuid: "A",
remoteHeadGuid: "A",
localBranchStart: undefined,
sequenceNumber: 2,
};
unrebasedRemoteChanges.E = {
op: OpKind.ChangeSet,
metadata: {},
changeSet: {},
guid: "E",
referenceGuid: "B",
remoteHeadGuid: "B",
localBranchStart: undefined,
sequenceNumber: 4,
};
const prundedData = SharedPropertyTree.prune(msn, remoteChanges, unrebasedRemoteChanges);
expect(prundedData.prunedCount).to.equal(3);
expect(prundedData.remoteChanges.length).to.be.equal(1);
expect(Object.keys(prundedData.unrebasedRemoteChanges).length).to.equal(1);
expect(remoteChanges[1]).to.equal(prundedData.remoteChanges[0]);
expect(unrebasedRemoteChanges.E).to.deep.equal(prundedData.unrebasedRemoteChanges.E);
});
it("Prune should not prune partially rebased commit chains", () => {
/**
* REMOTE CHANGES: (A,0) <- (B,1) <- (C,2)
* UNREBASED CHANGES: \-(B,1) <- (C,2)
*/
const msn = 2;
const remoteChanges: IPropertyTreeMessage[] = [
{
op: OpKind.ChangeSet,
metadata: {},
changeSet: {},
guid: "A",
referenceGuid: "",
remoteHeadGuid: "",
localBranchStart: undefined,
},
{
op: OpKind.ChangeSet,
metadata: {},
changeSet: {},
guid: "B",
referenceGuid: "A",
remoteHeadGuid: "A",
localBranchStart: undefined,
},
{
op: OpKind.ChangeSet,
metadata: {},
changeSet: {},
guid: "C",
referenceGuid: "B",
remoteHeadGuid: "A",
localBranchStart: undefined,
},
];
const unrebasedRemoteChanges: Record<string, IRemotePropertyTreeMessage> = {};
unrebasedRemoteChanges.B = {
op: OpKind.ChangeSet,
metadata: {},
changeSet: {},
guid: "B",
referenceGuid: "A",
remoteHeadGuid: "A",
localBranchStart: undefined,
sequenceNumber: 1,
};
unrebasedRemoteChanges.C = {
op: OpKind.ChangeSet,
metadata: {},
changeSet: {},
guid: "C",
referenceGuid: "B",
remoteHeadGuid: "A",
localBranchStart: undefined,
sequenceNumber: 2,
};
const prundedData = SharedPropertyTree.prune(msn, remoteChanges, unrebasedRemoteChanges);
expect(prundedData.prunedCount).to.equal(0);
expect(prundedData.remoteChanges.length).to.be.equal(3);
expect(Object.keys(prundedData.unrebasedRemoteChanges).length).to.equal(2);
});
it("Prune should not prune commits with an empty remote head", () => {
/**
* REMOTE CHANGES: * --(A,1)
* UNREBASED CHANGES: \--(A,1)
*/
const msn = 1;
const remoteChanges: IPropertyTreeMessage[] = [
{
op: OpKind.ChangeSet,
changeSet: {},
guid: "A",
referenceGuid: "",
remoteHeadGuid: "",
localBranchStart: undefined,
metadata: undefined,
},
];
const unrebasedRemoteChanges: Record<string, IRemotePropertyTreeMessage> = {};
unrebasedRemoteChanges.A = {
op: OpKind.ChangeSet,
changeSet: {},
guid: "A",
referenceGuid: "",
remoteHeadGuid: "",
localBranchStart: undefined,
sequenceNumber: 1,
metadata: undefined,
};
const prundedData = SharedPropertyTree.prune(msn, remoteChanges, unrebasedRemoteChanges);
expect(prundedData.prunedCount).to.equal(0);
expect(prundedData.remoteChanges.length).to.be.equal(1);
expect(Object.keys(prundedData.unrebasedRemoteChanges).length).to.equal(1);
});
});
}); | the_stack |
var $ : any;
module VORLON {
export class DOMTimelineDashboard extends DashboardPlugin {
//Do any setup you need, call super to configure
//the plugin with html and css for the dashboard
constructor() {
// name , html for dash css for dash
super("domtimeline", "control.html", "control.css");
(<any>this)._ready = true;
this._messageHandlers = {};
this._messageId = 0;
console.log('Started');
}
//Return unique id for your plugin
public getID(): string {
return "DOMTIMELINE";
}
// This code will run on the dashboard //////////////////////
// Start dashboard code
// uses _insertHtmlContentAsync to insert the control.html content
// into the dashboard
private _messageId: number;
private _messageHandlers: {[s:string]:(receivedObject:any)=>void};
private _carbonCopyHandlers: Function[] = [];
public startDashboardSide(div: HTMLDivElement = null): void {
this._insertHtmlContentAsync(div, (applicationDiv) => {
//this._outputDiv = <HTMLElement>filledDiv.querySelector('#output');
//this._toastDiv = <HTMLElement>filledDiv.querySelector('#toast');
var me = this;
var dashboard = initDashboard(
function(s) { me.sendMessageToClient(s); }
);
// Handle toolbar buttons
var clientCommands = applicationDiv.querySelectorAll("[data-client-command]");
for(var i = clientCommands.length; i--;) { var clientCommand = <HTMLElement>clientCommands[i];
clientCommand.onclick = function(event) {
me.sendMessageToClient(this.getAttribute("data-client-command"), (e)=>me.logMessage(e));
};
}
// Handle the settings pane
var settingsPane = <HTMLElement>applicationDiv.querySelector('#settings');
var settingsPaneOpenButton = <HTMLElement>applicationDiv.querySelector("#open-settings-button");
var settingsPaneCloseButton = <HTMLElement>settingsPane.querySelector("#close-settings-button");
settingsPaneOpenButton.addEventListener('click', e => {
applicationDiv.setAttribute('is-settings-pane-open','true');
settingsPane.focus();
});
settingsPaneCloseButton.addEventListener('click', e => {
applicationDiv.setAttribute('is-settings-pane-open','false');
settingsPaneOpenButton.focus();
});
settingsPane.addEventListener('keyup', e => {
if (e.keyCode == 27) {
settingsPaneCloseButton.click();
}
})
// settings>dombreakpoints
var breakpointsCheckbox = <HTMLInputElement>settingsPane.querySelector('#are-breakpoints-enabled');
var breakpointsCodeTextbox = <HTMLTextAreaElement>settingsPane.querySelector('#breakpoints-code');
var saveBreakpointsCodeForm = <HTMLFormElement>settingsPane.querySelector('#breakpoints-code-form');
saveBreakpointsCodeForm.addEventListener('submit', e => {
var code = (
breakpointsCheckbox.checked
? breakpointsCodeTextbox.value
: '/* disabled */'
)
me.sendMessageToClient(`domTimelineOptions.considerDomBreakpoint = function(m) {\n\n${code}\n\n}\n\n//# sourceURL=vorlon.max.dom-breakpoint.js`);
e.preventDefault(); return false;
});
breakpointsCheckbox.addEventListener('change', e => {
var code = (
breakpointsCheckbox.checked
? '/* not yet enabled; modify the code, then press save */'
: '/* disabled */'
)
me.sendMessageToClient(`domTimelineOptions.considerDomBreakpoint = function(m) {\n${code}\n}`);
});
// Refresh the output from time to time
var clientUrl = "about:blank";
var domData = new MappingSystem.NodeMappingSystem();
var alreadyKnownEvents : DashboardDataForEntry[] = [], lastPastEventsCount = 0;
var isIframeAlreadyCreated = false;
var updateTimer = setInterval(function() {
me.sendMessageToClient(
"domHistory.generateDashboardData("+`{history:${alreadyKnownEvents.length},lostFuture:0,domData:${domData.data.length}}`+")",
(e)=>{
// refresh metadata
clientUrl = e.message.url;
document.getElementById("dom-recorder").setAttribute('is-recording-started', e.message.isRecordingNow || e.message.isRecordingEnded);
document.getElementById("dom-recorder").setAttribute('is-recording-ended', e.message.isRecordingEnded);
// nothing significant changed, don't update
if(e.message.history.length == 0 && e.message.pastEventsCount == lastPastEventsCount && !(e.message.isRecordingEnded && !isIframeAlreadyCreated)) {
return;
}
// merge histories
if(e.message.pastEventsCount + e.message.futureEventsCount != 0) {
var newHistory = e.message.history.slice(alreadyKnownEvents.length - e.message.assumedKnownData.history);
alreadyKnownEvents = e.message.history = alreadyKnownEvents.concat(newHistory);
if(alreadyKnownEvents.length > e.message.pastEventsCount + e.message.futureEventsCount) {
debugger;
}
} else {
alreadyKnownEvents = e.message.history;
lastPastEventsCount = e.message.pastEventsCount;
}
for(var i = alreadyKnownEvents.length; i--;) {
alreadyKnownEvents[i].isCancelled = i >= e.message.pastEventsCount;
lastPastEventsCount = e.message.pastEventsCount;
}
// merge domData
if(domData.data.length > e.message.assumedKnownData.domData) {
e.message.domData.splice(0, domData.data.length - e.message.assumedKnownData.domData);
}
domData.importData(e.message.domData);
e.message.domData = domData.data;
// refresh content
dashboard.setTimeline(alreadyKnownEvents,e.message);
// create the preview iframe once the recording is done
if(e.message.isRecordingEnded && !isIframeAlreadyCreated) {
isIframeAlreadyCreated = true;
var popup = window.open("about:blank", "domtimeline-popup", "width=800,height=600,menubar=no,toolbar=no,location=no,resizable=yes,scrollbars=yes,status=no");
Helpers.implementDomHistoryInWindow({clientUrl, events:alreadyKnownEvents, domData}, popup);
popup.eval(`domHistory.seek(${lastPastEventsCount})`);
me._carbonCopyHandlers.push(message => popup.eval(message));
}
}
);
}, 500);
})
}
// When we get a message from the client, just show it
public logMessage(receivedObject: any) {
var message = document.createElement('p');
message.textContent = receivedObject.message;
console.log(message);
//this._toastDiv.appendChild(message);
}
// sends a message to the client, and enables you to provide a callback for the reply
public sendMessageToClient(message: string, callback:(receivedObject:any)=>void = undefined) {
// send the message to the real client
var messageId = this._messageId++;
if(callback) this._messageHandlers[messageId] = callback;
this.sendToClient({message,messageId});
// send carbon copies if needed
for(var x = this._carbonCopyHandlers.length; x--;) {
var ccHandler = this._carbonCopyHandlers[x];
ccHandler(message);
}
}
// execute the planned callback when we receive a message from the client
public onRealtimeMessageReceivedFromClientSide(receivedObject: any): void {
var callback = this._messageHandlers[receivedObject.messageId];
if(callback) {
this._messageHandlers[receivedObject.messageId] = undefined;
callback(receivedObject);
}
}
}
export class Helpers {
static implementDomHistoryInWindow({ clientUrl, events, domData }: DomHistoryData, popup : Window) {
var pDoc = popup.document;
var doctypeText = getDoctypeText();
pDoc.open();
pDoc.write(doctypeText+"<html></html>");
pDoc.close();
var oRE : HTMLHtmlElement = <any>pDoc.documentElement;
var oHE : HTMLHeadElement = <any>oRE.querySelector("head") || createHeadFor(oRE);
var oBE : HTMLBaseElement = <any>oHE.querySelector("base") || createBaseFor(oHE);
oBE.setAttribute('href', clientUrl);
oBE.href = clientUrl;
var popupDomData = new MappingSystem.NodeMappingSystem(popup.document);
popupDomData.importData(domData.data);
var nRE : HTMLHtmlElement = <any>getNewRootElement();
var nHE : HTMLHeadElement = <any>nRE.querySelector("head") || createHeadFor(nRE);
var nBE : HTMLBaseElement = <any>nHE.querySelector("base") || createBaseFor(nHE);
nBE.setAttribute('href', clientUrl);
nBE.href = clientUrl;
disableScripts(nRE);
popup.document.adoptNode(nRE);
popup.document.replaceChild(nRE,oRE);
enableScripts(nRE);
preparePopupWithShim();
function getDoctypeText() {
var docStart = <HTMLElement>domData.p2oMap.get("0:0");
return ("tagName" in docStart && docStart.tagName.toLowerCase() != 'parsererror') ? '' : domData.data[0].outerHTML;
}
function getNewRootElement() {
var docStart = <HTMLElement>popupDomData.p2oMap.get("0:0");
if(!("tagName" in docStart && docStart.tagName.toLowerCase() != 'parsererror')) {
docStart = <HTMLElement>popupDomData.p2oMap.get("1:0");
}
return docStart;
}
function createHeadFor(htmlElement) {
// normal position of the head,
// but we are screwed by now I think because doc will likely insert another one soon
var headElement = htmlElement.ownerDocument.createElement('head');
htmlElement.insertBefore(headElement, htmlElement.firstChild);
return headElement;
}
function createBaseFor(headElement) {
// position least likely to hurt anything,
// we should be okay
var baseElement = headElement.ownerDocument.createElement('base');
headElement.insertBefore(baseElement, headElement.lastChild);
return baseElement;
}
function disableScripts(root) {
var scripts = root.querySelectorAll('script');
for(var s = scripts.length; s--;) {
var script = scripts[s];
script.type = "!" + script.type;
}
}
function enableScripts(root) {
var scripts = root.querySelectorAll('script[type^="!"]');
for(var s = scripts.length; s--;) {
var script = scripts[s];
script.type = "!" + script.type;
}
}
function preparePopupWithShim() {
var currentPastEventsCount = 0;
popup['domHistory'] = {
generateDashboardData(knownData) {
return {
assumedKnownData: knownData,
url: clientUrl,
isRecordingNow: false,
isRecordingEnded: true,
history: events.slice(knownData.history|0),
pastEventsCount: currentPastEventsCount,
futureEventsCount: events.length - currentPastEventsCount,
domData: popupDomData.data.slice(knownData.domData),
};
},
startRecording() {
return false;
},
stopRecording() {
return false;
},
undo() {
if(currentPastEventsCount > 0) {
undoMutationRecord(convertToMutationRecord(events[--currentPastEventsCount].rawData));
return;
} else {
return false;
}
},
redo() {
if(currentPastEventsCount < events.length) {
redoMutationRecord(convertToMutationRecord(events[currentPastEventsCount++].rawData));
return true;
} else {
return false;
}
},
seek(newPastEventsCount: number) {
if(currentPastEventsCount != newPastEventsCount) {
// we should sync our view with the real view now
if(currentPastEventsCount < newPastEventsCount) {
// we need to redo some changes
for(var i = currentPastEventsCount; i != newPastEventsCount; i++) {
redoMutationRecord(convertToMutationRecord(events[i].rawData));
}
} else {
// we need to undo some changes
for(var i = currentPastEventsCount; i != newPastEventsCount; i--) {
undoMutationRecord(convertToMutationRecord(events[i-1].rawData));
}
}
// save the fact we synced
currentPastEventsCount = newPastEventsCount;
}
}
};
function convertToMutationRecord(d) {
var e : any = {};
for(var key in d) { e[key] = d[key]; }
if(e.target) e.target = popupDomData.getObjectFor(e.target);
if(e.nextSibling) e.nextSibling = popupDomData.getObjectFor(e.nextSibling);
if(e.addedNodes) e.addedNodes = popupDomData.getObjectListFor(e.addedNodes);
if(e.removedNodes) e.removedNodes = popupDomData.getObjectListFor(e.removedNodes);
return e;
}
//
// execute the action which cancels a mutation record
//
function undoMutationRecord(change) {
switch(change.type) {
//
case "attributes":
change.target.setAttribute(change.attributeName, change.oldValue);
if(change.attributeName=='value') change.target.value = change.oldValue||'';
return;
//
case "characterData":
change.target.nodeValue = change.oldValue;
return;
//
case "childList":
if(change.addedNodes) {
for(var i = change.addedNodes.length; i--;) {
change.addedNodes[i].remove();
}
}
if(change.removedNodes) {
var lastNode = change.nextSibling;
for(var i = change.removedNodes.length; i--;) {
if(change.removedNodes[i].ownerDocument != change.target.ownerDocument) {
change.target.ownerDocument.adoptNode(change.removedNodes[i]);
}
change.target.insertBefore(change.removedNodes[i], lastNode);
lastNode = change.removedNodes[i];
}
}
return;
}
}
//
// execute the action which replicates a mutation record
//
function redoMutationRecord(change) {
switch(change.type) {
//
case "attributes":
change.target.setAttribute(change.attributeName, change.newValue);
if(change.attributeName=='value') change.target.value = change.newValue||'';
return;
//
case "characterData":
change.target.nodeValue = change.newValue;
return;
//
case "childList":
if(change.addedNodes) {
var lastNode = change.nextSibling;
for(var i = change.addedNodes.length; i--;) {
if(change.addedNodes[i].ownerDocument != change.target.ownerDocument) {
change.target.ownerDocument.adoptNode(change.addedNodes[i]);
}
change.target.insertBefore(change.addedNodes[i], lastNode);
lastNode = change.addedNodes[i];
}
}
if(change.removedNodes) {
for(var i = change.removedNodes.length; i--;) {
change.removedNodes[i].remove();
}
}
return;
}
}
}
}
}
//Register the plugin with vorlon core
Core.RegisterDashboardPlugin(new DOMTimelineDashboard());
}
function initDashboard(executeScriptOnClient: (string)=>void) {
var SCALE = 0.5;
var START_TIME = 0;
var FRAMES_PER_SECOND = 5;
var TIMELINE_SECONDS = 90;
var appDiv = document.querySelector('.plugin-domtimeline #dom-recorder');
var timelineBaseHTML = appDiv.querySelector('#timeline-content').innerHTML;
var latestMessage : any = null;
var alreadyKnownEvents : DashboardDataForEntry[] = [];
var setNumberChanges = function (timeline : DashboardDataForEntry[]) {
document.querySelector('.inline-changes-added span').innerHTML = '' + countByType('added', timeline);
document.querySelector('.inline-changes-removed span').innerHTML = '' + countByType('removed', timeline);
document.querySelector('.inline-changes-modified span').innerHTML = '' + countByType('modified', timeline);
}
var setChanges = function (changes : DashboardDataForEntry[]) {
var html = '';
var scroller = <HTMLElement>document.querySelector(".plugin-domtimeline");
var scrollTop = scroller.scrollTop;
if(scrollTop >= scroller.scrollHeight - scroller.offsetHeight - 1) { scrollTop = 9e10; }
var times = {};
var max = { time: 0, count: 0 };
for (var i = 0, len = changes.length; i < len; i++) {
var change = changes[i], changeTime = Math.floor(change.timestamp/1000 * FRAMES_PER_SECOND) / FRAMES_PER_SECOND;
var details_table = '';
for (var key in change.details) {
var value = ''+change.details[key]; var value_lines = value.split('\n');
var value_line = ((value_lines.length < 3) ? value : fixCode(value_lines[0] + ' [...]'));
details_table += '<tr><td class="td-name">' + key + ':</td><td class="td-value" title="'+escapeHtml(value)+'">' + escapeHtml2(value_line) + '</td></tr>';
}
var details = '<li class="acc" style="display:none;"><table>' + details_table + '</table></li>';
html += '<li data-id=" ' + i + ' " data-time=" ' + changeTime + ' " data-are-details-visible="' + change.areDetailsVisible + '" is-cancelled="'+change.isCancelled+'" is-outside-selection="'+(selectionBehavior.isEnabled ? change.timestamp < selectionBehavior.selectionStartTimestamp || change.timestamp > selectionBehavior.selectionEndTimestamp : false)+'" class="show-change acc-tr accordion-changes-' + change.type + '">' + escapeHtml(change.description) + ' <span>' + changeTime + 's</span><i class="fa fa-undo"></i></li>' + details;
if (typeof times[changeTime] === 'undefined') {
times[changeTime] = { added: 0, removed: 0, modified: 0, count: 0 };
}
times[changeTime].count++;
times[changeTime][change.type]++;
if (max.count < times[changeTime].count) {
max.count = times[changeTime].count;
max.time = changeTime;
}
}
document.querySelector('.accordion-changes').innerHTML = html;
html = "";
for (var timeIndex in times) {
var time = times[timeIndex];
var minHeight = (time.added?3:0) + (time.added?3:0) + (time.added?3:0);
var totalHeight = SCALE * 85 * Math.log(1 + time.count / 10) / Math.log(1 + max.count / 10);
totalHeight = Math.max(totalHeight, minHeight);
var distributableHeight = totalHeight - minHeight;
var addedHeight = (time.added?3:0) + distributableHeight * time.added / time.count;
var removedHeight = (time.removed?3:0) + distributableHeight * time.removed / time.count;
var modifiedHeight = (time.modified?3:0) + distributableHeight * time.modified / time.count;
var times_h = '';
times_h += '<span data-hint="' + time.added + ' added" class="added_h hint--right hint--success" style="' + (((time.modified || time.removed) && time.added) ? 'border-bottom: 1px solid white;' : '') + 'height: ' + addedHeight + 'px;"></span>';
times_h += '<span data-hint="' + time.modified + ' modified" ' + ((!time.modified) ? 'style="border:none !important;"' : '') + ' class="modified_h hint--right hint--info" style="' + ((time.removed && time.modified) ? 'border-bottom: 1px solid white;' : '') + 'height: ' + modifiedHeight + 'px;"></span>';
times_h += '<span data-hint="' + time.removed + ' removed" ' + ((!time.removed) ? 'style="border:none !important;"' : '') + ' class="removed_h hint--right hint--error" style="height: ' + removedHeight + 'px;"></span>';
html += '<div class="time-' + timeIndex.replace('.', 'p') + '" style="left: ' + (SCALE * 61 * parseFloat(timeIndex)) + 'px;">' + times_h + '</div>';
}
document.getElementById('wrapper-timeline').style.fontSize = SCALE+'em';
//document.getElementById('timeline').style.backgroundSize = (SCALE*61)+'px';
document.getElementById('timeline').style.height = (SCALE*100+10)+'px';
document.getElementById('timeline-content').innerHTML = timelineBaseHTML + html;
scroller.scrollTop = scrollTop;
function fixCode(v0:string) {
if(v0[0]=='`' && v0.split('').reduce((i,c)=>(i+(c=='`'?1:0)),0)%2==1) {
return v0+'`';
} else {
return v0;
}
}
}
var setTimelineSeconds = function (s) {
var v = START_TIME;
var html = '';
for (var i = 0; i <= s; i++) {
var left = SCALE * ((i) ? ((i * 61) - (4 * i.toString().length)) : i);
html += '<span style="left: ' + left + 'px;">' + v + 's</span>';
v++;
}
document.querySelectorAll('.seconds-list')[0].innerHTML = html;
document.getElementById('timeline').style.width = SCALE * (61 * (s + 1)) + 'px';
}
var setTimeline = function (timeline : DashboardDataForEntry[], message:any) {
alreadyKnownEvents = timeline;
latestMessage = message;
setNumberChanges(timeline);
setChanges(timeline);
setTimelineSeconds(TIMELINE_SECONDS);
seekBehavior && seekBehavior.setSeekTime(undefined, false);
}
var filterChanges = function (timeline, type = undefined) {
setNumberChanges(timeline);
$('.acc-tr').each(function (i) {
var time = parseFloat($(this).data('time'));
if ($('#filter-changes').css('display') == 'none' || (time >= $('#filter-changes').find('.from').val() && time <= $('#filter-changes').find('.to').val())) {
$(this).removeClass('hide-change').addClass('show-change');
} else {
$(this).removeClass('show-change').addClass('hide-change');
}
});
$(".accordion-changes").animate({ scrollTop: $('.show-change').first().data('id') * 44 }, ((type == 'resize' || type == 'draggable') ? 0 : 500));
}
var levChanged = function (type = undefined) {
if (parseInt(document.getElementById('lev').style.width) > 0) {
$('#lev').css('border-width', '2px');
$('#filter-changes').show();
$('#filter-changes').find('.from').val(($('.lev').position().left / (SCALE*61)).toFixed(2));
$('#filter-changes').find('.to').val((($('.lev').position().left + parseInt(document.getElementById('lev').style.width)) / (SCALE*61)).toFixed(2));
} else {
$('#lev').css('border-width', '1px');
$('#filter-changes').hide();
}
filterChanges(timeline, type);
}
var escapeHtml = function (str) {
return String(str)
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'")
.replace(/\//g, "/");
}
var escapeHtml2 = function (str) {
return escapeHtml(str).replace(/`([^`]*)`/g,'<code>$1</code>');
}
var validate = window["validateInputNumber"] = function (evt) {
var theEvent = evt || window.event;
var key = theEvent.keyCode || theEvent.which;
key = String.fromCharCode(key);
var regex = /[0-9]|\./;
if (!regex.test(key)) {
theEvent.returnValue = false;
if (theEvent.preventDefault) theEvent.preventDefault();
}
}
var countByType = function (type, timeline) {
var count = 0;
for (var i = 0, len = timeline.length; i < len; i++) {
if (timeline[i].type == type) {
var isWithinSelection = (
timeline[i].timestamp >= selectionBehavior.selectionStartTimestamp
&& timeline[i].timestamp <= selectionBehavior.selectionEndTimestamp
);
if (!selectionBehavior.isEnabled || isWithinSelection) {
count++;
}
}
}
return count;
}
var timeline: DashboardDataForEntry[] = [];
setTimeline(timeline,null);
enableActionButtonsForChangeEntries();
function enableActionButtonsForChangeEntries() {
var changeList = document.querySelector('.accordion-changes');
changeList.addEventListener('mousedown', onmousedown, true);
function onmousedown(e:MouseEvent) {
e.stopPropagation(); e.preventDefault();
// disable in case of play animation
if(playBehavior.isEnabled) return;
// undo
var target = <HTMLElement>e.target;
if(target.className == 'fa fa-undo') {
executeScriptOnClient(`domHistory.seek(${target.parentElement.dataset['id']})`);
return;
}
// old code, to show/hide changes details
var li = target; while(li && li != this && li.tagName != 'LI') { li=li.parentElement };
if ($(li).hasClass('acc')) {
e.preventDefault();
return;
}
var change = alreadyKnownEvents[<any>li.dataset['id']|0];
if(change.areDetailsVisible) {
change.areDetailsVisible = false;
li.dataset['areDetailsVisible'] = 'false';
} else {
change.areDetailsVisible = true;
li.dataset['areDetailsVisible'] = 'true';
}
}
}
var playBehavior = enablePlayBehavior();
function enablePlayBehavior() {
document.querySelector(".plugin-domtimeline #playStopButton").addEventListener('click', e => {
if(!playBehavior.isEnabled || playBehavior.isPaused) {
playBehavior.playSelection();
} else {
playBehavior.stop()
}
});
function startPlayAnimation() {
var animationStartTime = performance.now();
requestAnimationFrame(continuePlayAnimation);
function continuePlayAnimation() {
// dont do anything is the animation was stopped
if(!playBehavior.isEnabled) { return; }
// save state and exit if it was paused
if(playBehavior.isPaused) {
playBehavior.animationStartTimestamp = seekBehavior.getSeekTime();
return;
}
var currentTimestamp = playBehavior.animationStartTimestamp + (performance.now() - animationStartTime) * playBehavior.speed;
if(currentTimestamp > playBehavior.animationEndTimestamp) {
currentTimestamp = playBehavior.animationEndTimestamp;
playBehavior.stop();
} else {
requestAnimationFrame(continuePlayAnimation);
}
seekBehavior.setSeekTime(currentTimestamp, true);
}
}
return {
isEnabled: false,
isPaused: false,
speed: 1,
animationStartTimestamp: 0,
animationEndTimestamp: 0,
playSelection() {
if(this.isPaused) { this.isPaused=false; return true; }
if(this.isEnabled) { return false; }
var selectionStart = selectionBehavior.isEnabled ? selectionBehavior.selectionStartTimestamp : 0;
var selectionEnd = selectionBehavior.isEnabled ? selectionBehavior.selectionEndTimestamp : alreadyKnownEvents[alreadyKnownEvents.length-1].timestamp;
playBehavior.isEnabled = true; document.querySelector(".plugin-domtimeline #dom-recorder").setAttribute('is-recording-playing', 'true');
playBehavior.animationStartTimestamp = selectionStart;
playBehavior.animationEndTimestamp = selectionEnd;
startPlayAnimation();
return true;
},
pause() {
if(this.isEnabled) { return this.isPaused = true; }
return false;
},
stop() {
if(this.isEnabled) {
this.isPaused = this.isEnabled = false;
document.querySelector(".plugin-domtimeline #dom-recorder").setAttribute('is-recording-playing', 'false');
return true;
}
return false;
}
}
}
var saveFileBehavior = enableSaveFileBehavior();
function enableSaveFileBehavior() {
appDiv.querySelector("#saveAsFileButton").addEventListener('click', function(e:MouseEvent) {
if(latestMessage.url.indexOf('http://localhost') == 0) {
if(!confirm("This recording was captured on a local server. It might not work as expected on another computer. Continue anyway?")) {
return;
}
}
var button = <HTMLButtonElement>e.target;
button.setAttribute('disabled','true');
var data = {
template: '',
html: '',
script: '',
date: `${new Date().toISOString()}`,
title: `(${latestMessage.title ? latestMessage.title.replace(/</g,'<') : 'Untitled'})`,
url: JSON.stringify(latestMessage.url).replace(/<\/script>/g,"<\\\/script>"),
history: JSON.stringify(latestMessage.history).replace(/<\/script>/g,"<\\\/script>"),
domData: JSON.stringify(latestMessage.domData).replace(/<\/script>/g,"<\\\/script>"),
}
var writeContent = function() {
if(data.html && data.template && data.script) {
var content = data.template.replace(/\{\{([a-z]+)\}\}/gi, (s,k) => data[k]);
var a = document.createElement('a');
a.style.display = "none";
var blob = new Blob([content], {type: "application/octet-stream"});
if(window.navigator.msSaveBlob) {
window.navigator.msSaveBlob(blob, 'standalone.html');
} else {
var url = window.URL.createObjectURL(blob);
a.href = url;
(<any>a).download = 'standalone.html';
document.body.appendChild(a);
a.click();
setTimeout(function() {
document.body.removeChild(a);
window.URL.revokeObjectURL(url);
button.setAttribute('disabled',null);
}, 1000);
}
}
};
var x = new XMLHttpRequest();
x.open('GET',window['vorlonBaseURL']+'/vorlon/plugins/domtimeline/vorlon.domtimeline.dashboard.min.js',true);
x.onload = function() { data.script = this.responseText; writeContent(); }
x.send(null);
var x = new XMLHttpRequest();
x.open('GET',window['vorlonBaseURL']+'/vorlon/plugins/domtimeline/images/standalone.part.html',true);
x.onload = function() { data.template = this.responseText; writeContent(); }
x.send(null);
var x = new XMLHttpRequest();
x.open('GET',window['vorlonBaseURL']+'/vorlon/plugins/domtimeline/control.html',true);
x.onload = function() {
// let's get the content
var html = this.responseText;
// we need to extract all images
var imageExtractor = /url\('.*?'\)/gi;
var images = this.responseText.match(imageExtractor) || [];
var imagecount = images.length;
images.forEach((s,i) => {
var f = s.substring(5,s.length-2);
var x = new XMLHttpRequest();
x.open('GET', window['vorlonBaseURL']+f, true);
x.responseType = 'arraybuffer';
x.onload = function() { images[i] = 'url(data:image/png;base64,'+convertToBase64(this.response)+')'; onload(); };
x.send(null);
});
// then we can finally finish
function onload() {
if(--imagecount == 0) {
data.html = html.replace(imageExtractor, x => images.shift());
writeContent();
}
}
function convertToBase64(arrayBuffer) {
// Source: https://gist.github.com/jonleighton/958841
var base64 = ''
var encodings = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
var bytes = new Uint8Array(arrayBuffer)
var byteLength = bytes.byteLength
var byteRemainder = byteLength % 3
var mainLength = byteLength - byteRemainder
var a, b, c, d
var chunk
// Main loop deals with bytes in chunks of 3
for (var i = 0; i < mainLength; i = i + 3) {
// Combine the three bytes into a single integer
chunk = (bytes[i] << 16) | (bytes[i + 1] << 8) | bytes[i + 2]
// Use bitmasks to extract 6-bit segments from the triplet
a = (chunk & 16515072) >> 18 // 16515072 = (2^6 - 1) << 18
b = (chunk & 258048) >> 12 // 258048 = (2^6 - 1) << 12
c = (chunk & 4032) >> 6 // 4032 = (2^6 - 1) << 6
d = chunk & 63 // 63 = 2^6 - 1
// Convert the raw binary segments to the appropriate ASCII encoding
base64 += encodings[a] + encodings[b] + encodings[c] + encodings[d]
}
// Deal with the remaining bytes and padding
if (byteRemainder == 1) {
chunk = bytes[mainLength]
a = (chunk & 252) >> 2 // 252 = (2^6 - 1) << 2
// Set the 4 least significant bits to zero
b = (chunk & 3) << 4 // 3 = 2^2 - 1
base64 += encodings[a] + encodings[b] + '=='
} else if (byteRemainder == 2) {
chunk = (bytes[mainLength] << 8) | bytes[mainLength + 1]
a = (chunk & 64512) >> 10 // 64512 = (2^6 - 1) << 10
b = (chunk & 1008) >> 4 // 1008 = (2^6 - 1) << 4
// Set the 2 least significant bits to zero
c = (chunk & 15) << 2 // 15 = 2^4 - 1
base64 += encodings[a] + encodings[b] + encodings[c] + '='
}
return base64
}
}
x.send(null);
});
return {};
}
var seekBehavior = enableTimelineSeekBehavior();
function enableTimelineSeekBehavior() {
function getSeekElement() {
return <HTMLElement>document.querySelector("#timeline-seek");
}
var lastSeekTime = 0;
function getSeekTime() {
var seekTime = 0;
for(var i = alreadyKnownEvents.length; i--;) {
if(!alreadyKnownEvents[i].isCancelled) {
if(seekTime == 0) {
return lastSeekTime = alreadyKnownEvents[i].timestamp;
} else if(lastSeekTime > alreadyKnownEvents[i].timestamp && lastSeekTime < seekTime) {
return lastSeekTime;
} else {
return lastSeekTime = 0.5 * (alreadyKnownEvents[i].timestamp + seekTime);
}
} else {
seekTime = alreadyKnownEvents[i].timestamp;
}
}
if(lastSeekTime < seekTime) return lastSeekTime;
return lastSeekTime = 0;
}
function setSeekTime(timestamp,syncBack?) {
timestamp = typeof(timestamp)=="undefined" ? getSeekTime() : timestamp|0;
var offset = convertTimestampToOffset(timestamp);
var amountOfPastEvents = 0;
for(var i = alreadyKnownEvents.length; i--;) {
if(alreadyKnownEvents[i].timestamp <= timestamp) {
amountOfPastEvents = i+1; break;
}
}
lastSeekTime = timestamp;
getSeekElement().style.transform = `translateX(${offset}px)`;
if(syncBack == true || (syncBack !== false && latestMessage && latestMessage.isRecordingEnded)) {
executeScriptOnClient(`domHistory.seek(${amountOfPastEvents})`);
}
}
var timeline = document.querySelector('#timeline');
timeline.addEventListener('mousedown', (e:MouseEvent) => {
// disable in case of play animation
if(playBehavior.isEnabled) return;
var startingOffset = e.clientX - timeline.getBoundingClientRect().left;
var didSelectionStart = false;
setSeekTimeBasedOnOffet(e);
window.addEventListener('mousemove', onmousemove, true);
window.addEventListener('mouseup', onmouseup, true);
e.stopPropagation();
e.stopImmediatePropagation();
function setSeekTimeBasedOnOffet(e:MouseEvent) {
var offset = e.clientX - timeline.getBoundingClientRect().left;
var timestamp = convertOffsetToTimestamp(offset);
setSeekTime(timestamp,true);
}
function setSelectionBasedOnOffset(e:MouseEvent) {
var offset = e.clientX - timeline.getBoundingClientRect().left;
if(didSelectionStart || Math.abs(offset - startingOffset) > 2) {
didSelectionStart = true;
var lev = <HTMLElement>document.querySelector("#lev");
var fakeLev = <HTMLElement>document.querySelector("#fake-lev");
var smallerOffsetX = Math.min(startingOffset, offset);
var biggerOffsetX = Math.max(startingOffset, offset);
lev.style.display = `none`;
fakeLev.style.display = `block`;
fakeLev.style.left = `${smallerOffsetX}px`;
fakeLev.style.width = `${biggerOffsetX - smallerOffsetX}px`;
}
}
function onmousemove(e:MouseEvent) {
e.preventDefault(); e.stopPropagation();
setSeekTimeBasedOnOffet(e);
setSelectionBasedOnOffset(e);
}
function onmouseup(e:MouseEvent) {
e.preventDefault(); e.stopPropagation();
setSeekTimeBasedOnOffet(e);
setSelectionBasedOnOffset(e);
var lev = <HTMLElement>document.querySelector("#lev");
var fakeLev = <HTMLElement>document.querySelector("#fake-lev");
fakeLev.style.display = `none`;
if(fakeLev.style.width != '0px') {
lev.style.display = `block`;
lev.style.left = fakeLev.style.left;
lev.style.width = fakeLev.style.width;
fakeLev.style.left = `0px`;
fakeLev.style.width = `0px`;
selectionBehavior.syncFromDOM();
}
window.removeEventListener('mousemove', onmousemove, true);
window.removeEventListener('mouseup', onmouseup, true);
}
}, false);
keepToolbarAndTimelineFixed();
function keepToolbarAndTimelineFixed() {
var anchor = <HTMLElement>document.querySelector('#dom-recorder');
var chromeFix = <HTMLElement>anchor.querySelector('#dom-recorder > #chrome-fix');
var toolbar = <HTMLElement>anchor.querySelector('#dom-recorder > div[role="toolbar"]');
var timeline = <HTMLElement>anchor.querySelector('#dom-recorder > nav');
var lastBox = {width:0,top:0,left:0};
requestAnimationFrame(moveToolbarAndTimeline);
function moveToolbarAndTimeline() {
requestAnimationFrame(moveToolbarAndTimeline);
var box = anchor.getBoundingClientRect();
var wrapperBox = anchor.parentElement.getBoundingClientRect();
if(box.left==lastBox.left && box.width==lastBox.width && wrapperBox.top==lastBox.top) {
return;
}
chromeFix.style.display='block';
chromeFix.style.zIndex='1';
chromeFix.style.position='fixed';
toolbar.style.position = 'fixed';
timeline.style.position = 'fixed';
chromeFix.style.top = `${wrapperBox.top-1}px`;
chromeFix.style.left = `${box.left-1}px`;
chromeFix.style.width = `${box.width+2}px`;
chromeFix.style.top = `${wrapperBox.top-1}px`;
toolbar.style.top = `${wrapperBox.top}px`;
toolbar.style.left = `${box.left}px`;
toolbar.style.width = `${box.width}px`;
timeline.style.top = `${wrapperBox.top+32+10}px`
timeline.style.left = `${box.left+10}px`;
timeline.style.width = `${box.width-20}px`;
lastBox={left:box.left,width:box.width,top:wrapperBox.top};
}
}
document.querySelector("#timeline-seek").addEventListener('mousedown', function() {
// disable in case of play animation
if(playBehavior.isEnabled) return;
// reset the selection in case of double-click
selectionBehavior.reset();
});
return {
getSeekTime() { return getSeekTime(); },
setSeekTime(v?,syncBack?) { setSeekTime(v,syncBack); }
};
}
var selectionBehavior = enableTimelineHandleBehavior();
function enableTimelineHandleBehavior() {
var selectionZone = <HTMLElement>document.querySelector('#lev');
var leftResizer = <HTMLElement>selectionZone.querySelector('.lev1');
var rightResizer = <HTMLElement>selectionZone.querySelector('.lev2');
selectionZone.addEventListener('mousedown', (e:MouseEvent) => {
e.stopPropagation(); e.preventDefault();
// disable in case of play animation
if(playBehavior.isEnabled) return;
var shiftWasEverNonZero = false;
var startClientX = e.clientX;
var startOffset = parseFloat(selectionZone.style.left);
var deltaOffset = parseFloat(selectionZone.style.width);
var startSeekTime = seekBehavior.getSeekTime();
var isValidSeekTime = (
startSeekTime >= convertOffsetToTimestamp(startOffset-1) &&
startSeekTime <= convertOffsetToTimestamp(startOffset + deltaOffset + 1)
);
if(!isValidSeekTime) startSeekTime = convertOffsetToTimestamp(startOffset + deltaOffset);
window.addEventListener('mousemove', onmousemove, true);
window.addEventListener('mouseup', onmouseup, true);
function shiftSelectionBasedOnOffset(e:MouseEvent) {
var shift = (e.clientX - startClientX);
if(Math.abs(shift) > 1) shiftWasEverNonZero = true;
var offset = Math.max(0, startOffset + (shift));
var seekTime = Math.max(0, startSeekTime + convertOffsetToTimestamp(e.clientX - startClientX));
selectionZone.style.left = `${offset}px`;
seekBehavior.setSeekTime(seekTime, true);
}
function onmousemove(e:MouseEvent) {
e.stopPropagation(); e.preventDefault();
shiftSelectionBasedOnOffset(e);
}
function onmouseup(e:MouseEvent) {
e.stopPropagation(); e.preventDefault();
shiftSelectionBasedOnOffset(e);
if(shiftWasEverNonZero) {
selectionBehavior.syncFromDOM();
} else {
seekBehavior.setSeekTime(
convertOffsetToTimestamp(e.clientX - selectionZone.parentElement.getBoundingClientRect().left),
true
);
}
window.removeEventListener('mousemove', onmousemove, true);
window.removeEventListener('mouseup', onmouseup, true);
}
});
leftResizer.addEventListener('mousedown', (e:MouseEvent) => {
e.stopPropagation();
var shiftWasEverNonZero = false;
var startClientX = e.clientX;
var startOffset1 = parseFloat(selectionZone.style.left);
var startOffset2 = startOffset1 + parseFloat(selectionZone.style.width);
var startSeekTime = convertOffsetToTimestamp(startOffset1);
window.addEventListener('mousemove', onmousemove, true);
window.addEventListener('mouseup', onmouseup, true);
function shiftSelectionBasedOnOffset(e:MouseEvent) {
var shift = (e.clientX - startClientX);
if(Math.abs(shift) > 1) shiftWasEverNonZero = true;
var offset = Math.max(0, startOffset1 + shift);
var offset1 = Math.min(offset, startOffset2);
var offset2 = Math.max(offset, startOffset2);
var seekTime = convertOffsetToTimestamp(offset);
selectionZone.style.left = `${offset1}px`;
selectionZone.style.width = `${offset2-offset1}px`;
seekBehavior.setSeekTime(seekTime, true);
}
function onmousemove(e:MouseEvent) {
e.stopPropagation(); e.preventDefault();
shiftSelectionBasedOnOffset(e);
}
function onmouseup(e:MouseEvent) {
e.stopPropagation(); e.preventDefault();
shiftSelectionBasedOnOffset(e);
if(shiftWasEverNonZero) {
selectionBehavior.syncFromDOM();
}
window.removeEventListener('mousemove', onmousemove, true);
window.removeEventListener('mouseup', onmouseup, true);
}
});
rightResizer.addEventListener('mousedown', (e:MouseEvent) => {
e.stopPropagation();
var shiftWasEverNonZero = false;
var startClientX = e.clientX;
var startOffset1 = parseFloat(selectionZone.style.left);
var startOffset2 = startOffset1 + parseFloat(selectionZone.style.width);
var startSeekTime = convertOffsetToTimestamp(startOffset1);
window.addEventListener('mousemove', onmousemove, true);
window.addEventListener('mouseup', onmouseup, true);
function shiftSelectionBasedOnOffset(e:MouseEvent) {
var shift = (e.clientX - startClientX);
if(Math.abs(shift) > 1) shiftWasEverNonZero = true;
var offset = Math.max(0, startOffset2 + shift);
var offset1 = Math.min(offset, startOffset1);
var offset2 = Math.max(offset, startOffset1);
var seekTime = convertOffsetToTimestamp(offset);
selectionZone.style.left = `${offset1}px`;
selectionZone.style.width = `${offset2-offset1}px`;
seekBehavior.setSeekTime(seekTime, true);
}
function onmousemove(e:MouseEvent) {
e.stopPropagation(); e.preventDefault();
shiftSelectionBasedOnOffset(e);
}
function onmouseup(e:MouseEvent) {
e.stopPropagation(); e.preventDefault();
shiftSelectionBasedOnOffset(e);
if(shiftWasEverNonZero) {
selectionBehavior.syncFromDOM();
}
window.removeEventListener('mousemove', onmousemove, true);
window.removeEventListener('mouseup', onmouseup, true);
}
});
return {
isEnabled: false,
selectionStartTimestamp: 0,
selectionEndTimestamp: 0,
reset() {
this.isEnabled = false;
this.selectionStartTimestamp = 0;
this.selectionEndTimestamp = 0;
selectionZone.style.display = "none";
},
set(startTimestamp, endTimestamp) {
this.isEnabled = true;
this.selectionStartTimestamp = startTimestamp;
this.selectionEndTimestamp = endTimestamp;
var startOffset = convertTimestampToOffset(startTimestamp);
var endOffset = convertTimestampToOffset(endTimestamp);
var offset1 = Math.min(startOffset, endOffset);
var offset2 = Math.max(startOffset, endOffset);
selectionZone.style.display = "block";
selectionZone.style.left = `${offset1}px`;
selectionZone.style.width = `${offset2-offset1}px`;
setNumberChanges(alreadyKnownEvents);
setChanges(alreadyKnownEvents);
},
syncFromDOM() {
var offset1 = parseFloat(selectionZone.style.left);
var offset2 = offset1 + parseFloat(selectionZone.style.width);
this.set(
convertOffsetToTimestamp(offset1),
convertOffsetToTimestamp(offset2)
);
}
}
}
function convertTimestampToOffset(timestamp) {
return (timestamp/1000) * (SCALE * 61);
}
function convertOffsetToTimestamp(offset) {
return 1000 * (offset / (SCALE * 61));
}
//selectable();
$('#filter-changes input').on('keypress', function (e) {
var toVal = $('#filter-changes .to').val();
var fromVal = $('#filter-changes .from').val();
if (e.keyCode == 13 && !(toVal < 0 || fromVal < 0 || toVal > TIMELINE_SECONDS || fromVal > TIMELINE_SECONDS)) {
$('#lev').css({ left: ($('#filter-changes .from').val() * (SCALE*61)), width: ($('#filter-changes .to').val() * (SCALE*61)) - ($('#filter-changes .from').val() * (SCALE*61)) });
levChanged();
}
});
$('#node-changes input').on('keyup', function () {
var value = this.value;
$('.accordion-changes .acc-tr').hide().each(function () {
if ($(this).text().search(value) > -1) {
$(this).show();
}
});
});
enableTimelinePanning();
function enableTimelinePanning() {
var x, y, top, left, down;
$(".seconds-list").mousedown(function (e) {
e.preventDefault();
down = true;
x = e.pageX;
left = $("#wrapper-timeline").scrollLeft();
//y = e.pageY;
//top = $("#wrapper-timeline").scrollTop();
});
$("body").mousemove(function (e) {
if (down) {
var newX = e.pageX;
$("#wrapper-timeline").scrollLeft(left - newX + x);
//var newY = e.pageY;
//$("#wrapper-timeline").scrollTop(top - newY + y);
}
});
$("body").mouseup(function (e) { down = false; });
}
$("#colorblind").change(function () {
if (!this.checked) {
$('#dom-recorder').removeClass('colorblind-on').addClass('colorblind-off');
} else {
$('#dom-recorder').removeClass('colorblind-off').addClass('colorblind-on');
}
});
$('#filter-changes').find('a').click(function (e) {
e.preventDefault();
$('#lev').css('width', '0px');
levChanged('reset');
});
/*var element = document.getElementById('lev');
$(".lev").draggable({
axis: 'x',
containment: 'parent',
handle: '.drag-lev',
drag: function (e) {
levChanged('draggable');
}
});
var resizerE = document.getElementsByClassName('lev2')[0];
resizerE.addEventListener('mousedown', initResizeE, false);
function initResizeE(e) {
// FIXME: $("#timeline").selectable('destroy');
window.addEventListener('mousemove', ResizeE, false);
window.addEventListener('mouseup', stopResizeE, false);
}
function ResizeE(e) {
levChanged('resize');
element.style.width = ((e.clientX - $('#timeline').offset().left) - $('.lev').position().left) + 'px';
}
function stopResizeE(e) {
selectable();
window.removeEventListener('mousemove', ResizeE, false);
window.removeEventListener('mouseup', stopResizeE, false);
}
var baseX;
var baseW;
var resizerW = document.getElementsByClassName('lev1')[0];
resizerW.addEventListener('mousedown', initResizeW, false);
function initResizeW(e) {
$("#timeline").selectable('destroy');
baseX = e.clientX - $('#timeline').offset().left;
baseW = parseInt(element.style.width);
window.addEventListener('mousemove', ResizeW, false);
window.addEventListener('mouseup', stopResizeW, false);
}
function ResizeW(e) {
levChanged('resize');
if (baseX < (e.clientX - $('#timeline').offset().left)) {
element.style.width = (baseW - ((e.clientX - $('#timeline').offset().left - baseX))) + 'px';
} else {
element.style.width = (baseW + (baseX - (e.clientX - $('#timeline').offset().left))) + 'px';
}
if (e.clientX - $('#timeline').offset().left < 0) {
element.style.left = '0px';
} else {
element.style.left = ((e.clientX - $('#timeline').offset().left)) + 'px';
}
}
function stopResizeW(e) {
selectable();
window.removeEventListener('mousemove', ResizeW, false);
window.removeEventListener('mouseup', stopResizeW, false);
}*/
return {
setTimeline: setTimeline
};
} | the_stack |
import * as fs from 'fs-extra';
import * as _ from 'lodash';
import * as path from 'path';
import * as yargs from 'yargs';
import * as pkg from '../../../../package.json';
import { pri } from '../../../node';
import { PRI_PACKAGE_NAME, CONFIG_FILE } from '../../../utils/constants';
import { safeJsonParse } from '../../../utils/functional';
import { globalState, transferToAllAbsolutePaths } from '../../../utils/global-state';
import {
declarePath,
gitIgnores,
npmIgnores,
tempPath,
tempTypesPath,
srcPath,
typingsPath,
} from '../../../utils/structor-config';
import { ensureComponentFiles } from './ensure-component';
import { ensurePluginFiles } from './ensure-plugin';
import { ensureProjectFiles } from './ensure-project';
export const main = async () => {
ensureGitignore();
ensureNpmignore();
ensureNpmrc();
ensureTsconfig();
ensureVscode();
ensureEslint();
ensurePrettier();
ensurePriConfig();
ensureDeclares();
switch (pri.sourceConfig.type) {
case 'project':
ensureProjectFiles();
ensureRootPackageJson();
break;
case 'component':
ensureComponentFiles();
ensureRootPackageJson();
break;
case 'plugin':
ensurePluginFiles();
ensureRootPackageJson();
break;
default:
// don't need ensure root package.json for extend type
}
};
const maxSizePri = 'node --max-old-space-size=16384 --max_old_space_size=16384 ./node_modules/.bin/pri';
const commonComponentPackageJson = {
scripts: {
start: `${maxSizePri} dev`,
docs: `${maxSizePri} docs`,
build: `${maxSizePri} build`,
bundle: `${maxSizePri} bundle`,
preview: `${maxSizePri} preview`,
analyse: `${maxSizePri} analyse`,
publish: `${maxSizePri} publish`,
lint: `${maxSizePri} lint`,
test: `${maxSizePri} test`,
},
husky: {
hooks: {
'pre-commit': 'npm test -- --package root',
},
},
};
function ensureDeclares() {
fs.copySync(path.join(__dirname, '../../../../declare'), path.join(pri.projectRootPath, declarePath.dir));
}
function ensureTsconfig() {
pri.project.addProjectFiles({
fileName: path.join(pri.projectRootPath, 'tsconfig.json'),
pipeContent: async () => {
return `${JSON.stringify(
{
compilerOptions: {
module: 'esnext',
moduleResolution: 'node',
strict: true,
strictNullChecks: false,
incremental: true,
jsx: 'react',
target: 'esnext',
experimentalDecorators: true,
skipLibCheck: true,
outDir: globalState.sourceConfig.distDir,
baseUrl: '.',
lib: ['dom', 'es5', 'es6', 'es7', 'scripthost', 'es2018.promise'],
emitDecoratorMetadata: true,
preserveConstEnums: true,
isolatedModules: true,
paths: {
[`${PRI_PACKAGE_NAME}/*`]: [PRI_PACKAGE_NAME, path.join(tempTypesPath.dir, '*')],
...(pri.sourceConfig.type === 'project' && { 'src/*': ['src/*'] }),
// Packages alias names
...globalState.packages.reduce((obj, eachPackage) => {
if (eachPackage.packageJson && eachPackage.packageJson.name) {
return {
...obj,
[eachPackage.packageJson.name]: [
path.join(path.relative(pri.projectRootPath, eachPackage.rootPath), 'src'),
],
};
}
return obj;
}, {}),
},
},
include: [
`${tempPath.dir}/**/*`,
`${typingsPath.dir}/**/*`,
...transferToAllAbsolutePaths(srcPath.dir).map(filePath => {
return `${path.relative(pri.projectRootPath, filePath)}/**/*`;
}),
],
exclude: ['node_modules', globalState.projectConfig.distDir, tempPath.dir],
},
null,
2,
)}\n`; // Make sure ./src structor. # https://github.com/Microsoft/TypeScript/issues/5134
},
});
}
function ensureEslint() {
pri.project.addProjectFiles({
fileName: path.join(pri.projectRootPath, '.eslintrc'),
pipeContent: async () => {
const eslintConfig = await fs.readFile(path.join(__dirname, '../../../../.eslintrc'));
return `${eslintConfig.toString()}\n`;
},
});
}
function ensurePrettier() {
pri.project.addProjectFiles({
fileName: path.join(pri.projectRootPath, '.prettierrc'),
pipeContent: async () => {
const prettierConfig = await fs.readFile(path.join(__dirname, '../../../../.prettierrc'));
return `${prettierConfig.toString()}\n`;
},
});
}
function ensureVscode() {
pri.project.addProjectFiles({
fileName: path.join(pri.projectRootPath, '.vscode/settings.json'),
pipeContent: (prev: string) => {
const pickedPrev = _.omit(safeJsonParse(prev), 'eslint.provideLintTask');
return `${JSON.stringify(
_.merge({}, pickedPrev, {
'editor.formatOnSave': true,
'typescript.tsdk': 'node_modules/typescript/lib',
'eslint.codeActionsOnSave': true,
'eslint.validate': ['javascript', 'javascriptreact', 'typescript', 'typescriptreact'],
'eslint.lintTask.enable': true,
'typescript.format.enable': true,
'javascript.format.enable': true,
'[typescriptreact]': {
'editor.defaultFormatter': 'esbenp.prettier-vscode',
},
'[typescript]': {
'editor.defaultFormatter': 'esbenp.prettier-vscode',
},
}),
null,
2,
)}\n`;
},
});
pri.project.addProjectFiles({
fileName: path.join(pri.projectRootPath, '.vscode/extensions.json'),
pipeContent: (prev: string) => {
return `${JSON.stringify(
_.merge({}, safeJsonParse(prev), {
recommendations: [
'dbaeumer.vscode-eslint',
'eamodio.gitlens',
'zhuangtongfa.material-theme',
'jasonhzq.vscode-pont',
],
}),
null,
2,
)}\n`;
},
});
}
function ensureGitignore() {
pri.project.addProjectFiles({
fileName: path.join(pri.projectRootPath, '.gitignore'),
pipeContent: (prev = '') => {
const values = prev.split('\n').filter(eachRule => {
return !!eachRule;
});
const gitIgnoresInRoot = gitIgnores.map(name => {
return `/${name}`;
});
return _.union(values, gitIgnoresInRoot).join('\n');
},
});
}
function ensureNpmignore() {
pri.project.addProjectFiles({
fileName: path.join(pri.projectRootPath, '.npmignore'),
pipeContent: (prev = '') => {
const values = prev.split('\n').filter(eachRule => {
return !!eachRule;
});
const npmIgnoresInRoot = npmIgnores.map(name => {
return `/${name}`;
});
return _.union(values, npmIgnoresInRoot).join('\n');
},
});
}
function ensureNpmrc() {
pri.project.addProjectFiles({
fileName: path.join(pri.projectRootPath, '.npmrc'),
pipeContent: () => {
return `package-lock=${globalState.projectConfig.packageLock ? 'true' : 'false'}`;
},
});
}
function ensureRootPackageJson() {
pri.project.addProjectFiles({
fileName: path.join(pri.projectRootPath, 'package.json'),
pipeContent: (prev: string) => {
let prevJson = safeJsonParse(prev);
const priDeps = pkg.dependencies || {};
if (pri.sourceConfig.type === 'project') {
// Remove all packages which already exists in pri dependencies.
if (prevJson.dependencies) {
prevJson.dependencies = _.omit(prevJson.dependencies, Object.keys(priDeps));
}
if (prevJson.devDependencies) {
prevJson.devDependencies = _.omit(prevJson.devDependencies, Object.keys(priDeps));
}
if (prevJson.peerDependencies) {
prevJson.peerDependencies = _.omit(prevJson.peerDependencies, Object.keys(priDeps));
}
} else {
// Not project type, just reset it's version if exist.
setVersionIfExist(prevJson, 'dependencies', priDeps);
// Remove devDeps which already exists in pri dependencies.
if (prevJson.devDependencies) {
prevJson.devDependencies = _.omit(prevJson.devDependencies, Object.keys(priDeps));
}
if (prevJson.peerDependencies) {
prevJson.peerDependencies = _.omit(prevJson.peerDependencies, Object.keys(priDeps));
}
}
// Mv pri-plugins to devDeps except plugin
if (pri.projectConfig.type === 'plugin') {
prevJson = mvPriPlugins(prevJson, 'devDependencies', 'dependencies');
prevJson = mvPriPlugins(prevJson, 'peerDependencies', 'dependencies');
} else {
prevJson = mvPriPlugins(prevJson, 'dependencies', 'devDependencies');
prevJson = mvPriPlugins(prevJson, 'peerDependencies', 'devDependencies');
}
switch (pri.projectConfig.type) {
case 'project':
{
// Move pri from devDeps to deps
const projectPriVersion =
_.get(prevJson, `devDependencies.${PRI_PACKAGE_NAME}`) ||
_.get(prevJson, `dependencies.${PRI_PACKAGE_NAME}`) ||
pkg.version;
_.unset(prevJson, `devDependencies.${PRI_PACKAGE_NAME}`);
_.set(prevJson, `dependencies.${PRI_PACKAGE_NAME}`, projectPriVersion);
}
break;
case 'plugin':
{
// Move pri from deps to devDeps
const projectPriVersion =
_.get(prevJson, `devDependencies.${PRI_PACKAGE_NAME}`) ||
_.get(prevJson, `dependencies.${PRI_PACKAGE_NAME}`) ||
pkg.version;
_.unset(prevJson, `dependencies.${PRI_PACKAGE_NAME}`);
_.set(prevJson, `devDependencies.${PRI_PACKAGE_NAME}`, projectPriVersion);
// Add babel-runtime
_.set(prevJson, 'dependencies.@babel/runtime', priDeps['@babel/runtime']);
}
break;
case 'component':
{
// Move pri from deps to devDeps
const projectPriVersion =
_.get(prevJson, `devDependencies.${PRI_PACKAGE_NAME}`) ||
_.get(prevJson, `dependencies.${PRI_PACKAGE_NAME}`) ||
pkg.version;
_.unset(prevJson, `dependencies.${PRI_PACKAGE_NAME}`);
_.set(prevJson, `devDependencies.${PRI_PACKAGE_NAME}`, projectPriVersion);
// Add babel-runtime
_.set(prevJson, 'dependencies.@babel/runtime', priDeps['@babel/runtime']);
}
break;
default:
}
switch (pri.projectConfig.type) {
case 'project':
_.set(prevJson, 'main', `${pri.projectConfig.distDir}/${pri.projectConfig.outFileName}`);
break;
case 'plugin':
case 'component':
if (yargs.argv._[0] === 'dev') {
// Component dev mode, has a whole project struct
if (pri.selectedSourceType === 'root') {
_.set(prevJson, 'main', `${pri.projectConfig.distDir}/main/src`);
_.set(prevJson, 'module', `${pri.projectConfig.distDir}/module/src`);
_.set(prevJson, 'types', 'src');
} else {
_.set(prevJson, 'main', `${pri.projectConfig.distDir}/main/packages/${pri.selectedSourceType}/src`);
_.set(prevJson, 'module', `${pri.projectConfig.distDir}/module/packages/${pri.selectedSourceType}/src`);
_.set(prevJson, 'types', `packages/${pri.selectedSourceType}/src`);
}
} else {
_.set(prevJson, 'main', `${pri.projectConfig.distDir}/main`);
_.set(prevJson, 'module', `${pri.projectConfig.distDir}/module`);
_.set(prevJson, 'types', 'declaration/index.d.ts');
}
break;
default:
}
return `${JSON.stringify(_.merge({}, prevJson, commonComponentPackageJson), null, 2)}\n`;
},
});
}
function ensurePriConfig() {
pri.project.addProjectFiles({
fileName: path.join(pri.sourceRoot, CONFIG_FILE),
pipeContent: (prev: string) => {
return `${JSON.stringify(
_.merge({}, safeJsonParse(prev), {
type: pri.sourceConfig.type,
}),
null,
2,
)}\n`;
},
});
}
function setVersionIfExist(sourceObj: any, key: string, targetObj: any) {
if (!_.isEmpty(_.get(sourceObj, key))) {
Object.keys(_.get(sourceObj, key)).forEach(sourceObjKey => {
if (targetObj[sourceObjKey]) {
_.set(sourceObj, [key, sourceObjKey], targetObj[sourceObjKey]);
}
});
}
}
function mvPriPlugins(obj: any, sourceKey: string, targetKey: string) {
const newObj = { ...obj };
if (!obj[sourceKey]) {
newObj[sourceKey] = {};
}
if (!obj[targetKey]) {
newObj[targetKey] = {};
}
const priPlugins = Object.keys(obj[sourceKey] || {}).filter(packageName => {
return packageName.startsWith('pri-plugin') || packageName.startsWith('@ali/pri-plugin');
});
// Add plugins to targetKey
priPlugins.forEach(packageName => {
newObj[targetKey][packageName] = obj[sourceKey][packageName];
});
// Remove plugins from sourceKey
newObj[sourceKey] = _.omit(obj[sourceKey], priPlugins);
return newObj;
} | the_stack |
import {Guid} from 'guid-typescript';
import Long from 'long';
import {onnx} from 'onnx-proto';
import {onnxruntime} from './ortSchema/ort_generated';
import ortFbs = onnxruntime.experimental.fbs;
import {ProtoUtil, ShapeUtil} from './util';
export let globalId = 0;
export declare namespace Tensor {
export interface DataTypeMap {
bool: Uint8Array;
float32: Float32Array;
float64: Float64Array;
string: string[];
int8: Int8Array;
uint8: Uint8Array;
int16: Int16Array;
uint16: Uint16Array;
int32: Int32Array;
uint32: Uint32Array;
}
export type DataType = keyof DataTypeMap;
export type StringType = Tensor.DataTypeMap['string'];
export type BooleanType = Tensor.DataTypeMap['bool'];
export type IntegerType = Tensor.DataTypeMap['int8']|Tensor.DataTypeMap['uint8']|Tensor.DataTypeMap['int16']|
Tensor.DataTypeMap['uint16']|Tensor.DataTypeMap['int32']|Tensor.DataTypeMap['uint32'];
export type FloatType = Tensor.DataTypeMap['float32']|Tensor.DataTypeMap['float64'];
export type NumberType = BooleanType|IntegerType|FloatType;
export type Id = Guid;
}
type TensorData = Tensor.DataTypeMap[Tensor.DataType];
type DataProvider = (id: Guid) => TensorData;
type AsyncDataProvider = (id: Guid) => Promise<TensorData>;
export class Tensor {
/**
* get the underlying tensor data
*/
get data(): TensorData {
if (this.cache === undefined) {
const data = this.dataProvider!(this.dataId);
if (data.length !== this.size) {
throw new Error(`Length of data provided by the Data Provider is inconsistent with the dims of this Tensor.`);
}
this.cache = data;
}
return this.cache;
}
/**
* get the underlying string tensor data. Should only use when type is STRING
*/
get stringData() {
if (this.type !== 'string') {
throw new TypeError(`data type is not string`);
}
return this.data as Tensor.StringType;
}
/**
* get the underlying integer tensor data. Should only use when type is one of the following: (UINT8, INT8, UINT16,
* INT16, INT32, UINT32, BOOL)
*/
get integerData() {
switch (this.type) {
case 'uint8':
case 'int8':
case 'uint16':
case 'int16':
case 'int32':
case 'uint32':
case 'bool':
return this.data as Tensor.IntegerType;
default:
throw new TypeError(`data type is not integer (uint8, int8, uint16, int16, int32, uint32, bool)`);
}
}
/**
* get the underlying float tensor data. Should only use when type is one of the following: (FLOAT, DOUBLE)
*/
get floatData() {
switch (this.type) {
case 'float32':
case 'float64':
return this.data as Tensor.FloatType;
default:
throw new TypeError(`data type is not float (float32, float64)`);
}
}
/**
* get the underlying number tensor data. Should only use when type is one of the following: (UINT8, INT8, UINT16,
* INT16, INT32, UINT32, BOOL, FLOAT, DOUBLE)
*/
get numberData() {
if (this.type !== 'string') {
return this.data as Tensor.NumberType;
}
throw new TypeError(`type cannot be non-number (string)`);
}
/**
* get value of an element at the given indices
*/
get(indices: ReadonlyArray<number>): Tensor.DataTypeMap[Tensor.DataType][number] {
return this.data[ShapeUtil.indicesToOffset(indices, this.strides)];
}
/**
* set value of an element at the given indices
*/
set(indices: ReadonlyArray<number>, value: Tensor.DataTypeMap[Tensor.DataType][number]) {
this.data[ShapeUtil.indicesToOffset(indices, this.strides)] = value;
}
/**
* get the underlying tensor data asynchronously
*/
async getData(): Promise<TensorData> {
// TBD: This function is designed for usage when any backend data provider offers a way to retrieve data in an
// asynchronous way. should implement this function when enabling webgl async read data.
if (this.cache === undefined) {
this.cache = await this.asyncDataProvider!(this.dataId);
}
return this.cache;
}
/**
* get the number of elements in the tensor
*/
public readonly size: number;
private _strides: ReadonlyArray<number>;
/**
* get the strides for each dimension
*/
get strides(): ReadonlyArray<number> {
if (!this._strides) {
this._strides = ShapeUtil.computeStrides(this.dims);
}
return this._strides;
}
constructor(
/**
* get the dimensions of the tensor
*/
public readonly dims: ReadonlyArray<number>,
/**
* get the type of the tensor
*/
public readonly type: Tensor.DataType, private dataProvider?: DataProvider,
private asyncDataProvider?: AsyncDataProvider, private cache?: TensorData,
/**
* get the data ID that used to map to a tensor data
*/
public readonly dataId: Guid = Guid.create()) {
this.size = ShapeUtil.validateDimsAndCalcSize(dims);
const size = this.size;
const empty = (dataProvider === undefined && asyncDataProvider === undefined && cache === undefined);
if (cache !== undefined) {
if (cache.length !== size) {
throw new RangeError(`Input dims doesn't match data length.`);
}
}
if (type === 'string') {
if (cache !== undefined && (!Array.isArray(cache) || !cache.every(i => typeof i === 'string'))) {
throw new TypeError(`cache should be a string array`);
}
if (empty) {
cache = new Array<string>(size);
}
} else {
if (cache !== undefined) {
const constructor = dataviewConstructor(type);
if (!(cache instanceof constructor)) {
throw new TypeError(`cache should be type ${constructor.name}`);
}
}
if (empty) {
const buf = new ArrayBuffer(size * sizeof(type));
this.cache = createView(buf, type);
}
}
}
/**
* Construct new Tensor from a ONNX Tensor object
* @param tensorProto the ONNX Tensor
*/
static fromProto(tensorProto: onnx.ITensorProto): Tensor {
if (!tensorProto) {
throw new Error('cannot construct Value from an empty tensor');
}
const type = ProtoUtil.tensorDataTypeFromProto(tensorProto.dataType!);
const dims = ProtoUtil.tensorDimsFromProto(tensorProto.dims!);
const value = new Tensor(dims, type);
if (type === 'string') {
// When it's STRING type, the value should always be stored in field
// 'stringData'
tensorProto.stringData!.forEach((str, i) => {
const buf = Buffer.from(str.buffer, str.byteOffset, str.byteLength);
value.data[i] = buf.toString();
});
} else if (
tensorProto.rawData && typeof tensorProto.rawData.byteLength === 'number' &&
tensorProto.rawData.byteLength > 0) {
// NOT considering segment for now (IMPORTANT)
// populate value from rawData
const dataDest = value.data;
const dataSource =
new DataView(tensorProto.rawData.buffer, tensorProto.rawData.byteOffset, tensorProto.rawData.byteLength);
const elementSize = sizeofProto(tensorProto.dataType!);
const length = tensorProto.rawData.byteLength / elementSize;
if (tensorProto.rawData.byteLength % elementSize !== 0) {
throw new Error(`invalid buffer length`);
}
if (dataDest.length !== length) {
throw new Error(`buffer length mismatch`);
}
for (let i = 0; i < length; i++) {
const n = readProto(dataSource, tensorProto.dataType!, i * elementSize);
dataDest[i] = n;
}
} else {
// populate value from array
let array: Array<number|Long>;
switch (tensorProto.dataType) {
case onnx.TensorProto.DataType.FLOAT:
array = tensorProto.floatData!;
break;
case onnx.TensorProto.DataType.INT32:
case onnx.TensorProto.DataType.INT16:
case onnx.TensorProto.DataType.UINT16:
case onnx.TensorProto.DataType.INT8:
case onnx.TensorProto.DataType.UINT8:
case onnx.TensorProto.DataType.BOOL:
array = tensorProto.int32Data!;
break;
case onnx.TensorProto.DataType.INT64:
array = tensorProto.int64Data!;
break;
case onnx.TensorProto.DataType.DOUBLE:
array = tensorProto.doubleData!;
break;
case onnx.TensorProto.DataType.UINT32:
case onnx.TensorProto.DataType.UINT64:
array = tensorProto.uint64Data!;
break;
default:
// should never run here
throw new Error('unspecific error');
}
if (array === null || array === undefined) {
throw new Error('failed to populate data from a tensorproto value');
}
const data = value.data;
if (data.length !== array.length) {
throw new Error(`array length mismatch`);
}
for (let i = 0; i < array.length; i++) {
const element = array[i];
if (Long.isLong(element)) {
data[i] = longToNumber(element, tensorProto.dataType);
} else {
data[i] = element;
}
}
}
return value;
}
/**
* Construct new Tensor from raw data
* @param data the raw data object. Should be a string array for 'string' tensor, and the corresponding typed array
* for other types of tensor.
* @param dims the dimensions of the tensor
* @param type the type of the tensor
*/
static fromData(data: Tensor.DataTypeMap[Tensor.DataType], dims: ReadonlyArray<number>, type: Tensor.DataType) {
return new Tensor(dims, type, undefined, undefined, data);
}
static fromOrtTensor(ortTensor: ortFbs.Tensor) {
if (!ortTensor) {
throw new Error('cannot construct Value from an empty tensor');
}
const dims = ProtoUtil.tensorDimsFromORTFormat(ortTensor);
const type = ProtoUtil.tensorDataTypeFromProto(ortTensor.dataType());
const value = new Tensor(dims, type);
if (type === 'string') {
// When it's STRING type, the value should always be stored in field
// 'stringData'
for (let i = 0; i < ortTensor.stringDataLength(); i++) {
value.data[i] = ortTensor.stringData(i);
}
} else if (ortTensor.rawData && typeof ortTensor.rawDataLength() === 'number' && ortTensor.rawDataLength() > 0) {
// NOT considering segment for now (IMPORTANT)
// populate value from rawData
const dataDest = value.data;
const dataSource = new DataView(
ortTensor.rawDataArray()!.buffer, ortTensor.rawDataArray()!.byteOffset, ortTensor.rawDataLength());
const elementSize = sizeofProto(ortTensor.dataType());
const length = ortTensor.rawDataLength() / elementSize;
if (ortTensor.rawDataLength() % elementSize !== 0) {
throw new Error(`invalid buffer length`);
}
if (dataDest.length !== length) {
throw new Error(`buffer length mismatch`);
}
for (let i = 0; i < length; i++) {
const n = readProto(dataSource, ortTensor.dataType(), i * elementSize);
dataDest[i] = n;
}
}
return value;
}
}
function sizeof(type: Tensor.DataType): number {
switch (type) {
case 'bool':
case 'int8':
case 'uint8':
return 1;
case 'int16':
case 'uint16':
return 2;
case 'int32':
case 'uint32':
case 'float32':
return 4;
case 'float64':
return 8;
default:
throw new Error(`cannot calculate sizeof() on type ${type}`);
}
}
function sizeofProto(type: onnx.TensorProto.DataType|ortFbs.TensorDataType): number {
switch (type) {
case onnx.TensorProto.DataType.UINT8|ortFbs.TensorDataType.UINT8:
case onnx.TensorProto.DataType.INT8|ortFbs.TensorDataType.INT8:
case onnx.TensorProto.DataType.BOOL|ortFbs.TensorDataType.BOOL:
return 1;
case onnx.TensorProto.DataType.UINT16|ortFbs.TensorDataType.UINT16:
case onnx.TensorProto.DataType.INT16|ortFbs.TensorDataType.INT16:
return 2;
case onnx.TensorProto.DataType.FLOAT|ortFbs.TensorDataType.FLOAT:
case onnx.TensorProto.DataType.INT32|ortFbs.TensorDataType.INT32:
case onnx.TensorProto.DataType.UINT32|ortFbs.TensorDataType.UINT32:
return 4;
case onnx.TensorProto.DataType.INT64|ortFbs.TensorDataType.INT64:
case onnx.TensorProto.DataType.DOUBLE|ortFbs.TensorDataType.DOUBLE:
case onnx.TensorProto.DataType.UINT64|ortFbs.TensorDataType.UINT64:
return 8;
default:
throw new Error(`cannot calculate sizeof() on type ${onnx.TensorProto.DataType[type]}`);
}
}
function createView(dataBuffer: ArrayBuffer, type: Tensor.DataType) {
return new (dataviewConstructor(type))(dataBuffer);
}
function dataviewConstructor(type: Tensor.DataType) {
switch (type) {
case 'bool':
case 'uint8':
return Uint8Array;
case 'int8':
return Int8Array;
case 'int16':
return Int16Array;
case 'uint16':
return Uint16Array;
case 'int32':
return Int32Array;
case 'uint32':
return Uint32Array;
case 'float32':
return Float32Array;
case 'float64':
return Float64Array;
default:
// should never run to here
throw new Error('unspecified error');
}
}
// convert a long number to a 32-bit integer (cast-down)
function longToNumber(i: Long, type: onnx.TensorProto.DataType|ortFbs.TensorDataType): number {
// INT64, UINT32, UINT64
if (type === onnx.TensorProto.DataType.INT64 || type === ortFbs.TensorDataType.INT64) {
if (i.greaterThanOrEqual(2147483648) || i.lessThan(-2147483648)) {
throw new TypeError('int64 is not supported');
}
} else if (
type === onnx.TensorProto.DataType.UINT32 || type === ortFbs.TensorDataType.UINT32 ||
type === onnx.TensorProto.DataType.UINT64 || type === ortFbs.TensorDataType.UINT64) {
if (i.greaterThanOrEqual(4294967296) || i.lessThan(0)) {
throw new TypeError('uint64 is not supported');
}
} else {
throw new TypeError(`not a LONG type: ${onnx.TensorProto.DataType[type]}`);
}
return i.toNumber();
}
// read one value from TensorProto
function readProto(view: DataView, type: onnx.TensorProto.DataType|ortFbs.TensorDataType, byteOffset: number): number {
switch (type) {
case onnx.TensorProto.DataType.BOOL|ortFbs.TensorDataType.BOOL:
case onnx.TensorProto.DataType.UINT8|ortFbs.TensorDataType.UINT8:
return view.getUint8(byteOffset);
case onnx.TensorProto.DataType.INT8|ortFbs.TensorDataType.INT8:
return view.getInt8(byteOffset);
case onnx.TensorProto.DataType.UINT16|ortFbs.TensorDataType.UINT16:
return view.getUint16(byteOffset, true);
case onnx.TensorProto.DataType.INT16|ortFbs.TensorDataType.INT16:
return view.getInt16(byteOffset, true);
case onnx.TensorProto.DataType.FLOAT|ortFbs.TensorDataType.FLOAT:
return view.getFloat32(byteOffset, true);
case onnx.TensorProto.DataType.INT32|ortFbs.TensorDataType.INT32:
return view.getInt32(byteOffset, true);
case onnx.TensorProto.DataType.UINT32|ortFbs.TensorDataType.UINT32:
return view.getUint32(byteOffset, true);
case onnx.TensorProto.DataType.INT64|ortFbs.TensorDataType.INT64:
return longToNumber(
Long.fromBits(view.getUint32(byteOffset, true), view.getUint32(byteOffset + 4, true), false), type);
case onnx.TensorProto.DataType.DOUBLE|ortFbs.TensorDataType.DOUBLE:
return view.getFloat64(byteOffset, true);
case onnx.TensorProto.DataType.UINT64|ortFbs.TensorDataType.UINT64:
return longToNumber(
Long.fromBits(view.getUint32(byteOffset, true), view.getUint32(byteOffset + 4, true), true), type);
default:
throw new Error(`cannot read from DataView for type ${onnx.TensorProto.DataType[type]}`);
}
} | the_stack |
import {
Directive, ElementRef, Renderer2,
Input, Output, OnInit, EventEmitter, OnChanges, SimpleChanges,
OnDestroy, AfterViewInit
} from '@angular/core';
import { Subscription, fromEvent } from 'rxjs';
import { HelperBlock } from './widgets/helper-block';
import { ResizeHandle } from './widgets/resize-handle';
import { ResizeHandleType } from './models/resize-handle-type';
import { Position, IPosition } from './models/position';
import { Size } from './models/size';
import { IResizeEvent } from './models/resize-event';
@Directive({
selector: '[ngResizable]',
exportAs: 'ngResizable'
})
export class AngularResizableDirective implements OnInit, OnChanges, OnDestroy, AfterViewInit {
private _resizable = true;
private _handles: { [key: string]: ResizeHandle } = {};
private _handleType: string[] = [];
private _handleResizing: ResizeHandle = null;
private _direction: { 'n': boolean, 's': boolean, 'w': boolean, 'e': boolean } = null;
private _directionChanged: { 'n': boolean, 's': boolean, 'w': boolean, 'e': boolean } = null;
private _aspectRatio = 0;
private _containment: HTMLElement = null;
private _origMousePos: Position = null;
/** Original Size and Position */
private _origSize: Size = null;
private _origPos: Position = null;
/** Current Size and Position */
private _currSize: Size = null;
private _currPos: Position = null;
/** Initial Size and Position */
private _initSize: Size = null;
private _initPos: Position = null;
/** Snap to gird */
private _gridSize: IPosition = null;
private _bounding: any = null;
/**
* Bugfix: iFrames, and context unrelated elements block all events, and are unusable
* https://github.com/xieziyu/angular2-draggable/issues/84
*/
private _helperBlock: HelperBlock = null;
private draggingSub: Subscription = null;
private _adjusted = false;
/** Disables the resizable if set to false. */
@Input() set ngResizable(v: any) {
if (v !== undefined && v !== null && v !== '') {
this._resizable = !!v;
this.updateResizable();
}
}
/**
* Which handles can be used for resizing.
* @example
* [rzHandles] = "'n,e,s,w,se,ne,sw,nw'"
* equals to: [rzHandles] = "'all'"
*
* */
@Input() rzHandles: ResizeHandleType = 'e,s,se';
/**
* Whether the element should be constrained to a specific aspect ratio.
* Multiple types supported:
* boolean: When set to true, the element will maintain its original aspect ratio.
* number: Force the element to maintain a specific aspect ratio during resizing.
*/
@Input() rzAspectRatio: boolean | number = false;
/**
* Constrains resizing to within the bounds of the specified element or region.
* Multiple types supported:
* Selector: The resizable element will be contained to the bounding box of the first element found by the selector.
* If no element is found, no containment will be set.
* Element: The resizable element will be contained to the bounding box of this element.
* String: Possible values: "parent".
*/
@Input() rzContainment: string | HTMLElement = null;
/**
* Snaps the resizing element to a grid, every x and y pixels.
* A number for both width and height or an array values like [ x, y ]
*/
@Input() rzGrid: number | number[] = null;
/** The minimum width the resizable should be allowed to resize to. */
@Input() rzMinWidth: number = null;
/** The minimum height the resizable should be allowed to resize to. */
@Input() rzMinHeight: number = null;
/** The maximum width the resizable should be allowed to resize to. */
@Input() rzMaxWidth: number = null;
/** The maximum height the resizable should be allowed to resize to. */
@Input() rzMaxHeight: number = null;
/** Whether to prevent default event */
@Input() preventDefaultEvent = true;
/** emitted when start resizing */
@Output() rzStart = new EventEmitter<IResizeEvent>();
/** emitted when start resizing */
@Output() rzResizing = new EventEmitter<IResizeEvent>();
/** emitted when stop resizing */
@Output() rzStop = new EventEmitter<IResizeEvent>();
constructor(private el: ElementRef<HTMLElement>, private renderer: Renderer2) {
this._helperBlock = new HelperBlock(el.nativeElement, renderer);
}
ngOnChanges(changes: SimpleChanges) {
if (changes['rzHandles'] && !changes['rzHandles'].isFirstChange()) {
this.updateResizable();
}
if (changes['rzAspectRatio'] && !changes['rzAspectRatio'].isFirstChange()) {
this.updateAspectRatio();
}
if (changes['rzContainment'] && !changes['rzContainment'].isFirstChange()) {
this.updateContainment();
}
}
ngOnInit() {
this.updateResizable();
}
ngOnDestroy() {
this.removeHandles();
this._containment = null;
this._helperBlock.dispose();
this._helperBlock = null;
}
ngAfterViewInit() {
const elm = this.el.nativeElement;
this._initSize = Size.getCurrent(elm);
this._initPos = Position.getCurrent(elm);
this._currSize = Size.copy(this._initSize);
this._currPos = Position.copy(this._initPos);
this.updateAspectRatio();
this.updateContainment();
}
/** A method to reset size */
public resetSize() {
this._currSize = Size.copy(this._initSize);
this._currPos = Position.copy(this._initPos);
this.doResize();
}
/** A method to get current status */
public getStatus() {
if (!this._currPos || !this._currSize) {
return null;
}
return {
size: {
width: this._currSize.width,
height: this._currSize.height
},
position: {
top: this._currPos.y,
left: this._currPos.x
}
};
}
private updateResizable() {
const element = this.el.nativeElement;
// clear handles:
this.renderer.removeClass(element, 'ng-resizable');
this.removeHandles();
// create new ones:
if (this._resizable) {
this.renderer.addClass(element, 'ng-resizable');
this.createHandles();
}
}
/** Use it to update aspect */
private updateAspectRatio() {
if (typeof this.rzAspectRatio === 'boolean') {
if (this.rzAspectRatio && this._currSize.height) {
this._aspectRatio = (this._currSize.width / this._currSize.height);
} else {
this._aspectRatio = 0;
}
} else {
let r = Number(this.rzAspectRatio);
this._aspectRatio = isNaN(r) ? 0 : r;
}
}
/** Use it to update containment */
private updateContainment() {
if (!this.rzContainment) {
this._containment = null;
return;
}
if (typeof this.rzContainment === 'string') {
if (this.rzContainment === 'parent') {
this._containment = this.el.nativeElement.parentElement;
} else {
this._containment = document.querySelector<HTMLElement>(this.rzContainment);
}
} else {
this._containment = this.rzContainment;
}
}
/** Use it to create handle divs */
private createHandles() {
if (!this.rzHandles) {
return;
}
let tmpHandleTypes: string[];
if (typeof this.rzHandles === 'string') {
if (this.rzHandles === 'all') {
tmpHandleTypes = ['n', 'e', 's', 'w', 'ne', 'se', 'nw', 'sw'];
} else {
tmpHandleTypes = this.rzHandles.replace(/ /g, '').toLowerCase().split(',');
}
for (let type of tmpHandleTypes) {
// default handle theme: ng-resizable-$type.
let handle = this.createHandleByType(type, `ng-resizable-${type}`);
if (handle) {
this._handleType.push(type);
this._handles[type] = handle;
}
}
} else {
tmpHandleTypes = Object.keys(this.rzHandles);
for (let type of tmpHandleTypes) {
// custom handle theme.
let handle = this.createHandleByType(type, this.rzHandles[type]);
if (handle) {
this._handleType.push(type);
this._handles[type] = handle;
}
}
}
}
/** Use it to create a handle */
private createHandleByType(type: string, css: string): ResizeHandle {
const _el = this.el.nativeElement;
if (!type.match(/^(se|sw|ne|nw|n|e|s|w)$/)) {
console.error('Invalid handle type:', type);
return null;
}
return new ResizeHandle(_el, this.renderer, type, css, this.onMouseDown.bind(this));
}
private removeHandles() {
for (let type of this._handleType) {
this._handles[type].dispose();
}
this._handleType = [];
this._handles = {};
}
onMouseDown(event: MouseEvent | TouchEvent, handle: ResizeHandle) {
// skip right click;
if (event instanceof MouseEvent && event.button === 2) {
return;
}
if (this.preventDefaultEvent) {
// prevent default events
event.stopPropagation();
event.preventDefault();
}
if (!this._handleResizing) {
this._origMousePos = Position.fromEvent(event);
this.startResize(handle);
this.subscribeEvents();
}
}
private subscribeEvents() {
this.draggingSub = fromEvent(document, 'mousemove', { passive: false }).subscribe(event => this.onMouseMove(event as MouseEvent));
this.draggingSub.add(fromEvent(document, 'touchmove', { passive: false }).subscribe(event => this.onMouseMove(event as TouchEvent)));
this.draggingSub.add(fromEvent(document, 'mouseup', { passive: false }).subscribe(() => this.onMouseLeave()));
// fix for issue #164
let isIEOrEdge = /msie\s|trident\//i.test(window.navigator.userAgent);
if (!isIEOrEdge) {
this.draggingSub.add(fromEvent(document, 'mouseleave', { passive: false }).subscribe(() => this.onMouseLeave()));
}
this.draggingSub.add(fromEvent(document, 'touchend', { passive: false }).subscribe(() => this.onMouseLeave()));
this.draggingSub.add(fromEvent(document, 'touchcancel', { passive: false }).subscribe(() => this.onMouseLeave()));
}
private unsubscribeEvents() {
this.draggingSub.unsubscribe();
this.draggingSub = null;
}
onMouseLeave() {
if (this._handleResizing) {
this.stopResize();
this._origMousePos = null;
this.unsubscribeEvents();
}
}
onMouseMove(event: MouseEvent | TouchEvent) {
if (this._handleResizing && this._resizable && this._origMousePos && this._origPos && this._origSize) {
this.resizeTo(Position.fromEvent(event));
this.onResizing();
}
}
private startResize(handle: ResizeHandle) {
const elm = this.el.nativeElement;
this._origSize = Size.getCurrent(elm);
this._origPos = Position.getCurrent(elm); // x: left, y: top
this._currSize = Size.copy(this._origSize);
this._currPos = Position.copy(this._origPos);
if (this._containment) {
this.getBounding();
}
this.getGridSize();
// Add a transparent helper div:
this._helperBlock.add();
this._handleResizing = handle;
this.updateDirection();
this.rzStart.emit(this.getResizingEvent());
}
private stopResize() {
// Remove the helper div:
this._helperBlock.remove();
this.rzStop.emit(this.getResizingEvent());
this._handleResizing = null;
this._direction = null;
this._origSize = null;
this._origPos = null;
if (this._containment) {
this.resetBounding();
}
}
private onResizing() {
this.rzResizing.emit(this.getResizingEvent());
}
private getResizingEvent(): IResizeEvent {
return {
host: this.el.nativeElement,
handle: this._handleResizing ? this._handleResizing.el : null,
size: {
width: this._currSize.width,
height: this._currSize.height
},
position: {
top: this._currPos.y,
left: this._currPos.x
},
direction: { ...this._directionChanged },
};
}
private updateDirection() {
this._direction = {
n: !!this._handleResizing.type.match(/n/),
s: !!this._handleResizing.type.match(/s/),
w: !!this._handleResizing.type.match(/w/),
e: !!this._handleResizing.type.match(/e/)
};
this._directionChanged = { ...this._direction };
// if aspect ration should be preserved:
if (this.rzAspectRatio) {
// if north then west (unless ne)
if (this._directionChanged.n && !this._directionChanged.e) {
this._directionChanged.w = true;
}
// if south then east (unless sw)
if (this._directionChanged.s && !this._directionChanged.w) {
this._directionChanged.e = true;
}
// if east then south (unless ne)
if (this._directionChanged.e && !this._directionChanged.n) {
this._directionChanged.s = true;
}
// if west then south (unless nw)
if (this._directionChanged.w && !this._directionChanged.n) {
this._directionChanged.s = true;
}
}
}
private resizeTo(p: Position) {
p.subtract(this._origMousePos);
const tmpX = Math.round(p.x / this._gridSize.x) * this._gridSize.x;
const tmpY = Math.round(p.y / this._gridSize.y) * this._gridSize.y;
if (this._direction.n) {
// n, ne, nw
this._currPos.y = this._origPos.y + tmpY;
this._currSize.height = this._origSize.height - tmpY;
} else if (this._direction.s) {
// s, se, sw
this._currSize.height = this._origSize.height + tmpY;
}
if (this._direction.e) {
// e, ne, se
this._currSize.width = this._origSize.width + tmpX;
} else if (this._direction.w) {
// w, nw, sw
this._currSize.width = this._origSize.width - tmpX;
this._currPos.x = this._origPos.x + tmpX;
}
this.checkBounds();
this.checkSize();
this.adjustByRatio();
this.doResize();
}
private doResize() {
const container = this.el.nativeElement;
if (!this._direction || this._direction.n || this._direction.s || this._aspectRatio) {
this.renderer.setStyle(container, 'height', this._currSize.height + 'px');
}
if (!this._direction || this._direction.w || this._direction.e || this._aspectRatio) {
this.renderer.setStyle(container, 'width', this._currSize.width + 'px');
}
this.renderer.setStyle(container, 'left', this._currPos.x + 'px');
this.renderer.setStyle(container, 'top', this._currPos.y + 'px');
}
private adjustByRatio() {
if (this._aspectRatio && !this._adjusted) {
if (this._direction.e || this._direction.w) {
const newHeight = Math.floor(this._currSize.width / this._aspectRatio);
if (this._direction.n) {
this._currPos.y += this._currSize.height - newHeight;
}
this._currSize.height = newHeight;
} else {
const newWidth = Math.floor(this._aspectRatio * this._currSize.height);
if (this._direction.n) {
this._currPos.x += this._currSize.width - newWidth;
}
this._currSize.width = newWidth;
}
}
}
private checkBounds() {
if (this._containment) {
const maxWidth = this._bounding.width - this._bounding.pr - this._bounding.deltaL - this._bounding.translateX - this._currPos.x;
const maxHeight = this._bounding.height - this._bounding.pb - this._bounding.deltaT - this._bounding.translateY - this._currPos.y;
if (this._direction.n && (this._currPos.y + this._bounding.translateY < 0)) {
this._currPos.y = -this._bounding.translateY;
this._currSize.height = this._origSize.height + this._origPos.y + this._bounding.translateY;
}
if (this._direction.w && (this._currPos.x + this._bounding.translateX) < 0) {
this._currPos.x = -this._bounding.translateX;
this._currSize.width = this._origSize.width + this._origPos.x + this._bounding.translateX;
}
if (this._currSize.width > maxWidth) {
this._currSize.width = maxWidth;
}
if (this._currSize.height > maxHeight) {
this._currSize.height = maxHeight;
}
/**
* Fix Issue: Additional check for aspect ratio
* https://github.com/xieziyu/angular2-draggable/issues/132
*/
if (this._aspectRatio) {
this._adjusted = false;
if ((this._direction.w || this._direction.e) &&
(this._currSize.width / this._aspectRatio) >= maxHeight) {
const newWidth = Math.floor(maxHeight * this._aspectRatio);
if (this._direction.w) {
this._currPos.x += this._currSize.width - newWidth;
}
this._currSize.width = newWidth;
this._currSize.height = maxHeight;
this._adjusted = true;
}
if ((this._direction.n || this._direction.s) &&
(this._currSize.height * this._aspectRatio) >= maxWidth) {
const newHeight = Math.floor(maxWidth / this._aspectRatio);
if (this._direction.n) {
this._currPos.y += this._currSize.height - newHeight;
}
this._currSize.width = maxWidth;
this._currSize.height = newHeight;
this._adjusted = true;
}
}
}
}
private checkSize() {
const minHeight = !this.rzMinHeight ? 1 : this.rzMinHeight;
const minWidth = !this.rzMinWidth ? 1 : this.rzMinWidth;
if (this._currSize.height < minHeight) {
this._currSize.height = minHeight;
if (this._direction.n) {
this._currPos.y = this._origPos.y + (this._origSize.height - minHeight);
}
}
if (this._currSize.width < minWidth) {
this._currSize.width = minWidth;
if (this._direction.w) {
this._currPos.x = this._origPos.x + (this._origSize.width - minWidth);
}
}
if (this.rzMaxHeight && this._currSize.height > this.rzMaxHeight) {
this._currSize.height = this.rzMaxHeight;
if (this._direction.n) {
this._currPos.y = this._origPos.y + (this._origSize.height - this.rzMaxHeight);
}
}
if (this.rzMaxWidth && this._currSize.width > this.rzMaxWidth) {
this._currSize.width = this.rzMaxWidth;
if (this._direction.w) {
this._currPos.x = this._origPos.x + (this._origSize.width - this.rzMaxWidth);
}
}
}
private getBounding() {
const el = this._containment;
const computed = window.getComputedStyle(el);
if (computed) {
let p = computed.getPropertyValue('position');
const nativeEl = window.getComputedStyle(this.el.nativeElement);
let transforms = nativeEl.getPropertyValue('transform').replace(/[^-\d,]/g, '').split(',');
this._bounding = {};
this._bounding.width = el.clientWidth;
this._bounding.height = el.clientHeight;
this._bounding.pr = parseInt(computed.getPropertyValue('padding-right'), 10);
this._bounding.pb = parseInt(computed.getPropertyValue('padding-bottom'), 10);
this._bounding.deltaL = this.el.nativeElement.offsetLeft - this._currPos.x;
this._bounding.deltaT = this.el.nativeElement.offsetTop - this._currPos.y;
if (transforms.length >= 6) {
this._bounding.translateX = parseInt(transforms[4], 10);
this._bounding.translateY = parseInt(transforms[5], 10);
} else {
this._bounding.translateX = 0;
this._bounding.translateY = 0;
}
this._bounding.position = computed.getPropertyValue('position');
if (p === 'static') {
this.renderer.setStyle(el, 'position', 'relative');
}
}
}
private resetBounding() {
if (this._bounding && this._bounding.position === 'static') {
this.renderer.setStyle(this._containment, 'position', 'relative');
}
this._bounding = null;
}
private getGridSize() {
// set default value:
this._gridSize = { x: 1, y: 1 };
if (this.rzGrid) {
if (typeof this.rzGrid === 'number') {
this._gridSize = { x: this.rzGrid, y: this.rzGrid };
} else if (Array.isArray(this.rzGrid)) {
this._gridSize = { x: this.rzGrid[0], y: this.rzGrid[1] };
}
}
}
} | the_stack |
import { SpreadsheetModel, Spreadsheet, BasicModule } from '../../../src/spreadsheet/index';
import { SpreadsheetHelper } from '../util/spreadsheethelper.spec';
import { defaultData } from '../util/datasource.spec';
import { CellModel, getCell } from '../../../src/index';
Spreadsheet.Inject(BasicModule);
/**
* Formula spec
*/
describe('Spreadsheet formula module ->', () => {
let helper: SpreadsheetHelper = new SpreadsheetHelper('spreadsheet');
let model: SpreadsheetModel;
describe('UI interaction checking ->', () => {
beforeAll((done: Function) => {
model = {
sheets: [
{
ranges: [{ dataSource: defaultData }]
}
]
};
helper.initializeSpreadsheet(model, done);
});
afterAll(() => {
helper.invoke('destroy');
});
// it('Formula edit testing', (done: Function) => {
// let td: HTMLTableCellElement = helper.invoke('getCell', [5, 4]);
// let coords: DOMRect = <DOMRect>td.getBoundingClientRect();
// //Selection update.
// helper.triggerMouseAction('mousedown', { x: coords.x, y: coords.y }, null, td);
// helper.triggerMouseAction('mouseup', { x: coords.x, y: coords.y }, null, td);
// //Start edit.
// helper.triggerMouseAction('dblclick', { x: coords.x, y: coords.y }, null, td);
// let editorElem: HTMLElement = helper.getElementFromSpreadsheet('.e-spreadsheet-edit');
// editorElem.textContent = '=S';
// //key up & down - S key for update internal properties.
// helper.triggerKeyEvent('keydown', 83, null, false, false, editorElem);
// helper.triggerKeyEvent('keyup', 83, null, false, false, editorElem);
// setTimeout(() => {
// let formulaPopupLi: HTMLElement = helper.getElement('#spreadsheet_ac_popup li');
// expect(formulaPopupLi).not.toBeNull();
// expect(formulaPopupLi.textContent).toBe('SUM');
// setTimeout(() => {
// helper.triggerKeyEvent('keydown', 9, null, false, false, editorElem); //Tab key
// setTimeout(() => {
// expect(editorElem.textContent).toBe('=SUM(');
// editorElem.textContent = editorElem.textContent + '10,20';
// //key down - S key for update internal properties.
// helper.triggerKeyEvent('keydown', 48, null, false, false, editorElem);
// //Enter key
// helper.triggerKeyEvent('keydown', 13, null, false, false, editorElem);
// helper.invoke('getData', ['Sheet1!E6']).then((values: Map<string, CellModel>) => {
// expect(values.get('E6').formula).toEqual('=SUM(10,20)');
// expect(values.get('E6').value).toEqual('30');
// done();
// });
// }, 10);
// }, 10);
// }, 110);
// });
it('Int formula', (done: Function) => {
helper.edit('D2', '11.5');
helper.edit('J1', '=int(D2)');
expect(helper.invoke('getCell', [0, 9]).textContent).toBe('11');
expect(JSON.stringify(helper.getInstance().sheets[0].rows[0].cells[9])).toBe('{"value":11,"formula":"=int(D2)"}');
done();
});
it('Today formula', (done: Function) => {
helper.edit('J2', '=today()');
const cell: CellModel = helper.getInstance().sheets[0].rows[1].cells[9];
expect(cell.format).toBe('mm-dd-yyyy');
expect(cell.formula).toBe('=today()');
done();
});
it('Sum product formula', (done: Function) => {
helper.edit('J3', '=sumproduct(D2:D5,E2:E5)');
expect(helper.invoke('getCell', [2, 9]).textContent).toBe('1430');
expect(JSON.stringify(helper.getInstance().sheets[0].rows[2].cells[9])).toBe('{"value":1430,"formula":"=sumproduct(D2:D5,E2:E5)"}');
done();
});
it('Roundup formula', (done: Function) => {
helper.edit('J4', '=roundup(D2, 0)');
expect(helper.invoke('getCell', [3, 9]).textContent).toBe('12');
expect(JSON.stringify(helper.getInstance().sheets[0].rows[3].cells[9])).toBe('{"value":"12","formula":"=roundup(D2, 0)"}');
done();
});
it('Sort formula', (done: Function) => {
helper.edit('K1', '=sort(A1:A4)');
expect(helper.invoke('getCell', [0, 10]).textContent).toBe('Casual Shoes');
expect(helper.invoke('getCell', [1, 10]).textContent).toBe('Formal Shoes');
expect(JSON.stringify(helper.getInstance().sheets[0].rows[0].cells[10])).toBe('{"value":"Casual Shoes","formula":"=sort(A1:A4)"}');
expect(helper.getInstance().sheets[0].rows[2].cells[10].value).toBe('Item Name')
expect(helper.getInstance().sheets[0].rows[3].cells[10].value).toBe('Sports Shoes')
done();
});
it('Text formula', (done: Function) => {
helper.edit('J5', '=Text(D2, "0%")');
expect(helper.invoke('getCell', [4, 9]).textContent).toBe('1150%');
expect(helper.getInstance().sheets[0].rows[4].cells[9].value).toBe("11.5");
done();
});
it('Lookup formula', (done: Function) => {
helper.edit('J6', '=LOOKUP(20,D2:D5,E2:E5)');
// expect(helper.invoke('getCell', [5, 9]).textContent).toBe('15'); // This case need to be fixed
// expect(JSON.stringify(helper.getInstance().sheets[0].rows[5].cells[9])).toBe('{"value":15,"formula":"=LOOKUP(20,D2:D5,E2:E5)"}');
done();
});
it('Slope formula', (done: Function) => {
helper.edit('J7', '=slope(D2:D5,E2:E5)');
expect(helper.invoke('getCell', [6, 9]).textContent).toBe('0.142105');
expect(JSON.stringify(helper.getInstance().sheets[0].rows[6].cells[9])).toBe('{"value":"0.142105","formula":"=slope(D2:D5,E2:E5)"}');
done();
});
it('Intercept formula', (done: Function) => {
helper.edit('J8', '=INTERCEPT(D2:D5,E2:E5)');
expect(helper.invoke('getCell', [7, 9]).textContent).toBe('13.60526');
expect(JSON.stringify(helper.getInstance().sheets[0].rows[7].cells[9])).toBe('{"value":"13.60526","formula":"=INTERCEPT(D2:D5,E2:E5)"}');
done();
});
it('Ln formula', (done: Function) => {
helper.edit('J9', '=ln(D2)');
expect(helper.invoke('getCell', [8, 9]).textContent).toBe('2.442347');
expect(JSON.stringify(helper.getInstance().sheets[0].rows[8].cells[9])).toBe('{"value":"2.442347","formula":"=ln(D2)"}');
done();
});
it('IsNumber formula', (done: Function) => {
helper.edit('J10', '=isnumber(D2)');
expect(helper.invoke('getCell', [9, 9]).textContent).toBe('TRUE');
expect(JSON.stringify(helper.getInstance().sheets[0].rows[9].cells[9])).toBe('{"value":true,"formula":"=isnumber(D2)"}');
helper.edit('J10', '=isnumber(A1)');
expect(helper.invoke('getCell', [9, 9]).textContent).toBe('FALSE');
expect(JSON.stringify(helper.getInstance().sheets[0].rows[9].cells[9])).toBe('{"value":false,"formula":"=isnumber(A1)"}');
done();
});
it('Round formula', (done: Function) => {
helper.edit('J11', '=round(D2, 0)');
expect(helper.invoke('getCell', [10, 9]).textContent).toBe('12');
expect(JSON.stringify(helper.getInstance().sheets[0].rows[10].cells[9])).toBe('{"value":"12","formula":"=round(D2, 0)"}');
done();
});
it('Power formula', (done: Function) => {
helper.edit('J12', '=power(G3,G4)');
expect(helper.invoke('getCell', [11, 9]).textContent).toBe('78125');
expect(JSON.stringify(helper.getInstance().sheets[0].rows[11].cells[9])).toBe('{"value":"78125","formula":"=power(G3,G4)"}');
done();
});
it('Log formula', (done: Function) => {
helper.edit('J13', '=log(D3,E3)');
expect(helper.invoke('getCell', [12, 9]).textContent).toBe('0.880788');
expect(JSON.stringify(helper.getInstance().sheets[0].rows[12].cells[9])).toBe('{"value":"0.880788","formula":"=log(D3,E3)"}');
done();
});
it('Trunc formula', (done: Function) => {
helper.edit('J14', '=trunc(D2)');
expect(helper.invoke('getCell', [13, 9]).textContent).toBe('11');
expect(JSON.stringify(helper.getInstance().sheets[0].rows[13].cells[9])).toBe('{"value":"11","formula":"=trunc(D2)"}');
done();
});
it('Exp formula', (done: Function) => {
helper.edit('J15', '=exp(D4)');
expect(helper.invoke('getCell', [14, 9]).textContent).toBe('485165195');
expect(JSON.stringify(helper.getInstance().sheets[0].rows[14].cells[9])).toBe('{"value":"485165195","formula":"=exp(D4)"}');
done();
});
it('Geomean formula', (done: Function) => {
helper.edit('J16', '=geomean(D2:D6)');
expect(helper.invoke('getCell', [15, 9]).textContent).toBe('18.33133');
expect(JSON.stringify(helper.getInstance().sheets[0].rows[15].cells[9])).toBe('{"value":"18.33133","formula":"=geomean(D2:D6)"}');
done();
});
it('Dependent cell update', (done: Function) => {
helper.edit('D6', '40');
expect(helper.invoke('getCell', [15, 9]).textContent).toBe('19.41699');
expect(JSON.stringify(helper.getInstance().sheets[0].rows[15].cells[9])).toBe('{"value":"19.41699","formula":"=geomean(D2:D6)"}');
done();
});
it('Compute expression', (done: Function) => {
expect(helper.invoke('computeExpression', ['=SUM(E2,E5)'])).toBe(40);
done();
});
});
describe('CR-Issues ->', () => {
describe('I311951, I309076, FB24295, FB23944 ->', () => {
beforeAll((done: Function) => {
helper.initializeSpreadsheet({ sheets: [{ rows: [{ cells: [{ value: '25' }] }] }] }, done);
});
afterAll(() => {
helper.invoke('destroy');
});
it('Formula with percentage not working and formula parsing issue', (done: Function) => {
helper.edit('A2', '=A1*5%');
const inst: Spreadsheet = helper.getInstance();
expect(inst.sheets[0].rows[1].cells[0].formula).toEqual('=A1*5%');
expect(inst.sheets[0].rows[1].cells[0].value).toEqual('1.25');
expect(inst.getCell(1, 0).textContent).toEqual('1.25');
helper.invoke('selectRange', ['A2']);
setTimeout(() => {
expect(helper.getElement('#' + helper.id + '_formula_input').value).toEqual('=A1*5%');
helper.invoke('selectRange', ['A3']);
setTimeout(() => {
helper.edit('A3', '=425/25*-1');
expect(inst.sheets[0].rows[2].cells[0].formula).toEqual('=425/25*-1');
expect(inst.sheets[0].rows[2].cells[0].value).toEqual('-17');
expect(inst.getCell(2, 0).textContent).toEqual('-17');
setTimeout((): void => {
expect(helper.getElement('#' + helper.id + '_formula_input').value).toEqual('=425/25*-1');
done();
});
});
});
});
it('Count value is not calculated properly in aggregate when selected range contains zero value', (done: Function) => {
helper.edit('B1', '0');
helper.invoke('selectRange', ['A1:B1']);
helper.click('#' + helper.id + '_aggregate');
expect(helper.getElement('#' + helper.id + '_aggregate-popup ul li').textContent).toBe('Count: 2');
done();
});
it('Formula popup not displayed on cell in the bottom of the sheet', (done: Function) => {
const spreadsheet: Spreadsheet = helper.getInstance();
spreadsheet.selectRange('C21');
spreadsheet.startEdit();
const editElem: HTMLElement = helper.getCellEditorElement();
editElem.textContent = '=s';
helper.triggerKeyEvent('keyup', 83, null, null, null, editElem);
setTimeout(()=>{
const popup: Element = helper.getElement('#' + helper.id + '_ac_popup');
expect(Math.abs(popup.getBoundingClientRect().bottom - editElem.getBoundingClientRect().top)).toBeLessThan(3);
setTimeout(()=>{
done();
}, 100);
});
});
});
describe('I261427 ->', () => {
beforeEach((done: Function) => {
helper.initializeSpreadsheet(
{ sheets: [{ rows: [{ cells: [{ value: '1' }] }] }, { rows: [{ cells: [{ value: '2' }] }] }, { rows: [{ cells: [{ formula:
'=Sheet1!A1+Sheet2!A1' }] }] }], activeSheetIndex: 2 }, done);
});
afterEach(() => {
helper.invoke('destroy');
});
it('Cross tab formula issue', (done: Function) => {
const target: HTMLElement = helper.getElement().querySelectorAll('.e-sheet-tab .e-toolbar-item')[1];
const spreadsheet: Spreadsheet = helper.getInstance();
expect(spreadsheet.sheets[2].rows[0].cells[0].formula).toEqual('=Sheet1!A1+Sheet2!A1');
expect(spreadsheet.sheets[2].rows[0].cells[0].value).toEqual('3');
helper.triggerMouseAction('contextmenu', { x: target.getBoundingClientRect().left + 20, y:
target.getBoundingClientRect().top + 10 }, null, target);
setTimeout(() => {
helper.getElement('#' + helper.id + '_cmenu_delete_sheet').click();
setTimeout(() => {
helper.getElement('.e-footer-content .e-btn.e-primary').click();
setTimeout(() => {
expect(spreadsheet.sheets[1].rows[0].cells[0].formula).toEqual('=SHEET1!A1+#REF!A1');
expect(spreadsheet.sheets[1].rows[0].cells[0].value).toEqual('#REF!');
done();
}, 10);
});
});
});
});
describe('I288646, I296410, I305593, I314883 ->', () => {
const model: SpreadsheetModel = { sheets: [{ rows: [{ cells: [{ value: '10' }, { value: '20' }, { index: 8, formula: '=H1' }] }, { cells: [{ formula: '=ROUNDUP(10.6)' },
{ index: 4, formula: '=INT(10.2)' }, { formula: '=SUMPRODUCT(A1:B1)' }, { index: 8, formula: '=H2' }] }] }] };
beforeAll((done: Function) => {
helper.initializeSpreadsheet(model, done);
});
afterAll(() => {
helper.invoke('destroy');
});
it('Include the unsupported formula (ROUNDUP, INT, SUMPRODUCT)', (done: Function) => {
const spreadsheet: Spreadsheet = helper.getInstance();
expect(spreadsheet.sheets[0].rows[1].cells[0].formula).toBe('=ROUNDUP(10.6)');
expect(spreadsheet.sheets[0].rows[1].cells[0].value.toString()).toBe('11');
expect(helper.invoke('getCell', [1, 0]).textContent).toBe('11');
expect(spreadsheet.sheets[0].rows[1].cells[4].formula).toBe('=INT(10.2)');
expect(spreadsheet.sheets[0].rows[1].cells[4].value.toString()).toBe('10');
expect(helper.invoke('getCell', [1, 4]).textContent).toBe('10');
expect(spreadsheet.sheets[0].rows[1].cells[5].formula).toBe('=SUMPRODUCT(A1:B1)');
expect(spreadsheet.sheets[0].rows[1].cells[5].value.toString()).toBe('30');
expect(helper.invoke('getCell', [1, 5]).textContent).toBe('30');
done();
});
it('Circular reference dialog opens multiple times when deleting column', (done: Function) => {
helper.setAnimationToNone(`#${helper.id}_contextmenu`);
helper.openAndClickCMenuItem(0, 5, [7], null, true);
setTimeout(() => {
expect(document.querySelectorAll('.e-dialog').length).toBe(0);
done();
});
});
// it('Formula dependent cell not updated after destroy', (done: Function) => {
// helper.edit('C1', 'Test');
// setTimeout(() => {
// helper.invoke('destroy');
// new Spreadsheet(model, '#' + helper.id);
// setTimeout(() => {
// setTimeout(() => {
// expect(helper.getInstance().sheets[0].rows[0].cells[2]).toBeUndefined();
// expect(helper.invoke('getCell', [0, 2]).textContent).toBe('');
// helper.edit('B1', '30');
// expect(helper.invoke('getCell', [1, 5]).textContent).toBe('40');
// expect(helper.getInstance().sheets[0].rows[1].cells[5].value).toBe(40);
// done();
// });
// });
// });
// });
});
describe('I312700 ->', () => {
beforeEach((done: Function) => {
helper.initializeSpreadsheet(
{ sheets: [{ rows: [{ cells: [{ formula: '=COUNTIF(AR1:AT1,"=10")' }, { index: 4, formula: '=SUMIF(AR1:AT1,"=10")' },
{ index: 43, value: '10' }, { value: '5' }, { value: '10' }] }] }] }, done);
});
afterEach(() => {
helper.invoke('destroy');
});
it('Improve the formulas with the range greater than AA and countif, countifs, sumif, sumifs formula with this ranges', (done: Function) => {
const spreadsheet: Spreadsheet = helper.getInstance();
expect(spreadsheet.sheets[0].rows[0].cells[0].formula).toBe('=COUNTIF(AR1:AT1,"=10")');
expect(spreadsheet.sheets[0].rows[0].cells[0].value.toString()).toBe('2');
expect(helper.invoke('getCell', [0, 0]).textContent).toBe('2');
expect(spreadsheet.sheets[0].rows[0].cells[4].formula).toBe('=SUMIF(AR1:AT1,"=10")');
expect(spreadsheet.sheets[0].rows[0].cells[4].value.toString()).toBe('20');
expect(helper.invoke('getCell', [0, 4]).textContent).toBe('20');
done();
});
});
describe('I296802, F162534 ->', () => {
beforeEach((done: Function) => {
helper.initializeSpreadsheet({ sheets: [{ rows: [{ cells: [{ index: 3, value: '100' }, { value: '50' }, { formula: '=D1+E1' }] }],
selectedRange: 'D1:D1' }] }, done);
});
afterEach(() => {
helper.invoke('destroy');
});
it('formula dependency not updated issue', (done: Function) => {
const spreadsheet: Spreadsheet = helper.getInstance();
expect(spreadsheet.sheets[0].rows[0].cells[5].value).toEqual('150');
helper.invoke('insertColumn', [4]);
setTimeout((): void => {
expect(spreadsheet.sheets[0].rows[0].cells[6].formula).toEqual('=D1+F1');
expect(spreadsheet.sheets[0].rows[0].cells[6].value).toEqual('150');
helper.edit('F1', '100');
expect(spreadsheet.sheets[0].rows[0].cells[6].value).toEqual('200');
expect(helper.invoke('getCell', [0, 6]).textContent).toEqual('200');
setTimeout((): void => {
done();
}, 10);
});
});
});
describe('I305406, I280608, I296710, I257045, I274819, I282974, I288646 ->', () => {
beforeEach((done: Function) => {
helper.initializeSpreadsheet({}, done);
});
afterEach(() => {
helper.invoke('destroy');
});
it('Formula selection support while editing the formula range, Highlight reference selection in formula and formula reference selection issue', (done: Function) => {
const spreadsheet: Spreadsheet = helper.getInstance();
helper.invoke('startEdit');
setTimeout((): void => {
const editor: HTMLElement = helper.getElement('#' +helper.id + '_edit');
editor.textContent = '=SUM(';
(spreadsheet as any).editModule.editCellData.value = '=SUM(';
let cell: HTMLElement = helper.invoke('getCell', [0, 1]);
helper.triggerMouseAction(
'mousedown', { x: cell.getBoundingClientRect().left + 1, y: cell.getBoundingClientRect().top + 1 }, null,
cell);
helper.triggerMouseAction(
'mouseup', { x: cell.getBoundingClientRect().left + 1, y: cell.getBoundingClientRect().top + 1 }, document,
cell);
setTimeout((): void => {
expect(editor.textContent).toEqual('=SUM(B1');
editor.textContent = '=SUM(A3';
editor.focus();
helper.triggerKeyEvent('keydown', 51, null, null, null, editor);
helper.triggerKeyEvent('keyup', 51, null, null, null, editor);
cell = helper.invoke('getCell', [2, 0]);
expect(cell.classList).toContain('e-formularef-selection');
expect(cell.classList).toContain('e-vborderright');
expect(cell.classList).toContain('e-vborderbottom');
done();
});
});
});
});
describe('I293654, I296802, I307653, I264424, I298789, I300031 ->', () => {
beforeEach((done: Function) => {
helper.initializeSpreadsheet({ sheets: [{ name: 'Cover', rows: [{ index: 5, height: 30, cells: [{ colSpan: 8, formula: '=Lookup!B1', style:
{ fontWeight: 'bold', textAlign: 'center', verticalAlign: 'middle' } }] }, { index: 7, cells: [{ colSpan: 6, value:
'Company No.12345678' }] }, { cells: [{ colSpan: 4, formula: '=IF(Lookup!B3="ABRIDGED",IF(IF(Lookup!B4="",FALSE,TRUE),"Directors'
+ "'" + '","Director' + "'" + 's")&" Report and "&IF(Lookup!B5="Audited","Audited","Unaudited")&" Abridged Accounts",IF(IF(Lookup!B4="",FALSE,TRUE),"Directors'
+ "'" + '","Director' + "'" + 's")&" Report and "&IF(Lookup!B5="Audited","Audited","Unaudited")&" Accounts")' }] }, { cells: [{ formula:
'=TEXT(Lookup!B6,"dd MMMM yyyy")' }, { index: 3, value: '37087.58' }, { value: '38767.36' }, { wrap: true, formula:
'=IF(OR(AND(ABS(D10)>ABS(E10),D10<0),AND(ABS(D10)<=ABS(E10),E10<0)),-1*(IF(D10=0,((ABS(E10)-ABS(D10))/1)*100,((ABS(E10)-ABS(D10))/ABS(D10))*100)),IF(D10=0,((ABS(E10)-ABS(D10))/1)*100,((ABS(E10)-ABS(D10))/ABS(D10))*100))'
}] }, { cells: [{ formula: '=1-0/0' }] }, { cells: [{ formula: '=(10-3)/1' }] }] }, { name: 'Lookup', rows: [{ cells: [{ value: 'CLIENTNAME' },
{ value: 'Example Limited Company' }] }, { cells: [{ value: 'REGISTRATIONNUMBER' }, { value: '12345678' }] }, { cells: [{ value: 'ACCOUNT' }] }, { cells: [{ value: 'DIRECTOR2' },
{ value: 'abc' }] }, { cells: [{ value: 'AUDITED' }, { value: 'Audited' }] }, { cells: [{ value: 'PERIODEND' }, { value: '9/1/2019' }] }] }] }, done);
});
afterEach(() => {
helper.invoke('destroy');
});
it('Opening the attached pre formatted excel file it is giving errors in the last two rows though the formula is correct and date format is also correct', (done: Function) => {
const spreadsheet: Spreadsheet = helper.getInstance();
expect(spreadsheet.sheets[0].rows[5].cells[0].value).toBe('Example Limited Company');
expect(helper.invoke('getCell', [5, 0]).textContent).toBe('Example Limited Company');
expect(spreadsheet.sheets[0].rows[8].cells[0].value).toBe("Directors' Report and Audited Accounts");
expect(helper.invoke('getCell', [8, 0]).textContent).toBe("Directors' Report and Audited Accounts");
expect(spreadsheet.sheets[0].rows[9].cells[0].value).toBe('September 1, 2019');
expect(helper.invoke('getCell', [9, 0]).textContent).toBe('September 1, 2019');
expect(spreadsheet.sheets[0].rows[9].cells[5].value).toBe('4.529225');
expect(helper.invoke('getCell', [9, 5]).textContent).toBe('4.529225');
expect(spreadsheet.sheets[0].rows[10].cells[0].value).toBe('#DIV/0!');
expect(helper.invoke('getCell', [10, 0]).textContent).toBe('#DIV/0!');
expect(spreadsheet.sheets[0].rows[11].cells[0].value).toBe('7');
expect(helper.invoke('getCell', [11, 0]).textContent).toBe('7');
done();
});
});
describe('FB23112 ->', () => {
beforeAll((done: Function) => {
helper.initializeSpreadsheet({ sheets: [{ ranges: [{ dataSource: defaultData }] }] }, done);
});
afterAll(() => {
helper.invoke('destroy');
});
it('Match function is not working for cell reference', (done: Function) => {
helper.edit('I2', 'Running Shoes');
helper.edit('I3', '=Match(I2, A2:A11)');
expect(helper.invoke('getCell', [2, 8]).textContent).toBe('7');
expect(helper.getInstance().sheets[0].rows[2].cells[8].value).toBe(7);
done();
});
});
describe('fb23644, fb23650 ->', () => {
beforeAll((done: Function) => {
helper.initializeSpreadsheet(
{ sheets: [{ rows: [{ cells: [{ value: '1' }] }, { cells: [{ value: '2' }] }, { cells: [{ value: '3' }] }, { cells:
[{ value: '5' }] }, { cells: [{ formula: '=SUM(A1:A4)' }] }], selectedRange: 'A4' }] }, done);
});
afterAll(() => {
helper.invoke('destroy');
});
it('Dependent cells not updated for loaded JSON using openFromJson method', (done: Function) => {
const spreadsheet: Spreadsheet = helper.getInstance();
expect(spreadsheet.sheets[0].rows[4].cells[0].value.toString()).toEqual('11');
helper.invoke('refresh');
setTimeout((): void => {
helper.edit('A4', '10');
expect(spreadsheet.sheets[0].rows[4].cells[0].value.toString()).toEqual('16');
setTimeout((): void => {
helper.invoke('selectRange', ['A5:A5']);
done();
});
});
});
it('Cell with inserted function is not properly copied and pasted (Formula range reference not proper on pasted cell)', (done: Function) => {
const spreadsheet: Spreadsheet = helper.getInstance();
expect(spreadsheet.sheets[0].rows[4].cells[1]).toBeUndefined();
helper.invoke('copy').then((): void => {
helper.invoke('paste', ['B5']);
setTimeout((): void => {
expect(spreadsheet.sheets[0].rows[4].cells[1].value.toString()).toEqual('0');
expect(spreadsheet.sheets[0].rows[4].cells[1].formula).toEqual('=SUM(B1:B4)');
expect(helper.invoke('getCell', [4, 1]).textContent).toEqual('0');
helper.invoke('paste', ['C4']);
setTimeout((): void => {
expect(spreadsheet.sheets[0].rows[3].cells[2].value).toEqual('#REF!');
expect(spreadsheet.sheets[0].rows[3].cells[2].formula).toEqual('=SUM(#REF!)');
expect(helper.invoke('getCell', [3, 2]).textContent).toEqual('#REF!');
done();
});
});
});
});
});
describe('fb24848 ->', () => {
beforeAll((done: Function) => {
helper.initializeSpreadsheet(
{ sheets: [{ rows: [{ cells: [{ value: '1' }, { index: 4, value: 'Tom' }] }, { cells: [{ value: '2' }, { index: 4,
value: 'John' }] }, { cells: [{ value: '5' }, { index: 4, value: 'Jane' }] }, { index: 4, cells: [{ formula:
'=INDEX(A1:A3,MATCH("Tom",E1:E3,0),1)' }, { index: 4, formula: '=INDEX(A1:A3,SUM(A1:A1),1)' }] }] }] }, done);
});
afterAll(() => {
helper.invoke('destroy');
});
it('"#REF!" error when combining functions with each over', (done: Function) => {
const spreadsheet: Spreadsheet = helper.getInstance();
expect(spreadsheet.sheets[0].rows[4].cells[0].value).toEqual('1');
expect(helper.invoke('getCell', [4, 0]).textContent).toEqual('1');
expect(spreadsheet.sheets[0].rows[4].cells[4].value).toEqual('1');
expect(helper.invoke('getCell', [4, 4]).textContent).toEqual('1');
helper.edit('A1', '3');
setTimeout((): void => {
expect(spreadsheet.sheets[0].rows[4].cells[0].value.toString()).toEqual('3');
expect(helper.invoke('getCell', [4, 0]).textContent).toEqual('3');
expect(spreadsheet.sheets[0].rows[4].cells[4].value.toString()).toEqual('5');
expect(helper.invoke('getCell', [4, 4]).textContent).toEqual('5');
done();
});
});
});
describe('I325908 ->', () => {
beforeAll((done: Function) => {
helper.initializeSpreadsheet(
{ sheets: [{ rows: [{ cells: [{ value: '0' }, { index: 4, value: '10' }] }, { cells: [{ formula:
'=IF($A1<>0,$A1*E$1,"0,00")' }] }] }] }, done);
});
afterAll(() => {
helper.invoke('destroy');
});
it('IF formula false value with "," inside scenario', (done: Function) => {
const spreadsheet: Spreadsheet = helper.getInstance();
expect(spreadsheet.sheets[0].rows[1].cells[0].value).toEqual('0,00');
expect(helper.invoke('getCell', [1, 0]).textContent).toEqual('0,00');
helper.edit('A1', '10');
setTimeout((): void => {
expect(spreadsheet.sheets[0].rows[1].cells[0].value).toEqual('100');
expect(helper.invoke('getCell', [1, 0]).textContent).toEqual('100');
done();
});
});
});
describe('SF-362961 ->', () => {
let spreadsheet: any;
beforeAll((done: Function) => {
helper.initializeSpreadsheet(
{ sheets: [{ name: 'Report Output', rows: [{ index: 1, cells:
[{ formula: '=IFS(NonOtherUQE!A1=0,"",NonOtherUQE!A1="Others","",TRUE,NonOtherUQE!A1)' }, { index: 3, formula: '=IFS(ClientData!E1=0,"",ClientData!E1="Others","",TRUE,ClientData!E1)' },
{ formula: '=IF($D2="","",IFERROR(IF(SUMIF(ClientData!D1:D3,$A4,ClientData!C1:C3)=0,"0",SUMIF(ClientData!D1:D3,$A4,ClientData!C1:C3)),"0"))' }] }] },
{ name: 'ClientData', rows: [{ cells: [{ index: 2, value: '100' }, { value: 'EY Adj 1' }, { formula: '=UNIQUE(ClientData!D1:D3)' }] },
{ cells: [{ value: 'EY Adj 2' }, { value: '1,000.00' }, { value: '150' }, { value: 'EY Adj 2' }] }, { cells: [{ index: 1, value: '-2,000.00' }, { value: '200' }, { value: 'Others' }] },
{ index: 5, cells: [{ index: 6, formula: '=C6' }] }, { cells: [{ index: 6, formula: '=D5' }] }, { index: 100, cells: [{ formula: '=SUM(C1:C2)' }] }] },
{ name: 'NonOtherUQE' }] }, done);
});
afterAll(() => {
helper.invoke('destroy');
});
it('Inserting row not properly updated the cell references in other sheets', (done: Function) => {
spreadsheet = helper.getInstance();
expect(spreadsheet.sheets[0].rows[1].cells[3].value).toEqual('EY Adj 1');
expect(spreadsheet.sheets[0].rows[1].cells[4].value).toEqual('0');
spreadsheet.activeSheetIndex = 1;
spreadsheet.dataBind();
setTimeout((): void => {
expect(spreadsheet.sheets[0].rows[1].cells[3].value).toEqual('EY Adj 1');
expect(spreadsheet.sheets[0].rows[1].cells[4].value).toEqual('0');
helper.invoke('insertRow');
setTimeout((): void => {
expect(spreadsheet.sheets[0].rows[1].cells[3].formula).toEqual('=IFS(ClientData!E2=0,"",ClientData!E2="Others","",TRUE,ClientData!E2)');
expect(spreadsheet.sheets[0].rows[1].cells[3].value).toBeNull();
expect(spreadsheet.sheets[0].rows[1].cells[4].formula).toEqual('=IF($D2="","",IFERROR(IF(SUMIF(ClientData!D2:D4,$A4,ClientData!C2:C4)=0,"0",SUMIF(ClientData!D2:D4,$A4,ClientData!C2:C4)),"0"))');
expect(spreadsheet.sheets[0].rows[1].cells[4].value).toBeNull();
done();
});
});
});
it('saveAsJson formula calculation for not calculated formula cell and #value error checking', (done: Function) => {
expect(spreadsheet.sheets[0].rows[1].cells[0].value).toEqual('');
expect(spreadsheet.sheets[1].rows[101].cells[0].value).toBeNull();
// saveAsJson operation codes are used to replicate the case, since CI will not compatible with Worker task so invoking getStringifyObject method directly.
const skipProps: string[] = ['dataSource', 'startCell', 'query', 'showFieldAsHeader'];
for (let i: number = 0, sheetCount: number = spreadsheet.sheets.length; i < sheetCount; i++) {
spreadsheet.workbookSaveModule.getStringifyObject(spreadsheet.sheets[i], skipProps, i);
}
expect(spreadsheet.sheets[0].rows[1].cells[0].value).toEqual('');
expect(spreadsheet.sheets[1].rows[101].cells[0].value).toEqual(250);
done();
});
it('External copy/paste and SUMIF formula calculation value is not proper', (done: Function) => {
expect(getCell(4, 2, spreadsheet.sheets[1])).toBeNull();
helper.invoke('updateCell', [{ formula: '=SUMIF(ClientData!$D$2:$D$4,$A3,ClientData!$B$2:$B$4)' }, 'C5']);
expect(spreadsheet.sheets[1].rows[4].cells[2].value).toEqual(1000);
done();
});
it('Referenced cells are not updated while updating the UNIQUE formula value', (done: Function) => {
expect(getCell(5, 2, spreadsheet.sheets[1])).toBeNull();
expect(spreadsheet.sheets[1].rows[6].cells[6].formula).toEqual('=C7');
expect(spreadsheet.sheets[1].rows[6].cells[6].value).toEqual('0');
expect(spreadsheet.sheets[1].rows[7].cells[6].formula).toEqual('=D6');
expect(spreadsheet.sheets[1].rows[7].cells[6].value).toEqual('0');
helper.invoke('updateCell', [{ formula: '=UNIQUE(C2:D4)' }, 'C6']);
expect(spreadsheet.sheets[1].rows[5].cells[2].value).toEqual('100');
expect(spreadsheet.sheets[1].rows[6].cells[6].value).toEqual('150');
expect(spreadsheet.sheets[1].rows[7].cells[6].value).toEqual('EY Adj 1');
done();
});
});
describe('EJ2-57075 ->', () => {
beforeAll((done: Function) => {
helper.initializeSpreadsheet(
{ sheets: [{ rows: [
{
cells: [
{ value: '10' },
{ value: '10' },
{ formula: '=SUMIF(A1:A2,"10",B1)' },
],
},
{ cells: [{ value: '10' }, { value: '10' }] },
], }] }, done);
});
afterAll(() => {
helper.invoke('destroy');
});
it('SUMIF calculation while criteriaRange is greater than Sum range', (done: Function) => {
expect(helper.getInstance().sheets[0].rows[0].cells[2].value.toString()).toEqual('20');
done();
});
});
describe('EJ2-57684 ->', () => {
beforeAll((done: Function) => {
helper.initializeSpreadsheet(
{
sheets: [{
rows: [
{
cells: [
{ value: '10', format: '#,##0.00' },
{ value: '10', format: '#,##0.00' },
],
},
],
}],
}, done);
});
afterAll(() => {
helper.invoke('destroy');
});
it('Aggregates not calculated properly for custom number formatted values', (done: Function) => {
helper.invoke('selectRange', ['A1:B1']);
expect(helper.getElement('#' + helper.id + '_aggregate').textContent).toBe('Sum: 20.00')
done();
});
});
describe('EJ2-58254, EJ2-59388 ->', () => {
beforeAll((done: Function) => {
helper.initializeSpreadsheet(
{
sheets: [
{
ranges: [{ dataSource: defaultData }]
}
]
}, done);
});
afterAll(() => {
helper.invoke('destroy');
});
it('Aggregates not calculated properly for date formatted values', (done: Function) => {
helper.invoke('selectRange', ['B2:B3']);
expect(helper.getElement('#' + helper.id + '_aggregate').textContent).toBe('Sum: 7/27/2128');
helper.invoke('selectRange', ['C2:C3']);
expect(helper.getElement('#' + helper.id + '_aggregate').textContent).toBe('Sum: 5:31:12 PM');
helper.invoke('selectRange', ['A2:A3']);
expect(helper.getElement('#' + helper.id + '_aggregate').textContent).toBe('Count: 2');
helper.invoke('selectRange', ['D2:D3']);
expect(helper.getElement('#' + helper.id + '_aggregate').textContent).toBe('Sum: 30');
helper.invoke('selectRange', ['A2:B5']);
expect(helper.getElement('#' + helper.id + '_aggregate').textContent).toBe('Sum: 167296');
helper.invoke('selectRange', ['B2:B3']);
helper.getElement('#' + helper.id + '_aggregate').click();
let Element:NodeListOf<HTMLElement> = document.querySelectorAll("#spreadsheet_aggregate-popup li");
expect(Element[0].textContent).toBe('Count: 2');
expect(Element[2].textContent).toBe('Avg: 4/13/2014');
expect(Element[3].textContent).toBe('Min: 2/14/2014');
expect(Element[4].textContent).toBe('Max: 6/11/2014');
Element[0].click();
expect(helper.getElement('#' + helper.id + '_aggregate').textContent).toBe('Count: 2');
done();
});
it('When using the dollar formula with a single argument, an error occurs', (done: Function) => {
helper.edit('I2', '=DOLLAR(H2)');
expect(helper.invoke('getCell', [1, 8]).textContent).toBe('$10.00');
expect(JSON.stringify(helper.getInstance().sheets[0].rows[1].cells[8].value)).toBe('"$10.00"');
helper.edit('I2', '=DOLLAR(H2,3)');
expect(helper.invoke('getCell', [1, 8]).textContent).toBe('$10.000');
expect(JSON.stringify(helper.getInstance().sheets[0].rows[1].cells[8].value)).toBe('"$10.000"');
done();
});
});
});
}); | the_stack |
import React from 'react';
import { Button, Icon } from 'semantic-ui-react';
import {
formatTimestamp,
getColorForStringHex,
getDefaultPicture,
iceServers,
} from '../../utils';
import { UserMenu } from '../UserMenu/UserMenu';
interface VideoChatProps {
socket: SocketIOClient.Socket;
participants: User[];
pictureMap: StringDict;
nameMap: StringDict;
tsMap: NumberDict;
rosterUpdateTS: Number;
hide?: boolean;
owner: string | undefined;
user: firebase.User | undefined;
}
export class VideoChat extends React.Component<VideoChatProps> {
ourStream?: MediaStream;
videoRefs: any = {};
videoPCs: PCDict = {};
socket = this.props.socket;
componentDidMount() {
this.socket.on('signal', this.handleSignal);
}
componentWillUnmount() {
this.socket.off('signal', this.handleSignal);
}
componentDidUpdate(prevProps: VideoChatProps) {
if (this.props.rosterUpdateTS !== prevProps.rosterUpdateTS) {
this.updateWebRTC();
}
}
handleSignal = async (data: any) => {
// Handle messages received from signaling server
const msg = data.msg;
const from = data.from;
const pc = this.videoPCs[from];
console.log('recv', from, data);
if (msg.ice !== undefined) {
pc.addIceCandidate(new RTCIceCandidate(msg.ice));
} else if (msg.sdp && msg.sdp.type === 'offer') {
// console.log('offer');
await pc.setRemoteDescription(new RTCSessionDescription(msg.sdp));
const answer = await pc.createAnswer();
await pc.setLocalDescription(answer);
this.sendSignal(from, { sdp: pc.localDescription });
} else if (msg.sdp && msg.sdp.type === 'answer') {
pc.setRemoteDescription(new RTCSessionDescription(msg.sdp));
}
};
setupWebRTC = async () => {
// Set up our own video
// Create default stream
let black = ({ width = 640, height = 480 } = {}) => {
let canvas: any = Object.assign(document.createElement('canvas'), {
width,
height,
});
canvas.getContext('2d')?.fillRect(0, 0, width, height);
let stream = canvas.captureStream();
return Object.assign(stream.getVideoTracks()[0], { enabled: false });
};
let stream = new MediaStream([black()]);
try {
stream = await navigator?.mediaDevices.getUserMedia({
audio: true,
video: true,
});
} catch (e) {
console.warn(e);
try {
console.log('attempt audio only stream');
stream = await navigator?.mediaDevices?.getUserMedia({
audio: true,
video: false,
});
} catch (e) {
console.warn(e);
}
}
this.ourStream = stream;
// alert server we've joined video chat
this.socket.emit('CMD:joinVideo');
};
stopWebRTC = () => {
this.ourStream &&
this.ourStream.getTracks().forEach((track) => {
track.stop();
});
this.ourStream = undefined;
Object.keys(this.videoPCs).forEach((key) => {
this.videoPCs[key].close();
delete this.videoPCs[key];
});
this.socket.emit('CMD:leaveVideo');
};
toggleVideoWebRTC = () => {
if (this.ourStream && this.ourStream.getVideoTracks()[0]) {
this.ourStream.getVideoTracks()[0].enabled = !this.ourStream.getVideoTracks()[0]
?.enabled;
}
this.forceUpdate();
};
getVideoWebRTC = () => {
return this.ourStream && this.ourStream.getVideoTracks()[0]?.enabled;
};
toggleAudioWebRTC = () => {
if (this.ourStream && this.ourStream.getAudioTracks()[0]) {
this.ourStream.getAudioTracks()[0].enabled = !this.ourStream.getAudioTracks()[0]
?.enabled;
}
this.forceUpdate();
};
getAudioWebRTC = () => {
return (
this.ourStream &&
this.ourStream.getAudioTracks()[0] &&
this.ourStream.getAudioTracks()[0].enabled
);
};
updateWebRTC = () => {
if (!this.ourStream) {
// We haven't started video chat, exit
return;
}
this.props.participants.forEach((user) => {
const id = user.id;
if (!user.isVideoChat && this.videoPCs[id]) {
// User isn't in video chat but we have a connection, close it
this.videoPCs[id].close();
delete this.videoPCs[id];
}
if (!user.isVideoChat || this.videoPCs[id]) {
// User isn't in video chat, or we already have a connection to them
return;
}
if (id === this.socket.id) {
this.videoPCs[id] = new RTCPeerConnection();
this.videoRefs[id].srcObject = this.ourStream;
} else {
const pc = new RTCPeerConnection({ iceServers: iceServers() });
this.videoPCs[id] = pc;
// Add our own video as outgoing stream
this.ourStream?.getTracks().forEach((track) => {
if (this.ourStream) {
pc.addTrack(track, this.ourStream);
}
});
pc.onicecandidate = (event) => {
// We generated an ICE candidate, send it to peer
if (event.candidate) {
this.sendSignal(id, { ice: event.candidate });
}
};
pc.ontrack = (event: RTCTrackEvent) => {
// Mount the stream from peer
// console.log(stream);
this.videoRefs[id].srcObject = event.streams[0];
};
// For each pair, have the lexicographically smaller ID be the offerer
const isOfferer = this.socket.id < id;
if (isOfferer) {
pc.onnegotiationneeded = async () => {
// Start connection for peer's video
const offer = await pc.createOffer();
await pc.setLocalDescription(offer);
this.sendSignal(id, { sdp: pc.localDescription });
};
}
}
});
};
sendSignal = async (to: string, data: any) => {
console.log('send', to, data);
this.socket.emit('signal', { to, msg: data });
};
render() {
const {
participants,
pictureMap,
nameMap,
tsMap,
socket,
owner,
user,
} = this.props;
const videoChatContentStyle = {
height: participants.length < 3 ? 220 : 110,
borderRadius: '4px',
objectFit: 'contain',
};
return (
<div
style={{
display: this.props.hide ? 'none' : 'flex',
width: '100%',
flexDirection: 'column',
overflow: 'auto',
}}
>
{!this.ourStream && (
<div
style={{
display: 'flex',
flexWrap: 'wrap',
marginTop: '8px',
}}
>
<Button
fluid
title="Join Video Chat"
color={'purple'}
size="medium"
icon
labelPosition="left"
onClick={this.setupWebRTC}
>
<Icon name="video" />
{`Join Video Chat`}
</Button>
</div>
)}
{this.ourStream && (
<div
style={{
display: 'flex',
flexWrap: 'wrap',
}}
>
<Button
fluid
color={'red'}
size="medium"
icon
labelPosition="left"
onClick={this.stopWebRTC}
>
<Icon name="external" />
{`Leave Video Chat`}
</Button>
<div
style={{
display: 'flex',
justifyContent: 'center',
marginTop: '8px',
width: '100%',
}}
>
<Button
color={this.getVideoWebRTC() ? 'green' : 'red'}
fluid
size="medium"
icon
labelPosition="left"
onClick={this.toggleVideoWebRTC}
>
<Icon name="video" />
{this.getVideoWebRTC() ? 'On' : 'Off'}
</Button>
<Button
color={this.getAudioWebRTC() ? 'green' : 'red'}
fluid
size="medium"
icon
labelPosition="left"
onClick={this.toggleAudioWebRTC}
>
<Icon
name={
this.getAudioWebRTC() ? 'microphone' : 'microphone slash'
}
/>
{this.getAudioWebRTC() ? 'On' : 'Off'}
</Button>
</div>
</div>
)}
<div
style={{
display: 'flex',
flexWrap: 'wrap',
justifyContent: 'center',
marginTop: '8px',
}}
>
{participants.map((p) => {
return (
<div key={p.id}>
<div
style={{
position: 'relative',
//marginLeft: '4px',
}}
>
<div>
<UserMenu
displayName={nameMap[p.id] || p.id}
user={user}
disabled={!Boolean(owner && owner === user?.uid)}
position={'left center'}
socket={socket}
userToManage={p.id}
trigger={
<Icon
name="ellipsis vertical"
size="large"
style={{
position: 'absolute',
right: -7,
top: 5,
cursor: 'pointer',
opacity: 0.75,
visibility: Boolean(owner && owner === user?.uid)
? 'visible'
: 'hidden',
}}
/>
}
/>
{this.ourStream && p.isVideoChat ? (
<video
ref={(el) => {
this.videoRefs[p.id] = el;
}}
style={{
...(videoChatContentStyle as any),
// mirror the video if it's our stream. this style mimics Zoom where your
// video is mirrored only for you)
transform: `scaleX(${
p.id === socket.id ? '-1' : '1'
})`,
}}
autoPlay
muted={p.id === socket.id}
data-id={p.id}
/>
) : (
<img
style={videoChatContentStyle as any}
src={
pictureMap[p.id] ||
getDefaultPicture(
nameMap[p.id],
getColorForStringHex(p.id)
)
}
alt=""
/>
)}
<div
style={{
position: 'absolute',
bottom: '4px',
left: '0px',
width: '100%',
backgroundColor: 'rgba(0,0,0,0)',
color: 'white',
borderRadius: '4px',
fontSize: '10px',
fontWeight: 700,
display: 'flex',
}}
>
<div
title={nameMap[p.id] || p.id}
style={{
width: '80px',
backdropFilter: 'brightness(80%)',
padding: '4px',
textOverflow: 'ellipsis',
whiteSpace: 'nowrap',
overflow: 'hidden',
display: 'inline-block',
}}
>
{p.isVideoChat && <Icon size="small" name="video" />}
{nameMap[p.id] || p.id}
</div>
<div
style={{
backdropFilter: 'brightness(60%)',
padding: '4px',
flexGrow: 1,
display: 'flex',
justifyContent: 'center',
}}
>
{formatTimestamp(tsMap[p.id] || 0)}
</div>
</div>
</div>
</div>
</div>
);
})}
</div>
</div>
);
}
} | the_stack |
import * as crypto from "crypto";
import * as debug_ from "debug";
import { app, protocol, ProtocolRequest, ProtocolResponse, session } from "electron";
import * as fs from "fs";
import * as mime from "mime-types";
import * as path from "path";
import { IS_DEV } from "readium-desktop/preprocessor-directives";
import { TaJsonSerialize } from "@r2-lcp-js/serializable";
import { parseDOM, serializeDOM } from "@r2-navigator-js/electron/common/dom";
import { IEventPayload_R2_EVENT_READIUMCSS } from "@r2-navigator-js/electron/common/events";
import { readiumCssTransformHtml } from "@r2-navigator-js/electron/common/readium-css-inject";
import {
convertCustomSchemeToHttpUrl, convertHttpUrlToCustomScheme, READIUM2_ELECTRON_HTTP_PROTOCOL,
} from "@r2-navigator-js/electron/common/sessions";
import { clearSessions, getWebViewSession } from "@r2-navigator-js/electron/main/sessions";
import {
URL_PARAM_CLIPBOARD_INTERCEPT, URL_PARAM_CSS, URL_PARAM_DEBUG_VISUALS,
URL_PARAM_EPUBREADINGSYSTEM, URL_PARAM_IS_IFRAME, URL_PARAM_SECOND_WEBVIEW,
URL_PARAM_WEBVIEW_SLOT,
} from "@r2-navigator-js/electron/renderer/common/url-params";
import { zipHasEntry } from "@r2-shared-js/_utils/zipHasEntry";
import { Publication as R2Publication } from "@r2-shared-js/models/publication";
import { Link } from "@r2-shared-js/models/publication-link";
import {
getAllMediaOverlays, getMediaOverlay, mediaOverlayURLParam, mediaOverlayURLPath,
} from "@r2-shared-js/parser/epub";
import { PublicationParsePromise } from "@r2-shared-js/parser/publication-parser";
import { Transformers } from "@r2-shared-js/transform/transformer";
import { TransformerHTML, TTransformFunction } from "@r2-shared-js/transform/transformer-html";
import { parseRangeHeader } from "@r2-utils-js/_utils/http/RangeUtils";
import { encodeURIComponent_RFC3986, isHTTP } from "@r2-utils-js/_utils/http/UrlUtils";
import { bufferToStream } from "@r2-utils-js/_utils/stream/BufferUtils";
import { IStreamAndLength, IZip } from "@r2-utils-js/_utils/zip/zip";
import {
computeReadiumCssJsonMessageInStreamer, MATHJAX_FILE_PATH, MATHJAX_URL_PATH,
READIUMCSS_FILE_PATH, setupMathJaxTransformer,
} from "./streamerCommon";
// import { _USE_HTTP_STREAMER } from "readium-desktop/preprocessor-directives";
const debug = debug_("readium-desktop:main#streamerNoHttp");
const URL_PARAM_SESSION_INFO = "r2_SESSION_INFO";
// this ceiling value seems very arbitrary ... what would be a reasonable default value?
// ... based on what metric, any particular HTTP server or client implementation?
export const MAX_PREFETCH_LINKS = 10;
export const THORIUM_READIUM2_ELECTRON_HTTP_PROTOCOL = "thoriumhttps";
const READIUM_CSS_URL_PATH = "readium-css";
if (true) { // !_USE_HTTP_STREAMER) {
function isFixedLayout(publication: R2Publication, link: Link | undefined): boolean {
if (link && link.Properties) {
if (link.Properties.Layout === "fixed") {
return true;
}
if (typeof link.Properties.Layout !== "undefined") {
return false;
}
}
if (publication &&
publication.Metadata &&
publication.Metadata.Rendition) {
return publication.Metadata.Rendition.Layout === "fixed";
}
return false;
}
const transformerReadiumCss: TTransformFunction = (
publication: R2Publication,
link: Link,
url: string | undefined,
str: string,
sessionInfo: string | undefined,
): string => {
let isIframe = false;
if (url) {
const url_ = new URL(url);
if (url_.searchParams.has(URL_PARAM_IS_IFRAME)) {
isIframe = true;
}
}
if (isIframe) {
return str;
}
let readiumcssJson = computeReadiumCssJsonMessageInStreamer(publication, link, sessionInfo);
if (isFixedLayout(publication, link)) {
const readiumcssJson_ = { setCSS: undefined, isFixedLayout: true } as IEventPayload_R2_EVENT_READIUMCSS;
if (readiumcssJson.setCSS) {
if (readiumcssJson.setCSS.mathJax) {
// TODO: apply MathJax to FXL?
// (reminder: setCSS must remain 'undefined'
// in order to completely remove ReadiumCSS from FXL docs)
}
if (readiumcssJson.setCSS.reduceMotion) {
// TODO: same as MathJax (see above)
}
// if (readiumcssJson.setCSS.audioPlaybackRate) {
// // TODO: same as MathJax (see above)
// }
}
readiumcssJson = readiumcssJson_;
}
if (readiumcssJson) {
if (!readiumcssJson.urlRoot) {
// `/${READIUM_CSS_URL_PATH}/`
readiumcssJson.urlRoot = THORIUM_READIUM2_ELECTRON_HTTP_PROTOCOL + "://0.0.0.0";
}
if (IS_DEV) {
console.log("_____ readiumCssJson.urlRoot (setupReadiumCSS() transformer): ", readiumcssJson.urlRoot);
}
// import * as mime from "mime-types";
let mediaType = "application/xhtml+xml"; // mime.lookup(link.Href);
if (link && link.TypeLink) {
mediaType = link.TypeLink;
}
return readiumCssTransformHtml(str, readiumcssJson, mediaType);
} else {
return str;
}
};
Transformers.instance().add(new TransformerHTML(transformerReadiumCss));
setupMathJaxTransformer(
() => `${THORIUM_READIUM2_ELECTRON_HTTP_PROTOCOL}://0.0.0.0/${MATHJAX_URL_PATH}/es5/tex-mml-chtml.js`,
);
}
function getPreFetchResources(publication: R2Publication): Link[] {
const links: Link[] = [];
if (publication.Resources) {
// https://w3c.github.io/publ-epub-revision/epub32/spec/epub-spec.html#cmt-grp-font
const mediaTypes = ["text/css",
"text/javascript", "application/javascript",
"application/vnd.ms-opentype", "font/otf", "application/font-sfnt",
"font/ttf", "application/font-sfnt",
"font/woff", "application/font-woff", "font/woff2"];
for (const mediaType of mediaTypes) {
for (const link of publication.Resources) {
if (link.TypeLink === mediaType) {
links.push(link);
}
}
}
}
return links;
}
const streamProtocolHandlerTunnel = async (
req: ProtocolRequest,
callback: (stream: (NodeJS.ReadableStream) | (ProtocolResponse)) => void) => {
debug("............... streamProtocolHandlerTunnel req.url", req.url);
req.url = convertCustomSchemeToHttpUrl(req.url);
streamProtocolHandler(req, callback);
};
// super hacky!! :(
// see usages of this boolean...
let _customUrlProtocolSchemeHandlerWasCalled = false;
const streamProtocolHandler = async (
req: ProtocolRequest,
callback: (stream: (NodeJS.ReadableStream) | (ProtocolResponse)) => void) => {
_customUrlProtocolSchemeHandlerWasCalled = true;
// debug("streamProtocolHandler:");
// debug(req.url);
// debug(req.referrer);
// debug(req.method);
// debug(req.headers);
debug("streamProtocolHandler req.url", req.url);
const u = new URL(req.url);
// https://github.com/readium/r2-streamer-js/commit/e214b7e1f8133a8400baec3c6f2d7c8204da01ad
// At this point, route relative path is already normalised with respect to /../ and /./ dot segments,
// but not double slashes (which seems to be an easy mistake to make at authoring time in EPUBs),
// so we collapse multiple slashes into a single one.
let uPathname = u.pathname;
if (uPathname) {
uPathname = uPathname.replace(/\/\/+/g, "/");
try {
uPathname = decodeURIComponent(uPathname);
} catch (e) {
debug("u.pathname decodeURIComponent!?");
debug(e);
}
}
const publicationAssetsPrefix = "/pub/";
const isPublicationAssets = uPathname.startsWith(publicationAssetsPrefix);
const mathJaxPrefix = `/${MATHJAX_URL_PATH}/`;
const isMathJax = uPathname.startsWith(mathJaxPrefix);
const readiumCssPrefix = `/${READIUM_CSS_URL_PATH}/`;
const isReadiumCSS = uPathname.startsWith(readiumCssPrefix);
const mediaOverlaysPrefix = `/${mediaOverlayURLPath}`;
const isMediaOverlays = uPathname.endsWith(mediaOverlaysPrefix);
debug("streamProtocolHandler uPathname", uPathname);
debug("streamProtocolHandler isPublicationAssets", isPublicationAssets);
debug("streamProtocolHandler isMathJax", isMathJax);
debug("streamProtocolHandler isReadiumCSS", isReadiumCSS);
debug("streamProtocolHandler isMediaOverlays", isMediaOverlays);
const isHead = req.method.toLowerCase() === "head";
if (isHead) {
debug("streamProtocolHandler HEAD !!!!!!!!!!!!!!!!!!!");
}
let ref = u.origin;
debug("streamProtocolHandler u.origin", ref);
if (req.referrer && req.referrer.trim()) {
ref = req.referrer;
debug("streamProtocolHandler req.referrer", ref);
}
if (IS_DEV) {
Object.keys(req.headers).forEach((header: string) => {
const val = req.headers[header];
debug("streamProtocolHandler req.header: " + header + " => " + val);
// if (val) {
// headers[header] = val;
// }
});
}
const headers: Record<string, (string) | (string[])> = {};
if (ref && ref !== "null" && !/^https?:\/\/localhost.+/.test(ref) && !/^https?:\/\/127\.0\.0\.1.+/.test(ref)) {
headers.referer = ref;
} else {
headers.referer = `${THORIUM_READIUM2_ELECTRON_HTTP_PROTOCOL}://0.0.0.0/`;
}
// CORS everything!
headers["Access-Control-Allow-Origin"] = "*";
headers["Access-Control-Allow-Methods"] = "GET, HEAD, OPTIONS"; // POST, DELETE, PUT, PATCH
// tslint:disable-next-line:max-line-length
headers["Access-Control-Allow-Headers"] = "Content-Type, Content-Length, Accept-Ranges, Content-Range, Range, Link, Transfer-Encoding, X-Requested-With, Authorization, Accept, Origin, User-Agent, DNT, Cache-Control, Keep-Alive, If-Modified-Since";
// tslint:disable-next-line:max-line-length
headers["Access-Control-Expose-Headers"] = "Content-Type, Content-Length, Accept-Ranges, Content-Range, Range, Link, Transfer-Encoding, X-Requested-With, Authorization, Accept, Origin, User-Agent, DNT, Cache-Control, Keep-Alive, If-Modified-Since";
if (isPublicationAssets || isMediaOverlays) {
let b64Path = uPathname.substr(publicationAssetsPrefix.length);
const i = b64Path.indexOf("/");
let pathInZip = "";
if (i >= 0) {
pathInZip = b64Path.substr(i + 1);
b64Path = b64Path.substr(0, i);
}
b64Path = decodeURIComponent(b64Path);
debug("streamProtocolHandler b64Path", b64Path);
debug("streamProtocolHandler pathInZip", pathInZip);
if (!pathInZip) {
const err = "PATH IN ZIP?? " + uPathname;
debug(err);
const buff = Buffer.from("<html><body><p>Internal Server Error</p><p>" + err + "</p></body></html>");
headers["Content-Length"] = buff.length.toString();
const obj = {
// NodeJS.ReadableStream
data: bufferToStream(buff),
headers,
statusCode: 500,
};
callback(obj);
return;
}
const pathBase64Str = Buffer.from(b64Path, "base64").toString("utf8");
// const fileName = path.basename(pathBase64Str);
// const ext = path.extname(fileName).toLowerCase();
let publication: R2Publication;
try {
publication = await streamerLoadOrGetCachedPublication(pathBase64Str);
} catch (err) {
debug(err);
const buff = Buffer.from("<html><body><p>Internal Server Error</p><p>" + err + "</p></body></html>");
headers["Content-Length"] = buff.length.toString();
const obj = {
// NodeJS.ReadableStream
data: bufferToStream(buff),
headers,
statusCode: 500,
};
callback(obj);
return;
}
if (isMediaOverlays) {
let objToSerialize: any = null;
// decodeURIComponent already done
const resource = u.searchParams.get(mediaOverlayURLParam) || undefined;
debug("streamProtocolHandler MO resource", resource);
if (resource && resource !== "all") {
try {
objToSerialize = await getMediaOverlay(publication, resource);
} catch (err) {
debug(err);
const buff =
Buffer.from("<html><body><p>Internal Server Error</p><p>" + err + "</p></body></html>");
headers["Content-Length"] = buff.length.toString();
const objz = {
// NodeJS.ReadableStream
data: bufferToStream(buff),
headers,
statusCode: 500,
};
callback(objz);
return;
}
} else {
try {
objToSerialize = await getAllMediaOverlays(publication);
} catch (err) {
debug(err);
const buff =
Buffer.from("<html><body><p>Internal Server Error</p><p>" + err + "</p></body></html>");
headers["Content-Length"] = buff.length.toString();
const objz = {
// NodeJS.ReadableStream
data: bufferToStream(buff),
headers,
statusCode: 500,
};
callback(objz);
return;
}
}
if (!objToSerialize) {
objToSerialize = [];
}
debug("streamProtocolHandler objToSerialize", objToSerialize);
const jsonObj = TaJsonSerialize(objToSerialize);
// jsonObj = { "media-overlay": jsonObj };
const jsonStr = global.JSON.stringify(jsonObj, null, " ");
const checkSum = crypto.createHash("sha256");
checkSum.update(jsonStr);
const hash = checkSum.digest("hex");
const match = req.headers["If-None-Match"];
if (match === hash) {
debug("streamProtocolHandler smil cache");
const obj: ProtocolResponse = {
// NodeJS.ReadableStream
data: null,
headers,
statusCode: 304, // StatusNotModified,
};
callback(obj);
return;
}
headers["Content-Type"] = "application/vnd.syncnarr+json; charset=utf-8";
headers.ETag = hash;
// headers["Cache-Control"] = "public,max-age=86400";
if (isHead) {
debug("streamProtocolHandler smil HEAD RESPONSE HEADERS: ", headers);
const obj: ProtocolResponse = {
// NodeJS.ReadableStream
data: null,
headers,
statusCode: 200,
};
callback(obj);
} else {
const buff = Buffer.from(jsonStr);
headers["Content-Length"] = buff.length.toString();
debug("streamProtocolHandler smil GET RESPONSE HEADERS: ", headers);
const obj: ProtocolResponse = {
// NodeJS.ReadableStream
data: bufferToStream(buff),
headers,
statusCode: 200,
};
callback(obj);
}
return;
}
if (pathInZip === "manifest.json") {
const rootUrl = "THORIUM_READIUM2_ELECTRON_HTTP_PROTOCOL://0.0.0.0/pub/" + encodeURIComponent_RFC3986(b64Path);
const manifestURL = rootUrl + "/" + "manifest.json";
const contentType =
(publication.Metadata && publication.Metadata.RDFType &&
/http[s]?:\/\/schema\.org\/Audiobook$/.test(publication.Metadata.RDFType)) ?
"application/audiobook+json" : ((publication.Metadata && publication.Metadata.RDFType &&
(/http[s]?:\/\/schema\.org\/ComicStory$/.test(publication.Metadata.RDFType) ||
/http[s]?:\/\/schema\.org\/VisualNarrative$/.test(publication.Metadata.RDFType))) ? "application/divina+json" :
"application/webpub+json");
const selfLink = publication.searchLinkByRel("self");
if (!selfLink) {
publication.AddLink(contentType, ["self"], manifestURL, undefined);
}
function absoluteURL(href: string): string {
return rootUrl + "/" + href;
}
let hasMO = false;
if (publication.Spine) {
const linkk = publication.Spine.find((l) => {
if (l.Properties && l.Properties.MediaOverlay) {
return true;
}
return false;
});
if (linkk) {
hasMO = true;
}
}
if (hasMO) {
const moLink = publication.searchLinkByRel("media-overlay");
if (!moLink) {
const moURL = // rootUrl + "/" +
mediaOverlayURLPath +
"?" + mediaOverlayURLParam + "={path}";
publication.AddLink("application/vnd.syncnarr+json", ["media-overlay"], moURL, true);
}
}
let coverImage: string | undefined;
const coverLink = publication.GetCover();
if (coverLink) {
coverImage = coverLink.Href;
if (coverImage && !isHTTP(coverImage)) {
coverImage = absoluteURL(coverImage);
}
}
headers["Content-Type"] = `${contentType}; charset=utf-8`;
const publicationJsonObj = TaJsonSerialize(publication);
// absolutizeURLs(publicationJsonObj);
const publicationJsonStr = global.JSON.stringify(publicationJsonObj, null, " ");
const checkSum = crypto.createHash("sha256");
checkSum.update(publicationJsonStr);
const hash = checkSum.digest("hex");
const match = req.headers["If-None-Match"];
if (match === hash) {
debug("streamProtocolHandler manifest.json cache");
const obj: ProtocolResponse = {
// NodeJS.ReadableStream
data: null,
headers,
statusCode: 304, // StatusNotModified,
};
callback(obj);
return;
}
headers.ETag = hash;
// headers["Cache-Control"] = "public,max-age=86400";
const links = getPreFetchResources(publication);
if (links && links.length) {
let n = 0;
let prefetch = "";
for (const l of links) {
n++;
if (n > MAX_PREFETCH_LINKS) {
break;
}
const href = absoluteURL(l.Href);
prefetch += "<" + href + ">;" + "rel=prefetch,";
}
headers.Link = prefetch;
}
if (isHead) {
debug("streamProtocolHandler manifest HEAD RESPONSE HEADERS: ", headers);
const obj: ProtocolResponse = {
// NodeJS.ReadableStream
data: null,
headers,
statusCode: 200,
};
callback(obj);
} else {
const buff = Buffer.from(publicationJsonStr);
headers["Content-Length"] = buff.length.toString();
debug("streamProtocolHandler manifest GET RESPONSE HEADERS: ", headers);
const obj: ProtocolResponse = {
// NodeJS.ReadableStream
data: bufferToStream(buff),
headers,
statusCode: 200,
};
callback(obj);
}
return;
}
const zipInternal = publication.findFromInternal("zip");
if (!zipInternal) {
const err = "No publication zip!";
debug(err);
const buff = Buffer.from("<html><body><p>Internal Server Error</p><p>" + err + "</p></body></html>");
headers["Content-Length"] = buff.length.toString();
const obj = {
// NodeJS.ReadableStream
data: bufferToStream(buff),
headers,
statusCode: 500,
};
callback(obj);
return;
}
const zip = zipInternal.Value as IZip;
if (!zipHasEntry(zip, pathInZip, undefined)) {
const err = "Asset not in zip! " + pathInZip;
debug(err);
const buff = Buffer.from("<html><body><p>Internal Server Error</p><p>" + err + "</p></body></html>");
headers["Content-Length"] = buff.length.toString();
const obj = {
// NodeJS.ReadableStream
data: bufferToStream(buff),
headers,
statusCode: 500,
};
callback(obj);
return;
}
const isDivina = publication.Metadata && publication.Metadata.RDFType &&
(/http[s]?:\/\/schema\.org\/ComicStory$/.test(publication.Metadata.RDFType) ||
/http[s]?:\/\/schema\.org\/VisualNarrative$/.test(publication.Metadata.RDFType));
let link: Link | undefined;
const findLinkRecursive = (relativePath: string, l: Link): Link | undefined => {
if (l.Href === relativePath) {
return l;
}
let found: Link | undefined;
if (l.Children) {
for (const child of l.Children) {
found = findLinkRecursive(relativePath, child);
if (found) {
return found;
}
}
}
if (l.Alternate) {
for (const alt of l.Alternate) {
found = findLinkRecursive(relativePath, alt);
if (found) {
return found;
}
}
}
return undefined;
};
if ((publication.Resources || publication.Spine || publication.Links)
&& pathInZip.indexOf("META-INF/") !== 0
&& !pathInZip.endsWith(".opf")) {
const relativePath = pathInZip;
if (publication.Resources) {
for (const l of publication.Resources) {
link = findLinkRecursive(relativePath, l);
if (link) {
break;
}
}
}
if (!link) {
if (publication.Spine) {
for (const l of publication.Spine) {
link = findLinkRecursive(relativePath, l);
if (link) {
break;
}
}
}
}
if (!link) {
if (publication.Links) {
for (const l of publication.Links) {
link = findLinkRecursive(relativePath, l);
if (link) {
break;
}
}
}
}
if (!link &&
!isDivina) {
const err = "Asset not declared in publication spine/resources! " + relativePath;
debug(err);
const buff = Buffer.from("<html><body><p>Internal Server Error</p><p>" + err + "</p></body></html>");
headers["Content-Length"] = buff.length.toString();
const obj = {
// NodeJS.ReadableStream
data: bufferToStream(buff),
headers,
statusCode: 500,
};
callback(obj);
return;
}
}
let mediaType = mime.lookup(pathInZip) || "stream/octet";
if (link && link.TypeLink) {
mediaType = link.TypeLink;
}
debug("streamProtocolHandler mediaType", mediaType);
// const isText = (typeof mediaType === "string") && (
// mediaType.indexOf("text/") === 0 ||
// mediaType.indexOf("application/xhtml") === 0 ||
// mediaType.indexOf("application/xml") === 0 ||
// mediaType.indexOf("application/json") === 0 ||
// mediaType.indexOf("application/svg") === 0 ||
// mediaType.indexOf("application/smil") === 0 ||
// mediaType.indexOf("+json") > 0 ||
// mediaType.indexOf("+smil") > 0 ||
// mediaType.indexOf("+svg") > 0 ||
// mediaType.indexOf("+xhtml") > 0 ||
// mediaType.indexOf("+xml") > 0);
// const isVideoAudio = mediaType && (
// mediaType.indexOf("audio/") === 0 ||
// mediaType.indexOf("video/") === 0);
// if (isVideoAudio) {
// debug(req.headers);
// }
const isEncrypted = link && link.Properties && link.Properties.Encrypted;
// const isObfuscatedFont = isEncrypted && link &&
// (link.Properties.Encrypted.Algorithm === "http://ns.adobe.com/pdf/enc#RC"
// || link.Properties.Encrypted.Algorithm === "http://www.idpf.org/2008/embedding");
debug("streamProtocolHandler isEncrypted", isEncrypted);
const isPartialByteRangeRequest = ((req.headers && req.headers.Range) ? true : false);
debug("streamProtocolHandler isPartialByteRangeRequest", isPartialByteRangeRequest);
// if (isEncrypted && isPartialByteRangeRequest) {
// const err = "Encrypted video/audio not supported (HTTP 206 partial request byte range)";
// debug(err);
// res.status(500).send("<html><body><p>Internal Server Error</p><p>"
// + err + "</p></body></html>");
// return;
// }
let partialByteBegin = 0; // inclusive boundaries
let partialByteEnd = -1;
if (isPartialByteRangeRequest) {
debug("streamProtocolHandler isPartialByteRangeRequest", req.headers.Range);
const ranges = parseRangeHeader(req.headers.Range);
// debug(ranges);
if (ranges && ranges.length) {
if (ranges.length > 1) {
const err = "Too many HTTP ranges: " + req.headers.Range;
debug(err);
const buff =
Buffer.from("<html><body><p>Internal Server Error</p><p>" + err + "</p></body></html>");
headers["Content-Length"] = buff.length.toString();
// headers["Content-Range"] = `*/${contentLength}`;
const obj = {
// NodeJS.ReadableStream
data: bufferToStream(buff),
headers,
statusCode: 416,
};
callback(obj);
return;
}
partialByteBegin = ranges[0].begin;
partialByteEnd = ranges[0].end;
if (partialByteBegin < 0) {
partialByteBegin = 0;
}
}
debug("streamProtocolHandler isPartialByteRangeRequest", `${pathInZip} >> ${partialByteBegin}-${partialByteEnd}`);
}
let zipStream_: IStreamAndLength;
try {
zipStream_ = isPartialByteRangeRequest && !isEncrypted ?
await zip.entryStreamRangePromise(pathInZip, partialByteBegin, partialByteEnd) :
await zip.entryStreamPromise(pathInZip);
} catch (err) {
debug(err);
const buff = Buffer.from("<html><body><p>Internal Server Error</p><p>" + err + "</p></body></html>");
headers["Content-Length"] = buff.length.toString();
const obj = {
// NodeJS.ReadableStream
data: bufferToStream(buff),
headers,
statusCode: 500,
};
callback(obj);
return;
}
// The HTML transforms are chained here too, so cannot check server.disableDecryption at this level!
const doTransform = true; // !isEncrypted || (isObfuscatedFont || !server.disableDecryption);
// decodeURIComponent already done
const sessionInfo = u.searchParams.get(URL_PARAM_SESSION_INFO) || undefined;
debug("streamProtocolHandler sessionInfo", sessionInfo);
if (doTransform && link) {
const fullUrl = req.url; // `${THORIUM_READIUM2_ELECTRON_HTTP_PROTOCOL}://0.0.0.0${uPathname}`;
let transformedStream: IStreamAndLength;
try {
transformedStream = await Transformers.tryStream(
publication,
link,
fullUrl,
zipStream_,
isPartialByteRangeRequest,
partialByteBegin,
partialByteEnd,
sessionInfo,
);
} catch (err) {
debug(err);
const buff = Buffer.from("<html><body><p>Internal Server Error</p><p>" + err + "</p></body></html>");
headers["Content-Length"] = buff.length.toString();
const obj = {
// NodeJS.ReadableStream
data: bufferToStream(buff),
headers,
statusCode: 500,
};
callback(obj);
return;
}
if (transformedStream) {
if (transformedStream !== zipStream_) {
debug("streamProtocolHandler Asset transformed ok", link.Href);
}
zipStream_ = transformedStream; // can be unchanged
} else {
const err = "Transform fail (encryption scheme not supported?)";
debug(err);
const buff = Buffer.from("<html><body><p>Internal Server Error</p><p>" + err + "</p></body></html>");
headers["Content-Length"] = buff.length.toString();
const obj = {
// NodeJS.ReadableStream
data: bufferToStream(buff),
headers,
statusCode: 500,
};
callback(obj);
return;
}
}
if (isPartialByteRangeRequest) {
headers["Cache-Control"] = "no-cache, no-store, must-revalidate";
headers.Pragma = "no-cache";
headers.Expires = "0";
} else {
headers["Cache-Control"] = "public,max-age=86400";
}
if (mediaType) {
headers["Content-Type"] = mediaType;
// res.type(mediaType);
}
headers["Accept-Ranges"] = "bytes";
let statusCode = 200;
if (isPartialByteRangeRequest) {
if (partialByteEnd < 0) {
partialByteEnd = zipStream_.length - 1;
}
const partialByteLength = isPartialByteRangeRequest ?
partialByteEnd - partialByteBegin + 1 :
zipStream_.length;
// res.setHeader("Connection", "close");
// res.setHeader("Transfer-Encoding", "chunked");
headers["Content-Length"] = `${partialByteLength}`;
const rangeHeader = `bytes ${partialByteBegin}-${partialByteEnd}/${zipStream_.length}`;
debug("streamProtocolHandler +++> " + rangeHeader + " (( " + partialByteLength);
headers["Content-Range"] = rangeHeader;
statusCode = 206;
} else {
headers["Content-Length"] = `${zipStream_.length}`;
debug("streamProtocolHandler ---> " + zipStream_.length);
statusCode = 200;
}
if (isHead) {
debug("streamProtocolHandler HEAD RESPONSE HEADERS: ", headers);
const obj: ProtocolResponse = {
// NodeJS.ReadableStream
data: null,
headers,
statusCode,
};
callback(obj);
} else {
debug("streamProtocolHandler GET RESPONSE HEADERS: ", headers);
const obj = {
// NodeJS.ReadableStream
data: zipStream_.stream,
headers,
statusCode,
};
callback(obj);
}
} else if (isMathJax || isReadiumCSS) {
const p = path.join(isReadiumCSS ? READIUMCSS_FILE_PATH : MATHJAX_FILE_PATH,
uPathname.substr((isReadiumCSS ? readiumCssPrefix : mathJaxPrefix).length));
debug("streamProtocolHandler isMathJax || isReadiumCSS", p);
if (!fs.existsSync(p)) {
const err = "404 NOT FOUND: " + p;
debug(err);
const buff = Buffer.from("<html><body><p>Internal Server Error</p><p>" + err + "</p></body></html>");
headers["Content-Length"] = buff.length.toString();
const objz = {
// NodeJS.ReadableStream
data: bufferToStream(buff),
headers,
statusCode: 404,
};
callback(objz);
return;
}
fs.readFile(p, (e, buffer) => {
if (e) {
const err = e + " :ERROR: " + p;
debug(err);
const buff = Buffer.from("<html><body><p>Internal Server Error</p><p>" + err + "</p></body></html>");
headers["Content-Length"] = buff.length.toString();
const objz = {
// NodeJS.ReadableStream
data: bufferToStream(buff),
headers,
statusCode: 500,
};
callback(objz);
return;
}
const mediaType = mime.lookup(p) || "stream/octet";
headers["Content-Type"] = mediaType;
const checkSum = crypto.createHash("sha256");
checkSum.update(buffer);
const hash = checkSum.digest("hex");
const match = req.headers["If-None-Match"];
if (match === hash) {
debug("streamProtocolHandler cached: " + p);
const obj_: ProtocolResponse = {
// NodeJS.ReadableStream
data: null,
headers,
statusCode: 304, // StatusNotModified,
};
callback(obj_);
return;
}
headers.ETag = hash;
// headers["Cache-Control"] = "public,max-age=86400";
headers["Content-Length"] = buffer.length.toString();
debug("streamProtocolHandler MATHJAX / READIUMCSS RESPONSE HEADERS: ", headers);
const obj: ProtocolResponse = {
// NodeJS.ReadableStream
data: bufferToStream(buffer),
headers,
statusCode: 200,
};
callback(obj);
});
} else {
const err = "NOPE :( " + uPathname;
debug(err);
const buff = Buffer.from("<html><body><p>Internal Server Error</p><p>" + err + "</p></body></html>");
headers["Content-Length"] = buff.length.toString();
const obj = {
// NodeJS.ReadableStream
data: bufferToStream(buff),
headers,
statusCode: 404,
};
callback(obj);
}
};
const transformerIFrames: TTransformFunction = (
_publication: R2Publication,
link: Link,
url: string | undefined,
htmlStr: string,
_sessionInfo: string | undefined,
): string => {
// super hacky! (guarantees that convertCustomSchemeToHttpUrl() is necessary,
// unlike this `url` function parameter which is always HTTP as it originates
// from the streamer/server)
if (!_customUrlProtocolSchemeHandlerWasCalled) {
return htmlStr;
}
if (!url) {
return htmlStr;
}
if (htmlStr.indexOf("<iframe") < 0) {
return htmlStr;
}
// let's remove the DOCTYPE (which can contain entities)
const iHtmlStart = htmlStr.indexOf("<html");
if (iHtmlStart < 0) {
return htmlStr;
}
const iBodyStart = htmlStr.indexOf("<body");
if (iBodyStart < 0) {
return htmlStr;
}
const parseableChunk = htmlStr.substr(iHtmlStart);
const htmlStrToParse = `<?xml version="1.0" encoding="utf-8"?>${parseableChunk}`;
// import * as mime from "mime-types";
let mediaType = "application/xhtml+xml"; // mime.lookup(link.Href);
if (link && link.TypeLink) {
mediaType = link.TypeLink;
}
// debug(htmlStrToParse);
const documant = parseDOM(htmlStrToParse, mediaType);
// debug(url);
let urlHttp = url;
if (!urlHttp.startsWith(READIUM2_ELECTRON_HTTP_PROTOCOL + "://")) {
// urlHttp = convertCustomSchemeToHttpUrl(urlHttp);
urlHttp = convertHttpUrlToCustomScheme(urlHttp);
}
const url_ = new URL(urlHttp);
// const r2_GOTO = url_.searchParams.get(URL_PARAM_GOTO);
// const r2_GOTO_DOM_RANGE = url_.searchParams.get(URL_PARAM_GOTO_DOM_RANGE);
// const r2_REFRESH = url_.searchParams.get(URL_PARAM_REFRESH);
const r2CSS = url_.searchParams.get(URL_PARAM_CSS);
const r2ERS = url_.searchParams.get(URL_PARAM_EPUBREADINGSYSTEM);
const r2DEBUG = url_.searchParams.get(URL_PARAM_DEBUG_VISUALS);
const r2CLIPBOARDINTERCEPT = url_.searchParams.get(URL_PARAM_CLIPBOARD_INTERCEPT);
const r2SESSIONINFO = url_.searchParams.get(URL_PARAM_SESSION_INFO);
const r2WEBVIEWSLOT = url_.searchParams.get(URL_PARAM_WEBVIEW_SLOT);
const r2SECONDWEBVIEW = url_.searchParams.get(URL_PARAM_SECOND_WEBVIEW);
url_.search = "";
url_.hash = "";
const urlStr = url_.toString();
// debug(urlStr);
const patchElementSrc = (el: Element) => {
const src = el.getAttribute("src");
if (!src || src[0] === "/" ||
/^http[s]?:\/\//.test(src) || /^data:\/\//.test(src)) {
return;
}
let src_ = src;
if (src_.startsWith("./")) {
src_ = src_.substr(2);
}
src_ = `${urlStr}/../${src_}`;
const iframeUrl = new URL(src_);
if (r2CLIPBOARDINTERCEPT) {
iframeUrl.searchParams.append(URL_PARAM_CLIPBOARD_INTERCEPT, r2CLIPBOARDINTERCEPT);
}
if (r2SESSIONINFO) {
iframeUrl.searchParams.append(URL_PARAM_SESSION_INFO, r2SESSIONINFO);
}
if (r2DEBUG) {
iframeUrl.searchParams.append(URL_PARAM_DEBUG_VISUALS, r2DEBUG);
}
if (r2ERS) {
iframeUrl.searchParams.append(URL_PARAM_EPUBREADINGSYSTEM, r2ERS);
}
if (r2CSS) {
iframeUrl.searchParams.append(URL_PARAM_CSS, r2CSS);
}
if (r2WEBVIEWSLOT) {
iframeUrl.searchParams.append(URL_PARAM_WEBVIEW_SLOT, r2WEBVIEWSLOT);
}
if (r2SECONDWEBVIEW) {
iframeUrl.searchParams.append(URL_PARAM_SECOND_WEBVIEW, r2SECONDWEBVIEW);
}
iframeUrl.searchParams.append(URL_PARAM_IS_IFRAME, "1");
// debug(iframeUrl.search);
src_ = iframeUrl.toString();
debug(`IFRAME SRC PATCH: ${src} ==> ${src_}`);
el.setAttribute("src", src_);
};
const processTree = (el: Element) => {
const elName = el.nodeName.toLowerCase();
if (elName === "iframe") {
patchElementSrc(el);
} else {
if (!el.childNodes) {
return;
}
// tslint:disable-next-line: prefer-for-of
for (let i = 0; i < el.childNodes.length; i++) {
const childNode = el.childNodes[i];
if (childNode.nodeType === 1) { // Node.ELEMENT_NODE
processTree(childNode as Element);
}
}
}
};
processTree(documant.body);
const serialized = serializeDOM(documant);
const prefix = htmlStr.substr(0, iHtmlStart);
const iHtmlStart_ = serialized.indexOf("<html");
if (iHtmlStart_ < 0) {
return htmlStr;
}
const remaining = serialized.substr(iHtmlStart_);
const newStr = `${prefix}${remaining}`;
// debug(newStr);
return newStr;
};
export function initSessions() {
app.commandLine.appendSwitch("autoplay-policy", "no-user-gesture-required");
Transformers.instance().add(new TransformerHTML(transformerIFrames));
protocol.registerSchemesAsPrivileged([{
privileges: {
allowServiceWorkers: false,
bypassCSP: false,
corsEnabled: true,
secure: true,
standard: true,
stream: true,
supportFetchAPI: true,
},
scheme: THORIUM_READIUM2_ELECTRON_HTTP_PROTOCOL,
}, {
privileges: {
allowServiceWorkers: false,
bypassCSP: false,
corsEnabled: true,
secure: true,
standard: true,
stream: true,
supportFetchAPI: true,
},
scheme: READIUM2_ELECTRON_HTTP_PROTOCOL,
}]);
app.on("ready", async () => {
debug("app ready");
try {
await clearSessions();
} catch (err) {
debug(err);
}
if (session.defaultSession) {
session.defaultSession.protocol.registerStreamProtocol(
THORIUM_READIUM2_ELECTRON_HTTP_PROTOCOL,
streamProtocolHandler);
session.defaultSession.protocol.registerStreamProtocol(
READIUM2_ELECTRON_HTTP_PROTOCOL,
streamProtocolHandlerTunnel);
}
const webViewSession = getWebViewSession();
if (webViewSession) {
webViewSession.protocol.registerStreamProtocol(
THORIUM_READIUM2_ELECTRON_HTTP_PROTOCOL,
streamProtocolHandler);
webViewSession.protocol.registerStreamProtocol(
READIUM2_ELECTRON_HTTP_PROTOCOL,
streamProtocolHandlerTunnel);
webViewSession.setPermissionRequestHandler((wc, permission, callback) => {
debug("setPermissionRequestHandler");
debug(wc.getURL());
debug(permission);
callback(true);
});
}
});
}
interface IPathPublicationMap { [key: string]: R2Publication; }
const _publications: string[] = [];
const _pathPublicationMap: IPathPublicationMap = {};
export function streamerAddPublications(pubs: string[]): string[] {
pubs.forEach((pub) => {
if (_publications.indexOf(pub) < 0) {
_publications.push(pub);
}
});
return pubs.map((pub) => {
const pubid = encodeURIComponent_RFC3986(Buffer.from(pub).toString("base64"));
return `/pub/${pubid}/manifest.json`;
});
}
export function streamerRemovePublications(pubs: string[]): string[] {
pubs.forEach((pub) => {
streamerUncachePublication(pub);
const i = _publications.indexOf(pub);
if (i >= 0) {
_publications.splice(i, 1);
}
});
return pubs.map((pub) => {
const pubid = encodeURIComponent_RFC3986(Buffer.from(pub).toString("base64"));
return `/pub/${pubid}/manifest.json`;
});
}
export async function streamerLoadOrGetCachedPublication(filePath: string): Promise<R2Publication> {
let publication = streamerCachedPublication(filePath);
if (!publication) {
// const fileName = path.basename(pathBase64Str);
// const ext = path.extname(fileName).toLowerCase();
try {
publication = await PublicationParsePromise(filePath);
} catch (err) {
debug(err);
return Promise.reject(err);
}
streamerCachePublication(filePath, publication);
}
// return Promise.resolve(publication);
return publication;
}
export function streamerIsPublicationCached(filePath: string): boolean {
return typeof streamerCachedPublication(filePath) !== "undefined";
}
export function streamerCachedPublication(filePath: string): R2Publication | undefined {
return _pathPublicationMap[filePath];
}
export function streamerCachePublication(filePath: string, pub: R2Publication) {
// TODO: implement LRU caching algorithm? Anything smarter than this will do!
if (!streamerIsPublicationCached(filePath)) {
_pathPublicationMap[filePath] = pub;
}
}
export function streamerUncachePublication(filePath: string) {
if (streamerIsPublicationCached(filePath)) {
const pub = streamerCachedPublication(filePath);
if (pub) {
pub.freeDestroy();
}
_pathPublicationMap[filePath] = undefined;
delete _pathPublicationMap[filePath];
}
}
// export function streamerGetPublications(): string[] {
// return _publications;
// }
// export function streamerUncachePublications() {
// Object.keys(_pathPublicationMap).forEach((filePath) => {
// streamerUncachePublication(filePath);
// });
// } | the_stack |
import React, { useContext, useEffect } from 'react';
import { Box, Text } from 'ink';
import { ExitError } from '@boost/common';
import { env } from '@boost/internal';
import { mockLogger } from '@boost/log/test';
import {
Arg,
Command,
Config,
GlobalOptions,
INTERNAL_OPTIONS,
OptionConfigMap,
Options,
Program,
TaskContext,
UnknownOptionMap,
} from '../src';
import { ProgramContext, useProgram } from '../src/react';
import { MockReadStream, MockWriteStream, runProgram, runTask } from '../src/test';
import { AllPropsCommand } from './__fixtures__/AllPropsCommand';
import { options, params } from './__fixtures__/args';
import { BuildDecoratorCommand } from './__fixtures__/BuildDecoratorCommand';
import { BuildPropsCommand } from './__fixtures__/BuildPropsCommand';
import { ClientDecoratorCommand } from './__fixtures__/ClientDecoratorCommand';
import { Child, GrandChild, Parent } from './__fixtures__/commands';
import { InstallDecoratorCommand } from './__fixtures__/InstallDecoratorCommand';
jest.mock('term-size');
class BoostCommand extends Command {
static override description = 'Description';
static override path = 'boost';
static override allowUnknownOptions = true;
static override allowVariadicParams = true;
run() {
return Promise.resolve();
}
}
class ErrorCommand extends Command {
static override description = 'Description';
static override path = 'boost';
static override allowVariadicParams = true;
run(): Promise<void> {
throw new Error('Broken!');
}
}
class StringCommand extends Command {
static override description = 'Description';
static override path = 'string';
run() {
return 'Hello!';
}
}
class ComponentCommand extends Command {
static override description = 'Description';
static override path = 'comp';
run() {
return (
<Box>
<Text>Hello!</Text>
</Box>
);
}
}
describe('<Program />', () => {
let program: Program;
let stderr: MockWriteStream;
let stdout: MockWriteStream;
let stdin: MockReadStream;
function createProgram(append?: boolean) {
stderr = new MockWriteStream(append);
stdout = new MockWriteStream(append);
stdin = new MockReadStream();
program = new Program(
{
bin: 'boost',
name: 'Boost',
version: '1.2.3',
},
{
stderr: stderr as unknown as NodeJS.WriteStream,
stdout: stdout as unknown as NodeJS.WriteStream,
stdin: stdin as unknown as NodeJS.ReadStream,
},
);
}
beforeEach(() => {
createProgram();
});
it('errors if bin is not kebab case', () => {
expect(
() =>
new Program({
bin: 'boostRocketGo_go',
name: 'Boost',
version: '1.2.3',
}),
).toThrowErrorMatchingSnapshot();
});
it('errors for invalid version format', () => {
expect(
() =>
new Program({
bin: 'boost',
name: 'Boost',
version: 'a.b12.323',
}),
).toThrowErrorMatchingSnapshot();
});
describe('bootstrap', () => {
it('can pass a boostrap function when running', async () => {
const order: string[] = [];
class BootstrapCommand extends Command {
static override description = 'Description';
static override path = 'boot';
run() {
order.push('second');
}
}
program.register(new BootstrapCommand());
await program.run(['boot'], async () => {
await new Promise((resolve) => {
setTimeout(() => {
order.push('first');
resolve(undefined);
}, 150);
});
});
expect(order).toEqual(['first', 'second']);
});
});
describe('exit', () => {
it('can exit', () => {
expect(() => {
program.exit();
}).toThrow(new ExitError('', 0));
});
it('can exit with a string', () => {
expect(() => {
program.exit('Oops');
}).toThrow(new ExitError('Oops', 1));
});
it('can exit with an error', () => {
expect(() => {
program.exit(new Error('Oops'));
}).toThrow(new ExitError('Oops', 1));
});
it('can exit with an exit error', () => {
expect(() => {
program.exit(new ExitError('Oops', 123));
}).toThrow(new ExitError('Oops', 123));
});
it('can exit with a custom code', () => {
expect(() => {
program.exit('Oops', 10);
}).toThrow(new ExitError('Oops', 10));
});
it('emits `onExit` event', () => {
const spy = jest.fn();
program.onExit.listen(spy);
try {
program.exit('Oops', 10);
} catch {
// Ignore
}
expect(spy).toHaveBeenCalledWith('Oops', 10);
});
function ExitComponent({ error }: { error: boolean }) {
const { exit } = useProgram();
useEffect(() => {
if (error) {
exit('Fail!');
} else {
exit();
}
}, [error, exit]);
return (
<Box>
<Text>Content</Text>
</Box>
);
}
class ExitCommand extends Command {
static override description = 'Description';
static override path = 'boost';
static override options = {
component: {
description: 'Render component',
type: 'boolean',
},
error: {
description: 'Error',
type: 'boolean',
},
} as const;
component = false;
error = false;
run() {
this.log('Before');
if (this.component) {
return <ExitComponent error={this.error} />;
}
if (this.error) {
this.exit('Fail!');
} else {
this.exit();
}
return 'After';
}
}
it('renders a zero exit', async () => {
program.default(new ExitCommand());
const { code, output } = await runProgram(program, []);
expect(output).toMatchSnapshot();
expect(code).toBe(0);
});
it('renders a zero exit with a component', async () => {
program.default(new ExitCommand());
const { code, output } = await runProgram(program, ['--component']);
expect(output).toMatchSnapshot();
expect(code).toBe(0);
});
it('renders a non-zero exit', async () => {
program.default(new ExitCommand());
const { code, output } = await runProgram(program, ['--error']);
expect(output).toMatchSnapshot();
expect(code).toBe(1);
});
it('renders a non-zero exit with component', async () => {
program.default(new ExitCommand());
const { code, output } = await runProgram(program, ['--error', '--component']);
expect(output).toMatchSnapshot();
// This should be 1 but waitUntilExit() doesnt get called in tests
// which is what would set the code via an ExitError.
expect(code).toBe(0);
});
});
describe('error', () => {
function ErrorComponent() {
throw new Error('Fail from component');
}
class Error2Command extends Command {
static override description = 'Description';
static override path = 'boost';
static override options = {
component: {
description: 'Render component',
type: 'boolean',
},
} as const;
component = false;
run() {
this.log('Before');
if (this.component) {
// @ts-expect-error JSX error
return <ErrorComponent />;
}
throw new Error('Fail');
}
}
it('renders a thrown error', async () => {
program.default(new Error2Command());
const { code, output } = await runProgram(program, []);
expect(output).toMatchSnapshot();
expect(code).toBe(1);
});
});
describe('commands', () => {
it('registers and returns a command with path', () => {
const command = new BuildDecoratorCommand();
program.register(command);
expect(program.getCommand('build')).toBe(command);
});
it('returns an aliased command', () => {
const command = new BuildDecoratorCommand();
program.register(command);
expect(program.getCommand('compile')).toBe(command);
});
it('errors if command with same path is registered', () => {
const command = new BuildDecoratorCommand();
expect(() => {
program.register(command);
program.register(command);
}).toThrow('A command already exists with the canonical path "build".');
});
it('errors for invalid type', () => {
expect(() => {
// @ts-expect-error Invalid type
program.register(123);
}).toThrow('Invalid command type being registered.');
});
it('returns null if command does not exist', () => {
expect(program.getCommand('unknown')).toBeNull();
});
it('returns null if nested command does not exist', () => {
const parent = new Parent();
const child = new Child();
parent.register(child);
program.register(parent);
expect(program.getCommand('parent:child:grandchild')).toBeNull();
});
it('returns nested commands by drilling down paths', () => {
const parent = new Parent();
const child = new Child();
const grand = new GrandChild();
child.register(grand);
parent.register(child);
program.register(parent);
expect(program.getCommand('parent:child:grandchild')).toBe(grand);
});
it('returns nested alias commands', () => {
const command = new ClientDecoratorCommand();
program.register(command);
expect(program.getCommand('client:compile')).not.toBeNull();
});
it('registers a default command', () => {
const command = new BuildDecoratorCommand();
program.default(command);
// @ts-expect-error Allow access
expect(program.standAlone).toBe('build');
});
it('errors if adding a command and a default is registered', () => {
expect(() => {
program.default(new Parent());
program.register(new Child());
}).toThrow(
'A default command has been registered. Cannot mix default and non-default commands.',
);
});
it('errors if adding a default and commands have been registered', () => {
expect(() => {
program.register(new Child());
program.default(new Parent());
}).toThrow(
'Other commands have been registered. Cannot mix default and non-default commands.',
);
});
it('returns all command paths', () => {
program.register(new BuildDecoratorCommand());
program.register(new InstallDecoratorCommand());
expect(program.getCommandPaths()).toEqual(['build', 'install', 'compile']);
});
it('returns all command paths, including nested', () => {
program.register(new ClientDecoratorCommand());
expect(program.getCommandPaths()).toEqual([
'client',
'client:build',
'client:install',
'client:uninstall',
'client:compile',
'client:up',
'client:down',
]);
});
it('emits `onBeforeRegister` and `onAfterRegister` events', () => {
const cmd = new ClientDecoratorCommand();
const beforeSpy = jest.fn();
const afterSpy = jest.fn();
program.onBeforeRegister.listen(beforeSpy);
program.onAfterRegister.listen(afterSpy);
program.register(cmd);
expect(beforeSpy).toHaveBeenCalledWith('client', cmd);
expect(afterSpy).toHaveBeenCalledWith('client', cmd);
});
it('emits `onBeforeRegister` and `onAfterRegister` events for default command', () => {
const cmd = new ClientDecoratorCommand();
const beforeSpy = jest.fn();
const afterSpy = jest.fn();
program.onBeforeRegister.listen(beforeSpy);
program.onAfterRegister.listen(afterSpy);
program.default(cmd);
expect(beforeSpy).toHaveBeenCalledWith('client', cmd);
expect(afterSpy).toHaveBeenCalledWith('client', cmd);
});
});
describe('version', () => {
it('outputs version when `--version` is passed', async () => {
program.default(new BoostCommand());
const { code, output } = await runProgram(program, ['--version']);
expect(output).toMatchSnapshot();
expect(code).toBe(0);
});
it('outputs version when `-v` is passed', async () => {
program.default(new BoostCommand());
const { code, output } = await runProgram(program, ['-v']);
expect(output).toMatchSnapshot();
expect(code).toBe(0);
});
});
describe('locale', () => {
it('errors for invalid `--locale`', async () => {
program.default(new BuildDecoratorCommand());
const { code, output } = await runProgram(program, ['--locale', 'wtf']);
expect(output).toMatchSnapshot();
expect(code).toBe(1);
});
});
describe('help', () => {
class HelpCommand extends Command {
static override description = 'Description';
static override path = 'boost';
static override options = { ...options };
static override params = [...params];
run() {
return Promise.resolve();
}
}
it('outputs help when `--help` is passed', async () => {
program.default(new HelpCommand());
const { code, output } = await runProgram(program, ['--help']);
expect(output).toMatchSnapshot();
expect(code).toBe(0);
});
it('outputs help when `-h` is passed', async () => {
program.default(new HelpCommand());
const { code, output } = await runProgram(program, ['-h']);
expect(output).toMatchSnapshot();
expect(code).toBe(0);
});
it('outputs help for a specific command', async () => {
program.register(new BuildDecoratorCommand());
program.register(new InstallDecoratorCommand());
const { output: o1 } = await runProgram(program, ['build', '-h']);
expect(o1).toMatchSnapshot();
const { output: o2 } = await runProgram(program, ['install', '--help']);
expect(o2).toMatchSnapshot();
});
it('outputs help for a nested sub-command', async () => {
program.register(new ClientDecoratorCommand());
const { output: o1 } = await runProgram(program, ['client:build', '-h']);
expect(o1).toMatchSnapshot();
const { output: o2 } = await runProgram(program, ['client:install', '--help']);
expect(o2).toMatchSnapshot();
const { output: o3 } = await runProgram(program, ['client', '--help']);
expect(o3).toMatchSnapshot();
});
it('outputs help for an aliased command', async () => {
program.register(new BuildDecoratorCommand());
const { output: o1 } = await runProgram(program, ['build', '-h']);
expect(o1).toMatchSnapshot();
const { output: o2 } = await runProgram(program, ['compile', '--help']);
expect(o2).toMatchSnapshot();
});
it('emits `onHelp` event', async () => {
const spy = jest.fn();
program.onHelp.listen(spy);
program.register(new HelpCommand());
await runProgram(program, ['boost', '--help']);
expect(spy).toHaveBeenCalled();
});
it('emits `onHelp` event for default', async () => {
const spy = jest.fn();
program.onHelp.listen(spy);
program.default(new HelpCommand());
await runProgram(program, ['--help']);
expect(spy).toHaveBeenCalled();
});
});
describe('default command', () => {
it('executes default when no args passed', async () => {
program.default(new BuildDecoratorCommand());
const { code, output } = await runProgram(program, []);
expect(output).toMatchSnapshot();
expect(code).toBe(0);
});
it('renders commands when no args passed', async () => {
program.register(new BuildDecoratorCommand());
program.register(new InstallDecoratorCommand());
const { code, output } = await runProgram(program, []);
expect(output).toMatchSnapshot();
expect(code).toBe(0);
});
});
describe('failure', () => {
it('renders when no commands have been registered', async () => {
const { code, output } = await runProgram(program, ['build']);
expect(output).toMatchSnapshot();
expect(code).toBe(1);
});
it('renders when invalid command name passed', async () => {
program.register(new BuildDecoratorCommand());
program.register(new InstallDecoratorCommand());
const { code, output } = await runProgram(program, ['prune']);
expect(output).toMatchSnapshot();
expect(code).toBe(1);
});
it('renders when misspelt command name passed', async () => {
program.register(new BuildDecoratorCommand());
program.register(new InstallDecoratorCommand());
const { code, output } = await runProgram(program, ['buld']);
expect(output).toMatchSnapshot();
expect(code).toBe(1);
});
it('renders when no commands could be found', async () => {
program.register(new BuildDecoratorCommand());
program.register(new InstallDecoratorCommand());
const { code, output } = await runProgram(program, ['--locale=en']);
expect(output).toMatchSnapshot();
expect(code).toBe(1);
});
it('renders when args parsing fails', async () => {
program.default(new ComponentCommand());
const { code, output } = await runProgram(program, ['--foo']);
expect(output).toMatchSnapshot();
expect(code).toBe(1);
});
it('renders if an error is thrown', async () => {
program.register(new ErrorCommand());
const { code, output } = await runProgram(program, ['boost']);
expect(output).toMatchSnapshot();
expect(code).toBe(1);
});
it('renders with custom exit error', async () => {
class ExitCommand extends Command {
static override description = 'Description';
static override path = 'boost';
run() {
this.exit('Oops', 123);
return Promise.resolve();
}
}
program.register(new ExitCommand());
const { code, output } = await runProgram(program, ['boost']);
expect(output).toMatchSnapshot();
expect(code).toBe(123);
});
it('emits `onBeforeRun` and `onAfterRun` events', async () => {
const beforeSpy = jest.fn();
const afterSpy = jest.fn();
program.onBeforeRun.listen(beforeSpy);
program.onAfterRun.listen(afterSpy);
program.register(new ErrorCommand());
await runProgram(program, ['boost']);
expect(beforeSpy).toHaveBeenCalledWith(['boost']);
expect(afterSpy).toHaveBeenCalledWith(new Error('Broken!'));
});
it('emits `onCommandNotFound` event', async () => {
const spy = jest.fn();
program.onCommandNotFound.listen(spy);
program.register(new BuildDecoratorCommand());
await runProgram(program, ['install', 'foo', 'bar']);
expect(spy).toHaveBeenCalledWith(['install', 'foo', 'bar'], 'install');
});
});
describe('success', () => {
beforeEach(() => {
env('CLI_TEST_FAIL_HARD', 'true');
});
afterEach(() => {
env('CLI_TEST_FAIL_HARD', null);
});
it('sets rest args to the rest command property', async () => {
const command = new BuildDecoratorCommand();
program.register(command);
await runProgram(program, ['build', '-S', './src', '--', 'foo', 'bar', '--baz', '-f']);
expect(command.rest).toEqual(['foo', 'bar', '--baz', '-f']);
});
it('sets options as command properties (declarative)', async () => {
const command = new BuildDecoratorCommand();
program.register(command);
await runProgram(program, ['build', '-S', './source', '-D', './library']);
expect(command.dst).toBe('./library');
expect(command.help).toBe(false);
expect(command.locale).toBe('en');
expect(command.src).toBe('./source');
expect(command.version).toBe(false);
});
it('sets options as command properties (imperative)', async () => {
const command = new BuildPropsCommand();
program.register(command);
await runProgram(program, ['build', '-S', './source']);
expect(command.dst).toBe('');
expect(command.help).toBe(false);
expect(command.locale).toBe('en');
expect(command.src).toBe('./source');
expect(command.version).toBe(false);
});
it('passes params to run method', async () => {
const command = new AllPropsCommand();
const spy = jest.spyOn(command, 'run');
program.default(command);
await runProgram(program, ['-F', 'foo', 'true', '123']);
expect(spy).toHaveBeenCalledWith('foo', true, 123);
});
it('can return nothing', async () => {
class NoneCommand extends Command {
static override description = 'Description';
static override path = 'none';
run() {}
}
program.register(new NoneCommand());
const { output } = await runProgram(program, ['none']);
expect(output).toBe('');
});
it('can return a string that writes directly to stream', async () => {
program.register(new StringCommand());
const { output } = await runProgram(program, ['string']);
expect(output).toBe('Hello!\n');
});
it('can return an element that writes with ink', async () => {
program.register(new ComponentCommand());
const { output } = await runProgram(program, ['comp']);
expect(output).toMatchSnapshot();
});
it('can run command using aliased path', async () => {
const command = new BuildDecoratorCommand();
const spy = jest.fn();
program.onCommandFound.listen(spy);
program.register(command);
const { code } = await runProgram(program, ['compile', '-S', './src']);
expect(code).toBe(0);
expect(spy).toHaveBeenCalledWith(['compile', '-S', './src'], 'compile', command);
});
it('emits `onBeforeRun` and `onAfterRun` events', async () => {
const beforeSpy = jest.fn();
const afterSpy = jest.fn();
program.onBeforeRun.listen(beforeSpy);
program.onAfterRun.listen(afterSpy);
program.register(new BoostCommand());
await runProgram(program, ['boost', 'foo', 'bar']);
expect(beforeSpy).toHaveBeenCalledWith(['boost', 'foo', 'bar']);
expect(afterSpy).toHaveBeenCalled();
});
it('emits `onCommandFound` event', async () => {
const spy = jest.fn();
const cmd = new BoostCommand();
program.onCommandFound.listen(spy);
program.register(cmd);
await runProgram(program, ['boost', 'foo', 'bar']);
expect(spy).toHaveBeenCalledWith(['boost', 'foo', 'bar'], 'boost', cmd);
});
it('emits `onBeforeRender` and `onAfterRender` events for components', async () => {
const beforeSpy = jest.fn();
const afterSpy = jest.fn();
program.onBeforeRender.listen(beforeSpy);
program.onAfterRender.listen(afterSpy);
program.default(new ComponentCommand());
await runProgram(program, []);
expect(beforeSpy).toHaveBeenCalledWith(
<Box>
<Text>Hello!</Text>
</Box>,
);
expect(afterSpy).toHaveBeenCalled();
});
});
describe('option defaults', () => {
class DeclCommand extends Command {
static override description = 'Description';
static override path = 'cmd';
@Arg.Number('Number')
numNoDefault: number = 0;
@Arg.Number('Number (default)')
numWithDefault: number = 123;
@Arg.Flag('Flag (false)')
flagFalse: boolean = false;
@Arg.Flag('Flag (true)')
flagTrue: boolean = true;
@Arg.String('String')
strNoDefault: string = '';
@Arg.String('String (default)')
strWithDefault: string = 'foo';
@Arg.Numbers('Numbers')
numsNoDefault: number[] = [];
@Arg.Numbers('Numbers (default)')
numsWithDefault: number[] = [1, 2, 3];
@Arg.Strings('Strings')
strsNoDefault: string[] = [];
@Arg.Strings('Strings (default)')
strsWithDefault: string[] = ['a', 'b', 'c'];
run() {}
}
class ImpCommand extends Command {
static override description = 'Description';
static override path = 'cmd';
static override options: OptionConfigMap = {
numNoDefault: {
description: 'Number',
type: 'number',
},
numWithDefault: {
default: 123,
description: 'Number (default)',
type: 'number',
},
flagFalse: {
description: 'Flag (false)',
type: 'boolean',
},
flagTrue: {
// Use property
// default: true,
description: 'Flag (true)',
type: 'boolean',
},
strNoDefault: {
description: 'String',
type: 'string',
},
strWithDefault: {
// Also with property
default: 'bar',
description: 'String (default)',
type: 'string',
},
numsNoDefault: {
description: 'Numbers',
multiple: true,
type: 'number',
},
numsWithDefault: {
default: [1, 2, 3],
description: 'Numbers (default)',
multiple: true,
type: 'number',
},
strsNoDefault: {
description: 'Strings',
multiple: true,
type: 'string',
},
strsWithDefault: {
description: 'Strings (default)',
multiple: true,
type: 'string',
},
};
numNoDefault!: number;
numWithDefault!: number;
flagFalse: boolean = false;
flagTrue: boolean = true;
strNoDefault: string = '';
strWithDefault: string = 'foo';
numsNoDefault: number[] = [];
numsWithDefault!: number[]; // Use config default
strsNoDefault!: string[]; // None set in either place
strsWithDefault: string[] = ['a', 'b', 'c'];
run() {}
}
const runners = {
declarative: () => new DeclCommand(),
imperative: () => new ImpCommand(),
};
Object.entries(runners).forEach(([type, factory]) => {
describe(`${type}`, () => {
let command: ImpCommand;
beforeEach(() => {
command = factory();
env('CLI_TEST_FAIL_HARD', 'true');
});
afterEach(() => {
env('CLI_TEST_FAIL_HARD', null);
});
it('returns number option if defined', async () => {
program.register(command);
await runProgram(program, ['cmd', '--numNoDefault', '456', '--numWithDefault=789']);
expect(command.numNoDefault).toBe(456);
expect(command.numWithDefault).toBe(789);
});
it('returns default number option if not defined', async () => {
program.register(command);
await runProgram(program, ['cmd']);
expect(command.numNoDefault).toBe(0);
expect(command.numWithDefault).toBe(123);
});
it('returns boolean option if defined', async () => {
program.register(command);
await runProgram(program, ['cmd', '--flagFalse', '--no-flagTrue']);
expect(command.flagFalse).toBe(true);
expect(command.flagTrue).toBe(false);
});
it('returns default boolean option if not defined', async () => {
program.register(command);
await runProgram(program, ['cmd']);
expect(command.flagFalse).toBe(false);
expect(command.flagTrue).toBe(true);
});
it('returns string option if defined', async () => {
program.register(command);
await runProgram(program, ['cmd', '--strNoDefault', 'bar', '--strWithDefault=baz']);
expect(command.strNoDefault).toBe('bar');
expect(command.strWithDefault).toBe('baz');
});
it('returns default string option if not defined', async () => {
program.register(command);
await runProgram(program, ['cmd']);
expect(command.strNoDefault).toBe('');
expect(command.strWithDefault).toBe('foo');
});
it('returns numbers option if defined', async () => {
program.register(command);
await runProgram(program, [
'cmd',
'--numsNoDefault',
'4',
'5',
'6',
'--numsWithDefault',
'7',
'8',
'9',
]);
expect(command.numsNoDefault).toEqual([4, 5, 6]);
expect(command.numsWithDefault).toEqual([7, 8, 9]);
});
it('returns default numbers option if not defined', async () => {
program.register(command);
await runProgram(program, ['cmd']);
expect(command.numsNoDefault).toEqual([]);
expect(command.numsWithDefault).toEqual([1, 2, 3]);
});
it('returns strings option if defined', async () => {
program.register(command);
await runProgram(program, [
'cmd',
'--strsNoDefault',
'4',
'5',
'6',
'--strsWithDefault',
'foo',
'bar',
]);
expect(command.strsNoDefault).toEqual(['4', '5', '6']);
expect(command.strsWithDefault).toEqual(['foo', 'bar']);
});
it('returns strings numbers option if not defined', async () => {
program.register(command);
await runProgram(program, ['cmd']);
expect(command.strsNoDefault).toEqual([]);
expect(command.strsWithDefault).toEqual(['a', 'b', 'c']);
});
});
});
});
describe('logging', () => {
function Log() {
const ctx = useContext(ProgramContext);
ctx.log('Component log');
ctx.log.error('Component error');
return (
<Box>
<Text>Returned from component!</Text>
</Box>
);
}
class LogCommand extends Command {
static override description = 'Description';
static override path = 'log';
static override options: OptionConfigMap = {
component: {
description: 'With component',
type: 'boolean',
},
};
component = false;
run() {
this.log('Log');
this.log.debug('Debug');
this.log.warn('Warn');
this.log.error('Error');
this.log.trace('Trace');
this.log.info('Info');
if (this.component) {
return <Log />;
}
return 'Returned from command!';
}
}
beforeEach(() => {
stdout.append = true;
stderr.append = true;
});
it('handles logging when rendering a component', async () => {
const logSpy = jest.spyOn(stdout, 'write');
const errSpy = jest.spyOn(stderr, 'write');
program.register(new LogCommand());
const { code, output } = await runProgram(program, ['log', '--component']);
expect(logSpy).toHaveBeenCalled();
expect(errSpy).toHaveBeenCalled();
expect(output).toMatchSnapshot();
expect(code).toBe(0);
logSpy.mockRestore();
errSpy.mockRestore();
});
it('handles logging when returning a string', async () => {
const logSpy = jest.spyOn(stdout, 'write');
const errSpy = jest.spyOn(stderr, 'write');
program.register(new LogCommand());
const { code, output } = await runProgram(program, ['log']);
expect(logSpy).toHaveBeenCalled();
expect(errSpy).toHaveBeenCalled();
expect(output).toMatchSnapshot();
expect(code).toBe(0);
logSpy.mockRestore();
errSpy.mockRestore();
});
});
describe('middleware', () => {
it('errors if not a function', () => {
expect(() => {
// @ts-expect-error Invalid type
program.middleware(123);
}).toThrow('Middleware must be a function.');
});
it('removes node and binary from `process.argv`', async () => {
const command = new BuildDecoratorCommand();
program.register(command);
const { code } = await runProgram(program, [
'/nvm/12.16.1/bin/node',
'/boost/bin.js',
'build',
'-S',
'./src',
]);
expect(code).toBe(0);
});
it('can modify argv before parsing', async () => {
const command = new BoostCommand();
program.default(command);
program.middleware((argv, next) => {
argv.push('--', 'foo', 'bar');
return next(argv);
});
await runProgram(program, ['--opt', 'value']);
expect(command.unknown).toEqual({ opt: 'value' });
expect(command.rest).toEqual(['foo', 'bar']);
});
it('can modify argv before parsing using promises', async () => {
const command = new BoostCommand();
program.default(command);
program.middleware((argv, next) =>
Promise.resolve()
.then(() => [...argv, '--opt', 'new value'])
.then(next),
);
await runProgram(program, ['--opt', 'value']);
expect(command.unknown).toEqual({ opt: 'new value' });
});
it('can modify args after parsing', async () => {
const command = new BoostCommand();
program.default(command);
program.middleware(async (argv, next) => {
const args = await next(argv);
args.options.locale = 'fr';
args.unknown.key = 'value';
return args;
});
await runProgram(program, ['--opt', 'value']);
expect(command.unknown).toEqual({ opt: 'value', key: 'value' });
expect(command[INTERNAL_OPTIONS]).toEqual({
help: false,
locale: 'fr',
version: false,
});
});
});
describe('categories', () => {
it('applies categories to index help', async () => {
@Config('foo', 'Description', { category: 'bottom' })
class FooCommand extends Command {
run() {}
}
@Config('bar', 'Description', { category: 'top' })
class BarCommand extends Command {
run() {}
}
@Config('baz', 'Description', { category: 'global' })
class BazCommand extends Command {
run() {}
}
@Config('qux', 'Description')
class QuxCommand extends Command {
run() {}
}
program.categories({
top: { name: 'Top', weight: 50 },
bottom: 'Bottom',
});
program.register(new FooCommand());
program.register(new BarCommand());
program.register(new BazCommand());
program.register(new QuxCommand());
const { output } = await runProgram(program, ['--help']);
expect(output).toMatchSnapshot();
});
});
describe('nested programs', () => {
class NestedProgramCommand extends Command {
static override description = 'Description';
static override path = 'prog';
async run() {
this.log('Before run');
await this.runProgram(['client:install', 'foo', '--save']);
this.log('After run');
return 'Return';
}
}
class NestedErrorCommand extends Command {
static override description = 'Description';
static override path = 'prog-error';
async run() {
await this.runProgram(['prog-error-inner']);
}
}
class NestedErrorInnerCommand extends Command {
static override description = 'Description';
static override path = 'prog-error-inner';
run() {
throw new Error('Bubbles');
}
}
it('can run a program within a command', async () => {
stdout.append = true;
program.register(new NestedProgramCommand()).register(new ClientDecoratorCommand());
const { output } = await runProgram(program, ['prog']);
expect(output).toMatchSnapshot();
});
it('errors if no program instance', () => {
const command = new NestedProgramCommand();
expect(() => command.runProgram(['foo'])).toThrow(
'No program found. Must be ran within the context of a parent program.',
);
});
it('bubbles up errors', async () => {
program.register(new NestedErrorCommand()).register(new NestedErrorInnerCommand());
const { output } = await runProgram(program, ['prog-error']);
expect(output).toMatchSnapshot();
});
});
describe('tasks', () => {
// Test logging and options
function syncTask(this: TaskContext, a: number, b: number) {
this.log('Hi');
this.log.error('Bye');
return a + b;
}
function nestedSyncTask(this: TaskContext, msg: string) {
this.log(msg);
this.log(String(this.runTask(syncTask, 1, 1)));
}
// Test misc args
interface AsyncOptions extends GlobalOptions {
value: string;
}
async function asyncTask(this: TaskContext<AsyncOptions>, a: string, b: string) {
this.unknown.foo = 'true';
const c = await Promise.resolve(this.value);
this.rest.push('foo');
return c + a + b.toUpperCase();
}
beforeEach(() => {
stdout.append = true;
});
it('runs a sync task correctly', async () => {
class SyncTaskCommand extends Command {
static override description = 'Description';
static override path = 'task';
run() {
return String(this.runTask(syncTask, 10, 5));
}
}
program.register(new SyncTaskCommand());
const { output } = await runProgram(program, ['task']);
expect(output).toMatchSnapshot();
});
it('runs a sync task correctly (using test util)', async () => {
const log = mockLogger();
const output = await runTask(syncTask, [10, 5], { log });
expect(output).toBe(15);
expect(log).toHaveBeenCalledWith('Hi');
expect(log.error).toHaveBeenCalledWith('Bye');
});
it('runs an async task correctly', async () => {
class AsyncTaskCommand extends Command<AsyncOptions> {
static override description = 'Description';
static override path = 'task';
static override options: Options<AsyncOptions> = {
value: {
description: 'Description',
type: 'string',
},
};
async run() {
const value = await this.runTask(asyncTask, 'foo', 'bar');
return value;
}
}
const command = new AsyncTaskCommand();
program.register(command);
const { output } = await runProgram(program, ['task', '--value', 'baz']);
expect(output).toMatchSnapshot();
expect(command.unknown.foo).toBe('true');
expect(command.rest).toEqual(['foo']);
});
it('runs an async task correctly (using test util)', async () => {
const unknown: UnknownOptionMap = {};
const rest: string[] = [];
const output = await runTask(asyncTask, ['foo', 'bar'], { unknown, rest, value: 'baz' });
expect(output).toBe('bazfooBAR');
expect(unknown.foo).toBe('true');
expect(rest).toEqual(['foo']);
});
it('can run a task within a task', async () => {
class NestedSyncTaskCommand extends Command {
static override description = 'Description';
static override path = 'task';
run() {
this.runTask(nestedSyncTask, 'Test');
}
}
program.register(new NestedSyncTaskCommand());
const { output } = await runProgram(program, ['task']);
expect(output).toMatchSnapshot();
});
});
describe('components', () => {
function Comp({ children }: { children: string }) {
return (
<Box>
<Text>{children}</Text>
</Box>
);
}
class CompCommand extends Command {
static override description = 'Description';
static override path = 'comp';
static override options = {};
static override params = [];
async run() {
this.log('Before');
await this.render(<Comp>Foo</Comp>);
this.log.info('Middle');
await this.render(<Comp>Bar</Comp>);
this.log.error('After');
return <Comp>Baz</Comp>;
}
}
beforeEach(() => {
createProgram(true);
});
it('renders and outputs multiple component renders', async () => {
program.default(new CompCommand());
const { code, output } = await runProgram(program, ['comp']);
expect(output).toMatchSnapshot();
expect(code).toBe(0);
});
});
}); | the_stack |
import classNames from 'classnames'
import ArrowLeftBoldIcon from 'mdi-react/ArrowLeftBoldIcon'
import ArrowRightBoldIcon from 'mdi-react/ArrowRightBoldIcon'
import ErrorIcon from 'mdi-react/ErrorIcon'
import WarningIcon from 'mdi-react/WarningIcon'
import React, { useCallback, useMemo } from 'react'
import { RouteComponentProps } from 'react-router'
import { Observable, of, timer } from 'rxjs'
import { catchError, concatMap, delay, map, repeatWhen, takeWhile } from 'rxjs/operators'
import { parse as _parseVersion, SemVer } from 'semver'
import { LoadingSpinner } from '@sourcegraph/react-loading-spinner'
import { TelemetryProps } from '@sourcegraph/shared/src/telemetry/telemetryService'
import { asError, ErrorLike, isErrorLike } from '@sourcegraph/shared/src/util/errors'
import { useObservable } from '@sourcegraph/shared/src/util/useObservable'
import { ErrorAlert } from '../components/alerts'
import { Collapsible } from '../components/Collapsible'
import { FilteredConnection, FilteredConnectionFilter, Connection } from '../components/FilteredConnection'
import { PageTitle } from '../components/PageTitle'
import { Timestamp } from '../components/time/Timestamp'
import { OutOfBandMigrationFields } from '../graphql-operations'
import {
fetchAllOutOfBandMigrations as defaultFetchAllMigrations,
fetchSiteUpdateCheck as defaultFetchSiteUpdateCheck,
} from './backend'
import styles from './SiteAdminMigrationsPage.module.scss'
export interface SiteAdminMigrationsPageProps extends RouteComponentProps<{}>, TelemetryProps {
fetchAllMigrations?: typeof defaultFetchAllMigrations
fetchSiteUpdateCheck?: () => Observable<{ productVersion: string }>
now?: () => Date
}
const filters: FilteredConnectionFilter[] = [
{
id: 'filters',
label: 'Migration state',
type: 'select',
values: [
{
label: 'All',
value: 'all',
tooltip: 'Show all migrations',
args: {},
},
{
label: 'Pending',
value: 'pending',
tooltip: 'Show pending migrations',
args: { completed: false },
},
{
label: 'Completed',
value: 'completed',
tooltip: 'Show completed migrations',
args: { completed: true },
},
],
},
]
/* How frequently to refresh data from the API. */
const REFRESH_INTERVAL_MS = 5000
/* How many (minor) versions we can upgrade at once. */
const UPGRADE_RANGE = 1
/* How many (minor) versions we can downgrade at once. */
const DOWNGRADE_RANGE = 1
export const SiteAdminMigrationsPage: React.FunctionComponent<SiteAdminMigrationsPageProps> = ({
fetchAllMigrations = defaultFetchAllMigrations,
fetchSiteUpdateCheck = defaultFetchSiteUpdateCheck,
now,
telemetryService,
...props
}) => {
const migrationsOrError = useObservable(
useMemo(
() =>
timer(0, REFRESH_INTERVAL_MS, undefined).pipe(
concatMap(() =>
fetchAllMigrations().pipe(
catchError((error): [ErrorLike] => [asError(error)]),
repeatWhen(observable => observable.pipe(delay(REFRESH_INTERVAL_MS)))
)
),
takeWhile(() => true, true)
),
[fetchAllMigrations]
)
)
const queryMigrations = useCallback(
({
query,
completed,
}: {
query?: string
completed?: boolean
}): Observable<Connection<OutOfBandMigrationFields>> => {
if (isErrorLike(migrationsOrError) || migrationsOrError === undefined) {
return of({ nodes: [] })
}
return of({
nodes: migrationsOrError.filter(
migration =>
(completed === undefined || completed === isComplete(migration)) &&
(!query || matchesQuery(migration, query))
),
totalCount: migrationsOrError.length,
pageInfo: { hasNextPage: false },
})
},
[migrationsOrError]
)
return (
<div className="site-admin-migrations-page">
{isErrorLike(migrationsOrError) ? (
<ErrorAlert prefix="Error loading out of band migrations" error={migrationsOrError} />
) : migrationsOrError === undefined ? (
<LoadingSpinner className="icon-inline" />
) : (
<>
<PageTitle title="Out of band migrations - Admin" />
<h2>Out-of-band migrations</h2>
<p>
Out-of-band migrations run in the background of the Sourcegraph instance convert data from an
old format into a new format. Consult this page prior to upgrading your Sourcegraph instance to
ensure that all expected migrations have completed.
</p>
<MigrationBanners migrations={migrationsOrError} fetchSiteUpdateCheck={fetchSiteUpdateCheck} />
<div className="list-group">
<FilteredConnection<OutOfBandMigrationFields, Omit<MigrationNodeProps, 'node'>>
listComponent="div"
listClassName={classNames('mb-3', styles.migrationsGrid)}
noun="migration"
pluralNoun="migrations"
queryConnection={queryMigrations}
nodeComponent={MigrationNode}
nodeComponentProps={{ now }}
history={props.history}
location={props.location}
filters={filters}
/>
</div>
</>
)}
</div>
)
}
interface MigrationBannersProps {
migrations: OutOfBandMigrationFields[]
fetchSiteUpdateCheck?: () => Observable<{ productVersion: string }>
}
const MigrationBanners: React.FunctionComponent<MigrationBannersProps> = ({
migrations,
fetchSiteUpdateCheck = defaultFetchSiteUpdateCheck,
}) => {
const productVersion = useObservable(
useMemo(() => fetchSiteUpdateCheck().pipe(map(site => parseVersion(site.productVersion))), [
fetchSiteUpdateCheck,
])
)
if (!productVersion) {
return <></>
}
const nextVersion = parseVersion(`${productVersion.major}.${productVersion.minor + UPGRADE_RANGE}.0`)
const previousVersion = parseVersion(`${productVersion.major}.${productVersion.minor - DOWNGRADE_RANGE}.0`)
const invalidMigrations = migrationsInvalidForVersion(migrations, productVersion)
const invalidMigrationsAfterUpgrade = migrationsInvalidForVersion(migrations, nextVersion)
const invalidMigrationsAfterDowngrade = migrationsInvalidForVersion(migrations, previousVersion)
if (invalidMigrations.length > 0) {
return <MigrationInvalidBanner migrations={invalidMigrations} />
}
return (
<>
{invalidMigrationsAfterUpgrade.length > 0 && (
<MigrationUpgradeWarningBanner migrations={invalidMigrationsAfterUpgrade} />
)}
{invalidMigrationsAfterDowngrade.length > 0 && (
<MigrationDowngradeWarningBanner migrations={invalidMigrationsAfterDowngrade} />
)}
</>
)
}
interface MigrationInvalidBannerProps {
migrations: OutOfBandMigrationFields[]
}
const MigrationInvalidBanner: React.FunctionComponent<MigrationInvalidBannerProps> = ({ migrations }) => (
<div className="alert alert-danger">
<p>
<ErrorIcon className="icon-inline mr-2" />
<strong>Contact support.</strong> The following migrations are not in the expected state. You have partially
migrated or un-migrated data in a format that is incompatible with the currently deployed version of
Sourcegraph.{' '}
<strong>Continuing to run your instance in this state will result in errors and possible data loss.</strong>
</p>
<ul className="mb-0">
{migrations.map(migration => (
<li key={migration.id}>{migration.description}</li>
))}
</ul>
</div>
)
interface MigrationUpgradeWarningBannerProps {
migrations: OutOfBandMigrationFields[]
}
const MigrationUpgradeWarningBanner: React.FunctionComponent<MigrationUpgradeWarningBannerProps> = ({ migrations }) => (
<div className="alert alert-warning">
<p>
The next version of Sourcegraph removes support for reading an old data format. Your Sourcegraph instance
must complete the following migrations to ensure your data remains readable.{' '}
<strong>If you upgrade your Sourcegraph instance now, you may corrupt or lose data.</strong>
</p>
<ul>
{migrations.map(migration => (
<li key={migration.id}>{migration.description}</li>
))}
</ul>
<span>Contact support if these migrations are not making progress or if there are associated errors.</span>
</div>
)
interface MigrationDowngradeWarningBannerProps {
migrations: OutOfBandMigrationFields[]
}
const MigrationDowngradeWarningBanner: React.FunctionComponent<MigrationDowngradeWarningBannerProps> = ({
migrations,
}) => (
<div className="alert alert-warning">
<p>
<WarningIcon className="icon-inline mr-2" />
<span>
The previous version of Sourcegraph does not support reading data that has been migrated into a new
format. Your Sourcegraph instance must undo the following migrations to ensure your data can be read by
the previous version.{' '}
<strong>If you downgrade your Sourcegraph instance now, you may corrupt or lose data.</strong>
</span>
</p>
<ul>
{migrations.map(migration => (
<li key={migration.id}>{migration.description}</li>
))}
</ul>
<span>Contact support for assistance with downgrading your instance.</span>
</div>
)
interface MigrationNodeProps {
node: OutOfBandMigrationFields
now?: () => Date
}
const MigrationNode: React.FunctionComponent<MigrationNodeProps> = ({ node, now }) => (
<React.Fragment key={node.id}>
<span className={styles.separator} />
<div className={classNames('d-flex flex-column', styles.information)}>
<div>
<h3>{node.description}</h3>
<p className="m-0">
<span className="text-muted">Team</span> <strong>{node.team}</strong>{' '}
<span className="text-muted">is migrating data in</span> <strong>{node.component}</strong>
<span className="text-muted">.</span>
</p>
<p className="m-0">
<span className="text-muted">Began running in v</span>
{node.introduced}
{node.deprecated && (
<>
{' '}
<span className="text-muted">and will cease running in v</span>
{node.deprecated}
</>
)}
.
</p>
</div>
</div>
<span className={classNames('d-none d-md-inline', styles.progress)}>
<div className="m-0 text-nowrap d-flex flex-column align-items-center justify-content-center">
<div>
{node.applyReverse ? (
<ArrowLeftBoldIcon className="icon-inline mr-1 text-danger" />
) : (
<ArrowRightBoldIcon className="icon-inline mr-1" />
)}
{Math.floor(node.progress * 100)}%
</div>
<div>
<meter
min={0}
low={0.2}
high={0.8}
max={1}
optimum={1}
value={node.progress}
data-tooltip={`${Math.floor(node.progress * 100)}%`}
aria-label="migration progress"
data-placement="bottom"
/>
</div>
{node.lastUpdated && node.lastUpdated !== '' && (
<>
<div className="text-center">
<span className="text-muted">Last updated</span>
</div>
<div className="text-center">
<small>
<Timestamp date={node.lastUpdated} now={now} noAbout={true} />
</small>
</div>
</>
)}
</div>
</span>
{node.errors.length > 0 && (
<Collapsible
title={<strong>Recent errors ({node.errors.length})</strong>}
className="p-0 font-weight-normal"
buttonClassName="mb-0"
titleAtStart={true}
defaultExpanded={false}
>
<div className={classNames('pt-2', styles.nodeGrid)}>
{node.errors
.map((error, index) => ({ ...error, index }))
.map(error => (
<React.Fragment key={error.index}>
<div className="py-1 pr-2">
<Timestamp date={error.created} now={now} />
</div>
<span className={classNames('py-1 pl-2', styles.nodeGridCode)}>
<code>{error.message}</code>
</span>
</React.Fragment>
))}
</div>
</Collapsible>
)}
</React.Fragment>
)
type PartialVersion = SemVer | null
/** Parse the given version safely. */
const parseVersion = (version: string): PartialVersion => {
try {
return _parseVersion(version)
} catch {
return null
}
}
/** Returns true if the given migration state is invalid for the given version. */
export const isInvalidForVersion = (migration: OutOfBandMigrationFields, version: PartialVersion): boolean => {
if (!version) {
return false
}
// Migrations only store major/minor version components
const introduced = parseVersion(`${migration.introduced}.0`)
if (introduced && version.major === introduced.major && version.minor < introduced.minor) {
return migration.progress !== 0 && !migration.nonDestructive
}
if (migration.deprecated) {
// Migrations only store major/minor version components
const deprecated = parseVersion(`${migration.deprecated}.0`)
if (deprecated && version.major === deprecated.major && version.minor >= deprecated.minor) {
return migration.progress !== 1
}
}
return false
}
/** Returns the set of migrations that are invalid for the given version. */
const migrationsInvalidForVersion = (
migrations: OutOfBandMigrationFields[],
version: PartialVersion
): OutOfBandMigrationFields[] => migrations.filter(migration => isInvalidForVersion(migration, version))
/** Returns true if the given migration is has completed (100% if forward, 0% if reverse). */
export const isComplete = (migration: OutOfBandMigrationFields): boolean =>
(migration.progress === 0 && migration.applyReverse) || (migration.progress === 1 && !migration.applyReverse)
/** Returns the searchable text from a migration. */
const searchFields = (migration: OutOfBandMigrationFields): string[] => [
migration.team,
migration.component,
migration.description,
migration.introduced,
migration.deprecated || '',
...migration.errors.map(error => error.message),
]
/** Returns true if the migration matches the given query. */
const matchesQuery = (migration: OutOfBandMigrationFields, query: string): boolean => {
const fields = searchFields(migration)
.map(value => value.toLowerCase())
.filter(value => value !== '')
return query
.toLowerCase()
.split(' ')
.filter(query => query !== '')
.every(query => fields.some(value => value.includes(query)))
} | the_stack |
import { CloudErrorMapper, BaseResourceMapper } from "@azure/ms-rest-azure-js";
import * as msRest from "@azure/ms-rest-js";
export const CloudError = CloudErrorMapper;
export const BaseResource = BaseResourceMapper;
export const SkuCapacity: msRest.CompositeMapper = {
serializedName: "SkuCapacity",
type: {
name: "Composite",
className: "SkuCapacity",
modelProperties: {
minimum: {
readOnly: true,
serializedName: "minimum",
type: {
name: "Number"
}
},
maximum: {
readOnly: true,
serializedName: "maximum",
type: {
name: "Number"
}
},
default: {
readOnly: true,
serializedName: "default",
type: {
name: "Number"
}
},
scaleType: {
readOnly: true,
serializedName: "scaleType",
type: {
name: "String"
}
}
}
}
};
export const SkuCapability: msRest.CompositeMapper = {
serializedName: "SkuCapability",
type: {
name: "Composite",
className: "SkuCapability",
modelProperties: {
name: {
readOnly: true,
serializedName: "name",
type: {
name: "String"
}
},
value: {
readOnly: true,
serializedName: "value",
type: {
name: "String"
}
}
}
}
};
export const SkuCost: msRest.CompositeMapper = {
serializedName: "SkuCost",
type: {
name: "Composite",
className: "SkuCost",
modelProperties: {
meterID: {
readOnly: true,
serializedName: "meterID",
type: {
name: "String"
}
},
quantity: {
readOnly: true,
serializedName: "quantity",
type: {
name: "Number"
}
},
extendedUnit: {
readOnly: true,
serializedName: "extendedUnit",
type: {
name: "String"
}
}
}
}
};
export const SkuRestrictions: msRest.CompositeMapper = {
serializedName: "SkuRestrictions",
type: {
name: "Composite",
className: "SkuRestrictions",
modelProperties: {
type: {
readOnly: true,
serializedName: "type",
type: {
name: "String"
}
},
values: {
readOnly: true,
serializedName: "values",
type: {
name: "Sequence",
element: {
type: {
name: "String"
}
}
}
},
reasonCode: {
readOnly: true,
serializedName: "reasonCode",
type: {
name: "String"
}
}
}
}
};
export const CatalogSku: msRest.CompositeMapper = {
serializedName: "CatalogSku",
type: {
name: "Composite",
className: "CatalogSku",
modelProperties: {
resourceType: {
readOnly: true,
serializedName: "resourceType",
type: {
name: "String"
}
},
name: {
readOnly: true,
serializedName: "name",
type: {
name: "String"
}
},
tier: {
readOnly: true,
serializedName: "tier",
type: {
name: "String"
}
},
locations: {
readOnly: true,
serializedName: "locations",
type: {
name: "Sequence",
element: {
type: {
name: "String"
}
}
}
},
capacity: {
readOnly: true,
serializedName: "capacity",
type: {
name: "Composite",
className: "SkuCapacity"
}
},
capabilities: {
readOnly: true,
serializedName: "capabilities",
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "SkuCapability"
}
}
}
},
costs: {
readOnly: true,
serializedName: "costs",
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "SkuCost"
}
}
}
},
restrictions: {
readOnly: true,
serializedName: "restrictions",
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "SkuRestrictions"
}
}
}
}
}
}
};
export const Resource: msRest.CompositeMapper = {
serializedName: "Resource",
type: {
name: "Composite",
className: "Resource",
modelProperties: {
id: {
readOnly: true,
serializedName: "id",
type: {
name: "String"
}
},
name: {
readOnly: true,
serializedName: "name",
type: {
name: "String"
}
},
location: {
required: true,
serializedName: "location",
type: {
name: "String"
}
},
type: {
readOnly: true,
serializedName: "type",
type: {
name: "String"
}
},
tags: {
serializedName: "tags",
type: {
name: "Dictionary",
value: {
type: {
name: "String"
}
}
}
}
}
}
};
export const CommitmentAssociationProperties: msRest.CompositeMapper = {
serializedName: "CommitmentAssociationProperties",
type: {
name: "Composite",
className: "CommitmentAssociationProperties",
modelProperties: {
associatedResourceId: {
readOnly: true,
serializedName: "associatedResourceId",
type: {
name: "String"
}
},
commitmentPlanId: {
readOnly: true,
serializedName: "commitmentPlanId",
type: {
name: "String"
}
},
creationDate: {
readOnly: true,
serializedName: "creationDate",
type: {
name: "DateTime"
}
}
}
}
};
export const CommitmentAssociation: msRest.CompositeMapper = {
serializedName: "CommitmentAssociation",
type: {
name: "Composite",
className: "CommitmentAssociation",
modelProperties: {
...Resource.type.modelProperties,
etag: {
serializedName: "etag",
type: {
name: "String"
}
},
properties: {
serializedName: "properties",
type: {
name: "Composite",
className: "CommitmentAssociationProperties"
}
}
}
}
};
export const ResourceSku: msRest.CompositeMapper = {
serializedName: "ResourceSku",
type: {
name: "Composite",
className: "ResourceSku",
modelProperties: {
capacity: {
serializedName: "capacity",
type: {
name: "Number"
}
},
name: {
serializedName: "name",
type: {
name: "String"
}
},
tier: {
serializedName: "tier",
type: {
name: "String"
}
}
}
}
};
export const MoveCommitmentAssociationRequest: msRest.CompositeMapper = {
serializedName: "MoveCommitmentAssociationRequest",
type: {
name: "Composite",
className: "MoveCommitmentAssociationRequest",
modelProperties: {
destinationPlanId: {
serializedName: "destinationPlanId",
type: {
name: "String"
}
}
}
}
};
export const CommitmentPlanPatchPayload: msRest.CompositeMapper = {
serializedName: "CommitmentPlanPatchPayload",
type: {
name: "Composite",
className: "CommitmentPlanPatchPayload",
modelProperties: {
tags: {
serializedName: "tags",
type: {
name: "Dictionary",
value: {
type: {
name: "String"
}
}
}
},
sku: {
serializedName: "sku",
type: {
name: "Composite",
className: "ResourceSku"
}
}
}
}
};
export const PlanQuantity: msRest.CompositeMapper = {
serializedName: "PlanQuantity",
type: {
name: "Composite",
className: "PlanQuantity",
modelProperties: {
allowance: {
readOnly: true,
serializedName: "allowance",
type: {
name: "Number"
}
},
amount: {
readOnly: true,
serializedName: "amount",
type: {
name: "Number"
}
},
includedQuantityMeter: {
readOnly: true,
serializedName: "includedQuantityMeter",
type: {
name: "String"
}
},
overageMeter: {
readOnly: true,
serializedName: "overageMeter",
type: {
name: "String"
}
}
}
}
};
export const CommitmentPlanProperties: msRest.CompositeMapper = {
serializedName: "CommitmentPlanProperties",
type: {
name: "Composite",
className: "CommitmentPlanProperties",
modelProperties: {
chargeForOverage: {
readOnly: true,
serializedName: "chargeForOverage",
type: {
name: "Boolean"
}
},
chargeForPlan: {
readOnly: true,
serializedName: "chargeForPlan",
type: {
name: "Boolean"
}
},
creationDate: {
readOnly: true,
serializedName: "creationDate",
type: {
name: "DateTime"
}
},
includedQuantities: {
readOnly: true,
serializedName: "includedQuantities",
type: {
name: "Dictionary",
value: {
type: {
name: "Composite",
className: "PlanQuantity"
}
}
}
},
maxAssociationLimit: {
readOnly: true,
serializedName: "maxAssociationLimit",
type: {
name: "Number"
}
},
maxCapacityLimit: {
readOnly: true,
serializedName: "maxCapacityLimit",
type: {
name: "Number"
}
},
minCapacityLimit: {
readOnly: true,
serializedName: "minCapacityLimit",
type: {
name: "Number"
}
},
planMeter: {
readOnly: true,
serializedName: "planMeter",
type: {
name: "String"
}
},
refillFrequencyInDays: {
readOnly: true,
serializedName: "refillFrequencyInDays",
type: {
name: "Number"
}
},
suspendPlanOnOverage: {
readOnly: true,
serializedName: "suspendPlanOnOverage",
type: {
name: "Boolean"
}
}
}
}
};
export const CommitmentPlan: msRest.CompositeMapper = {
serializedName: "CommitmentPlan",
type: {
name: "Composite",
className: "CommitmentPlan",
modelProperties: {
...Resource.type.modelProperties,
etag: {
serializedName: "etag",
type: {
name: "String"
}
},
properties: {
readOnly: true,
serializedName: "properties",
type: {
name: "Composite",
className: "CommitmentPlanProperties"
}
},
sku: {
serializedName: "sku",
type: {
name: "Composite",
className: "ResourceSku"
}
}
}
}
};
export const PlanUsageHistory: msRest.CompositeMapper = {
serializedName: "PlanUsageHistory",
type: {
name: "Composite",
className: "PlanUsageHistory",
modelProperties: {
planDeletionOverage: {
serializedName: "planDeletionOverage",
type: {
name: "Dictionary",
value: {
type: {
name: "Number"
}
}
}
},
planMigrationOverage: {
serializedName: "planMigrationOverage",
type: {
name: "Dictionary",
value: {
type: {
name: "Number"
}
}
}
},
planQuantitiesAfterUsage: {
serializedName: "planQuantitiesAfterUsage",
type: {
name: "Dictionary",
value: {
type: {
name: "Number"
}
}
}
},
planQuantitiesBeforeUsage: {
serializedName: "planQuantitiesBeforeUsage",
type: {
name: "Dictionary",
value: {
type: {
name: "Number"
}
}
}
},
planUsageOverage: {
serializedName: "planUsageOverage",
type: {
name: "Dictionary",
value: {
type: {
name: "Number"
}
}
}
},
usage: {
serializedName: "usage",
type: {
name: "Dictionary",
value: {
type: {
name: "Number"
}
}
}
},
usageDate: {
serializedName: "usageDate",
type: {
name: "DateTime"
}
}
}
}
};
export const SkuListResult: msRest.CompositeMapper = {
serializedName: "SkuListResult",
type: {
name: "Composite",
className: "SkuListResult",
modelProperties: {
value: {
readOnly: true,
serializedName: "",
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "CatalogSku"
}
}
}
}
}
}
};
export const CommitmentAssociationListResult: msRest.CompositeMapper = {
serializedName: "CommitmentAssociationListResult",
type: {
name: "Composite",
className: "CommitmentAssociationListResult",
modelProperties: {
nextLink: {
serializedName: "nextLink",
type: {
name: "String"
}
},
value: {
serializedName: "",
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "CommitmentAssociation"
}
}
}
}
}
}
};
export const CommitmentPlanListResult: msRest.CompositeMapper = {
serializedName: "CommitmentPlanListResult",
type: {
name: "Composite",
className: "CommitmentPlanListResult",
modelProperties: {
nextLink: {
serializedName: "nextLink",
type: {
name: "String"
}
},
value: {
serializedName: "",
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "CommitmentPlan"
}
}
}
}
}
}
};
export const PlanUsageHistoryListResult: msRest.CompositeMapper = {
serializedName: "PlanUsageHistoryListResult",
type: {
name: "Composite",
className: "PlanUsageHistoryListResult",
modelProperties: {
nextLink: {
serializedName: "nextLink",
type: {
name: "String"
}
},
value: {
serializedName: "",
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "PlanUsageHistory"
}
}
}
}
}
}
}; | the_stack |
/// <reference types="angular" />
import * as angular from 'angular';
declare var angularFileUploadDefaultExport: string;
export = angularFileUploadDefaultExport;
declare module 'angular' {
export namespace angularFileUpload {
interface ImageDimensions {
height: number;
width: number;
}
interface FileUploadOptions {
/**
* Standard HTML accept attr, browser specific select popup window
* @type {string}
*/
ngfAccept?: string | undefined;
/**
* Default true, allow dropping files only for Chrome webkit browser
* @type {boolean}
*/
ngfAllowDir?: boolean | undefined;
/**
* Default false, enable firefox image paste by making element contenteditable
* @type {boolean}
*/
ngfEnableFirefoxPaste?: boolean | undefined;
/**
* Default false, hides element if file drag&drop is not
* @type {boolean}
*/
ngfHideOnDropNotAvailable?: boolean | undefined;
/**
* Validate error name: minDuration
* @type {(number|string)}
*/
ngfMinDuration?: number | string | undefined;
/**
* Validate error name: minSize
* @type {(number|string)}
*/
ngfMinSize?: number | string | undefined;
/**
* Validate error name: minRatio
* @type {(number|string)}
*/
ngfMinRatio?: number | string | undefined;
/**
* Validate error name: maxDuration
* @type {(number|string)}
*/
ngfMaxDuration?: number | string | undefined;
/**
* Maximum number of files allowed to be selected or dropped, validate error name: maxFiles
* @type {number}
*/
ngfMaxFiles?: number | undefined;
/**
* Validate error name: maxSize
* @type {(number|string)}
*/
ngfMaxSize?: number | string | undefined;
/**
* Validate error name: maxTotalSize
* @type {(number|string)}
*/
ngfMaxTotalSize?: number | string | undefined;
/**
* Allows selecting multiple files
* @type {boolean}
*/
ngfMultiple?: boolean | undefined;
/**
* List of comma separated valid aspect ratio of images in float or 2:3 format
* @type {string}
*/
ngfRatio?: string | undefined;
/**
* Default false, whether to propagate drag/drop events.
* @type {boolean}
*/
ngfStopPropagation?: boolean | undefined;
/**
* Default false, if true file.$error will be set if the dimension or duration
* values for validations cannot be calculated for example image load error or unsupported video by the browser.
* By default it would assume the file is valid if the duration or dimension cannot be calculated by the browser.
* @type {boolean}
*/
ngfValidateForce?: boolean | undefined;
}
interface ResizeIfFunction {
(width: number, height: number): boolean;
}
interface FileResizeOptions {
centerCrop?: boolean | undefined;
height?: number | undefined;
pattern?: string | undefined;
ratio?: number | string | undefined;
resizeIf?: ResizeIfFunction | undefined;
restoreExif?: boolean | undefined;
quality?: number | undefined;
type?: string | undefined;
width?: number | undefined;
}
interface IUploadService {
/**
* Convert a single file or array of files to a single or array of
* base64 data url representation of the file(s).
* Could be used to send file in base64 format inside json to the databases
*
* @param {Array<File>}
* @return {angular.IPromise}
*/
base64DataUrl(files: File | Array<File>): angular.IPromise<Array<string> | string>;
/**
* Convert the file to blob url object or base64 data url based on boolean disallowObjectUrl value
*
* @param {File} file
* @param {boolean} [disallowObjectUrl]
* @return {angular.IPromise<string>}
*/
dataUrl(file: File, disallowObjectUrl?: boolean): angular.IPromise<Blob | string>;
/**
* Alternative way of uploading, send the file binary with the file's content-type.
* Could be used to upload files to CouchDB, imgur, etc... html5 FileReader is needed.
* This is equivalent to angular $http() but allow you to listen to the progress event for HTML5 browsers.
*
* @param {IRequestConfig} config
* @return {angular.IPromise<ImageDimensions>}
*/
http<T>(config: IRequestConfig): IUploadPromise<T>;
/**
* Get image file dimensions
*
* @param {File} file
* @return {angular.IPromise<ImageDimensions>}
*/
imageDimensions(file: File): angular.IPromise<ImageDimensions>;
/**
* Returns boolean showing if image resize is supported by this browser
*
* @return {boolean}
*/
isResizeSupported(): boolean;
/**
* Returns boolean showing if resumable upload is supported by this browser
*
* @return {boolean}
*/
isResumeSupported(): boolean;
/**
* Returns true if there is an upload in progress. Can be used to prompt user before closing browser tab
*
* @return {boolean}
*/
isUploadInProgress(): boolean;
/**
* Converts the value to json to send data as json string. Same as angular.toJson(obj)
*
* @param {Object} obj
* @return {string}
*/
json(obj: Object): string;
/**
* Converts the object to a Blob object with application/json content type
* for jsob byte streaming support
*
* @param {Object} obj
* @return {Blob}
*/
jsonBlob(obj: Object): Blob;
/**
* Returns a file which will be uploaded with the newName instead of original file name
*
* @param {File} file
* @param {string} newName
* @return {File}
*/
rename(file: File, newName: string): Blob;
/**
* Resizes an image. Returns a promise
*
* @param {File} file
* @param {number} [width]
* @param {number} [height]
* @param {number} [quality]
* @param {string} [type]
* @param {number} [ratio]
* @param {boolean} [centerCrop]
* @return {angular.IPromise<string>}
*/
resize(file: File, options: FileResizeOptions): angular.IPromise<File>;
/**
* Set the default values for ngf-select and ngf-drop directives
*
* @param {FileUploadOptions} defaultFileUploadOptions
*/
setDefaults(defaultFileUploadOptions: FileUploadOptions): void;
/**
* Upload a file. Returns a Promise,
*
* @param {IFileUploadConfigFile} config
* @return {IUploadPromise<T>}
*/
upload<T>(config: IFileUploadConfigFile): IUploadPromise<T>;
}
interface IUploadPromise<T> extends IHttpPromise<T> {
/**
* Cancel/abort the upload in progress.
*
* @return {IUploadPromise<T>}
*/
abort(): IUploadPromise<T>;
progress(callback: (event: IFileProgressEvent) => void): IUploadPromise<T>;
/**
* Access or attach event listeners to the underlying XMLHttpRequest
*
* @param {IHttpPromiseCallback<T>}
* @return {IUploadPromise<T>}
*/
xhr(callback: IHttpPromiseCallback<T>): IUploadPromise<T>;
}
interface IFileUploadConfigFile extends IRequestConfig {
/**
* Specify the file and optional data to be sent to the server.
* Each field including nested objects will be sent as a form data multipart.
* Samples: {pic: file, username: username}
* {files: files, otherInfo: {id: id, person: person,...}} multiple files (html5)
* {profiles: {[{pic: file1, username: username1}, {pic: file2, username: username2}]} nested array multiple files (html5)
* {file: file, info: Upload.json({id: id, name: name, ...})} send fields as json string
* {file: file, info: Upload.jsonBlob({id: id, name: name, ...})} send fields as json blob, 'application/json' content_type
* {picFile: Upload.rename(file, 'profile.jpg'), title: title} send file with picFile key and profile.jpg file name
*
* @type {Object}
*/
data: any;
/**
* upload.php script, node.js route, or servlet url
* @type {string}
*/
url: string;
/**
* Add which HTTP method to use: 'POST' or 'PUT' (html5)
*/
method: string;
/**
* This is to accommodate server implementations expecting nested data object keys in .key or [key] format.
* Example: data: {rec: {name: 'N', pic: file}} sent as: rec[name] -> N, rec[pic] -> file
* data: {rec: {name: 'N', pic: file}, objectKey: '.k'} sent as: rec.name -> N, rec.pic -> file
* @type {string}
*/
objectKey?: string | undefined;
/**
* This is to accommodate server implementations expecting array data object keys in '[i]' or '[]' or
* ''(multiple entries with same key) format.
* Example: data: {rec: [file[0], file[1], ...]} sent as: rec[0] -> file[0], rec[1] -> file[1],...
* data: {rec: {rec: [f[0], f[1], ...], arrayKey: '[]'} sent as: rec[] -> f[0], rec[] -> f[1],...
* @type {string}
*/
arrayKey?: string | undefined;
/**
* Uploaded file size so far on the server
* @type {string}
*/
resumeSizeUrl?: string | undefined;
/**
* Reads the uploaded file size from resumeSizeUrl GET response
* @type {Function}
*/
resumeSizeResponseReader?: Function | undefined;
/**
* Function that returns a prommise which will be resolved to the upload file size on the server.
* @type {[type]}
*/
resumeSize?: Function | undefined;
/**
* Upload in chunks of specified size
* @type {(number|string)}
*/
resumeChunkSize?: number | string | undefined;
/**
* Default false, experimental as hotfix for potential library conflicts with other plugins
* @type {boolean}
*/
disableProgress?: boolean | undefined;
}
interface IFileProgressEvent extends ProgressEvent {
config: IFileUploadConfigFile;
}
}
} | the_stack |
import React from 'react'
import ReactDOM from 'react-dom'
import './index.css'
import {
Column,
createTable,
TableInstance,
useTableInstance,
ColumnFiltersState,
getCoreRowModel,
getFilteredRowModel,
getFacetedRowModel,
getFacetedUniqueValues,
getFacetedMinMaxValues,
getPaginationRowModel,
sortingFns,
getSortedRowModel,
} from '@tanstack/react-table'
import {
RankingInfo,
rankItem,
compareItems,
rankings,
} from '@tanstack/match-sorter-utils'
import { makeData, Person } from './makeData'
let table = createTable()
.setRowType<Person>()
.setFilterMetaType<RankingInfo>()
.setOptions({
filterFns: {
fuzzy: (row, columnId, value, addMeta) => {
// Rank the item
const itemRank = rankItem(row.getValue(columnId), value, {
threshold: rankings.MATCHES,
})
// Store the ranking info
addMeta(itemRank)
// Return if the item should be filtered in/out
return itemRank.passed
},
},
sortingFns: {
fuzzy: (rowA, rowB, columnId) => {
let dir = 0
// Only sort by rank if the column has ranking information
if (rowA.columnFiltersMeta[columnId]) {
dir = compareItems(
rowA.columnFiltersMeta[columnId]!,
rowB.columnFiltersMeta[columnId]!
)
}
// Provide a fallback for when the item ranks are equal
return dir === 0 ? sortingFns.alphanumeric(rowA, rowB, columnId) : dir
},
},
})
function App() {
const rerender = React.useReducer(() => ({}), {})[1]
const [columnFilters, setColumnFilters] = React.useState<ColumnFiltersState>(
[]
)
const [globalFilter, setGlobalFilter] = React.useState('')
const columns = React.useMemo(
() => [
table.createGroup({
header: 'Name',
footer: props => props.column.id,
columns: [
table.createDataColumn('firstName', {
cell: info => info.getValue(),
footer: props => props.column.id,
}),
table.createDataColumn(row => row.lastName, {
id: 'lastName',
cell: info => info.getValue(),
header: () => <span>Last Name</span>,
footer: props => props.column.id,
}),
table.createDataColumn(row => `${row.firstName} ${row.lastName}`, {
id: 'fullName',
header: 'Full Name',
cell: info => info.getValue(),
footer: props => props.column.id,
filterFn: 'fuzzy',
sortingFn: 'fuzzy',
}),
],
}),
table.createGroup({
header: 'Info',
footer: props => props.column.id,
columns: [
table.createDataColumn('age', {
header: () => 'Age',
footer: props => props.column.id,
}),
table.createGroup({
header: 'More Info',
columns: [
table.createDataColumn('visits', {
header: () => <span>Visits</span>,
footer: props => props.column.id,
}),
table.createDataColumn('status', {
header: 'Status',
footer: props => props.column.id,
}),
table.createDataColumn('progress', {
header: 'Profile Progress',
footer: props => props.column.id,
}),
],
}),
],
}),
],
[]
)
const [data, setData] = React.useState(() => makeData(50000))
const refreshData = () => setData(old => makeData(50000))
const instance = useTableInstance(table, {
data,
columns,
state: {
columnFilters,
globalFilter,
},
onColumnFiltersChange: setColumnFilters,
onGlobalFilterChange: setGlobalFilter,
globalFilterFn: 'fuzzy',
getCoreRowModel: getCoreRowModel(),
getFilteredRowModel: getFilteredRowModel(),
getSortedRowModel: getSortedRowModel(),
getPaginationRowModel: getPaginationRowModel(),
getFacetedRowModel: getFacetedRowModel(),
getFacetedUniqueValues: getFacetedUniqueValues(),
getFacetedMinMaxValues: getFacetedMinMaxValues(),
debugTable: true,
debugHeaders: true,
debugColumns: false,
})
React.useEffect(() => {
if (instance.getState().columnFilters[0]?.id === 'fullName') {
if (instance.getState().sorting[0]?.id !== 'fullName') {
instance.setSorting([{ id: 'fullName', desc: false }])
}
}
}, [instance.getState().columnFilters[0]?.id])
return (
<div className="p-2">
<div>
<DebouncedInput
value={globalFilter ?? ''}
onChange={value => setGlobalFilter(String(value))}
className="p-2 font-lg shadow border border-block"
placeholder="Search all columns..."
/>
</div>
<div className="h-2" />
<table>
<thead>
{instance.getHeaderGroups().map(headerGroup => (
<tr key={headerGroup.id}>
{headerGroup.headers.map(header => {
return (
<th key={header.id} colSpan={header.colSpan}>
{header.isPlaceholder ? null : (
<>
<div
{...{
className: header.column.getCanSort()
? 'cursor-pointer select-none'
: '',
onClick: header.column.getToggleSortingHandler(),
}}
>
{header.renderHeader()}
{{
asc: ' 🔼',
desc: ' 🔽',
}[header.column.getIsSorted() as string] ?? null}
</div>
{header.column.getCanFilter() ? (
<div>
<Filter
column={header.column}
instance={instance}
/>
</div>
) : null}
</>
)}
</th>
)
})}
</tr>
))}
</thead>
<tbody>
{instance.getRowModel().rows.map(row => {
return (
<tr key={row.id}>
{row.getVisibleCells().map(cell => {
return <td key={cell.id}>{cell.renderCell()}</td>
})}
</tr>
)
})}
</tbody>
</table>
<div className="h-2" />
<div className="flex items-center gap-2">
<button
className="border rounded p-1"
onClick={() => instance.setPageIndex(0)}
disabled={!instance.getCanPreviousPage()}
>
{'<<'}
</button>
<button
className="border rounded p-1"
onClick={() => instance.previousPage()}
disabled={!instance.getCanPreviousPage()}
>
{'<'}
</button>
<button
className="border rounded p-1"
onClick={() => instance.nextPage()}
disabled={!instance.getCanNextPage()}
>
{'>'}
</button>
<button
className="border rounded p-1"
onClick={() => instance.setPageIndex(instance.getPageCount() - 1)}
disabled={!instance.getCanNextPage()}
>
{'>>'}
</button>
<span className="flex items-center gap-1">
<div>Page</div>
<strong>
{instance.getState().pagination.pageIndex + 1} of{' '}
{instance.getPageCount()}
</strong>
</span>
<span className="flex items-center gap-1">
| Go to page:
<input
type="number"
defaultValue={instance.getState().pagination.pageIndex + 1}
onChange={e => {
const page = e.target.value ? Number(e.target.value) - 1 : 0
instance.setPageIndex(page)
}}
className="border p-1 rounded w-16"
/>
</span>
<select
value={instance.getState().pagination.pageSize}
onChange={e => {
instance.setPageSize(Number(e.target.value))
}}
>
{[10, 20, 30, 40, 50].map(pageSize => (
<option key={pageSize} value={pageSize}>
Show {pageSize}
</option>
))}
</select>
</div>
<div>{instance.getPrePaginationRowModel().rows.length} Rows</div>
<div>
<button onClick={() => rerender()}>Force Rerender</button>
</div>
<div>
<button onClick={() => refreshData()}>Refresh Data</button>
</div>
<pre>{JSON.stringify(instance.getState(), null, 2)}</pre>
</div>
)
}
function Filter({
column,
instance,
}: {
column: Column<any>
instance: TableInstance<any>
}) {
const firstValue = instance
.getPreFilteredRowModel()
.flatRows[0]?.getValue(column.id)
const columnFilterValue = column.getFilterValue()
const sortedUniqueValues = React.useMemo(
() =>
typeof firstValue === 'number'
? []
: Array.from(column.getFacetedUniqueValues().keys()).sort(),
[column.getFacetedUniqueValues()]
)
return typeof firstValue === 'number' ? (
<div>
<div className="flex space-x-2">
<DebouncedInput
type="number"
min={Number(column.getFacetedMinMaxValues()?.[0] ?? '')}
max={Number(column.getFacetedMinMaxValues()?.[1] ?? '')}
value={(columnFilterValue as [number, number])?.[0] ?? ''}
onChange={value =>
column.setFilterValue((old: [number, number]) => [value, old?.[1]])
}
placeholder={`Min ${
column.getFacetedMinMaxValues()?.[0]
? `(${column.getFacetedMinMaxValues()?.[0]})`
: ''
}`}
className="w-24 border shadow rounded"
/>
<DebouncedInput
type="number"
min={Number(column.getFacetedMinMaxValues()?.[0] ?? '')}
max={Number(column.getFacetedMinMaxValues()?.[1] ?? '')}
value={(columnFilterValue as [number, number])?.[1] ?? ''}
onChange={value =>
column.setFilterValue((old: [number, number]) => [old?.[0], value])
}
placeholder={`Max ${
column.getFacetedMinMaxValues()?.[1]
? `(${column.getFacetedMinMaxValues()?.[1]})`
: ''
}`}
className="w-24 border shadow rounded"
/>
</div>
<div className="h-1" />
</div>
) : (
<>
<datalist id={column.id + 'list'}>
{sortedUniqueValues.slice(0, 5000).map(value => (
<option value={value} key={value} />
))}
</datalist>
<DebouncedInput
type="text"
value={(columnFilterValue ?? '') as string}
onChange={value => column.setFilterValue(value)}
placeholder={`Search... (${column.getFacetedUniqueValues().size})`}
className="w-36 border shadow rounded"
list={column.id + 'list'}
/>
<div className="h-1" />
</>
)
}
// A debounced input react component
function DebouncedInput({
value: initialValue,
onChange,
debounce = 500,
...props
}: {
value: string | number
onChange: (value: string | number) => void
debounce?: number
} & Omit<React.InputHTMLAttributes<HTMLInputElement>, 'onChange'>) {
const [value, setValue] = React.useState(initialValue)
React.useEffect(() => {
setValue(initialValue)
}, [initialValue])
React.useEffect(() => {
const timeout = setTimeout(() => {
onChange(value)
}, debounce)
return () => clearTimeout(timeout)
}, [value])
return (
<input {...props} value={value} onChange={e => setValue(e.target.value)} />
)
}
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
) | the_stack |
import React, { ReactElement } from "react";
import i18next from "i18next";
import { useTranslation } from "react-i18next";
import { Link, useParams } from "react-router-dom";
import { Card, Col, Row, Skeleton, Tag, Tooltip } from "antd";
import find from "lodash/find";
import BigNumber from "bignumber.js";
import TimeAgo from "timeago-react";
import useAccountHistory from "api/hooks/use-account-history";
import {
Theme,
PreferencesContext,
CurrencySymbol,
CurrencyDecimal,
} from "api/contexts/Preferences";
import { MarketStatisticsContext } from "api/contexts/MarketStatistics";
import { AccountInfoContext } from "api/contexts/AccountInfo";
import {
Representative,
RepresentativesContext,
} from "api/contexts/Representatives";
import { ConfirmationQuorumContext } from "api/contexts/ConfirmationQuorum";
import LoadingStatistic from "components/LoadingStatistic";
import QuestionCircle from "components/QuestionCircle";
import { rawToRai, timestampToDate, TwoToneColors } from "components/utils";
import AccountHeader from "../Header";
import ExtraRow from "./ExtraRow";
import { Sections } from "../.";
import type { PageParams } from "types/page";
import type { Transaction } from "types/transaction";
interface AccountDetailsLayoutProps {
bordered?: boolean;
children?: ReactElement;
}
export const AccountDetailsLayout = ({
bordered,
children,
}: AccountDetailsLayoutProps) => (
<Card size="small" bordered={bordered} className="detail-layout">
{children}
</Card>
);
interface Props {
socketTransactions: Transaction[];
socketBalance: number;
socketPendingBalance: number;
}
const AccountDetails: React.FC<Props> = ({
socketTransactions,
socketBalance,
socketPendingBalance,
}) => {
const { t } = useTranslation();
const { section = Sections.TRANSACTIONS } = useParams<PageParams>();
const { theme, fiat } = React.useContext(PreferencesContext);
const [representativeAccount, setRepresentativeAccount] = React.useState(
{} as any,
);
const [accountsRepresentative, setAccountsRepresentative] = React.useState(
{} as Representative,
);
const {
marketStatistics: {
currentPrice,
priceStats: { bitcoin: { [fiat]: btcCurrentPrice = 0 } } = {
bitcoin: { [fiat]: 0 },
},
},
isInitialLoading: isMarketStatisticsInitialLoading,
} = React.useContext(MarketStatisticsContext);
const {
account,
accountInfo,
isLoading: isAccountInfoLoading,
} = React.useContext(AccountInfoContext);
const {
accountHistory: { history },
isLoading: isAccountHistoryLoading,
} = useAccountHistory(account, {
count: "5",
raw: true,
});
const {
representatives,
isLoading: isRepresentativesLoading,
} = React.useContext(RepresentativesContext);
const {
confirmationQuorum: {
principal_representative_min_weight: principalRepresentativeMinWeight,
online_stake_total: onlineStakeTotal = 0,
},
} = React.useContext(ConfirmationQuorumContext);
let balance = new BigNumber(rawToRai(accountInfo?.balance || 0))
.plus(socketBalance)
.toNumber();
// @NOTE temporary fix until a solution is found with the websocket messages going below 0
if (balance < 0) {
balance = 0;
}
const balancePending = new BigNumber(rawToRai(accountInfo?.pending || 0))
.plus(socketPendingBalance)
.toFormat(8);
const fiatBalance = new BigNumber(balance)
.times(currentPrice)
.toFormat(CurrencyDecimal?.[fiat]);
const btcBalance = new BigNumber(balance)
.times(currentPrice)
.dividedBy(btcCurrentPrice)
.toFormat(12);
const lastTransaction = (history || []).find(
({ local_timestamp, subtype = "" }) =>
["change", "send", "receive"].includes(subtype) &&
parseInt(local_timestamp || "0"),
);
const modifiedTimestamp =
Number(lastTransaction?.local_timestamp || 0) * 1000;
const skeletonProps = {
active: true,
paragraph: false,
loading: isAccountInfoLoading || isMarketStatisticsInitialLoading,
};
React.useEffect(() => {
if (!account || isAccountInfoLoading || !representatives.length) return;
setRepresentativeAccount(find(representatives, ["account", account]) || {});
if (accountInfo.representative) {
const accountsRepresentative: Representative = find(representatives, [
"account",
accountInfo.representative,
])!;
setAccountsRepresentative(accountsRepresentative);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [account, isAccountInfoLoading, representatives]);
const votingWeight = new BigNumber(representativeAccount.weight)
.times(100)
.dividedBy(rawToRai(onlineStakeTotal))
.toNumber();
return (
<AccountDetailsLayout bordered={false}>
<>
<Row gutter={6}>
<Col xs={24}>
<AccountHeader />
</Col>
</Row>
<Row gutter={6}>
<Col xs={24} sm={6} md={4}>
{t("common.balance")}
</Col>
<Col xs={24} sm={18} md={20}>
<LoadingStatistic
isLoading={skeletonProps.loading}
suffix="NANO"
value={balance >= 1 ? balance : new BigNumber(balance).toFormat()}
/>
<Skeleton {...skeletonProps}>
{`${CurrencySymbol?.[fiat]}${fiatBalance} / ${btcBalance} BTC`}
</Skeleton>
</Col>
</Row>
{representativeAccount?.account ? (
<Row gutter={6}>
<Col xs={24} sm={6} md={4}>
{t("pages.account.votingWeight")}
<Tooltip
placement="right"
title={t("tooltips.votingWeight", {
minWeight: principalRepresentativeMinWeight,
})}
>
<QuestionCircle />
</Tooltip>
</Col>
<Col xs={24} sm={18} md={20}>
<>
{new BigNumber(representativeAccount.weight).toFormat()}
<br />
{new BigNumber(votingWeight).toFormat(
votingWeight > 0.01 ? 2 : 4,
)}
{t("pages.account.percentNetworkVotingWeight")}
</>
</Col>
</Row>
) : null}
<Row gutter={6}>
<Col xs={24} sm={6} md={4}>
{t("common.representative")}
</Col>
<Col xs={24} sm={18} md={20}>
<Skeleton
{...skeletonProps}
loading={isAccountInfoLoading || isRepresentativesLoading}
>
{accountsRepresentative?.account ? (
<>
<div style={{ display: "flex", margin: "3px 0" }}>
{typeof accountsRepresentative.isOnline === "boolean" ? (
<Tag
color={
accountsRepresentative.isOnline
? theme === Theme.DARK
? TwoToneColors.RECEIVE_DARK
: TwoToneColors.RECEIVE
: theme === Theme.DARK
? TwoToneColors.SEND_DARK
: TwoToneColors.SEND
}
className={`tag-${
accountsRepresentative.isOnline ? "online" : "offline"
}`}
>
{t(
`common.${
accountsRepresentative.isOnline
? "online"
: "offline"
}`,
)}
</Tag>
) : null}
{accountsRepresentative?.isPrincipal ? (
<Tag>{t("common.principalRepresentative")}</Tag>
) : null}
</div>
{accountsRepresentative.alias ? (
<div className="color-important">
{accountsRepresentative.alias}
</div>
) : null}
</>
) : null}
{!accountsRepresentative?.account &&
accountInfo.representative ? (
<div style={{ display: "flex", margin: "3px 0" }}>
<Tag
color={
theme === Theme.DARK
? TwoToneColors.WARNING_DARK
: TwoToneColors.WARNING
}
>
{t("pages.account.notVoting")}
</Tag>
</div>
) : null}
{accountsRepresentative?.account || accountInfo.representative ? (
<Link
to={`/account/${accountInfo.representative}${
section === Sections.TRANSACTIONS ? "/delegators" : ""
}`}
className="break-word"
>
{accountInfo.representative}
</Link>
) : null}
{!accountsRepresentative?.account && !accountInfo.representative
? t("pages.account.noRepresentative")
: null}
</Skeleton>
</Col>
</Row>
{parseFloat(balancePending) ? (
<Row gutter={6}>
<Col xs={24} sm={6} md={4}>
{t("transaction.pending")}
<Tooltip placement="right" title={t("tooltips.pending")}>
<QuestionCircle />
</Tooltip>
</Col>
<Col xs={24} sm={18} md={20}>
<Skeleton {...skeletonProps}>{balancePending} NANO</Skeleton>
</Col>
</Row>
) : null}
<Row gutter={6}>
<Col xs={24} sm={6} md={4}>
{t("pages.account.confirmationHeight")}
<Tooltip placement="right" title={t("tooltips.confirmationHeight")}>
<QuestionCircle />
</Tooltip>
</Col>
<Col xs={24} sm={18} md={20}>
<Skeleton {...skeletonProps}>
{new BigNumber(accountInfo.confirmation_height)
.plus(socketTransactions.length)
.toNumber()}
</Skeleton>
</Col>
</Row>
<Row gutter={6}>
<Col xs={24} sm={6} md={4}>
{t("pages.account.lastTransaction")}
</Col>
<Col xs={24} sm={18} md={20}>
<Skeleton {...skeletonProps} loading={isAccountHistoryLoading}>
{modifiedTimestamp ? (
<>
{timestampToDate(modifiedTimestamp)}{" "}
<span className="color-muted" style={{ fontSize: "12px" }}>
(
<TimeAgo
datetime={modifiedTimestamp}
live={false}
locale={i18next.language}
/>
)
</span>
</>
) : (
<>
{t("common.unknown")}
<Tooltip
placement="right"
title={t("tooltips.unknownLastTransaction")}
>
<QuestionCircle />
</Tooltip>
</>
)}
</Skeleton>
</Col>
</Row>
<ExtraRow account={account} />
</>
</AccountDetailsLayout>
);
};
export default AccountDetails; | the_stack |
export function WorldMagneticModel() {
this.coff = [
" 1, 0, -29404.5 , 0.0 , 6.7 , 0.0",
" 1, 1, -1450.7 , 4652.9 , 7.7 , -25.1",
" 2, 0, -2500.0 , 0.0 , -11.5 , 0.0",
" 2, 1, 2982.0 , -2991.6 , -7.1 , -30.2",
" 2, 2, 1676.8 , -734.8 , -2.2 , -23.9",
" 3, 0, 1363.9 , 0.0 , 2.8 , 0.0",
" 3, 1, -2381.0 , -82.2 , -6.2 , 5.7",
" 3, 2, 1236.2 , 241.8 , 3.4 , -1.0",
" 3, 3, 525.7 , -542.9 , -12.2 , 1.1",
" 4, 0, 903.1 , 0.0 , -1.1 , 0.0",
" 4, 1, 809.4 , 282.0 , -1.6 , 0.2",
" 4, 2, 86.2 , -158.4 , -6.0 , 6.9",
" 4, 3, -309.4 , 199.8 , 5.4 , 3.7",
" 4, 4, 47.9 , -350.1 , -5.5 , -5.6",
" 5, 0, -234.4 , 0.0 , -0.3 , 0.0",
" 5, 1, 363.1 , 47.7 , 0.6 , 0.1",
" 5, 2, 187.8 , 208.4 , -0.7 , 2.5",
" 5, 3, -140.7 , -121.3 , 0.1 , -0.9",
" 5, 4, -151.2 , 32.2 , 1.2 , 3.0",
" 5, 5, 13.7 , 99.1 , 1.0 , 0.5",
" 6, 0, 65.9 , 0.0 , -0.6 , 0.0",
" 6, 1, 65.6 , -19.1 , -0.4 , 0.1",
" 6, 2, 73.0 , 25.0 , 0.5 , -1.8",
" 6, 3, -121.5 , 52.7 , 1.4 , -1.4",
" 6, 4, -36.2 , -64.4 , -1.4 , 0.9",
" 6, 5, 13.5 , 9.0 , -0.0 , 0.1",
" 6, 6, -64.7 , 68.1 , 0.8 , 1.0",
" 7, 0, 80.6 , 0.0 , -0.1 , 0.0",
" 7, 1, -76.8 , -51.4 , -0.3 , 0.5",
" 7, 2, -8.3 , -16.8 , -0.1 , 0.6",
" 7, 3, 56.5 , 2.3 , 0.7 , -0.7",
" 7, 4, 15.8 , 23.5 , 0.2 , -0.2",
" 7, 5, 6.4 , -2.2 , -0.5 , -1.2",
" 7, 6, -7.2 , -27.2 , -0.8 , 0.2",
" 7, 7, 9.8 , -1.9 , 1.0 , 0.3",
" 8, 0, 23.6 , 0.0 , -0.1 , 0.0",
" 8, 1, 9.8 , 8.4 , 0.1 , -0.3",
" 8, 2, -17.5 , -15.3 , -0.1 , 0.7",
" 8, 3, -0.4 , 12.8 , 0.5 , -0.2",
" 8, 4, -21.1 , -11.8 , -0.1 , 0.5",
" 8, 5, 15.3 , 14.9 , 0.4 , -0.3",
" 8, 6, 13.7 , 3.6 , 0.5 , -0.5",
" 8, 7, -16.5 , -6.9 , 0.0 , 0.4",
" 8, 8, -0.3 , 2.8 , 0.4 , 0.1",
" 9, 0, 5.0 , 0.0 , -0.1 , 0.0",
" 9, 1, 8.2 , -23.3 , -0.2 , -0.3",
" 9, 2, 2.9 , 11.1 , -0.0 , 0.2",
" 9, 3, -1.4 , 9.8 , 0.4 , -0.4",
" 9, 4, -1.1 , -5.1 , -0.3 , 0.4",
" 9, 5, -13.3 , -6.2 , -0.0 , 0.1",
" 9, 6, 1.1 , 7.8 , 0.3 , -0.0",
" 9, 7, 8.9 , 0.4 , -0.0 , -0.2",
" 9, 8, -9.3 , -1.5 , -0.0 , 0.5",
" 9, 9, -11.9 , 9.7 , -0.4 , 0.2",
" 10, 0, -1.9 , 0.0 , 0.0 , 0.0",
" 10, 1, -6.2 , 3.4 , -0.0 , -0.0",
" 10, 2, -0.1 , -0.2 , -0.0 , 0.1",
" 10, 3, 1.7 , 3.5 , 0.2 , -0.3",
" 10, 4, -0.9 , 4.8 , -0.1 , 0.1",
" 10, 5, 0.6 , -8.6 , -0.2 , -0.2",
" 10, 6, -0.9 , -0.1 , -0.0 , 0.1",
" 10, 7, 1.9 , -4.2 , -0.1 , -0.0",
" 10, 8, 1.4 , -3.4 , -0.2 , -0.1",
" 10, 9, -2.4 , -0.1 , -0.1 , 0.2",
" 10, 10, -3.9 , -8.8 , -0.0 , -0.0",
" 11, 0, 3.0 , 0.0 , -0.0 , 0.0",
" 11, 1, -1.4 , -0.0 , -0.1 , -0.0",
" 11, 2, -2.5 , 2.6 , -0.0 , 0.1",
" 11, 3, 2.4 , -0.5 , 0.0 , 0.0",
" 11, 4, -0.9 , -0.4 , -0.0 , 0.2",
" 11, 5, 0.3 , 0.6 , -0.1 , -0.0",
" 11, 6, -0.7 , -0.2 , 0.0 , 0.0",
" 11, 7, -0.1 , -1.7 , -0.0 , 0.1",
" 11, 8, 1.4 , -1.6 , -0.1 , -0.0",
" 11, 9, -0.6 , -3.0 , -0.1 , -0.1",
" 11, 10, 0.2 , -2.0 , -0.1 , 0.0",
" 11, 11, 3.1 , -2.6 , -0.1 , -0.0",
" 12, 0, -2.0 , 0.0 , 0.0 , 0.0",
" 12, 1, -0.1 , -1.2 , -0.0 , -0.0",
" 12, 2, 0.5 , 0.5 , -0.0 , 0.0",
" 12, 3, 1.3 , 1.3 , 0.0 , -0.1",
" 12, 4, -1.2 , -1.8 , -0.0 , 0.1",
" 12, 5, 0.7 , 0.1 , -0.0 , -0.0",
" 12, 6, 0.3 , 0.7 , 0.0 , 0.0",
" 12, 7, 0.5 , -0.1 , -0.0 , -0.0",
" 12, 8, -0.2 , 0.6 , 0.0 , 0.1",
" 12, 9, -0.5 , 0.2 , -0.0 , -0.0",
" 12, 10, 0.1 , -0.9 , -0.0 , -0.0",
" 12, 11, -1.1 , -0.0 , -0.0 , 0.0",
" 12, 12, -0.3 , 0.5 , -0.1 , -0.1",
];
/* static variables */
/* some 13x13 2D arrays */
this.c = new Array(13);
this.cd = new Array(13);
this.tc = new Array(13);
this.dp = new Array(13);
this.k = new Array(13);
for(var i: any = 0; i< 13; i++)
{
this.c[i] = new Array(13);
this.cd[i] = new Array(13);
this.tc[i] = new Array(13);
this.dp[i] = new Array(13);
this.k[i] = new Array(13);
}
/* some 1D arrays */
this.snorm = new Array(169);
this.sp = new Array(13);
this.cp = new Array(13);
this.fn = new Array(13);
this.fm = new Array(13);
this.pp = new Array(13);
/* locals */
var maxdeg = 12;
var maxord;
var i,j,D1,D2,n,m;
var a,b,a2,b2,c2,a4,b4,c4,re;
var gnm,hnm,dgnm,dhnm,flnmj;
var c_str;
var c_flds;
/* INITIALIZE CONSTANTS */
maxord = maxdeg;
this.sp[0] = 0.0;
this.cp[0] = this.snorm[0] = this.pp[0] = 1.0;
this.dp[0][0] = 0.0;
a = 6378.137;
b = 6356.7523142;
re = 6371.2;
a2 = a*a;
b2 = b*b;
c2 = a2-b2;
a4 = a2*a2;
b4 = b2*b2;
c4 = a4 - b4;
/* READ WORLD MAGNETIC MODEL SPHERICAL HARMONIC COEFFICIENTS */
this.c[0][0] = 0.0;
this.cd[0][0] = 0.0;
for (i = 0; i < this.coff.length; i++) {
c_str = this.coff[i];
c_flds = c_str.split(",");
n = parseInt(c_flds[0],10);
m = parseInt(c_flds[1],10);
gnm = parseFloat(c_flds[2]);
hnm = parseFloat(c_flds[3]);
dgnm = parseFloat(c_flds[4]);
dhnm = parseFloat(c_flds[5]);
if (m <= n) {
this.c[m][n] = gnm;
this.cd[m][n] = dgnm;
if (m != 0) {
this.c[n][m-1] = hnm;
this.cd[n][m-1] = dhnm;
}
}
}
/* CONVERT SCHMIDT NORMALIZED GAUSS COEFFICIENTS TO UNNORMALIZED */
this.snorm[0] = 1.0;
for (n=1; n<=maxord; n++)
{
this.snorm[n] = this.snorm[n-1]*(2*n-1)/n;
j = 2;
for (m=0,D1=1,D2=(n-m+D1)/D1; D2>0; D2--,m+=D1)
{
this.k[m][n] = (((n-1)*(n-1))-(m*m))/((2*n-1)*(2*n-3));
if (m > 0)
{
flnmj = ((n-m+1)*j)/(n+m);
this.snorm[n+m*13] = this.snorm[n+(m-1)*13]*Math.sqrt(flnmj);
j = 1;
this.c[n][m-1] = this.snorm[n+m*13]*this.c[n][m-1];
this.cd[n][m-1] = this.snorm[n+m*13]*this.cd[n][m-1];
}
this.c[m][n] = this.snorm[n+m*13]*this.c[m][n];
this.cd[m][n] = this.snorm[n+m*13]*this.cd[m][n];
}
this.fn[n] = (n+1);
this.fm[n] = n;
}
this.k[1][1] = 0.0;
this.fm[0] = 0.0;// !!!!!! WMM C and Fortran both have a bug in that fm[0] is not initialised
}
WorldMagneticModel.prototype.declination = function(altitudeKm, latitudeDegrees, longitudeDegrees, yearFloat) {
/* locals */
var a = 6378.137;
var b = 6356.7523142;
var re = 6371.2;
var a2 = a*a;
var b2 = b*b;
var c2 = a2-b2;
var a4 = a2*a2;
var b4 = b2*b2;
var c4 = a4 - b4;
var D3, D4;
var dip, ti, gv, dec;
var n,m;
var pi, dt, rlon, rlat, srlon, srlat, crlon, crlat,srlat2,
crlat2, q, q1, q2, ct, d,aor,ar, br, r, r2, bpp, par,
temp1,parp,temp2,bx,by,bz,bh,dtr,bp,bt, st,ca,sa;
var maxord = 12;
var alt = altitudeKm;
var glon = longitudeDegrees;
var glat = latitudeDegrees;
/*************************************************************************/
dt = yearFloat - 2020.0;
//if more then 5 years has passed since last epoch update then return invalid
if ((dt < 0.0) || (dt > 5.0))
return -999;
pi = 3.14159265359;
dtr = pi/180.0;
rlon = glon*dtr;
rlat = glat*dtr;
srlon = Math.sin(rlon);
srlat = Math.sin(rlat);
crlon = Math.cos(rlon);
crlat = Math.cos(rlat);
srlat2 = srlat*srlat;
crlat2 = crlat*crlat;
this.sp[1] = srlon;
this.cp[1] = crlon;
/* CONVERT FROM GEODETIC COORDS. TO SPHERICAL COORDS. */
q = Math.sqrt(a2-c2*srlat2);
q1 = alt*q;
q2 = ((q1+a2)/(q1+b2))*((q1+a2)/(q1+b2));
ct = srlat/Math.sqrt(q2*crlat2+srlat2);
st = Math.sqrt(1.0-(ct*ct));
r2 = (alt*alt)+2.0*q1+(a4-c4*srlat2)/(q*q);
r = Math.sqrt(r2);
d = Math.sqrt(a2*crlat2+b2*srlat2);
ca = (alt+d)/r;
sa = c2*crlat*srlat/(r*d);
for (m=2; m<=maxord; m++)
{
this.sp[m] = this.sp[1]*this.cp[m-1]+this.cp[1]*this.sp[m-1];
this.cp[m] = this.cp[1]*this.cp[m-1]-this.sp[1]*this.sp[m-1];
}
aor = re/r;
ar = aor*aor;
br = bt = bp = bpp = 0.0;
for (n=1; n<=maxord; n++)
{
ar = ar*aor;
for (m=0,D3=1,D4=(n+m+D3)/D3; D4>0; D4--,m+=D3)
{
/*
COMPUTE UNNORMALIZED ASSOCIATED LEGENDRE POLYNOMIALS
AND DERIVATIVES VIA RECURSION RELATIONS
*/
if (n == m)
{
this.snorm[n+m*13] = st*this.snorm[n-1+(m-1)*13];
this.dp[m][n] = st*this.dp[m-1][n-1]+ct*this.snorm[n-1+(m-1)*13];
}
else if (n == 1 && m == 0)
{
this.snorm[n+m*13] = ct*this.snorm[n-1+m*13];
this.dp[m][n] = ct*this.dp[m][n-1]-st*this.snorm[n-1+m*13];
}
else if (n > 1 && n != m)
{
if (m > n-2) this.snorm[n-2+m*13] = 0.0;
if (m > n-2) this.dp[m][n-2] = 0.0;
this.snorm[n+m*13] = ct*this.snorm[n-1+m*13]-this.k[m][n]*this.snorm[n-2+m*13];
this.dp[m][n] = ct*this.dp[m][n-1] - st*this.snorm[n-1+m*13]-this.k[m][n]*this.dp[m][n-2];
}
/*
TIME ADJUST THE GAUSS COEFFICIENTS
*/
this.tc[m][n] = this.c[m][n]+dt*this.cd[m][n];
if (m != 0) this.tc[n][m-1] = this.c[n][m-1]+dt*this.cd[n][m-1];
/*
ACCUMULATE TERMS OF THE SPHERICAL HARMONIC EXPANSIONS
*/
par = ar*this.snorm[n+m*13];
if (m == 0)
{
temp1 = this.tc[m][n]*this.cp[m];
temp2 = this.tc[m][n]*this.sp[m];
}
else
{
temp1 = this.tc[m][n]*this.cp[m]+this.tc[n][m-1]*this.sp[m];
temp2 = this.tc[m][n]*this.sp[m]-this.tc[n][m-1]*this.cp[m];
}
bt = bt-ar*temp1*this.dp[m][n];
bp += (this.fm[m]*temp2*par);
br += (this.fn[n]*temp1*par);
/*
SPECIAL CASE: NORTH/SOUTH GEOGRAPHIC POLES
*/
if (st == 0.0 && m == 1)
{
if (n == 1) this.pp[n] = this.pp[n-1];
else this.pp[n] = this.ct*this.pp[n-1]-this.k[m][n]*this.pp[n-2];
parp = ar*this.pp[n];
bpp += (this.fm[m]*temp2*parp);
}
}
}
if (st == 0.0)
bp = bpp;
else
bp /= st;
/*
ROTATE MAGNETIC VECTOR COMPONENTS FROM SPHERICAL TO
GEODETIC COORDINATES
*/
bx = -bt*ca-br*sa;
by = bp;
bz = bt*sa-br*ca;
/*
COMPUTE DECLINATION (DEC), INCLINATION (DIP) AND
TOTAL INTENSITY (TI)
*/
bh = Math.sqrt((bx*bx)+(by*by));
ti = Math.sqrt((bh*bh)+(bz*bz));
dec = Math.atan2(by,bx)/dtr;
dip = Math.atan2(bz,bh)/dtr;
/*
COMPUTE MAGNETIC GRID VARIATION IF THE CURRENT
GEODETIC POSITION IS IN THE ARCTIC OR ANTARCTIC
(I.E. GLAT > +55 DEGREES OR GLAT < -55 DEGREES)
OTHERWISE, SET MAGNETIC GRID VARIATION TO -999.0
*/
gv = -999.0;
if (Math.abs(glat) >= 55.0)
{
if (glat > 0.0 && glon >= 0.0) gv = dec-glon;
if (glat > 0.0 && glon < 0.0) gv = dec+Math.abs(glon);
if (glat < 0.0 && glon >= 0.0) gv = dec+glon;
if (glat < 0.0 && glon < 0.0) gv = dec-Math.abs(glon);
if (gv > +180.0) gv -= 360.0;
if (gv < -180.0) gv += 360.0;
}
return dec;
}
WorldMagneticModel.prototype.knownAnswerTest = function(){
/* http://www.ngdc.noaa.gov/geomag/WMM WMM2010testvalues.pdf */
/* Lat Lon Dec */
/* Lon 240 = 120W, Lon 300 = 60W */
/* Alt 0 km */
var kat2010 = [
"80.00 ,0.00 ,-6.13 ",
"0.00 ,120.00 ,0.97 ",
"-80.00 ,240.00 ,70.21 "
];
var kat2012p5 = [
"80.00 ,0.00 ,-5.21 ",
"0.00 ,120.00 ,0.88 ",
"-80.00 ,240.00 ,70.04 "
];
var maxErr = 0.0;
for(var i=0; i<kat2010.length; i++){
var c_str = kat2010[i];
var c_flds = c_str.split(",");
var lat = parseFloat(c_flds[0]);
var lon = parseFloat(c_flds[1]);
var exp = parseFloat(c_flds[2]);
var maxExp;
var dec = this.declination(0,lat,lon,2010.0);
if(Math.abs(dec-exp) > maxErr){
maxErr = Math.abs(dec-exp);
maxExp = exp;
}
}
for (var i = 0; i < kat2012p5.length; i++) {
var c_str = kat2012p5[i];
var c_flds = c_str.split(",");
var lat = parseFloat(c_flds[0]);
var lon = parseFloat(c_flds[1]);
var exp = parseFloat(c_flds[2]);
var maxExp;
var dec = this.declination(0, lat, lon, 2012.5);
if (Math.abs(dec - exp) > maxErr) {
maxErr = Math.abs(dec - exp);
maxExp = exp;
}
}
return maxErr * 100 / maxExp;//max % error
}
/*
C***********************************************************************
C
C
C SUBROUTINE GEOMAG (GEOMAGNETIC FIELD COMPUTATION)
C
C
C***********************************************************************
C
C GEOMAG IS A NATIONAL GEOSPATIAL INTELLIGENCE AGENCY (NGA) STANDARD
C PRODUCT. IT IS COVERED UNDER NGA MILITARY SPECIFICATION:
C MIL-W-89500 (1993).
C
C***********************************************************************
C Contact Information
C
C Software and Model Support
C National Geophysical Data Center
C NOAA EGC/2
C 325 Broadway
C Boulder, CO 80303 USA
C Attn: Susan McLean or Stefan Maus
C Phone: (303) 497-6478 or -6522
C Email: Susan.McLean@noaa.gov or Stefan.Maus@noaa.gov
C Web: http://www.ngdc.noaa.gov/seg/WMM/
C
C Sponsoring Government Agency
C National Geospatial-Intelligence Agency
C PRG / CSAT, M.S. L-41
C 3838 Vogel Road
C Arnold, MO 63010
C Attn: Craig Rollins
C Phone: (314) 263-4186
C Email: Craig.M.Rollins@Nga.Mil
C
C Original Program By:
C Dr. John Quinn
C FLEET PRODUCTS DIVISION, CODE N342
C NAVAL OCEANOGRAPHIC OFFICE (NAVOCEANO)
C STENNIS SPACE CENTER (SSC), MS 39522-5001
C
C***********************************************************************
C
C PURPOSE: THIS ROUTINE COMPUTES THE DECLINATION (DEC),
C INCLINATION (DIP), TOTAL INTENSITY (TI) AND
C GRID VARIATION (GV - POLAR REGIONS ONLY, REFERENCED
C TO GRID NORTH OF A STEREOGRAPHIC PROJECTION) OF THE
C EARTH'S MAGNETIC FIELD IN GEODETIC COORDINATES
C FROM THE COEFFICIENTS OF THE CURRENT OFFICIAL
C DEPARTMENT OF DEFENSE (DOD) SPHERICAL HARMONIC WORLD
C MAGNETIC MODEL (WMM.COF). THE WMM SERIES OF MODELS IS
C UPDATED EVERY 5 YEARS ON JANUARY 1ST OF THOSE YEARS
C WHICH ARE DIVISIBLE BY 5 (I.E. 2000, 2005, 2010 ETC.)
C BY NOAA'S NATIONAL GEOPHYSICAL DATA CENTER IN
C COOPERATION WITH THE BRITISH GEOLOGICAL SURVEY (BGS).
C THE MODEL IS BASED ON GEOMAGNETIC FIELD MEASUREMENTS
C FROM SATELLITE AND GROUND OBSERVATORIES.
C
C***********************************************************************
C
C MODEL: THE WMM SERIES GEOMAGNETIC MODELS ARE COMPOSED
C OF TWO PARTS: THE MAIN FIELD MODEL, WHICH IS
C VALID AT THE BASE EPOCH OF THE CURRENT MODEL AND
C A SECULAR VARIATION MODEL, WHICH ACCOUNTS FOR SLOW
C TEMPORAL VARIATIONS IN THE MAIN GEOMAGNETIC FIELD
C FROM THE BASE EPOCH TO A MAXIMUM OF 5 YEARS BEYOND
C THE BASE EPOCH. FOR EXAMPLE, THE BASE EPOCH OF
C THE WMM-2005 MODEL IS 2005.0. THIS MODEL IS THEREFORE
C CONSIDERED VALID BETWEEN 2005.0 AND 2010.0. THE
C COMPUTED MAGNETIC PARAMETERS ARE REFERENCED TO THE
C WGS-84 ELLIPSOID.
C
C***********************************************************************
C
C ACCURACY: IN OCEAN AREAS AT THE EARTH'S SURFACE OVER THE
C ENTIRE 5 YEAR LIFE OF THE DEGREE AND ORDER 12
C SPHERICAL HARMONIC MODEL WMM-2005, THE ESTIMATED
C MAXIMUM RMS ERRORS FOR THE VARIOUS MAGNETIC COMPONENTS
C ARE:
C
C DEC - 0.5 Degrees
C DIP - 0.5 Degrees
C TI - 280.0 nanoTeslas (nT)
C GV - 0.5 Degrees
C
C OTHER MAGNETIC COMPONENTS THAT CAN BE DERIVED FROM
C THESE FOUR BY SIMPLE TRIGONOMETRIC RELATIONS WILL
C HAVE THE FOLLOWING APPROXIMATE ERRORS OVER OCEAN AREAS:
C
C X - 140 nT (North)
C Y - 140 nT (East)
C Z - 200 nT (Vertical) Positive is down
C H - 200 nT (Horizontal)
C
C OVER LAND THE MAXIMUM RMS ERRORS ARE EXPECTED TO BE
C HIGHER, ALTHOUGH THE RMS ERRORS FOR DEC, DIP, AND GV
C ARE STILL ESTIMATED TO BE LESS THAN 1.0 DEGREE, FOR
C THE ENTIRE 5-YEAR LIFE OF THE MODEL AT THE EARTH's
C SURFACE. THE OTHER COMPONENT ERRORS OVER LAND ARE
C MORE DIFFICULT TO ESTIMATE AND SO ARE NOT GIVEN.
C
C THE ACCURACY AT ANY GIVEN TIME FOR ALL OF THESE
C GEOMAGNETIC PARAMETERS DEPENDS ON THE GEOMAGNETIC
C LATITUDE. THE ERRORS ARE LEAST FROM THE EQUATOR TO
C MID-LATITUDES AND GREATEST NEAR THE MAGNETIC POLES.
C
C IT IS VERY IMPORTANT TO NOTE THAT A DEGREE AND
C ORDER 12 MODEL, SUCH AS WMM-2005, DESCRIBES ONLY
C THE LONG WAVELENGTH SPATIAL MAGNETIC FLUCTUATIONS
C DUE TO EARTH'S CORE. NOT INCLUDED IN THE WMM SERIES
C MODELS ARE INTERMEDIATE AND SHORT WAVELENGTH
C SPATIAL FLUCTUATIONS OF THE GEOMAGNETIC FIELD
C WHICH ORIGINATE IN THE EARTH'S MANTLE AND CRUST.
C CONSEQUENTLY, ISOLATED ANGULAR ERRORS AT VARIOUS
C POSITIONS ON THE SURFACE (PRIMARILY OVER LAND, IN
C CONTINENTAL MARGINS AND OVER OCEANIC SEAMOUNTS,
C RIDGES AND TRENCHES) OF SEVERAL DEGREES MAY BE
C EXPECTED. ALSO NOT INCLUDED IN THE MODEL ARE
C NONSECULAR TEMPORAL FLUCTUATIONS OF THE GEOMAGNETIC
C FIELD OF MAGNETOSPHERIC AND IONOSPHERIC ORIGIN.
C DURING MAGNETIC STORMS, TEMPORAL FLUCTUATIONS CAN
C CAUSE SUBSTANTIAL DEVIATIONS OF THE GEOMAGNETIC
C FIELD FROM MODEL VALUES. IN ARCTIC AND ANTARCTIC
C REGIONS, AS WELL AS IN EQUATORIAL REGIONS, DEVIATIONS
C FROM MODEL VALUES ARE BOTH FREQUENT AND PERSISTENT.
C
C IF THE REQUIRED DECLINATION ACCURACY IS MORE
C STRINGENT THAN THE WMM SERIES OF MODELS PROVIDE, THEN
C THE USER IS ADVISED TO REQUEST SPECIAL (REGIONAL OR
C LOCAL) SURVEYS BE PERFORMED AND MODELS PREPARED.
C REQUESTS OF THIS NATURE SHOULD BE MADE TO NIMA
C AT THE ADDRESS ABOVE.
C
C***********************************************************************
C
C USAGE: THIS ROUTINE IS BROKEN UP INTO TWO PARTS:
C
C A) AN INITIALIZATION MODULE, WHICH IS CALLED ONLY
C ONCE AT THE BEGINNING OF THE MAIN (CALLING)
C PROGRAM
C B) A PROCESSING MODULE, WHICH COMPUTES THE MAGNETIC
C FIELD PARAMETERS FOR EACH SPECIFIED GEODETIC
C POSITION (ALTITUDE, LATITUDE, LONGITUDE) AND TIME
C
C INITIALIZATION IS MADE VIA A SINGLE CALL TO THE MAIN
C ENTRY POINT (GEOMAG), WHILE SUBSEQUENT PROCESSING
C CALLS ARE MADE THROUGH THE SECOND ENTRY POINT (GEOMG1).
C ONE CALL TO THE PROCESSING MODULE IS REQUIRED FOR EACH
C POSITION AND TIME.
C
C THE VARIABLE MAXDEG IN THE INITIALIZATION CALL IS THE
C MAXIMUM DEGREE TO WHICH THE SPHERICAL HARMONIC MODEL
C IS TO BE COMPUTED. IT MUST BE SPECIFIED BY THE USER
C IN THE CALLING ROUTINE. NORMALLY IT IS 12 BUT IT MAY
C BE SET LESS THAN 12 TO INCREASE COMPUTATIONAL SPEED AT
C THE EXPENSE OF REDUCED ACCURACY.
C
C THE PC VERSION OF THIS SUBROUTINE MUST BE COMPILED
C WITH A FORTRAN 77 COMPATIBLE COMPILER SUCH AS THE
C MICROSOFT OPTIMIZING FORTRAN COMPILER VERSION 4.1
C OR LATER.
C
C**********************************************************************
C
C REFERENCES:
C
C JOHN M. QUINN, DAVID J. KERRIDGE AND DAVID R. BARRACLOUGH,
C WORLD MAGNETIC CHARTS FOR 1985 - SPHERICAL HARMONIC
C MODELS OF THE GEOMAGNETIC FIELD AND ITS SECULAR
C VARIATION, GEOPHYS. J. R. ASTR. SOC. (1986) 87,
C PP 1143-1157
C
C DEFENSE MAPPING AGENCY TECHNICAL REPORT, TR 8350.2:
C DEPARTMENT OF DEFENSE WORLD GEODETIC SYSTEM 1984,
C SEPT. 30 (1987)
C
C JOHN M. QUINN, RACHEL J. COLEMAN, MICHAEL R. PECK, AND
C STEPHEN E. LAUBER; THE JOINT US/UK 1990 EPOCH
C WORLD MAGNETIC MODEL, TECHNICAL REPORT NO. 304,
C NAVAL OCEANOGRAPHIC OFFICE (1991)
C
C JOHN M. QUINN, RACHEL J. COLEMAN, DONALD L. SHIEL, AND
C JOHN M. NIGRO; THE JOINT US/UK 1995 EPOCH WORLD
C MAGNETIC MODEL, TECHNICAL REPORT NO. 314, NAVAL
C OCEANOGRAPHIC OFFICE (1995)
C
C SUSAN AMCMILLAN, DAVID R. BARRACLOUGH, JOHN M. QUINN, AND
C RACHEL J. COLEMAN; THE 1995 REVISION OF THE JOINT US/UK
C GEOMAGNETIC FIELD MODELS - I. SECULAR VARIATION, JOURNAL OF
C GEOMAGNETISM AND GEOELECTRICITY, VOL. 49, PP. 229-243
C (1997)
C
C JOHN M. QUINN, RACHEL J. COELMAN, SUSAM MACMILLAN, AND
C DAVID R. BARRACLOUGH; THE 1995 REVISION OF THE JOINT
C US/UK GEOMAGNETIC FIELD MODELS: II. MAIN FIELD,JOURNAL OF
C GEOMAGNETISM AND GEOELECTRICITY, VOL. 49, PP. 245 - 261
C (1997)
C
C***********************************************************************
C
C PARAMETER DESCRIPTIONS:
C
C A - SEMIMAJOR AXIS OF WGS-84 ELLIPSOID (KM)
C B - SEMIMINOR AXIS OF WGS-84 ELLIPSOID (KM)
C RE - MEAN RADIUS OF IAU-66 ELLIPSOID (KM)
C SNORM - SCHMIDT NORMALIZATION FACTORS
C C - GAUSS COEFFICIENTS OF MAIN GEOMAGNETIC MODEL (NT)
C CD - GAUSS COEFFICIENTS OF SECULAR GEOMAGNETIC MODEL (NT/YR)
C TC - TIME ADJUSTED GEOMAGNETIC GAUSS COEFFICIENTS (NT)
C OTIME - TIME ON PREVIOUS CALL TO GEOMAG (YRS)
C OALT - GEODETIC ALTITUDE ON PREVIOUS CALL TO GEOMAG (YRS)
C OLAT - GEODETIC LATITUDE ON PREVIOUS CALL TO GEOMAG (DEG.)
C TIME - COMPUTATION TIME (YRS) (INPUT)
C (EG. 1 JULY 1995 = 1995.500)
C ALT - GEODETIC ALTITUDE (KM) (INPUT)
C GLAT - GEODETIC LATITUDE (DEG.) (INPUT)
C GLON - GEODETIC LONGITUDE (DEG.) (INPUT)
C EPOCH - BASE TIME OF GEOMAGNETIC MODEL (YRS)
C DTR - DEGREE TO RADIAN CONVERSION
C SP(M) - SINE OF (M*SPHERICAL COORD. LONGITUDE)
C CP(M) - COSINE OF (M*SPHERICAL COORD. LONGITUDE)
C ST - SINE OF (SPHERICAL COORD. LATITUDE)
C CT - COSINE OF (SPHERICAL COORD. LATITUDE)
C R - SPHERICAL COORDINATE RADIAL POSITION (KM)
C CA - COSINE OF SPHERICAL TO GEODETIC VECTOR ROTATION ANGLE
C SA - SINE OF SPHERICAL TO GEODETIC VECTOR ROTATION ANGLE
C BR - RADIAL COMPONENT OF GEOMAGNETIC FIELD (NT)
C BT - THETA COMPONENT OF GEOMAGNETIC FIELD (NT)
C BP - PHI COMPONENT OF GEOMAGNETIC FIELD (NT)
C P(N,M) - ASSOCIATED LEGENDRE POLYNOMIALS (UNNORMALIZED)
C PP(N) - ASSOCIATED LEGENDRE POLYNOMIALS FOR M=1 (UNNORMALIZED)
C DP(N,M)- THETA DERIVATIVE OF P(N,M) (UNNORMALIZED)
C BX - NORTH GEOMAGNETIC COMPONENT (NT)
C BY - EAST GEOMAGNETIC COMPONENT (NT)
C BZ - VERTICALLY DOWN GEOMAGNETIC COMPONENT (NT)
C BH - HORIZONTAL GEOMAGNETIC COMPONENT (NT)
C DEC - GEOMAGNETIC DECLINATION (DEG.) (OUTPUT)
C EAST=POSITIVE ANGLES
C WEST=NEGATIVE ANGLES
C DIP - GEOMAGNETIC INCLINATION (DEG.) (OUTPUT)
C DOWN=POSITIVE ANGLES
C UP=NEGATIVE ANGLES
C TI - GEOMAGNETIC TOTAL INTENSITY (NT) (OUTPUT)
C GV - GEOMAGNETIC GRID VARIATION (DEG.) (OUTPUT)
C REFERENCED TO GRID NORTH
C GRID NORTH REFERENCED TO 0 MERIDIAN
C OF A POLAR STEREOGRAPHIC PROJECTION
C (ARCTIC/ANTARCTIC ONLY)
C MAXDEG - MAXIMUM DEGREE OF SPHERICAL HARMONIC MODEL (INPUT)
C MOXORD - MAXIMUM ORDER OF SPHERICAL HARMONIC MODEL
C
C***********************************************************************
C
C NOTE: THIS VERSION OF GEOMAG USES A WMM SERIES GEOMAGNETIC
C FIELS MODEL REFERENCED TO THE WGS-84 GRAVITY MODEL
C ELLIPSOID
C
*/ | the_stack |
import { DeployData } from '@faasjs/func'
import { deepMerge } from '@faasjs/deep_merge'
import { Logger, Color } from '@faasjs/logger'
import { execSync } from 'child_process'
import {
checkBucket, createBucket, upload, remove
} from './cos'
import { scf } from './scf'
import { Provider } from '..'
import { join } from 'path'
const defaults = {
Handler: 'index.handler',
MemorySize: 64,
Timeout: 30,
Runtime: 'Nodejs12.16'
}
// 腾讯云内置插件 https://cloud.tencent.com/document/product/583/12060
const INCLUDED_NPM = [
'cos-nodejs-sdk-v5',
'base64-js',
'buffer',
'crypto-browserify',
'ieee754',
'imagemagick',
'isarray',
'jmespath',
'lodash',
'microtime',
'npm',
'punycode',
'puppeteer',
'qcloudapi-sdk',
'request',
'sax',
'scf-nodejs-serverlessdb-sdk',
'tencentcloud-sdk-nodejs',
'url',
'uuid',
'xml2js',
'xmlbuilder',
// 移除构建所需的依赖项
'@faasjs/load'
]
export async function deployCloudFunction (
tc: Provider,
data: DeployData,
origin: { [key: string]: any }
): Promise<void> {
const logger = new Logger(`${data.env}#${data.name}`)
const loggerPrefix = `[${data.env}#${data.name}]`
logger.raw(`${logger.colorfy(Color.GRAY, loggerPrefix + '[01/12]')} 生成配置项...`)
const config = deepMerge(origin)
// 补全默认参数
if (config.config.name) {
config.config.FunctionName = config.config.name
delete config.config.name
} else config.config.FunctionName = data.name.replace(/[^a-zA-Z0-9-_]/g, '_')
if (!config.config.Description) config.config.Description = `Source: ${data.name}\nPublished by ${process.env.LOGNAME}\nPublished at ${config.config.version}`
if (config.config.memorySize) {
config.config.MemorySize = config.config.memorySize
delete config.config.memorySize
}
if (config.config.timeout) {
config.config.Timeout = config.config.timeout
delete config.config.timeout
}
config.config = deepMerge(defaults, config.config, {
// 基本参数
Region: tc.config.region,
Namespace: data.env,
Environment: {
Variables: [
{
Key: 'FaasMode',
Value: 'remote'
},
{
Key: 'FaasEnv',
Value: data.env
},
{
Key: 'FaasLog',
Value: 'debug'
},
{
Key: 'NODE_ENV',
Value: data.env
}
]
},
FunctionVersion: '1',
// 构建参数
filename: data.filename,
name: data.name,
version: data.version,
env: data.env,
dependencies: data.dependencies,
tmp: data.tmp,
// cos 参数
Bucket: `scf-${tc.config.appId}`,
FilePath: `${data.tmp}deploy.zip`,
CosObjectName: data.env + '/' + config.config.FunctionName + '/' + data.version + '.zip'
})
logger.debug('[01/12] 完成配置项 %o', config)
logger.raw(`${logger.colorfy(Color.GRAY, loggerPrefix + '[02/12]')} 生成代码包...`)
logger.debug('[2.1/12] 生成 index.js...')
// eslint-disable-next-line @typescript-eslint/no-var-requires
const ts = await require('@faasjs/load').loadTs(config.config.filename, {
output: {
file: config.config.tmp + '/index.js',
format: 'cjs',
name: 'index',
banner: `/**
* @name ${config.config.name}
* @author ${config.config.author}
* @build ${config.config.version}
* @staging ${config.config.env}
* @dependencies ${Object.keys(config.config.dependencies).join(',')}
*/`,
footer: `
const main = module.exports;
main.config = ${JSON.stringify(data.config)};
if(typeof cloud_function !== 'undefined' && !main.plugins.find(p => p.type === 'cloud_function'))
main.plugins.unshift(new cloud_function.CloudFunction(main.config.plugins['cloud_function'] || {}))
module.exports = main.export();`
},
modules: {
excludes: INCLUDED_NPM,
additions: Object.keys(config.config.dependencies).concat(['@faasjs/tencentcloud'])
}
})
logger.debug('%o', ts.modules)
logger.debug('[2.2/12] 生成 node_modules...')
for (const key in ts.modules) {
const target = join(config.config.tmp, 'node_modules', key)
execSync(`mkdir -p ${target}`)
execSync(`rsync -avhpr --exclude={'*.cache','*.bin','LICENSE','license','ChangeLog','CHANGELOG','*.ts','*.flow','*.map','*.md','node_modules/*/node_modules','__tests__'} ${join(ts.modules[key], '*')} ${target}`)
}
execSync(`rm -rf ${join(config.config.tmp, 'node_modules', '*', 'node_modules')}`)
logger.raw(`${logger.colorfy(Color.GRAY, loggerPrefix + '[03/12]')} 打包代码包...`)
execSync(`cd ${config.config.tmp} && zip -r deploy.zip *`)
logger.raw(`${logger.colorfy(Color.GRAY, loggerPrefix + '[04/12]')} 检查 COS...`)
try {
logger.debug('[4.1/12] 检查 Cos Bucket 状态')
await checkBucket(tc, {
Bucket: config.config.Bucket,
Region: tc.config.region
})
logger.debug('[4.2/12] Cos Bucket 已存在,跳过')
} catch (error) {
logger.debug('[4.2/12] 创建 Cos Bucket...')
await createBucket(tc, {
Bucket: config.config.Bucket,
Region: tc.config.region
})
}
logger.raw(`${logger.colorfy(Color.GRAY, loggerPrefix + '[05/12]')} 上传代码包...`)
await upload(tc, {
Bucket: config.config.Bucket,
FilePath: config.config.FilePath,
Key: config.config.CosObjectName,
Region: tc.config.region
})
logger.raw(`${logger.colorfy(Color.GRAY, loggerPrefix + '[06/12]')} 检查命名空间...`)
logger.debug('[6.1/12] 检查命名空间状态')
const namespaceList = await scf('ListNamespaces', tc.config, {})
if (!namespaceList.Namespaces.find((n: any) => n.Name === config.config.Namespace)) {
logger.debug('[6.2/12] 创建命名空间...')
await scf('CreateNamespace', tc.config, { Namespace: config.config.Namespace })
} else logger.debug('[6.2/12] 命名空间已存在,跳过')
logger.raw(`${logger.colorfy(Color.GRAY, loggerPrefix + '[07/12]')} 上传云函数...`)
try {
logger.debug('[7.1/12] 检查云函数是否已存在...')
await scf('GetFunction', tc.config, {
FunctionName: config.config.FunctionName,
Namespace: config.config.Namespace
})
logger.debug('[7.2/12] 更新云函数代码...')
await scf('UpdateFunctionCode', tc.config, {
CosBucketName: 'scf',
CosBucketRegion: config.config.Region,
CosObjectName: config.config.CosObjectName,
FunctionName: config.config.FunctionName,
Handler: config.config.Handler,
Namespace: config.config.Namespace
})
let status = null
while (status !== 'Active') {
logger.debug('[7.3/12] 等待云函数代码更新完成...')
status = await scf('GetFunction', tc.config, {
FunctionName: config.config.FunctionName,
Namespace: config.config.Namespace
}).then(res => res.Status)
}
logger.debug('[7.2/12] 更新云函数配置...')
await scf('UpdateFunctionConfiguration', tc.config, {
Environment: config.config.Environment,
FunctionName: config.config.FunctionName,
MemorySize: config.config.MemorySize,
Timeout: config.config.Timeout,
VpcConfig: config.config.VpcConfig,
Namespace: config.config.Namespace,
Role: config.config.Role,
ClsLogsetId: config.config.ClsLogsetId,
ClsTopicId: config.config.ClsTopicId,
Layers: config.config.Layers,
DeadLetterConfig: config.config.DeadLetterConfig,
PublicNetConfig: config.config.PublicNetConfig,
CfsConfig: config.config.CfsConfig,
InitTimeout: config.config.InitTimeout
})
status = null
while (status !== 'Active') {
logger.debug('[7.3/12] 等待云函数配置更新完成...')
status = await scf('GetFunction', tc.config, {
FunctionName: config.config.FunctionName,
Namespace: config.config.Namespace
}).then(res => res.Status)
}
} catch (error: any) {
if (error.message.startsWith('ResourceNotFound')) {
logger.debug('[7.2/12] 创建云函数...')
await scf('CreateFunction', tc.config, {
ClsLogsetId: config.config.ClsLogsetId,
ClsTopicId: config.config.ClsTopicId,
Code: {
CosBucketName: 'scf',
CosBucketRegion: config.config.Region,
CosObjectName: config.config.CosObjectName
},
CodeSource: config.config.CodeSource,
Environment: config.config.Environment,
FunctionName: config.config.FunctionName,
Handler: config.config.Handler,
Description: config.config.Description,
Namespace: config.config.Namespace,
MemorySize: config.config.MemorySize,
Runtime: config.config.Runtime,
Role: config.config.Role,
Timeout: config.config.Timeout,
VpcConfig: config.config.VpcConfig,
Layers: config.config.Layers,
DeadLetterConfig: config.config.DeadLetterConfig,
PublicNetConfig: config.config.PublicNetConfig,
CfsConfig: config.config.CfsConfig,
InitTimeout: config.config.InitTimeout
})
// eslint-disable-next-line no-constant-condition
while (true) {
logger.debug('[7.3/12] 等待云函数代码更新完成...')
if ((await scf('GetFunction', tc.config, {
FunctionName: config.config.FunctionName,
Namespace: config.config.Namespace
})).Status === 'Active') break
}
} else throw error
}
logger.raw(`${logger.colorfy(Color.GRAY, loggerPrefix + '[08/12]')} 发布版本...`)
const version = await scf('PublishVersion', tc.config, {
Description: `Published by ${process.env.LOGNAME}`,
FunctionName: config.config.FunctionName,
Namespace: config.config.Namespace
})
config.config.FunctionVersion = version.FunctionVersion
// eslint-disable-next-line no-constant-condition
while (true) {
logger.debug('[8.1/12] 等待版本发布完成...')
if ((await scf('GetFunction', tc.config, {
FunctionName: config.config.FunctionName,
Namespace: config.config.Namespace,
Qualifier: config.config.FunctionVersion
})).Status === 'Active') break
}
logger.raw(`${logger.colorfy(Color.GRAY, loggerPrefix + '[09/12]')} 更新别名...`)
try {
logger.debug('[9.1/12] 检查别名状态...')
await scf('GetAlias', tc.config, {
Name: config.config.Namespace,
FunctionName: config.config.FunctionName,
Namespace: config.config.Namespace
})
logger.debug('[9.2/12] 更新别名...')
await scf('UpdateAlias', tc.config, {
Name: config.config.Namespace,
FunctionName: config.config.FunctionName,
Namespace: config.config.Namespace,
FunctionVersion: config.config.FunctionVersion,
})
} catch (error: any) {
if (error.message.startsWith('ResourceNotFound.Alias')) {
logger.debug('[9.2/12] 创建别名...')
await scf('CreateAlias', tc.config, {
Name: config.config.Namespace,
FunctionName: config.config.FunctionName,
FunctionVersion: config.config.FunctionVersion,
Namespace: config.config.Namespace
})
} else
throw error
}
logger.raw(`${logger.colorfy(Color.GRAY, loggerPrefix + '[10/12]')} 更新触发器...`)
const triggers = await scf('ListTriggers', tc.config, {
FunctionName: config.config.FunctionName,
Namespace: config.config.Namespace
})
for (const trigger of triggers.Triggers) {
logger.debug('[10.1/12] 删除旧触发器: %s...', trigger.TriggerName)
await scf('DeleteTrigger', tc.config, {
FunctionName: config.config.FunctionName,
Namespace: config.config.Namespace,
TriggerName: trigger.TriggerName,
Type: trigger.Type,
Qualifier: trigger.Qualifier
})
}
if (config.config.triggers)
for (const trigger of config.config.triggers) {
logger.debug('[10.2/12] 创建触发器 %s...', trigger.name)
await scf('CreateTrigger', tc.config, {
FunctionName: config.config.FunctionName,
TriggerName: trigger.name || trigger.type,
Type: trigger.type,
TriggerDesc: trigger.value,
Qualifier: config.config.FunctionVersion,
Namespace: config.config.Namespace,
Enable: 'OPEN'
})
}
logger.raw(`${logger.colorfy(Color.GRAY, loggerPrefix + '[11/12]')} 更新预制并发...`)
logger.debug('[11.1/12] 查询预制并发...')
const current = await scf('GetProvisionedConcurrencyConfig', tc.config, {
FunctionName: config.config.FunctionName,
Namespace: config.config.Namespace
})
if (current.Allocated.length)
for (const allocated of current.Allocated) {
logger.debug('[11.2/12] 删除旧预制并发 %o...', allocated)
await scf('DeleteProvisionedConcurrencyConfig', tc.config, {
FunctionName: config.config.FunctionName,
Namespace: config.config.Namespace,
Qualifier: allocated.Qualifier
})
}
if (config.config.provisionedConcurrent && config.config.provisionedConcurrent.executions) {
logger.debug('[11/12] 添加预制并发 %s...', config.config.provisionedConcurrent.executions)
await scf('PutProvisionedConcurrencyConfig', tc.config, {
FunctionName: config.config.FunctionName,
Namespace: config.config.Namespace,
Qualifier: config.config.FunctionVersion,
VersionProvisionedConcurrencyNum: config.config.provisionedConcurrent.executions
})
}
logger.raw(`${logger.colorfy(Color.GRAY, loggerPrefix + '[12/12]')} 清理文件...`)
logger.debug('[12.1/12] 清理 Cos Bucket...')
await remove(tc, {
Bucket: config.config.Bucket,
Key: config.config.CosObjectName,
Region: config.config.Region
})
if (process.env.FaasLog !== 'debug') {
logger.debug('[12.2/12] 清理本地文件...')
execSync(`rm -rf ${config.config.tmp}`)
}
logger.info(`云函数发布完成 ${data.env}#${data.name}#${config.config.FunctionVersion}`)
} | the_stack |
import { Button, Form, message, Modal, Select, Tag, Typography } from 'antd';
import React, { useEffect, useRef, useState } from 'react';
import styled from 'styled-components';
import { Link } from 'react-router-dom';
import { useAddOwnerMutation } from '../../../../../../../graphql/mutations.generated';
import { useGetSearchResultsLazyQuery } from '../../../../../../../graphql/search.generated';
import {
CorpUser,
EntityType,
OwnerEntityType,
OwnershipType,
SearchResult,
} from '../../../../../../../types.generated';
import { useEntityRegistry } from '../../../../../../useEntityRegistry';
import { CustomAvatar } from '../../../../../../shared/avatar';
import analytics, { EventType, EntityActionType } from '../../../../../../analytics';
import { OWNERSHIP_DISPLAY_TYPES } from './ownershipUtils';
const SearchResultContainer = styled.div`
display: flex;
justify-content: space-between;
align-items: center;
padding: 12px;
`;
const SearchResultContent = styled.div`
display: flex;
justify-content: start;
align-items: center;
`;
const SearchResultDisplayName = styled.div`
margin-left: 12px;
`;
type Props = {
urn: string;
type: EntityType;
visible: boolean;
defaultOwnerType?: OwnershipType;
hideOwnerType?: boolean | undefined;
onClose: () => void;
refetch?: () => Promise<any>;
};
type SelectedActor = {
displayName: string;
type: EntityType;
urn: string;
};
export const AddOwnerModal = ({ urn, type, visible, hideOwnerType, defaultOwnerType, onClose, refetch }: Props) => {
const entityRegistry = useEntityRegistry();
const [selectedActor, setSelectedActor] = useState<SelectedActor | undefined>(undefined);
const [selectedOwnerType, setSelectedOwnerType] = useState<OwnershipType>(defaultOwnerType || OwnershipType.None);
const [userSearch, { data: userSearchData }] = useGetSearchResultsLazyQuery();
const [groupSearch, { data: groupSearchData }] = useGetSearchResultsLazyQuery();
const [addOwnerMutation] = useAddOwnerMutation();
// User and group dropdown search results!
const userSearchResults = userSearchData?.search?.searchResults || [];
const groupSearchResults = groupSearchData?.search?.searchResults || [];
const combinedSearchResults = [...userSearchResults, ...groupSearchResults];
const inputEl = useRef(null);
const onOk = async () => {
if (!selectedActor) {
return;
}
try {
const ownerEntityType =
selectedActor.type === EntityType.CorpGroup ? OwnerEntityType.CorpGroup : OwnerEntityType.CorpUser;
await addOwnerMutation({
variables: {
input: {
ownerUrn: selectedActor.urn,
type: selectedOwnerType,
resourceUrn: urn,
ownerEntityType,
},
},
});
message.success({ content: 'Owner Added', duration: 2 });
analytics.event({
type: EventType.EntityActionEvent,
actionType: EntityActionType.UpdateOwnership,
entityType: type,
entityUrn: urn,
});
} catch (e: unknown) {
message.destroy();
if (e instanceof Error) {
message.error({ content: `Failed to add owner: \n ${e.message || ''}`, duration: 3 });
}
}
setSelectedActor(undefined);
refetch?.();
onClose();
};
// When a user search result is selected, set the urn as the selected urn.
const onSelectActor = (newUrn: string) => {
if (inputEl && inputEl.current) {
(inputEl.current as any).blur();
}
const filteredActors = combinedSearchResults
.filter((result) => result.entity.urn === newUrn)
.map((result) => result.entity);
if (filteredActors.length) {
const actor = filteredActors[0];
setSelectedActor({
displayName: entityRegistry.getDisplayName(actor.type, actor),
type: actor.type,
urn: actor.urn,
});
}
};
// When a user search result is selected, set the urn as the selected urn.
const onDeselectActor = (_: string) => {
setSelectedActor(undefined);
};
// When a user search result is selected, set the urn as the selected urn.
const onSelectOwnerType = (newType: OwnershipType) => {
setSelectedOwnerType(newType);
};
// Invokes the search API as the user types
const handleSearch = (entityType: EntityType, text: string, searchQuery: any) => {
if (text.length > 2) {
searchQuery({
variables: {
input: {
type: entityType,
query: text,
start: 0,
count: 5,
},
},
});
}
};
// Invokes the user search API for both users and groups.
// TODO: replace with multi entity search.
const handleActorSearch = (text: string) => {
handleSearch(EntityType.CorpUser, text, userSearch);
handleSearch(EntityType.CorpGroup, text, groupSearch);
};
// Renders a search result in the select dropdown.
const renderSearchResult = (result: SearchResult) => {
const avatarUrl =
result.entity.type === EntityType.CorpUser
? (result.entity as CorpUser).editableProperties?.pictureLink || undefined
: undefined;
const displayName = entityRegistry.getDisplayName(result.entity.type, result.entity);
return (
<SearchResultContainer>
<SearchResultContent>
<CustomAvatar
size={32}
name={displayName}
photoUrl={avatarUrl}
isGroup={result.entity.type === EntityType.CorpGroup}
/>
<SearchResultDisplayName>
<div>
<Typography.Text type="secondary">
{entityRegistry.getEntityName(result.entity.type)}
</Typography.Text>
</div>
<div>{displayName}</div>
</SearchResultDisplayName>
</SearchResultContent>
<Link
target="_blank"
rel="noopener noreferrer"
to={() => `/${entityRegistry.getPathName(result.entity.type)}/${result.entity.urn}`}
>
View
</Link>{' '}
</SearchResultContainer>
);
};
const selectValue = (selectedActor && [selectedActor.displayName]) || [];
const ownershipTypes = OWNERSHIP_DISPLAY_TYPES;
useEffect(() => {
if (ownershipTypes) {
setSelectedOwnerType(ownershipTypes[0].type);
}
}, [ownershipTypes]);
// Handle the Enter press
// TODO: Allow user to be selected prior to executed the save.
// useEnterKeyListener({
// querySelectorToExecuteClick: selectedActor && '#addOwnerButton',
// });
return (
<Modal
title="Add Owner"
visible={visible}
onCancel={onClose}
keyboard
footer={
<>
<Button onClick={onClose} type="text">
Cancel
</Button>
<Button id="addOwnerButton" disabled={selectedActor === undefined} onClick={onOk}>
Add
</Button>
</>
}
>
<Form layout="vertical" colon={false}>
<Form.Item label={<Typography.Text strong>Owner</Typography.Text>}>
<Typography.Paragraph>Find a user or group</Typography.Paragraph>
<Form.Item name="owner">
<Select
autoFocus
filterOption={false}
value={selectValue}
mode="multiple"
ref={inputEl}
placeholder="Search for users or groups..."
onSelect={(actorUrn: any) => onSelectActor(actorUrn)}
onDeselect={(actorUrn: any) => onDeselectActor(actorUrn)}
onSearch={handleActorSearch}
tagRender={(tagProps) => <Tag>{tagProps.value}</Tag>}
>
{combinedSearchResults?.map((result) => (
<Select.Option key={result?.entity?.urn} value={result.entity.urn}>
{renderSearchResult(result)}
</Select.Option>
))}
</Select>
</Form.Item>
</Form.Item>
{!hideOwnerType && (
<Form.Item label={<Typography.Text strong>Type</Typography.Text>}>
<Typography.Paragraph>Choose an owner type</Typography.Paragraph>
<Form.Item name="type">
<Select
defaultValue={selectedOwnerType}
value={selectedOwnerType}
onChange={onSelectOwnerType}
>
{ownershipTypes.map((ownerType) => (
<Select.Option key={ownerType.type} value={ownerType.type}>
<Typography.Text>{ownerType.name}</Typography.Text>
<div>
<Typography.Paragraph style={{ wordBreak: 'break-all' }} type="secondary">
{ownerType.description}
</Typography.Paragraph>
</div>
</Select.Option>
))}
</Select>
</Form.Item>
</Form.Item>
)}
</Form>
</Modal>
);
}; | the_stack |
import { Dom7Array } from 'dom7';
import Framework7, { CSSSelector, Framework7EventsClass, Framework7Plugin } from '../app/app-class';
import { View } from '../view/view';
import { Searchbar } from '../searchbar/searchbar';
export namespace SmartSelect {
interface Events {
/** Event will be triggered before Smart Select open. As second argument it receives "prevent" function that can be called to prevent Smart Select from opening */
beforeOpen: (smartSelect: SmartSelect, prevent: () => void) => void;
/** Event will be triggered when Smart Select starts its opening animation. As an argument event handler receives smart select instance */
open: (smartSelect: SmartSelect) => void;
/** Event will be triggered when Smart Select completes its opening animation. As an argument event handler receives smart select instance */
opened: (smartSelect: SmartSelect) => void;
/** Event will be triggered when Smart Select starts its closing animation. As an argument event handler receives smart select instance */
close: (smartSelect: SmartSelect) => void;
/** Event will be triggered after Smart Select completes its closing animation. As an argument event handler receives smart select instance */
closed: (smartSelect: SmartSelect) => void;
/** Event will be triggered right before Smart Select instance will be destroyed */
beforeDestroy: (smartSelect: SmartSelect) => void;
}
interface Parameters {
/** Smart Select element. Can be useful if you already have Smart Select element in your HTML and want to create new instance using this element */
el?: HTMLElement | CSSSelector;
/** Link to initialized View instance which is required for Smart Select to work. By default, if not specified, it will be opened in parent View. */
view?: View.View;
/** Visual element where to insert selected value. If not passed then it will look for <div class="item-after"> element */
valueEl?: HTMLElement | CSSSelector;
/** When enabled then smart select will automatically insert value text into "valueEl" in format returned by "formatValueText" */
setValueText?: boolean;
/** Custom function to format smart select text value that appears on list item */
formatValueText?: (values: any[]) => string;
/** Defines how to open Smart Select. Can be page or popup or popover or sheet (default is "page") */
openIn?: 'page' | 'popup' | 'popover' | 'sheet';
/** Enables smart select popup to push view/s behind on open (default false) */
popupPush?: boolean;
/** Enables ability to close smart select popup with swipe (default undefined) */
popupSwipeToClose?: boolean | undefined;
/** Enables smart select sheet to push view/s behind on open (default false) */
sheetPush?: boolean;
/** Enables ability to close smart select sheet with swipe (default undefined) */
sheetSwipeToClose?: boolean | undefined;
/** Enables smart select sheet backdrop (default false) */
sheetBackdrop?: boolean;
/** Smart select page title. If not passed then it will be the <div class="item-title"> text */
pageTitle?: string;
/** Smart select Page back link text (default 'Back') */
pageBackLinkText?: string;
/** Smart select Popup close link text (default 'Close') */
popupCloseLinkText?: string;
/** Smart select Popup will be opened as full screen popup on tablet */
popupTabletFullscreen?: boolean;
/** Smart select Sheet close link text (default 'Done') */
sheetCloseLinkText?: string;
/** Enables Searchbar on smart select page. If passed as object then it should be valid Searchbar parameters (default false) */
searchbar?: boolean | Searchbar.Parameters;
/** Searchbar placeholder text (default 'Search') */
searchbarPlaceholder?: string;
/** Searchbar "cancel" link text. Has effect only in iOS theme (default 'Cancel') */
searchbarDisableText?: string;
/** Enables searchbar disable button. By default, disabled for Aurora theme */
searchbarDisableButton?: boolean;
/** Value of "spellcheck" attribute on searchbar input (default false) */
searchbarSpellcheck?: boolean;
/** Appends block with content that displayed when there are no Searchbar results (default false) */
appendSearchbarNotFound?: boolean | string | HTMLElement;
/** If enabled then smart select will be automatically closed after user selectes any option (default false) */
closeOnSelect?: boolean;
/** Enable Virtual List for smart select if your select has a lot (hundreds, thousands) of options (default false) */
virtualList?: boolean;
/** Virtual list item height. If number - list item height in px. If function then function should return item height */
virtualListHeight?: number | Function;
/** When enabled it will scroll smart select content to first selected item on open (default false) */
scrollToSelectedItem?: boolean;
/** Smart select page form color theme. One of the default colors */
formColorTheme?: string;
/** Smart select navbar color theme. One of the default colors */
navbarColorTheme?: string;
/** Will add opened smart select modal (when openIn is popup, popover or sheet) to router history which gives ability to close smart select by going back in router history and set current route to the smart select modal (default false) */
routableModals?: boolean;
/** Smart select page/modal URL that will be set as a current route (default 'select/') */
url?: string;
/** Additional CSS class name to be set on Smart Select container (Page, Popup, Popover or Sheet) */
cssClass?: string;
/** Select option icon to be set on all options. If it just a string then will create an icon with this class. If it is in the format of `f7:icon_name` then it will create a F7-Icons icon. If it is in the format of `md:icon_name` then it will create a Material Icons icon. */
optionIcon?: string;
/** Same as `optionIcon` but will apply only when iOS theme is active */
optionIconIos?: string;
/** Same as `optionIcon` but will apply only when MD theme is active */
optionIconMd?: string;
/** Same as `optionIcon` but will apply only when Aurora theme is active */
optionIconAurora?: string;
/** Function to render smart select page, must return full page HTML string */
renderPage?: (items: any[]) => string;
/** Function to render smart select popup, must return full popup HTML string */
renderPopup?: (items: any[]) => string;
/** Function to render smart select sheet, must return full sheet HTML string */
renderSheet?: (items: any[]) => string;
/** Function to render smart select popover, must return full popover HTML string */
renderPopover?: (items: any[]) => string;
/** Function to render all smart select items, must return all items HTML string */
renderItems?: (items: any[]) => string;
/** Function to render smart select item, must return item HTML string */
renderItem?: (item: any, index: number) => string;
/** Function to render smart select searchbar dropdown, must return searchbar HTML string */
renderSearchbar?: () => string;
/** Object with events handlers.. */
on?: {
[event in keyof Events]?: Events[event];
};
}
interface SmartSelect extends Framework7EventsClass<Events> {
/** Link to global app instance */
app: Framework7;
/** Smart Select HTML element */
el: HTMLElement;
/** Dom7 instance with Smart Select HTML element */
$el: Dom7Array;
/** HTML element used to display value */
valueEl: HTMLElement;
/** Dom7 instance with HTML element used to display value */
$valueEl: Dom7Array;
/** Child select element <select> */
selectEl: HTMLElement;
/** Dom7 instance with child select element */
$selectEl: Dom7Array;
/** Smart Select URL (that was passed in url parameter) */
url: string;
/** Smart Select View (that was passed in view parameter) or found parent view */
view: View.View;
/** Smart Select parameters */
params: Parameters;
/** Scroll smart select content to first selected item */
scrollToSelectedItem(): SmartSelect;
/** Set new smart select value. In case of select is multiple it must be an array with new values */
setValue(value: string | number | any[]): SmartSelect;
/** Unset smart select value */
unsetValue(): SmartSelect;
/** Returns smart select value. In case of select is multiple it returns array with selected values */
getValue(): string | number | any[];
/** Open smart select. */
open(): SmartSelect;
/** Close smart select. */
close(): SmartSelect;
/** Destroy smart select */
destroy(): void;
}
interface DomEvents {
/** Event will be triggered before Smart Select open. event.detail.prevent is a function that can be called to prevent Smart Select from opening */
'smartselect:beforeopen': () => void;
/** Event will be triggered when Smart Select starts its opening animation */
'smartselect:open': () => void;
/** Event will be triggered after Smart Select completes its opening animation */
'smartselect:opened': () => void;
/** Event will be triggered when Smart Select starts its closing animation */
'smartselect:close': () => void;
/** Event will be triggered after Smart Select completes its closing animation */
'smartselect:closed': () => void;
/** Event will be triggered right before Smart Select instance will be destroyed */
'smartselect:beforedestroy': () => void;
}
interface AppMethods {
smartSelect: {
/** create Smart Select instance */
create(parameters: Parameters): SmartSelect;
/** destroy Smart Select instance */
destroy(el: HTMLElement | CSSSelector | SmartSelect): void;
/** get Smart Select instance by HTML element */
get(el: HTMLElement | CSSSelector): SmartSelect;
/** open Smart Select */
open(el: HTMLElement | CSSSelector): SmartSelect;
/** close Smart Select */
close(el: HTMLElement | CSSSelector): SmartSelect;
};
}
interface AppParams {
smartSelect?: Parameters | undefined;
}
interface AppEvents {
/** Event will be triggered before Smart Select open. As second argument it receives "prevent" function that can be called to prevent Smart Select from opening */
smartSelectBeforeOpen: (smartSelect: SmartSelect, prevent: () => void) => void;
/** Event will be triggered when Smart Select starts its opening animation. As an argument event handler receives smart select instance */
smartSelectOpen: (smartSelect: SmartSelect) => void;
/** Event will be triggered when Smart Select completes its opening animation. As an argument event handler receives smart select instance */
smartSelectOpened: (smartSelect: SmartSelect) => void;
/** Event will be triggered when Smart Select starts its closing animation. As an argument event handler receives smart select instance */
smartSelectClose: (smartSelect: SmartSelect) => void;
/** Event will be triggered after Smart Select completes its closing animation. As an argument event handler receives smart select instance */
smartSelectClosed: (smartSelect: SmartSelect) => void;
/** Event will be triggered right before Smart Select instance will be destroyed */
smartSelectBeforeDestroy: (smartSelect: SmartSelect) => void;
}
}
declare const SmartSelectComponent: Framework7Plugin;
export default SmartSelectComponent; | the_stack |
import {Navigator, URLOptions, NavigationOptions} from '@layr/navigator';
import {hasOwnProperty} from 'core-helpers';
import type {RoutableComponent} from './routable';
import type {Route, RouteOptions} from './route';
import type {WrapperOptions} from './wrapper';
import type {Pattern} from './pattern';
import {isRoutableClassOrInstance} from './utilities';
/**
* Defines a [route](https://layrjs.com/docs/v2/reference/route) for a static or instance method in a [routable component](https://layrjs.com/docs/v2/reference/routable#routable-component-class).
*
* @param pattern The canonical [URL pattern](https://layrjs.com/docs/v2/reference/route#url-pattern-type) of the route.
* @param [options] An object specifying the options to pass to the `Route`'s [constructor](https://layrjs.com/docs/v2/reference/route#constructor) when the route is created.
*
* @details
* **Shortcut functions:**
*
* In addition to defining a route, the decorator adds some shortcut functions to the decorated method so that you can interact with the route more easily.
*
* For example, if you define a `route` for a `Home()` method you automatically get the following functions:
*
* - `Home.matchURL(url)` is the equivalent of [`route.matchURL(url)`](https://layrjs.com/docs/v2/reference/route#match-url-instance-method).
* - `Home.generateURL(params, options)` is the equivalent of [`route.generateURL(params, options)`](https://layrjs.com/docs/v2/reference/route#generate-url-instance-method).
*
* If the defined `route` is controlled by a [`navigator`](https://layrjs.com/docs/v2/reference/navigator), you also get the following shortcut functions:
*
* - `Home.navigate(params, options)` is the equivalent of [`navigator.navigate(url, options)`](https://layrjs.com/docs/v2/reference/navigator#navigate-instance-method) where `url` is generated by calling [`route.generateURL(params, options)`](https://layrjs.com/docs/v2/reference/route#generate-url-instance-method).
* - `Home.redirect(params, options)` is the equivalent of [`navigator.redirect(url, options)`](https://layrjs.com/docs/v2/reference/navigator#redirect-instance-method) where `url` is generated by calling [`route.generateURL(params, options)`](https://layrjs.com/docs/v2/reference/route#generate-url-instance-method).
* - `Home.reload(params, options)` is the equivalent of [`navigator.reload(url)`](https://layrjs.com/docs/v2/reference/navigator#reload-instance-method) where `url` is generated by calling [`route.generateURL(params, options)`](https://layrjs.com/docs/v2/reference/route#generate-url-instance-method).
* - `Home.isActive(params)` returns a boolean indicating whether the `route`'s URL (generated by calling [`route.generateURL(params)`](https://layrjs.com/docs/v2/reference/route#generate-url-instance-method)) matches the current `navigator`'s URL.
*
* Lastly, if the defined `route` is controlled by a [`navigator`](https://layrjs.com/docs/v2/reference/navigator) that is created by using the [`useBrowserNavigator()`](https://layrjs.com/docs/v2/reference/react-integration#use-browser-navigator-react-hook) React hook, you also get the following shortcut function:
*
* - `Home.Link({params, hash, ...props})` is the equivalent of [`navigator.Link({to, ...props})`](https://layrjs.com/docs/v2/reference/browser-navigator#link-instance-method) where `to` is generated by calling [`route.generateURL(params, {hash})`](https://layrjs.com/docs/v2/reference/route#generate-url-instance-method).
*
* @examplelink See an example of use in the [`BrowserNavigator`](https://layrjs.com/docs/v2/reference/browser-navigator) class.
*
* @category Decorators
* @decorator
*/
export function route(pattern: Pattern, options: RouteOptions = {}) {
return function (
target: typeof RoutableComponent | RoutableComponent,
name: string,
descriptor: PropertyDescriptor
) {
const {value: method, get: originalGet, configurable, enumerable} = descriptor;
if (
!(
isRoutableClassOrInstance(target) &&
(typeof method === 'function' || originalGet !== undefined) &&
enumerable === false
)
) {
throw new Error(
`@route() should be used to decorate a routable component method (property: '${name}')`
);
}
const route: Route = target.setRoute(name, pattern, options);
const decorate = function (
this: typeof RoutableComponent | RoutableComponent,
method: Function
) {
const component = this;
defineMethod(method, 'matchURL', function (url: URL | string) {
return route.matchURL(url);
});
defineMethod(method, 'generateURL', function (params?: any, options?: URLOptions) {
return route.generateURL(component, params, options);
});
defineMethod(method, 'generatePath', function () {
return route.generatePath(component);
});
defineMethod(method, 'generateQueryString', function (params?: any) {
return route.generateQueryString(params);
});
Object.defineProperty(method, '__isDecorated', {value: true});
};
const decorateWithNavigator = function (
this: typeof RoutableComponent | RoutableComponent,
method: Function,
navigator: Navigator
) {
defineMethod(
method,
'navigate',
function (this: Function, params?: any, options?: URLOptions & NavigationOptions) {
return navigator.navigate(this.generateURL(params, options), options);
}
);
defineMethod(
method,
'redirect',
function (this: Function, params?: any, options?: URLOptions & NavigationOptions) {
return navigator.redirect(this.generateURL(params, options), options);
}
);
defineMethod(method, 'reload', function (this: Function, params?: any, options?: URLOptions) {
navigator.reload(this.generateURL(params, options));
});
defineMethod(method, 'isActive', function (this: Function) {
return this.matchURL(navigator.getCurrentURL()) !== undefined;
});
navigator.applyCustomRouteDecorators(this, method);
Object.defineProperty(method, '__isDecoratedWithNavigator', {value: true});
};
const defineMethod = function (object: any, name: string, func: Function) {
Object.defineProperty(object, name, {
value: func,
writable: true,
enumerable: false,
configurable: true
});
};
const get = function (this: typeof RoutableComponent | RoutableComponent) {
// TODO: Don't assume that `originalGet` returns a bound method (like when @view() is used).
// We should return a bound method in any case to make instance routes work
// (see `decorator.test.ts`)
const actualMethod = originalGet !== undefined ? originalGet.call(this) : method;
if (typeof actualMethod !== 'function') {
throw new Error(`@route() can only be used on methods`);
}
if (!hasOwnProperty(actualMethod, '__isDecorated')) {
decorate.call(this, actualMethod);
}
if (!hasOwnProperty(actualMethod, '__isDecoratedWithNavigator')) {
const navigator = this.findNavigator();
if (navigator !== undefined) {
decorateWithNavigator.call(this, actualMethod, navigator);
}
}
return actualMethod;
};
return {get, configurable, enumerable};
};
}
export function wrapper(pattern: Pattern, options: WrapperOptions = {}) {
return function (
target: typeof RoutableComponent | RoutableComponent,
name: string,
descriptor: PropertyDescriptor
) {
const {value: method, get, enumerable} = descriptor;
if (
!(
isRoutableClassOrInstance(target) &&
(typeof method === 'function' || get !== undefined) &&
enumerable === false
)
) {
throw new Error(
`@wrapper() should be used to decorate a routable component method (property: '${name}')`
);
}
target.setWrapper(name, pattern, options);
return descriptor;
};
}
const HTTP_METHODS = ['GET', 'POST', 'PUT', 'DELETE', 'PATCH'] as const;
const ANY_HTTP_METHOD = '*';
type HTTPMethod = typeof HTTP_METHODS[number];
type AnyHTTPMethod = typeof ANY_HTTP_METHOD;
export function basicHTTPRouteInputTransformer(params: any, _request: any) {
return params;
}
export function basicHTTPRouteOutputTransformer(result: any, request: any) {
let response: {status?: number; headers?: Record<string, string>; body?: string | Buffer} = {};
if (result === undefined) {
response.status = 204; // No Content
} else {
if (request?.method === 'POST') {
response.status = 201; // Created
} else {
response.status = 200; // OK
}
if (Buffer.isBuffer(result)) {
response.headers = {'content-type': 'application/octet-stream'};
response.body = result;
} else {
response.headers = {'content-type': 'application/json'};
response.body = JSON.stringify(result);
}
}
return response;
}
export function basicHTTPRouteErrorTransformer(error: any, _request: any) {
const response: {status: number; headers: Record<string, string>; body: string} = {
status: 500,
headers: {'content-type': 'application/json'},
body: JSON.stringify({
message: 'Internal server error'
})
};
if (typeof error !== 'object' || error === null) {
return response;
}
if (typeof error.status === 'number') {
response.status = error.status;
}
const expose: boolean = typeof error.expose === 'boolean' ? error.expose : response.status < 500;
if (expose) {
const body: Record<string, any> = {};
body.message = typeof error.message === 'string' ? error.message : 'Unknown error';
for (const [key, value] of Object.entries(error)) {
if (key === 'status' || key === 'message' || value === undefined) {
continue;
}
body[key] = value;
}
response.body = JSON.stringify(body);
}
return response;
}
export function httpRoute(
httpMethod: HTTPMethod | AnyHTTPMethod,
pattern: Pattern,
options: RouteOptions = {}
) {
if (!(httpMethod === ANY_HTTP_METHOD || HTTP_METHODS.includes(httpMethod))) {
throw new Error(
`The HTTP method '${httpMethod}' is not supported by the @httpRoute() decorator (supported values are: ${HTTP_METHODS.map(
(method) => `'${method}'`
).join(', ')}, or '${ANY_HTTP_METHOD}')`
);
}
const {
filter = function (request) {
return httpMethod === '*'
? HTTP_METHODS.includes(request?.method)
: request?.method === httpMethod;
},
transformers = {},
...otherOptions
} = options;
const {
input = basicHTTPRouteInputTransformer,
output = basicHTTPRouteOutputTransformer,
error = basicHTTPRouteErrorTransformer
} = transformers;
return function (
target: typeof RoutableComponent | RoutableComponent,
name: string,
descriptor: PropertyDescriptor
) {
return route(pattern, {filter, transformers: {input, output, error}, ...otherOptions})(
target,
name,
descriptor
);
};
} | the_stack |
import { Job } from './job';
import { getLogger } from 'pinus-logger';
import * as path from 'path';
let logger = getLogger('pinus-scheduler', path.basename(__filename));
let SECOND = 0;
let MIN = 1;
let HOUR = 2;
let DOM = 3;
let MONTH = 4;
let DOW = 5;
let Limit = [
[0, 59],
[0, 59],
[0, 24],
[1, 31],
[0, 11],
[0, 6]
];
export class CronTrigger {
trigger: any;
nextTime: number;
job: Job;
/**
* The constructor of the CronTrigger
* @param trigger The trigger str used to build the cronTrigger instance
*/
constructor(trigger: string, job: Job) {
this.trigger = this.decodeTrigger(trigger);
this.nextTime = this.nextExcuteTime(Date.now());
this.job = job;
}
/**
* Get the current excuteTime of trigger
*/
excuteTime() {
return this.nextTime;
}
/**
* Caculate the next valid cronTime after the given time
* @param The given time point
* @return The nearest valid time after the given time point
*/
nextExcuteTime(time: number) {
// add 1s to the time so it must be the next time
time = !!time ? time : this.nextTime;
time += 1000;
let cronTrigger = this.trigger;
let date = new Date(time);
date.setMilliseconds(0);
outmost: while (true) {
if (date.getFullYear() > 2999) {
logger.error('Can\'t compute the next time, exceed the limit');
return null;
}
if (!timeMatch(date.getMonth(), cronTrigger[MONTH])) {
let nextMonth = nextCronTime(date.getMonth(), cronTrigger[MONTH]);
if (nextMonth == null)
return null;
if (nextMonth <= date.getMonth()) {
date.setFullYear(date.getFullYear() + 1);
date.setMonth(0);
date.setDate(1);
date.setHours(0);
date.setMinutes(0);
date.setSeconds(0);
continue;
}
date.setDate(1);
date.setMonth(nextMonth);
date.setHours(0);
date.setMinutes(0);
date.setSeconds(0);
}
if (!timeMatch(date.getDate(), cronTrigger[DOM]) || !timeMatch(date.getDay(), cronTrigger[DOW])) {
let domLimit = getDomLimit(date.getFullYear(), date.getMonth());
do {
let nextDom = nextCronTime(date.getDate(), cronTrigger[DOM]);
if (nextDom == null)
return null;
// If the date is in the next month, add month
if (nextDom <= date.getDate() || nextDom > domLimit) {
date.setDate(1);
date.setMonth(date.getMonth() + 1);
date.setHours(0);
date.setMinutes(0);
date.setSeconds(0);
continue outmost;
}
date.setDate(nextDom);
} while (!timeMatch(date.getDay(), cronTrigger[DOW]));
date.setHours(0);
date.setMinutes(0);
date.setSeconds(0);
}
if (!timeMatch(date.getHours(), cronTrigger[HOUR])) {
let nextHour = nextCronTime(date.getHours(), cronTrigger[HOUR]);
if (nextHour <= date.getHours()) {
date.setDate(date.getDate() + 1);
date.setHours(nextHour);
date.setMinutes(0);
date.setSeconds(0);
continue;
}
date.setHours(nextHour);
date.setMinutes(0);
date.setSeconds(0);
}
if (!timeMatch(date.getMinutes(), cronTrigger[MIN])) {
let nextMinute = nextCronTime(date.getMinutes(), cronTrigger[MIN]);
if (nextMinute <= date.getMinutes()) {
date.setHours(date.getHours() + 1);
date.setMinutes(nextMinute);
date.setSeconds(0);
continue;
}
date.setMinutes(nextMinute);
date.setSeconds(0);
}
if (!timeMatch(date.getSeconds(), cronTrigger[SECOND])) {
let nextSecond = nextCronTime(date.getSeconds(), cronTrigger[SECOND]);
if (nextSecond <= date.getSeconds()) {
date.setMinutes(date.getMinutes() + 1);
date.setSeconds(nextSecond);
continue;
}
date.setSeconds(nextSecond);
}
break;
}
this.nextTime = date.getTime();
return this.nextTime;
}
/**
* Decude the cronTrigger string to arrays
* @param cronTimeStr The cronTimeStr need to decode, like "0 12 * * * 3"
* @return The array to represent the cronTimer
*/
decodeTrigger(cronTimeStr: string) {
cronTimeStr = cronTimeStr.trim();
let cronTimes = <any[]>cronTimeStr.split(/\s+/);
if (cronTimes.length !== 6) {
console.log('error');
return null;
}
for (let i = 0; i < cronTimes.length; i++) {
cronTimes[i] = (this.decodeTimeStr(cronTimes[i], i));
if (!checkNum(cronTimes[i], Limit[i][0], Limit[i][1])) {
logger.error('Decode crontime error, value exceed limit!' +
JSON.stringify({
cronTime: cronTimes[i],
limit: Limit[i]
}));
return null;
}
}
return cronTimes;
}
/**
* Decode the cron Time string
* @param timeStr The cron time string, like: 1,2 or 1-3
* @return A sorted array, like [1,2,3]
*/
decodeTimeStr(timeStr: any, type: number) {
let result: {[key: number]: number} = {};
let arr = [];
if (timeStr === '*') {
return -1;
} else if (timeStr.search(',') > 0) {
let timeArr = timeStr.split(',');
for (let i = 0; i < timeArr.length; i++) {
let time: any = timeArr[i];
if (time.match(/^\d+-\d+$/)) {
decodeRangeTime(result, time);
} else if (time.match(/^\d+\/\d+/)) {
decodePeriodTime(result, time, type);
} else if (!isNaN(time)) {
let num = Number(time);
result[num] = num;
} else
return null;
}
} else if (timeStr.match(/^\d+-\d+$/)) {
decodeRangeTime(result, timeStr);
} else if (timeStr.match(/^\d+\/\d+/)) {
decodePeriodTime(result, timeStr, type);
} else if (!isNaN(timeStr)) {
let num = Number(timeStr);
result[num] = num;
} else {
return null;
}
for (let key in result) {
arr.push(result[key]);
}
arr.sort(function (a, b) {
return a - b;
});
return arr;
}
}
/**
* return the next match time of the given value
* @param value The time value
* @param cronTime The cronTime need to match
* @return The match value or null if unmatch(it offten means an error occur).
*/
function nextCronTime(value: number, cronTime: Array<number>) {
value += 1;
if (typeof (cronTime) === 'number') {
if (cronTime === -1)
return value;
else
return cronTime;
} else if (typeof (cronTime) === 'object' && cronTime instanceof Array) {
if (value <= cronTime[0] || value > cronTime[cronTime.length - 1])
return cronTime[0];
for (let i = 0; i < cronTime.length; i++)
if (value <= cronTime[i])
return cronTime[i];
}
logger.warn('Compute next Time error! value :' + value + ' cronTime : ' + cronTime);
return null;
}
/**
* Match the given value to the cronTime
* @param value The given value
* @param cronTime The cronTime
* @return The match result
*/
function timeMatch(value: number, cronTime: Array<number>) {
if (typeof (cronTime) === 'number') {
if (cronTime === -1)
return true;
if (value === cronTime)
return true;
return false;
} else if (typeof (cronTime) === 'object' && cronTime instanceof Array) {
if (value < cronTime[0] || value > cronTime[cronTime.length - 1])
return false;
for (let i = 0; i < cronTime.length; i++)
if (value === cronTime[i])
return true;
return false;
}
return null;
}
/**
* Decode time range
* @param map The decode map
* @param timeStr The range string, like 2-5
*/
function decodeRangeTime(map: {[key: number]: number}, timeStr: string): void {
let times = <any[]>timeStr.split('-');
times[0] = Number(times[0]);
times[1] = Number(times[1]);
if (times[0] > times[1]) {
console.log('Error time range');
return null;
}
for (let i = times[0]; i <= times[1]; i++) {
map[i] = i;
}
}
/**
* Compute the period timer
*/
function decodePeriodTime(map: {[key: number]: number}, timeStr: string, type: number) {
let times = timeStr.split('/');
let min = Limit[type][0];
let max = Limit[type][1];
let remind = Number(times[0]);
let period = Number(times[1]);
if (period === 0)
return;
for (let i = remind; i <= max; i += period) {
// if (i % period == remind)
map[i] = i;
// }
}
}
/**
* Check if the numbers are valid
* @param nums The numbers array need to check
* @param min Minimus value
* @param max Maximam value
* @return If all the numbers are in the data range
*/
function checkNum(nums: any, min: number, max: number) {
if (nums == null)
return false;
if (nums === -1)
return true;
for (let i = 0; i < nums.length; i++) {
if (nums[i] < min || nums[i] > max)
return false;
}
return true;
}
/**
* Get the date limit of given month
* @param The given year
* @month The given month
* @return The date count of given month
*/
function getDomLimit(year: number, month: number) {
let date = new Date(year, month + 1, 0);
return date.getDate();
}
/**
* Create cronTrigger
* @param trigger The Cron Trigger string
* @return The Cron trigger
*/
export function createTrigger(trigger: string, job: Job) {
return new CronTrigger(trigger, job);
} | the_stack |
import { JenkinsApiImpl } from './jenkinsApi';
import jenkins from 'jenkins';
import { JenkinsInfo } from './jenkinsInfoProvider';
import { JenkinsBuild, JenkinsProject } from '../types';
import { AuthorizeResult } from '@backstage/plugin-permission-common';
import { NotAllowedError } from '@backstage/errors';
jest.mock('jenkins');
const mockedJenkinsClient = {
job: {
get: jest.fn(),
build: jest.fn(),
},
build: {
get: jest.fn(),
},
};
const mockedJenkins = jenkins as jest.Mocked<any>;
mockedJenkins.mockReturnValue(mockedJenkinsClient);
const resourceRef = 'component:default/example-component';
const jobFullName = 'example-jobName/foo';
const buildNumber = 19;
const jenkinsInfo: JenkinsInfo = {
baseUrl: 'https://jenkins.example.com',
headers: { headerName: 'headerValue' },
jobFullName: 'example-jobName',
};
const fakePermissionApi = {
authorize: jest.fn().mockResolvedValue([
{
result: AuthorizeResult.ALLOW,
},
]),
authorizeConditional: jest.fn(),
};
describe('JenkinsApi', () => {
const jenkinsApi = new JenkinsApiImpl(fakePermissionApi);
describe('getProjects', () => {
const project: JenkinsProject = {
actions: [],
displayName: 'Example Build',
fullDisplayName: 'Example jobName » Example Build',
fullName: 'example-jobName/exampleBuild',
inQueue: false,
lastBuild: {
actions: [],
timestamp: 1,
building: false,
duration: 10,
result: 'success',
displayName: '#7',
fullDisplayName: 'Example jobName » Example Build #7',
url: 'https://jenkins.example.com/job/example-jobName/job/exampleBuild',
number: 7,
},
};
describe('unfiltered', () => {
it('standard github layout', async () => {
mockedJenkinsClient.job.get.mockResolvedValueOnce({ jobs: [project] });
const result = await jenkinsApi.getProjects(jenkinsInfo);
expect(mockedJenkins).toHaveBeenCalledWith({
baseUrl: jenkinsInfo.baseUrl,
headers: jenkinsInfo.headers,
promisify: true,
});
expect(mockedJenkinsClient.job.get).toBeCalledWith({
name: jenkinsInfo.jobFullName,
tree: expect.anything(),
});
expect(result).toHaveLength(1);
expect(result[0]).toEqual({
actions: [],
displayName: 'Example Build',
fullDisplayName: 'Example jobName » Example Build',
fullName: 'example-jobName/exampleBuild',
inQueue: false,
lastBuild: {
actions: [],
timestamp: 1,
building: false,
duration: 10,
result: 'success',
displayName: '#7',
fullDisplayName: 'Example jobName » Example Build #7',
url: 'https://jenkins.example.com/job/example-jobName/job/exampleBuild',
number: 7,
status: 'success',
source: {},
},
status: 'success',
});
});
});
describe('filtered by branch', () => {
it('standard github layout', async () => {
mockedJenkinsClient.job.get.mockResolvedValueOnce(project);
const result = await jenkinsApi.getProjects(
jenkinsInfo,
'testBranchName',
);
expect(mockedJenkins).toHaveBeenCalledWith({
baseUrl: jenkinsInfo.baseUrl,
headers: jenkinsInfo.headers,
promisify: true,
});
expect(mockedJenkinsClient.job.get).toBeCalledWith({
name: `${jenkinsInfo.jobFullName}/testBranchName`,
tree: expect.anything(),
});
expect(result).toHaveLength(1);
});
});
describe('augmented', () => {
const projectWithScmActions: JenkinsProject = {
actions: [
{},
{},
{},
{},
{
_class: 'jenkins.scm.api.metadata.ContributorMetadataAction',
contributor: 'testuser',
contributorDisplayName: 'Mr. T User',
contributorEmail: null,
},
{},
{
_class: 'jenkins.scm.api.metadata.ObjectMetadataAction',
objectDescription: '',
objectDisplayName: 'Add LICENSE, CoC etc',
objectUrl: 'https://github.com/backstage/backstage/pull/1',
},
{},
{},
{
_class: 'com.cloudbees.plugins.credentials.ViewCredentialsAction',
stores: {},
},
],
displayName: 'Example Build',
fullDisplayName: 'Example jobName » Example Build',
fullName: 'example-jobName/exampleBuild',
inQueue: false,
lastBuild: {
actions: [
{
_class: 'hudson.model.CauseAction',
causes: [
{
_class: 'jenkins.branch.BranchIndexingCause',
shortDescription: 'Branch indexing',
},
],
},
{},
{},
{},
{
_class: 'org.jenkinsci.plugins.workflow.cps.EnvActionImpl',
environment: {},
},
{},
{},
{},
{},
{},
{
_class: 'hudson.plugins.git.util.BuildData',
buildsByBranchName: {
'PR-1': {
_class: 'hudson.plugins.git.util.Build',
buildNumber: 5,
buildResult: null,
marked: {
SHA1: '14d31bde346fcad64ab939f82d195db36701cfcb',
branch: [
{
SHA1: '14d31bde346fcad64ab939f82d195db36701cfcb',
name: 'PR-1',
},
],
},
revision: {
SHA1: '6c6b34c0fb91cf077a01fe62d3e8e996b4ea5861',
branch: [
{
SHA1: '14d31bde346fcad64ab939f82d195db36701cfcb',
name: 'PR-1',
},
],
},
},
},
lastBuiltRevision: {
SHA1: '6c6b34c0fb91cf077a01fe62d3e8e996b4ea5861',
branch: [
{
SHA1: '14d31bde346fcad64ab939f82d195db36701cfcb',
name: 'PR-1',
},
],
},
remoteUrls: ['https://github.com/backstage/backstage.git'],
scmName: '',
},
{
_class: 'hudson.plugins.git.util.BuildData',
buildsByBranchName: {
master: {
_class: 'hudson.plugins.git.util.Build',
buildNumber: 5,
buildResult: null,
marked: {
SHA1: '14d31bde346fcad64ab939f82d195db36701cfcb',
branch: [
{
SHA1: '14d31bde346fcad64ab939f82d195db36701cfcb',
name: 'master',
},
],
},
revision: {
SHA1: '6c6b34c0fb91cf077a01fe62d3e8e996b4ea5861',
branch: [
{
SHA1: '14d31bde346fcad64ab939f82d195db36701cfcb',
name: 'master',
},
],
},
},
},
lastBuiltRevision: {
SHA1: '6c6b34c0fb91cf077a01fe62d3e8e996b4ea5861',
branch: [
{
SHA1: '14d31bde346fcad64ab939f82d195db36701cfcb',
name: 'master',
},
],
},
remoteUrls: ['https://github.com/backstage/backstage.git'],
scmName: '',
},
{},
{},
{
_class: 'hudson.tasks.junit.TestResultAction',
failCount: 2,
skipCount: 1,
totalCount: 635,
urlName: 'testReport',
},
{},
{},
{
_class:
'org.jenkinsci.plugins.pipeline.modeldefinition.actions.RestartDeclarativePipelineAction',
restartEnabled: false,
restartableStages: [],
},
{},
],
timestamp: 1,
building: false,
duration: 10,
result: 'success',
displayName: '#7',
fullDisplayName: 'Example jobName » Example Build #7',
url: 'https://jenkins.example.com/job/example-jobName/job/exampleBuild/7/',
number: 7,
},
};
const projectWithoutBuild: JenkinsProject = {
actions: [],
displayName: 'Example Build',
fullDisplayName: 'Example jobName » Example Build',
fullName: 'example-jobName/exampleBuild',
inQueue: false,
lastBuild: null,
};
it('augments project', async () => {
mockedJenkinsClient.job.get.mockResolvedValueOnce({
jobs: [projectWithScmActions],
});
const result = await jenkinsApi.getProjects(jenkinsInfo);
expect(result).toHaveLength(1);
expect(result[0].status).toEqual('success');
});
it('augments project without build', async () => {
mockedJenkinsClient.job.get.mockResolvedValueOnce({
jobs: [projectWithoutBuild],
});
const result = await jenkinsApi.getProjects(jenkinsInfo);
expect(result).toHaveLength(1);
expect(result[0].status).toEqual('build not found');
});
it('augments build', async () => {
mockedJenkinsClient.job.get.mockResolvedValueOnce({
jobs: [projectWithScmActions],
});
const result = await jenkinsApi.getProjects(jenkinsInfo);
expect(result).toHaveLength(1);
// TODO: I am really just asserting the previous behaviour with no understanding here.
// In my 2 Jenkins instances, 1 returns a lot of different and confusing BuildData sections and 1 returns none ☹️
expect(result[0].lastBuild!.source).toEqual({
branchName: 'master',
commit: {
hash: '14d31bde',
},
url: 'https://github.com/backstage/backstage/pull/1',
displayName: 'Add LICENSE, CoC etc',
author: 'Mr. T User',
});
});
it('finds test report', async () => {
mockedJenkinsClient.job.get.mockResolvedValueOnce({
jobs: [projectWithScmActions],
});
const result = await jenkinsApi.getProjects(jenkinsInfo);
expect(result).toHaveLength(1);
expect(result[0].lastBuild!.tests).toEqual({
total: 635,
passed: 632,
skipped: 1,
failed: 2,
testUrl:
'https://jenkins.example.com/job/example-jobName/job/exampleBuild/7/testReport/',
});
});
});
describe('augmented with null values', () => {
const projectWithScmActionsAndNulls: JenkinsProject = {
actions: [
{},
{},
{},
{},
{
_class: 'jenkins.scm.api.metadata.ContributorMetadataAction',
contributor: 'testuser',
contributorDisplayName: 'Mr. T User',
contributorEmail: null,
},
{},
{
_class: 'jenkins.scm.api.metadata.ObjectMetadataAction',
objectDescription: '',
objectDisplayName: 'Add LICENSE, CoC etc',
objectUrl: 'https://github.com/backstage/backstage/pull/1',
},
{},
{},
{
_class: 'com.cloudbees.plugins.credentials.ViewCredentialsAction',
stores: {},
},
],
displayName: 'Example Build',
fullDisplayName: 'Example jobName » Example Build',
fullName: 'example-jobName/exampleBuild',
inQueue: false,
lastBuild: {
actions: [
{
_class: 'hudson.model.CauseAction',
causes: [
{
_class: 'jenkins.branch.BranchIndexingCause',
shortDescription: 'Branch indexing',
},
],
},
null,
{},
{},
{
_class: 'org.jenkinsci.plugins.workflow.cps.EnvActionImpl',
environment: {},
},
{},
{},
{},
{},
{},
{
_class: 'hudson.plugins.git.util.BuildData',
buildsByBranchName: {
'PR-1': {
_class: 'hudson.plugins.git.util.Build',
buildNumber: 5,
buildResult: null,
marked: {
SHA1: '14d31bde346fcad64ab939f82d195db36701cfcb',
branch: [
{
SHA1: '14d31bde346fcad64ab939f82d195db36701cfcb',
name: 'PR-1',
},
],
},
revision: {
SHA1: '6c6b34c0fb91cf077a01fe62d3e8e996b4ea5861',
branch: [
{
SHA1: '14d31bde346fcad64ab939f82d195db36701cfcb',
name: 'PR-1',
},
],
},
},
},
lastBuiltRevision: {
SHA1: '6c6b34c0fb91cf077a01fe62d3e8e996b4ea5861',
branch: [
{
SHA1: '14d31bde346fcad64ab939f82d195db36701cfcb',
name: 'PR-1',
},
],
},
remoteUrls: ['https://github.com/backstage/backstage.git'],
scmName: '',
},
{
_class: 'hudson.plugins.git.util.BuildData',
buildsByBranchName: {
master: {
_class: 'hudson.plugins.git.util.Build',
buildNumber: 5,
buildResult: null,
marked: {
SHA1: '14d31bde346fcad64ab939f82d195db36701cfcb',
branch: [
{
SHA1: '14d31bde346fcad64ab939f82d195db36701cfcb',
name: 'master',
},
],
},
revision: {
SHA1: '6c6b34c0fb91cf077a01fe62d3e8e996b4ea5861',
branch: [
{
SHA1: '14d31bde346fcad64ab939f82d195db36701cfcb',
name: 'master',
},
],
},
},
},
lastBuiltRevision: {
SHA1: '6c6b34c0fb91cf077a01fe62d3e8e996b4ea5861',
branch: [
{
SHA1: '14d31bde346fcad64ab939f82d195db36701cfcb',
name: 'master',
},
],
},
remoteUrls: ['https://github.com/backstage/backstage.git'],
scmName: '',
},
{},
{},
{
_class: 'hudson.tasks.junit.TestResultAction',
failCount: 2,
skipCount: 1,
totalCount: 635,
urlName: 'testReport',
},
{},
{},
{
_class:
'org.jenkinsci.plugins.pipeline.modeldefinition.actions.RestartDeclarativePipelineAction',
restartEnabled: false,
restartableStages: [],
},
{},
],
timestamp: 1,
building: false,
duration: 10,
result: 'success',
displayName: '#7',
fullDisplayName: 'Example jobName » Example Build #7',
url: 'https://jenkins.example.com/job/example-jobName/job/exampleBuild/7/',
number: 7,
},
};
it('augments project', async () => {
mockedJenkinsClient.job.get.mockResolvedValueOnce({
jobs: [projectWithScmActionsAndNulls],
});
const result = await jenkinsApi.getProjects(jenkinsInfo);
expect(result).toHaveLength(1);
expect(result[0].status).toEqual('success');
});
it('augments build', async () => {
mockedJenkinsClient.job.get.mockResolvedValueOnce({
jobs: [projectWithScmActionsAndNulls],
});
const result = await jenkinsApi.getProjects(jenkinsInfo);
expect(result).toHaveLength(1);
// TODO: I am really just asserting the previous behaviour with no understanding here.
// In my 2 Jenkins instances, 1 returns a lot of different and confusing BuildData sections and 1 returns none ☹️
expect(result[0].lastBuild!.source).toEqual({
branchName: 'master',
commit: {
hash: '14d31bde',
},
url: 'https://github.com/backstage/backstage/pull/1',
displayName: 'Add LICENSE, CoC etc',
author: 'Mr. T User',
});
});
it('finds test report', async () => {
mockedJenkinsClient.job.get.mockResolvedValueOnce({
jobs: [projectWithScmActionsAndNulls],
});
const result = await jenkinsApi.getProjects(jenkinsInfo);
expect(result).toHaveLength(1);
expect(result[0].lastBuild!.tests).toEqual({
total: 635,
passed: 632,
skipped: 1,
failed: 2,
testUrl:
'https://jenkins.example.com/job/example-jobName/job/exampleBuild/7/testReport/',
});
});
});
});
it('getBuild', async () => {
const project: JenkinsProject = {
actions: [],
displayName: 'Example Build',
fullDisplayName: 'Example jobName » Example Build',
fullName: 'example-jobName/exampleBuild',
inQueue: false,
lastBuild: {
actions: [],
timestamp: 1,
building: false,
duration: 10,
result: 'success',
displayName: '#7',
fullDisplayName: 'Example jobName » Example Build #7',
url: 'https://jenkins.example.com/job/example-jobName/job/exampleBuild',
number: 7,
},
};
const build: JenkinsBuild = {
actions: [],
timestamp: 1,
building: false,
duration: 10,
result: 'success',
fullDisplayName: 'example-jobName/exampleBuild',
displayName: 'exampleBuild',
url: `https://jenkins.example.com/job/example-jobName/job/exampleBuild/build/${buildNumber}`,
number: buildNumber,
};
mockedJenkinsClient.job.get.mockResolvedValueOnce(project);
mockedJenkinsClient.build.get.mockResolvedValueOnce(build);
await jenkinsApi.getBuild(jenkinsInfo, jobFullName, buildNumber);
expect(mockedJenkins).toHaveBeenCalledWith({
baseUrl: jenkinsInfo.baseUrl,
headers: jenkinsInfo.headers,
promisify: true,
});
expect(mockedJenkinsClient.job.get).toBeCalledWith({
name: jobFullName,
depth: 1,
});
expect(mockedJenkinsClient.build.get).toBeCalledWith(
jobFullName,
buildNumber,
);
});
it('buildProject', async () => {
await jenkinsApi.buildProject(jenkinsInfo, jobFullName, resourceRef);
expect(mockedJenkins).toHaveBeenCalledWith({
baseUrl: jenkinsInfo.baseUrl,
headers: jenkinsInfo.headers,
promisify: true,
});
expect(mockedJenkinsClient.job.build).toBeCalledWith(jobFullName);
});
it('buildProject should fail if it does not have required permissions', async () => {
fakePermissionApi.authorize.mockResolvedValueOnce([
{
result: AuthorizeResult.DENY,
},
]);
await expect(() =>
jenkinsApi.buildProject(jenkinsInfo, jobFullName, resourceRef),
).rejects.toThrow(NotAllowedError);
});
it('buildProject should succeed if it have required permissions', async () => {
fakePermissionApi.authorize.mockResolvedValueOnce([
{
result: AuthorizeResult.ALLOW,
},
]);
await jenkinsApi.buildProject(jenkinsInfo, jobFullName, resourceRef);
expect(mockedJenkins).toHaveBeenCalledWith({
baseUrl: jenkinsInfo.baseUrl,
headers: jenkinsInfo.headers,
promisify: true,
});
expect(mockedJenkinsClient.job.build).toBeCalledWith(jobFullName);
});
it('buildProject with crumbIssuer option', async () => {
const info: JenkinsInfo = { ...jenkinsInfo, crumbIssuer: true };
await jenkinsApi.buildProject(info, jobFullName, resourceRef);
expect(mockedJenkins).toHaveBeenCalledWith({
baseUrl: jenkinsInfo.baseUrl,
headers: jenkinsInfo.headers,
promisify: true,
crumbIssuer: true,
});
expect(mockedJenkinsClient.job.build).toBeCalledWith(jobFullName);
});
}); | the_stack |
import * as customPropTypes from '@fluentui/react-proptypes'
import { Accessibility, carouselBehavior } from '@fluentui/accessibility'
import * as React from 'react'
import * as _ from 'lodash'
import * as PropTypes from 'prop-types'
import cx from 'classnames'
import { Ref } from '@fluentui/react-component-ref'
import Animation from '../Animation/Animation'
import {
UIComponentProps,
createShorthandFactory,
ShorthandFactory,
commonPropTypes,
applyAccessibilityKeyHandlers,
childrenExist,
ChildrenComponentProps,
getOrGenerateIdFromShorthand,
AutoControlledComponent,
isFromKeyboard,
} from '../../utils'
import {
WithAsProp,
withSafeTypeForAs,
DebounceResultFn,
ShorthandCollection,
ShorthandValue,
ComponentEventHandler,
} from '../../types'
import Button, { ButtonProps } from '../Button/Button'
import CarouselItem, { CarouselItemProps } from './CarouselItem'
import Text from '../Text/Text'
import CarouselNavigation, { CarouselNavigationProps } from './CarouselNavigation'
import CarouselNavigationItem, { CarouselNavigationItemProps } from './CarouselNavigationItem'
export interface CarouselSlotClassNames {
itemsContainer: string
paddleNext: string
paddlePrevious: string
pagination: string
navigation: string
}
export interface CarouselProps extends UIComponentProps, ChildrenComponentProps {
/**
* Accessibility behavior if overridden by the user.
* @available menuAsToolbarBehavior, tabListBehavior, tabBehavior
*/
accessibility?: Accessibility
/** Index of the currently active item. */
activeIndex?: number | string
/**
* Sets the aria-roledescription attribute.
*/
ariaRoleDescription?: string
/** Specifies if the process of switching slides is circular. */
circular?: boolean
/** Initial activeIndex value. */
defaultActiveIndex?: number | string
/**
* Message generator for item position in the carousel. Used to generate the
* text for pagination. Also generates invisible text content for each item
* which is added along with the slide content. These are used by the screen
* reader to narrate position when active item is changed.
*/
getItemPositionText?: (index: number, size: number) => string
/** Shorthand array of props for CarouselItem. */
items?: ShorthandCollection<CarouselItemProps>
/** Shorthand array of props for the buttons of the CarouselNavigation. */
navigation?:
| ShorthandValue<CarouselNavigationProps>
| ShorthandCollection<CarouselNavigationItemProps>
/**
* A Carousel can position its navigation below the content by default,
* above the content, to the start or to the end of the content.
*/
navigationPosition?: 'below' | 'above' | 'start' | 'end'
/**
* Called when a panel title is clicked.
*
* @param {SyntheticEvent} event - React's original SyntheticEvent.
* @param {object} data - All Carousel props.
*/
onActiveIndexChange?: ComponentEventHandler<CarouselProps>
/** Shorthand for the paddle that navigates to the next item. */
paddleNext?: ShorthandValue<ButtonProps>
/**
* A Carousel can position its paddels inside the content, outside or inline
* with the navigation component.
*/
paddlesPosition?: 'inside' | 'outside' | 'inline'
/** Shorthand for the paddle that navigates to the previous item. */
paddlePrevious?: ShorthandValue<ButtonProps>
}
export interface CarouselState {
activeIndex: number
prevActiveIndex: number
ariaLiveOn: boolean
itemIds: string[]
shouldFocusContainer: boolean
isFromKeyboard: boolean
}
class Carousel extends AutoControlledComponent<WithAsProp<CarouselProps>, CarouselState> {
static create: ShorthandFactory<CarouselProps>
static displayName = 'Carousel'
static className = 'ui-carousel'
static slotClassNames: CarouselSlotClassNames = {
itemsContainer: `${Carousel.className}__itemscontainer`,
paddleNext: `${Carousel.className}__paddlenext`,
paddlePrevious: `${Carousel.className}__paddleprevious`,
pagination: `${Carousel.className}__pagination`,
navigation: `${Carousel.className}__navigation`,
}
static propTypes = {
...commonPropTypes.createCommon({
content: false,
}),
activeIndex: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
ariaRoleDescription: PropTypes.string,
circular: PropTypes.bool,
defaultActiveIndex: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
getItemPositionText: PropTypes.func,
items: customPropTypes.collectionShorthand,
navigation: PropTypes.oneOfType([
customPropTypes.collectionShorthand,
customPropTypes.itemShorthand,
]),
navigationPosition: PropTypes.string,
onActiveIndexChange: PropTypes.func,
paddleNext: customPropTypes.itemShorthand,
paddlesPosition: PropTypes.string,
paddlePrevious: customPropTypes.itemShorthand,
}
static autoControlledProps = ['activeIndex']
static defaultProps = {
accessibility: carouselBehavior as Accessibility,
paddlePrevious: {},
paddleNext: {},
}
static Item = CarouselItem
static Navigation = CarouselNavigation
static NavigationItem = CarouselNavigationItem
static getAutoControlledStateFromProps(props: CarouselProps, state: CarouselState) {
const { items } = props
const { itemIds } = state
if (!items) {
return null
}
return {
itemIds: items.map((item, index) =>
getOrGenerateIdFromShorthand('carousel-item-', item, itemIds[index]),
),
}
}
componentWillUnmount() {
this.focusItemAtIndex.cancel()
}
actionHandlers = {
showNextSlideByKeyboardNavigation: e => {
e.preventDefault()
this.showNextSlide(e, true)
},
showPreviousSlideByKeyboardNavigation: e => {
e.preventDefault()
this.showPreviousSlide(e, true)
},
showNextSlideByPaddlePress: e => {
e.preventDefault()
const { activeIndex } = this.state
const { circular, items, navigation } = this.props
this.showNextSlide(e, false)
// if 'next' paddle will disappear, will focus 'previous' one.
if (!navigation && activeIndex >= items.length - 2 && !circular) {
this.paddlePreviousRef.current.focus()
}
},
showPreviousSlideByPaddlePress: e => {
e.preventDefault()
const { activeIndex } = this.state
const { circular, navigation } = this.props
this.showPreviousSlide(e, false)
// if 'previous' paddle will disappear, will focus 'next' one.
if (!navigation && activeIndex <= 1 && !circular) {
this.paddleNextRef.current.focus()
}
},
}
getInitialAutoControlledState(): CarouselState {
return {
activeIndex: 0,
prevActiveIndex: -1,
ariaLiveOn: false,
itemIds: [] as string[],
shouldFocusContainer: false,
isFromKeyboard: false,
}
}
itemRefs = [] as React.RefObject<HTMLElement>[]
paddleNextRef = React.createRef<HTMLElement>()
paddlePreviousRef = React.createRef<HTMLElement>()
focusItemAtIndex: DebounceResultFn<(index: number) => void> = _.debounce((index: number) => {
this.itemRefs[index].current.focus()
}, 400)
setActiveIndex(e: React.SyntheticEvent, index: number, focusItem: boolean): void {
const { circular, items } = this.props
const lastItemIndex = items.length - 1
let activeIndex = index
if (index < 0) {
if (!circular) {
return
}
activeIndex = lastItemIndex
}
if (index > lastItemIndex) {
if (!circular) {
return
}
activeIndex = 0
}
this.setState({
prevActiveIndex: this.state.activeIndex,
activeIndex,
})
_.invoke(this.props, 'onActiveIndexChange', e, this.props)
if (focusItem) {
this.focusItemAtIndex(activeIndex)
}
}
overrideItemProps = predefinedProps => ({
onFocus: (e, itemProps) => {
this.setState({
shouldFocusContainer: e.currentTarget === e.target,
isFromKeyboard: isFromKeyboard(),
})
_.invoke(predefinedProps, 'onFocus', e, itemProps)
},
onBlur: (e, itemProps) => {
this.setState({
shouldFocusContainer: e.currentTarget.contains(e.relatedTarget),
isFromKeyboard: false,
})
_.invoke(predefinedProps, 'onBlur', e, itemProps)
},
})
renderContent = (accessibility, classes, unhandledProps) => {
const { ariaRoleDescription, getItemPositionText, items, circular } = this.props
const { activeIndex, itemIds, prevActiveIndex } = this.state
this.itemRefs = []
return (
<div
className={classes.itemsContainerWrapper}
{...accessibility.attributes.itemsContainerWrapper}
>
<div
className={cx(Carousel.slotClassNames.itemsContainer, classes.itemsContainer)}
aria-roledescription={ariaRoleDescription}
{...accessibility.attributes.itemsContainer}
{...applyAccessibilityKeyHandlers(
accessibility.keyHandlers.itemsContainer,
unhandledProps,
)}
>
{items &&
items.map((item, index) => {
const itemRef = React.createRef<HTMLElement>()
this.itemRefs.push(itemRef)
const active = activeIndex === index
let slideToNext = prevActiveIndex < activeIndex
const initialMounting = prevActiveIndex === -1
if (circular && prevActiveIndex === items.length - 1 && activeIndex === 0) {
slideToNext = true
} else if (circular && prevActiveIndex === 0 && activeIndex === items.length - 1) {
slideToNext = false
}
return (
<Animation
key={item['key'] || index}
mountOnEnter
unmountOnExit
visible={active}
name={
initialMounting
? ''
: active
? slideToNext
? 'carousel-slide-to-next-enter'
: 'carousel-slide-to-previous-enter'
: slideToNext
? 'carousel-slide-to-next-exit'
: 'carousel-slide-to-previous-exit'
}
>
<Ref innerRef={itemRef}>
{CarouselItem.create(item, {
defaultProps: () => ({
active,
id: itemIds[index],
navigation: !!this.props.navigation,
...(getItemPositionText && {
itemPositionText: getItemPositionText(index, items.length),
}),
}),
overrideProps: this.overrideItemProps,
})}
</Ref>
</Animation>
)
})}
</div>
</div>
)
}
showPreviousSlide = (e: React.SyntheticEvent, focusItem: boolean) => {
this.setActiveIndex(e, this.state.activeIndex - 1, focusItem)
}
showNextSlide = (e: React.SyntheticEvent, focusItem: boolean) => {
this.setActiveIndex(e, this.state.activeIndex + 1, focusItem)
}
handlePaddleOverrides = (predefinedProps: ButtonProps, paddleName: string) => ({
onClick: (e: React.SyntheticEvent, buttonProps: ButtonProps) => {
_.invoke(predefinedProps, 'onClick', e, buttonProps)
if (paddleName === 'paddleNext') {
this.showNextSlide(e, false)
} else if (paddleName === 'paddlePrevious') {
this.showPreviousSlide(e, false)
}
},
onBlur: (e: React.FocusEvent, buttonProps: ButtonProps) => {
if (e.relatedTarget !== this.paddleNextRef.current) {
this.setState({ ariaLiveOn: false })
}
},
onFocus: (e: React.SyntheticEvent, buttonProps: ButtonProps) => {
_.invoke(predefinedProps, 'onFocus', e, buttonProps)
this.setState({
ariaLiveOn: true,
})
},
})
renderPaddles = (accessibility, styles) => {
const { paddlePrevious, paddleNext } = this.props
return (
<>
<Ref innerRef={this.paddlePreviousRef}>
{Button.create(paddlePrevious, {
defaultProps: () => ({
className: Carousel.slotClassNames.paddlePrevious,
iconOnly: true,
icon: 'icon-chevron-start',
styles: styles.paddlePrevious,
...accessibility.attributes.paddlePrevious,
...applyAccessibilityKeyHandlers(
accessibility.keyHandlers.paddlePrevious,
paddlePrevious,
),
}),
overrideProps: (predefinedProps: ButtonProps) =>
this.handlePaddleOverrides(predefinedProps, 'paddlePrevious'),
})}
</Ref>
<Ref innerRef={this.paddleNextRef}>
{Button.create(paddleNext, {
defaultProps: () => ({
className: Carousel.slotClassNames.paddleNext,
iconOnly: true,
icon: 'icon-chevron-end',
styles: styles.paddleNext,
...accessibility.attributes.paddleNext,
...applyAccessibilityKeyHandlers(accessibility.keyHandlers.paddleNext, paddleNext),
}),
overrideProps: (predefinedProps: ButtonProps) =>
this.handlePaddleOverrides(predefinedProps, 'paddleNext'),
})}
</Ref>
</>
)
}
renderNavigation = () => {
const { getItemPositionText, navigation, items } = this.props
if (!items || !items.length) {
return null
}
const { activeIndex } = this.state
return navigation ? (
CarouselNavigation.create(navigation, {
defaultProps: () => ({
className: Carousel.slotClassNames.navigation,
iconOnly: true,
activeIndex,
}),
overrideProps: (predefinedProps: CarouselNavigationItemProps) => ({
onItemClick: (e: React.SyntheticEvent, itemProps: CarouselNavigationItemProps) => {
const { index } = itemProps
this.setActiveIndex(e, index, true)
_.invoke(predefinedProps, 'onClick', e, itemProps)
},
}),
})
) : (
<Text
className={Carousel.slotClassNames.pagination}
content={getItemPositionText(activeIndex, items.length)}
/>
)
}
renderComponent({ ElementType, classes, styles, accessibility, unhandledProps }) {
const { children } = this.props
return (
<ElementType
className={classes.root}
{...accessibility.attributes.root}
{...unhandledProps}
{...applyAccessibilityKeyHandlers(accessibility.keyHandlers.root, unhandledProps)}
>
{childrenExist(children) ? (
children
) : (
<>
{this.renderContent(accessibility, classes, unhandledProps)}
{this.renderPaddles(accessibility, styles)}
{this.renderNavigation()}
</>
)}
</ElementType>
)
}
}
Carousel.create = createShorthandFactory({
Component: Carousel,
mappedArrayProp: 'items',
})
/**
* A Carousel displays data organised as a gallery.
*
* @accessibility
* Implements [ARIA Carousel](https://www.w3.org/WAI/tutorials/carousels/structure/) design pattern.
* @accessibilityIssues
* [VoiceOver doens't narrate label referenced by aria-labelledby attribute, when role is "tabpanel"](https://bugs.chromium.org/p/chromium/issues/detail?id=1040924)
*/
export default withSafeTypeForAs<typeof Carousel, CarouselProps, 'div'>(Carousel) | the_stack |
if (typeof [].includes !== 'function') {
console.log('Minimum required Node.js version is 6, please update.')
process.exit(-1)
}
import { PropertyValues } from '@signalk/server-api'
import { FullSignalK, getSourceId } from '@signalk/signalk-schema'
import { Debugger } from 'debug'
import express, { Request, Response } from 'express'
import http from 'http'
import https from 'https'
import _ from 'lodash'
import path from 'path'
import { SelfIdentity, ServerApp, SignalKMessageHub, WithConfig } from './app'
import { ConfigApp, load, sendBaseDeltas } from './config/config'
import { createDebug } from './debug'
import DeltaCache from './deltacache'
import DeltaChain, { DeltaInputHandler } from './deltachain'
import { getToPreferredDelta, ToPreferredDelta } from './deltaPriority'
import { incDeltaStatistics, startDeltaStatistics } from './deltastats'
import { checkForNewServerVersion } from './modules'
import { getExternalPort, getPrimaryPort, getSecondaryPort } from './ports'
import {
getCertificateOptions,
getSecurityConfig,
saveSecurityConfig,
startSecurity
} from './security.js'
import SubscriptionManager from './subscriptionmanager'
import { Delta } from './types'
const debug = createDebug('signalk-server')
// tslint:disable-next-line: no-var-requires
const { StreamBundle } = require('./streambundle')
interface ServerOptions {
securityConfig: any
}
class Server {
app: ServerApp & SelfIdentity & WithConfig & SignalKMessageHub
constructor(opts: ServerOptions) {
const FILEUPLOADSIZELIMIT = process.env.FILEUPLOADSIZELIMIT || '10mb'
const bodyParser = require('body-parser')
const app = express() as any
app.use(require('compression')())
app.use(bodyParser.json({ limit: FILEUPLOADSIZELIMIT }))
this.app = app
app.started = false
_.merge(app, opts)
load(app)
app.logging = require('./logging')(app)
app.version = '0.0.1'
startSecurity(app, opts ? opts.securityConfig : null)
setupCors(app, getSecurityConfig(app))
require('./serverroutes')(app, saveSecurityConfig, getSecurityConfig)
require('./put').start(app)
app.signalk = new FullSignalK(app.selfId, app.selfType)
app.propertyValues = new PropertyValues()
const deltachain = new DeltaChain(app.signalk.addDelta.bind(app.signalk))
app.registerDeltaInputHandler = (handler: DeltaInputHandler) =>
deltachain.register(handler)
app.providerStatus = {}
app.setPluginStatus = (providerId: string, statusMessage: string) => {
doSetProviderStatus(providerId, statusMessage, 'status', 'plugin')
}
app.setPluginError = (providerId: string, errorMessage: string) => {
doSetProviderStatus(providerId, errorMessage, 'error', 'plugin')
}
app.setProviderStatus = (providerId: string, statusMessage: string) => {
doSetProviderStatus(providerId, statusMessage, 'status')
}
app.setProviderError = (providerId: string, errorMessage: string) => {
doSetProviderStatus(providerId, errorMessage, 'error')
}
function doSetProviderStatus(
providerId: string,
statusMessage: string,
type: string,
statusType = 'provider'
) {
if (!statusMessage) {
delete app.providerStatus[providerId]
return
}
if (_.isUndefined(app.providerStatus[providerId])) {
app.providerStatus[providerId] = {}
}
const status = app.providerStatus[providerId]
if (status.type === 'error' && status.message !== statusMessage) {
status.lastError = status.message
status.lastErrorTimeStamp = status.timeStamp
}
status.type = type
status.id = providerId
status.statusType = statusType
status.timeStamp = new Date().toLocaleString()
status.message = statusMessage
app.emit('serverevent', {
type: 'PROVIDERSTATUS',
from: 'signalk-server',
data: app.getProviderStatus()
})
}
app.getProviderStatus = () => {
const providerStatus = _.values(app.providerStatus)
if (app.plugins) {
app.plugins.forEach((plugin: any) => {
try {
if (
typeof plugin.statusMessage === 'function' &&
_.isUndefined(app.providerStatus[plugin.id])
) {
let message = plugin.statusMessage()
if (message) {
message = message.trim()
if (message.length > 0) {
providerStatus.push({
message,
type: 'status',
id: plugin.id,
statusType: 'plugin'
})
}
}
}
} catch (e) {
console.error(e)
providerStatus.push({
message:
'Error fetching provider status, see server log for details',
type: 'status',
id: plugin.id
})
}
})
}
return providerStatus
}
app.registerHistoryProvider = (provider: any) => {
app.historyProvider = provider
}
app.unregisterHistoryProvider = () => {
delete app.historyProvider
}
let toPreferredDelta: ToPreferredDelta = () => undefined
app.activateSourcePriorities = () => {
try {
toPreferredDelta = getToPreferredDelta(
app.config.settings.sourcePriorities
)
} catch (e) {
console.error(`getToPreferredDelta failed: ${(e as any).message}`)
}
}
app.activateSourcePriorities()
app.handleMessage = (providerId: string, data: any) => {
if (data && data.updates) {
incDeltaStatistics(app, providerId)
if (
typeof data.context === 'undefined' ||
data.context === 'vessels.self'
) {
data.context = 'vessels.' + app.selfId
}
const now = new Date()
data.updates.forEach((update: Delta) => {
if (typeof update.source !== 'undefined') {
update.source.label = providerId
if (!update.$source) {
update.$source = getSourceId(update.source)
}
} else {
if (typeof update.$source === 'undefined') {
update.$source = providerId
}
}
if (!update.timestamp || app.config.overrideTimestampWithNow) {
update.timestamp = now.toISOString()
}
})
try {
deltachain.process(toPreferredDelta(data, now, app.selfContext))
} catch (err) {
console.error(err)
}
}
}
app.streambundle = new StreamBundle(app, app.selfId)
app.signalk.on('delta', app.streambundle.pushDelta.bind(app.streambundle))
app.subscriptionmanager = new SubscriptionManager(app)
app.deltaCache = new DeltaCache(app, app.streambundle)
app.getHello = () => ({
name: app.config.name,
version: app.config.version,
self: `vessels.${app.selfId}`,
roles: ['master', 'main'],
timestamp: new Date()
})
app.isNmea2000OutAvailable = false
app.on('nmea2000OutAvailable', () => {
app.isNmea2000OutAvailable = true
})
}
start() {
const self = this
const app = this.app
const eventDebugs: { [key: string]: Debugger } = {}
const expressAppEmit = app.emit.bind(app)
app.emit = (eventName: string, ...args: any[]) => {
if (eventName !== 'serverlog') {
let eventDebug = eventDebugs[eventName]
if (!eventDebug) {
eventDebugs[eventName] = eventDebug = createDebug(
`signalk-server:events:${eventName}`
)
}
if (eventDebug.enabled) {
eventDebug(args)
}
}
expressAppEmit(eventName, ...args)
}
this.app.intervals = []
this.app.intervals.push(
setInterval(
app.signalk.pruneContexts.bind(
app.signalk,
(app.config.settings.pruneContextsMinutes || 60) * 60
),
60 * 1000
)
)
this.app.intervals.push(
setInterval(
app.deltaCache.pruneContexts.bind(
app.deltaCache,
(app.config.settings.pruneContextsMinutes || 60) * 60
),
60 * 1000
)
)
app.intervals.push(
setInterval(() => {
app.emit('serverevent', {
type: 'PROVIDERSTATUS',
from: 'signalk-server',
data: app.getProviderStatus()
})
}, 5 * 1000)
)
function serverUpgradeIsAvailable(err: any, newVersion?: string) {
if (err) {
console.error(err)
return
}
const msg = `A new version (${newVersion}) of the server is available`
console.log(msg)
app.handleMessage(app.config.name, {
updates: [
{
values: [
{
path: 'notifications.server.newVersion',
value: {
state: 'alert',
method: [],
message: msg
}
}
]
}
]
})
}
if (!process.env.SIGNALK_DISABLE_SERVER_UPDATES) {
checkForNewServerVersion(app.config.version, serverUpgradeIsAvailable)
app.intervals.push(
setInterval(
() =>
checkForNewServerVersion(
app.config.version,
serverUpgradeIsAvailable
),
60 * 1000 * 60 * 24
)
)
}
this.app.providers = []
app.lastServerEvents = {}
app.on('serverevent', (event: any) => {
if (event.type) {
app.lastServerEvents[event.type] = event
}
})
app.intervals.push(startDeltaStatistics(app))
return new Promise((resolve, reject) => {
createServer(app, (err, server) => {
if (err) {
reject(err)
return
}
app.server = server
app.interfaces = {}
app.clients = 0
debug('ID type: ' + app.selfType)
debug('ID: ' + app.selfId)
sendBaseDeltas((app as unknown) as ConfigApp)
startInterfaces(app)
startMdns(app)
app.providers = require('./pipedproviders')(app).start()
const primaryPort = getPrimaryPort(app)
debug(`primary port:${primaryPort}`)
server.listen(primaryPort, () => {
console.log(
'signalk-server running at 0.0.0.0:' + primaryPort.toString() + '\n'
)
app.started = true
resolve(self)
})
const secondaryPort = getSecondaryPort(app)
debug(`secondary port:${primaryPort}`)
if (app.config.settings.ssl && secondaryPort) {
startRedirectToSsl(
secondaryPort,
getExternalPort(app),
(anErr: any, aServer: any) => {
if (!anErr) {
app.redirectServer = aServer
}
}
)
}
})
})
}
reload(mixed: any) {
let settings
const self = this
if (typeof mixed === 'string') {
try {
settings = require(path.join(process.cwd(), mixed))
} catch (e) {
debug(`Settings file '${settings}' does not exist`)
}
}
if (mixed !== null && typeof mixed === 'object') {
settings = mixed
}
if (settings) {
this.app.config.settings = settings
}
this.stop().catch(e => console.error(e))
setTimeout(() => {
self.start().catch(e => console.error(e))
}, 1000)
return this
}
stop(cb?: () => void) {
return new Promise((resolve, reject) => {
if (!this.app.started) {
resolve(this)
} else {
try {
_.each(this.app.interfaces, (intf: any) => {
if (
intf !== null &&
typeof intf === 'object' &&
typeof intf.stop === 'function'
) {
intf.stop()
}
})
this.app.intervals.forEach(interval => {
clearInterval(interval)
})
this.app.providers.forEach(providerHolder => {
providerHolder.pipeElements[0].end()
})
debug('Closing server...')
const that = this
this.app.server.close(() => {
debug('Server closed')
if (that.app.redirectServer) {
try {
that.app.redirectServer.close(() => {
debug('Redirect server closed')
delete that.app.redirectServer
that.app.started = false
cb && cb()
resolve(that)
})
} catch (err) {
reject(err)
}
} else {
that.app.started = false
cb && cb()
resolve(that)
}
})
} catch (err) {
reject(err)
}
}
})
}
}
module.exports = Server
function createServer(app: any, cb: (err: any, server?: any) => void) {
if (app.config.settings.ssl) {
getCertificateOptions(app, (err: any, options: any) => {
if (err) {
cb(err)
} else {
debug('Starting server to serve both http and https')
cb(null, https.createServer(options, app))
}
})
return
}
let server
try {
debug('Starting server to serve only http')
server = http.createServer(app)
} catch (e) {
cb(e)
return
}
cb(null, server)
}
function startRedirectToSsl(
port: number,
redirectPort: number,
cb: (e: unknown, server: any) => void
) {
const redirectApp = express()
redirectApp.use((req: Request, res: Response) => {
const hostHeader = req.headers.host || ''
const host = req.headers.host?.split(':')[0]
res.redirect(`https://${host}:${redirectPort}${req.path}`)
})
const server = http.createServer(redirectApp)
server.listen(port, () => {
console.log(`Redirect server running on port ${port.toString()}`)
cb(null, server)
})
}
function startMdns(app: ServerApp & WithConfig) {
if (_.isUndefined(app.config.settings.mdns) || app.config.settings.mdns) {
debug(`Starting interface 'mDNS'`)
try {
app.interfaces.mdns = require('./mdns')(app)
} catch (ex) {
console.error('Could not start mDNS:' + ex)
}
} else {
debug(`Interface 'mDNS' was disabled in configuration`)
}
}
function startInterfaces(app: ServerApp & WithConfig) {
debug('Interfaces config:' + JSON.stringify(app.config.settings.interfaces))
const availableInterfaces = require('./interfaces')
_.forIn(availableInterfaces, (theInterface: any, name: string) => {
if (
_.isUndefined(app.config.settings.interfaces) ||
_.isUndefined((app.config.settings.interfaces || {})[name]) ||
(app.config.settings.interfaces || {})[name]
) {
debug(`Loading interface '${name}'`)
app.interfaces[name] = theInterface(app)
if (app.interfaces[name] && _.isFunction(app.interfaces[name].start)) {
if (
_.isUndefined(app.interfaces[name].forceInactive) ||
!app.interfaces[name].forceInactive
) {
debug(`Starting interface '${name}'`)
app.interfaces[name].data = app.interfaces[name].start()
} else {
debug(`Not starting interface '${name}' by forceInactive`)
}
}
} else {
debug(`Not loading interface '${name}' because of configuration`)
}
})
}
function setupCors(app: any, { allowedCorsOrigins }: any) {
const corsDebug = createDebug('signalk-server:cors')
const corsOrigins = allowedCorsOrigins ? allowedCorsOrigins.split(',') : []
corsDebug(`corsOrigins:${corsOrigins.toString()}`)
const corsOptions: any = {
credentials: true
}
if (corsOrigins.length) {
corsOptions.origin = (origin: any, cb: any) => {
if (corsOrigins.indexOf(origin)) {
corsDebug(`Found CORS origin ${origin}`)
cb(undefined, origin)
} else {
const errorMsg = `CORS origin not allowed ${origin}`
corsDebug(errorMsg)
cb(new Error(errorMsg))
}
}
}
app.use(require('cors')(corsOptions))
} | the_stack |
import path from 'path';
import { FHIRDefinitions, loadFromPath } from '../../src/fhirdefs';
import { ElementDefinition, ElementDefinitionType, StructureDefinition } from '../../src/fhirtypes';
import { loggerSpy, TestFisher } from '../testhelpers';
import { AddElementRule } from '../../src/fshtypes/rules';
describe('ElementDefinition', () => {
let defs: FHIRDefinitions;
let alternateIdentification: StructureDefinition;
let fisher: TestFisher;
beforeAll(() => {
defs = new FHIRDefinitions();
loadFromPath(path.join(__dirname, '..', 'testhelpers', 'testdefs'), 'r4-definitions', defs);
fisher = new TestFisher().withFHIR(defs);
});
beforeEach(() => {
alternateIdentification = fisher.fishForStructureDefinition('AlternateIdentification');
loggerSpy.reset();
});
describe('#applyAddElementRule()', () => {
// NOTE: ElementDefinition.applyAddElementRule(...) uses the following ElementDefinition
// methods:
// - constrainType(...)
// - constrainCardinality(...)
// - applyFlags(...)
// Those methods have their own exhaustive tests in other test suites; therefore,
// only minimal tests are provided for those aspects within the AddElementRule.
it('should throw an error for an invalid AddElementRule path', () => {
const addElementRule = new AddElementRule('foo.bar');
addElementRule.min = 0;
addElementRule.max = '1';
addElementRule.types = [{ type: 'boolean' }];
addElementRule.short = 'A bar';
const newElement: ElementDefinition = alternateIdentification.newElement(addElementRule.path);
expect(() => {
newElement.applyAddElementRule(addElementRule, fisher);
}).toThrow('The element or path you referenced does not exist: foo.bar');
});
it('should apply AddElementRule with minimum required attributes', () => {
const addElementRule = new AddElementRule('comments');
addElementRule.min = 0;
addElementRule.max = '1';
addElementRule.types = [{ type: 'string' }];
addElementRule.short = 'provide some comments';
const newElement: ElementDefinition = alternateIdentification.newElement(addElementRule.path);
newElement.applyAddElementRule(addElementRule, fisher);
expect(loggerSpy.getAllLogs('warn')).toHaveLength(0);
expect(newElement.path).toBe('AlternateIdentification.comments');
expect(newElement.min).toBe(0);
expect(newElement.max).toBe('1');
const expectedType = new ElementDefinitionType('string');
expect(newElement.type).toStrictEqual([expectedType]);
expect(newElement.isModifier).toBeUndefined();
expect(newElement.mustSupport).toBeUndefined();
expect(newElement.isSummary).toBeUndefined();
expect(newElement.extension).toBeUndefined(); // standards flags extensions
expect(newElement.short).toBe('provide some comments');
expect(newElement.definition).toBe('provide some comments');
expect(newElement.base).toBeDefined();
expect(newElement.base.path).toBe(newElement.path);
expect(newElement.base.min).toBe(newElement.min);
expect(newElement.base.max).toBe(newElement.max);
expect(newElement.constraint).toBeDefined();
expect(newElement.constraint).toHaveLength(1);
expect(newElement.constraint[0].key).toBe('ele-1');
expect(newElement.constraint[0].requirements).toBeUndefined();
expect(newElement.constraint[0].severity).toBe('error');
expect(newElement.constraint[0].human).toBe(
'All FHIR elements must have a @value or children'
);
expect(newElement.constraint[0].expression).toBe(
'hasValue() or (children().count() > id.count())'
);
expect(newElement.constraint[0].xpath).toBe('@value|f:*|h:div');
expect(newElement.constraint[0].source).toBe(
'http://hl7.org/fhir/StructureDefinition/Element'
);
});
it('should apply AddElementRule with multiple targetTypes', () => {
const addElementRule = new AddElementRule('created[x]');
addElementRule.min = 0;
addElementRule.max = '1';
addElementRule.types = [{ type: 'instant' }, { type: 'dateTime' }, { type: 'Period' }];
addElementRule.short = 'short definition';
const newElement: ElementDefinition = alternateIdentification.newElement(addElementRule.path);
newElement.applyAddElementRule(addElementRule, fisher);
expect(loggerSpy.getAllLogs('warn')).toHaveLength(0);
expect(newElement.path).toBe('AlternateIdentification.created[x]');
const expectedType1 = new ElementDefinitionType('instant');
const expectedType2 = new ElementDefinitionType('dateTime');
const expectedType3 = new ElementDefinitionType('Period');
expect(newElement.type).toStrictEqual([expectedType1, expectedType2, expectedType3]);
});
it('should apply AddElementRule with multiple targetTypes including a reference', () => {
const addElementRule = new AddElementRule('entity[x]');
addElementRule.min = 0;
addElementRule.max = '1';
addElementRule.types = [
{ type: 'string' },
{ type: 'uri' },
{ type: 'Organization', isReference: true }
];
addElementRule.short = 'short definition';
const newElement: ElementDefinition = alternateIdentification.newElement(addElementRule.path);
newElement.applyAddElementRule(addElementRule, fisher);
expect(loggerSpy.getAllLogs('warn')).toHaveLength(0);
expect(newElement.path).toBe('AlternateIdentification.entity[x]');
const expectedType1 = new ElementDefinitionType('string');
const expectedType2 = new ElementDefinitionType('uri');
const expectedType3 = new ElementDefinitionType('Reference').withTargetProfiles(
'http://hl7.org/fhir/StructureDefinition/Organization'
);
expect(newElement.type).toStrictEqual([expectedType1, expectedType2, expectedType3]);
});
it('should apply AddElementRule with single Reference targetType', () => {
const addElementRule = new AddElementRule('org');
addElementRule.min = 0;
addElementRule.max = '1';
addElementRule.types = [{ type: 'Organization', isReference: true }];
addElementRule.short = 'short definition';
const newElement: ElementDefinition = alternateIdentification.newElement(addElementRule.path);
newElement.applyAddElementRule(addElementRule, fisher);
expect(loggerSpy.getAllLogs('warn')).toHaveLength(0);
expect(newElement.path).toBe('AlternateIdentification.org');
const expectedType = new ElementDefinitionType('Reference').withTargetProfiles(
'http://hl7.org/fhir/StructureDefinition/Organization'
);
expect(newElement.type).toStrictEqual([expectedType]);
});
it('should apply AddElementRule with multiple Reference targetType', () => {
const addElementRule = new AddElementRule('org[x]');
addElementRule.min = 0;
addElementRule.max = '1';
addElementRule.types = [
{ type: 'Organization', isReference: true },
{ type: 'Practitioner', isReference: true }
];
addElementRule.short = 'short definition';
const newElement: ElementDefinition = alternateIdentification.newElement(addElementRule.path);
newElement.applyAddElementRule(addElementRule, fisher);
expect(loggerSpy.getAllLogs('warn')).toHaveLength(0);
expect(newElement.path).toBe('AlternateIdentification.org[x]');
const expectedType = new ElementDefinitionType('Reference').withTargetProfiles(
'http://hl7.org/fhir/StructureDefinition/Organization',
'http://hl7.org/fhir/StructureDefinition/Practitioner'
);
expect(newElement.type).toStrictEqual([expectedType]);
});
it('should apply AddElementRule with multiple targetTypes including a canonical', () => {
const addElementRule = new AddElementRule('entity[x]');
addElementRule.min = 0;
addElementRule.max = '1';
addElementRule.types = [
{ type: 'string' },
{ type: 'uri' },
{ type: 'Organization', isCanonical: true }
];
addElementRule.short = 'short definition';
const newElement: ElementDefinition = alternateIdentification.newElement(addElementRule.path);
newElement.applyAddElementRule(addElementRule, fisher);
expect(loggerSpy.getAllLogs('warn')).toHaveLength(0);
expect(newElement.path).toBe('AlternateIdentification.entity[x]');
const expectedType1 = new ElementDefinitionType('string');
const expectedType2 = new ElementDefinitionType('uri');
const expectedType3 = new ElementDefinitionType('canonical').withTargetProfiles(
'http://hl7.org/fhir/StructureDefinition/Organization'
);
expect(newElement.type).toStrictEqual([expectedType1, expectedType2, expectedType3]);
});
it('should apply AddElementRule with single canonical targetType', () => {
const addElementRule = new AddElementRule('org');
addElementRule.min = 0;
addElementRule.max = '1';
addElementRule.types = [{ type: 'Organization', isCanonical: true }];
addElementRule.short = 'short definition';
const newElement: ElementDefinition = alternateIdentification.newElement(addElementRule.path);
newElement.applyAddElementRule(addElementRule, fisher);
expect(loggerSpy.getAllLogs('warn')).toHaveLength(0);
expect(newElement.path).toBe('AlternateIdentification.org');
const expectedType = new ElementDefinitionType('canonical').withTargetProfiles(
'http://hl7.org/fhir/StructureDefinition/Organization'
);
expect(newElement.type).toStrictEqual([expectedType]);
});
it('should apply AddElementRule with multiple canonical targetType', () => {
const addElementRule = new AddElementRule('org[x]');
addElementRule.min = 0;
addElementRule.max = '1';
addElementRule.types = [
{ type: 'Organization', isCanonical: true },
{ type: 'Practitioner', isCanonical: true }
];
addElementRule.short = 'short definition';
const newElement: ElementDefinition = alternateIdentification.newElement(addElementRule.path);
newElement.applyAddElementRule(addElementRule, fisher);
expect(loggerSpy.getAllLogs('warn')).toHaveLength(0);
expect(newElement.path).toBe('AlternateIdentification.org[x]');
const expectedType = new ElementDefinitionType('canonical').withTargetProfiles(
'http://hl7.org/fhir/StructureDefinition/Organization',
'http://hl7.org/fhir/StructureDefinition/Practitioner'
);
expect(newElement.type).toStrictEqual([expectedType]);
});
it('should log a warning when adding duplicate targetTypes', () => {
const addElementRule = new AddElementRule('created[x]');
addElementRule.min = 0;
addElementRule.max = '1';
addElementRule.types = [{ type: 'instant' }, { type: 'instant' }, { type: 'Period' }];
addElementRule.short = 'short definition';
const newElement: ElementDefinition = alternateIdentification.newElement(addElementRule.path);
newElement.applyAddElementRule(addElementRule, fisher);
expect(newElement.path).toBe('AlternateIdentification.created[x]');
expect(newElement.type).toHaveLength(2);
const expectedType1 = new ElementDefinitionType('instant');
const expectedType2 = new ElementDefinitionType('Period');
expect(newElement.type).toStrictEqual([expectedType1, expectedType2]);
expect(loggerSpy.getLastMessage('warn')).toBe(
'created[x] includes duplicate types. Duplicates have been ignored.'
);
});
it('should not log a duplicate warning when adding multiple Reference and canonical targetTypes', () => {
const addElementRule = new AddElementRule('prop1[x]');
addElementRule.min = 0;
addElementRule.max = '1';
addElementRule.types = [
{ type: 'string' },
{ type: 'uri' },
{ type: 'Organization', isReference: true },
{ type: 'Practitioner', isReference: true },
{ type: 'Organization', isCanonical: true },
{ type: 'Practitioner', isCanonical: true }
];
addElementRule.short = 'short definition';
const newElement: ElementDefinition = alternateIdentification.newElement(addElementRule.path);
newElement.applyAddElementRule(addElementRule, fisher);
expect(loggerSpy.getAllLogs('warn')).toHaveLength(0);
expect(newElement.path).toBe('AlternateIdentification.prop1[x]');
const expectedType1 = new ElementDefinitionType('string');
const expectedType2 = new ElementDefinitionType('uri');
const expectedType3 = new ElementDefinitionType('Reference').withTargetProfiles(
'http://hl7.org/fhir/StructureDefinition/Organization',
'http://hl7.org/fhir/StructureDefinition/Practitioner'
);
const expectedType4 = new ElementDefinitionType('canonical').withTargetProfiles(
'http://hl7.org/fhir/StructureDefinition/Organization',
'http://hl7.org/fhir/StructureDefinition/Practitioner'
);
expect(newElement.type).toStrictEqual([
expectedType1,
expectedType2,
expectedType3,
expectedType4
]);
});
it('should throw an error when invalid path for multiple targetTypes', () => {
const addElementRule = new AddElementRule('prop1');
addElementRule.min = 0;
addElementRule.max = '1';
addElementRule.types = [{ type: 'string' }, { type: 'Annotation' }];
addElementRule.short = 'prop1 definition';
const newElement: ElementDefinition = alternateIdentification.newElement(addElementRule.path);
expect(() => {
newElement.applyAddElementRule(addElementRule, fisher);
}).toThrow(
"As a FHIR choice data type, the specified prop1 for AddElementRule must end with '[x]'."
);
});
it('should apply AddElementRule with single Profile targetType using the profile id', () => {
const addElementRule = new AddElementRule('patient');
addElementRule.min = 0;
addElementRule.max = '1';
addElementRule.types = [{ type: 'us-core-patient' }];
addElementRule.short = 'short definition';
const newElement: ElementDefinition = alternateIdentification.newElement(addElementRule.path);
newElement.applyAddElementRule(addElementRule, fisher);
expect(newElement.path).toBe('AlternateIdentification.patient');
const expectedType = new ElementDefinitionType('Patient').withProfiles(
'http://hl7.org/fhir/us/core/StructureDefinition/us-core-patient'
);
expect(newElement.type).toStrictEqual([expectedType]);
});
it('should apply AddElementRule with single Profile targetType using the profile name', () => {
const addElementRule = new AddElementRule('patient');
addElementRule.min = 0;
addElementRule.max = '1';
addElementRule.types = [{ type: 'USCorePatientProfile' }];
addElementRule.short = 'short definition';
const newElement: ElementDefinition = alternateIdentification.newElement(addElementRule.path);
newElement.applyAddElementRule(addElementRule, fisher);
expect(newElement.path).toBe('AlternateIdentification.patient');
const expectedType = new ElementDefinitionType('Patient').withProfiles(
'http://hl7.org/fhir/us/core/StructureDefinition/us-core-patient'
);
expect(newElement.type).toStrictEqual([expectedType]);
});
it('should apply AddElementRule with single Logical Model targetType using the model id', () => {
const addElementRule = new AddElementRule('serviceModel');
addElementRule.min = 0;
addElementRule.max = '1';
addElementRule.types = [{ type: 'eLTSSServiceModel' }];
addElementRule.short = 'short definition';
const newElement: ElementDefinition = alternateIdentification.newElement(addElementRule.path);
newElement.applyAddElementRule(addElementRule, fisher);
expect(newElement.path).toBe('AlternateIdentification.serviceModel');
const expectedType = new ElementDefinitionType('eLTSSServiceModel');
expect(newElement.type).toStrictEqual([expectedType]);
});
it('should apply AddElementRule with single Logical Model targetType using the model name', () => {
const addElementRule = new AddElementRule('serviceModel');
addElementRule.min = 0;
addElementRule.max = '1';
addElementRule.types = [{ type: 'ELTSSServiceModel' }];
addElementRule.short = 'short definition';
const newElement: ElementDefinition = alternateIdentification.newElement(addElementRule.path);
newElement.applyAddElementRule(addElementRule, fisher);
expect(newElement.path).toBe('AlternateIdentification.serviceModel');
const expectedType = new ElementDefinitionType('eLTSSServiceModel');
expect(newElement.type).toStrictEqual([expectedType]);
});
it('should apply AddElementRule with all boolean flags set to true', () => {
const addElementRule = new AddElementRule('comments');
addElementRule.min = 0;
addElementRule.max = '1';
addElementRule.types = [{ type: 'string' }];
addElementRule.short = 'short definition';
addElementRule.summary = true;
addElementRule.modifier = true;
// MustSupport must be false/undefined for logical models and resources;
// otherwise, error will be thrown - tested elsewhere
const newElement: ElementDefinition = alternateIdentification.newElement(addElementRule.path);
newElement.applyAddElementRule(addElementRule, fisher);
expect(newElement.path).toBe('AlternateIdentification.comments');
expect(newElement.mustSupport).toBeFalsy();
expect(newElement.isSummary).toBeTrue();
expect(newElement.isModifier).toBeTrue();
expect(newElement.extension).toBeUndefined(); // standards flags extensions
});
it('should apply AddElementRule with all boolean flags set to false', () => {
const addElementRule = new AddElementRule('comments');
addElementRule.min = 0;
addElementRule.max = '1';
addElementRule.types = [{ type: 'string' }];
addElementRule.short = 'short definition';
addElementRule.mustSupport = false;
addElementRule.summary = false;
addElementRule.modifier = false;
const newElement: ElementDefinition = alternateIdentification.newElement(addElementRule.path);
newElement.applyAddElementRule(addElementRule, fisher);
expect(newElement.path).toBe('AlternateIdentification.comments');
// When flags are set to false, the attributes are not generated rather than set to false
expect(newElement.mustSupport).toBeUndefined();
expect(newElement.isSummary).toBeUndefined();
expect(newElement.isModifier).toBeUndefined();
expect(newElement.extension).toBeUndefined(); // standards flags extensions
});
it('should apply AddElementRule with trial use standards flag set to true', () => {
const addElementRule = new AddElementRule('comments');
addElementRule.min = 0;
addElementRule.max = '1';
addElementRule.types = [{ type: 'string' }];
addElementRule.short = 'short definition';
addElementRule.trialUse = true;
addElementRule.normative = false;
addElementRule.draft = false;
const newElement: ElementDefinition = alternateIdentification.newElement(addElementRule.path);
newElement.applyAddElementRule(addElementRule, fisher);
expect(newElement.path).toBe('AlternateIdentification.comments');
// When standards flags are set to true, an extension is created
expect(newElement.extension).toHaveLength(1);
expect(newElement.extension[0]).toEqual({
url: 'http://hl7.org/fhir/StructureDefinition/structuredefinition-standards-status',
valueCode: 'trial-use'
});
});
it('should apply AddElementRule with normative standards flag set to true', () => {
const addElementRule = new AddElementRule('comments');
addElementRule.min = 0;
addElementRule.max = '1';
addElementRule.types = [{ type: 'string' }];
addElementRule.short = 'short definition';
addElementRule.trialUse = false;
addElementRule.normative = true;
addElementRule.draft = false;
const newElement: ElementDefinition = alternateIdentification.newElement(addElementRule.path);
newElement.applyAddElementRule(addElementRule, fisher);
expect(newElement.path).toBe('AlternateIdentification.comments');
// When standards flags are set to true, an extension is created
expect(newElement.extension).toHaveLength(1);
expect(newElement.extension[0]).toEqual({
url: 'http://hl7.org/fhir/StructureDefinition/structuredefinition-standards-status',
valueCode: 'normative'
});
});
it('should apply AddElementRule with draft standards flag set to true', () => {
const addElementRule = new AddElementRule('comments');
addElementRule.min = 0;
addElementRule.max = '1';
addElementRule.types = [{ type: 'string' }];
addElementRule.short = 'short definition';
addElementRule.trialUse = false;
addElementRule.normative = false;
addElementRule.draft = true;
const newElement: ElementDefinition = alternateIdentification.newElement(addElementRule.path);
newElement.applyAddElementRule(addElementRule, fisher);
expect(newElement.path).toBe('AlternateIdentification.comments');
// When standards flags are set to true, an extension is created
expect(newElement.extension).toHaveLength(1);
expect(newElement.extension[0]).toEqual({
url: 'http://hl7.org/fhir/StructureDefinition/structuredefinition-standards-status',
valueCode: 'draft'
});
});
it('should apply AddElementRule with all standards flags set to false', () => {
const addElementRule = new AddElementRule('comments');
addElementRule.min = 0;
addElementRule.max = '1';
addElementRule.types = [{ type: 'string' }];
addElementRule.short = 'short definition';
addElementRule.trialUse = false;
addElementRule.normative = false;
addElementRule.draft = false;
const newElement: ElementDefinition = alternateIdentification.newElement(addElementRule.path);
newElement.applyAddElementRule(addElementRule, fisher);
expect(newElement.path).toBe('AlternateIdentification.comments');
// When standards flags are set to false, the underlying extension is not created
expect(newElement.extension).toBeUndefined();
});
it('should throw an error when apply AddElementRule with multiple standards flags set to true', () => {
const addElementRule = new AddElementRule('comments');
addElementRule.min = 0;
addElementRule.max = '1';
addElementRule.types = [{ type: 'string' }];
addElementRule.short = 'short definition';
addElementRule.trialUse = true;
addElementRule.normative = true;
addElementRule.draft = true;
const newElement: ElementDefinition = alternateIdentification.newElement(addElementRule.path);
expect(() => {
newElement.applyAddElementRule(addElementRule, fisher);
}).toThrow('Cannot apply multiple standards status on AlternateIdentification.comments');
});
it('should apply AddElementRule with supported doc attributes', () => {
const addElementRule1 = new AddElementRule('prop1');
addElementRule1.min = 0;
addElementRule1.max = '1';
addElementRule1.types = [{ type: 'string' }];
addElementRule1.short = 'short description for prop1';
addElementRule1.definition = 'definition for prop1';
const addElementRule2 = new AddElementRule('prop2');
addElementRule2.min = 0;
addElementRule2.max = '1';
addElementRule2.types = [{ type: 'string' }];
addElementRule2.short = 'short description for prop2';
const newElement1: ElementDefinition = alternateIdentification.newElement(
addElementRule1.path
);
newElement1.applyAddElementRule(addElementRule1, fisher);
expect(newElement1.path).toBe('AlternateIdentification.prop1');
expect(newElement1.short).toBe(addElementRule1.short);
expect(newElement1.definition).toBe(addElementRule1.definition);
const newElement2: ElementDefinition = alternateIdentification.newElement(
addElementRule2.path
);
newElement2.applyAddElementRule(addElementRule2, fisher);
expect(newElement2.path).toBe('AlternateIdentification.prop2');
expect(newElement2.short).toBe(addElementRule2.short);
// definition gets defaulted to short
expect(newElement2.definition).toBe(addElementRule2.short);
});
});
}); | the_stack |
interface Dict<T extends any = any> {
[key: string]: T;
}
type AnyObj = { [key: string]: any };
type AnyFn = (...args: any[]) => any;
// PIT is short of ProtonIntegrationType
type PIT_euler = "euler";
type PIT_runge_kutta2 = "runge-kutta2";
type PIT_types = PIT_euler | PIT_runge_kutta2;
type PARTICLE_CREATED = "PARTICLE_CREATED";
type PARTICLE_DEAD = "PARTICLE_DEAD";
type PARTICLE_SLEEP = "PARTICLE_SLEEP";
type PARTICLE_UPDATE = "PARTICLE_UPDATE";
type PROTON_UPDATE = "PROTON_UPDATE";
type PROTON_UPDATE_AFTER = "PROTON_UPDATE_AFTER";
type PARTICLE_EVENT =
| PARTICLE_CREATED
| PARTICLE_DEAD
| PARTICLE_SLEEP
| PARTICLE_UPDATE;
type PROTON_EVENT = PROTON_UPDATE | PROTON_UPDATE_AFTER;
type InvalidValues = number | string | boolean | AnyFn | any[];
interface ParticleCtorConf {
life: number;
dead: boolean;
}
interface VectorValConf {
x?: number;
y?: number;
vx?: number;
vy?: number;
ax?: number;
ay?: number;
p?: number;
v?: number;
a?: number;
position?: number;
velocity?: number;
accelerate?: number;
}
interface VectorV {
x: number;
y: number;
}
declare class BaseRenderer {
constructor(element: HTMLElement, stroke: any);
setStroke(color: string, thinkness: number): void;
initHandler(): void;
init(t: any): void;
resize(width: number, heigh: number): void;
destroy(t: any): void;
remove(): void;
onProtonUpdate(): void;
onProtonUpdateAfter(): void;
onEmitterAdded(emitter: Proton.Emitter): void;
onEmitterRemoved(emitter: Proton.Emitter): void;
onParticleCreated(particle: Proton.Particle): void;
onParticleUpdate(particle: Proton.Particle): void;
onParticleDead(particle: Proton.Particle): void;
}
interface RGB {
r: number;
g: number;
b: number;
}
declare class Ease {
static easeInBack(value: number): number;
static easeInCirc(value: number): number;
static easeInCubic(value: number): number;
static easeInExpo(value: number): number;
static easeInOutBack(value: number): number;
static easeInOutCirc(value: number): number;
static easeInOutCubic(value: number): number;
static easeInOutExpo(value: number): number;
static easeInOutQuad(value: number): number;
static easeInOutQuart(value: number): number;
static easeInOutSine(value: number): number;
static easeInQuad(value: number): number;
static easeInQuart(value: number): number;
static easeInSine(value: number): number;
static easeLinear(value: number): number;
static easeOutBack(value: number): number;
static easeOutCirc(value: number): number;
static easeOutCubic(value: number): number;
static easeOutExpo(value: number): number;
static easeOutQuad(value: number): number;
static easeOutQuart(value: number): number;
static easeOutSine(value: number): number;
static getEasing(value: number): number;
}
// 实际上代码里 Proton 并未继承 Ease, Ease里的所有方法是通过Object.assign分配到Proton上的,
// 同时Proton也可以通过Proton.ease 访问Ease里的所有方法, 所有抽出一个Ease,
// 让Proton类继承它,同时也让Proton命名空间里有个ease常量类型定义为它
declare class Proton extends Ease {
static CustomRenderer(t: any): any;
static DEFAULT_INTERVAL: number;
static EMITTER_ADDED: string;
static EMITTER_REMOVED: string;
static EULER: PIT_euler;
static RK2: PIT_runge_kutta2;
static MEASURE: number;
static PARTICLE_CREATED: PARTICLE_CREATED;
static PARTICLE_DEAD: PARTICLE_DEAD;
static PARTICLE_SLEEP: PARTICLE_SLEEP;
static PARTICLE_UPDATE: PARTICLE_UPDATE;
static PROTON_UPDATE: PROTON_UPDATE;
static PROTON_UPDATE_AFTER: PROTON_UPDATE_AFTER;
static USE_CLOCK: "USE_CLOCK";
static amendChangeTabsBug: boolean;
// !!! 已在 namespace里定义
// static createArraySpan(t: any): any;
// !!! 已在 namespace里定义
// static getSpan(t: any, e: any, i: any): any;
fps: number;
integrationType: PIT_types;
emitters: Proton.Emitter[];
renderers: BaseRenderer[];
time: number;
oldtime: number;
constructor(integrationType?: PIT_types);
/**
* add the Emitter
*
* @method addEmitter
* @memberof Proton
* @instance
*
* @param {Proton.Emitter} emitter
*/
addEmitter(emitter: Proton.Emitter): void;
addEventListener(type: string, listener: Function): Function;
/**
* add a type of Renderer
*
* @method addRenderer
* @memberof Proton
* @instance
*
* @param {BaseRenderer} render
*/
addRenderer<T extends BaseRenderer>(render: T): void;
amendChangeTabsBug(): void;
/**
* Destroys everything related to this Proton instance. This includes all emitters, and all properties
*
* @method destroy
* @memberof Proton
* @param {boolean} [remove=false]
*/
destroy(remove: boolean): void;
destroyAllEmitters(): void;
dispatchEvent(t: any, e: any): any;
emittersUpdate(t: any): void;
getAllParticles(): any;
/**
* Counts all particles from all emitters
*
* @method getCount
* @memberof Proton
* @instance
*/
getCount(): number;
hasEventListener(t: any): any;
removeAllEventListeners(t: any): void;
removeEmitter(t: any): void;
removeEventListener(t: any, e: any): void;
removeRenderer(t: any): void;
update(): void;
}
/**
* Advanced Combinations
* see https://www.typescriptlang.org/docs/handbook/declaration-files/deep-dive.html
*/
declare namespace Proton {
const getSpan: (a: any, b: any, center: any) => typeof Span;
const createArraySpan: typeof ArraySpan.createArraySpan;
class Alpha {
name: string;
/**
* @memberof! Proton#
* @augments Proton.Behaviour
* @constructor
* @alias Proton.Alpha
*
* @todo add description for 'a' and 'b'
*
* @param {Number} a
* @param {String} b
* @param {Number} [life=Infinity] this behaviour's life
* @param {String} [easing=ease.easeLinear] this behaviour's easing
*/
constructor(a: number, b: string, life: number, easing: string);
/**
* @method applyBehaviour
* @memberof Proton#Proton.Alpha
* @instance
*
* @param {Proton.Particle} particle
* @param {Number} time the integrate time 1/ms
* @param {Int} index the particle index
*/
applyBehaviour(
particle: Proton.Particle,
time: number,
index: number
): void;
/**
* Sets the new alpha value of the particle
*
* @method initialize
* @memberof Proton#Proton.Alpha
* @instance
*
* @param {Proton.Particle} particle A single Proton generated particle
*/
initialize(particle: Proton.Particle): void;
/**
* Reset this behaviour's parameters
*
* @method reset
* @memberof Proton#Proton.Alpha
* @instance
*
* @todo add description for 'a' and 'b'
*
* @param {Number} a
* @param {String} b
* @param {Number} [life=Infinity] this behaviour's life
* @param {String} [easing=ease.easeLinear] this behaviour's easing
*/
reset(a: number, b: string, life: number, easing: string): void;
static id: number;
}
class ArraySpan {
constructor(t: any);
getValue(): any;
/**
* Make sure that the color is an instance of Proton.ArraySpan, if not it makes a new instance
*/
static createArraySpan(arr: any[]): any;
static getSpanValue(t: any): any;
static setSpanValue(t: any, e: any, i: any): any;
}
const A: Attraction;
class Attraction {
/**
* This behaviour let the particles follow one specific Proton.Vector2D
*
* @memberof! Proton#
* @augments Proton.Behaviour
* @constructor
* @alias Proton.Attraction
*
* @todo add description for 'force' and 'radius'
*
* @param {Proton.Vector2D} targetPosition the attraction point coordinates
* @param {Number} [force=100]
* @param {Number} [radius=1000]
* @param {Number} [life=Infinity] this behaviour's life
* @param {String} [easing=ease.easeLinear] this behaviour's easing
*
* @property {Proton.Vector2D} targetPosition
* @property {Number} radius
* @property {Number} force
* @property {Number} radiusSq
* @property {Proton.Vector2D} attractionForce
* @property {Number} lengthSq
* @property {String} name The Behaviour name
*/
constructor(
targetPosition: Proton.Vector2D,
force: number,
radius: number,
life: number,
easing: string
);
applyBehaviour(t: any, e: any, i: any): void;
reset(t: any, e: any, i: any, a: any, r: any): void;
static id: number;
}
class Behaviour {
static id: number;
id: number;
age: number;
energy: number;
dead: boolean;
parents: Behaviour[];
name: string;
/**
* The Behaviour class is the base for the other Behaviour
*
* @memberof! -
* @interface
* @alias Proton.Behaviour
*
* @param {Number} life the behaviours life
* @param {String} easing The behaviour's decaying trend, for example ease.easeOutQuart
*
* @property {String} id The behaviours id
* @param {Number} [life=Infinity] this behaviour's life
* @param {String} [easing=ease.easeLinear] this behaviour's easing
* @property {Number} age=0 How long the particle should be 'alife'
* @property {Number} energy=1
* @property {Boolean} dead=false The particle is dead at first
* @property {Array} parents The behaviour's parents array
* @property {String} name The behaviour name
*/
constructor(life: number, easing: string);
/**
* Apply this behaviour for all particles every time
*
* @method applyBehaviour
* @memberof Proton.Behaviour
* @instance
*
* @param {Proton.Particle} particle
* @param {Number} time the integrate time 1/ms
*/
calculate(particle: Particle, time: number): void;
destroy(): void;
/**
* Initialize the behaviour's parameters for all particles
*
* @method initialize
* @memberof Proton.Behaviour
*/
initialize(t: any): void;
/**
* Normalize a force by 1:100;
*
* @method normalizeForce
* @memberof Proton.Behaviour
* @instance
*
* @param {Proton.Vector2D} force
*/
normalizeForce(force: Vector2D): Vector2D;
/**
* Normalize a value by 1:100;
*
* @method normalizeValue
* @memberof Proton.Behaviour
* @instance
*
* @param {Number} value
*/
normalizeValue(value: number): number;
/**
* Reset this behaviour's parameters
*
* @method reset
* @memberof Proton.Behaviour
* @instance
*
* @param {Number} [life=Infinity] this behaviour's life
* @param {String} [easing=easeLinear] this behaviour's easing
*/
reset(life: number, easing: string): void;
}
class BehaviourEmitter {
constructor(t: any);
addSelfBehaviour(...args: any[]): void;
removeSelfBehaviour(t: any): void;
update(t: any): void;
}
const B: Body;
class Body extends Initialize {
constructor(image: ArraySpan | string, w: number, h: number);
initialize(t: any): void;
setSpanValue(t: any): any;
}
class CanvasRenderer extends BaseRenderer {
constructor(element: HTMLElement);
addImg2Body(img: string, particle: Particle): void;
createBuffer(image: HTMLImageElement): any;
drawCircle(particle: Particle): void;
drawImage(particle: Particle): void;
onParticleCreated(particle: Particle): void;
onParticleDead(particle: Particle): void;
onParticleUpdate(particle: Particle): void;
onProtonUpdate(): void;
resize(width: number, heigh: number): void;
}
class DomRenderer extends BaseRenderer {
constructor(element: HTMLElement);
addImg2Body(t: any, e: any): void;
bodyReady(particle: Particle): boolean;
createBody(body: any, particle: Particle): HTMLDivElement;
createCircle(particle: Particle): HTMLDivElement;
createSprite(body: any, particle: Particle): HTMLDivElement;
onParticleCreated(particle: Particle): void;
onParticleDead(particle: Particle): void;
onParticleUpdate(particle: Particle): void;
}
class EaselRenderer extends BaseRenderer {
constructor(element: HTMLElement, stroke: any);
createCircle(particle: Particle): HTMLDivElement;
createSprite(t: any): void;
onParticleCreated(particle: Particle): void;
onParticleDead(particle: Particle): void;
onParticleUpdate(particle: Particle): void;
}
class PixelRenderer extends BaseRenderer {
constructor(element: HTMLElement, stroke: any);
createImageData(t: any): void;
onParticleCreated(particle: Particle): void;
onParticleDead(particle: Particle): void;
onParticleUpdate(particle: Particle): void;
onProtonUpdate(): void;
onProtonUpdateAfter(): void;
resize(width: number, height: number): void;
setPixel(imagedata: any, x: number, y: number, particle: Particle): void;
}
class PixiRenderer extends BaseRenderer {
constructor(element: HTMLElement, stroke: any);
createBody(t: any, e: any): any;
createCircle(t: any): any;
createSprite(t: any): any;
destroy(t: any): void;
onParticleCreated(particle: Particle): void;
onParticleDead(particle: Particle): void;
onParticleUpdate(particle: Particle): void;
onProtonUpdate(): void;
setPIXI(t: any): void;
transform(t: any, e: any): void;
}
class CircleZone extends Zone {
x: number;
y: number;
radius: number;
/** @default 0 */
angle: number;
center: { x: number; y: number };
constructor(t: any, e: any, i: any);
crossing(particle: Particle): void;
getGradient(particle: Particle): number;
getPosition(): any;
getSymmetric(particle: Particle): void;
setCenter(x: number, y: number): void;
}
class Collision {
constructor(t: any, e: any, i: any, a: any, r: any);
applyBehaviour(t: any, e: any, i: any): void;
reset(t: any, e: any, i: any, a: any, r: any): void;
static id: number;
}
class Color {
constructor(t: any, e: any, i: any, a: any);
applyBehaviour(t: any, e: any, i: any): void;
initialize(t: any): void;
reset(t: any, e: any, i: any, a: any): void;
static id: number;
}
class CrossZone extends Behaviour {
zone: Zone;
name: "CrossZone";
/**
* Defines what happens if the particles come to the end of the specified zone
*
* @memberof! Proton#
* @augments Proton.Behaviour
* @constructor
* @alias Proton.CrossZone
*
* @param {Proton.Zone} zone can be any Proton.Zone - e.g. Proton.RectZone()
* @param {String} [crossType=dead] what happens if the particles pass the zone - allowed strings: dead | bound | cross
* @param {Number} [life=Infinity] this behaviour's life
* @param {String} [easing=ease.easeLinear] this behaviour's easing
*
* @property {String} name The Behaviour name
*/
constructor(zone: Zone, crossType: string, life: number, easing: string);
/**
* Apply this behaviour for all particles every time
*
* @method applyBehaviour
* @memberof Proton#Proton.CrossZone
* @instance
*
* @param {Proton.Particle} particle
* @param {Number} the integrate time 1/ms
* @param {Int} the particle index
*/
applyBehaviour(particle: Particle, time: number, index: number): void;
reset(zone: Zone, crossType: string, life: number, easing: string): void;
static id: number;
}
class Cyclone extends Behaviour {
name: "Cyclone";
constructor(t: any, e: any, i: any, a: any);
applyBehaviour(t: any, e: any, i: any): void;
initialize(t: any): void;
reset(t: any, e: any, i: any, a: any): void;
setAngleAndForce(t: any, e: any): void;
static id: number;
}
class Emitter extends Particle {
particles: Particle[];
behaviours: Behaviour[];
initializes: Initialize[];
emitTime: number;
emitSpeed: number;
totalTime: number;
/**
* The friction coefficient for all particle emit by This;
* @default 0.006
*/
damping: number;
/**
* If bindEmitter the particles can bind this emitter's property;
* @default true
*/
bindEmitter: boolean;
/**
* If bindEmitter the particles can bind this emitter's property;
* @default {Rate(1, .1)}
*/
rate: Rate;
name: string;
id: string;
constructor(conf: ParticleCtorConf);
/**
* add the Behaviour to particles;
*
* you can use Behaviours array:emitter.addBehaviour(Behaviour1,Behaviour2,Behaviour3);
* @method addBehaviour
* @param {Behaviour} behaviour like this new Color('random')
*/
addBehaviour(...args: Behaviour[]): void;
addEventListener(t: any, e: any): any;
/**
* add the Initialize to particles;
*
* you can use initializes array:for example emitter.addInitialize(initialize1,initialize2,initialize3);
* @method addInitialize
* @param {Initialize} initialize like this new Radius(1, 12)
*/
addInitialize(...args: Initialize[]): void;
/**
* add initialize to this emitter
* @method addSelfInitialize
*/
addSelfInitialize(initialize: Initialize): void;
/**
* create single particle;
*
* can use emit({x:10},new Gravity(10),{'particleUpdate',fun}) or emit([{x:10},new Initialize],new Gravity(10),{'particleUpdate',fun})
*/
createParticle(initialize: Initialize, behaviour: Behaviour): any;
destroy(): void;
dispatch(t: any, e: any): void;
dispatchEvent(t: any, e: any): any;
/**
* start emit particle
* @method emit
* @param {Number} emitTime begin emit time;
* @param {String} life the life of this emitter
*/
emit(emitTime: number, life: string): void;
emitting(t: any): void;
hasEventListener(t: any): any;
integrate(time: number): void;
preEmit(time: number): void;
remove(): void;
removeAllBehaviours(): void;
removeAllEventListeners(t: any): void;
removeAllInitializers(): void;
removeAllParticles(): void;
/**
* remove the Behaviour
* @method removeBehaviour
* @param {Behaviour} behaviour a behaviour
*/
removeBehaviour(behaviour: Behaviour): any;
removeEventListener(t: any, e: any): void;
/**
* remove the Initialize
* @method removeInitialize
* @param {Initialize} initialize a initialize
*/
removeInitialize(initialize: Initialize): void;
setupParticle(t: any, e: any, i: any): void;
stop(): void;
update(time: number): void;
}
class FollowEmitter {
constructor(t: any, e: any, i: any);
destroy(): void;
emit(): void;
initEventHandler(): any;
mousemove(t: any): void;
stop(): void;
}
const F: Force;
class Force {
constructor(t: any, e: any, i: any, a: any);
applyBehaviour(t: any, e: any, i: any): void;
reset(t: any, e: any, i: any, a: any): void;
static id: number;
}
const G: Gravity;
class Gravity extends Force {
name: "Gravity";
constructor(t: any, e: any, i: any);
reset(t: any, e: any, i: any): void;
static id: number;
}
class GravityWell extends Behaviour {
distanceVec: Vector2D;
centerPoint: number;
force: number;
name: "GravityWell";
constructor(t: any, e: any, i: any, a: any);
applyBehaviour(t: any, e: any): void;
initialize(): void;
reset(t: any, e: any, i: any, a: any): void;
static id: number;
}
class ImageZone extends Zone {
x: number;
y: number;
d: number;
vectors: Vector2D[];
constructor(t: any, e: any, i: any, a: any);
crossing(t: any): void;
getBound(t: any, e: any): any;
getColor(x: number, y: number): boolean;
getPosition(): any;
reset(t: any, e: any, i: any, a: any): void;
setVectors(): any;
}
const Init: Initialize;
class Initialize {
constructor();
init(t: any, e: any): void;
initialize(t: any): void;
reset(t: any, e: any, i: any): void;
}
const L: Life;
class Life extends Initialize {
constructor(t: any, e: any, i: any);
initialize(t: any): void;
}
class LineZone extends Zone {
x1: number;
y1: number;
x2: number;
y2: number;
dx: number;
dy: number;
minx: number;
miny: number;
maxx: number;
maxy: number;
dot: number;
xxyy: number;
gradient: number;
length: number;
direction: number;
constructor(
x1: number,
y1: number,
x2: number,
y2: number,
direction: number
);
crossing(particle: Particle): void;
getDirection(x: number, y: number): number;
getDistance(x: number, y: number): number;
getGradient(): number;
getLength(): number;
getPosition(): Vector2D;
getSymmetric(v: any): any;
rangeOut(particle: Particle): any;
}
const M: Mass;
class Mass extends Initialize {
name: string;
massPan: Span;
constructor(a: any, b: any, c: any);
initialize(target: any): void;
}
const P: Particle;
class Particle {
id: string;
old: { p: Vector2D; v: Vector2D; a: Vector2D };
data: Dict;
behaviours: Behaviour[];
p: Vector2D;
v: Vector2D;
a: Vector2D;
rgb: RGB;
constructor(conf: ParticleCtorConf);
getDirection(): number;
reset(): this;
update(time: number, index: number): void;
applyBehaviours(time: number, index: number): void;
addBehaviour(behaviour: Behaviour): void;
addBehaviours(behaviours: Behaviour[]): void;
removeBehaviour(behaviour: Behaviour): void;
removeAllBehaviours(): void;
destroy(): void;
}
class PointZone extends Zone {
x: number;
y: number;
constructor(x: number, y: number);
crossing(): void;
getPosition(): Vector2D;
}
const Polar: Polar2D;
class Polar2D {
r: number;
tha: number;
constructor(r: number, tha: number);
clear(): this;
clone(): Polar2D;
copy(t: any): any;
equals(t: any): boolean;
getX(): number;
getY(): number;
normalize(): this;
set(r: number, tha: number): this;
setR(r: number): this;
setTha(tha: number): this;
toVector(): Vector2D;
}
class Pool {
total: number;
cache: Dict;
constructor(t: any);
createOrClone(t: any, e: any): any;
destroy(): void;
expire(t: any): any;
/**
* @todo add description
*
* @method get
* @memberof Proton#Proton.Pool
*
* @param {Object|Function} target
* @param {Object} [params] just add if `target` is a function
*
* @return {Object}
*/
get(target: Object | Function, params: any, uid: string): any;
getCache(t: any, ...args: any[]): any;
/**
* @todo add description - what is in the cache?
*
* @method getCount
* @memberof Proton#Proton.Pool
*
* @return {Number}
*/
getCount(): number;
}
class Position {
constructor(t: any);
initialize(t: any): void;
reset(t: any): void;
}
const R: Radius;
class Radius extends Initialize {
radius: Span;
name: "Radius";
constructor(t: any, e: any, i: any);
initialize(particle: Particle): void;
reset(t: any, e: any, i: any): void;
}
const RD: RandomDrift;
class RandomDrift extends Behaviour {
/** @default 0 */
time: number;
name: "RandomDrift";
constructor(t: any, e: any, i: any, a: any, r: any);
applyBehaviour(t: any, e: any, i: any): void;
initialize(t: any): void;
reset(t: any, e: any, i: any, a: any, r: any): void;
static id: number;
}
class Rate {
constructor(t: any, e: any);
getValue(t: any): any;
init(): void;
}
class RectZone extends Zone {
constructor(t: any, e: any, i: any, a: any);
crossing(particle: Particle): void;
getPosition(): any;
}
class Rectangle {
constructor(t: any, e: any, i: any, a: any);
contains(t: any, e: any): any;
}
class Repulsion extends Attraction {
name: "Repulsion";
constructor(t: any, e: any, i: any, a: any, r: any);
reset(t: any, e: any, i: any, a: any, r: any): void;
static id: number;
}
class Rotate extends Behaviour {
name: "Rotate";
constructor(t: any, e: any, i: any, a: any, r: any);
applyBehaviour(t: any, e: any, i: any): void;
initialize(t: any): void;
reset(t: any, e: any, i: any, a: any, r: any): void;
static id: number;
}
const S: Scale;
class Scale extends Behaviour {
name: "Scale";
constructor(t: any, e: any, i: any, a: any);
applyBehaviour(t: any, e: any, i: any): void;
initialize(t: any): void;
reset(t: any, e: any, i: any, a: any): void;
static id: number;
}
class Span {
constructor(t: any, e: any, i: any);
getValue(t: any, ...args: any[]): any;
static getSpanValue(t: any): any;
static setSpanValue(t: any, e: any, i: any): any;
}
const Vector: Vector2D;
class Vector2D {
/** @default 0 */
x: number;
/** @default 0 */
y: number;
constructor(x: number, y: number);
add(v: VectorV, w: VectorV): this;
addVectors(t: VectorV, e: VectorV): this;
addXY(x: number, y: number): any;
clear(): this;
clone(): Vector2D;
copy(v: VectorV): this;
distanceTo(v: VectorV): number;
distanceToSquared(v: VectorV): number;
divideScalar(s: number): this;
dot(v: VectorV): number;
equals(v: VectorV): boolean;
getGradient(): number;
length(): number;
lengthSq(): number;
lerp(v: VectorV, alpha: number): this;
multiplyScalar(s: number): this;
negate(): this;
normalize(): this;
rotate(tha: number): this;
set(x: number, y: number): this;
setX(x: number): this;
setY(y: number): this;
sub(v: VectorV, w: VectorV): this;
subVectors(a: VectorV, b: VectorV): this;
}
const V: Velocity;
class Velocity extends Initialize {
rPan: Span;
thaPan: Span;
type: string;
name: string;
constructor(rpan: Span | string, thapan: Span | string, type: string);
initialize(target: any): void;
normalizeVelocity(vr: number): number;
reset(rpan: Span | string, thapan: Span | string, type: string): void;
}
const WebGlRenderer: WebGLRenderer;
class WebGLRenderer extends BaseRenderer {
constructor(t: any);
addImg2Body(t: any, e: any): void;
blendEquation(t: any): void;
blendFunc(t: any, e: any): void;
createCircle(t: any): any;
drawImg2Canvas(t: any): void;
getFragmentShader(): any;
getShader(t: any, e: any, i: any): any;
getVertexShader(): any;
init(t: any): void;
initBuffers(): void;
initShaders(): void;
initVar(): void;
onParticleCreated(t: any): void;
onParticleDead(): void;
onParticleUpdate(t: any): void;
onProtonUpdate(): void;
resize(t: any, e: any): void;
setMaxRadius(t: any): void;
updateMatrix(t: any): void;
}
class Zone {
vector: Vector2D;
/**
* @default 0
*/
random: number;
/**
* @default 'dead'
*/
crossType: string;
/**
* @default true
*/
alert: boolean;
constructor();
crossing(particle: Particle): void;
getPosition(): void;
}
namespace ColorUtil {
/**
* converts a hex value to a rgb object
*
* @memberof Proton#Proton.Util
* @method hexToRgb
*
* @param {String} h any hex value, e.g. #000000 or 000000 for black
*
* @return {rgbObject}
*/
function hexToRgb(hex: string): RGB;
function rgbToHex(rgbObject: RGB): string;
function getHex16FromParticle(particle: Proton.Particle): string;
}
namespace Debug {
function addEventListener(t: any, e: any): any;
function drawEmitter(t: any, e: any, i: any, a: any): void;
function drawZone(t: any, e: any, i: any, a: any): void;
function getStyle(t: any, ...args: any[]): any;
}
namespace Mat3 {
function create(t: any): any;
function inverse(t: any, e: any): any;
function multiply(t: any, e: any, i: any): any;
function multiplyVec2(t: any, e: any, i: any): any;
function set(t: any, e: any): any;
}
namespace MathUtil {
const Infinity: number;
const N180_PI: number;
const PI: number;
const PI_180: number;
const PI_2: number;
const PIx2: number;
function degreeTransform(t: any): any;
function floor(t: any, e: any, ...args: any[]): any;
function isInfinity(t: any): any;
function randomAToB(t: any, e: any, i: any, ...args: any[]): any;
function randomColor(): any;
function randomFloating(t: any, e: any, i: any): any;
function randomZone(): void;
function toColor16(t: any): any;
}
namespace Util {
function initValue(value: InvalidValues, defaults: any): any;
function isArray(value: any): boolean;
function emptyArray(arr: any[]): boolean;
function toArray<T>(input: T): T extends any[] ? T : T[];
function getRandFromArray<T>(input: T): T extends any[] ? number : null;
/**
* @description - Destroyes the given object
*/
function emptyObject<T extends AnyObj>(input: T, ignore?: string[]): void;
function classApply(constructor: Function, args?: any[]): any;
function setVectorVal(particle: Particle, conf?: VectorValConf): void;
function hasProp(target: any, key: string): boolean;
function setProp<T extends AnyObj, U extends T>(
target: T,
props: string[]
): U;
/**
* This will get the image data. It could be necessary to create a Proton.Zone.
*
* @memberof Proton#Proton.Util
* @method getImageData
*
* @param {HTMLCanvasElement} context any canvas, must be a 2dContext 'canvas.getContext('2d')'
* @param {Object} image could be any dom image, e.g. document.getElementById('thisIsAnImgTag');
* @param {Proton.Rectangle} rect
*/
function getImageData(
context: HTMLCanvasElement,
image: object,
rect: Proton.Rectangle
): void;
function destroyAll(arr: any[], param?: any): void;
function assign<T extends AnyObj>(target: AnyObj, source: AnyObj): T;
}
const ease: Ease;
}
declare let defaultExport: typeof Proton;
export default defaultExport; | the_stack |
import {Request} from '../lib/request';
import {Response} from '../lib/response';
import {AWSError} from '../lib/error';
import {Service} from '../lib/service';
import {ServiceConfigurationOptions} from '../lib/service';
import {ConfigBase as Config} from '../lib/config';
interface Blob {}
declare class Budgets extends Service {
/**
* Constructs a service object. This object has one method for each API operation.
*/
constructor(options?: Budgets.Types.ClientConfiguration)
config: Config & Budgets.Types.ClientConfiguration;
/**
* Create a new budget
*/
createBudget(params: Budgets.Types.CreateBudgetRequest, callback?: (err: AWSError, data: Budgets.Types.CreateBudgetResponse) => void): Request<Budgets.Types.CreateBudgetResponse, AWSError>;
/**
* Create a new budget
*/
createBudget(callback?: (err: AWSError, data: Budgets.Types.CreateBudgetResponse) => void): Request<Budgets.Types.CreateBudgetResponse, AWSError>;
/**
* Create a new Notification with subscribers for a budget
*/
createNotification(params: Budgets.Types.CreateNotificationRequest, callback?: (err: AWSError, data: Budgets.Types.CreateNotificationResponse) => void): Request<Budgets.Types.CreateNotificationResponse, AWSError>;
/**
* Create a new Notification with subscribers for a budget
*/
createNotification(callback?: (err: AWSError, data: Budgets.Types.CreateNotificationResponse) => void): Request<Budgets.Types.CreateNotificationResponse, AWSError>;
/**
* Create a new Subscriber for a notification
*/
createSubscriber(params: Budgets.Types.CreateSubscriberRequest, callback?: (err: AWSError, data: Budgets.Types.CreateSubscriberResponse) => void): Request<Budgets.Types.CreateSubscriberResponse, AWSError>;
/**
* Create a new Subscriber for a notification
*/
createSubscriber(callback?: (err: AWSError, data: Budgets.Types.CreateSubscriberResponse) => void): Request<Budgets.Types.CreateSubscriberResponse, AWSError>;
/**
* Delete a budget and related notifications
*/
deleteBudget(params: Budgets.Types.DeleteBudgetRequest, callback?: (err: AWSError, data: Budgets.Types.DeleteBudgetResponse) => void): Request<Budgets.Types.DeleteBudgetResponse, AWSError>;
/**
* Delete a budget and related notifications
*/
deleteBudget(callback?: (err: AWSError, data: Budgets.Types.DeleteBudgetResponse) => void): Request<Budgets.Types.DeleteBudgetResponse, AWSError>;
/**
* Delete a notification and related subscribers
*/
deleteNotification(params: Budgets.Types.DeleteNotificationRequest, callback?: (err: AWSError, data: Budgets.Types.DeleteNotificationResponse) => void): Request<Budgets.Types.DeleteNotificationResponse, AWSError>;
/**
* Delete a notification and related subscribers
*/
deleteNotification(callback?: (err: AWSError, data: Budgets.Types.DeleteNotificationResponse) => void): Request<Budgets.Types.DeleteNotificationResponse, AWSError>;
/**
* Delete a Subscriber for a notification
*/
deleteSubscriber(params: Budgets.Types.DeleteSubscriberRequest, callback?: (err: AWSError, data: Budgets.Types.DeleteSubscriberResponse) => void): Request<Budgets.Types.DeleteSubscriberResponse, AWSError>;
/**
* Delete a Subscriber for a notification
*/
deleteSubscriber(callback?: (err: AWSError, data: Budgets.Types.DeleteSubscriberResponse) => void): Request<Budgets.Types.DeleteSubscriberResponse, AWSError>;
/**
* Get a single budget
*/
describeBudget(params: Budgets.Types.DescribeBudgetRequest, callback?: (err: AWSError, data: Budgets.Types.DescribeBudgetResponse) => void): Request<Budgets.Types.DescribeBudgetResponse, AWSError>;
/**
* Get a single budget
*/
describeBudget(callback?: (err: AWSError, data: Budgets.Types.DescribeBudgetResponse) => void): Request<Budgets.Types.DescribeBudgetResponse, AWSError>;
/**
* Get all budgets for an account
*/
describeBudgets(params: Budgets.Types.DescribeBudgetsRequest, callback?: (err: AWSError, data: Budgets.Types.DescribeBudgetsResponse) => void): Request<Budgets.Types.DescribeBudgetsResponse, AWSError>;
/**
* Get all budgets for an account
*/
describeBudgets(callback?: (err: AWSError, data: Budgets.Types.DescribeBudgetsResponse) => void): Request<Budgets.Types.DescribeBudgetsResponse, AWSError>;
/**
* Get notifications of a budget
*/
describeNotificationsForBudget(params: Budgets.Types.DescribeNotificationsForBudgetRequest, callback?: (err: AWSError, data: Budgets.Types.DescribeNotificationsForBudgetResponse) => void): Request<Budgets.Types.DescribeNotificationsForBudgetResponse, AWSError>;
/**
* Get notifications of a budget
*/
describeNotificationsForBudget(callback?: (err: AWSError, data: Budgets.Types.DescribeNotificationsForBudgetResponse) => void): Request<Budgets.Types.DescribeNotificationsForBudgetResponse, AWSError>;
/**
* Get subscribers of a notification
*/
describeSubscribersForNotification(params: Budgets.Types.DescribeSubscribersForNotificationRequest, callback?: (err: AWSError, data: Budgets.Types.DescribeSubscribersForNotificationResponse) => void): Request<Budgets.Types.DescribeSubscribersForNotificationResponse, AWSError>;
/**
* Get subscribers of a notification
*/
describeSubscribersForNotification(callback?: (err: AWSError, data: Budgets.Types.DescribeSubscribersForNotificationResponse) => void): Request<Budgets.Types.DescribeSubscribersForNotificationResponse, AWSError>;
/**
* Update the information of a budget already created
*/
updateBudget(params: Budgets.Types.UpdateBudgetRequest, callback?: (err: AWSError, data: Budgets.Types.UpdateBudgetResponse) => void): Request<Budgets.Types.UpdateBudgetResponse, AWSError>;
/**
* Update the information of a budget already created
*/
updateBudget(callback?: (err: AWSError, data: Budgets.Types.UpdateBudgetResponse) => void): Request<Budgets.Types.UpdateBudgetResponse, AWSError>;
/**
* Update the information about a notification already created
*/
updateNotification(params: Budgets.Types.UpdateNotificationRequest, callback?: (err: AWSError, data: Budgets.Types.UpdateNotificationResponse) => void): Request<Budgets.Types.UpdateNotificationResponse, AWSError>;
/**
* Update the information about a notification already created
*/
updateNotification(callback?: (err: AWSError, data: Budgets.Types.UpdateNotificationResponse) => void): Request<Budgets.Types.UpdateNotificationResponse, AWSError>;
/**
* Update a subscriber
*/
updateSubscriber(params: Budgets.Types.UpdateSubscriberRequest, callback?: (err: AWSError, data: Budgets.Types.UpdateSubscriberResponse) => void): Request<Budgets.Types.UpdateSubscriberResponse, AWSError>;
/**
* Update a subscriber
*/
updateSubscriber(callback?: (err: AWSError, data: Budgets.Types.UpdateSubscriberResponse) => void): Request<Budgets.Types.UpdateSubscriberResponse, AWSError>;
}
declare namespace Budgets {
export type AccountId = string;
export interface Budget {
BudgetName: BudgetName;
BudgetLimit: Spend;
CostFilters?: CostFilters;
CostTypes: CostTypes;
TimeUnit: TimeUnit;
TimePeriod: TimePeriod;
CalculatedSpend?: CalculatedSpend;
BudgetType: BudgetType;
}
export type BudgetName = string;
export type BudgetType = "USAGE"|"COST"|string;
export type Budgets = Budget[];
export interface CalculatedSpend {
ActualSpend: Spend;
ForecastedSpend?: Spend;
}
export type ComparisonOperator = "GREATER_THAN"|"LESS_THAN"|"EQUAL_TO"|string;
export type CostFilters = {[key: string]: DimensionValues};
export interface CostTypes {
IncludeTax: GenericBoolean;
IncludeSubscription: GenericBoolean;
UseBlended: GenericBoolean;
}
export interface CreateBudgetRequest {
AccountId: AccountId;
Budget: Budget;
NotificationsWithSubscribers?: NotificationWithSubscribersList;
}
export interface CreateBudgetResponse {
}
export interface CreateNotificationRequest {
AccountId: AccountId;
BudgetName: BudgetName;
Notification: Notification;
Subscribers: Subscribers;
}
export interface CreateNotificationResponse {
}
export interface CreateSubscriberRequest {
AccountId: AccountId;
BudgetName: BudgetName;
Notification: Notification;
Subscriber: Subscriber;
}
export interface CreateSubscriberResponse {
}
export interface DeleteBudgetRequest {
AccountId: AccountId;
BudgetName: BudgetName;
}
export interface DeleteBudgetResponse {
}
export interface DeleteNotificationRequest {
AccountId: AccountId;
BudgetName: BudgetName;
Notification: Notification;
}
export interface DeleteNotificationResponse {
}
export interface DeleteSubscriberRequest {
AccountId: AccountId;
BudgetName: BudgetName;
Notification: Notification;
Subscriber: Subscriber;
}
export interface DeleteSubscriberResponse {
}
export interface DescribeBudgetRequest {
AccountId: AccountId;
BudgetName: BudgetName;
}
export interface DescribeBudgetResponse {
Budget?: Budget;
}
export interface DescribeBudgetsRequest {
AccountId: AccountId;
MaxResults?: MaxResults;
NextToken?: GenericString;
}
export interface DescribeBudgetsResponse {
Budgets?: Budgets;
NextToken?: GenericString;
}
export interface DescribeNotificationsForBudgetRequest {
AccountId: AccountId;
BudgetName: BudgetName;
MaxResults?: MaxResults;
NextToken?: GenericString;
}
export interface DescribeNotificationsForBudgetResponse {
Notifications?: Notifications;
NextToken?: GenericString;
}
export interface DescribeSubscribersForNotificationRequest {
AccountId: AccountId;
BudgetName: BudgetName;
Notification: Notification;
MaxResults?: MaxResults;
NextToken?: GenericString;
}
export interface DescribeSubscribersForNotificationResponse {
Subscribers?: Subscribers;
NextToken?: GenericString;
}
export type DimensionValues = GenericString[];
export type GenericBoolean = boolean;
export type GenericString = string;
export type GenericTimestamp = Date;
export type MaxResults = number;
export interface Notification {
NotificationType: NotificationType;
ComparisonOperator: ComparisonOperator;
Threshold: NotificationThreshold;
}
export type NotificationThreshold = number;
export type NotificationType = "ACTUAL"|"FORECASTED"|string;
export interface NotificationWithSubscribers {
Notification: Notification;
Subscribers: Subscribers;
}
export type NotificationWithSubscribersList = NotificationWithSubscribers[];
export type Notifications = Notification[];
export type NumericValue = string;
export interface Spend {
Amount: NumericValue;
Unit: GenericString;
}
export interface Subscriber {
SubscriptionType: SubscriptionType;
Address: GenericString;
}
export type Subscribers = Subscriber[];
export type SubscriptionType = "SNS"|"EMAIL"|string;
export interface TimePeriod {
Start: GenericTimestamp;
End: GenericTimestamp;
}
export type TimeUnit = "MONTHLY"|"QUARTERLY"|"ANNUALLY"|string;
export interface UpdateBudgetRequest {
AccountId: AccountId;
NewBudget: Budget;
}
export interface UpdateBudgetResponse {
}
export interface UpdateNotificationRequest {
AccountId: AccountId;
BudgetName: BudgetName;
OldNotification: Notification;
NewNotification: Notification;
}
export interface UpdateNotificationResponse {
}
export interface UpdateSubscriberRequest {
AccountId: AccountId;
BudgetName: BudgetName;
Notification: Notification;
OldSubscriber: Subscriber;
NewSubscriber: Subscriber;
}
export interface UpdateSubscriberResponse {
}
export type errorMessage = string;
/**
* A string in YYYY-MM-DD format that represents the latest possible API version that can be used in this service. Specify 'latest' to use the latest possible version.
*/
export type apiVersion = "2016-10-20"|"latest"|string;
export interface ClientApiVersions {
/**
* A string in YYYY-MM-DD format that represents the latest possible API version that can be used in this service. Specify 'latest' to use the latest possible version.
*/
apiVersion?: apiVersion;
}
export type ClientConfiguration = ServiceConfigurationOptions & ClientApiVersions;
/**
* Contains interfaces for use with the Budgets client.
*/
export import Types = Budgets;
}
export = Budgets; | the_stack |
import { asyncify } from "@core/lib/async";
import { clearOrphanedRootPubkeyReplacements } from "./models/crypto";
import { getOrg } from "./models/orgs";
import { log, logWithElapsed, logStderr } from "@core/lib/utils/logger";
import { getLogTransactionStatement } from "./models/logs";
import { createPatch } from "rfc6902";
import { Api, Client, Auth, Crypto, Blob, Rbac, Awaited } from "@core/types";
import { authenticate, authorizeEnvsUpdate } from "./auth";
import * as R from "ramda";
import {
getNewTransactionConn,
objectTransactionItemsEmpty,
mergeObjectTransactionItems,
objectTransactionStatements,
executeTransactionStatements,
releaseTransaction,
} from "./db";
import { env } from "./env";
import {
getGraphTransactionItems,
getOrgGraph,
getApiUserGraph,
clearOrphanedLocals,
} from "./graph";
import {
getCurrentEncryptedKeys,
deleteExpiredAuthObjects,
graphTypes,
getNumActiveDeviceLike,
getNumActiveOrInvitedUsers,
} from "@core/lib/graph";
import { keySetDifference, keySetEmpty } from "@core/lib/blob";
import {
getDeleteEncryptedKeysTransactionItems,
getEnvParamsTransactionItems,
getEnvEncryptedKeys,
getChangesetEncryptedKeys,
requireEncryptedKeys,
queueBlobsForReencryptionFromToDeleteEncryptedKeys,
getReorderEncryptedKeysTransactionItems,
getEnvEncryptedBlobs,
getChangesetEncryptedBlobs,
} from "./blob";
import { pick } from "@core/lib/utils/pick";
import { wait } from "@core/lib/utils/wait";
import { v4 as uuid } from "uuid";
import { PoolConnection } from "mysql2/promise";
import produce from "immer";
type ApiActionConfig = Api.ApiActionParams<
Api.Action.RequestAction,
Api.Net.ApiResult
>;
let replicationFn: Api.ReplicationFn | undefined;
let updateOrgStatsFn: Api.UpdateOrgStatsFn | undefined;
let throttleRequestFn: Api.ThrottleRequestFn | undefined;
let throttleResponseFn: Api.ThrottleResponseFn | undefined;
export const apiAction = <
ActionType extends Api.Action.RequestAction,
ResponseType extends Api.Net.ApiResult,
AuthContextType extends Auth.AuthContext = Auth.DefaultAuthContext
>(
apiAction: Api.ApiActionParams<ActionType, ResponseType, AuthContextType>
) => {
if (apiActions[apiAction.type]) {
throw new Api.ApiError(
"Api Action with this type was already defined",
500
);
}
apiActions[apiAction.type] = apiAction as Api.ApiActionParams<
Api.Action.RequestAction,
ResponseType
>;
},
registerSocketServer = (server: Api.SocketServer) => (socketServer = server),
// inject s3 replication handler
registerReplicationFn = (fn: typeof replicationFn) => {
replicationFn = fn;
},
registerUpdateOrgStatsFn = (fn: Api.UpdateOrgStatsFn) => {
updateOrgStatsFn = fn;
},
registerThrottleRequestFn = (fn: Api.ThrottleRequestFn) => {
throttleRequestFn = fn;
},
getThrottleRequestFn = () => throttleRequestFn,
registerThrottleResponseFn = (fn: Api.ThrottleResponseFn) => {
throttleResponseFn = fn;
},
getThrottleResponseFn = () => throttleResponseFn,
handleAction = async (
action: Api.Action.RequestAction | Api.Action.BulkGraphAction,
requestParams: Api.RequestParams
): Promise<Api.Net.ApiResult> => {
const transactionId = uuid();
const requestBytes = Buffer.byteLength(JSON.stringify(action), "utf8");
log("Received action " + action.type, {
requestBytes,
transactionId,
requestParams,
});
const isFetchAction =
action.type == Api.ActionType.FETCH_ENVKEY ||
action.type == Api.ActionType.ENVKEY_FETCH_UPDATE_TRUSTED_ROOT_PUBKEY;
const apiActionConfig = apiActions[action.type];
if (!apiActionConfig && action.type != Api.ActionType.BULK_GRAPH_ACTION) {
const msg = "No handler matched the API action type";
log(msg);
throw new Api.ApiError(msg, 404);
}
const requestStart = Date.now();
const transactionConn = await getNewTransactionConn();
logWithElapsed(transactionId + " - started transaction", requestStart);
try {
let auth: Auth.AuthContext | undefined;
let actionStart = requestStart;
if (
action.type == Api.ActionType.BULK_GRAPH_ACTION ||
apiActionConfig.authenticated
) {
if (!("auth" in action.meta) || !action.meta.auth) {
throw new Api.ApiError(
`Authentication failed (${transactionId})`,
401
);
}
auth = await authenticate(
action.meta.auth,
transactionConn,
requestParams.ip,
action.type == Api.ActionType.FETCH_ORG_STATS
).catch((err) => {
throw err;
});
actionStart = Date.now();
}
logWithElapsed(transactionId + " - authenticated", requestStart);
if (auth) {
log("Authenticated action", {
type: action.type,
transactionId,
requestBytes,
requestStart,
actionStart,
org: [auth.org.name, auth.org.id].join(" → "),
user:
"user" in auth && auth.user
? "firstName" in auth.user
? [
[auth.user.firstName, auth.user.lastName].join(" "),
auth.user.id,
].join(" → ")
: [auth.user.name, auth.user.id].join(" → ")
: undefined,
device:
"orgUserDevice" in auth
? [auth.orgUserDevice.name, auth.orgUserDevice.id].join(" → ")
: undefined,
provisioningProvider:
"provisioningProvider" in auth
? [
auth.provisioningProvider.nickname,
auth.provisioningProvider.id,
].join(" → ")
: undefined,
orgRole: "orgRole" in auth ? auth.orgRole?.name : undefined,
// orgPermissions: Array.from(auth.orgPermissions),
});
}
const result = await tryHandleAction({
action,
requestParams,
apiActionConfig,
requestStart,
actionStart,
transactionId,
auth,
transactionConn,
requestBytes,
});
return result;
} catch (err) {
let msg: string, status: number;
if (err instanceof Api.ApiError) {
msg = err.message;
status = err.code;
} else if (err instanceof Error) {
msg = err.message;
status = 500;
} else {
msg = "Server error";
status = 500;
}
logWithElapsed(`api error: ${msg}`, requestStart, {
status,
stack: err.stack,
transactionConn: Boolean(transactionConn),
});
try {
await transactionConn.query("ROLLBACK;");
logWithElapsed("rolled back transaction", requestStart);
} catch (err) {
logStderr("Error rolling back transaction:", {
err,
stack: err.stack,
});
}
throw new Api.ApiError(msg, status);
} finally {
try {
await releaseTransaction(transactionConn);
logWithElapsed("released transaction", requestStart);
} catch (err) {
logStderr("Error releasing transaction:", {
err,
stack: err.stack,
});
}
}
},
tryHandleAction = async (params: {
action: Api.Action.RequestAction | Api.Action.BulkGraphAction;
requestParams: Api.RequestParams;
apiActionConfig: ApiActionConfig;
requestStart: number;
actionStart: number;
transactionId: string;
auth?: Auth.AuthContext;
transactionConn: PoolConnection;
requestBytes: number;
}): Promise<Api.Net.ApiResult> => {
const {
action,
requestParams,
apiActionConfig,
requestStart,
actionStart,
transactionId,
auth,
transactionConn,
requestBytes,
} = params;
let response: Api.Net.ApiResult | undefined,
responseBytes: number | undefined,
transactionStatements: Api.Db.SqlStatement[] = [],
backgroundStatements: Api.Db.SqlStatement[] = [],
postUpdateActions: Api.HandlerPostUpdateActions | undefined,
clearUserSockets: Api.ClearUserSocketParams[] = [],
clearEnvkeySockets: Api.ClearEnvkeySocketParams[] = [],
updatedGeneratedEnvkeyIds: string[] = [],
orgGraph: Api.Graph.OrgGraph | undefined,
updatedOrgGraph: Api.Graph.OrgGraph | undefined,
reorderBlobsIfNeeded = false,
handlerContext: Api.HandlerContext | undefined;
if (action.type == Api.ActionType.BULK_GRAPH_ACTION && auth) {
const graphScopeFns: ReturnType<Api.GraphScopeFn>[][] = [];
for (let graphAction of action.payload) {
const graphApiActionConfig = apiActions[graphAction.type];
if (
graphApiActionConfig.graphAction &&
!graphApiActionConfig.skipGraphUpdatedAtCheck &&
(
(graphAction as Api.Action.RequestAction).meta as {
graphUpdatedAt: number;
}
).graphUpdatedAt !== auth.org.graphUpdatedAt
) {
throw new Api.ApiError("client graph outdated", 400);
}
if (
graphApiActionConfig.graphAction &&
graphApiActionConfig.graphScopes
) {
graphApiActionConfig.graphScopes.forEach((fn, i) => {
if (!graphScopeFns[i]) {
graphScopeFns[i] = [];
}
graphScopeFns[i].push(
fn(auth, graphAction as Api.Action.RequestAction)
);
});
}
}
if (graphScopeFns.length > 0) {
for (let scopeFns of graphScopeFns) {
const scopes = new Set<string>();
for (let scopeFn of scopeFns) {
for (let scope of scopeFn(orgGraph)) {
scopes.add(scope);
}
}
orgGraph = await getOrgGraph(
auth.org.id,
{
transactionConn,
},
Array.from(scopes)
);
}
} else {
orgGraph = await getOrgGraph(auth.org.id, {
transactionConn,
});
}
logWithElapsed(transactionId + " - got org graph", requestStart);
const actionResults: Awaited<ReturnType<typeof getActionRes>>[] = [];
// const actionResults = await Promise.all(
// action.payload.map(async (graphAction) => {
for (let graphAction of action.payload) {
const graphApiActionConfig = apiActions[graphAction.type];
if (!graphApiActionConfig) {
throw new Api.ApiError("no handler supplied", 500);
}
if (!graphApiActionConfig.graphAction) {
throw new Api.ApiError(
"Bulk graph action can only be composed of graph actions",
500
);
}
if (graphApiActionConfig.reorderBlobsIfNeeded) {
reorderBlobsIfNeeded = true;
}
log("Processing bulk action sub-action: ", {
transactionId,
graphAction: graphAction.type,
});
const res = await getActionRes(
graphApiActionConfig,
{
...graphAction,
meta: {
...graphAction.meta,
client: action.meta.client,
auth: action.meta.auth,
},
} as Api.Action.GraphAction,
requestParams,
transactionConn,
requestStart,
actionStart,
transactionId,
requestBytes,
auth,
orgGraph,
true
);
actionResults.push(res);
// return res;
}
// ));
for (let res of actionResults) {
if (
res.response.type != "graphDiffs" ||
(response && response.type != "graphDiffs") ||
!res.updatedOrgGraph ||
!res.updatedUserGraph
) {
throw new Api.ApiError(
"Bulk graph action can only be composed of graph actions with 'graphDiffs' responses",
400
);
}
const diffs = res.response.diffs;
({ updatedOrgGraph } = res);
response = response
? (response = {
...response,
diffs: [...response.diffs, ...diffs],
})
: res.response;
if (res.transactionItems) {
transactionStatements.push(
...objectTransactionStatements(res.transactionItems, actionStart)
);
}
if (res.logTransactionStatement) {
transactionStatements.push(res.logTransactionStatement);
}
if (res.backgroundLogStatement) {
backgroundStatements.push(res.backgroundLogStatement);
}
postUpdateActions = postUpdateActions
? postUpdateActions.concat(res.postUpdateActions ?? [])
: res.postUpdateActions;
clearUserSockets = clearUserSockets.concat(res.clearUserSockets ?? []);
clearEnvkeySockets = clearEnvkeySockets.concat(
res.clearEnvkeySockets ?? []
);
updatedGeneratedEnvkeyIds = R.uniq(
updatedGeneratedEnvkeyIds.concat(res.updatedGeneratedEnvkeyIds ?? [])
);
}
} else {
if (apiActionConfig.graphAction && auth) {
// force latest graph for all graph actions (unless they explicitly opt-out)
if (
!apiActionConfig.skipGraphUpdatedAtCheck &&
(action.meta as { graphUpdatedAt: number }).graphUpdatedAt !==
auth.org.graphUpdatedAt
) {
throw new Api.ApiError("client graph outdated", 400);
}
if (apiActionConfig.graphScopes) {
for (let scopeFn of apiActionConfig.graphScopes) {
orgGraph = await getOrgGraph(
auth.org.id,
{
transactionConn,
},
scopeFn(auth, action)(orgGraph)
);
}
} else {
orgGraph = await getOrgGraph(auth.org.id, {
transactionConn,
});
}
logWithElapsed(transactionId + " - got org graph", requestStart);
if (apiActionConfig.reorderBlobsIfNeeded) {
reorderBlobsIfNeeded = true;
}
}
const res = await getActionRes(
apiActionConfig,
action,
requestParams,
transactionConn,
requestStart,
actionStart,
transactionId,
requestBytes,
auth,
orgGraph
);
response = res.response;
responseBytes = res.responseBytes;
postUpdateActions = res.postUpdateActions;
clearUserSockets = res.clearUserSockets ?? [];
clearEnvkeySockets = res.clearEnvkeySockets ?? [];
updatedOrgGraph = res.updatedOrgGraph;
handlerContext = res.handlerContext;
updatedGeneratedEnvkeyIds = res.updatedGeneratedEnvkeyIds ?? [];
if (res.transactionItems) {
transactionStatements.push(
...objectTransactionStatements(res.transactionItems, actionStart)
);
}
if (res.logTransactionStatement) {
transactionStatements.push(res.logTransactionStatement);
}
if (res.backgroundLogStatement) {
backgroundStatements.push(res.backgroundLogStatement);
}
}
logWithElapsed(transactionId + " - got action result", requestStart);
if (!responseBytes) {
responseBytes = Buffer.byteLength(JSON.stringify(response), "utf8");
}
if (!response) {
throw new Api.ApiError("Response undefined", 500);
}
if (reorderBlobsIfNeeded && auth && orgGraph && updatedOrgGraph) {
const reorderTransactionItems = getReorderEncryptedKeysTransactionItems(
orgGraph,
updatedOrgGraph
);
if (!objectTransactionItemsEmpty(reorderTransactionItems)) {
transactionStatements.push(
...objectTransactionStatements(reorderTransactionItems, actionStart)
);
}
}
// if this is a graph update, do a locking read on the org object
// and ensure we have the latest graph before proceeding, otherwise
// throw an error to abort transaction so client can retry
if (
auth &&
(action.type == Api.ActionType.BULK_GRAPH_ACTION ||
action.meta.loggableType == "orgAction")
) {
const lockedOrg = await getOrg(auth.org.id, transactionConn, true);
if (!lockedOrg) {
throw new Api.ApiError("couldn't obtain org write lock", 500);
}
if (action.type == Api.ActionType.BULK_GRAPH_ACTION) {
for (let graphAction of action.payload) {
const graphApiActionConfig = apiActions[graphAction.type];
if (
graphApiActionConfig.graphAction &&
!graphApiActionConfig.skipGraphUpdatedAtCheck &&
(
(graphAction as Api.Action.RequestAction).meta as {
graphUpdatedAt: number;
}
).graphUpdatedAt !== lockedOrg.graphUpdatedAt
) {
throw new Api.ApiError("client graph outdated", 400);
}
}
} else if (
apiActionConfig.graphAction &&
!apiActionConfig.skipGraphUpdatedAtCheck &&
(action.meta as { graphUpdatedAt: number }).graphUpdatedAt !==
lockedOrg.graphUpdatedAt
) {
throw new Api.ApiError("client graph outdated", 400);
}
}
try {
await executeTransactionStatements(
transactionStatements,
transactionConn
);
} catch (err) {
log("transaction error:", err);
throw new Api.ApiError("Transaction failed", 500);
}
logWithElapsed(transactionId + " - executed transaction", requestStart);
if (postUpdateActions) {
await Promise.all(postUpdateActions.map((fn) => fn()));
}
resolveUserSocketUpdates(apiActionConfig, action, auth, clearUserSockets);
resolveEnvkeySocketUpdates(
auth,
updatedGeneratedEnvkeyIds,
clearEnvkeySockets
);
logWithElapsed(transactionId + " - resolved socket updates", requestStart);
// async s3 replication
if (replicationFn && auth && updatedOrgGraph) {
// don't await result, log/alert on error
logWithElapsed(
transactionId + " - replicating if needed asynchronously",
requestStart
);
(async () => {
// give the database a beat to release the transaction
// so that replication fetches committed results
await wait(1000);
replicationFn(
updatedOrgGraph[auth.org.id] as Api.Db.Org,
updatedOrgGraph,
actionStart
).catch((err) => {
logStderr("Replication error", { err, orgId: auth.org.id });
});
})();
}
if (backgroundStatements.length > 0) {
logWithElapsed("execute background SQL statements", requestStart);
// don't await result, log/alert on error
getNewTransactionConn().then((backgroundConn) => {
executeTransactionStatements(backgroundStatements, backgroundConn)
.catch((err) => {
logStderr("error executing background SQL statements:", {
err,
orgId: auth?.org.id,
});
})
.finally(() => backgroundConn.release());
});
}
if (updateOrgStatsFn && response.type != "notModified") {
// update org stats in background (don't await)
logWithElapsed("update org stats", requestStart);
updateOrgStatsFn(
auth,
handlerContext,
requestBytes,
responseBytes ?? 0,
Boolean(updatedOrgGraph),
actionStart
).catch((err) => {
logStderr("Error updating org stats", { err, orgId: auth?.org.id });
});
}
let status: number;
if ("errorStatus" in response) {
status = response.errorStatus;
} else if ("status" in response) {
status = response.status;
} else {
status = 200;
}
logWithElapsed(transactionId + " - response:", requestStart, {
error: "error" in response && response.error,
errorReason: "errorReason" in response ? response.errorReason : undefined,
status,
actionType: action.type,
responseBytes,
timestamp: actionStart,
});
return response;
},
getApiActionForType = (type: Api.ActionType) => {
return apiActions[type];
};
let socketServer: Api.SocketServer | undefined;
const apiActions: {
[type: string]: ApiActionConfig;
} = {},
getActionRes = async (
apiActionConfig: ApiActionConfig,
action: Api.Action.RequestAction,
requestParams: Api.RequestParams,
transactionConn: PoolConnection,
requestStart: number,
actionStart: number,
transactionId: string,
requestBytes: number,
auth?: Auth.AuthContext,
orgGraph?: Api.Graph.OrgGraph,
isBulkAction?: true
) => {
if (!socketServer) {
throw new Api.ApiError("Socket server not registered", 500);
}
if (
throttleRequestFn &&
auth &&
auth.orgStats &&
// give enough access in throttling scenarios for the license to be updated
!(
action.type == Api.ActionType.UPDATE_LICENSE ||
action.type == Api.ActionType.FETCH_ORG_STATS ||
(action.type == Api.ActionType.GET_SESSION &&
auth.type == "tokenAuthContext" &&
auth.orgPermissions.has("org_manage_billing"))
)
) {
await throttleRequestFn(
auth.orgStats,
auth.license,
requestBytes,
Boolean("blobs" in action.payload && action.payload.blobs)
);
}
// validate payload with zod schema
let payloadSchema = Api.Net.getSchema(action.type);
if (!payloadSchema) {
throw new Api.ApiError("No schema defined for action", 500);
}
try {
// keys / blobs can be large and slow to validate, and they are fully authorized elsewhere -- we will ignore errors for these props
payloadSchema.parse(R.omit(["keys", "blobs"], action.payload));
} catch (err) {
let ignoredPropsOnly = true;
if ("errors" in err && err.errors?.length) {
for (let { path } of err.errors) {
if (!R.equals(path, ["keys"]) && !R.equals(path, ["blobs"])) {
ignoredPropsOnly = false;
}
}
}
if (!ignoredPropsOnly) {
log("Payload failed validation", {
payloadSchema,
payload: action.payload,
err,
});
let message = "Invalid payload";
if ("errors" in err && err.errors?.length) {
try {
message +=
": " +
err.errors
.map(
(e: any) =>
e.unionErrors.map((u: any) => u.message ?? u) ??
e.message ??
e
)
?.filter(Boolean)
?.join(". ");
} catch (parseErr) {
log("Failed simplifying validation errors", {
payloadSchema,
payload: action.payload,
err,
});
}
} else {
message += ": " + err.message;
}
throw new Api.ApiError(message, 422);
}
}
logWithElapsed(transactionId + " - validated schema", requestStart);
const { ip } = requestParams;
let updatedOrgGraph: Api.Graph.OrgGraph,
userGraph: Client.Graph.UserGraph = {} as Client.Graph.UserGraph,
updatedUserGraph: Client.Graph.UserGraph = {} as Client.Graph.UserGraph;
if (!auth) {
if (apiActionConfig.authenticated) {
throw new Api.ApiError("Auth required", 400);
}
const {
response,
transactionItems,
postUpdateActions,
handlerContext,
logTargetIds,
backgroundLogTargetIds,
responseBytes: handlerResponseBytes,
} = await apiActionConfig.handler(
action,
actionStart,
requestParams,
transactionConn
);
const targetIds = Array.isArray(logTargetIds)
? logTargetIds
: logTargetIds(response);
let backgroundTargetIds: string[] | undefined;
if (backgroundLogTargetIds) {
backgroundTargetIds = Array.isArray(backgroundLogTargetIds)
? backgroundLogTargetIds
: backgroundLogTargetIds?.(response);
}
const responseBytes =
handlerResponseBytes ??
Buffer.byteLength(JSON.stringify(response), "utf8");
let logTransactionStatement: Api.Db.SqlStatement | undefined;
let backgroundLogStatement: Api.Db.SqlStatement | undefined;
try {
({ logTransactionStatement, backgroundLogStatement } =
getLogTransactionStatement({
action,
auth,
response,
ip,
transactionId,
responseBytes,
handlerContext,
targetIds,
backgroundTargetIds,
now: actionStart,
}));
} catch (err) {
const { message, code } = err as Api.ApiError;
throw new Api.ApiError(message, code);
}
return {
response,
responseBytes,
logTransactionStatement,
backgroundLogStatement,
transactionItems,
postUpdateActions,
handlerContext,
};
}
if (!apiActionConfig.authenticated) {
throw new Api.ApiError("Auth required", 400);
}
let authorized: boolean;
let userGraphDeviceId: string | undefined;
switch (auth.type) {
case "tokenAuthContext":
userGraphDeviceId = auth.orgUserDevice.id;
break;
case "inviteAuthContext":
userGraphDeviceId = auth.invite.id;
break;
case "deviceGrantAuthContext":
userGraphDeviceId = auth.deviceGrant.id;
break;
case "recoveryKeyAuthContext":
userGraphDeviceId = auth.recoveryKey.id;
break;
}
if (apiActionConfig.graphAction) {
if (!transactionConn) {
throw new Api.ApiError(
"Transaction connection required for graph actions",
500
);
}
if (!orgGraph) {
throw new Api.ApiError("org graph required for graph action", 500);
}
if ("user" in auth) {
userGraph = getApiUserGraph(
orgGraph,
auth.org.id,
auth.user.id,
userGraphDeviceId,
actionStart
);
logWithElapsed(transactionId + " - got user graph", requestStart);
}
// if there are any pending root pubkey replacements queued in this user's graph, these must be processed before user can make graph updates (enforced client-side too)
// * only applies to actions with token or cli auth, not actions with invite, device grant, or recovery key auth
if (
auth.type == "tokenAuthContext" ||
auth.type == "cliUserAuthContext"
) {
const { rootPubkeyReplacements } = graphTypes(userGraph);
if (rootPubkeyReplacements.length > 0) {
throw new Api.ApiError(
"root pubkey replacements are pending in client graph--these must be processed prior to graph updates",
400
);
}
}
if (apiActionConfig.graphAuthorizer) {
authorized = await apiActionConfig.graphAuthorizer(
action,
orgGraph,
userGraph,
auth,
actionStart,
requestParams,
transactionConn
);
if (!authorized) {
log("graphAuthorizer - false", {
action: action.type,
transactionId,
});
}
} else {
authorized = true;
}
logWithElapsed(transactionId + " - ran graph authorizer", requestStart);
} else {
if (apiActionConfig.authenticated && apiActionConfig.authorizer) {
authorized = await apiActionConfig.authorizer(
action,
auth,
transactionConn
);
if (!authorized) {
log("handler unauthorized", { action: action.type, transactionId });
}
} else {
authorized = true;
}
}
if (!authorized) {
throw new Api.ApiError("Unauthorized", 403);
}
if (!apiActionConfig.graphAction) {
const {
response,
transactionItems,
handlerContext,
postUpdateActions,
logTargetIds,
backgroundLogTargetIds,
responseBytes: handlerResponseBytes,
} = await apiActionConfig.handler(
action,
auth,
actionStart,
requestParams,
transactionConn
),
responseBytes =
handlerResponseBytes ??
Buffer.byteLength(JSON.stringify(response), "utf8");
const targetIds = Array.isArray(logTargetIds)
? logTargetIds
: logTargetIds(response);
let backgroundTargetIds: string[] | undefined;
if (backgroundLogTargetIds) {
backgroundTargetIds = Array.isArray(backgroundLogTargetIds)
? backgroundLogTargetIds
: backgroundLogTargetIds?.(response);
}
let logTransactionStatement: Api.Db.SqlStatement | undefined;
let backgroundLogStatement: Api.Db.SqlStatement | undefined;
try {
({ logTransactionStatement, backgroundLogStatement } =
getLogTransactionStatement({
action,
auth,
updatedUserGraph: (
response as {
graph?: Client.Graph.UserGraph;
}
).graph,
response,
transactionId,
ip,
targetIds,
backgroundTargetIds,
responseBytes,
handlerContext,
now: actionStart,
}));
} catch (err) {
const { message, code } = err as Api.ApiError;
throw new Api.ApiError(message, code);
}
return {
response,
responseBytes,
logTransactionStatement,
backgroundLogStatement,
transactionItems,
postUpdateActions,
handlerContext,
};
}
if (!(orgGraph && userGraph)) {
throw new Api.ApiError("orgGraph and userGraph not loaded", 500);
}
let handlerContext: Api.HandlerContext | undefined,
handlerTransactionItems: Api.Db.ObjectTransactionItems | undefined,
handlerPostUpdateActions: Api.HandlerPostUpdateActions | undefined,
handlerEnvs: Api.HandlerEnvsResponse | undefined,
handlerChangesets: Api.HandlerChangesetsResponse | undefined,
handlerSignedTrustedRootPubkey: Crypto.SignedData | undefined,
handlerEncryptedKeysScope: Rbac.OrgAccessScope | undefined,
handlerLogTargetIds: Api.GraphHandlerResult["logTargetIds"] | undefined,
handlerBackgroundLogTargetIds:
| Api.GraphHandlerResult["backgroundLogTargetIds"]
| undefined,
handlerUserClearSockets: Api.ClearUserSocketParams[] | undefined,
handlerEnvkeyClearSockets: Api.ClearEnvkeySocketParams[] | undefined,
handlerUpdatedGeneratedEnvkeyIds: string[] | undefined,
handlerResponseBytes: number | undefined;
if (apiActionConfig.graphHandler) {
if (!transactionConn) {
throw new Api.ApiError(
"Transaction connection required for graph actions",
500
);
}
const handlerRes = await apiActionConfig.graphHandler(
action,
orgGraph,
auth,
actionStart,
requestParams,
transactionConn,
socketServer
);
logWithElapsed(transactionId + " - ran graph handler", requestStart);
if (handlerRes.type == "response") {
const responseBytes =
handlerRes.responseBytes ??
Buffer.byteLength(JSON.stringify(handlerRes.response), "utf8");
const targetIds = Array.isArray(handlerRes.logTargetIds)
? handlerRes.logTargetIds
: handlerRes.logTargetIds(handlerRes.response);
let backgroundTargetIds: string[] | undefined;
if (handlerBackgroundLogTargetIds) {
handlerBackgroundLogTargetIds = Array.isArray(
handlerRes.backgroundLogTargetIds
)
? handlerRes.backgroundLogTargetIds
: handlerRes.backgroundLogTargetIds?.(handlerRes.response);
}
let logTransactionStatement: Api.Db.SqlStatement | undefined;
let backgroundLogStatement: Api.Db.SqlStatement | undefined;
try {
({ logTransactionStatement, backgroundLogStatement } =
getLogTransactionStatement({
action,
auth,
previousOrgGraph: orgGraph,
updatedOrgGraph: orgGraph,
updatedUserGraph: userGraph!,
response: handlerRes.response,
handlerContext: handlerRes.handlerContext,
ip,
transactionId,
targetIds,
backgroundTargetIds,
responseBytes,
now: actionStart,
}));
} catch (err) {
const { message, code } = err as Api.ApiError;
throw new Api.ApiError(message, code);
}
return {
response: handlerRes.response,
responseBytes,
logTransactionStatement,
backgroundLogStatement,
transactionItems: handlerRes.transactionItems,
postUpdateActions: handlerRes.postUpdateActions,
handlerContext,
};
}
handlerContext = handlerRes.handlerContext;
handlerTransactionItems = handlerRes.transactionItems;
handlerPostUpdateActions = handlerRes.postUpdateActions;
handlerEnvs = handlerRes.envs;
handlerChangesets = handlerRes.changesets;
handlerSignedTrustedRootPubkey = handlerRes.signedTrustedRoot;
handlerEncryptedKeysScope = handlerRes.encryptedKeysScope;
handlerLogTargetIds = handlerRes.logTargetIds;
handlerBackgroundLogTargetIds = handlerRes.backgroundLogTargetIds;
handlerUserClearSockets = handlerRes.clearUserSockets;
handlerEnvkeyClearSockets = handlerRes.clearEnvkeySockets;
handlerUpdatedGeneratedEnvkeyIds = handlerRes.updatedGeneratedEnvkeyIds;
handlerResponseBytes = handlerRes.responseBytes;
updatedOrgGraph = handlerRes.graph;
} else {
updatedOrgGraph = orgGraph;
}
let allTransactionItems: Api.Db.ObjectTransactionItems =
handlerTransactionItems ?? {};
if (!apiActionConfig.graphScopes) {
updatedOrgGraph = deleteExpiredAuthObjects(updatedOrgGraph, actionStart);
logWithElapsed(
transactionId + " - deletes expired auth objects",
requestStart
);
updatedOrgGraph = clearOrphanedRootPubkeyReplacements(
updatedOrgGraph,
actionStart
);
logWithElapsed(
transactionId + " - cleared orphaned pubkey replacements",
requestStart
);
}
if (
action.meta.loggableType == "orgAction" &&
apiActionConfig.shouldClearOrphanedLocals
) {
const clearOrphanedLocalsRes = clearOrphanedLocals(
updatedOrgGraph,
actionStart
);
updatedOrgGraph = clearOrphanedLocalsRes[0];
allTransactionItems = mergeObjectTransactionItems([
allTransactionItems,
clearOrphanedLocalsRes[1],
]);
logWithElapsed(
transactionId + " - cleared orphaned locals",
requestStart
);
}
logWithElapsed(transactionId + " - cleaned up org graph", requestStart);
if ("user" in auth) {
updatedUserGraph = getApiUserGraph(
updatedOrgGraph,
auth.org.id,
auth.user.id,
userGraphDeviceId,
actionStart
);
}
logWithElapsed(transactionId + " - got updated user graph", requestStart);
if (
auth.type != "provisioningBearerAuthContext" &&
apiActionConfig.graphAuthorizer &&
(("keys" in action.payload && action.payload.keys) ||
("blobs" in action.payload && action.payload.blobs))
) {
authorized = await authorizeEnvsUpdate(
updatedUserGraph,
auth,
action as Api.Action.GraphAction
);
if (!authorized) {
log("env update unauthorized");
throw new Api.ApiError("Unauthorized", 403);
}
}
let updatedGeneratedEnvkeyIds: string[] =
handlerUpdatedGeneratedEnvkeyIds ?? [];
let toDeleteEncryptedKeys: Blob.KeySet | undefined;
let beforeUpdateCurrentEncryptedKeys: Blob.KeySet | undefined;
let updatedCurrentEncryptedKeys: Blob.KeySet | undefined;
if (
handlerEncryptedKeysScope &&
orgGraph != updatedOrgGraph &&
action.type != Api.ActionType.FETCH_ENVS
) {
[beforeUpdateCurrentEncryptedKeys, updatedCurrentEncryptedKeys] =
await Promise.all([
asyncify("getCurrentEncryptedKeys", getCurrentEncryptedKeys)(
orgGraph,
handlerEncryptedKeysScope,
actionStart,
true
),
asyncify("getCurrentEncryptedKeys", getCurrentEncryptedKeys)(
updatedOrgGraph,
handlerEncryptedKeysScope,
actionStart
),
]);
logWithElapsed(
transactionId + " - got current encrypted keys",
requestStart
);
toDeleteEncryptedKeys = keySetDifference(
beforeUpdateCurrentEncryptedKeys,
updatedCurrentEncryptedKeys
);
logWithElapsed(
transactionId + " - resolved any encrypted keys that need deletion",
requestStart
);
if (!handlerUpdatedGeneratedEnvkeyIds) {
// add updated generatedEnvkeyIds from blockKeyableParents
// either setting new key or deleting
const ids = new Set<string>();
if (
"keys" in action.payload &&
action.payload.keys &&
action.payload.keys.blockKeyableParents
) {
for (let blockId in action.payload.keys.blockKeyableParents) {
for (let keyableParentId in action.payload.keys.blockKeyableParents[
blockId
]) {
for (let generatedEnvkeyId in action.payload.keys
.blockKeyableParents[blockId][keyableParentId]) {
ids.add(generatedEnvkeyId);
}
}
}
}
if (toDeleteEncryptedKeys.blockKeyableParents) {
for (let blockId in toDeleteEncryptedKeys.blockKeyableParents) {
for (let keyableParentId in toDeleteEncryptedKeys
.blockKeyableParents[blockId]) {
for (let generatedEnvkeyId in toDeleteEncryptedKeys
.blockKeyableParents[blockId][keyableParentId]) {
ids.add(generatedEnvkeyId);
}
}
}
}
updatedGeneratedEnvkeyIds = Array.from(ids);
}
}
if (updatedGeneratedEnvkeyIds.length > 0) {
updatedOrgGraph = produce(updatedOrgGraph, (draft) => {
for (let generatedEnvkeyId of updatedGeneratedEnvkeyIds!) {
(draft[generatedEnvkeyId] as Api.Db.GeneratedEnvkey).blobsUpdatedAt =
actionStart;
}
});
logWithElapsed(
transactionId + " - set blobsUpdatedAt on updated generatedEnvkeys",
requestStart
);
}
let graphTransactionItems =
action.type == Api.ActionType.FETCH_ENVS || orgGraph == updatedOrgGraph
? {}
: getGraphTransactionItems(orgGraph, updatedOrgGraph, actionStart);
logWithElapsed(
transactionId + " - got graph transaction items",
requestStart
);
const hasGraphTransactionItems = !objectTransactionItemsEmpty(
graphTransactionItems
);
logWithElapsed(
transactionId + " - checked transactions empty",
requestStart
);
if (hasGraphTransactionItems) {
if (toDeleteEncryptedKeys && !keySetEmpty(toDeleteEncryptedKeys)) {
const queueBlobsForReencryptionRes =
queueBlobsForReencryptionFromToDeleteEncryptedKeys(
auth,
toDeleteEncryptedKeys,
updatedOrgGraph,
actionStart
);
if (queueBlobsForReencryptionRes) {
updatedOrgGraph = queueBlobsForReencryptionRes;
graphTransactionItems = getGraphTransactionItems(
orgGraph,
updatedOrgGraph,
actionStart
);
}
const deleteEncryptedKeysTransactionItems =
await getDeleteEncryptedKeysTransactionItems(
auth,
orgGraph,
toDeleteEncryptedKeys
);
allTransactionItems = mergeObjectTransactionItems([
allTransactionItems,
deleteEncryptedKeysTransactionItems,
]);
}
if (
env.NODE_ENV == "development" &&
updatedCurrentEncryptedKeys &&
beforeUpdateCurrentEncryptedKeys
) {
// too slow for prod, but good for catching issues with mismatched permissions/envs in dev/testing
const toRequireEncryptedKeys = keySetDifference(
updatedCurrentEncryptedKeys,
beforeUpdateCurrentEncryptedKeys
);
logWithElapsed(
transactionId + " - toRequireEncryptedKeys",
requestStart
);
if (!keySetEmpty(toRequireEncryptedKeys)) {
try {
requireEncryptedKeys(
(action.payload as Api.Net.EnvParams).keys ?? {},
toRequireEncryptedKeys,
handlerContext,
orgGraph
);
} catch (err) {
const { message, code } = err as Api.ApiError;
throw new Api.ApiError(message, code);
}
}
}
allTransactionItems = mergeObjectTransactionItems([
allTransactionItems,
graphTransactionItems,
]);
logWithElapsed(
transactionId + " - merged transaction items",
requestStart
);
const toUpdateOrg = updatedOrgGraph[auth.org.id] as Api.Db.Org;
const updatedOrg = {
...toUpdateOrg,
deviceLikeCount: apiActionConfig.graphScopes
? toUpdateOrg.deviceLikeCount
: getNumActiveDeviceLike(updatedOrgGraph, actionStart),
activeUserOrInviteCount: apiActionConfig.graphScopes
? toUpdateOrg.activeUserOrInviteCount
: getNumActiveOrInvitedUsers(updatedOrgGraph, actionStart),
graphUpdatedAt: actionStart,
rbacUpdatedAt: apiActionConfig.rbacUpdate
? actionStart
: auth.org.rbacUpdatedAt,
updatedAt: actionStart,
} as Api.Db.Org;
updatedOrgGraph = { ...updatedOrgGraph, [auth.org.id]: updatedOrg };
logWithElapsed(transactionId + " - set updated org graph", requestStart);
allTransactionItems = mergeObjectTransactionItems([
allTransactionItems,
{
updates: [[pick(["pkey", "skey"], updatedOrg), updatedOrg]],
},
]);
if ("user" in auth) {
updatedUserGraph = getApiUserGraph(
updatedOrgGraph,
auth.org.id,
auth.user.id,
userGraphDeviceId,
actionStart
);
}
logWithElapsed(transactionId + " - got updated user graph", requestStart);
if (
auth.type != "provisioningBearerAuthContext" &&
(("keys" in action.payload && action.payload.keys) ||
("blobs" in action.payload && action.payload.blobs))
) {
const envParamsTransactionItems = getEnvParamsTransactionItems(
auth,
orgGraph,
updatedOrgGraph,
action,
actionStart,
handlerContext
);
allTransactionItems = mergeObjectTransactionItems([
allTransactionItems,
envParamsTransactionItems,
]);
}
}
let responseType: Api.GraphResponseType =
apiActionConfig.graphResponse ?? "diffs",
deviceId: string;
if (auth.type == "inviteAuthContext") {
deviceId = auth.invite.id;
} else if (auth.type == "deviceGrantAuthContext") {
deviceId = auth.deviceGrant.id;
} else if (auth.type == "recoveryKeyAuthContext") {
deviceId = auth.recoveryKey.id;
} else if (auth.type == "cliUserAuthContext") {
deviceId = "cli";
} else if (auth.type == "tokenAuthContext") {
deviceId = auth.orgUserDevice.id;
}
let response: Api.Net.ApiResult | undefined;
const graphUpdatedAt = hasGraphTransactionItems
? actionStart
: auth.org.graphUpdatedAt;
switch (responseType) {
case "diffs":
response = {
type: "graphDiffs",
diffs: hasGraphTransactionItems
? createPatch(userGraph, updatedUserGraph)
: [],
graphUpdatedAt,
timestamp: actionStart,
};
break;
case "graph":
response = {
type: "graph",
graph: updatedUserGraph,
graphUpdatedAt,
signedTrustedRoot: handlerSignedTrustedRootPubkey,
timestamp: actionStart,
};
break;
case "ok":
response = {
type: "success",
};
break;
case "scimUserCandidate":
const { status, scimUserResponse } = handlerContext as Extract<
Api.HandlerContext,
{ type: Api.ActionType.GET_SCIM_USER }
>;
response = {
status,
...scimUserResponse,
};
break;
case "loadedInvite":
case "loadedDeviceGrant":
case "loadedRecoveryKey":
case "envsAndOrChangesets":
let envEncryptedKeys: Blob.UserEncryptedKeysByEnvironmentIdOrComposite =
{},
envBlobs: Blob.UserEncryptedBlobsByComposite = {},
changesetEncryptedKeys: Blob.UserEncryptedChangesetKeysByEnvironmentId =
{},
changesetBlobs: Blob.UserEncryptedBlobsByEnvironmentId = {};
if (auth.type != "provisioningBearerAuthContext") {
if (handlerEnvs) {
if (handlerEnvs.all) {
[envEncryptedKeys, changesetEncryptedKeys, envBlobs] =
await Promise.all([
getEnvEncryptedKeys(
{
orgId: auth.org.id,
userId: auth.user.id,
deviceId: deviceId!,
blobType: "env",
},
{ transactionConn }
),
getChangesetEncryptedKeys(
{
orgId: auth.org.id,
userId: auth.user.id,
deviceId: deviceId!,
},
{ transactionConn }
),
getEnvEncryptedBlobs(
{
orgId: auth.org.id,
blobType: "env",
},
{ transactionConn }
),
]);
} else if (handlerEnvs.scopes) {
[envEncryptedKeys, changesetEncryptedKeys, envBlobs] =
await Promise.all([
Promise.all(
handlerEnvs.scopes.map((scope) =>
getEnvEncryptedKeys(
{
orgId: auth.org.id,
userId: auth.user.id,
deviceId: deviceId!,
...scope,
},
{ transactionConn }
)
)
).then((encryptedKeys) =>
encryptedKeys.reduce(R.mergeDeepRight, {})
),
Promise.all(
handlerEnvs.scopes.map((scope) =>
getChangesetEncryptedKeys(
{
orgId: auth.org.id,
userId: auth.user.id,
deviceId: deviceId!,
...scope,
},
{ transactionConn }
)
)
).then((encryptedKeys) => {
return encryptedKeys.reduce(R.mergeDeepRight, {});
}),
Promise.all(
handlerEnvs.scopes.map((scope) =>
getEnvEncryptedBlobs(
{
orgId: auth.org.id,
...scope,
},
{ transactionConn }
)
)
).then((blobs) => blobs.reduce(R.mergeDeepRight, {})),
]);
}
envBlobs = pick(Object.keys(envEncryptedKeys), envBlobs);
}
if (handlerChangesets) {
if (handlerChangesets.all) {
[changesetEncryptedKeys, changesetBlobs] = await Promise.all([
handlerEnvs && handlerEnvs.all
? changesetEncryptedKeys
: getChangesetEncryptedKeys(
{
orgId: auth.org.id,
userId: auth.user.id,
deviceId: deviceId!,
},
{ transactionConn }
),
getChangesetEncryptedBlobs(
{
orgId: auth.org.id,
createdAfter: handlerChangesets.createdAfter,
},
{ transactionConn }
),
]);
} else if (handlerChangesets.scopes) {
[changesetEncryptedKeys, changesetBlobs] = await Promise.all([
Promise.all(
handlerChangesets.scopes.map((scope) =>
getChangesetEncryptedKeys(
{
orgId: auth.org.id,
userId: auth.user.id,
deviceId: deviceId!,
...scope,
},
{ transactionConn }
)
)
).then((encryptedKeys) => {
return encryptedKeys.reduce(
R.mergeDeepRight,
changesetEncryptedKeys ?? {}
);
}),
Promise.all(
handlerChangesets.scopes.map((scope) =>
getChangesetEncryptedBlobs(
{
orgId: auth.org.id,
...scope,
},
{ transactionConn }
)
)
).then((blobs) => {
return blobs.reduce(R.mergeDeepRight, {});
}),
]);
}
}
}
if (responseType == "envsAndOrChangesets") {
response = {
type: "envsAndOrChangesets",
envs: { keys: envEncryptedKeys, blobs: envBlobs },
changesets: { keys: changesetEncryptedKeys, blobs: changesetBlobs },
timestamp: actionStart,
};
} else {
const baseGraphWithEnvsResponse = {
graph: updatedUserGraph,
graphUpdatedAt,
envs: { keys: envEncryptedKeys, blobs: envBlobs },
changesets: { keys: changesetEncryptedKeys, blobs: changesetBlobs },
signedTrustedRoot: handlerSignedTrustedRootPubkey,
timestamp: actionStart,
};
if (responseType == "loadedInvite") {
if (auth.type != "inviteAuthContext") {
throw new Api.ApiError("Missing invite authentication", 400);
}
response = {
...baseGraphWithEnvsResponse,
type: "loadedInvite",
orgId: auth.org.id,
invite: pick(
[
"id",
"encryptedPrivkey",
"pubkey",
"invitedByDeviceId",
"invitedByUserId",
"inviteeId",
"deviceId",
],
auth.invite
),
};
} else if (responseType == "loadedDeviceGrant") {
if (auth.type != "deviceGrantAuthContext") {
throw new Api.ApiError(
"Missing device grant authentication",
500
);
}
response = {
...baseGraphWithEnvsResponse,
type: "loadedDeviceGrant",
orgId: auth.org.id,
deviceGrant: pick(
[
"id",
"encryptedPrivkey",
"pubkey",
"grantedByDeviceId",
"grantedByUserId",
"granteeId",
"deviceId",
],
auth.deviceGrant
),
};
} else if (
responseType == "loadedRecoveryKey" &&
handlerContext &&
handlerContext.type == Api.ActionType.LOAD_RECOVERY_KEY
) {
response = {
...baseGraphWithEnvsResponse,
type: "loadedRecoveryKey",
orgId: auth.org.id,
recoveryKey: pick(
[
"pubkey",
"encryptedPrivkey",
"userId",
"deviceId",
"creatorDeviceId",
],
handlerContext.recoveryKey
),
};
}
}
break;
case "session":
switch (auth.type) {
case "tokenAuthContext":
response = {
type: "tokenSession",
token: auth.authToken.token,
provider: auth.authToken.provider,
...pick(["uid", "email", "firstName", "lastName"], auth.user),
userId: auth.user.id,
orgId: auth.org.id,
deviceId: auth.orgUserDevice.id,
graph: updatedUserGraph,
graphUpdatedAt,
signedTrustedRoot: auth.orgUserDevice.signedTrustedRoot,
timestamp: actionStart,
...(env.IS_CLOUD
? {
hostType: <const>"cloud",
}
: {
hostType: <const>"self-hosted",
deploymentTag: env.DEPLOYMENT_TAG!,
}),
};
break;
case "inviteAuthContext":
case "deviceGrantAuthContext":
case "recoveryKeyAuthContext":
if (
handlerContext &&
(handlerContext.type == Api.ActionType.ACCEPT_INVITE ||
handlerContext.type == Api.ActionType.ACCEPT_DEVICE_GRANT ||
handlerContext.type == Api.ActionType.REDEEM_RECOVERY_KEY)
) {
response = {
type: "tokenSession",
token: handlerContext.authToken.token,
provider: handlerContext.authToken.provider,
...pick(["uid", "email", "firstName", "lastName"], auth.user),
userId: auth.user.id,
orgId: auth.org.id,
deviceId: handlerContext.orgUserDevice.id,
graph: updatedUserGraph,
graphUpdatedAt,
envs: {
keys: {},
blobs: {},
},
timestamp: actionStart,
...(env.IS_CLOUD
? {
hostType: <const>"cloud",
}
: {
hostType: <const>"self-hosted",
deploymentTag: env.DEPLOYMENT_TAG!,
}),
};
}
break;
}
}
if (!response) {
throw new Api.ApiError("response is undefined", 500);
}
logWithElapsed(transactionId + " - got response", requestStart);
const responseBytes =
handlerResponseBytes ??
Buffer.byteLength(JSON.stringify(response), "utf8");
if (
throttleResponseFn &&
auth &&
auth.orgStats &&
// give enough access in throttling scenarios for the license to be updated
!(
action.type == Api.ActionType.UPDATE_LICENSE ||
action.type == Api.ActionType.FETCH_ORG_STATS ||
(action.type == Api.ActionType.GET_SESSION &&
auth.type == "tokenAuthContext" &&
auth.orgPermissions.has("org_manage_billing"))
)
) {
await throttleResponseFn(auth.orgStats, auth.license, responseBytes);
}
logWithElapsed(transactionId + " - got access updated", requestStart);
const targetIds = Array.isArray(handlerLogTargetIds)
? handlerLogTargetIds
: handlerLogTargetIds!(response);
let backgroundTargetIds: string[] | undefined;
if (handlerBackgroundLogTargetIds) {
backgroundTargetIds = Array.isArray(handlerBackgroundLogTargetIds)
? handlerBackgroundLogTargetIds
: handlerBackgroundLogTargetIds?.(response);
}
let logTransactionStatement: Api.Db.SqlStatement | undefined;
let backgroundLogStatement: Api.Db.SqlStatement | undefined;
try {
({ logTransactionStatement, backgroundLogStatement } =
getLogTransactionStatement({
action,
auth,
previousOrgGraph: orgGraph,
updatedOrgGraph,
updatedUserGraph,
response: response,
handlerContext,
transactionId,
targetIds,
backgroundTargetIds,
ip,
responseBytes,
now: actionStart,
}));
} catch (err) {
const { message, code } = err as Api.ApiError;
throw new Api.ApiError(message, code);
}
logWithElapsed(
transactionId + " - got log transaction items",
requestStart
);
return {
response,
responseBytes,
logTransactionStatement,
backgroundLogStatement,
transactionItems: allTransactionItems,
postUpdateActions: handlerPostUpdateActions,
clearUserSockets: handlerUserClearSockets,
clearEnvkeySockets: handlerEnvkeyClearSockets,
updatedGeneratedEnvkeyIds,
updatedOrgGraph,
updatedUserGraph,
handlerContext,
};
},
resolveUserSocketUpdates = (
apiActionConfig: ApiActionConfig | undefined,
action: Api.Action.RequestAction,
auth: Auth.AuthContext | undefined,
handlerUserClearSockets: Api.ClearUserSocketParams[]
) => {
if (!auth || !socketServer) {
return;
}
let shouldSendSocketUpdate = false,
actionTypes: Api.ActionType[],
userIds: string[] | undefined,
deviceIds: string[] | undefined;
if (action.meta.loggableType == "orgAction") {
shouldSendSocketUpdate = true;
actionTypes = [action.type];
} else if (action.type == Api.ActionType.BULK_GRAPH_ACTION) {
shouldSendSocketUpdate = true;
actionTypes = action.payload.map(R.prop("type"));
} else if (
apiActionConfig &&
"broadcastOrgSocket" in apiActionConfig &&
apiActionConfig.broadcastOrgSocket
) {
if (apiActionConfig.broadcastOrgSocket === true) {
shouldSendSocketUpdate = true;
actionTypes = [action.type];
} else {
const broadcastRes = apiActionConfig.broadcastOrgSocket(action);
if (typeof broadcastRes == "object") {
actionTypes = [action.type];
shouldSendSocketUpdate = true;
if ("userIds" in broadcastRes) {
userIds = broadcastRes.userIds;
} else {
deviceIds = broadcastRes.deviceIds;
}
} else if (broadcastRes === true) {
actionTypes = [action.type];
shouldSendSocketUpdate = true;
}
}
}
let broadcastAdditionalOrgSocketIds: string[] = [];
if (action.type == Api.ActionType.BULK_GRAPH_ACTION) {
for (let subAction of action.payload) {
const subApiActionConfig = apiActions[subAction.type];
if (
"broadcastAdditionalOrgSocketIds" in subApiActionConfig &&
subApiActionConfig.broadcastAdditionalOrgSocketIds
) {
broadcastAdditionalOrgSocketIds =
broadcastAdditionalOrgSocketIds.concat(
subApiActionConfig.broadcastAdditionalOrgSocketIds
);
}
}
} else {
if (
apiActionConfig &&
"broadcastAdditionalOrgSocketIds" in apiActionConfig &&
apiActionConfig.broadcastAdditionalOrgSocketIds
) {
broadcastAdditionalOrgSocketIds =
apiActionConfig.broadcastAdditionalOrgSocketIds;
}
}
if (shouldSendSocketUpdate || handlerUserClearSockets.length > 0) {
// defer these until after response
setImmediate(() => {
if (shouldSendSocketUpdate) {
socketServer!.sendOrgUpdate(
auth.org.id,
{
actionTypes,
actorId:
auth.type == "provisioningBearerAuthContext"
? auth.provisioningProvider.id
: auth.user.id,
},
"orgUserDevice" in auth ? auth.orgUserDevice.id : undefined,
{ userIds, deviceIds }
);
if (broadcastAdditionalOrgSocketIds) {
for (let orgId of broadcastAdditionalOrgSocketIds) {
socketServer!.sendOrgUpdate(orgId, { actionTypes });
}
}
}
handlerUserClearSockets.forEach(clearUserSockets);
});
}
},
resolveEnvkeySocketUpdates = (
auth: Auth.AuthContext | undefined,
handlerUpdatedGeneratedEnvkeyIds: string[],
handlerEnvkeyClearSockets: Api.ClearEnvkeySocketParams[]
) => {
if (!auth || !socketServer) {
return;
}
if (
handlerUpdatedGeneratedEnvkeyIds.length > 0 ||
handlerEnvkeyClearSockets.length > 0
) {
setImmediate(() => {
handlerUpdatedGeneratedEnvkeyIds.forEach((generatedEnvkeyId) =>
socketServer!.sendEnvkeyUpdate(auth.org.id, generatedEnvkeyId)
);
handlerEnvkeyClearSockets.forEach(clearEnvkeySockets);
});
}
},
clearUserSockets = (params: Api.ClearUserSocketParams) => {
if ("deviceId" in params) {
socketServer!.clearDeviceSocket(
params.orgId,
params.userId,
params.deviceId,
true,
true
);
} else if ("userId" in params) {
socketServer!.clearUserSockets(params.orgId, params.userId, true, true);
} else {
socketServer!.clearOrgSockets(params.orgId, true, true);
}
},
clearEnvkeySockets = (params: Api.ClearEnvkeySocketParams) => {
if ("generatedEnvkeyId" in params) {
socketServer!.clearEnvkeySockets(
params.orgId,
params.generatedEnvkeyId,
true,
true
);
} else {
socketServer!.clearOrgEnvkeySockets(params.orgId, true, true);
}
}; | the_stack |
const missingSources: { [key: string]: number[] } = {
ada: [],
adventure: [
11686457, // Unethical Experiments Cloak
11686458, // Orobas Vectura Cloak
320310249, // Orobas Vectura Bond
320310250, // Unethical Experiments Bond
886128573, // Mindbreaker Boots
1096417434, // Shieldbreaker Robes
1286488743, // Shieldbreaker Plate
1355771621, // Shieldbreaker Vest
1701005142, // Songbreaker Gloves
1701005143, // Gearhead Gloves
2317191363, // Mindbreaker Boots
2426340788, // Orobas Vectura Mark
2426340791, // Unethical Experiments Mark
2486041712, // Gearhead Gauntlets
2486041713, // Songbreaker Gauntlets
2913284400, // Mindbreaker Boots
3706457514, // Gearhead Grips
3706457515, // Songbreaker Grips
],
banshee: [
583723938, // Fusion Rifle Loader
583723939, // Linear Fusion Rifle Targeting
583723940, // Shotgun Dexterity
583723941, // Sword Scavenger
739655784, // Auto Rifle Loader
739655787, // Shotgun Ammo Finder
739655788, // Sidearm Dexterity
],
battlegrounds: [],
blackarmory: [],
calus: [
17280095, // Shadow's Strides
30962015, // Boots of the Ace-Defiant
64543268, // Boots of the Emperor's Minister
64543269, // Boots of the Fulminator
223783885, // Insigne Shade Bond
239489770, // Bond of Sekris
253344425, // Mask of Feltroc
256904954, // Shadow's Grips
288406317, // Greaves of Rull
309687341, // Shadow's Greaves
311429765, // Mark of the Emperor's Champion
325125949, // Shadow's Helm
325434398, // Vest of the Ace-Defiant
325434399, // Vest of the Emperor's Agent
336656483, // Boots of the Emperor's Minister
340118991, // Boots of Sekris
383742277, // Cloak of Feltroc
407863747, // Vest of the Ace-Defiant
455108040, // Helm of the Emperor's Champion
455108041, // Mask of Rull
503773817, // Insigne Shade Gloves
548581042, // Insigne Shade Boots
560455272, // Penumbral Mark
574137192, // Shadow's Mark
581908796, // Bond of the Emperor's Minister
588627781, // Bond of Sekris
608074492, // Robes of the Emperor's Minister
608074493, // Robes of the Fulminator
612065993, // Penumbral Mark
618662448, // Headpiece of the Emperor's Minister
641933203, // Mask of the Emperor's Agent
666883012, // Gauntlets of Nohr
748485514, // Mask of the Fulminator
748485515, // Headpiece of the Emperor's Minister
754149842, // Wraps of the Emperor's Minister
754149843, // Wraps of the Fulminator
796914932, // Mask of Sekris
802557885, // Turris Shade Gauntlets
845536715, // Vest of Feltroc
853543290, // Greaves of Rull
853543291, // Greaves of the Emperor's Champion
855363300, // Turris Shade Helm
874272413, // Shadow's Robes
917591018, // Grips of the Ace-Defiant
917591019, // Gloves of the Emperor's Agent
974648224, // Shadow's Boots
1034660314, // Boots of Feltroc
1108389626, // Gloves of the Emperor's Agent
1156439528, // Insigne Shade Cover
1230192769, // Robes of the Emperor's Minister
1242139836, // Plate of Nohr
1256688732, // Mask of Feltroc
1296628624, // Insigne Shade Robes
1339632007, // Turris Shade Helm
1354679721, // Cloak of the Emperor's Agent
1390282760, // Chassis of Rull
1390282761, // Cuirass of the Emperor's Champion
1413589586, // Mask of Rull
1434870610, // Shadow's Helm
1457195686, // Shadow's Gloves
1481751647, // Shadow's Mind
1675393889, // Insigne Shade Cover
1756558505, // Mask of Sekris
1793869832, // Turris Shade Greaves
1862963733, // Shadow's Plate
1876645653, // Chassis of Rull
1879942843, // Gauntlets of Rull
1901223867, // Shadow's Gauntlets
1934647691, // Shadow's Mask
1937834292, // Shadow's Strides
1946621757, // Shadow's Grips
1960303677, // Grips of the Ace-Defiant
1991039861, // Mask of Nohr
1999427172, // Shadow's Mask
2013109092, // Helm of the Ace-Defiant
2023695690, // Shadow's Robes
2070062384, // Shadow's Bond
2070062385, // Bond of the Emperor's Minister
2128823667, // Turris Shade Mark
2153222031, // Shadow's Gloves
2158603584, // Gauntlets of Rull
2158603585, // Gauntlets of the Emperor's Champion
2183861870, // Gauntlets of the Emperor's Champion
2193494688, // Boots of the Fulminator
2194479195, // Penumbral Bond
2232730708, // Vest of the Emperor's Agent
2329031091, // Robes of Sekris
2339720736, // Grips of Feltroc
2369496221, // Plate of Nohr
2513313400, // Insigne Shade Gloves
2537874394, // Boots of Sekris
2552158692, // Equitis Shade Rig
2597529070, // Greaves of Nohr
2620001759, // Insigne Shade Robes
2653039573, // Grips of Feltroc
2676042150, // Wraps of the Fulminator
2700598111, // Mask of the Fulminator
2710517999, // Equitis Shade Grips
2722103686, // Equitis Shade Boots
2758465168, // Greaves of the Emperor's Champion
2765688378, // Penumbral Cloak
2769298993, // Shadow's Boots
2904930850, // Turris Shade Plate
2913992255, // Helm of the Emperor's Champion
2933666377, // Equitis Shade Rig
2976612200, // Vest of Feltroc
2994007601, // Mark of Nohr
3066613133, // Equitis Shade Cowl
3082625196, // Shadow's Gauntlets
3092380260, // Mark of the Emperor's Champion
3092380261, // Shadow's Mark
3099636805, // Greaves of Nohr
3108321700, // Penumbral Bond
3168183519, // Turris Shade Greaves
3181497704, // Robes of Sekris
3285121297, // Equitis Shade Boots
3292127944, // Cuirass of the Emperor's Champion
3349283422, // Shadow's Mind
3359121706, // Mask of Nohr
3364682867, // Gauntlets of Nohr
3395856235, // Insigne Shade Boots
3416932282, // Turris Shade Mark
3440648382, // Equitis Shade Cowl
3483984579, // Shadow's Vest
3497220322, // Cloak of Feltroc
3517729518, // Shadow's Vest
3518193943, // Penumbral Cloak
3530284425, // Wraps of the Emperor's Minister
3581198350, // Turris Shade Gauntlets
3592548938, // Robes of the Fulminator
3711700026, // Mask of the Emperor's Agent
3711700027, // Helm of the Ace-Defiant
3719175804, // Equitis Shade Grips
3720446265, // Equitis Shade Cloak
3759659288, // Shadow's Plate
3763332443, // Shadow's Bond
3831484112, // Mark of Nohr
3842934816, // Wraps of Sekris
3853397100, // Boots of the Emperor's Agent
3867160430, // Insigne Shade Bond
3950028838, // Cloak of the Emperor's Agent
3950028839, // Shadow's Cloak
3964287245, // Wraps of Sekris
3984534842, // Shadow's Cloak
4135228483, // Turris Shade Plate
4152814806, // Shadow's Greaves
4229161783, // Boots of Feltroc
4247935492, // Equitis Shade Cloak
4251770244, // Boots of the Ace-Defiant
4251770245, // Boots of the Emperor's Agent
],
campaign: [
423789, // Mythos Hack 4.1
11686456, // Dreamer's Cloak
13719069, // Atgeir Mark
40512774, // Farseeker's Casque
59990642, // Refugee Plate
67798808, // Atonement Tau
76554114, // Cry Defiance
83898430, // Scavenger Suit
91289429, // Atonement Tau
124410141, // Shadow Specter
126602378, // Primal Siege Type 1
137713267, // Refugee Vest
174910288, // Mark of Inquisition
177215556, // Shadow Specter
182285650, // Kit Fox 1.5
201644247, // Hardcase Battleplate
202783988, // Black Shield Mark
203317967, // Fieldplate Type 10
226227391, // Fortress Field
246765359, // Mythos Hack 4.1
255520209, // Cloak of Retelling
280187206, // Hardcase Battleplate
288815409, // Renegade Greaves
320174990, // Bond of Chiron
320310251, // Dreamer's Bond
341343759, // Prophet Snow
341468857, // Bond of Insight
366418892, // The Outlander's Grip
387708030, // Prophet Snow
392489920, // Primal Siege Type 1
397654099, // Wastelander Vest
402937789, // Shadow Specter
406995961, // Stagnatious Rebuke
417821705, // Primal Siege Type 1
418611312, // Shadow Specter
420937712, // War Mantis Cloak
452060094, // Refugee Gloves
457297858, // Atgeir 2T1
459778797, // Refugee Mask
461025654, // Primal Siege Type 1
463563656, // Primal Siege Type 1
467612864, // Chiron's Cure
474150341, // RPC Valiant
482091581, // Hardcase Stompers
484126150, // Chiron's Cure
516502270, // Firebreak Field
539726822, // Refugee Boots
550258943, // Chiron's Cure
558125905, // Frumious Mask
598178607, // Mark of Confrontation
600059642, // The Outlander's Cloak
610837228, // Raven Shard
612495088, // Homeward
622291842, // Farseeker's March
625602056, // Memory of Cayde Cloak
627055961, // Fortress Field
643145875, // Legion-Bane
648022469, // Makeshift Suit
648638907, // Kit Fox 2.1
674335586, // Chiron's Cure
696808195, // Refugee Mark
703683040, // Atgeir 2T1
720723122, // At Least It's a Cape
721208609, // Farseeker's Intuition
732520437, // Baseline Mark
733635242, // RPC Valiant
735669834, // Shadow Specter
739196403, // RPC Valiant
739406993, // Atgeir 2T1
747210772, // Mythos Hack 4.1
777818225, // Fieldplate Type 10
789384557, // Atonement Tau
795389673, // The Outlander's Cloak
803939997, // War Mantis
833626649, // Chiron's Cure
844823562, // Mechanik 1.1
846463017, // Fieldplate Type 10
856745412, // War Mantis
857264972, // Scavenger Suit
863007481, // Farseeker's March
867963905, // Hardcase Brawlers
868799838, // Renegade Helm
871442456, // Refugee Boots
881194063, // Prophet Snow
897275209, // The Outlander's Heart
905249529, // Shadow Specter
911039437, // Refugee Gloves
933345182, // Fieldplate Type 10
995248967, // Makeshift Suit
1012254326, // The Outlander's Steps
1014677029, // Memory of Cayde
1022126988, // Baseline Mark
1045948748, // Mythos Hack 4.1
1048498953, // Bond of the Raven Shard
1070180272, // Hardcase Helm
1118437892, // War Mantis
1169595348, // Mythos Hack 4.1
1256569366, // Raven Shard
1279721672, // Fortress Field
1300106409, // Prophet Snow
1328755281, // Farseeker's Casque
1331205087, // Cosmic Wind III
1360445272, // Firebreak Field
1365739620, // Mythos Hack 4.1
1365979278, // Legion-Bane
1378545975, // Refugee Helm
1443091319, // Firebreak Field
1452147980, // Makeshift Suit
1455694321, // Prophet Snow
1473385934, // Mark of the Golden Citadel
1479532637, // The Outlander's Cover
1479892134, // War Mantis
1484009400, // RPC Valiant
1486292360, // Chiron's Cure
1488618333, // Chiron's Cure
1500704923, // Prophet Snow
1503713660, // Stagnatious Rebuke
1512570524, // Hardcase Stompers
1556652797, // The Outlander's Grip
1578478684, // Refugee Gloves
1581838479, // Refugee Boots
1611221278, // Prophet Snow
1616317796, // Prophet Snow
1630079134, // Bond of Forgotten Wars
1658512403, // Mythos Hack 4.1
1665016007, // Primal Siege Type 1
1691784182, // Mythos Hack 4.1
1701236611, // The Outlander's Heart
1715842350, // Generalist Shell
1736993473, // Legion-Bane
1775818231, // Legion-Bane
1784774885, // Vector Home
1824298413, // War Mantis
1848999098, // Bond of Symmetry
1862164825, // War Mantis Cloak
1872887954, // Atonement Tau
1912568536, // Primal Siege Type 1
1915498345, // Cloak of Retelling
1933944659, // Hardcase Helm
1965476837, // War Mantis
1981225397, // Shadow Specter
1988790493, // Stagnatious Rebuke
1992338980, // The Outlander's Cover
2002682954, // Vector Home
2049820819, // Vector Home
2065578431, // Shadow Specter
2148305277, // Raven Shard
2151724216, // Prophet Snow
2159062493, // Mythos Hack 4.1
2162276668, // Cry Defiance
2165661157, // Baseline Mark
2183384906, // War Mantis
2190967049, // Prophet Snow
2211544324, // The Outlander's Cloak
2230522771, // War Mantis
2253044470, // Legion-Bane
2317046938, // Shadow Specter
2329963686, // Mark of Confrontation
2339344379, // Atonement Tau
2343139242, // Bond of Refuge
2362809459, // Hardcase Stompers
2363903643, // Makeshift Suit
2426340790, // Dreamer's Mark
2441435355, // Prophet Snow
2459075622, // RPC Valiant
2466525328, // RPC Valiant
2476964124, // War Mantis
2504771764, // Refugee Helm
2541019576, // Mark of Confrontation
2567295299, // Cosmic Wind III
2574857320, // Sly Cloak
2583547635, // Cry Defiance
2626766308, // Mark of the Longest Line
2640935765, // Memory of Cayde
2644553610, // Renegade Hood
2689896341, // Mythos Hack 4.1
2739875972, // RPC Valiant
2742930797, // Fatum Praevaricator
2745108287, // War Mantis
2803009638, // Cry Defiance
2803481901, // RPC Valiant
2813695893, // Fatum Praevaricator
2814965254, // Aspirant Boots
2815743359, // Legion-Bane
2822491218, // Atonement Tau
2825160682, // RPC Valiant
2833813592, // Bond of Chiron
2854973517, // Farseeker's Casque
2871824910, // Mythos Hack 4.1
2880545163, // Black Shield Mark
2886651369, // Renegade Plate
2893448006, // Farseeker's March
2930768301, // Wastelander Wraps
2937068650, // Chiron's Cure
2943629439, // Chiron's Cure
2959986506, // Prophet Snow
2983961673, // Primal Siege Type 1
2985655620, // Refugee Vest
2994740249, // RPC Valiant
3007889693, // RPC Valiant
3035240099, // Shadow Specter
3061532064, // Farseeker's Intuition
3080409700, // Bond of Forgotten Wars
3102366928, // Atonement Tau
3121104079, // Rite of Refusal
3159474701, // Aspirant Helm
3160437036, // Shadow Specter
3163241201, // Primal Siege Type 1
3164547673, // Atonement Tau
3174394351, // The Outlander's Grip
3183585337, // Legion-Bane
3212340413, // War Mantis
3238424670, // Memory of Cayde Mark
3260546749, // Cosmic Wind
3264653916, // Mythos Hack 4.1
3302420523, // Hardcase Brawlers
3309120116, // Shadow Specter
3310450277, // Scavenger Suit
3313352164, // Cosmic Wind
3349439959, // Farseeker's Reach
3352069677, // Kit Fox 1.1
3382396922, // Primal Siege Type 1
3391214896, // Atonement Tau
3403897789, // Vector Home
3419425578, // Atonement Tau
3437155610, // War Mantis Cloak
3438103366, // Black Shield Mark
3456147612, // RPC Valiant
3465323600, // Legion-Bane
3468148580, // Aspirant Robes
3483602905, // Mark of Inquisition
3507639356, // Farseeker's Reach
3508205736, // Fatum Praevaricator
3519241547, // Fortress Field
3523134386, // Firebreak Field
3524846593, // Atonement Tau
3544711340, // Memory of Cayde Mark
3544884935, // Hood of Tallies
3554672786, // Memory of Cayde Cloak
3556023425, // Scavenger Cloak
3573886331, // Bond of Chiron
3585730968, // Shadow Specter
3639035739, // Mechanik 1.2
3643144047, // Wastelander Boots
3650925928, // Atgeir 2T1
3656549306, // Legion-Bane
3693917763, // Mark of the Fire
3725709067, // Chiron's Cure
3748997649, // The Outlander's Steps
3763392098, // Hardcase Brawlers
3790903614, // Mechanik 2.1
3812037372, // Aspirant Gloves
3867725217, // Legion-Bane
3877365781, // Kit Fox 1.4
3880804895, // The Outlander's Steps
3885104741, // Hardcase Battleplate
3904524734, // The Outlander's Cover
3922069396, // The Outlander's Heart
3958133156, // Farseeker's Intuition
3962776002, // Hardcase Helm
3967705743, // Renegade Gauntlets
3968319087, // Legion-Bane
4012302343, // Bond of Forgotten Wars
4035217656, // Atonement Tau
4052950089, // Shadow Specter
4062934448, // Primal Siege Type 1
4069941456, // Legion-Bane
4091127092, // Scavenger Suit
4100043028, // Wastelander Mask
4133705268, // Raven Shard
4135938411, // Last City Shell (Damaged)
4155348771, // War Mantis
4166795065, // Primal Siege Type 1
4174470997, // Mark of Inquisition
4177795589, // Chiron's Cure
4179002916, // Mechanik 1.1
4195519897, // Refugee Cloak
4200817316, // Mark of the Renegade
4230626646, // Shadow Specter
4248632159, // Frumious Mask
4267370571, // Chiron's Cure
4281850920, // Farseeker's Reach
4288395850, // Cloak of Retelling
],
cayde6: [],
cipher: [],
compass: [],
contact: [],
crownofsorrow: [
17280095, // Shadow's Strides
256904954, // Shadow's Grips
309687341, // Shadow's Greaves
325125949, // Shadow's Helm
560455272, // Penumbral Mark
612065993, // Penumbral Mark
874272413, // Shadow's Robes
974648224, // Shadow's Boots
1434870610, // Shadow's Helm
1457195686, // Shadow's Gloves
1481751647, // Shadow's Mind
1862963733, // Shadow's Plate
1901223867, // Shadow's Gauntlets
1934647691, // Shadow's Mask
1937834292, // Shadow's Strides
1946621757, // Shadow's Grips
1999427172, // Shadow's Mask
2023695690, // Shadow's Robes
2153222031, // Shadow's Gloves
2194479195, // Penumbral Bond
2765688378, // Penumbral Cloak
2769298993, // Shadow's Boots
3082625196, // Shadow's Gauntlets
3108321700, // Penumbral Bond
3349283422, // Shadow's Mind
3483984579, // Shadow's Vest
3517729518, // Shadow's Vest
3518193943, // Penumbral Cloak
3759659288, // Shadow's Plate
4152814806, // Shadow's Greaves
],
crucible: [
85800627, // Ankaa Seeker IV
98331691, // Binary Phoenix Mark
185853176, // Wing Discipline
252414402, // Swordflight 4.1
283188616, // Wing Contender
290136582, // Wing Theorem
327530279, // Wing Theorem
328902054, // Swordflight 4.1
356269375, // Wing Theorem
388771599, // Phoenix Strife Type 0
419812559, // Ankaa Seeker IV
438224459, // Wing Discipline
449878234, // Phoenix Strife Type 0
468899627, // Binary Phoenix Mark
530558102, // Phoenix Strife Type 0
636679949, // Ankaa Seeker IV
670877864, // Binary Phoenix Mark
727838174, // Swordflight 4.1
744199039, // Wing Contender
761953100, // Ankaa Seeker IV
820446170, // Phoenix Strife Type 0
849529384, // Phoenix Strife Type 0
874101646, // Wing Theorem
876608500, // Ankaa Seeker IV
920187221, // Wing Discipline
929917162, // Wing Theorem
997903134, // Wing Theorem
1036467370, // Wing Theorem
1062166003, // Wing Contender
1063904165, // Wing Discipline
1069887756, // Wing Contender
1071350799, // Binary Phoenix Cloak
1084033161, // Wing Contender
1127237110, // Wing Contender
1245115841, // Wing Theorem
1307478991, // Ankaa Seeker IV
1333087155, // Ankaa Seeker IV
1464207979, // Wing Discipline
1467590642, // Binary Phoenix Bond
1484937602, // Phoenix Strife Type 0
1548928853, // Phoenix Strife Type 0
1571781304, // Swordflight 4.1
1654427223, // Swordflight 4.1
1658896287, // Binary Phoenix Cloak
1673285051, // Wing Theorem
1716643851, // Wing Contender
1722623780, // Wing Discipline
1742680797, // Binary Phoenix Mark
1742940528, // Phoenix Strife Type 0
1764274932, // Ankaa Seeker IV
1801625827, // Swordflight 4.1
1830829330, // Swordflight 4.1
1838158578, // Binary Phoenix Bond
1838273186, // Wing Contender
1852468615, // Ankaa Seeker IV
1904811766, // Swordflight 4.1
1929596421, // Ankaa Seeker IV
2070517134, // Wing Contender
2124666626, // Wing Discipline
2191401041, // Phoenix Strife Type 0
2231762285, // Phoenix Strife Type 0
2291226602, // Binary Phoenix Bond
2293476915, // Swordflight 4.1
2296560252, // Swordflight 4.1
2296691422, // Swordflight 4.1
2323865727, // Wing Theorem
2331227463, // Wing Contender
2415711886, // Wing Contender
2426070307, // Binary Phoenix Cloak
2466453881, // Wing Discipline
2473130418, // Swordflight 4.1
2496309431, // Wing Discipline
2525395257, // Wing Theorem
2543903638, // Phoenix Strife Type 0
2555965565, // Wing Discipline
2670393359, // Phoenix Strife Type 0
2718495762, // Swordflight 4.1
2727890395, // Ankaa Seeker IV
2775298636, // Ankaa Seeker IV
2815422368, // Phoenix Strife Type 0
3089908066, // Wing Discipline
3098458331, // Ankaa Seeker IV
3119528729, // Wing Contender
3140634552, // Swordflight 4.1
3211001969, // Wing Contender
3223280471, // Swordflight 4.1
3298826188, // Swordflight 4.1
3313736739, // Binary Phoenix Cloak
3315265682, // Phoenix Strife Type 0
3483546829, // Wing Discipline
3522021318, // Wing Discipline
3538513130, // Binary Phoenix Bond
3724026171, // Wing Theorem
3756286064, // Phoenix Strife Type 0
3772194440, // Wing Contender
3781722107, // Phoenix Strife Type 0
3818803676, // Wing Discipline
3839561204, // Wing Theorem
4043980813, // Ankaa Seeker IV
4123918087, // Wing Contender
4134090375, // Ankaa Seeker IV
4136212668, // Wing Discipline
4144133120, // Wing Theorem
4211218181, // Ankaa Seeker IV
4264096388, // Wing Theorem
],
dcv: [
17280095, // Shadow's Strides
30962015, // Boots of the Ace-Defiant
64543268, // Boots of the Emperor's Minister
64543269, // Boots of the Fulminator
223783885, // Insigne Shade Bond
239489770, // Bond of Sekris
253344425, // Mask of Feltroc
256904954, // Shadow's Grips
288406317, // Greaves of Rull
309687341, // Shadow's Greaves
311429765, // Mark of the Emperor's Champion
325125949, // Shadow's Helm
325434398, // Vest of the Ace-Defiant
325434399, // Vest of the Emperor's Agent
336656483, // Boots of the Emperor's Minister
340118991, // Boots of Sekris
350056552, // Bladesmith's Memory Mask
383742277, // Cloak of Feltroc
388999052, // Bulletsmith's Ire Mark
407863747, // Vest of the Ace-Defiant
455108040, // Helm of the Emperor's Champion
455108041, // Mask of Rull
503773817, // Insigne Shade Gloves
548581042, // Insigne Shade Boots
560455272, // Penumbral Mark
574137192, // Shadow's Mark
581908796, // Bond of the Emperor's Minister
588627781, // Bond of Sekris
608074492, // Robes of the Emperor's Minister
608074493, // Robes of the Fulminator
612065993, // Penumbral Mark
618662448, // Headpiece of the Emperor's Minister
641933203, // Mask of the Emperor's Agent
666883012, // Gauntlets of Nohr
748485514, // Mask of the Fulminator
748485515, // Headpiece of the Emperor's Minister
754149842, // Wraps of the Emperor's Minister
754149843, // Wraps of the Fulminator
796914932, // Mask of Sekris
802557885, // Turris Shade Gauntlets
845536715, // Vest of Feltroc
853543290, // Greaves of Rull
853543291, // Greaves of the Emperor's Champion
855363300, // Turris Shade Helm
874272413, // Shadow's Robes
886128573, // Mindbreaker Boots
917591018, // Grips of the Ace-Defiant
917591019, // Gloves of the Emperor's Agent
974648224, // Shadow's Boots
1034660314, // Boots of Feltroc
1108389626, // Gloves of the Emperor's Agent
1156439528, // Insigne Shade Cover
1230192769, // Robes of the Emperor's Minister
1242139836, // Plate of Nohr
1256688732, // Mask of Feltroc
1296628624, // Insigne Shade Robes
1339632007, // Turris Shade Helm
1354679721, // Cloak of the Emperor's Agent
1390282760, // Chassis of Rull
1390282761, // Cuirass of the Emperor's Champion
1413589586, // Mask of Rull
1434870610, // Shadow's Helm
1457195686, // Shadow's Gloves
1481751647, // Shadow's Mind
1624906371, // Gunsmith's Devotion Crown
1675393889, // Insigne Shade Cover
1701005142, // Songbreaker Gloves
1756558505, // Mask of Sekris
1793869832, // Turris Shade Greaves
1862963733, // Shadow's Plate
1876645653, // Chassis of Rull
1879942843, // Gauntlets of Rull
1901223867, // Shadow's Gauntlets
1917693279, // Bladesmith's Memory Vest
1934647691, // Shadow's Mask
1937834292, // Shadow's Strides
1946621757, // Shadow's Grips
1960303677, // Grips of the Ace-Defiant
1991039861, // Mask of Nohr
1999427172, // Shadow's Mask
2013109092, // Helm of the Ace-Defiant
2023695690, // Shadow's Robes
2070062384, // Shadow's Bond
2070062385, // Bond of the Emperor's Minister
2128823667, // Turris Shade Mark
2153222031, // Shadow's Gloves
2158603584, // Gauntlets of Rull
2158603585, // Gauntlets of the Emperor's Champion
2183861870, // Gauntlets of the Emperor's Champion
2193494688, // Boots of the Fulminator
2194479195, // Penumbral Bond
2232730708, // Vest of the Emperor's Agent
2317191363, // Mindbreaker Boots
2329031091, // Robes of Sekris
2339720736, // Grips of Feltroc
2369496221, // Plate of Nohr
2486041713, // Songbreaker Gauntlets
2513313400, // Insigne Shade Gloves
2530113265, // Bulletsmith's Ire Plate
2537874394, // Boots of Sekris
2552158692, // Equitis Shade Rig
2589473259, // Bladesmith's Memory Strides
2597529070, // Greaves of Nohr
2620001759, // Insigne Shade Robes
2653039573, // Grips of Feltroc
2676042150, // Wraps of the Fulminator
2700598111, // Mask of the Fulminator
2710517999, // Equitis Shade Grips
2722103686, // Equitis Shade Boots
2758465168, // Greaves of the Emperor's Champion
2762445138, // Gunsmith's Devotion Gloves
2765688378, // Penumbral Cloak
2769298993, // Shadow's Boots
2878130185, // Bulletsmith's Ire Greaves
2904930850, // Turris Shade Plate
2913284400, // Mindbreaker Boots
2913992255, // Helm of the Emperor's Champion
2921334134, // Bulletsmith's Ire Helm
2933666377, // Equitis Shade Rig
2976612200, // Vest of Feltroc
2994007601, // Mark of Nohr
3066613133, // Equitis Shade Cowl
3082625196, // Shadow's Gauntlets
3092380260, // Mark of the Emperor's Champion
3092380261, // Shadow's Mark
3099636805, // Greaves of Nohr
3108321700, // Penumbral Bond
3163683564, // Gunsmith's Devotion Boots
3164851950, // Bladesmith's Memory Cloak
3168183519, // Turris Shade Greaves
3181497704, // Robes of Sekris
3285121297, // Equitis Shade Boots
3292127944, // Cuirass of the Emperor's Champion
3349283422, // Shadow's Mind
3359121706, // Mask of Nohr
3364682867, // Gauntlets of Nohr
3395856235, // Insigne Shade Boots
3416932282, // Turris Shade Mark
3440648382, // Equitis Shade Cowl
3483984579, // Shadow's Vest
3497220322, // Cloak of Feltroc
3517729518, // Shadow's Vest
3518193943, // Penumbral Cloak
3530284425, // Wraps of the Emperor's Minister
3567761471, // Gunsmith's Devotion Bond
3581198350, // Turris Shade Gauntlets
3592548938, // Robes of the Fulminator
3706457515, // Songbreaker Grips
3711700026, // Mask of the Emperor's Agent
3711700027, // Helm of the Ace-Defiant
3719175804, // Equitis Shade Grips
3720446265, // Equitis Shade Cloak
3759659288, // Shadow's Plate
3763332443, // Shadow's Bond
3831484112, // Mark of Nohr
3842934816, // Wraps of Sekris
3853397100, // Boots of the Emperor's Agent
3867160430, // Insigne Shade Bond
3950028838, // Cloak of the Emperor's Agent
3950028839, // Shadow's Cloak
3964287245, // Wraps of Sekris
3984534842, // Shadow's Cloak
3992358137, // Bladesmith's Memory Grips
4125324487, // Bulletsmith's Ire Gauntlets
4135228483, // Turris Shade Plate
4152814806, // Shadow's Greaves
4229161783, // Boots of Feltroc
4238134294, // Gunsmith's Devotion Robes
4247935492, // Equitis Shade Cloak
4251770244, // Boots of the Ace-Defiant
4251770245, // Boots of the Emperor's Agent
],
deepstonecrypt: [],
deluxe: [
2683682447, // Traitor's Fate
3752071760, //
3752071761, //
3752071762, //
3752071763, //
3752071765, //
3752071766, //
3752071767, //
],
do: [
66235782, // Anti-Extinction Grasps
132368575, // Anti-Extinction Mask
387100392, // Anti-Extinction Plate
1978760489, // Anti-Extinction Helm
2089197765, // Stella Incognita Mark
2760076378, // Anti-Extinction Greaves
2873960175, // Anti-Extinction Robes
3146241834, // Anti-Extinction Vest
3299588760, // Anti-Extinction Hood
3763392361, // Anti-Extinction Gloves
3783059515, // Stella Incognita Cloak
3920232320, // Anti-Extinction Legs
4055334203, // Anti-Extinction Boots
4065136800, // Anti-Extinction Gauntlets
4121118846, // Stella Incognita Bond
],
dreaming: [
99549082, // Reverie Dawn Helm
185695659, // Reverie Dawn Hood
188778964, // Reverie Dawn Boots
344548395, // Reverie Dawn Strides
934704429, // Reverie Dawn Plate
998096007, // Reverie Dawn Hood
1452333832, // Reverie Dawn Boots
1593474975, // Reverie Dawn Hauberk
1705856569, // Reverie Dawn Grasps
1903023095, // Reverie Dawn Grasps
1928769139, // Reverie Dawn Bond
1980768298, // Reverie Dawn Mark
2336820707, // Reverie Dawn Gauntlets
2467635521, // Reverie Dawn Hauberk
2503434573, // Reverie Dawn Gauntlets
2704876322, // Reverie Dawn Tabard
2761343386, // Reverie Dawn Gloves
2824453288, // Reverie Dawn Casque
2859583726, // Reverie Dawn Tabard
2889063206, // Reverie Dawn Casque
3174233615, // Reverie Dawn Greaves
3239662350, // Reverie Dawn Gloves
3250140572, // Reverie Dawn Cloak
3306564654, // Reverie Dawn Cloak
3343583008, // Reverie Dawn Mark
3602032567, // Reverie Dawn Bond
3711557785, // Reverie Dawn Strides
4070309619, // Reverie Dawn Plate
4097166900, // Reverie Dawn Helm
4257800469, // Reverie Dawn Greaves
],
drifter: [
9767416, // Ancient Apocalypse Bond
94425673, // Ancient Apocalypse Gloves
127018032, // Ancient Apocalypse Grips
191247558, // Ancient Apocalypse Plate
191535001, // Ancient Apocalypse Greaves
230878649, // Ancient Apocalypse Mask
386367515, // Ancient Apocalypse Boots
392058749, // Ancient Apocalypse Boots
485653258, // Ancient Apocalypse Strides
509238959, // Ancient Apocalypse Mark
629787707, // Ancient Apocalypse Mask
759348512, // Ancient Apocalypse Mask
787909455, // Ancient Apocalypse Robes
887818405, // Ancient Apocalypse Robes
978447246, // Ancient Apocalypse Gauntlets
1013137701, // Ancient Apocalypse Hood
1169857924, // Ancient Apocalypse Strides
1188039652, // Ancient Apocalypse Gauntlets
1193646249, // Ancient Apocalypse Boots
1236746902, // Ancient Apocalypse Hood
1237661249, // Ancient Apocalypse Plate
1356064950, // Ancient Apocalypse Grips
1359908066, // Ancient Apocalypse Gauntlets
1488486721, // Ancient Apocalypse Bond
1548620661, // Ancient Apocalypse Cloak
1741396519, // Ancient Apocalypse Vest
1752237812, // Ancient Apocalypse Gloves
2020166300, // Ancient Apocalypse Mark
2039976446, // Ancient Apocalypse Boots
2088829612, // Ancient Apocalypse Bond
2130645994, // Ancient Apocalypse Grips
2440840551, // Ancient Apocalypse Gloves
2451538755, // Ancient Apocalypse Strides
2459422430, // Ancient Apocalypse Bond
2506514251, // Ancient Apocalypse Cloak
2512196373, // Ancient Apocalypse Helm
2518527196, // Ancient Apocalypse Plate
2568447248, // Ancient Apocalypse Strides
2620389105, // Ancient Apocalypse Grips
2677967607, // Ancient Apocalypse Gauntlets
2694124942, // Ancient Apocalypse Greaves
2728668760, // Ancient Apocalypse Vest
2858060922, // Ancient Apocalypse Vest
2881248566, // Ancient Apocalypse Cloak
3031848199, // Ancient Apocalypse Helm
3184912423, // Ancient Apocalypse Cloak
3339632627, // Ancient Apocalypse Mark
3404053788, // Ancient Apocalypse Greaves
3486086024, // Ancient Apocalypse Greaves
3537476911, // Ancient Apocalypse Mask
3550729740, // Ancient Apocalypse Robes
3595268459, // Ancient Apocalypse Gloves
3664007718, // Ancient Apocalypse Helm
3804360785, // Ancient Apocalypse Mark
3825427923, // Ancient Apocalypse Helm
3855285278, // Ancient Apocalypse Vest
3925589496, // Ancient Apocalypse Hood
4115739810, // Ancient Apocalypse Plate
4188366993, // Ancient Apocalypse Robes
4255727106, // Ancient Apocalypse Hood
],
dsc: [],
dungeon: [],
edz: [
10307688, // Wildwood Plate
11686458, // Orobas Vectura Cloak
320310249, // Orobas Vectura Bond
872284448, // Wildwood Gauntlets
1304122208, // Wildwood Bond
1664741411, // Wildwood Gloves
1701005143, // Gearhead Gloves
1712405061, // Wildwood Mark
2426340788, // Orobas Vectura Mark
2486041712, // Gearhead Gauntlets
2724176749, // Wildwood Robes
2729740202, // Wildwood Vest
3080875433, // Wildwood Helm
3366557883, // Wildwood Cloak
3466255616, // Wildwood Strides
3706457514, // Gearhead Grips
3764013786, // Wildwood Cover
3862191322, // Wildwood Greaves
3907226374, // Wildwood Grips
3973359167, // Wildwood Mask
4051755349, // Wildwood Boots
],
eow: [
239489770, // Bond of Sekris
253344425, // Mask of Feltroc
340118991, // Boots of Sekris
383742277, // Cloak of Feltroc
588627781, // Bond of Sekris
666883012, // Gauntlets of Nohr
796914932, // Mask of Sekris
845536715, // Vest of Feltroc
1034660314, // Boots of Feltroc
1242139836, // Plate of Nohr
1256688732, // Mask of Feltroc
1756558505, // Mask of Sekris
1991039861, // Mask of Nohr
2329031091, // Robes of Sekris
2339720736, // Grips of Feltroc
2369496221, // Plate of Nohr
2537874394, // Boots of Sekris
2597529070, // Greaves of Nohr
2653039573, // Grips of Feltroc
2976612200, // Vest of Feltroc
2994007601, // Mark of Nohr
3099636805, // Greaves of Nohr
3181497704, // Robes of Sekris
3359121706, // Mask of Nohr
3364682867, // Gauntlets of Nohr
3497220322, // Cloak of Feltroc
3831484112, // Mark of Nohr
3842934816, // Wraps of Sekris
3964287245, // Wraps of Sekris
4229161783, // Boots of Feltroc
],
ep: [],
europa: [],
events: [
116784191, // Solstice Boots (Renewed)
140842223, // Solstice Mask (Drained)
143299650, // Solstice Plate (Renewed)
153144587, // Solstice Cloak (Drained)
226436555, // Solstice Mask (Renewed)
231432261, // Solstice Bond (Resplendent)
234970842, // Solstice Boots (Resplendent)
250513201, // Solstice Greaves (Resplendent)
335763433, // Solstice Plate (Resplendent)
346065606, // Solstice Cloak (Rekindled)
391889347, // Solstice Robes (Drained)
419435523, // Inaugural Revelry Grips
450844637, // Solstice Robes (Majestic)
492834021, // Inaugural Revelry Hood
518930465, // Solstice Grasps (Rekindled)
531005896, // Solstice Cloak (Resplendent)
540653483, // Solstice Vest (Scorched)
574167778, // Solstice Gauntlets (Drained)
574790717, // Solstice Gloves (Drained)
627596132, // Solstice Hood (Drained)
677939288, // Solstice Helm (Scorched)
721146704, // Solstice Mask (Rekindled)
784499738, // Solstice Bond (Renewed)
830497630, // Solstice Helm (Resplendent)
929148730, // Solstice Vest (Drained)
967650555, // Solstice Greaves (Scorched)
1056992393, // Inaugural Revelry Plate
1141639721, // Solstice Gauntlets (Scorched)
1229961870, // Solstice Vest (Renewed)
1273510836, // Inaugural Revelry Wraps
1288683596, // Solstice Plate (Majestic)
1341471164, // Solstice Mask (Scorched)
1361620030, // Solstice Mark (Scorched)
1365491398, // Solstice Plate (Drained)
1376763596, // Inaugural Revelry Robes
1450633717, // Solstice Vest (Resplendent)
1502692899, // Solstice Robes (Renewed)
1510405477, // Solstice Helm (Majestic)
1540031264, // Solstice Gloves (Resplendent)
1548056407, // Solstice Cloak (Renewed)
1556831535, // Inaugural Revelry Gauntlets
1561249470, // Inaugural Revelry Boots
1589318419, // Solstice Strides (Rekindled)
1649929380, // Solstice Mark (Resplendent)
1651275175, // Solstice Helm (Renewed)
1683482799, // Solstice Mark (Drained)
1706764072, // Quilted Winter Mark
1706874193, // Inaugural Revelry Greaves
1775707016, // Solstice Grasps (Majestic)
1812385587, // Festive Winter Bond
1862324869, // Solstice Boots (Majestic)
1897528210, // Solstice Robes (Scorched)
2105409832, // Solstice Greaves (Renewed)
2111111693, // Solstice Strides (Resplendent)
2120905920, // Inaugural Revelry Cloak
2127474099, // Solstice Gloves (Majestic)
2150778206, // Solstice Gloves (Scorched)
2155928170, // Solstice Mark (Rekindled)
2156817213, // Solstice Cloak (Majestic)
2287277682, // Solstice Robes (Rekindled)
2291082292, // Solstice Gauntlets (Majestic)
2328435454, // Inaugural Revelry Helm
2337290000, // Solstice Bond (Majestic)
2419100474, // Solstice Grasps (Renewed)
2470583197, // Solstice Gloves (Renewed)
2477028154, // Inaugural Revelry Mask
2492769187, // Solstice Bond (Scorched)
2523388612, // Solstice Hood (Renewed)
2546370410, // Solstice Hood (Majestic)
2578820926, // Solstice Greaves (Majestic)
2618313500, // Solstice Greaves (Drained)
2685001662, // Solstice Gloves (Rekindled)
2696245301, // Solstice Grasps (Scorched)
2720534902, // Solstice Grasps (Drained)
2764769717, // Inaugural Revelry Strides
2770157746, // Solstice Mask (Resplendent)
2777913564, // Warm Winter Cloak
2805101184, // Solstice Vest (Majestic)
2824302184, // Solstice Robes (Resplendent)
2837295684, // Inaugural Revelry Mark
2877046370, // Solstice Strides (Majestic)
2924095235, // Solstice Bond (Rekindled)
2940416351, // Solstice Boots (Drained)
2978747767, // Solstice Vest (Rekindled)
2994721336, // Solstice Boots (Scorched)
3015197581, // Solstice Gauntlets (Rekindled)
3039687635, // Solstice Helm (Drained)
3077367255, // Solstice Hood (Scorched)
3104384024, // Solstice Boots (Rekindled)
3159052337, // Solstice Mask (Majestic)
3192336962, // Solstice Cloak (Scorched)
3236510875, // Solstice Grasps (Resplendent)
3611487543, // Solstice Hood (Rekindled)
3685996623, // Solstice Greaves (Rekindled)
3748622249, // Solstice Hood (Resplendent)
3892841518, // Solstice Gauntlets (Renewed)
3929403535, // Solstice Gauntlets (Resplendent)
3932814032, // Solstice Strides (Drained)
3943394479, // Solstice Plate (Scorched)
3965417933, // Inaugural Revelry Vest
3968560442, // Solstice Bond (Drained)
3987442049, // Solstice Mark (Majestic)
4075522049, // Inaugural Revelry Bond
4100029812, // Solstice Strides (Renewed)
4128297107, // Solstice Mark (Renewed)
4142792564, // Solstice Helm (Rekindled)
4245469491, // Solstice Plate (Rekindled)
4272367383, // Solstice Strides (Scorched)
],
eververse: [
138961800, // Helm of Optimacy
163660481, // Bond of Optimacy
167651268, // Crimson Passion
269339124, // Dawning Hope
599687980, // Purple Dawning Lanterns
691914261, // Silver Dawning Lanterns
706111909, // Hood of Optimacy
710937567, // Legs of Optimacy
921357268, // Winterhart Plate
989291706, // Cloak of Optimacy
1051903593, // Dawning Bauble Shell
1135293055, // Plate of Optimacy
1290784012, // Winterhart Gauntlets
1397284432, // Jasper Dawn Shell
1445212020, // Arms of Optimacy
1602334068, // Regent Redeemer
1706764073, // Winterhart Mark
1707587907, // Vest of Optimacy
1732950654, // Legs of Optimacy
1812385586, // Winterhart Bond
1816495538, // Sweet Memories Shell
1844125034, // Dawning Festiveness
1936516278, // Winterhart Greaves
1956273477, // Winterhart Gloves
1984190529, // Magikon
2112889975, // Crimson Valor
2225903500, // Robes of Optimacy
2303499975, // Winterhart Boots
2378378507, // Legs of Optimacy
2623660327, // Dawning Brilliance
2640279229, // Arms of Optimacy
2693084644, // Mask of Optimacy
2717158440, // Winterhart Grips
2760398988, // Winterhart Cover
2777913565, // Winterhart Cloak
2806805902, // Mark of Optimacy
2828252061, // Winterhart Helm
2998296658, // Ice Ball Effects
3161524490, // Rupture
3168164098, // Yellow Dawning Lanterns
3177119978, // Carmina Commencing
3352566658, // Winterhart Strides
3455566107, // Winterhart Robes
3569791559, // Shimmering Iris
3729709035, // Joyfire
3781263385, // Arms of Optimacy
3850655136, // Winterhart Vest
3866715933, // Dawning Warmth
3947596543, // Green Dawning Lanterns
4059030097, // Winterhart Mask
],
exoticcipher: [],
fwc: [
680327840, // Simulator Greaves
807866445, // Simulator Gloves
1162875302, // Simulator Gauntlets
1187431263, // Simulator Helm
1355893732, // Simulator Vest
1418921862, // Simulator Boots
1478665487, // Simulator Legs
1566612778, // Entanglement Bond
1763431309, // Simulator Mask
2401598772, // Simulator Hood
2415993980, // Simulator Grips
2524181305, // Entanglement Cloak
3656154099, // Simulator Robes
3671665226, // Simulator Plate
3842448731, // Entanglement Mark
],
gambit: [
9767416, // Ancient Apocalypse Bond
94425673, // Ancient Apocalypse Gloves
127018032, // Ancient Apocalypse Grips
191247558, // Ancient Apocalypse Plate
191535001, // Ancient Apocalypse Greaves
230878649, // Ancient Apocalypse Mask
386367515, // Ancient Apocalypse Boots
392058749, // Ancient Apocalypse Boots
485653258, // Ancient Apocalypse Strides
509238959, // Ancient Apocalypse Mark
629787707, // Ancient Apocalypse Mask
759348512, // Ancient Apocalypse Mask
787909455, // Ancient Apocalypse Robes
887818405, // Ancient Apocalypse Robes
978447246, // Ancient Apocalypse Gauntlets
1013137701, // Ancient Apocalypse Hood
1169857924, // Ancient Apocalypse Strides
1188039652, // Ancient Apocalypse Gauntlets
1193646249, // Ancient Apocalypse Boots
1236746902, // Ancient Apocalypse Hood
1237661249, // Ancient Apocalypse Plate
1356064950, // Ancient Apocalypse Grips
1359908066, // Ancient Apocalypse Gauntlets
1488486721, // Ancient Apocalypse Bond
1548620661, // Ancient Apocalypse Cloak
1741396519, // Ancient Apocalypse Vest
1752237812, // Ancient Apocalypse Gloves
2020166300, // Ancient Apocalypse Mark
2039976446, // Ancient Apocalypse Boots
2088829612, // Ancient Apocalypse Bond
2130645994, // Ancient Apocalypse Grips
2440840551, // Ancient Apocalypse Gloves
2451538755, // Ancient Apocalypse Strides
2459422430, // Ancient Apocalypse Bond
2506514251, // Ancient Apocalypse Cloak
2512196373, // Ancient Apocalypse Helm
2518527196, // Ancient Apocalypse Plate
2568447248, // Ancient Apocalypse Strides
2620389105, // Ancient Apocalypse Grips
2677967607, // Ancient Apocalypse Gauntlets
2694124942, // Ancient Apocalypse Greaves
2728668760, // Ancient Apocalypse Vest
2858060922, // Ancient Apocalypse Vest
2881248566, // Ancient Apocalypse Cloak
3031848199, // Ancient Apocalypse Helm
3184912423, // Ancient Apocalypse Cloak
3339632627, // Ancient Apocalypse Mark
3404053788, // Ancient Apocalypse Greaves
3486086024, // Ancient Apocalypse Greaves
3537476911, // Ancient Apocalypse Mask
3550729740, // Ancient Apocalypse Robes
3595268459, // Ancient Apocalypse Gloves
3664007718, // Ancient Apocalypse Helm
3804360785, // Ancient Apocalypse Mark
3825427923, // Ancient Apocalypse Helm
3855285278, // Ancient Apocalypse Vest
3925589496, // Ancient Apocalypse Hood
4115739810, // Ancient Apocalypse Plate
4188366993, // Ancient Apocalypse Robes
4255727106, // Ancient Apocalypse Hood
],
gambitprime: [
95332289, // Notorious Collector Strides
95332290, // Outlawed Collector Strides
98700833, // Outlawed Reaper Cloak
98700834, // Notorious Reaper Cloak
130287073, // Notorious Sentry Gauntlets
130287074, // Outlawed Sentry Gauntlets
154180149, // Outlawed Sentry Cloak
154180150, // Notorious Sentry Cloak
223681332, // Notorious Reaper Helm
223681335, // Outlawed Reaper Helm
234582861, // Outlawed Reaper Mark
234582862, // Notorious Reaper Mark
264182640, // Outlawed Collector Grips
264182643, // Notorious Collector Grips
370332340, // Notorious Collector Cloak
370332343, // Outlawed Collector Cloak
420625860, // Outlawed Invader Plate
420625863, // Notorious Invader Plate
432797516, // Outlawed Collector Bond
432797519, // Notorious Collector Bond
563461320, // Outlawed Reaper Greaves
563461323, // Notorious Reaper Greaves
722344177, // Outlawed Reaper Gloves
722344178, // Notorious Reaper Gloves
759881004, // Outlawed Sentry Plate
759881007, // Notorious Sentry Plate
893169981, // Outlawed Invader Cloak
893169982, // Notorious Invader Cloak
975478397, // Outlawed Collector Helm
975478398, // Notorious Collector Helm
1039402696, // Notorious Reaper Boots
1039402699, // Outlawed Reaper Boots
1159077396, // Outlawed Reaper Strides
1159077399, // Notorious Reaper Strides
1208982392, // Outlawed Reaper Hood
1208982395, // Notorious Reaper Hood
1295793304, // Notorious Reaper Mask
1295793307, // Outlawed Reaper Mask
1386198149, // Notorious Reaper Gauntlets
1386198150, // Outlawed Reaper Gauntlets
1438999856, // Notorious Collector Boots
1438999859, // Outlawed Collector Boots
1477025072, // Outlawed Sentry Bond
1477025075, // Notorious Sentry Bond
1505642257, // Outlawed Collector Robes
1505642258, // Notorious Collector Robes
1920676413, // Notorious Invader Bond
1920676414, // Outlawed Invader Bond
1951201409, // Notorious Invader Hood
1951201410, // Outlawed Invader Hood
1979001652, // Outlawed Reaper Bond
1979001655, // Notorious Reaper Bond
1984789548, // Outlawed Reaper Vest
1984789551, // Notorious Reaper Vest
1989814421, // Notorious Invader Grips
1989814422, // Outlawed Invader Grips
2051266836, // Outlawed Sentry Greaves
2051266839, // Notorious Sentry Greaves
2187982744, // Notorious Sentry Helm
2187982747, // Outlawed Sentry Helm
2334120368, // Outlawed Reaper Plate
2334120371, // Notorious Reaper Plate
2336344261, // Outlawed Sentry Gloves
2336344262, // Notorious Sentry Gloves
2371932404, // Outlawed Collector Gauntlets
2371932407, // Notorious Collector Gauntlets
2565812704, // Outlawed Collector Hood
2565812707, // Notorious Collector Hood
2591049236, // Notorious Invader Robes
2591049239, // Outlawed Invader Robes
2593076932, // Notorious Invader Mask
2593076935, // Outlawed Invader Mask
2698109345, // Outlawed Collector Mask
2698109346, // Notorious Collector Mask
2710420856, // Outlawed Sentry Vest
2710420859, // Notorious Sentry Vest
2799932928, // Notorious Collector Mark
2799932931, // Outlawed Collector Mark
2976484617, // Notorious Invader Gauntlets
2976484618, // Outlawed Invader Gauntlets
3088740176, // Notorious Invader Gloves
3088740179, // Outlawed Invader Gloves
3166483968, // Outlawed Sentry Strides
3166483971, // Notorious Sentry Strides
3168759585, // Outlawed Sentry Mark
3168759586, // Notorious Sentry Mark
3220030412, // Notorious Sentry Mask
3220030415, // Outlawed Sentry Mask
3373994936, // Outlawed Invader Strides
3373994939, // Notorious Invader Strides
3403732217, // Outlawed Collector Gloves
3403732218, // Notorious Collector Gloves
3489978605, // Outlawed Invader Boots
3489978606, // Notorious Invader Boots
3525447589, // Notorious Collector Vest
3525447590, // Outlawed Collector Vest
3533064929, // Notorious Reaper Grips
3533064930, // Outlawed Reaper Grips
3583507225, // Outlawed Reaper Robes
3583507226, // Notorious Reaper Robes
3636943392, // Notorious Invader Helm
3636943395, // Outlawed Invader Helm
3660501108, // Outlawed Sentry Hood
3660501111, // Notorious Sentry Hood
3837542169, // Outlawed Invader Mark
3837542170, // Notorious Invader Mark
3948054485, // Notorious Collector Greaves
3948054486, // Outlawed Collector Greaves
3981071584, // Outlawed Invader Vest
3981071587, // Notorious Invader Vest
4020124605, // Outlawed Sentry Robes
4020124606, // Notorious Sentry Robes
4026665500, // Outlawed Invader Greaves
4026665503, // Notorious Invader Greaves
4060232809, // Notorious Collector Plate
4060232810, // Outlawed Collector Plate
4245233853, // Notorious Sentry Grips
4245233854, // Outlawed Sentry Grips
4266990316, // Notorious Sentry Boots
4266990319, // Outlawed Sentry Boots
],
garden: [
11974904, // Greaves of Ascendancy
281660259, // Temptation's Mark
519078295, // Helm of Righteousness
557676195, // Cowl of Righteousness
1653741426, // Grips of Exaltation
2015894615, // Gloves of Exaltation
2054979724, // Strides of Ascendancy
2320830625, // Robes of Transcendence
3001934726, // Mask of Righteousness
3103335676, // Temptation's Bond
3549177695, // Cloak of Temptation
3824429433, // Boots of Ascendancy
3887559710, // Gauntlets of Exaltation
3939809874, // Plate of Transcendence
4177973942, // Vest of Transcendence
],
gunsmith: [
583723938, // Fusion Rifle Loader
583723939, // Linear Fusion Rifle Targeting
583723940, // Shotgun Dexterity
583723941, // Sword Scavenger
739655784, // Auto Rifle Loader
739655787, // Shotgun Ammo Finder
739655788, // Sidearm Dexterity
],
harbinger: [],
ikora: [
89175653, // Noble Constant Mark
185326970, // Noble Constant Type 2
385045066, // Frumious Vest
555828571, // Frumious Cloak
662797277, // Frumious Cloak
868792277, // Ego Talon IV
1490387264, // Noble Constant Type 2
1532009197, // Ego Talon IV
1698434490, // Ego Talon Bond
1735538848, // Frumious Vest
1842727357, // Ego Talon IV
1895532772, // Ego Talon IV
1940451444, // Noble Constant Type 2
2416730691, // Ego Talon IV
2615512594, // Ego Talon IV
2682045448, // Noble Constant Type 2
2684281417, // Noble Constant Mark
2688111404, // Noble Constant Type 2
3081969019, // Ego Talon IV
3511221544, // Frumious Grips
3741528736, // Frumious Strides
3758301014, // Noble Constant Type 2
4081859017, // Noble Constant Type 2
4146629762, // Frumious Strides
4208352991, // Ego Talon IV
4224076198, // Frumious Grips
4225579453, // Noble Constant Type 2
4285708584, // Ego Talon Bond
],
io: [
886128573, // Mindbreaker Boots
2317191363, // Mindbreaker Boots
2913284400, // Mindbreaker Boots
],
ironbanner: [
21320325, // Bond of Remembrance
63725907, // Iron Remembrance Plate
75550387, // Iron Truage Legs
92135663, // Iron Remembrance Vest
124696333, // Iron Truage Vestments
130221063, // Iron Truage Vestments
131359121, // Iron Fellowship Casque
142417051, // Iron Fellowship Casque
167461728, // Iron Remembrance Gloves
197164672, // Iron Truage Hood
198946996, // Iron Symmachy Helm
219816655, // Iron Fellowship Bond
228784708, // Iron Symmachy Robes
258029924, // Iron Fellowship Strides
279785447, // Iron Remembrance Vest
287471683, // Iron Truage Gloves
344804890, // Iron Fellowship Cloak
423204919, // Iron Truage Hood
425007249, // Iron Remembrance Plate
473526496, // Iron Fellowship Vest
479917491, // Mantle of Efrideet
481390023, // Iron Truage Casque
485774636, // Iron Remembrance Helm
500363457, // Iron Symmachy Grips
510020159, // Iron Fellowship Strides
511170376, // Iron Truage Boots
559176540, // Iron Symmachy Gloves
561808153, // Mantle of Efrideet
691332172, // Iron Truage Gauntlets
706104224, // Iron Truage Gauntlets
713182381, // Iron Remembrance Gauntlets
738836759, // Iron Truage Vestments
738938985, // Radegast's Iron Sash
739655237, // Iron Truage Helm
741704251, // Iron Remembrance Plate
744156528, // Iron Symmachy Mask
770140877, // Iron Will Greaves
808693674, // Iron Symmachy Mark
831464034, // Iron Truage Vest
863444264, // Iron Will Gloves
892360677, // Iron Fellowship Helm
935677805, // Iron Truage Casque
957732971, // Iron Symmachy Grips
959040145, // Iron Symmachy Bond
995283190, // Cloak of Remembrance
1015625830, // Iron Truage Boots
1027482647, // Iron Fellowship Boots
1058936857, // Iron Will Vest
1062998051, // Iron Fellowship Vest
1084553865, // Iron Symmachy Greaves
1098138990, // Iron Will Mask
1105558158, // Iron Truage Helm
1127757814, // Iron Symmachy Helm
1164755828, // Iron Fellowship Bond
1166260237, // Iron Truage Vestments
1173846338, // Iron Fellowship Bond
1181560527, // Iron Truage Vest
1233689371, // Iron Remembrance Hood
1234228360, // Iron Will Mark
1245456047, // Iron Fellowship Gauntlets
1279731468, // Iron Symmachy Mark
1311649814, // Timur's Iron Bond
1313089081, // Iron Truage Plate
1313767877, // Radegast's Iron Sash
1337167606, // Iron Truage Greaves
1339294334, // Cloak of Remembrance
1342036510, // Iron Truage Greaves
1349302244, // Iron Remembrance Legs
1395498705, // Iron Fellowship Greaves
1425558127, // Iron Remembrance Greaves
1438648985, // Iron Symmachy Bond
1452894389, // Mantle of Efrideet
1465485698, // Iron Fellowship Gloves
1469050017, // Iron Will Boots
1476572353, // Iron Truage Greaves
1478755348, // Iron Truage Gauntlets
1496224967, // Iron Truage Casque
1498852482, // Iron Will Steps
1526005320, // Iron Truage Boots
1570751539, // Iron Symmachy Strides
1601698634, // Iron Fellowship Grips
1604601714, // Iron Truage Vestments
1618191618, // Iron Symmachy Mask
1631733639, // Bond of Remembrance
1631922345, // Iron Remembrance Greaves
1673037492, // Iron Fellowship Gauntlets
1675022998, // Iron Remembrance Helm
1717896437, // Iron Truage Legs
1804445917, // Iron Truage Helm
1822989604, // Iron Symmachy Gloves
1854612346, // Iron Truage Hood
1876007169, // Iron Fellowship Mark
1882457108, // Iron Remembrance Helm
1889355043, // Iron Truage Legs
1891964978, // Iron Fellowship Greaves
1895324274, // Iron Will Helm
1944853984, // Iron Remembrance Casque
1960776126, // Iron Fellowship Greaves
1990315366, // Iron Symmachy Cloak
2017059966, // Iron Fellowship Helm
2049490557, // Iron Symmachy Strides
2054377692, // Iron Truage Grips
2055774222, // Iron Fellowship Hood
2058205265, // Iron Truage Gloves
2083136519, // Iron Fellowship Cloak
2205315921, // Iron Will Hood
2234855160, // Iron Symmachy Cloak
2241419267, // Timur's Iron Bond
2266122060, // Iron Truage Gauntlets
2274205961, // Iron Fellowship Plate
2302106622, // Iron Remembrance Vestments
2310625418, // Mark of Remembrance
2320100699, // Iron Will Gauntlets
2331748167, // Iron Symmachy Gauntlets
2340483067, // Iron Remembrance Hood
2391553724, // Iron Fellowship Hood
2414679508, // Iron Will Cloak
2426788417, // Iron Fellowship Boots
2455992644, // Iron Remembrance Legs
2500327265, // Radegast's Iron Sash
2536633781, // Iron Will Plate
2547799775, // Iron Will Sleeves
2555322239, // Iron Truage Gauntlets
2589114445, // Iron Fellowship Mark
2614190248, // Iron Remembrance Vestments
2620437164, // Mark of Remembrance
2627255028, // Radegast's Iron Sash
2674485749, // Iron Truage Legs
2692970954, // Iron Remembrance Gloves
2723059534, // Iron Truage Grips
2753509502, // Iron Fellowship Vest
2758933481, // Iron Remembrance Hood
2811201658, // Iron Truage Hood
2817130155, // Iron Fellowship Robes
2845071512, // Iron Remembrance Casque
2850783764, // Iron Truage Plate
2853073502, // Mantle of Efrideet
2863819165, // Iron Fellowship Grips
2867156198, // Timur's Iron Bond
2879116647, // Iron Remembrance Gauntlets
2885394189, // Iron Remembrance Strides
2898234995, // Iron Symmachy Plate
2900181965, // Iron Symmachy Gauntlets
2911957494, // Iron Truage Greaves
2914695209, // Iron Truage Helm
2916624580, // Iron Fellowship Casque
2999505920, // Timur's Iron Bond
3018777825, // Iron Fellowship Helm
3042878056, // Iron Fellowship Grips
3055410141, // Iron Will Bond
3057399960, // Iron Truage Vest
3112906149, // Iron Symmachy Vest
3115791898, // Iron Remembrance Legs
3147146325, // Iron Symmachy Hood
3292445816, // Iron Truage Casque
3300129601, // Iron Truage Gloves
3308875113, // Iron Remembrance Grips
3329206472, // Cloak of Remembrance
3345886183, // Bond of Remembrance
3369424240, // Iron Truage Grips
3379235805, // Iron Truage Helm
3420845681, // Iron Symmachy Plate
3472216012, // Iron Fellowship Plate
3505538303, // Iron Fellowship Gloves
3543613212, // Iron Symmachy Robes
3543922672, // Iron Truage Hood
3544440242, // Iron Remembrance Casque
3551208252, // Iron Fellowship Boots
3570981007, // Iron Symmachy Greaves
3600816955, // Iron Remembrance Strides
3625849667, // Iron Truage Gloves
3646911172, // Iron Truage Vest
3661959184, // Iron Fellowship Plate
3678620931, // Iron Remembrance Strides
3686482762, // Iron Truage Boots
3696011098, // Iron Truage Greaves
3735443949, // Iron Symmachy Hood
3737894478, // Iron Truage Grips
3746327861, // Iron Fellowship Gloves
3753635534, // Iron Symmachy Boots
3756249289, // Iron Truage Grips
3791686334, // Iron Truage Gloves
3799661482, // Iron Remembrance Gloves
3815391974, // Iron Symmachy Boots
3817948370, // Mark of Remembrance
3818295475, // Mantle of Efrideet
3847368113, // Iron Remembrance Grips
3856062457, // Iron Truage Casque
3856697336, // Iron Fellowship Gauntlets
3865618708, // Iron Truage Plate
3899385447, // Iron Remembrance Greaves
3906637800, // Iron Truage Plate
3972479219, // Iron Fellowship Hood
3974682334, // Iron Remembrance Vestments
3976616421, // Iron Remembrance Gauntlets
4010793371, // Iron Remembrance Grips
4019071337, // Radegast's Iron Sash
4041069824, // Timur's Iron Bond
4048191131, // Iron Truage Boots
4054509252, // Iron Fellowship Mark
4078529821, // Iron Fellowship Cloak
4096639276, // Iron Truage Plate
4128151712, // Iron Will Vestments
4144217282, // Iron Fellowship Strides
4145557177, // Iron Fellowship Robes
4156963223, // Iron Symmachy Vest
4169842018, // Iron Truage Vest
4196689510, // Iron Fellowship Robes
4211068696, // Iron Truage Legs
4248834293, // Iron Remembrance Vest
],
lastwish: [
4968701, // Greaves of the Great Hunt
16387641, // Mark of the Great Hunt
49280456, // Gloves of the Great Hunt
65929376, // Gauntlets of the Great Hunt
146275556, // Vest of the Great Hunt
196235132, // Grips of the Great Hunt
576683388, // Gauntlets of the Great Hunt
726265506, // Boots of the Great Hunt
776723133, // Robes of the Great Hunt
778784376, // Mark of the Great Hunt
821841934, // Bond of the Great Hunt
972689703, // Vest of the Great Hunt
1021341893, // Mark of the Great Hunt
1127835600, // Grips of the Great Hunt
1190016345, // Mask of the Great Hunt
1195800715, // Boots of the Great Hunt
1258342944, // Mask of the Great Hunt
1314563129, // Cloak of the Great Hunt
1432728945, // Hood of the Great Hunt
1444894250, // Strides of the Great Hunt
1477271933, // Bond of the Great Hunt
1646520469, // Cloak of the Great Hunt
1656835365, // Plate of the Great Hunt
2112541750, // Cloak of the Great Hunt
2274520361, // Helm of the Great Hunt
2280287728, // Bond of the Great Hunt
2550116544, // Robes of the Great Hunt
2598685593, // Gloves of the Great Hunt
2868042232, // Vest of the Great Hunt
2950533187, // Strides of the Great Hunt
3055836250, // Greaves of the Great Hunt
3119383537, // Grips of the Great Hunt
3143067364, // Plate of the Great Hunt
3208178411, // Gauntlets of the Great Hunt
3227674085, // Boots of the Great Hunt
3251351304, // Hood of the Great Hunt
3445296383, // Robes of the Great Hunt
3445582154, // Hood of the Great Hunt
3492720019, // Gloves of the Great Hunt
3494130310, // Strides of the Great Hunt
3614211816, // Plate of the Great Hunt
3838639757, // Mask of the Great Hunt
3868637058, // Helm of the Great Hunt
3874578566, // Greaves of the Great Hunt
4219088013, // Helm of the Great Hunt
],
legendaryengram: [
24598504, // Red Moon Phantom Vest
25091086, // Tangled Web Cloak
32806262, // Cloak of Five Full Moons
42219189, // Tangled Web Gauntlets
73720713, // High-Minded Complex
107232578, // Tangled Web Gauntlets
107582877, // Kerak Type 2
130772858, // Tangled Web Vest
133227345, // Kerak Type 2
144651852, // Prodigal Mask
155832748, // Icarus Drifter Mask
160388292, // Kerak Type 2
265279665, // Clandestine Maneuvers
269552461, // Road Complex AA1
308026950, // Road Complex AA1
311394919, // Insight Unyielding Greaves
316000947, // Dead End Cure 2.1
339438127, // High-Minded Complex
362404956, // Terra Concord Plate
369384485, // Insight Rover Vest
373203219, // Philomath Bond
388625893, // Insight Unyielding Gauntlets
410671183, // High-Minded Complex
417345678, // Thorium Holt Gloves
432525353, // Red Moon Phantom Mask
433294875, // Devastation Complex
434243995, // Hodiocentrist Bond
474076509, // Errant Knight 1.0
489114030, // Philomath Gloves
489480785, // High-Minded Complex
489743173, // Insight Unyielding Gauntlets
493299171, // Errant Knight 1.0
494682309, // Massyrian's Draw
532728591, // Thorium Holt Gloves
537272242, // Tangled Web Boots
545134223, // Tangled Web Mark
548907748, // Devastation Complex
553373026, // Tangled Web Hood
554000115, // Thorium Holt Bond
583723943, // Hands-On
597618504, // Insight Vikti Hood
629469344, // Heiro Camo
629482101, // Dead End Cure 2.1
633160551, // Insight Rover Vest
635809934, // Terra Concord Helm
639670612, // Mimetic Savior Plate
655964556, // Mimetic Savior Gauntlets
683173058, // Philomath Robes
690335398, // Terra Concord Helm
695071581, // Tesseract Trace IV
731888972, // Insight Vikti Robes
737010724, // Thorium Holt Bond
836969671, // Insight Unyielding Greaves
854373147, // Insight Unyielding Plate
875215126, // Prodigal Mark
880368054, // Tangled Web Grips
881579413, // Terra Concord Helm
919186882, // Tangled Web Mark
922218300, // Road Complex AA1
966777042, // Anti-Hero Victory
974507844, // Insight Rover Grips
983115833, // Terra Concord Plate
993844472, // High-Minded Complex
1006824129, // Terra Concord Greaves
1020198891, // Insight Rover Grips
1024867629, // Errant Knight 1.0
1028913028, // Tesseract Trace IV
1034149520, // Tangled Web Robes
1063507982, // Terra Concord Greaves
1088960547, // Prodigal Greaves
1111042046, // High-Minded Complex
1127029635, // Insight Rover Boots
1148805553, // Thorium Holt Boots
1153347999, // Icarus Drifter Cape
1192751404, // Insight Unyielding Helm
1195298951, // Be Thy Champion
1213841242, // Red Moon Phantom Steps
1257810769, // Prodigal Gauntlets
1260134370, // Devastation Complex
1266060945, // Prodigal Mark
1293868684, // Insight Unyielding Helm
1295776817, // Insight Rover Grips
1301696822, // Mimetic Savior Greaves
1330107298, // Thorium Holt Robes
1330542168, // Tangled Web Bond
1348658294, // Clandestine Maneuvers
1364856221, // Retro-Grade TG2
1367655773, // Tangled Web Boots
1399263478, // Icarus Drifter Vest
1415533220, // Road Complex AA1
1425077417, // Mimetic Savior Mark
1429424420, // Prodigal Gauntlets
1432831619, // Red Moon Phantom Steps
1432969759, // Mimetic Savior Greaves
1457647945, // High-Minded Complex
1512829977, // Terra Concord Greaves
1513486336, // Road Complex AA1
1548943654, // Tesseract Trace IV
1553407343, // Prodigal Robes
1598372079, // Retro-Grade TG2
1601578801, // Red Moon Phantom Grips
1618341271, // Tangled Web Greaves
1648238545, // Terra Concord Mark
1655109893, // Tesseract Trace IV
1664085089, // Tangled Web Hood
1664611474, // Heiro Camo
1680657538, // Insight Rover Mask
1693706589, // Prodigal Cloak
1726695877, // Cloak of Five Full Moons
1728789982, // Thorium Holt Hood
1740873035, // Icarus Drifter Grips
1742735530, // Road Complex AA1
1749589787, // High-Minded Complex
1761136389, // Errant Knight 1.0
1772639961, // Hodiocentrist Bond
1810399711, // Philomath Bond
1847870034, // Icarus Drifter Cape
1854024004, // Be Thy Cipher
1865671934, // Devastation Complex
1892576458, // Devastation Complex
1893349933, // Tesseract Trace IV
1904199788, // Mark of the Unassailable
1920259123, // Tesseract Trace IV
1954457094, // Road Complex AA1
1964977914, // Mimetic Savior Mark
1978110490, // Mark of the Unassailable
1998314509, // Dead End Cure 2.1
2012084760, // Prodigal Hood
2020589887, // Road Complex AA1
2026285619, // Errant Knight 1.0
2048751167, // Kerak Type 2
2082184158, // Be Thy Cipher
2085574015, // Terra Concord Fists
2092750352, // Tangled Web Strides
2111956477, // Insight Rover Boots
2112821379, // Insight Unyielding Helm
2148295091, // Tangled Web Helm
2151378428, // Tangled Web Greaves
2159363321, // Be Thy Guide
2173858802, // Prodigal Cloak
2185500219, // Insight Unyielding Plate
2193432605, // Mimetic Savior Helm
2205604183, // Dead End Cure 2.1
2206284939, // Tangled Web Strides
2265859909, // Retro-Grade TG2
2297281780, // Terra Concord Mark
2298664693, // Insight Rover Mask
2332398934, // Kerak Type 2
2339155434, // Tesseract Trace IV
2360521872, // A Cloak Called Home
2364041279, // Insight Vikti Robes
2379553211, // Be Thy Guide
2402435619, // Philomath Cover
2414278933, // Errant Knight 1.0
2439195958, // Philomath Robes
2442805346, // Icarus Drifter Mask
2445181930, // Errant Knight 1.0
2454861732, // Prodigal Robes
2470746631, // Thorium Holt Hood
2475888361, // Prodigal Gloves
2478301019, // Insight Vikti Hood
2502004600, // Tangled Web Gloves
2518901664, // Red Moon Phantom Grips
2521426922, // Far Gone Hood
2525344810, // Retro-Grade TG2
2530905971, // Retro-Grade TG2
2542514983, // Philomath Cover
2546015644, // Tesseract Trace IV
2550994842, // Errant Knight 1.0
2561056920, // Retro-Grade TG2
2562470699, // Tangled Web Plate
2562555736, // Icarus Drifter Cape
2567710435, // Icarus Drifter Mask
2581516944, // Hodiocentrist Bond
2629014079, // Anti-Hero Victory
2648545535, // Tangled Web Vest
2669113551, // Dead End Cure 2.1
2674524165, // Tangled Web Robes
2696303651, // Kerak Type 2
2713755753, // Kerak Type 2
2728535008, // Tesseract Trace IV
2734010957, // Prodigal Hood
2753581141, // Prodigal Helm
2762426792, // Prodigal Grasps
2766448160, // Prodigal Vest
2767830203, // Prodigal Steps
2770578349, // Massyrian's Draw
2772485446, // Prodigal Steps
2791527489, // Heiro Camo
2800566014, // Prodigal Bond
2808379196, // Insight Rover Vest
2811180959, // Tesseract Trace IV
2819613314, // Far Gone Hood
2826844112, // Retro-Grade Mark
2837138379, // Insight Vikti Boots
2838060329, // Heiro Camo
2845530750, // Retro-Grade Mark
2905153902, // Insight Rover Boots
2905154661, // Insight Vikti Hood
2924984456, // Thorium Holt Boots
2932121030, // Devastation Complex
2979161761, // Hand Cannon Holster
2982412348, // Tangled Web Helm
2996649640, // Philomath Boots
3018268196, // Insight Vikti Boots
3024860521, // Retro-Grade TG2
3061780015, // Tangled Web Mask
3066154883, // Mimetic Savior Plate
3066593211, // Icarus Drifter Vest
3087552232, // Heiro Camo
3125909492, // Dead End Cure 2.1
3169402598, // Tesseract Trace IV
3198691833, // Prodigal Bond
3239215026, // Icarus Drifter Grips
3250112431, // Be Thy Champion
3250360146, // Insight Unyielding Gauntlets
3257088093, // Icarus Drifter Legs
3291075521, // Terra Concord Plate
3299386902, // Insight Unyielding Plate
3304280092, // Devastation Complex
3316802363, // Retro-Grade TG2
3360070350, // Prodigal Greaves
3386676796, // Prodigal Gloves
3397835010, // Prodigal Strides
3403784957, // Mimetic Savior Gauntlets
3430647425, // Synaptic Construct
3433746208, // A Cloak Called Home
3434158555, // Prodigal Vest
3498500850, // Philomath Gloves
3506159922, // Anti-Hero Victory
3516789127, // Prodigal Strides
3527995388, // Dead End Cure 2.1
3536492583, // Kerak Type 2
3569443559, // Icarus Drifter Legs
3593916933, // Prodigal Grasps
3609169817, // Tangled Web Grips
3611199822, // Synaptic Construct
3612275815, // Red Moon Phantom Vest
3619376218, // Heiro Camo
3629447000, // Heiro Camo
3646674533, // Icarus Drifter Grips
3651598572, // Insight Unyielding Greaves
3685831476, // Insight Vikti Gloves
3688229984, // Insight Rover Mask
3691737472, // Prodigal Helm
3717812073, // Thorium Holt Robes
3725654227, // Devastation Complex
3786300792, // Clandestine Maneuvers
3839471140, // Mimetic Savior Helm
3850634012, // Prodigal Cuirass
3852389988, // Terra Concord Fists
3884999792, // Heiro Camo
3899739148, // Philomath Boots
3906537733, // Icarus Drifter Vest
3920228039, // Synaptic Construct
3973570110, // Insight Vikti Boots
3979056138, // Insight Vikti Gloves
3988753671, // Prodigal Cuirass
3994031968, // Red Moon Phantom Mask
3999262583, // Terra Concord Fists
4064910796, // Icarus Drifter Legs
4073580572, // Terra Concord Mark
4074193483, // Tangled Web Cloak
4079913195, // Dead End Cure 2.1
4092393610, // Tesseract Trace IV
4097652774, // Tangled Web Plate
4104298449, // Prodigal Mask
4146408011, // Tangled Web Gloves
4166246718, // Insight Vikti Robes
4239920089, // Insight Vikti Gloves
4256272077, // Tangled Web Bond
4261835528, // Tangled Web Mask
],
leviathan: [
30962015, // Boots of the Ace-Defiant
64543268, // Boots of the Emperor's Minister
64543269, // Boots of the Fulminator
288406317, // Greaves of Rull
311429765, // Mark of the Emperor's Champion
325434398, // Vest of the Ace-Defiant
325434399, // Vest of the Emperor's Agent
336656483, // Boots of the Emperor's Minister
407863747, // Vest of the Ace-Defiant
455108040, // Helm of the Emperor's Champion
455108041, // Mask of Rull
574137192, // Shadow's Mark
581908796, // Bond of the Emperor's Minister
608074492, // Robes of the Emperor's Minister
608074493, // Robes of the Fulminator
618662448, // Headpiece of the Emperor's Minister
641933203, // Mask of the Emperor's Agent
748485514, // Mask of the Fulminator
748485515, // Headpiece of the Emperor's Minister
754149842, // Wraps of the Emperor's Minister
754149843, // Wraps of the Fulminator
853543290, // Greaves of Rull
853543291, // Greaves of the Emperor's Champion
917591018, // Grips of the Ace-Defiant
917591019, // Gloves of the Emperor's Agent
1108389626, // Gloves of the Emperor's Agent
1230192769, // Robes of the Emperor's Minister
1354679721, // Cloak of the Emperor's Agent
1390282760, // Chassis of Rull
1390282761, // Cuirass of the Emperor's Champion
1413589586, // Mask of Rull
1876645653, // Chassis of Rull
1879942843, // Gauntlets of Rull
1960303677, // Grips of the Ace-Defiant
2013109092, // Helm of the Ace-Defiant
2070062384, // Shadow's Bond
2070062385, // Bond of the Emperor's Minister
2158603584, // Gauntlets of Rull
2158603585, // Gauntlets of the Emperor's Champion
2183861870, // Gauntlets of the Emperor's Champion
2193494688, // Boots of the Fulminator
2232730708, // Vest of the Emperor's Agent
2676042150, // Wraps of the Fulminator
2700598111, // Mask of the Fulminator
2758465168, // Greaves of the Emperor's Champion
2913992255, // Helm of the Emperor's Champion
3092380260, // Mark of the Emperor's Champion
3092380261, // Shadow's Mark
3292127944, // Cuirass of the Emperor's Champion
3530284425, // Wraps of the Emperor's Minister
3592548938, // Robes of the Fulminator
3711700026, // Mask of the Emperor's Agent
3711700027, // Helm of the Ace-Defiant
3763332443, // Shadow's Bond
3853397100, // Boots of the Emperor's Agent
3950028838, // Cloak of the Emperor's Agent
3950028839, // Shadow's Cloak
3984534842, // Shadow's Cloak
4251770244, // Boots of the Ace-Defiant
4251770245, // Boots of the Emperor's Agent
],
limited: [
2683682447, // Traitor's Fate
3752071760, //
3752071761, //
3752071762, //
3752071763, //
3752071765, //
3752071766, //
3752071767, //
],
lostsectors: [],
mars: [],
menagerie: [
126418248, // Exodus Down Vest
192377242, // Exodus Down Strides
472691604, // Exodus Down Vest
853736709, // Exodus Down Cloak
1539014368, // Exodus Down Grips
1640979177, // Exodus Down Cloak
2172333833, // Exodus Down Mask
2252973221, // Exodus Down Cloak
2423003287, // Exodus Down Grips
2462524641, // Exodus Down Vest
2947629004, // Exodus Down Grips
2953649850, // Exodus Down Strides
3026265798, // Exodus Down Mask
3446606632, // Exodus Down Vest
3593464438, // Exodus Down Strides
3669590332, // Exodus Down Cloak
3807183801, // Exodus Down Strides
3875829376, // Exodus Down Grips
4060742749, // Exodus Down Mask
4130486121, // Exodus Down Mask
],
mercury: [],
moon: [
193805725, // Dreambane Cloak
272413517, // Dreambane Helm
310888006, // Dreambane Greaves
377813570, // Dreambane Strides
659922705, // Dreambane Cowl
682780965, // Dreambane Gloves
883769696, // Dreambane Vest
925079356, // Dreambane Gauntlets
1030110631, // Dreambane Boots
1528483180, // Dreambane Hood
2048903186, // Dreambane Bond
2568538788, // Dreambane Plate
3312368889, // Dreambane Mark
3571441640, // Dreambane Grips
3692187003, // Dreambane Robes
],
nessus: [
11686457, // Unethical Experiments Cloak
56157064, // Exodus Down Gauntlets
177493699, // Exodus Down Plate
320310250, // Unethical Experiments Bond
527652447, // Exodus Down Mark
569251271, // Exodus Down Gloves
569678873, // Exodus Down Mark
582151075, // Exodus Down Helm
667921213, // Exodus Down Mark
874856664, // Exodus Down Bond
957928253, // Exodus Down Gauntlets
1010733668, // Exodus Down Helm
1096417434, // Shieldbreaker Robes
1156448694, // Exodus Down Plate
1157496418, // Exodus Down Greaves
1286488743, // Shieldbreaker Plate
1316205184, // Exodus Down Plate
1355771621, // Shieldbreaker Vest
1427620200, // Exodus Down Gloves
1439502385, // Exodus Down Helm
1669675549, // Exodus Down Bond
1678216306, // Exodus Down Gauntlets
1810569868, // Exodus Down Bond
2029766091, // Exodus Down Gloves
2032811197, // Exodus Down Robes
2079454604, // Exodus Down Greaves
2218838661, // Exodus Down Robes
2359639520, // Exodus Down Robes
2426340791, // Unethical Experiments Mark
2528959426, // Exodus Down Boots
2731698402, // Exodus Down Hood
2736812653, // Exodus Down Helm
2811068561, // Exodus Down Hood
2816760678, // Exodus Down Greaves
3323553887, // Exodus Down Greaves
3536375792, // Exodus Down Bond
3545981149, // Exodus Down Boots
3617024265, // Exodus Down Boots
3654781892, // Exodus Down Plate
3660228214, // Exodus Down Hood
3742350309, // Exodus Down Boots
3754164794, // Exodus Down Mark
3855512540, // Exodus Down Gauntlets
3951684081, // Exodus Down Robes
3960258378, // Exodus Down Hood
4007396243, // Exodus Down Gloves
],
nightfall: [],
nightmare: [],
nm: [
25798127, // Sovereign Grips
106359434, // Coronation Mark
147165546, // Sovereign Legs
316745113, // Sovereign Hood
342618372, // Coronation Cloak
600401425, // Sovereign Boots
755928510, // Sovereign Mask
831738837, // Coronation Bond
1890693805, // Sovereign Gauntlets
2154427219, // Sovereign Plate
2436244536, // Sovereign Robes
2603069551, // Sovereign Greaves
3059968532, // Sovereign Helm
3323316553, // Sovereign Vest
4083497488, // Sovereign Gloves
],
pit: [],
presage: [],
prestige: [],
prophecy: [],
raid: [
4968701, // Greaves of the Great Hunt
11974904, // Greaves of Ascendancy
16387641, // Mark of the Great Hunt
17280095, // Shadow's Strides
30962015, // Boots of the Ace-Defiant
49280456, // Gloves of the Great Hunt
64543268, // Boots of the Emperor's Minister
64543269, // Boots of the Fulminator
65929376, // Gauntlets of the Great Hunt
146275556, // Vest of the Great Hunt
196235132, // Grips of the Great Hunt
223783885, // Insigne Shade Bond
239489770, // Bond of Sekris
253344425, // Mask of Feltroc
256904954, // Shadow's Grips
281660259, // Temptation's Mark
288406317, // Greaves of Rull
309687341, // Shadow's Greaves
311429765, // Mark of the Emperor's Champion
325125949, // Shadow's Helm
325434398, // Vest of the Ace-Defiant
325434399, // Vest of the Emperor's Agent
336656483, // Boots of the Emperor's Minister
340118991, // Boots of Sekris
350056552, // Bladesmith's Memory Mask
383742277, // Cloak of Feltroc
388999052, // Bulletsmith's Ire Mark
407863747, // Vest of the Ace-Defiant
455108040, // Helm of the Emperor's Champion
455108041, // Mask of Rull
503773817, // Insigne Shade Gloves
519078295, // Helm of Righteousness
548581042, // Insigne Shade Boots
557676195, // Cowl of Righteousness
560455272, // Penumbral Mark
574137192, // Shadow's Mark
576683388, // Gauntlets of the Great Hunt
581908796, // Bond of the Emperor's Minister
588627781, // Bond of Sekris
608074492, // Robes of the Emperor's Minister
608074493, // Robes of the Fulminator
612065993, // Penumbral Mark
618662448, // Headpiece of the Emperor's Minister
641933203, // Mask of the Emperor's Agent
666883012, // Gauntlets of Nohr
726265506, // Boots of the Great Hunt
748485514, // Mask of the Fulminator
748485515, // Headpiece of the Emperor's Minister
754149842, // Wraps of the Emperor's Minister
754149843, // Wraps of the Fulminator
776723133, // Robes of the Great Hunt
778784376, // Mark of the Great Hunt
796914932, // Mask of Sekris
802557885, // Turris Shade Gauntlets
821841934, // Bond of the Great Hunt
845536715, // Vest of Feltroc
853543290, // Greaves of Rull
853543291, // Greaves of the Emperor's Champion
855363300, // Turris Shade Helm
874272413, // Shadow's Robes
917591018, // Grips of the Ace-Defiant
917591019, // Gloves of the Emperor's Agent
972689703, // Vest of the Great Hunt
974648224, // Shadow's Boots
1021341893, // Mark of the Great Hunt
1034660314, // Boots of Feltroc
1108389626, // Gloves of the Emperor's Agent
1127835600, // Grips of the Great Hunt
1156439528, // Insigne Shade Cover
1190016345, // Mask of the Great Hunt
1195800715, // Boots of the Great Hunt
1230192769, // Robes of the Emperor's Minister
1242139836, // Plate of Nohr
1256688732, // Mask of Feltroc
1258342944, // Mask of the Great Hunt
1296628624, // Insigne Shade Robes
1314563129, // Cloak of the Great Hunt
1339632007, // Turris Shade Helm
1354679721, // Cloak of the Emperor's Agent
1390282760, // Chassis of Rull
1390282761, // Cuirass of the Emperor's Champion
1413589586, // Mask of Rull
1432728945, // Hood of the Great Hunt
1434870610, // Shadow's Helm
1444894250, // Strides of the Great Hunt
1457195686, // Shadow's Gloves
1477271933, // Bond of the Great Hunt
1481751647, // Shadow's Mind
1624906371, // Gunsmith's Devotion Crown
1646520469, // Cloak of the Great Hunt
1653741426, // Grips of Exaltation
1656835365, // Plate of the Great Hunt
1675393889, // Insigne Shade Cover
1756558505, // Mask of Sekris
1793869832, // Turris Shade Greaves
1862963733, // Shadow's Plate
1876645653, // Chassis of Rull
1879942843, // Gauntlets of Rull
1901223867, // Shadow's Gauntlets
1917693279, // Bladesmith's Memory Vest
1934647691, // Shadow's Mask
1937834292, // Shadow's Strides
1946621757, // Shadow's Grips
1960303677, // Grips of the Ace-Defiant
1991039861, // Mask of Nohr
1999427172, // Shadow's Mask
2013109092, // Helm of the Ace-Defiant
2015894615, // Gloves of Exaltation
2023695690, // Shadow's Robes
2054979724, // Strides of Ascendancy
2070062384, // Shadow's Bond
2070062385, // Bond of the Emperor's Minister
2112541750, // Cloak of the Great Hunt
2128823667, // Turris Shade Mark
2153222031, // Shadow's Gloves
2158603584, // Gauntlets of Rull
2158603585, // Gauntlets of the Emperor's Champion
2183861870, // Gauntlets of the Emperor's Champion
2193494688, // Boots of the Fulminator
2194479195, // Penumbral Bond
2232730708, // Vest of the Emperor's Agent
2274520361, // Helm of the Great Hunt
2280287728, // Bond of the Great Hunt
2320830625, // Robes of Transcendence
2329031091, // Robes of Sekris
2339720736, // Grips of Feltroc
2369496221, // Plate of Nohr
2513313400, // Insigne Shade Gloves
2530113265, // Bulletsmith's Ire Plate
2537874394, // Boots of Sekris
2550116544, // Robes of the Great Hunt
2552158692, // Equitis Shade Rig
2589473259, // Bladesmith's Memory Strides
2597529070, // Greaves of Nohr
2598685593, // Gloves of the Great Hunt
2620001759, // Insigne Shade Robes
2653039573, // Grips of Feltroc
2676042150, // Wraps of the Fulminator
2700598111, // Mask of the Fulminator
2710517999, // Equitis Shade Grips
2722103686, // Equitis Shade Boots
2758465168, // Greaves of the Emperor's Champion
2762445138, // Gunsmith's Devotion Gloves
2765688378, // Penumbral Cloak
2769298993, // Shadow's Boots
2868042232, // Vest of the Great Hunt
2878130185, // Bulletsmith's Ire Greaves
2904930850, // Turris Shade Plate
2913992255, // Helm of the Emperor's Champion
2921334134, // Bulletsmith's Ire Helm
2933666377, // Equitis Shade Rig
2950533187, // Strides of the Great Hunt
2976612200, // Vest of Feltroc
2994007601, // Mark of Nohr
3001934726, // Mask of Righteousness
3055836250, // Greaves of the Great Hunt
3066613133, // Equitis Shade Cowl
3082625196, // Shadow's Gauntlets
3092380260, // Mark of the Emperor's Champion
3092380261, // Shadow's Mark
3099636805, // Greaves of Nohr
3103335676, // Temptation's Bond
3108321700, // Penumbral Bond
3119383537, // Grips of the Great Hunt
3143067364, // Plate of the Great Hunt
3163683564, // Gunsmith's Devotion Boots
3164851950, // Bladesmith's Memory Cloak
3168183519, // Turris Shade Greaves
3181497704, // Robes of Sekris
3208178411, // Gauntlets of the Great Hunt
3227674085, // Boots of the Great Hunt
3251351304, // Hood of the Great Hunt
3285121297, // Equitis Shade Boots
3292127944, // Cuirass of the Emperor's Champion
3349283422, // Shadow's Mind
3359121706, // Mask of Nohr
3364682867, // Gauntlets of Nohr
3395856235, // Insigne Shade Boots
3416932282, // Turris Shade Mark
3440648382, // Equitis Shade Cowl
3445296383, // Robes of the Great Hunt
3445582154, // Hood of the Great Hunt
3483984579, // Shadow's Vest
3492720019, // Gloves of the Great Hunt
3494130310, // Strides of the Great Hunt
3497220322, // Cloak of Feltroc
3517729518, // Shadow's Vest
3518193943, // Penumbral Cloak
3530284425, // Wraps of the Emperor's Minister
3549177695, // Cloak of Temptation
3567761471, // Gunsmith's Devotion Bond
3581198350, // Turris Shade Gauntlets
3592548938, // Robes of the Fulminator
3614211816, // Plate of the Great Hunt
3711700026, // Mask of the Emperor's Agent
3711700027, // Helm of the Ace-Defiant
3719175804, // Equitis Shade Grips
3720446265, // Equitis Shade Cloak
3759659288, // Shadow's Plate
3763332443, // Shadow's Bond
3824429433, // Boots of Ascendancy
3831484112, // Mark of Nohr
3838639757, // Mask of the Great Hunt
3842934816, // Wraps of Sekris
3853397100, // Boots of the Emperor's Agent
3867160430, // Insigne Shade Bond
3868637058, // Helm of the Great Hunt
3874578566, // Greaves of the Great Hunt
3887559710, // Gauntlets of Exaltation
3939809874, // Plate of Transcendence
3950028838, // Cloak of the Emperor's Agent
3950028839, // Shadow's Cloak
3964287245, // Wraps of Sekris
3984534842, // Shadow's Cloak
3992358137, // Bladesmith's Memory Grips
4125324487, // Bulletsmith's Ire Gauntlets
4135228483, // Turris Shade Plate
4152814806, // Shadow's Greaves
4177973942, // Vest of Transcendence
4219088013, // Helm of the Great Hunt
4229161783, // Boots of Feltroc
4238134294, // Gunsmith's Devotion Robes
4247935492, // Equitis Shade Cloak
4251770244, // Boots of the Ace-Defiant
4251770245, // Boots of the Emperor's Agent
],
rasputin: [],
saint14: [],
scourge: [
350056552, // Bladesmith's Memory Mask
388999052, // Bulletsmith's Ire Mark
1624906371, // Gunsmith's Devotion Crown
1917693279, // Bladesmith's Memory Vest
2530113265, // Bulletsmith's Ire Plate
2589473259, // Bladesmith's Memory Strides
2762445138, // Gunsmith's Devotion Gloves
2878130185, // Bulletsmith's Ire Greaves
2921334134, // Bulletsmith's Ire Helm
3163683564, // Gunsmith's Devotion Boots
3164851950, // Bladesmith's Memory Cloak
3567761471, // Gunsmith's Devotion Bond
3992358137, // Bladesmith's Memory Grips
4125324487, // Bulletsmith's Ire Gauntlets
4238134294, // Gunsmith's Devotion Robes
],
seasonpass: [
1387688628, // The Gate Lord's Eye
],
servitor: [],
shatteredthrone: [],
shaxx: [
85800627, // Ankaa Seeker IV
98331691, // Binary Phoenix Mark
185853176, // Wing Discipline
252414402, // Swordflight 4.1
283188616, // Wing Contender
290136582, // Wing Theorem
327530279, // Wing Theorem
328902054, // Swordflight 4.1
356269375, // Wing Theorem
388771599, // Phoenix Strife Type 0
419812559, // Ankaa Seeker IV
438224459, // Wing Discipline
449878234, // Phoenix Strife Type 0
468899627, // Binary Phoenix Mark
530558102, // Phoenix Strife Type 0
636679949, // Ankaa Seeker IV
670877864, // Binary Phoenix Mark
727838174, // Swordflight 4.1
744199039, // Wing Contender
761953100, // Ankaa Seeker IV
820446170, // Phoenix Strife Type 0
849529384, // Phoenix Strife Type 0
874101646, // Wing Theorem
876608500, // Ankaa Seeker IV
920187221, // Wing Discipline
929917162, // Wing Theorem
997903134, // Wing Theorem
1036467370, // Wing Theorem
1062166003, // Wing Contender
1063904165, // Wing Discipline
1069887756, // Wing Contender
1071350799, // Binary Phoenix Cloak
1084033161, // Wing Contender
1127237110, // Wing Contender
1245115841, // Wing Theorem
1307478991, // Ankaa Seeker IV
1333087155, // Ankaa Seeker IV
1464207979, // Wing Discipline
1467590642, // Binary Phoenix Bond
1484937602, // Phoenix Strife Type 0
1548928853, // Phoenix Strife Type 0
1571781304, // Swordflight 4.1
1654427223, // Swordflight 4.1
1658896287, // Binary Phoenix Cloak
1673285051, // Wing Theorem
1716643851, // Wing Contender
1722623780, // Wing Discipline
1742680797, // Binary Phoenix Mark
1742940528, // Phoenix Strife Type 0
1764274932, // Ankaa Seeker IV
1801625827, // Swordflight 4.1
1830829330, // Swordflight 4.1
1838158578, // Binary Phoenix Bond
1838273186, // Wing Contender
1852468615, // Ankaa Seeker IV
1904811766, // Swordflight 4.1
1929596421, // Ankaa Seeker IV
2070517134, // Wing Contender
2124666626, // Wing Discipline
2191401041, // Phoenix Strife Type 0
2231762285, // Phoenix Strife Type 0
2291226602, // Binary Phoenix Bond
2293476915, // Swordflight 4.1
2296560252, // Swordflight 4.1
2296691422, // Swordflight 4.1
2323865727, // Wing Theorem
2331227463, // Wing Contender
2415711886, // Wing Contender
2426070307, // Binary Phoenix Cloak
2466453881, // Wing Discipline
2473130418, // Swordflight 4.1
2496309431, // Wing Discipline
2525395257, // Wing Theorem
2543903638, // Phoenix Strife Type 0
2555965565, // Wing Discipline
2670393359, // Phoenix Strife Type 0
2718495762, // Swordflight 4.1
2727890395, // Ankaa Seeker IV
2775298636, // Ankaa Seeker IV
2815422368, // Phoenix Strife Type 0
3089908066, // Wing Discipline
3098458331, // Ankaa Seeker IV
3119528729, // Wing Contender
3140634552, // Swordflight 4.1
3211001969, // Wing Contender
3223280471, // Swordflight 4.1
3298826188, // Swordflight 4.1
3313736739, // Binary Phoenix Cloak
3315265682, // Phoenix Strife Type 0
3483546829, // Wing Discipline
3522021318, // Wing Discipline
3538513130, // Binary Phoenix Bond
3724026171, // Wing Theorem
3756286064, // Phoenix Strife Type 0
3772194440, // Wing Contender
3781722107, // Phoenix Strife Type 0
3818803676, // Wing Discipline
3839561204, // Wing Theorem
4043980813, // Ankaa Seeker IV
4123918087, // Wing Contender
4134090375, // Ankaa Seeker IV
4136212668, // Wing Discipline
4144133120, // Wing Theorem
4211218181, // Ankaa Seeker IV
4264096388, // Wing Theorem
],
shipwright: [],
sos: [
223783885, // Insigne Shade Bond
503773817, // Insigne Shade Gloves
548581042, // Insigne Shade Boots
802557885, // Turris Shade Gauntlets
855363300, // Turris Shade Helm
1156439528, // Insigne Shade Cover
1296628624, // Insigne Shade Robes
1339632007, // Turris Shade Helm
1675393889, // Insigne Shade Cover
1793869832, // Turris Shade Greaves
2128823667, // Turris Shade Mark
2513313400, // Insigne Shade Gloves
2552158692, // Equitis Shade Rig
2620001759, // Insigne Shade Robes
2710517999, // Equitis Shade Grips
2722103686, // Equitis Shade Boots
2904930850, // Turris Shade Plate
2933666377, // Equitis Shade Rig
3066613133, // Equitis Shade Cowl
3168183519, // Turris Shade Greaves
3285121297, // Equitis Shade Boots
3395856235, // Insigne Shade Boots
3416932282, // Turris Shade Mark
3440648382, // Equitis Shade Cowl
3581198350, // Turris Shade Gauntlets
3719175804, // Equitis Shade Grips
3720446265, // Equitis Shade Cloak
3867160430, // Insigne Shade Bond
4135228483, // Turris Shade Plate
4247935492, // Equitis Shade Cloak
],
strikes: [
24244626, // Mark of Shelter
34846448, // Xenos Vale IV
335317194, // Vigil of Heroes
358599471, // Vigil of Heroes
406401261, // The Took Offense
413460498, // Xenos Vale IV
417061387, // Xenos Vale IV
420247988, // Xenos Vale IV
432360904, // Vigil of Heroes
506100699, // Vigil of Heroes
508642129, // Vigil of Heroes
575676771, // Vigil of Heroes
758026143, // Vigil of Heroes
799187478, // Vigil of Heroes
986111044, // Vigil of Heroes
1003941622, // Vigil of Heroes
1007759904, // Vigil of Heroes
1054960580, // Vigil of Heroes
1099472035, // The Took Offense
1130203390, // Vigil of Heroes
1188816597, // The Took Offense
1247181362, // Vigil of Heroes
1320081419, // The Shelter in Place
1405063395, // Vigil of Heroes
1490307366, // Vigil of Heroes
1514841742, // Mark of Shelter
1514863327, // Vigil of Heroes
1538362007, // Vigil of Heroes
1540376513, // Xenos Vale IV
1667528443, // The Shelter in Place
1699493316, // The Last Dance
1825880546, // The Took Offense
2011569904, // Vigil of Heroes
2060516289, // Vigil of Heroes
2072877132, // Vigil of Heroes
2076567986, // Vigil of Heroes
2304309360, // Vigil of Heroes
2337221567, // Vigil of Heroes
2378296024, // Xenos Vale IV
2422319309, // Vigil of Heroes
2442309039, // Vigil of Heroes
2460793798, // Vigil of Heroes
2592351697, // Vigil of Heroes
2671880779, // Vigil of Heroes
2722966297, // The Shelter in Place
2764938807, // The Took Offense
2902263756, // Vigil of Heroes
2939022735, // Vigil of Heroes
3027732901, // The Shelter in Place
3034285946, // Xenos Vale IV
3074985148, // Vigil of Heroes
3130904371, // Vigil of Heroes
3198744410, // The Took Offense
3213912958, // Vigil of Heroes
3215392301, // Xenos Vale Bond
3221304270, // Xenos Vale IV
3281314016, // The Took Offense
3375062567, // The Shelter in Place
3375632008, // The Shelter in Place
3469164235, // The Took Offense
3486485973, // The Took Offense
3499839403, // Vigil of Heroes
3500775049, // Vigil of Heroes
3544662820, // Vigil of Heroes
3569624585, // Vigil of Heroes
3584380110, // Vigil of Heroes
3666681446, // Vigil of Heroes
3670149407, // Vigil of Heroes
3851385946, // Vigil of Heroes
3873435116, // The Shelter in Place
3916064886, // Vigil of Heroes
3963753111, // Xenos Vale Bond
4024037919, // Origin Story
4074662489, // Vigil of Heroes
4087433052, // The Took Offense
4138296191, // The Shelter in Place
4288492921, // Vigil of Heroes
],
sundial: [],
tangled: [
177829853, // Scatterhorn Bond
218523139, // Scatterhorn Grasps
307138509, // Scatterhorn Vest
411850804, // Scatterhorn Wraps
694120634, // Scatterhorn Mark
699589438, // Scatterhorn Boots
902989307, // Scorned Baron Vest
1069453608, // Scatterhorn Wraps
1250571424, // Scatterhorn Robe
1347463276, // Scatterhorn Mark
1349281425, // Scorned Baron Plate
1407026808, // Torobatl Celebration Mask
1412416835, // Scatterhorn Plate
1467355683, // Scatterhorn Strides
1566911695, // Scorned Baron Plate
1636205905, // Scatterhorn Grasps
1704861826, // Scatterhorn Boots
1862088022, // Scatterhorn Helm
1863170823, // Scatterhorn Vest
1928007477, // Scorned Baron Vest
1989103583, // Scatterhorn Greaves
2007698582, // Torobatl Celebration Mask
2243444841, // Scatterhorn Greaves
2276115770, // Scatterhorn Mask
2411325265, // Scatterhorn Hood
2563857333, // Scatterhorn Strides
2571396481, // Scatterhorn Bond
2757593792, // Scatterhorn Cloak
2932919026, // Nea-Thonis Breather
2944336620, // Nea-Thonis Breather
3044599574, // Scatterhorn Cloak
3066181671, // Scatterhorn Gauntlets
3183089352, // Scorned Baron Robes
3523809305, // Eimin-Tin Ritual Mask
3858472841, // Eimin-Tin Ritual Mask
3871458129, // Scatterhorn Plate
3918445245, // Scatterhorn Gauntlets
3926141285, // Scatterhorn Hood
3971250660, // Scatterhorn Helm
4070132608, // Scatterhorn Mask
4167605324, // Scatterhorn Robe
4245441464, // Scorned Baron Robes
],
titan: [
1701005142, // Songbreaker Gloves
2486041713, // Songbreaker Gauntlets
3706457515, // Songbreaker Grips
],
trials: [
72827962, // Focusing Robes
142864314, // Bond of the Exile
150551028, // Boots of the Exile
155955678, // Mark Relentless
272735286, // Greaves of the Exile
421771594, // Cloak Relentless
442736573, // Gloves of the Exile
495541988, // Hood of the Exile
571925067, // Cover of the Exile
686607149, // Focusing Cowl
773318267, // Floating Vest
784751927, // Annihilating Plate
861160515, // Robe of the Exile
875395086, // Vest of the Exile
945907383, // Floating Grips
1164471069, // Helm of the Exile
1193489623, // Cloak of the Exile
1929400866, // Annihilating Helm
2158289681, // Floating Boots
2579999316, // Plate of the Exile
2764588986, // Grips of the Exile
2808362207, // Legs of the Exile
3025466099, // Annihilating Guard
3127319342, // Floating Cowl
3149072083, // Bond Relentless
3365406121, // Mark of the Exile
3426704397, // Annihilating Greaves
3921970316, // Gauntlets of the Exile
4100217958, // Focusing Boots
4177448932, // Focusing Wraps
],
umbral: [],
vexoffensive: [],
vog: [],
wartable: [],
wrathborn: [],
zavala: [
24244626, // Mark of Shelter
34846448, // Xenos Vale IV
335317194, // Vigil of Heroes
358599471, // Vigil of Heroes
406401261, // The Took Offense
413460498, // Xenos Vale IV
417061387, // Xenos Vale IV
420247988, // Xenos Vale IV
432360904, // Vigil of Heroes
506100699, // Vigil of Heroes
508642129, // Vigil of Heroes
575676771, // Vigil of Heroes
758026143, // Vigil of Heroes
799187478, // Vigil of Heroes
986111044, // Vigil of Heroes
1003941622, // Vigil of Heroes
1007759904, // Vigil of Heroes
1054960580, // Vigil of Heroes
1099472035, // The Took Offense
1130203390, // Vigil of Heroes
1188816597, // The Took Offense
1247181362, // Vigil of Heroes
1320081419, // The Shelter in Place
1405063395, // Vigil of Heroes
1490307366, // Vigil of Heroes
1514841742, // Mark of Shelter
1514863327, // Vigil of Heroes
1538362007, // Vigil of Heroes
1540376513, // Xenos Vale IV
1667528443, // The Shelter in Place
1699493316, // The Last Dance
1825880546, // The Took Offense
2011569904, // Vigil of Heroes
2060516289, // Vigil of Heroes
2072877132, // Vigil of Heroes
2076567986, // Vigil of Heroes
2304309360, // Vigil of Heroes
2337221567, // Vigil of Heroes
2378296024, // Xenos Vale IV
2422319309, // Vigil of Heroes
2442309039, // Vigil of Heroes
2460793798, // Vigil of Heroes
2592351697, // Vigil of Heroes
2671880779, // Vigil of Heroes
2722966297, // The Shelter in Place
2764938807, // The Took Offense
2902263756, // Vigil of Heroes
2939022735, // Vigil of Heroes
3027732901, // The Shelter in Place
3034285946, // Xenos Vale IV
3074985148, // Vigil of Heroes
3130904371, // Vigil of Heroes
3198744410, // The Took Offense
3213912958, // Vigil of Heroes
3215392301, // Xenos Vale Bond
3221304270, // Xenos Vale IV
3281314016, // The Took Offense
3375062567, // The Shelter in Place
3375632008, // The Shelter in Place
3469164235, // The Took Offense
3486485973, // The Took Offense
3499839403, // Vigil of Heroes
3500775049, // Vigil of Heroes
3544662820, // Vigil of Heroes
3569624585, // Vigil of Heroes
3584380110, // Vigil of Heroes
3666681446, // Vigil of Heroes
3670149407, // Vigil of Heroes
3851385946, // Vigil of Heroes
3873435116, // The Shelter in Place
3916064886, // Vigil of Heroes
3963753111, // Xenos Vale Bond
4024037919, // Origin Story
4074662489, // Vigil of Heroes
4087433052, // The Took Offense
4138296191, // The Shelter in Place
4288492921, // Vigil of Heroes
],
};
export default missingSources; | the_stack |
import { gql } from '@apollo/client';
import * as Apollo from '@apollo/client';
export type Maybe<T> = T | null;
export type Exact<T extends { [key: string]: unknown }> = { [K in keyof T]: T[K] };
export type MakeOptional<T, K extends keyof T> = Omit<T, K> & { [SubKey in K]?: Maybe<T[SubKey]> };
export type MakeMaybe<T, K extends keyof T> = Omit<T, K> & { [SubKey in K]: Maybe<T[SubKey]> };
/** All built-in and custom scalars, mapped to their actual values */
export type Scalars = {
ID: string;
String: string;
Boolean: boolean;
Int: number;
Float: number;
bigint: any;
timestamptz: any;
uuid: any;
};
/** expression to compare columns of type bigint. All fields are combined with logical 'AND'. */
export type Bigint_Comparison_Exp = {
_eq?: Maybe<Scalars['bigint']>;
_gt?: Maybe<Scalars['bigint']>;
_gte?: Maybe<Scalars['bigint']>;
_in?: Maybe<Array<Maybe<Scalars['bigint']>>>;
_is_null?: Maybe<Scalars['Boolean']>;
_lt?: Maybe<Scalars['bigint']>;
_lte?: Maybe<Scalars['bigint']>;
_neq?: Maybe<Scalars['bigint']>;
_nin?: Maybe<Array<Maybe<Scalars['bigint']>>>;
};
/** expression to compare columns of type boolean. All fields are combined with logical 'AND'. */
export type Boolean_Comparison_Exp = {
_eq?: Maybe<Scalars['Boolean']>;
_gt?: Maybe<Scalars['Boolean']>;
_gte?: Maybe<Scalars['Boolean']>;
_in?: Maybe<Array<Maybe<Scalars['Boolean']>>>;
_is_null?: Maybe<Scalars['Boolean']>;
_lt?: Maybe<Scalars['Boolean']>;
_lte?: Maybe<Scalars['Boolean']>;
_neq?: Maybe<Scalars['Boolean']>;
_nin?: Maybe<Array<Maybe<Scalars['Boolean']>>>;
};
/** conflict action */
export enum Conflict_Action {
/** ignore the insert on this row */
Ignore = 'ignore',
/** update the row with the given values */
Update = 'update'
}
/** expression to compare columns of type integer. All fields are combined with logical 'AND'. */
export type Integer_Comparison_Exp = {
_eq?: Maybe<Scalars['Int']>;
_gt?: Maybe<Scalars['Int']>;
_gte?: Maybe<Scalars['Int']>;
_in?: Maybe<Array<Maybe<Scalars['Int']>>>;
_is_null?: Maybe<Scalars['Boolean']>;
_lt?: Maybe<Scalars['Int']>;
_lte?: Maybe<Scalars['Int']>;
_neq?: Maybe<Scalars['Int']>;
_nin?: Maybe<Array<Maybe<Scalars['Int']>>>;
};
/** mutation root */
export type Mutation_Root = {
__typename?: 'mutation_root';
/** delete data from the table: "riders" */
delete_riders?: Maybe<Riders_Mutation_Response>;
/** delete data from the table: "tb_cliente" */
delete_tb_cliente?: Maybe<Tb_Cliente_Mutation_Response>;
/** delete data from the table: "vehicle" */
delete_vehicle?: Maybe<Vehicle_Mutation_Response>;
/** delete data from the table: "vehicle_location" */
delete_vehicle_location?: Maybe<Vehicle_Location_Mutation_Response>;
/** insert data into the table: "riders" */
insert_riders?: Maybe<Riders_Mutation_Response>;
/** insert data into the table: "tb_cliente" */
insert_tb_cliente?: Maybe<Tb_Cliente_Mutation_Response>;
/** insert data into the table: "vehicle" */
insert_vehicle?: Maybe<Vehicle_Mutation_Response>;
/** insert data into the table: "vehicle_location" */
insert_vehicle_location?: Maybe<Vehicle_Location_Mutation_Response>;
/** update data of the table: "riders" */
update_riders?: Maybe<Riders_Mutation_Response>;
/** update data of the table: "tb_cliente" */
update_tb_cliente?: Maybe<Tb_Cliente_Mutation_Response>;
/** update data of the table: "vehicle" */
update_vehicle?: Maybe<Vehicle_Mutation_Response>;
/** update data of the table: "vehicle_location" */
update_vehicle_location?: Maybe<Vehicle_Location_Mutation_Response>;
};
/** mutation root */
export type Mutation_RootDelete_RidersArgs = {
where: Riders_Bool_Exp;
};
/** mutation root */
export type Mutation_RootDelete_Tb_ClienteArgs = {
where: Tb_Cliente_Bool_Exp;
};
/** mutation root */
export type Mutation_RootDelete_VehicleArgs = {
where: Vehicle_Bool_Exp;
};
/** mutation root */
export type Mutation_RootDelete_Vehicle_LocationArgs = {
where: Vehicle_Location_Bool_Exp;
};
/** mutation root */
export type Mutation_RootInsert_RidersArgs = {
objects: Array<Riders_Insert_Input>;
on_conflict?: Maybe<Riders_On_Conflict>;
};
/** mutation root */
export type Mutation_RootInsert_Tb_ClienteArgs = {
objects: Array<Tb_Cliente_Insert_Input>;
on_conflict?: Maybe<Tb_Cliente_On_Conflict>;
};
/** mutation root */
export type Mutation_RootInsert_VehicleArgs = {
objects: Array<Vehicle_Insert_Input>;
on_conflict?: Maybe<Vehicle_On_Conflict>;
};
/** mutation root */
export type Mutation_RootInsert_Vehicle_LocationArgs = {
objects: Array<Vehicle_Location_Insert_Input>;
on_conflict?: Maybe<Vehicle_Location_On_Conflict>;
};
/** mutation root */
export type Mutation_RootUpdate_RidersArgs = {
_inc?: Maybe<Riders_Inc_Input>;
_set?: Maybe<Riders_Set_Input>;
where: Riders_Bool_Exp;
};
/** mutation root */
export type Mutation_RootUpdate_Tb_ClienteArgs = {
_inc?: Maybe<Tb_Cliente_Inc_Input>;
_set?: Maybe<Tb_Cliente_Set_Input>;
where: Tb_Cliente_Bool_Exp;
};
/** mutation root */
export type Mutation_RootUpdate_VehicleArgs = {
_inc?: Maybe<Vehicle_Inc_Input>;
_set?: Maybe<Vehicle_Set_Input>;
where: Vehicle_Bool_Exp;
};
/** mutation root */
export type Mutation_RootUpdate_Vehicle_LocationArgs = {
_inc?: Maybe<Vehicle_Location_Inc_Input>;
_set?: Maybe<Vehicle_Location_Set_Input>;
where: Vehicle_Location_Bool_Exp;
};
/** column ordering options */
export enum Order_By {
/** in the ascending order, nulls last */
Asc = 'asc',
/** in the ascending order, nulls first */
AscNullsFirst = 'asc_nulls_first',
/** in the ascending order, nulls last */
AscNullsLast = 'asc_nulls_last',
/** in the descending order, nulls first */
Desc = 'desc',
/** in the descending order, nulls first */
DescNullsFirst = 'desc_nulls_first',
/** in the descending order, nulls last */
DescNullsLast = 'desc_nulls_last'
}
/** query root */
export type Query_Root = {
__typename?: 'query_root';
/** fetch data from the table: "riders" */
riders: Array<Riders>;
/** fetch aggregated fields from the table: "riders" */
riders_aggregate: Riders_Aggregate;
/** fetch data from the table: "riders" using primary key columns */
riders_by_pk?: Maybe<Riders>;
/** fetch data from the table: "tb_cliente" */
tb_cliente: Array<Tb_Cliente>;
/** fetch aggregated fields from the table: "tb_cliente" */
tb_cliente_aggregate: Tb_Cliente_Aggregate;
/** fetch data from the table: "tb_cliente" using primary key columns */
tb_cliente_by_pk?: Maybe<Tb_Cliente>;
/** fetch data from the table: "vehicle" */
vehicle: Array<Vehicle>;
/** fetch aggregated fields from the table: "vehicle" */
vehicle_aggregate: Vehicle_Aggregate;
/** fetch data from the table: "vehicle" using primary key columns */
vehicle_by_pk?: Maybe<Vehicle>;
/** fetch data from the table: "vehicle_location" */
vehicle_location: Array<Vehicle_Location>;
/** fetch aggregated fields from the table: "vehicle_location" */
vehicle_location_aggregate: Vehicle_Location_Aggregate;
/** fetch data from the table: "vehicle_location" using primary key columns */
vehicle_location_by_pk?: Maybe<Vehicle_Location>;
};
/** query root */
export type Query_RootRidersArgs = {
distinct_on?: Maybe<Array<Riders_Select_Column>>;
limit?: Maybe<Scalars['Int']>;
offset?: Maybe<Scalars['Int']>;
order_by?: Maybe<Array<Riders_Order_By>>;
where?: Maybe<Riders_Bool_Exp>;
};
/** query root */
export type Query_RootRiders_AggregateArgs = {
distinct_on?: Maybe<Array<Riders_Select_Column>>;
limit?: Maybe<Scalars['Int']>;
offset?: Maybe<Scalars['Int']>;
order_by?: Maybe<Array<Riders_Order_By>>;
where?: Maybe<Riders_Bool_Exp>;
};
/** query root */
export type Query_RootRiders_By_PkArgs = {
id: Scalars['Int'];
};
/** query root */
export type Query_RootTb_ClienteArgs = {
distinct_on?: Maybe<Array<Tb_Cliente_Select_Column>>;
limit?: Maybe<Scalars['Int']>;
offset?: Maybe<Scalars['Int']>;
order_by?: Maybe<Array<Tb_Cliente_Order_By>>;
where?: Maybe<Tb_Cliente_Bool_Exp>;
};
/** query root */
export type Query_RootTb_Cliente_AggregateArgs = {
distinct_on?: Maybe<Array<Tb_Cliente_Select_Column>>;
limit?: Maybe<Scalars['Int']>;
offset?: Maybe<Scalars['Int']>;
order_by?: Maybe<Array<Tb_Cliente_Order_By>>;
where?: Maybe<Tb_Cliente_Bool_Exp>;
};
/** query root */
export type Query_RootTb_Cliente_By_PkArgs = {
id_cliente: Scalars['bigint'];
};
/** query root */
export type Query_RootVehicleArgs = {
distinct_on?: Maybe<Array<Vehicle_Select_Column>>;
limit?: Maybe<Scalars['Int']>;
offset?: Maybe<Scalars['Int']>;
order_by?: Maybe<Array<Vehicle_Order_By>>;
where?: Maybe<Vehicle_Bool_Exp>;
};
/** query root */
export type Query_RootVehicle_AggregateArgs = {
distinct_on?: Maybe<Array<Vehicle_Select_Column>>;
limit?: Maybe<Scalars['Int']>;
offset?: Maybe<Scalars['Int']>;
order_by?: Maybe<Array<Vehicle_Order_By>>;
where?: Maybe<Vehicle_Bool_Exp>;
};
/** query root */
export type Query_RootVehicle_By_PkArgs = {
id: Scalars['String'];
};
/** query root */
export type Query_RootVehicle_LocationArgs = {
distinct_on?: Maybe<Array<Vehicle_Location_Select_Column>>;
limit?: Maybe<Scalars['Int']>;
offset?: Maybe<Scalars['Int']>;
order_by?: Maybe<Array<Vehicle_Location_Order_By>>;
where?: Maybe<Vehicle_Location_Bool_Exp>;
};
/** query root */
export type Query_RootVehicle_Location_AggregateArgs = {
distinct_on?: Maybe<Array<Vehicle_Location_Select_Column>>;
limit?: Maybe<Scalars['Int']>;
offset?: Maybe<Scalars['Int']>;
order_by?: Maybe<Array<Vehicle_Location_Order_By>>;
where?: Maybe<Vehicle_Location_Bool_Exp>;
};
/** query root */
export type Query_RootVehicle_Location_By_PkArgs = {
id: Scalars['Int'];
};
/** columns and relationships of "riders" */
export type Riders = {
__typename?: 'riders';
address: Scalars['String'];
created_at: Scalars['timestamptz'];
email: Scalars['String'];
id: Scalars['Int'];
is_active: Scalars['Boolean'];
name: Scalars['String'];
phone: Scalars['String'];
updated_at: Scalars['timestamptz'];
vehicle_id?: Maybe<Scalars['String']>;
};
/** aggregated selection of "riders" */
export type Riders_Aggregate = {
__typename?: 'riders_aggregate';
aggregate?: Maybe<Riders_Aggregate_Fields>;
nodes: Array<Riders>;
};
/** aggregate fields of "riders" */
export type Riders_Aggregate_Fields = {
__typename?: 'riders_aggregate_fields';
avg?: Maybe<Riders_Avg_Fields>;
count?: Maybe<Scalars['Int']>;
max?: Maybe<Riders_Max_Fields>;
min?: Maybe<Riders_Min_Fields>;
stddev?: Maybe<Riders_Stddev_Fields>;
stddev_pop?: Maybe<Riders_Stddev_Pop_Fields>;
stddev_samp?: Maybe<Riders_Stddev_Samp_Fields>;
sum?: Maybe<Riders_Sum_Fields>;
var_pop?: Maybe<Riders_Var_Pop_Fields>;
var_samp?: Maybe<Riders_Var_Samp_Fields>;
variance?: Maybe<Riders_Variance_Fields>;
};
/** aggregate fields of "riders" */
export type Riders_Aggregate_FieldsCountArgs = {
columns?: Maybe<Array<Riders_Select_Column>>;
distinct?: Maybe<Scalars['Boolean']>;
};
/** order by aggregate values of table "riders" */
export type Riders_Aggregate_Order_By = {
avg?: Maybe<Riders_Avg_Order_By>;
count?: Maybe<Order_By>;
max?: Maybe<Riders_Max_Order_By>;
min?: Maybe<Riders_Min_Order_By>;
stddev?: Maybe<Riders_Stddev_Order_By>;
stddev_pop?: Maybe<Riders_Stddev_Pop_Order_By>;
stddev_samp?: Maybe<Riders_Stddev_Samp_Order_By>;
sum?: Maybe<Riders_Sum_Order_By>;
var_pop?: Maybe<Riders_Var_Pop_Order_By>;
var_samp?: Maybe<Riders_Var_Samp_Order_By>;
variance?: Maybe<Riders_Variance_Order_By>;
};
/** input type for inserting array relation for remote table "riders" */
export type Riders_Arr_Rel_Insert_Input = {
data: Array<Riders_Insert_Input>;
on_conflict?: Maybe<Riders_On_Conflict>;
};
/** aggregate avg on columns */
export type Riders_Avg_Fields = {
__typename?: 'riders_avg_fields';
id?: Maybe<Scalars['Float']>;
};
/** order by avg() on columns of table "riders" */
export type Riders_Avg_Order_By = {
id?: Maybe<Order_By>;
};
/** Boolean expression to filter rows from the table "riders". All fields are combined with a logical 'AND'. */
export type Riders_Bool_Exp = {
_and?: Maybe<Array<Maybe<Riders_Bool_Exp>>>;
_not?: Maybe<Riders_Bool_Exp>;
_or?: Maybe<Array<Maybe<Riders_Bool_Exp>>>;
address?: Maybe<Text_Comparison_Exp>;
created_at?: Maybe<Timestamptz_Comparison_Exp>;
email?: Maybe<Text_Comparison_Exp>;
id?: Maybe<Integer_Comparison_Exp>;
is_active?: Maybe<Boolean_Comparison_Exp>;
name?: Maybe<Text_Comparison_Exp>;
phone?: Maybe<Text_Comparison_Exp>;
updated_at?: Maybe<Timestamptz_Comparison_Exp>;
vehicle_id?: Maybe<Text_Comparison_Exp>;
};
/** unique or primary key constraints on table "riders" */
export enum Riders_Constraint {
/** unique or primary key constraint */
RidersPkey = 'riders_pkey',
/** unique or primary key constraint */
RidersVehicleIdKey = 'riders_vehicle_id_key'
}
/** input type for incrementing integer columne in table "riders" */
export type Riders_Inc_Input = {
id?: Maybe<Scalars['Int']>;
};
/** input type for inserting data into table "riders" */
export type Riders_Insert_Input = {
address?: Maybe<Scalars['String']>;
created_at?: Maybe<Scalars['timestamptz']>;
email?: Maybe<Scalars['String']>;
id?: Maybe<Scalars['Int']>;
is_active?: Maybe<Scalars['Boolean']>;
name?: Maybe<Scalars['String']>;
phone?: Maybe<Scalars['String']>;
updated_at?: Maybe<Scalars['timestamptz']>;
vehicle_id?: Maybe<Scalars['String']>;
};
/** aggregate max on columns */
export type Riders_Max_Fields = {
__typename?: 'riders_max_fields';
address?: Maybe<Scalars['String']>;
created_at?: Maybe<Scalars['timestamptz']>;
email?: Maybe<Scalars['String']>;
id?: Maybe<Scalars['Int']>;
name?: Maybe<Scalars['String']>;
phone?: Maybe<Scalars['String']>;
updated_at?: Maybe<Scalars['timestamptz']>;
vehicle_id?: Maybe<Scalars['String']>;
};
/** order by max() on columns of table "riders" */
export type Riders_Max_Order_By = {
address?: Maybe<Order_By>;
created_at?: Maybe<Order_By>;
email?: Maybe<Order_By>;
id?: Maybe<Order_By>;
name?: Maybe<Order_By>;
phone?: Maybe<Order_By>;
updated_at?: Maybe<Order_By>;
vehicle_id?: Maybe<Order_By>;
};
/** aggregate min on columns */
export type Riders_Min_Fields = {
__typename?: 'riders_min_fields';
address?: Maybe<Scalars['String']>;
created_at?: Maybe<Scalars['timestamptz']>;
email?: Maybe<Scalars['String']>;
id?: Maybe<Scalars['Int']>;
name?: Maybe<Scalars['String']>;
phone?: Maybe<Scalars['String']>;
updated_at?: Maybe<Scalars['timestamptz']>;
vehicle_id?: Maybe<Scalars['String']>;
};
/** order by min() on columns of table "riders" */
export type Riders_Min_Order_By = {
address?: Maybe<Order_By>;
created_at?: Maybe<Order_By>;
email?: Maybe<Order_By>;
id?: Maybe<Order_By>;
name?: Maybe<Order_By>;
phone?: Maybe<Order_By>;
updated_at?: Maybe<Order_By>;
vehicle_id?: Maybe<Order_By>;
};
/** response of any mutation on the table "riders" */
export type Riders_Mutation_Response = {
__typename?: 'riders_mutation_response';
/** number of affected rows by the mutation */
affected_rows: Scalars['Int'];
/** data of the affected rows by the mutation */
returning: Array<Riders>;
};
/** input type for inserting object relation for remote table "riders" */
export type Riders_Obj_Rel_Insert_Input = {
data: Riders_Insert_Input;
on_conflict?: Maybe<Riders_On_Conflict>;
};
/** on conflict condition type for table "riders" */
export type Riders_On_Conflict = {
constraint: Riders_Constraint;
update_columns: Array<Riders_Update_Column>;
};
/** ordering options when selecting data from "riders" */
export type Riders_Order_By = {
address?: Maybe<Order_By>;
created_at?: Maybe<Order_By>;
email?: Maybe<Order_By>;
id?: Maybe<Order_By>;
is_active?: Maybe<Order_By>;
name?: Maybe<Order_By>;
phone?: Maybe<Order_By>;
updated_at?: Maybe<Order_By>;
vehicle_id?: Maybe<Order_By>;
};
/** select columns of table "riders" */
export enum Riders_Select_Column {
/** column name */
Address = 'address',
/** column name */
CreatedAt = 'created_at',
/** column name */
Email = 'email',
/** column name */
Id = 'id',
/** column name */
IsActive = 'is_active',
/** column name */
Name = 'name',
/** column name */
Phone = 'phone',
/** column name */
UpdatedAt = 'updated_at',
/** column name */
VehicleId = 'vehicle_id'
}
/** input type for updating data in table "riders" */
export type Riders_Set_Input = {
address?: Maybe<Scalars['String']>;
created_at?: Maybe<Scalars['timestamptz']>;
email?: Maybe<Scalars['String']>;
id?: Maybe<Scalars['Int']>;
is_active?: Maybe<Scalars['Boolean']>;
name?: Maybe<Scalars['String']>;
phone?: Maybe<Scalars['String']>;
updated_at?: Maybe<Scalars['timestamptz']>;
vehicle_id?: Maybe<Scalars['String']>;
};
/** aggregate stddev on columns */
export type Riders_Stddev_Fields = {
__typename?: 'riders_stddev_fields';
id?: Maybe<Scalars['Float']>;
};
/** order by stddev() on columns of table "riders" */
export type Riders_Stddev_Order_By = {
id?: Maybe<Order_By>;
};
/** aggregate stddev_pop on columns */
export type Riders_Stddev_Pop_Fields = {
__typename?: 'riders_stddev_pop_fields';
id?: Maybe<Scalars['Float']>;
};
/** order by stddev_pop() on columns of table "riders" */
export type Riders_Stddev_Pop_Order_By = {
id?: Maybe<Order_By>;
};
/** aggregate stddev_samp on columns */
export type Riders_Stddev_Samp_Fields = {
__typename?: 'riders_stddev_samp_fields';
id?: Maybe<Scalars['Float']>;
};
/** order by stddev_samp() on columns of table "riders" */
export type Riders_Stddev_Samp_Order_By = {
id?: Maybe<Order_By>;
};
/** aggregate sum on columns */
export type Riders_Sum_Fields = {
__typename?: 'riders_sum_fields';
id?: Maybe<Scalars['Int']>;
};
/** order by sum() on columns of table "riders" */
export type Riders_Sum_Order_By = {
id?: Maybe<Order_By>;
};
/** update columns of table "riders" */
export enum Riders_Update_Column {
/** column name */
Address = 'address',
/** column name */
CreatedAt = 'created_at',
/** column name */
Email = 'email',
/** column name */
Id = 'id',
/** column name */
IsActive = 'is_active',
/** column name */
Name = 'name',
/** column name */
Phone = 'phone',
/** column name */
UpdatedAt = 'updated_at',
/** column name */
VehicleId = 'vehicle_id'
}
/** aggregate var_pop on columns */
export type Riders_Var_Pop_Fields = {
__typename?: 'riders_var_pop_fields';
id?: Maybe<Scalars['Float']>;
};
/** order by var_pop() on columns of table "riders" */
export type Riders_Var_Pop_Order_By = {
id?: Maybe<Order_By>;
};
/** aggregate var_samp on columns */
export type Riders_Var_Samp_Fields = {
__typename?: 'riders_var_samp_fields';
id?: Maybe<Scalars['Float']>;
};
/** order by var_samp() on columns of table "riders" */
export type Riders_Var_Samp_Order_By = {
id?: Maybe<Order_By>;
};
/** aggregate variance on columns */
export type Riders_Variance_Fields = {
__typename?: 'riders_variance_fields';
id?: Maybe<Scalars['Float']>;
};
/** order by variance() on columns of table "riders" */
export type Riders_Variance_Order_By = {
id?: Maybe<Order_By>;
};
/** subscription root */
export type Subscription_Root = {
__typename?: 'subscription_root';
/** fetch data from the table: "riders" */
riders: Array<Riders>;
/** fetch aggregated fields from the table: "riders" */
riders_aggregate: Riders_Aggregate;
/** fetch data from the table: "riders" using primary key columns */
riders_by_pk?: Maybe<Riders>;
/** fetch data from the table: "tb_cliente" */
tb_cliente: Array<Tb_Cliente>;
/** fetch aggregated fields from the table: "tb_cliente" */
tb_cliente_aggregate: Tb_Cliente_Aggregate;
/** fetch data from the table: "tb_cliente" using primary key columns */
tb_cliente_by_pk?: Maybe<Tb_Cliente>;
/** fetch data from the table: "vehicle" */
vehicle: Array<Vehicle>;
/** fetch aggregated fields from the table: "vehicle" */
vehicle_aggregate: Vehicle_Aggregate;
/** fetch data from the table: "vehicle" using primary key columns */
vehicle_by_pk?: Maybe<Vehicle>;
/** fetch data from the table: "vehicle_location" */
vehicle_location: Array<Vehicle_Location>;
/** fetch aggregated fields from the table: "vehicle_location" */
vehicle_location_aggregate: Vehicle_Location_Aggregate;
/** fetch data from the table: "vehicle_location" using primary key columns */
vehicle_location_by_pk?: Maybe<Vehicle_Location>;
};
/** subscription root */
export type Subscription_RootRidersArgs = {
distinct_on?: Maybe<Array<Riders_Select_Column>>;
limit?: Maybe<Scalars['Int']>;
offset?: Maybe<Scalars['Int']>;
order_by?: Maybe<Array<Riders_Order_By>>;
where?: Maybe<Riders_Bool_Exp>;
};
/** subscription root */
export type Subscription_RootRiders_AggregateArgs = {
distinct_on?: Maybe<Array<Riders_Select_Column>>;
limit?: Maybe<Scalars['Int']>;
offset?: Maybe<Scalars['Int']>;
order_by?: Maybe<Array<Riders_Order_By>>;
where?: Maybe<Riders_Bool_Exp>;
};
/** subscription root */
export type Subscription_RootRiders_By_PkArgs = {
id: Scalars['Int'];
};
/** subscription root */
export type Subscription_RootTb_ClienteArgs = {
distinct_on?: Maybe<Array<Tb_Cliente_Select_Column>>;
limit?: Maybe<Scalars['Int']>;
offset?: Maybe<Scalars['Int']>;
order_by?: Maybe<Array<Tb_Cliente_Order_By>>;
where?: Maybe<Tb_Cliente_Bool_Exp>;
};
/** subscription root */
export type Subscription_RootTb_Cliente_AggregateArgs = {
distinct_on?: Maybe<Array<Tb_Cliente_Select_Column>>;
limit?: Maybe<Scalars['Int']>;
offset?: Maybe<Scalars['Int']>;
order_by?: Maybe<Array<Tb_Cliente_Order_By>>;
where?: Maybe<Tb_Cliente_Bool_Exp>;
};
/** subscription root */
export type Subscription_RootTb_Cliente_By_PkArgs = {
id_cliente: Scalars['bigint'];
};
/** subscription root */
export type Subscription_RootVehicleArgs = {
distinct_on?: Maybe<Array<Vehicle_Select_Column>>;
limit?: Maybe<Scalars['Int']>;
offset?: Maybe<Scalars['Int']>;
order_by?: Maybe<Array<Vehicle_Order_By>>;
where?: Maybe<Vehicle_Bool_Exp>;
};
/** subscription root */
export type Subscription_RootVehicle_AggregateArgs = {
distinct_on?: Maybe<Array<Vehicle_Select_Column>>;
limit?: Maybe<Scalars['Int']>;
offset?: Maybe<Scalars['Int']>;
order_by?: Maybe<Array<Vehicle_Order_By>>;
where?: Maybe<Vehicle_Bool_Exp>;
};
/** subscription root */
export type Subscription_RootVehicle_By_PkArgs = {
id: Scalars['String'];
};
/** subscription root */
export type Subscription_RootVehicle_LocationArgs = {
distinct_on?: Maybe<Array<Vehicle_Location_Select_Column>>;
limit?: Maybe<Scalars['Int']>;
offset?: Maybe<Scalars['Int']>;
order_by?: Maybe<Array<Vehicle_Location_Order_By>>;
where?: Maybe<Vehicle_Location_Bool_Exp>;
};
/** subscription root */
export type Subscription_RootVehicle_Location_AggregateArgs = {
distinct_on?: Maybe<Array<Vehicle_Location_Select_Column>>;
limit?: Maybe<Scalars['Int']>;
offset?: Maybe<Scalars['Int']>;
order_by?: Maybe<Array<Vehicle_Location_Order_By>>;
where?: Maybe<Vehicle_Location_Bool_Exp>;
};
/** subscription root */
export type Subscription_RootVehicle_Location_By_PkArgs = {
id: Scalars['Int'];
};
/** columns and relationships of "tb_cliente" */
export type Tb_Cliente = {
__typename?: 'tb_cliente';
email: Scalars['String'];
id_cliente: Scalars['bigint'];
identificador: Scalars['uuid'];
nome: Scalars['String'];
status: Scalars['Int'];
};
/** aggregated selection of "tb_cliente" */
export type Tb_Cliente_Aggregate = {
__typename?: 'tb_cliente_aggregate';
aggregate?: Maybe<Tb_Cliente_Aggregate_Fields>;
nodes: Array<Tb_Cliente>;
};
/** aggregate fields of "tb_cliente" */
export type Tb_Cliente_Aggregate_Fields = {
__typename?: 'tb_cliente_aggregate_fields';
avg?: Maybe<Tb_Cliente_Avg_Fields>;
count?: Maybe<Scalars['Int']>;
max?: Maybe<Tb_Cliente_Max_Fields>;
min?: Maybe<Tb_Cliente_Min_Fields>;
stddev?: Maybe<Tb_Cliente_Stddev_Fields>;
stddev_pop?: Maybe<Tb_Cliente_Stddev_Pop_Fields>;
stddev_samp?: Maybe<Tb_Cliente_Stddev_Samp_Fields>;
sum?: Maybe<Tb_Cliente_Sum_Fields>;
var_pop?: Maybe<Tb_Cliente_Var_Pop_Fields>;
var_samp?: Maybe<Tb_Cliente_Var_Samp_Fields>;
variance?: Maybe<Tb_Cliente_Variance_Fields>;
};
/** aggregate fields of "tb_cliente" */
export type Tb_Cliente_Aggregate_FieldsCountArgs = {
columns?: Maybe<Array<Tb_Cliente_Select_Column>>;
distinct?: Maybe<Scalars['Boolean']>;
};
/** order by aggregate values of table "tb_cliente" */
export type Tb_Cliente_Aggregate_Order_By = {
avg?: Maybe<Tb_Cliente_Avg_Order_By>;
count?: Maybe<Order_By>;
max?: Maybe<Tb_Cliente_Max_Order_By>;
min?: Maybe<Tb_Cliente_Min_Order_By>;
stddev?: Maybe<Tb_Cliente_Stddev_Order_By>;
stddev_pop?: Maybe<Tb_Cliente_Stddev_Pop_Order_By>;
stddev_samp?: Maybe<Tb_Cliente_Stddev_Samp_Order_By>;
sum?: Maybe<Tb_Cliente_Sum_Order_By>;
var_pop?: Maybe<Tb_Cliente_Var_Pop_Order_By>;
var_samp?: Maybe<Tb_Cliente_Var_Samp_Order_By>;
variance?: Maybe<Tb_Cliente_Variance_Order_By>;
};
/** input type for inserting array relation for remote table "tb_cliente" */
export type Tb_Cliente_Arr_Rel_Insert_Input = {
data: Array<Tb_Cliente_Insert_Input>;
on_conflict?: Maybe<Tb_Cliente_On_Conflict>;
};
/** aggregate avg on columns */
export type Tb_Cliente_Avg_Fields = {
__typename?: 'tb_cliente_avg_fields';
id_cliente?: Maybe<Scalars['Float']>;
status?: Maybe<Scalars['Float']>;
};
/** order by avg() on columns of table "tb_cliente" */
export type Tb_Cliente_Avg_Order_By = {
id_cliente?: Maybe<Order_By>;
status?: Maybe<Order_By>;
};
/** Boolean expression to filter rows from the table "tb_cliente". All fields are combined with a logical 'AND'. */
export type Tb_Cliente_Bool_Exp = {
_and?: Maybe<Array<Maybe<Tb_Cliente_Bool_Exp>>>;
_not?: Maybe<Tb_Cliente_Bool_Exp>;
_or?: Maybe<Array<Maybe<Tb_Cliente_Bool_Exp>>>;
email?: Maybe<Varchar_Comparison_Exp>;
id_cliente?: Maybe<Bigint_Comparison_Exp>;
identificador?: Maybe<Uuid_Comparison_Exp>;
nome?: Maybe<Varchar_Comparison_Exp>;
status?: Maybe<Integer_Comparison_Exp>;
};
/** unique or primary key constraints on table "tb_cliente" */
export enum Tb_Cliente_Constraint {
/** unique or primary key constraint */
TbClienteEmailKey = 'tb_cliente_email_key',
/** unique or primary key constraint */
TbClienteIdentificadorKey = 'tb_cliente_identificador_key',
/** unique or primary key constraint */
TbClientePkey = 'tb_cliente_pkey'
}
/** input type for incrementing integer columne in table "tb_cliente" */
export type Tb_Cliente_Inc_Input = {
id_cliente?: Maybe<Scalars['bigint']>;
status?: Maybe<Scalars['Int']>;
};
/** input type for inserting data into table "tb_cliente" */
export type Tb_Cliente_Insert_Input = {
email?: Maybe<Scalars['String']>;
id_cliente?: Maybe<Scalars['bigint']>;
identificador?: Maybe<Scalars['uuid']>;
nome?: Maybe<Scalars['String']>;
status?: Maybe<Scalars['Int']>;
};
/** aggregate max on columns */
export type Tb_Cliente_Max_Fields = {
__typename?: 'tb_cliente_max_fields';
email?: Maybe<Scalars['String']>;
id_cliente?: Maybe<Scalars['bigint']>;
nome?: Maybe<Scalars['String']>;
status?: Maybe<Scalars['Int']>;
};
/** order by max() on columns of table "tb_cliente" */
export type Tb_Cliente_Max_Order_By = {
email?: Maybe<Order_By>;
id_cliente?: Maybe<Order_By>;
nome?: Maybe<Order_By>;
status?: Maybe<Order_By>;
};
/** aggregate min on columns */
export type Tb_Cliente_Min_Fields = {
__typename?: 'tb_cliente_min_fields';
email?: Maybe<Scalars['String']>;
id_cliente?: Maybe<Scalars['bigint']>;
nome?: Maybe<Scalars['String']>;
status?: Maybe<Scalars['Int']>;
};
/** order by min() on columns of table "tb_cliente" */
export type Tb_Cliente_Min_Order_By = {
email?: Maybe<Order_By>;
id_cliente?: Maybe<Order_By>;
nome?: Maybe<Order_By>;
status?: Maybe<Order_By>;
};
/** response of any mutation on the table "tb_cliente" */
export type Tb_Cliente_Mutation_Response = {
__typename?: 'tb_cliente_mutation_response';
/** number of affected rows by the mutation */
affected_rows: Scalars['Int'];
/** data of the affected rows by the mutation */
returning: Array<Tb_Cliente>;
};
/** input type for inserting object relation for remote table "tb_cliente" */
export type Tb_Cliente_Obj_Rel_Insert_Input = {
data: Tb_Cliente_Insert_Input;
on_conflict?: Maybe<Tb_Cliente_On_Conflict>;
};
/** on conflict condition type for table "tb_cliente" */
export type Tb_Cliente_On_Conflict = {
constraint: Tb_Cliente_Constraint;
update_columns: Array<Tb_Cliente_Update_Column>;
};
/** ordering options when selecting data from "tb_cliente" */
export type Tb_Cliente_Order_By = {
email?: Maybe<Order_By>;
id_cliente?: Maybe<Order_By>;
identificador?: Maybe<Order_By>;
nome?: Maybe<Order_By>;
status?: Maybe<Order_By>;
};
/** select columns of table "tb_cliente" */
export enum Tb_Cliente_Select_Column {
/** column name */
Email = 'email',
/** column name */
IdCliente = 'id_cliente',
/** column name */
Identificador = 'identificador',
/** column name */
Nome = 'nome',
/** column name */
Status = 'status'
}
/** input type for updating data in table "tb_cliente" */
export type Tb_Cliente_Set_Input = {
email?: Maybe<Scalars['String']>;
id_cliente?: Maybe<Scalars['bigint']>;
identificador?: Maybe<Scalars['uuid']>;
nome?: Maybe<Scalars['String']>;
status?: Maybe<Scalars['Int']>;
};
/** aggregate stddev on columns */
export type Tb_Cliente_Stddev_Fields = {
__typename?: 'tb_cliente_stddev_fields';
id_cliente?: Maybe<Scalars['Float']>;
status?: Maybe<Scalars['Float']>;
};
/** order by stddev() on columns of table "tb_cliente" */
export type Tb_Cliente_Stddev_Order_By = {
id_cliente?: Maybe<Order_By>;
status?: Maybe<Order_By>;
};
/** aggregate stddev_pop on columns */
export type Tb_Cliente_Stddev_Pop_Fields = {
__typename?: 'tb_cliente_stddev_pop_fields';
id_cliente?: Maybe<Scalars['Float']>;
status?: Maybe<Scalars['Float']>;
};
/** order by stddev_pop() on columns of table "tb_cliente" */
export type Tb_Cliente_Stddev_Pop_Order_By = {
id_cliente?: Maybe<Order_By>;
status?: Maybe<Order_By>;
};
/** aggregate stddev_samp on columns */
export type Tb_Cliente_Stddev_Samp_Fields = {
__typename?: 'tb_cliente_stddev_samp_fields';
id_cliente?: Maybe<Scalars['Float']>;
status?: Maybe<Scalars['Float']>;
};
/** order by stddev_samp() on columns of table "tb_cliente" */
export type Tb_Cliente_Stddev_Samp_Order_By = {
id_cliente?: Maybe<Order_By>;
status?: Maybe<Order_By>;
};
/** aggregate sum on columns */
export type Tb_Cliente_Sum_Fields = {
__typename?: 'tb_cliente_sum_fields';
id_cliente?: Maybe<Scalars['bigint']>;
status?: Maybe<Scalars['Int']>;
};
/** order by sum() on columns of table "tb_cliente" */
export type Tb_Cliente_Sum_Order_By = {
id_cliente?: Maybe<Order_By>;
status?: Maybe<Order_By>;
};
/** update columns of table "tb_cliente" */
export enum Tb_Cliente_Update_Column {
/** column name */
Email = 'email',
/** column name */
IdCliente = 'id_cliente',
/** column name */
Identificador = 'identificador',
/** column name */
Nome = 'nome',
/** column name */
Status = 'status'
}
/** aggregate var_pop on columns */
export type Tb_Cliente_Var_Pop_Fields = {
__typename?: 'tb_cliente_var_pop_fields';
id_cliente?: Maybe<Scalars['Float']>;
status?: Maybe<Scalars['Float']>;
};
/** order by var_pop() on columns of table "tb_cliente" */
export type Tb_Cliente_Var_Pop_Order_By = {
id_cliente?: Maybe<Order_By>;
status?: Maybe<Order_By>;
};
/** aggregate var_samp on columns */
export type Tb_Cliente_Var_Samp_Fields = {
__typename?: 'tb_cliente_var_samp_fields';
id_cliente?: Maybe<Scalars['Float']>;
status?: Maybe<Scalars['Float']>;
};
/** order by var_samp() on columns of table "tb_cliente" */
export type Tb_Cliente_Var_Samp_Order_By = {
id_cliente?: Maybe<Order_By>;
status?: Maybe<Order_By>;
};
/** aggregate variance on columns */
export type Tb_Cliente_Variance_Fields = {
__typename?: 'tb_cliente_variance_fields';
id_cliente?: Maybe<Scalars['Float']>;
status?: Maybe<Scalars['Float']>;
};
/** order by variance() on columns of table "tb_cliente" */
export type Tb_Cliente_Variance_Order_By = {
id_cliente?: Maybe<Order_By>;
status?: Maybe<Order_By>;
};
/** expression to compare columns of type text. All fields are combined with logical 'AND'. */
export type Text_Comparison_Exp = {
_eq?: Maybe<Scalars['String']>;
_gt?: Maybe<Scalars['String']>;
_gte?: Maybe<Scalars['String']>;
_ilike?: Maybe<Scalars['String']>;
_in?: Maybe<Array<Maybe<Scalars['String']>>>;
_is_null?: Maybe<Scalars['Boolean']>;
_like?: Maybe<Scalars['String']>;
_lt?: Maybe<Scalars['String']>;
_lte?: Maybe<Scalars['String']>;
_neq?: Maybe<Scalars['String']>;
_nilike?: Maybe<Scalars['String']>;
_nin?: Maybe<Array<Maybe<Scalars['String']>>>;
_nlike?: Maybe<Scalars['String']>;
_nsimilar?: Maybe<Scalars['String']>;
_similar?: Maybe<Scalars['String']>;
};
/** expression to compare columns of type timestamptz. All fields are combined with logical 'AND'. */
export type Timestamptz_Comparison_Exp = {
_eq?: Maybe<Scalars['timestamptz']>;
_gt?: Maybe<Scalars['timestamptz']>;
_gte?: Maybe<Scalars['timestamptz']>;
_in?: Maybe<Array<Maybe<Scalars['timestamptz']>>>;
_is_null?: Maybe<Scalars['Boolean']>;
_lt?: Maybe<Scalars['timestamptz']>;
_lte?: Maybe<Scalars['timestamptz']>;
_neq?: Maybe<Scalars['timestamptz']>;
_nin?: Maybe<Array<Maybe<Scalars['timestamptz']>>>;
};
/** expression to compare columns of type uuid. All fields are combined with logical 'AND'. */
export type Uuid_Comparison_Exp = {
_eq?: Maybe<Scalars['uuid']>;
_gt?: Maybe<Scalars['uuid']>;
_gte?: Maybe<Scalars['uuid']>;
_in?: Maybe<Array<Maybe<Scalars['uuid']>>>;
_is_null?: Maybe<Scalars['Boolean']>;
_lt?: Maybe<Scalars['uuid']>;
_lte?: Maybe<Scalars['uuid']>;
_neq?: Maybe<Scalars['uuid']>;
_nin?: Maybe<Array<Maybe<Scalars['uuid']>>>;
};
/** expression to compare columns of type varchar. All fields are combined with logical 'AND'. */
export type Varchar_Comparison_Exp = {
_eq?: Maybe<Scalars['String']>;
_gt?: Maybe<Scalars['String']>;
_gte?: Maybe<Scalars['String']>;
_ilike?: Maybe<Scalars['String']>;
_in?: Maybe<Array<Maybe<Scalars['String']>>>;
_is_null?: Maybe<Scalars['Boolean']>;
_like?: Maybe<Scalars['String']>;
_lt?: Maybe<Scalars['String']>;
_lte?: Maybe<Scalars['String']>;
_neq?: Maybe<Scalars['String']>;
_nilike?: Maybe<Scalars['String']>;
_nin?: Maybe<Array<Maybe<Scalars['String']>>>;
_nlike?: Maybe<Scalars['String']>;
_nsimilar?: Maybe<Scalars['String']>;
_similar?: Maybe<Scalars['String']>;
};
/** columns and relationships of "vehicle" */
export type Vehicle = {
__typename?: 'vehicle';
id: Scalars['String'];
/** An array relationship */
locations: Array<Vehicle_Location>;
/** An aggregated array relationship */
locations_aggregate: Vehicle_Location_Aggregate;
name: Scalars['String'];
yrdy: Scalars['Int'];
};
/** columns and relationships of "vehicle" */
export type VehicleLocationsArgs = {
distinct_on?: Maybe<Array<Vehicle_Location_Select_Column>>;
limit?: Maybe<Scalars['Int']>;
offset?: Maybe<Scalars['Int']>;
order_by?: Maybe<Array<Vehicle_Location_Order_By>>;
where?: Maybe<Vehicle_Location_Bool_Exp>;
};
/** columns and relationships of "vehicle" */
export type VehicleLocations_AggregateArgs = {
distinct_on?: Maybe<Array<Vehicle_Location_Select_Column>>;
limit?: Maybe<Scalars['Int']>;
offset?: Maybe<Scalars['Int']>;
order_by?: Maybe<Array<Vehicle_Location_Order_By>>;
where?: Maybe<Vehicle_Location_Bool_Exp>;
};
/** aggregated selection of "vehicle" */
export type Vehicle_Aggregate = {
__typename?: 'vehicle_aggregate';
aggregate?: Maybe<Vehicle_Aggregate_Fields>;
nodes: Array<Vehicle>;
};
/** aggregate fields of "vehicle" */
export type Vehicle_Aggregate_Fields = {
__typename?: 'vehicle_aggregate_fields';
avg?: Maybe<Vehicle_Avg_Fields>;
count?: Maybe<Scalars['Int']>;
max?: Maybe<Vehicle_Max_Fields>;
min?: Maybe<Vehicle_Min_Fields>;
stddev?: Maybe<Vehicle_Stddev_Fields>;
stddev_pop?: Maybe<Vehicle_Stddev_Pop_Fields>;
stddev_samp?: Maybe<Vehicle_Stddev_Samp_Fields>;
sum?: Maybe<Vehicle_Sum_Fields>;
var_pop?: Maybe<Vehicle_Var_Pop_Fields>;
var_samp?: Maybe<Vehicle_Var_Samp_Fields>;
variance?: Maybe<Vehicle_Variance_Fields>;
};
/** aggregate fields of "vehicle" */
export type Vehicle_Aggregate_FieldsCountArgs = {
columns?: Maybe<Array<Vehicle_Select_Column>>;
distinct?: Maybe<Scalars['Boolean']>;
};
/** order by aggregate values of table "vehicle" */
export type Vehicle_Aggregate_Order_By = {
avg?: Maybe<Vehicle_Avg_Order_By>;
count?: Maybe<Order_By>;
max?: Maybe<Vehicle_Max_Order_By>;
min?: Maybe<Vehicle_Min_Order_By>;
stddev?: Maybe<Vehicle_Stddev_Order_By>;
stddev_pop?: Maybe<Vehicle_Stddev_Pop_Order_By>;
stddev_samp?: Maybe<Vehicle_Stddev_Samp_Order_By>;
sum?: Maybe<Vehicle_Sum_Order_By>;
var_pop?: Maybe<Vehicle_Var_Pop_Order_By>;
var_samp?: Maybe<Vehicle_Var_Samp_Order_By>;
variance?: Maybe<Vehicle_Variance_Order_By>;
};
/** input type for inserting array relation for remote table "vehicle" */
export type Vehicle_Arr_Rel_Insert_Input = {
data: Array<Vehicle_Insert_Input>;
on_conflict?: Maybe<Vehicle_On_Conflict>;
};
/** aggregate avg on columns */
export type Vehicle_Avg_Fields = {
__typename?: 'vehicle_avg_fields';
yrdy?: Maybe<Scalars['Float']>;
};
/** order by avg() on columns of table "vehicle" */
export type Vehicle_Avg_Order_By = {
yrdy?: Maybe<Order_By>;
};
/** Boolean expression to filter rows from the table "vehicle". All fields are combined with a logical 'AND'. */
export type Vehicle_Bool_Exp = {
_and?: Maybe<Array<Maybe<Vehicle_Bool_Exp>>>;
_not?: Maybe<Vehicle_Bool_Exp>;
_or?: Maybe<Array<Maybe<Vehicle_Bool_Exp>>>;
id?: Maybe<Text_Comparison_Exp>;
locations?: Maybe<Vehicle_Location_Bool_Exp>;
name?: Maybe<Text_Comparison_Exp>;
yrdy?: Maybe<Integer_Comparison_Exp>;
};
/** unique or primary key constraints on table "vehicle" */
export enum Vehicle_Constraint {
/** unique or primary key constraint */
VehiclePkey = 'vehicle_pkey'
}
/** input type for incrementing integer columne in table "vehicle" */
export type Vehicle_Inc_Input = {
yrdy?: Maybe<Scalars['Int']>;
};
/** input type for inserting data into table "vehicle" */
export type Vehicle_Insert_Input = {
id?: Maybe<Scalars['String']>;
locations?: Maybe<Vehicle_Location_Arr_Rel_Insert_Input>;
name?: Maybe<Scalars['String']>;
yrdy?: Maybe<Scalars['Int']>;
};
/** columns and relationships of "vehicle_location" */
export type Vehicle_Location = {
__typename?: 'vehicle_location';
id: Scalars['Int'];
location: Scalars['String'];
timestamp: Scalars['timestamptz'];
vehicle_id: Scalars['String'];
};
/** aggregated selection of "vehicle_location" */
export type Vehicle_Location_Aggregate = {
__typename?: 'vehicle_location_aggregate';
aggregate?: Maybe<Vehicle_Location_Aggregate_Fields>;
nodes: Array<Vehicle_Location>;
};
/** aggregate fields of "vehicle_location" */
export type Vehicle_Location_Aggregate_Fields = {
__typename?: 'vehicle_location_aggregate_fields';
avg?: Maybe<Vehicle_Location_Avg_Fields>;
count?: Maybe<Scalars['Int']>;
max?: Maybe<Vehicle_Location_Max_Fields>;
min?: Maybe<Vehicle_Location_Min_Fields>;
stddev?: Maybe<Vehicle_Location_Stddev_Fields>;
stddev_pop?: Maybe<Vehicle_Location_Stddev_Pop_Fields>;
stddev_samp?: Maybe<Vehicle_Location_Stddev_Samp_Fields>;
sum?: Maybe<Vehicle_Location_Sum_Fields>;
var_pop?: Maybe<Vehicle_Location_Var_Pop_Fields>;
var_samp?: Maybe<Vehicle_Location_Var_Samp_Fields>;
variance?: Maybe<Vehicle_Location_Variance_Fields>;
};
/** aggregate fields of "vehicle_location" */
export type Vehicle_Location_Aggregate_FieldsCountArgs = {
columns?: Maybe<Array<Vehicle_Location_Select_Column>>;
distinct?: Maybe<Scalars['Boolean']>;
};
/** order by aggregate values of table "vehicle_location" */
export type Vehicle_Location_Aggregate_Order_By = {
avg?: Maybe<Vehicle_Location_Avg_Order_By>;
count?: Maybe<Order_By>;
max?: Maybe<Vehicle_Location_Max_Order_By>;
min?: Maybe<Vehicle_Location_Min_Order_By>;
stddev?: Maybe<Vehicle_Location_Stddev_Order_By>;
stddev_pop?: Maybe<Vehicle_Location_Stddev_Pop_Order_By>;
stddev_samp?: Maybe<Vehicle_Location_Stddev_Samp_Order_By>;
sum?: Maybe<Vehicle_Location_Sum_Order_By>;
var_pop?: Maybe<Vehicle_Location_Var_Pop_Order_By>;
var_samp?: Maybe<Vehicle_Location_Var_Samp_Order_By>;
variance?: Maybe<Vehicle_Location_Variance_Order_By>;
};
/** input type for inserting array relation for remote table "vehicle_location" */
export type Vehicle_Location_Arr_Rel_Insert_Input = {
data: Array<Vehicle_Location_Insert_Input>;
on_conflict?: Maybe<Vehicle_Location_On_Conflict>;
};
/** aggregate avg on columns */
export type Vehicle_Location_Avg_Fields = {
__typename?: 'vehicle_location_avg_fields';
id?: Maybe<Scalars['Float']>;
};
/** order by avg() on columns of table "vehicle_location" */
export type Vehicle_Location_Avg_Order_By = {
id?: Maybe<Order_By>;
};
/** Boolean expression to filter rows from the table "vehicle_location". All fields are combined with a logical 'AND'. */
export type Vehicle_Location_Bool_Exp = {
_and?: Maybe<Array<Maybe<Vehicle_Location_Bool_Exp>>>;
_not?: Maybe<Vehicle_Location_Bool_Exp>;
_or?: Maybe<Array<Maybe<Vehicle_Location_Bool_Exp>>>;
id?: Maybe<Integer_Comparison_Exp>;
location?: Maybe<Text_Comparison_Exp>;
timestamp?: Maybe<Timestamptz_Comparison_Exp>;
vehicle_id?: Maybe<Text_Comparison_Exp>;
};
/** unique or primary key constraints on table "vehicle_location" */
export enum Vehicle_Location_Constraint {
/** unique or primary key constraint */
VehicleLocationPkey = 'vehicle_location_pkey'
}
/** input type for incrementing integer columne in table "vehicle_location" */
export type Vehicle_Location_Inc_Input = {
id?: Maybe<Scalars['Int']>;
};
/** input type for inserting data into table "vehicle_location" */
export type Vehicle_Location_Insert_Input = {
id?: Maybe<Scalars['Int']>;
location?: Maybe<Scalars['String']>;
timestamp?: Maybe<Scalars['timestamptz']>;
vehicle_id?: Maybe<Scalars['String']>;
};
/** aggregate max on columns */
export type Vehicle_Location_Max_Fields = {
__typename?: 'vehicle_location_max_fields';
id?: Maybe<Scalars['Int']>;
location?: Maybe<Scalars['String']>;
timestamp?: Maybe<Scalars['timestamptz']>;
vehicle_id?: Maybe<Scalars['String']>;
};
/** order by max() on columns of table "vehicle_location" */
export type Vehicle_Location_Max_Order_By = {
id?: Maybe<Order_By>;
location?: Maybe<Order_By>;
timestamp?: Maybe<Order_By>;
vehicle_id?: Maybe<Order_By>;
};
/** aggregate min on columns */
export type Vehicle_Location_Min_Fields = {
__typename?: 'vehicle_location_min_fields';
id?: Maybe<Scalars['Int']>;
location?: Maybe<Scalars['String']>;
timestamp?: Maybe<Scalars['timestamptz']>;
vehicle_id?: Maybe<Scalars['String']>;
};
/** order by min() on columns of table "vehicle_location" */
export type Vehicle_Location_Min_Order_By = {
id?: Maybe<Order_By>;
location?: Maybe<Order_By>;
timestamp?: Maybe<Order_By>;
vehicle_id?: Maybe<Order_By>;
};
/** response of any mutation on the table "vehicle_location" */
export type Vehicle_Location_Mutation_Response = {
__typename?: 'vehicle_location_mutation_response';
/** number of affected rows by the mutation */
affected_rows: Scalars['Int'];
/** data of the affected rows by the mutation */
returning: Array<Vehicle_Location>;
};
/** input type for inserting object relation for remote table "vehicle_location" */
export type Vehicle_Location_Obj_Rel_Insert_Input = {
data: Vehicle_Location_Insert_Input;
on_conflict?: Maybe<Vehicle_Location_On_Conflict>;
};
/** on conflict condition type for table "vehicle_location" */
export type Vehicle_Location_On_Conflict = {
constraint: Vehicle_Location_Constraint;
update_columns: Array<Vehicle_Location_Update_Column>;
};
/** ordering options when selecting data from "vehicle_location" */
export type Vehicle_Location_Order_By = {
id?: Maybe<Order_By>;
location?: Maybe<Order_By>;
timestamp?: Maybe<Order_By>;
vehicle_id?: Maybe<Order_By>;
};
/** select columns of table "vehicle_location" */
export enum Vehicle_Location_Select_Column {
/** column name */
Id = 'id',
/** column name */
Location = 'location',
/** column name */
Timestamp = 'timestamp',
/** column name */
VehicleId = 'vehicle_id'
}
/** input type for updating data in table "vehicle_location" */
export type Vehicle_Location_Set_Input = {
id?: Maybe<Scalars['Int']>;
location?: Maybe<Scalars['String']>;
timestamp?: Maybe<Scalars['timestamptz']>;
vehicle_id?: Maybe<Scalars['String']>;
};
/** aggregate stddev on columns */
export type Vehicle_Location_Stddev_Fields = {
__typename?: 'vehicle_location_stddev_fields';
id?: Maybe<Scalars['Float']>;
};
/** order by stddev() on columns of table "vehicle_location" */
export type Vehicle_Location_Stddev_Order_By = {
id?: Maybe<Order_By>;
};
/** aggregate stddev_pop on columns */
export type Vehicle_Location_Stddev_Pop_Fields = {
__typename?: 'vehicle_location_stddev_pop_fields';
id?: Maybe<Scalars['Float']>;
};
/** order by stddev_pop() on columns of table "vehicle_location" */
export type Vehicle_Location_Stddev_Pop_Order_By = {
id?: Maybe<Order_By>;
};
/** aggregate stddev_samp on columns */
export type Vehicle_Location_Stddev_Samp_Fields = {
__typename?: 'vehicle_location_stddev_samp_fields';
id?: Maybe<Scalars['Float']>;
};
/** order by stddev_samp() on columns of table "vehicle_location" */
export type Vehicle_Location_Stddev_Samp_Order_By = {
id?: Maybe<Order_By>;
};
/** aggregate sum on columns */
export type Vehicle_Location_Sum_Fields = {
__typename?: 'vehicle_location_sum_fields';
id?: Maybe<Scalars['Int']>;
};
/** order by sum() on columns of table "vehicle_location" */
export type Vehicle_Location_Sum_Order_By = {
id?: Maybe<Order_By>;
};
/** update columns of table "vehicle_location" */
export enum Vehicle_Location_Update_Column {
/** column name */
Id = 'id',
/** column name */
Location = 'location',
/** column name */
Timestamp = 'timestamp',
/** column name */
VehicleId = 'vehicle_id'
}
/** aggregate var_pop on columns */
export type Vehicle_Location_Var_Pop_Fields = {
__typename?: 'vehicle_location_var_pop_fields';
id?: Maybe<Scalars['Float']>;
};
/** order by var_pop() on columns of table "vehicle_location" */
export type Vehicle_Location_Var_Pop_Order_By = {
id?: Maybe<Order_By>;
};
/** aggregate var_samp on columns */
export type Vehicle_Location_Var_Samp_Fields = {
__typename?: 'vehicle_location_var_samp_fields';
id?: Maybe<Scalars['Float']>;
};
/** order by var_samp() on columns of table "vehicle_location" */
export type Vehicle_Location_Var_Samp_Order_By = {
id?: Maybe<Order_By>;
};
/** aggregate variance on columns */
export type Vehicle_Location_Variance_Fields = {
__typename?: 'vehicle_location_variance_fields';
id?: Maybe<Scalars['Float']>;
};
/** order by variance() on columns of table "vehicle_location" */
export type Vehicle_Location_Variance_Order_By = {
id?: Maybe<Order_By>;
};
/** aggregate max on columns */
export type Vehicle_Max_Fields = {
__typename?: 'vehicle_max_fields';
id?: Maybe<Scalars['String']>;
name?: Maybe<Scalars['String']>;
yrdy?: Maybe<Scalars['Int']>;
};
/** order by max() on columns of table "vehicle" */
export type Vehicle_Max_Order_By = {
id?: Maybe<Order_By>;
name?: Maybe<Order_By>;
yrdy?: Maybe<Order_By>;
};
/** aggregate min on columns */
export type Vehicle_Min_Fields = {
__typename?: 'vehicle_min_fields';
id?: Maybe<Scalars['String']>;
name?: Maybe<Scalars['String']>;
yrdy?: Maybe<Scalars['Int']>;
};
/** order by min() on columns of table "vehicle" */
export type Vehicle_Min_Order_By = {
id?: Maybe<Order_By>;
name?: Maybe<Order_By>;
yrdy?: Maybe<Order_By>;
};
/** response of any mutation on the table "vehicle" */
export type Vehicle_Mutation_Response = {
__typename?: 'vehicle_mutation_response';
/** number of affected rows by the mutation */
affected_rows: Scalars['Int'];
/** data of the affected rows by the mutation */
returning: Array<Vehicle>;
};
/** input type for inserting object relation for remote table "vehicle" */
export type Vehicle_Obj_Rel_Insert_Input = {
data: Vehicle_Insert_Input;
on_conflict?: Maybe<Vehicle_On_Conflict>;
};
/** on conflict condition type for table "vehicle" */
export type Vehicle_On_Conflict = {
constraint: Vehicle_Constraint;
update_columns: Array<Vehicle_Update_Column>;
};
/** ordering options when selecting data from "vehicle" */
export type Vehicle_Order_By = {
id?: Maybe<Order_By>;
locations_aggregate?: Maybe<Vehicle_Location_Aggregate_Order_By>;
name?: Maybe<Order_By>;
yrdy?: Maybe<Order_By>;
};
/** select columns of table "vehicle" */
export enum Vehicle_Select_Column {
/** column name */
Id = 'id',
/** column name */
Name = 'name',
/** column name */
Yrdy = 'yrdy'
}
/** input type for updating data in table "vehicle" */
export type Vehicle_Set_Input = {
id?: Maybe<Scalars['String']>;
name?: Maybe<Scalars['String']>;
yrdy?: Maybe<Scalars['Int']>;
};
/** aggregate stddev on columns */
export type Vehicle_Stddev_Fields = {
__typename?: 'vehicle_stddev_fields';
yrdy?: Maybe<Scalars['Float']>;
};
/** order by stddev() on columns of table "vehicle" */
export type Vehicle_Stddev_Order_By = {
yrdy?: Maybe<Order_By>;
};
/** aggregate stddev_pop on columns */
export type Vehicle_Stddev_Pop_Fields = {
__typename?: 'vehicle_stddev_pop_fields';
yrdy?: Maybe<Scalars['Float']>;
};
/** order by stddev_pop() on columns of table "vehicle" */
export type Vehicle_Stddev_Pop_Order_By = {
yrdy?: Maybe<Order_By>;
};
/** aggregate stddev_samp on columns */
export type Vehicle_Stddev_Samp_Fields = {
__typename?: 'vehicle_stddev_samp_fields';
yrdy?: Maybe<Scalars['Float']>;
};
/** order by stddev_samp() on columns of table "vehicle" */
export type Vehicle_Stddev_Samp_Order_By = {
yrdy?: Maybe<Order_By>;
};
/** aggregate sum on columns */
export type Vehicle_Sum_Fields = {
__typename?: 'vehicle_sum_fields';
yrdy?: Maybe<Scalars['Int']>;
};
/** order by sum() on columns of table "vehicle" */
export type Vehicle_Sum_Order_By = {
yrdy?: Maybe<Order_By>;
};
/** update columns of table "vehicle" */
export enum Vehicle_Update_Column {
/** column name */
Id = 'id',
/** column name */
Name = 'name',
/** column name */
Yrdy = 'yrdy'
}
/** aggregate var_pop on columns */
export type Vehicle_Var_Pop_Fields = {
__typename?: 'vehicle_var_pop_fields';
yrdy?: Maybe<Scalars['Float']>;
};
/** order by var_pop() on columns of table "vehicle" */
export type Vehicle_Var_Pop_Order_By = {
yrdy?: Maybe<Order_By>;
};
/** aggregate var_samp on columns */
export type Vehicle_Var_Samp_Fields = {
__typename?: 'vehicle_var_samp_fields';
yrdy?: Maybe<Scalars['Float']>;
};
/** order by var_samp() on columns of table "vehicle" */
export type Vehicle_Var_Samp_Order_By = {
yrdy?: Maybe<Order_By>;
};
/** aggregate variance on columns */
export type Vehicle_Variance_Fields = {
__typename?: 'vehicle_variance_fields';
yrdy?: Maybe<Scalars['Float']>;
};
/** order by variance() on columns of table "vehicle" */
export type Vehicle_Variance_Order_By = {
yrdy?: Maybe<Order_By>;
};
export type QueryVehicleByIdQueryVariables = Exact<{
vehicleId: Scalars['String'];
}>;
export type QueryVehicleByIdQuery = (
{ __typename?: 'query_root' }
& { vehicle_by_pk?: Maybe<(
{ __typename?: 'vehicle' }
& VehicleFragment
)> }
);
export type QueryVehicleObjectsQueryVariables = Exact<{
distinct_on?: Maybe<Array<Vehicle_Select_Column> | Vehicle_Select_Column>;
where?: Maybe<Vehicle_Bool_Exp>;
limit?: Maybe<Scalars['Int']>;
offset?: Maybe<Scalars['Int']>;
order_by?: Maybe<Array<Vehicle_Order_By> | Vehicle_Order_By>;
}>;
export type QueryVehicleObjectsQuery = (
{ __typename?: 'query_root' }
& { vehicle: Array<(
{ __typename?: 'vehicle' }
& VehicleFragment
)> }
);
export type SubscribeToVehicleByIdSubscriptionVariables = Exact<{
vehicleId: Scalars['String'];
}>;
export type SubscribeToVehicleByIdSubscription = (
{ __typename?: 'subscription_root' }
& { vehicle_by_pk?: Maybe<(
{ __typename?: 'vehicle' }
& VehicleFragment
)> }
);
export type SubscribeToVehicleObjectsSubscriptionVariables = Exact<{
distinct_on?: Maybe<Array<Vehicle_Select_Column> | Vehicle_Select_Column>;
where?: Maybe<Vehicle_Bool_Exp>;
limit?: Maybe<Scalars['Int']>;
offset?: Maybe<Scalars['Int']>;
order_by?: Maybe<Array<Vehicle_Order_By> | Vehicle_Order_By>;
}>;
export type SubscribeToVehicleObjectsSubscription = (
{ __typename?: 'subscription_root' }
& { vehicle: Array<(
{ __typename?: 'vehicle' }
& VehicleFragment
)> }
);
export type InsertVehicleMutationVariables = Exact<{
objects: Array<Vehicle_Insert_Input> | Vehicle_Insert_Input;
}>;
export type InsertVehicleMutation = (
{ __typename?: 'mutation_root' }
& { insert_vehicle?: Maybe<(
{ __typename?: 'vehicle_mutation_response' }
& Pick<Vehicle_Mutation_Response, 'affected_rows'>
& { returning: Array<(
{ __typename?: 'vehicle' }
& VehicleFragment
)> }
)> }
);
export type InsertVehicleWithOnConflictMutationVariables = Exact<{
objects: Array<Vehicle_Insert_Input> | Vehicle_Insert_Input;
onConflict?: Maybe<Vehicle_On_Conflict>;
}>;
export type InsertVehicleWithOnConflictMutation = (
{ __typename?: 'mutation_root' }
& { insert_vehicle?: Maybe<(
{ __typename?: 'vehicle_mutation_response' }
& Pick<Vehicle_Mutation_Response, 'affected_rows'>
& { returning: Array<(
{ __typename?: 'vehicle' }
& VehicleFragment
)> }
)> }
);
export type UpdateVehicleByIdMutationVariables = Exact<{
id?: Maybe<Scalars['String']>;
set?: Maybe<Vehicle_Set_Input>;
}>;
export type UpdateVehicleByIdMutation = (
{ __typename?: 'mutation_root' }
& { update_vehicle?: Maybe<(
{ __typename?: 'vehicle_mutation_response' }
& Pick<Vehicle_Mutation_Response, 'affected_rows'>
& { returning: Array<(
{ __typename?: 'vehicle' }
& VehicleFragment
)> }
)> }
);
export type UpdateVehicleMutationVariables = Exact<{
set?: Maybe<Vehicle_Set_Input>;
where: Vehicle_Bool_Exp;
}>;
export type UpdateVehicleMutation = (
{ __typename?: 'mutation_root' }
& { update_vehicle?: Maybe<(
{ __typename?: 'vehicle_mutation_response' }
& Pick<Vehicle_Mutation_Response, 'affected_rows'>
& { returning: Array<(
{ __typename?: 'vehicle' }
& VehicleFragment
)> }
)> }
);
export type RemoveVehicleModelByIdMutationVariables = Exact<{
id?: Maybe<Scalars['String']>;
}>;
export type RemoveVehicleModelByIdMutation = (
{ __typename?: 'mutation_root' }
& { delete_vehicle?: Maybe<(
{ __typename?: 'vehicle_mutation_response' }
& Pick<Vehicle_Mutation_Response, 'affected_rows'>
)> }
);
export type RemoveVehicleModelMutationVariables = Exact<{
where: Vehicle_Bool_Exp;
}>;
export type RemoveVehicleModelMutation = (
{ __typename?: 'mutation_root' }
& { delete_vehicle?: Maybe<(
{ __typename?: 'vehicle_mutation_response' }
& Pick<Vehicle_Mutation_Response, 'affected_rows'>
)> }
);
export type QueryVehicleLocationOnlyByIdQueryVariables = Exact<{
vehicleId: Scalars['String'];
}>;
export type QueryVehicleLocationOnlyByIdQuery = (
{ __typename?: 'query_root' }
& { vehicle_by_pk?: Maybe<(
{ __typename?: 'vehicle' }
& VehicleLocationOnlyFragment
)> }
);
export type QueryVehicleLocationOnlyObjectsQueryVariables = Exact<{
distinct_on?: Maybe<Array<Vehicle_Select_Column> | Vehicle_Select_Column>;
where?: Maybe<Vehicle_Bool_Exp>;
limit?: Maybe<Scalars['Int']>;
offset?: Maybe<Scalars['Int']>;
order_by?: Maybe<Array<Vehicle_Order_By> | Vehicle_Order_By>;
}>;
export type QueryVehicleLocationOnlyObjectsQuery = (
{ __typename?: 'query_root' }
& { vehicle: Array<(
{ __typename?: 'vehicle' }
& VehicleLocationOnlyFragment
)> }
);
export type SubscribeToVehicleLocationOnlyByIdSubscriptionVariables = Exact<{
vehicleId: Scalars['String'];
}>;
export type SubscribeToVehicleLocationOnlyByIdSubscription = (
{ __typename?: 'subscription_root' }
& { vehicle_by_pk?: Maybe<(
{ __typename?: 'vehicle' }
& VehicleLocationOnlyFragment
)> }
);
export type SubscribeToVehicleLocationOnlyObjectsSubscriptionVariables = Exact<{
distinct_on?: Maybe<Array<Vehicle_Select_Column> | Vehicle_Select_Column>;
where?: Maybe<Vehicle_Bool_Exp>;
limit?: Maybe<Scalars['Int']>;
offset?: Maybe<Scalars['Int']>;
order_by?: Maybe<Array<Vehicle_Order_By> | Vehicle_Order_By>;
}>;
export type SubscribeToVehicleLocationOnlyObjectsSubscription = (
{ __typename?: 'subscription_root' }
& { vehicle: Array<(
{ __typename?: 'vehicle' }
& VehicleLocationOnlyFragment
)> }
);
export type InsertVehicleLocationOnlyMutationVariables = Exact<{
objects: Array<Vehicle_Insert_Input> | Vehicle_Insert_Input;
}>;
export type InsertVehicleLocationOnlyMutation = (
{ __typename?: 'mutation_root' }
& { insert_vehicle?: Maybe<(
{ __typename?: 'vehicle_mutation_response' }
& Pick<Vehicle_Mutation_Response, 'affected_rows'>
& { returning: Array<(
{ __typename?: 'vehicle' }
& VehicleLocationOnlyFragment
)> }
)> }
);
export type InsertVehicleLocationOnlyWithOnConflictMutationVariables = Exact<{
objects: Array<Vehicle_Insert_Input> | Vehicle_Insert_Input;
onConflict?: Maybe<Vehicle_On_Conflict>;
}>;
export type InsertVehicleLocationOnlyWithOnConflictMutation = (
{ __typename?: 'mutation_root' }
& { insert_vehicle?: Maybe<(
{ __typename?: 'vehicle_mutation_response' }
& Pick<Vehicle_Mutation_Response, 'affected_rows'>
& { returning: Array<(
{ __typename?: 'vehicle' }
& VehicleLocationOnlyFragment
)> }
)> }
);
export type UpdateVehicleLocationOnlyByIdMutationVariables = Exact<{
id?: Maybe<Scalars['String']>;
set?: Maybe<Vehicle_Set_Input>;
}>;
export type UpdateVehicleLocationOnlyByIdMutation = (
{ __typename?: 'mutation_root' }
& { update_vehicle?: Maybe<(
{ __typename?: 'vehicle_mutation_response' }
& Pick<Vehicle_Mutation_Response, 'affected_rows'>
& { returning: Array<(
{ __typename?: 'vehicle' }
& VehicleLocationOnlyFragment
)> }
)> }
);
export type UpdateVehicleLocationOnlyMutationVariables = Exact<{
set?: Maybe<Vehicle_Set_Input>;
where: Vehicle_Bool_Exp;
}>;
export type UpdateVehicleLocationOnlyMutation = (
{ __typename?: 'mutation_root' }
& { update_vehicle?: Maybe<(
{ __typename?: 'vehicle_mutation_response' }
& Pick<Vehicle_Mutation_Response, 'affected_rows'>
& { returning: Array<(
{ __typename?: 'vehicle' }
& VehicleLocationOnlyFragment
)> }
)> }
);
export type VehicleFragment = (
{ __typename?: 'vehicle' }
& Pick<Vehicle, 'id' | 'name'>
& { locations: Array<(
{ __typename?: 'vehicle_location' }
& Pick<Vehicle_Location, 'location'>
)> }
);
export type VehicleLocationOnlyFragment = (
{ __typename?: 'vehicle' }
& Pick<Vehicle, 'id'>
& { locations: Array<(
{ __typename?: 'vehicle_location' }
& Pick<Vehicle_Location, 'location'>
)> }
);
export const VehicleFragmentDoc = gql`
fragment Vehicle on vehicle {
id
name
locations {
location
}
}
`;
export const VehicleLocationOnlyFragmentDoc = gql`
fragment VehicleLocationOnly on vehicle {
id
locations {
location
}
}
`;
export const QueryVehicleByIdDocument = gql`
query queryVehicleById($vehicleId: String!) {
vehicle_by_pk(id: $vehicleId) {
...Vehicle
}
}
${VehicleFragmentDoc}`;
export type QueryVehicleByIdQueryResult = Apollo.QueryResult<QueryVehicleByIdQuery, QueryVehicleByIdQueryVariables>;
export const QueryVehicleObjectsDocument = gql`
query queryVehicleObjects($distinct_on: [vehicle_select_column!], $where: vehicle_bool_exp, $limit: Int, $offset: Int, $order_by: [vehicle_order_by!]) {
vehicle(
distinct_on: $distinct_on
where: $where
limit: $limit
offset: $offset
order_by: $order_by
) {
...Vehicle
}
}
${VehicleFragmentDoc}`;
export type QueryVehicleObjectsQueryResult = Apollo.QueryResult<QueryVehicleObjectsQuery, QueryVehicleObjectsQueryVariables>;
export const SubscribeToVehicleByIdDocument = gql`
subscription subscribeToVehicleById($vehicleId: String!) {
vehicle_by_pk(id: $vehicleId) {
...Vehicle
}
}
${VehicleFragmentDoc}`;
export type SubscribeToVehicleByIdSubscriptionResult = Apollo.SubscriptionResult<SubscribeToVehicleByIdSubscription>;
export const SubscribeToVehicleObjectsDocument = gql`
subscription subscribeToVehicleObjects($distinct_on: [vehicle_select_column!], $where: vehicle_bool_exp, $limit: Int, $offset: Int, $order_by: [vehicle_order_by!]) {
vehicle(
distinct_on: $distinct_on
where: $where
limit: $limit
offset: $offset
order_by: $order_by
) {
...Vehicle
}
}
${VehicleFragmentDoc}`;
export type SubscribeToVehicleObjectsSubscriptionResult = Apollo.SubscriptionResult<SubscribeToVehicleObjectsSubscription>;
export const InsertVehicleDocument = gql`
mutation insertVehicle($objects: [vehicle_insert_input!]!) {
insert_vehicle(objects: $objects) {
affected_rows
returning {
...Vehicle
}
}
}
${VehicleFragmentDoc}`;
export type InsertVehicleMutationFn = Apollo.MutationFunction<InsertVehicleMutation, InsertVehicleMutationVariables>;
export type InsertVehicleMutationResult = Apollo.MutationResult<InsertVehicleMutation>;
export type InsertVehicleMutationOptions = Apollo.BaseMutationOptions<InsertVehicleMutation, InsertVehicleMutationVariables>;
export const InsertVehicleWithOnConflictDocument = gql`
mutation insertVehicleWithOnConflict($objects: [vehicle_insert_input!]!, $onConflict: vehicle_on_conflict) {
insert_vehicle(objects: $objects, on_conflict: $onConflict) {
affected_rows
returning {
...Vehicle
}
}
}
${VehicleFragmentDoc}`;
export type InsertVehicleWithOnConflictMutationFn = Apollo.MutationFunction<InsertVehicleWithOnConflictMutation, InsertVehicleWithOnConflictMutationVariables>;
export type InsertVehicleWithOnConflictMutationResult = Apollo.MutationResult<InsertVehicleWithOnConflictMutation>;
export type InsertVehicleWithOnConflictMutationOptions = Apollo.BaseMutationOptions<InsertVehicleWithOnConflictMutation, InsertVehicleWithOnConflictMutationVariables>;
export const UpdateVehicleByIdDocument = gql`
mutation updateVehicleById($id: String, $set: vehicle_set_input) {
update_vehicle(_set: $set, where: {id: {_eq: $id}}) {
affected_rows
returning {
...Vehicle
}
}
}
${VehicleFragmentDoc}`;
export type UpdateVehicleByIdMutationFn = Apollo.MutationFunction<UpdateVehicleByIdMutation, UpdateVehicleByIdMutationVariables>;
export type UpdateVehicleByIdMutationResult = Apollo.MutationResult<UpdateVehicleByIdMutation>;
export type UpdateVehicleByIdMutationOptions = Apollo.BaseMutationOptions<UpdateVehicleByIdMutation, UpdateVehicleByIdMutationVariables>;
export const UpdateVehicleDocument = gql`
mutation updateVehicle($set: vehicle_set_input, $where: vehicle_bool_exp!) {
update_vehicle(_set: $set, where: $where) {
affected_rows
returning {
...Vehicle
}
}
}
${VehicleFragmentDoc}`;
export type UpdateVehicleMutationFn = Apollo.MutationFunction<UpdateVehicleMutation, UpdateVehicleMutationVariables>;
export type UpdateVehicleMutationResult = Apollo.MutationResult<UpdateVehicleMutation>;
export type UpdateVehicleMutationOptions = Apollo.BaseMutationOptions<UpdateVehicleMutation, UpdateVehicleMutationVariables>;
export const RemoveVehicleModelByIdDocument = gql`
mutation removeVehicleModelById($id: String) {
delete_vehicle(where: {id: {_eq: $id}}) {
affected_rows
}
}
`;
export type RemoveVehicleModelByIdMutationFn = Apollo.MutationFunction<RemoveVehicleModelByIdMutation, RemoveVehicleModelByIdMutationVariables>;
export type RemoveVehicleModelByIdMutationResult = Apollo.MutationResult<RemoveVehicleModelByIdMutation>;
export type RemoveVehicleModelByIdMutationOptions = Apollo.BaseMutationOptions<RemoveVehicleModelByIdMutation, RemoveVehicleModelByIdMutationVariables>;
export const RemoveVehicleModelDocument = gql`
mutation removeVehicleModel($where: vehicle_bool_exp!) {
delete_vehicle(where: $where) {
affected_rows
}
}
`;
export type RemoveVehicleModelMutationFn = Apollo.MutationFunction<RemoveVehicleModelMutation, RemoveVehicleModelMutationVariables>;
export type RemoveVehicleModelMutationResult = Apollo.MutationResult<RemoveVehicleModelMutation>;
export type RemoveVehicleModelMutationOptions = Apollo.BaseMutationOptions<RemoveVehicleModelMutation, RemoveVehicleModelMutationVariables>;
export const QueryVehicleLocationOnlyByIdDocument = gql`
query queryVehicleLocationOnlyById($vehicleId: String!) {
vehicle_by_pk(id: $vehicleId) {
...VehicleLocationOnly
}
}
${VehicleLocationOnlyFragmentDoc}`;
export type QueryVehicleLocationOnlyByIdQueryResult = Apollo.QueryResult<QueryVehicleLocationOnlyByIdQuery, QueryVehicleLocationOnlyByIdQueryVariables>;
export const QueryVehicleLocationOnlyObjectsDocument = gql`
query queryVehicleLocationOnlyObjects($distinct_on: [vehicle_select_column!], $where: vehicle_bool_exp, $limit: Int, $offset: Int, $order_by: [vehicle_order_by!]) {
vehicle(
distinct_on: $distinct_on
where: $where
limit: $limit
offset: $offset
order_by: $order_by
) {
...VehicleLocationOnly
}
}
${VehicleLocationOnlyFragmentDoc}`;
export type QueryVehicleLocationOnlyObjectsQueryResult = Apollo.QueryResult<QueryVehicleLocationOnlyObjectsQuery, QueryVehicleLocationOnlyObjectsQueryVariables>;
export const SubscribeToVehicleLocationOnlyByIdDocument = gql`
subscription subscribeToVehicleLocationOnlyById($vehicleId: String!) {
vehicle_by_pk(id: $vehicleId) {
...VehicleLocationOnly
}
}
${VehicleLocationOnlyFragmentDoc}`;
export type SubscribeToVehicleLocationOnlyByIdSubscriptionResult = Apollo.SubscriptionResult<SubscribeToVehicleLocationOnlyByIdSubscription>;
export const SubscribeToVehicleLocationOnlyObjectsDocument = gql`
subscription subscribeToVehicleLocationOnlyObjects($distinct_on: [vehicle_select_column!], $where: vehicle_bool_exp, $limit: Int, $offset: Int, $order_by: [vehicle_order_by!]) {
vehicle(
distinct_on: $distinct_on
where: $where
limit: $limit
offset: $offset
order_by: $order_by
) {
...VehicleLocationOnly
}
}
${VehicleLocationOnlyFragmentDoc}`;
export type SubscribeToVehicleLocationOnlyObjectsSubscriptionResult = Apollo.SubscriptionResult<SubscribeToVehicleLocationOnlyObjectsSubscription>;
export const InsertVehicleLocationOnlyDocument = gql`
mutation insertVehicleLocationOnly($objects: [vehicle_insert_input!]!) {
insert_vehicle(objects: $objects) {
affected_rows
returning {
...VehicleLocationOnly
}
}
}
${VehicleLocationOnlyFragmentDoc}`;
export type InsertVehicleLocationOnlyMutationFn = Apollo.MutationFunction<InsertVehicleLocationOnlyMutation, InsertVehicleLocationOnlyMutationVariables>;
export type InsertVehicleLocationOnlyMutationResult = Apollo.MutationResult<InsertVehicleLocationOnlyMutation>;
export type InsertVehicleLocationOnlyMutationOptions = Apollo.BaseMutationOptions<InsertVehicleLocationOnlyMutation, InsertVehicleLocationOnlyMutationVariables>;
export const InsertVehicleLocationOnlyWithOnConflictDocument = gql`
mutation insertVehicleLocationOnlyWithOnConflict($objects: [vehicle_insert_input!]!, $onConflict: vehicle_on_conflict) {
insert_vehicle(objects: $objects, on_conflict: $onConflict) {
affected_rows
returning {
...VehicleLocationOnly
}
}
}
${VehicleLocationOnlyFragmentDoc}`;
export type InsertVehicleLocationOnlyWithOnConflictMutationFn = Apollo.MutationFunction<InsertVehicleLocationOnlyWithOnConflictMutation, InsertVehicleLocationOnlyWithOnConflictMutationVariables>;
export type InsertVehicleLocationOnlyWithOnConflictMutationResult = Apollo.MutationResult<InsertVehicleLocationOnlyWithOnConflictMutation>;
export type InsertVehicleLocationOnlyWithOnConflictMutationOptions = Apollo.BaseMutationOptions<InsertVehicleLocationOnlyWithOnConflictMutation, InsertVehicleLocationOnlyWithOnConflictMutationVariables>;
export const UpdateVehicleLocationOnlyByIdDocument = gql`
mutation updateVehicleLocationOnlyById($id: String, $set: vehicle_set_input) {
update_vehicle(_set: $set, where: {id: {_eq: $id}}) {
affected_rows
returning {
...VehicleLocationOnly
}
}
}
${VehicleLocationOnlyFragmentDoc}`;
export type UpdateVehicleLocationOnlyByIdMutationFn = Apollo.MutationFunction<UpdateVehicleLocationOnlyByIdMutation, UpdateVehicleLocationOnlyByIdMutationVariables>;
export type UpdateVehicleLocationOnlyByIdMutationResult = Apollo.MutationResult<UpdateVehicleLocationOnlyByIdMutation>;
export type UpdateVehicleLocationOnlyByIdMutationOptions = Apollo.BaseMutationOptions<UpdateVehicleLocationOnlyByIdMutation, UpdateVehicleLocationOnlyByIdMutationVariables>;
export const UpdateVehicleLocationOnlyDocument = gql`
mutation updateVehicleLocationOnly($set: vehicle_set_input, $where: vehicle_bool_exp!) {
update_vehicle(_set: $set, where: $where) {
affected_rows
returning {
...VehicleLocationOnly
}
}
}
${VehicleLocationOnlyFragmentDoc}`;
export type UpdateVehicleLocationOnlyMutationFn = Apollo.MutationFunction<UpdateVehicleLocationOnlyMutation, UpdateVehicleLocationOnlyMutationVariables>;
export type UpdateVehicleLocationOnlyMutationResult = Apollo.MutationResult<UpdateVehicleLocationOnlyMutation>;
export type UpdateVehicleLocationOnlyMutationOptions = Apollo.BaseMutationOptions<UpdateVehicleLocationOnlyMutation, UpdateVehicleLocationOnlyMutationVariables>; | the_stack |
import { DIALECT, GUIDE_COLOR, GUIDE_STROKEWIDTH } from '../../util/Constants';
import Point from '../geometry/Point';
import PolylineShape from '../geometry/edge/PolylineShape';
import CellState from '../cell/CellState';
import Shape from '../geometry/Shape';
import Rectangle from '../geometry/Rectangle';
import { Graph } from '../Graph';
/**
* Implements the alignment of selection cells to other cells in the graph.
*
* Constructor: mxGuide
*
* Constructs a new guide object.
*/
class Guide {
constructor(graph: Graph, states: CellState[]) {
this.graph = graph;
this.setStates(states);
}
/**
* Reference to the enclosing {@link Graph} instance.
*/
graph: Graph;
/**
* Contains the {@link CellStates} that are used for alignment.
*/
states: CellState[] = [];
/**
* Specifies if horizontal guides are enabled. Default is true.
*/
horizontal = true;
/**
* Specifies if vertical guides are enabled. Default is true.
*/
vertical = true;
/**
* Holds the {@link Shape} for the horizontal guide.
*/
guideX: Shape | null = null;
/**
* Holds the {@link Shape} for the vertical guide.
*/
guideY: Shape | null = null;
/**
* Specifies if rounded coordinates should be used. Default is false.
*/
rounded = false;
/**
* Default tolerance in px if grid is disabled. Default is 2.
*/
tolerance = 2;
/**
* Sets the {@link CellStates} that should be used for alignment.
*/
setStates(states: CellState[]) {
this.states = states;
}
/**
* Returns true if the guide should be enabled for the given native event. This
* implementation always returns true.
*/
isEnabledForEvent(evt: MouseEvent) {
return true;
}
/**
* Returns the tolerance for the guides. Default value is gridSize / 2.
*/
getGuideTolerance(gridEnabled = false) {
return gridEnabled && this.graph.isGridEnabled()
? this.graph.getGridSize() / 2
: this.tolerance;
}
/**
* Returns the mxShape to be used for painting the respective guide. This
* implementation returns a new, dashed and crisp {@link Polyline} using
* {@link Constants#GUIDE_COLOR} and {@link Constants#GUIDE_STROKEWIDTH} as the format.
*
* @param horizontal Boolean that specifies which guide should be created.
*/
createGuideShape(horizontal = false) {
// TODO: Should vertical guides be supported here?? ============================
const guide = new PolylineShape([], GUIDE_COLOR, GUIDE_STROKEWIDTH);
guide.isDashed = true;
return guide;
}
/**
* Returns true if the given state should be ignored.
* @param state
*/
isStateIgnored(state: CellState) {
return false;
}
/**
* Moves the <bounds> by the given {@link Point} and returnt the snapped point.
*/
move(
bounds: Rectangle | null = null,
delta: Point,
gridEnabled = false,
clone = false
) {
if ((this.horizontal || this.vertical) && bounds) {
const { scale } = this.graph.getView();
const tt = this.getGuideTolerance(gridEnabled) * scale;
const b = bounds.clone();
b.x += delta.x;
b.y += delta.y;
let overrideX = false;
let stateX: CellState | null = null;
let valueX: number | null = null;
let overrideY = false;
let stateY: CellState | null = null;
let valueY: number | null = null;
let ttX = tt;
let ttY = tt;
const left = b.x;
const right = b.x + b.width;
const center = b.getCenterX();
const top = b.y;
const bottom = b.y + b.height;
const middle = b.getCenterY();
// Snaps the left, center and right to the given x-coordinate
const snapX = (x: number, state: CellState, centerAlign: boolean) => {
let override = false;
if (centerAlign && Math.abs(x - center) < ttX) {
delta.x = x - bounds.getCenterX();
ttX = Math.abs(x - center);
override = true;
} else if (!centerAlign) {
if (Math.abs(x - left) < ttX) {
delta.x = x - bounds.x;
ttX = Math.abs(x - left);
override = true;
} else if (Math.abs(x - right) < ttX) {
delta.x = x - bounds.x - bounds.width;
ttX = Math.abs(x - right);
override = true;
}
}
if (override) {
stateX = state;
valueX = x;
if (!this.guideX) {
this.guideX = this.createGuideShape(true);
// Makes sure to use SVG shapes in order to implement
// event-transparency on the background area of the rectangle since
// HTML shapes do not let mouseevents through even when transparent
this.guideX.dialect = DIALECT.SVG;
this.guideX.pointerEvents = false;
this.guideX.init(this.graph.getView().getOverlayPane());
}
}
overrideX = overrideX || override;
};
// Snaps the top, middle or bottom to the given y-coordinate
const snapY = (y: number, state: CellState, centerAlign: boolean) => {
let override = false;
if (centerAlign && Math.abs(y - middle) < ttY) {
delta.y = y - bounds.getCenterY();
ttY = Math.abs(y - middle);
override = true;
} else if (!centerAlign) {
if (Math.abs(y - top) < ttY) {
delta.y = y - bounds.y;
ttY = Math.abs(y - top);
override = true;
} else if (Math.abs(y - bottom) < ttY) {
delta.y = y - bounds.y - bounds.height;
ttY = Math.abs(y - bottom);
override = true;
}
}
if (override) {
stateY = state;
valueY = y;
if (!this.guideY) {
this.guideY = this.createGuideShape(false);
// Makes sure to use SVG shapes in order to implement
// event-transparency on the background area of the rectangle since
// HTML shapes do not let mouseevents through even when transparent
this.guideY.dialect = DIALECT.SVG;
this.guideY.pointerEvents = false;
this.guideY.init(this.graph.getView().getOverlayPane());
}
}
overrideY = overrideY || override;
};
for (let i = 0; i < this.states.length; i += 1) {
const state = this.states[i];
if (state && !this.isStateIgnored(state)) {
// Align x
if (this.horizontal) {
snapX(state.getCenterX(), state, true);
snapX(state.x, state, false);
snapX(state.x + state.width, state, false);
// Aligns left and right of shape to center of page
if (!state.cell) {
snapX(state.getCenterX(), state, false);
}
}
// Align y
if (this.vertical) {
snapY(state.getCenterY(), state, true);
snapY(state.y, state, false);
snapY(state.y + state.height, state, false);
// Aligns left and right of shape to center of page
if (!state.cell) {
snapY(state.getCenterY(), state, false);
}
}
}
}
// Moves cells to the raster if not aligned
this.graph.snapDelta(delta, bounds, !gridEnabled, overrideX, overrideY);
delta = this.getDelta(bounds, stateX, delta.x, stateY, delta.y);
// Redraws the guides
const c = this.graph.container;
if (!overrideX && this.guideX) {
this.guideX.node.style.visibility = 'hidden';
} else if (this.guideX) {
let minY: number | null = null;
let maxY: number | null = null;
if (stateX) {
minY = Math.min(bounds.y + delta.y - this.graph.getPanDy(), stateX!.y);
maxY = Math.max(
bounds.y + bounds.height + delta.y - this.graph.getPanDy(),
// @ts-ignore stateX! doesn't work for some reason...
stateX!.y + stateX!.height
);
}
if (minY !== null && maxY !== null) {
this.guideX.points = [new Point(valueX!, minY), new Point(valueX!, maxY)];
} else {
this.guideX.points = [
new Point(valueX!, -this.graph.getPanDy()),
new Point(valueX!, c.scrollHeight - 3 - this.graph.getPanDy()),
];
}
this.guideX.stroke = this.getGuideColor(stateX!, true);
this.guideX.node.style.visibility = 'visible';
this.guideX.redraw();
}
if (!overrideY && this.guideY != null) {
this.guideY.node.style.visibility = 'hidden';
} else if (this.guideY != null) {
let minX = null;
let maxX = null;
if (stateY != null && bounds != null) {
minX = Math.min(bounds.x + delta.x - this.graph.getPanDx(), stateY!.x);
maxX = Math.max(
bounds.x + bounds.width + delta.x - this.graph.getPanDx(),
// @ts-ignore
stateY.x + stateY.width
);
}
if (minX != null && maxX != null && valueY !== null) {
this.guideY.points = [new Point(minX, valueY), new Point(maxX, valueY)];
} else if (valueY !== null) {
this.guideY.points = [
new Point(-this.graph.getPanDx(), valueY),
new Point(c.scrollWidth - 3 - this.graph.getPanDx(), valueY),
];
}
this.guideY.stroke = this.getGuideColor(stateY!, false);
this.guideY.node.style.visibility = 'visible';
this.guideY.redraw();
}
}
return delta;
}
/**
* Rounds to pixels for virtual states (eg. page guides)
*/
getDelta(
bounds: Rectangle,
stateX: CellState | null = null,
dx: number,
stateY: CellState | null = null,
dy: number
): Point {
const s = this.graph.view.scale;
if (this.rounded || (stateX != null && stateX.cell == null)) {
dx = Math.round((bounds.x + dx) / s) * s - bounds.x;
}
if (this.rounded || (stateY != null && stateY.cell == null)) {
dy = Math.round((bounds.y + dy) / s) * s - bounds.y;
}
return new Point(dx, dy);
}
/**
* Hides all current guides.
*/
getGuideColor(state: CellState, horizontal: boolean) {
return GUIDE_COLOR;
}
/**
* Hides all current guides.
*/
hide() {
this.setVisible(false);
}
/**
* Shows or hides the current guides.
*/
setVisible(visible: boolean) {
if (this.guideX) {
this.guideX.node.style.visibility = visible ? 'visible' : 'hidden';
}
if (this.guideY) {
this.guideY.node.style.visibility = visible ? 'visible' : 'hidden';
}
}
/**
* Destroys all resources that this object uses.
*/
destroy() {
if (this.guideX) {
this.guideX.destroy();
this.guideX = null;
}
if (this.guideY) {
this.guideY.destroy();
this.guideY = null;
}
}
}
export default Guide; | the_stack |
import dayjs from 'dayjs';
import dayJsIsBetween from 'dayjs/plugin/isBetween';
import chunk from 'lodash/chunk';
dayjs.extend(dayJsIsBetween);
/**
* 首字母大写
* @param {String} str 目标字符串
* @returns {String}
*/
export function firstUpperCase(str: string): string {
if (!str) return str;
return str[0].toUpperCase().concat(str.substring(1, str.length));
}
interface DateObj {
year: number;
month: number;
}
/**
* 返回指定年、月的第一天日期
* @param {Object} { year, month }
* @returns {Date}
*/
function getFirstDayOfMonth({ year, month }: DateObj): Date {
return new Date(year, month, 1);
}
/**
* 返回指定年、月的天数
* @param {Object} { year, month }
* @returns {Number}
*/
function getDaysInMonth({ year, month }: DateObj): number {
return new Date(year, month + 1, 0).getDate();
}
/**
* 返回指定年、月的最后一天日期
* @param {Object} { year, month }
* @returns {Date}
*/
function getLastDayOfMonth({ year, month }: DateObj): Date {
return new Date(year, month, getDaysInMonth({ year, month }));
}
function isSameYear(date1: Date, date2: Date): boolean {
return date1.getFullYear() === date2.getFullYear();
}
function isSameMonth(date1: Date, date2: Date): boolean {
return isSameYear(date1, date2) && date1.getMonth() === date2.getMonth();
}
function isSameDate(date1: Date, date2: Date): boolean {
return isSameMonth(date1, date2) && date1.getDate() === date2.getDate();
}
/**
* 比较两个日期对象的时间戳
* @param {Date} date1 日期1
* @param {Date} date2 日期2
* @returns {Number} 返回 date1.getTime() - date2.getTime() 的差值
*/
function compareAsc(date1: { getTime: () => any }, date2: Date): number {
const d1 = date1.getTime();
const d2 = date2.getTime();
if (d1 < d2) return -1;
if (d1 > d2) return 1;
return 0;
}
/**
* 比较两个 Date 是否是同一天 或则 同一月 或则 同一年
* @param {Date} date1 比较的日期
* @param {Date} date2 比较的日期
* @param {String} type 比较类型,默认比较到『日』 date|month|year
* @returns {Boolean}
*/
export function isSame(date1: Date, date2: Date, type = 'date'): boolean {
const func = {
isSameYear,
isSameMonth,
isSameDate,
};
return func[`isSame${firstUpperCase(type)}`](date1, date2);
}
export function outOfRanges(d: Date, min: any, max: any) {
return (min && compareAsc(d, min) === -1) || (max && compareAsc(d, max) === 1);
}
/**
* @returns {Date} 当天零点的日期对象
*/
export function getToday(): Date {
const now = new Date();
return new Date(now.getFullYear(), now.getMonth(), now.getDate(), 0, 0, 0);
}
/**
* 返回日期对象的年、月、日、小时、分钟、秒、12小时制标识
* @param {Date} date
* @returns {Object}
*/
export function getDateObj(date: Date) {
let tempDate = date;
if (!(date instanceof Date)) {
tempDate = getToday();
}
return {
year: tempDate.getFullYear(),
month: tempDate.getMonth(),
date: tempDate.getDate(),
hours: tempDate.getHours(),
minutes: tempDate.getMinutes(),
seconds: tempDate.getSeconds(),
milliseconds: tempDate.getMilliseconds(),
meridiem: tempDate.getHours() > 11 ? 'PM' : 'AM',
};
}
/**
* 设置日期对象的时间部分
* @param {Date} date 日期
* @param {Number} hours 小时
* @param {Number} minutes 分钟
* @param {Number} seconds 秒
* @param {Number} milliseconds 毫秒
* @returns {Date} 一个新的date
*/
export function setDateTime(
date: Date,
hours: number,
minutes: number,
seconds: number,
milliseconds?: number
): Date {
return dayjs(date)
.hour(hours)
.minute(minutes)
.second(seconds)
.millisecond(milliseconds)
.toDate();
}
/**
* 减少月份
* @param {Date} date 起始日期
* @param {Number} num 月份数
* @returns {Date}
*/
export function subtractMonth(date: Date, num: number): Date {
return dayjs(date).subtract(num, 'month').toDate();
}
/**
* 增加月份
* @param {Date} date 起始日期
* @param {Number} num 月份数
* @returns {Date}
*/
export function addMonth(date: Date, num: number): Date {
return dayjs(date).add(num, 'month').toDate();
}
export type DateValue = string | Date | number;
export interface DisableDateObj { from?: string; to?: string; before?: string; after?: string }
export type DisableDate = Array<DateValue> | DisableDateObj | ((date: DateValue) => boolean);
export interface OptionsType {
firstDayOfWeek: number;
disableDate: DisableDate;
minDate: Date;
maxDate: Date;
monthLocal?: string[];
}
export function getWeeks(
{ year, month }: { year: number; month: number },
{
firstDayOfWeek,
disableDate = () => false,
minDate,
maxDate,
}: OptionsType,
) {
const prependDay = getFirstDayOfMonth({ year, month });
const appendDay = getLastDayOfMonth({ year, month });
const maxDays = getDaysInMonth({ year, month });
const daysArr = [];
let i = 1;
const today = getToday();
for (i; i <= maxDays; i++) {
const currentDay = new Date(year, month, i);
daysArr.push({
text: i,
active: false,
value: currentDay,
disabled: (typeof disableDate === 'function' && disableDate(currentDay)) || outOfRanges(currentDay, minDate, maxDate),
now: isSame(today, currentDay),
firstDayOfMonth: i === 1,
lastDayOfMonth: i === maxDays,
type: 'current-month',
});
}
if (prependDay.getDay() !== firstDayOfWeek) {
prependDay.setDate(0); // 上一月
while (true) {
daysArr.unshift({
text: prependDay.getDate().toString(),
active: false,
value: new Date(prependDay),
disabled: (typeof disableDate === 'function' && disableDate(prependDay)) || outOfRanges(prependDay, minDate, maxDate),
additional: true, // 非当前月
type: 'prev-month',
});
prependDay.setDate(prependDay.getDate() - 1);
if (prependDay.getDay() === Math.abs(firstDayOfWeek + 6) % 7) break;
}
}
const LEN = 42; // 显示6周
while (daysArr.length < LEN) {
appendDay.setDate(appendDay.getDate() + 1);
daysArr.push({
text: appendDay.getDate(),
active: false,
value: new Date(appendDay),
disabled: (typeof disableDate === 'function' && disableDate(appendDay)) || outOfRanges(appendDay, minDate, maxDate),
additional: true, // 非当前月
type: 'next-month',
});
}
return chunk(daysArr, 7);
}
export function getYears(
year: number,
{
disableDate = () => false,
minDate,
maxDate,
}: OptionsType,
) {
const startYear = parseInt((year / 10).toString(), 10) * 10;
const endYear = startYear + 9;
const yearArr = [];
const today = getToday();
for (let i = startYear; i <= endYear; i++) {
const date = new Date(i, 1);
let disabledMonth = 0;
let outOfRangeMonth = 0;
for (let j = 0; j < 12; j++) {
const d = new Date(i, j);
if (typeof disableDate === 'function' && disableDate(d)) disabledMonth += 1;
if (outOfRanges(d, minDate, maxDate)) outOfRangeMonth += 1;
}
yearArr.push({
value: date,
now: isSame(date, today, 'year'),
disabled: disabledMonth === 12 || outOfRangeMonth === 12,
active: false,
text: `${date.getFullYear()}`,
});
}
return chunk(yearArr, 3);
}
export function getMonths(year: number, params: OptionsType) {
const {
disableDate = () => false, minDate, maxDate, monthLocal,
} = params;
const MonthArr = [];
const today = getToday();
for (let i = 0; i <= 11; i++) {
const date = new Date(year, i);
let disabledDay = 0;
let outOfRangeDay = 0;
const daysInMonth = getDaysInMonth({ year, month: i });
for (let j = 1; j <= daysInMonth; j++) {
const d = new Date(year, i, j);
if (typeof disableDate === 'function' && disableDate(d)) disabledDay += 1;
if (outOfRanges(d, minDate, maxDate)) outOfRangeDay += 1;
}
MonthArr.push({
value: date,
now: isSame(date, today, 'month'),
disabled: disabledDay === daysInMonth || outOfRangeDay === daysInMonth,
active: false,
text: monthLocal[date.getMonth()], // `${date.getMonth() + 1} ${monthText || '月'}`,
});
}
return chunk(MonthArr, 3);
}
export interface DateTime {
additional: boolean;
active: boolean;
highlight: boolean;
hoverHighlight: boolean;
startOfRange: boolean;
endOfRange: boolean;
hoverStartOfRange: boolean;
hoverEndOfRange: boolean;
value: Date;
}
export function flagActive(data: any[], { ...args }: any) {
const { start, end, hoverStart, hoverEnd, type = 'date', isRange = false } = args;
if (!isRange) {
return data.map((row: any[]) => row.map((item: DateTime) => {
const _item = item;
_item.active = start && isSame(item.value, start, type) && !_item.additional;
return _item;
}));
}
return data.map((row: any[]) => row.map((item: DateTime) => {
const _item = item;
const date = item.value;
const isStart = start && isSame(start, date, type);
const isHoverStart = hoverStart && isSame(hoverStart, date, type);
const isEnd = end && isSame(end, date, type);
const isHoverEnd = hoverEnd && isSame(hoverEnd, date, type);
_item.active = (isStart || isEnd) && !_item.additional;
if (start && end) {
_item.highlight = dayjs(date).isBetween(start, end, type, '[]') && !_item.additional;
_item.startOfRange = isStart;
_item.endOfRange = isEnd;
}
if (hoverStart && hoverEnd) {
// eslint-disable-next-line
_item.hoverHighlight = dayjs(date).isBetween(hoverStart, hoverEnd, type, '[]') && !_item.additional;
_item.hoverStartOfRange = isHoverStart;
_item.hoverEndOfRange = isHoverEnd;
}
return _item;
}));
}
// extract time format from a completed date format 'YYYY-MM-DD HH:mm' -> 'HH:mm'
export function extractTimeFormat(dateFormat: string = '') {
const res = dateFormat.match(/(a\s)?h{1,2}:m{1,2}(:s{1,2})?(\sa)?/i);
if (!res) return null;
return res[0];
}
/**
* 返回时间对象的小时、分钟、秒、12小时制标识
* @param {String} timeFormat 'pm 20:11:11:333'
* @returns {Object}
*/
export function extractTimeObj(timeFormat: string = '') {
const matchedMeridiem = timeFormat.match(/[ap]m/i) || [''];
const timeReg = /\d{1,2}:\d{1,2}(:\d{1,2})?(:\d{1,3})?/;
const matchedTimeStr = timeFormat.match(timeReg) || ['0:0:0:0'];
const [hours = 0, minutes = 0, seconds = 0, milliseconds = 0] = matchedTimeStr[0].split(':');
return {
hours: +hours,
minutes: +minutes,
seconds: +seconds,
milliseconds: +milliseconds,
meridiem: matchedMeridiem[0],
};
}
/**
* 日期是否可用
* @param {Object} { value, disableDate, mode, format }
* @returns {Boolean}
*/
export function isEnabledDate({
value,
disableDate,
mode,
format,
}: {
value: Date;
mode: 'year' | 'month' | 'date';
format: string;
disableDate: DisableDate;
}): boolean {
if (!disableDate) return true;
let isEnabled = true;
// 值类型为 Function 则表示返回值为 true 的日期会被禁用
if (typeof disableDate === 'function') {
return !disableDate(value);
}
// 禁用日期,示例:['A', 'B'] 表示日期 A 和日期 B 会被禁用。
if (Array.isArray(disableDate)) {
const formattedDisabledDate = disableDate.map((item: string) => dayjs(item, format));
// eslint-disable-next-line
const isIncludes = formattedDisabledDate.some(item => item.isSame(dayjs(value)));
return !isIncludes;
}
// { from: 'A', to: 'B' } 表示在 A 到 B 之间的日期会被禁用。
// eslint-disable-next-line
const { from, to, before, after } = disableDate;
if (from && to) {
const compareMin = dayjs(new Date(from));
const compareMax = dayjs(new Date(to));
return !dayjs(value).isBetween(compareMin, compareMax, mode, '[]');
}
const min = before ? new Date(before) : null;
const max = after ? new Date(after) : null;
// { before: 'A', after: 'B' } 表示在 A 之前和在 B 之后的日期都会被禁用。
if (max && min) {
const compareMin = dayjs(new Date(min));
const compareMax = dayjs(new Date(max));
isEnabled = dayjs(value).isBetween(compareMin, compareMax, mode, '[]');
} else if (min) {
const compareMin = dayjs(new Date(min));
isEnabled = !dayjs(value).isBefore(compareMin, mode);
} else if (max) {
const compareMax = dayjs(new Date(max));
isEnabled = !dayjs(value).isAfter(compareMax, mode);
}
return isEnabled;
} | the_stack |
import { keyMap } from '../jsutils/keyMap';
import { inspect } from '../jsutils/inspect';
import { mapValue } from '../jsutils/mapValue';
import { invariant } from '../jsutils/invariant';
import { devAssert } from '../jsutils/devAssert';
import type { Maybe } from '../jsutils/Maybe';
import type {
DocumentNode,
TypeNode,
NamedTypeNode,
SchemaDefinitionNode,
SchemaExtensionNode,
TypeDefinitionNode,
InterfaceTypeDefinitionNode,
InterfaceTypeExtensionNode,
ObjectTypeDefinitionNode,
ObjectTypeExtensionNode,
UnionTypeDefinitionNode,
UnionTypeExtensionNode,
FieldDefinitionNode,
InputObjectTypeDefinitionNode,
InputObjectTypeExtensionNode,
InputValueDefinitionNode,
EnumTypeDefinitionNode,
EnumTypeExtensionNode,
EnumValueDefinitionNode,
DirectiveDefinitionNode,
ScalarTypeDefinitionNode,
ScalarTypeExtensionNode,
} from '../language/ast';
import { Kind } from '../language/kinds';
import {
isTypeDefinitionNode,
isTypeExtensionNode,
} from '../language/predicates';
import { assertValidSDLExtension } from '../validation/validate';
import { getDirectiveValues } from '../execution/values';
import type {
GraphQLSchemaValidationOptions,
GraphQLSchemaNormalizedConfig,
} from '../type/schema';
import type {
GraphQLType,
GraphQLNamedType,
GraphQLFieldConfig,
GraphQLFieldConfigMap,
GraphQLArgumentConfig,
GraphQLFieldConfigArgumentMap,
GraphQLEnumValueConfigMap,
GraphQLInputFieldConfigMap,
} from '../type/definition';
import { assertSchema, GraphQLSchema } from '../type/schema';
import { specifiedScalarTypes, isSpecifiedScalarType } from '../type/scalars';
import { introspectionTypes, isIntrospectionType } from '../type/introspection';
import {
GraphQLDirective,
GraphQLDeprecatedDirective,
GraphQLSpecifiedByDirective,
} from '../type/directives';
import {
isScalarType,
isObjectType,
isInterfaceType,
isUnionType,
isListType,
isNonNullType,
isEnumType,
isInputObjectType,
GraphQLList,
GraphQLNonNull,
GraphQLScalarType,
GraphQLObjectType,
GraphQLInterfaceType,
GraphQLUnionType,
GraphQLEnumType,
GraphQLInputObjectType,
} from '../type/definition';
import { valueFromAST } from './valueFromAST';
interface Options extends GraphQLSchemaValidationOptions {
/**
* Set to true to assume the SDL is valid.
*
* Default: false
*/
assumeValidSDL?: boolean;
}
/**
* Produces a new schema given an existing schema and a document which may
* contain GraphQL type extensions and definitions. The original schema will
* remain unaltered.
*
* Because a schema represents a graph of references, a schema cannot be
* extended without effectively making an entire copy. We do not know until it's
* too late if subgraphs remain unchanged.
*
* This algorithm copies the provided schema, applying extensions while
* producing the copy. The original schema remains unaltered.
*/
export function extendSchema(
schema: GraphQLSchema,
documentAST: DocumentNode,
options?: Options,
): GraphQLSchema {
assertSchema(schema);
devAssert(
documentAST != null && documentAST.kind === Kind.DOCUMENT,
'Must provide valid Document AST.',
);
if (options?.assumeValid !== true && options?.assumeValidSDL !== true) {
assertValidSDLExtension(documentAST, schema);
}
const schemaConfig = schema.toConfig();
const extendedConfig = extendSchemaImpl(schemaConfig, documentAST, options);
return schemaConfig === extendedConfig
? schema
: new GraphQLSchema(extendedConfig);
}
/**
* @internal
*/
export function extendSchemaImpl(
schemaConfig: GraphQLSchemaNormalizedConfig,
documentAST: DocumentNode,
options?: Options,
): GraphQLSchemaNormalizedConfig {
// Collect the type definitions and extensions found in the document.
const typeDefs: Array<TypeDefinitionNode> = [];
const typeExtensionsMap = Object.create(null);
// New directives and types are separate because a directives and types can
// have the same name. For example, a type named "skip".
const directiveDefs: Array<DirectiveDefinitionNode> = [];
let schemaDef: Maybe<SchemaDefinitionNode>;
// Schema extensions are collected which may add additional operation types.
const schemaExtensions: Array<SchemaExtensionNode> = [];
for (const def of documentAST.definitions) {
if (def.kind === Kind.SCHEMA_DEFINITION) {
schemaDef = def;
} else if (def.kind === Kind.SCHEMA_EXTENSION) {
schemaExtensions.push(def);
} else if (isTypeDefinitionNode(def)) {
typeDefs.push(def);
} else if (isTypeExtensionNode(def)) {
const extendedTypeName = def.name.value;
const existingTypeExtensions = typeExtensionsMap[extendedTypeName];
typeExtensionsMap[extendedTypeName] = existingTypeExtensions
? existingTypeExtensions.concat([def])
: [def];
} else if (def.kind === Kind.DIRECTIVE_DEFINITION) {
directiveDefs.push(def);
}
}
// If this document contains no new types, extensions, or directives then
// return the same unmodified GraphQLSchema instance.
if (
Object.keys(typeExtensionsMap).length === 0 &&
typeDefs.length === 0 &&
directiveDefs.length === 0 &&
schemaExtensions.length === 0 &&
schemaDef == null
) {
return schemaConfig;
}
const typeMap = Object.create(null);
for (const existingType of schemaConfig.types) {
typeMap[existingType.name] = extendNamedType(existingType);
}
for (const typeNode of typeDefs) {
const name = typeNode.name.value;
typeMap[name] = stdTypeMap[name] ?? buildType(typeNode);
}
const operationTypes = {
// Get the extended root operation types.
query: schemaConfig.query && replaceNamedType(schemaConfig.query),
mutation: schemaConfig.mutation && replaceNamedType(schemaConfig.mutation),
subscription:
schemaConfig.subscription && replaceNamedType(schemaConfig.subscription),
// Then, incorporate schema definition and all schema extensions.
...(schemaDef && getOperationTypes([schemaDef])),
...getOperationTypes(schemaExtensions),
};
// Then produce and return a Schema config with these types.
return {
description: schemaDef?.description?.value,
...operationTypes,
types: Object.values(typeMap),
directives: [
...schemaConfig.directives.map(replaceDirective),
...directiveDefs.map(buildDirective),
],
extensions: Object.create(null),
astNode: schemaDef ?? schemaConfig.astNode,
extensionASTNodes: schemaConfig.extensionASTNodes.concat(schemaExtensions),
assumeValid: options?.assumeValid ?? false,
};
// Below are functions used for producing this schema that have closed over
// this scope and have access to the schema, cache, and newly defined types.
function replaceType<T extends GraphQLType>(type: T): T {
if (isListType(type)) {
// @ts-expect-error
return new GraphQLList(replaceType(type.ofType));
}
if (isNonNullType(type)) {
// @ts-expect-error
return new GraphQLNonNull(replaceType(type.ofType));
}
// @ts-expect-error FIXME
return replaceNamedType(type);
}
function replaceNamedType<T extends GraphQLNamedType>(type: T): T {
// Note: While this could make early assertions to get the correctly
// typed values, that would throw immediately while type system
// validation with validateSchema() will produce more actionable results.
return typeMap[type.name];
}
function replaceDirective(directive: GraphQLDirective): GraphQLDirective {
const config = directive.toConfig();
return new GraphQLDirective({
...config,
args: mapValue(config.args, extendArg),
});
}
function extendNamedType(type: GraphQLNamedType): GraphQLNamedType {
if (isIntrospectionType(type) || isSpecifiedScalarType(type)) {
// Builtin types are not extended.
return type;
}
if (isScalarType(type)) {
return extendScalarType(type);
}
if (isObjectType(type)) {
return extendObjectType(type);
}
if (isInterfaceType(type)) {
return extendInterfaceType(type);
}
if (isUnionType(type)) {
return extendUnionType(type);
}
if (isEnumType(type)) {
return extendEnumType(type);
}
// istanbul ignore else (See: 'https://github.com/graphql/graphql-js/issues/2618')
if (isInputObjectType(type)) {
return extendInputObjectType(type);
}
// istanbul ignore next (Not reachable. All possible types have been considered)
invariant(false, 'Unexpected type: ' + inspect(type));
}
function extendInputObjectType(
type: GraphQLInputObjectType,
): GraphQLInputObjectType {
const config = type.toConfig();
const extensions = typeExtensionsMap[config.name] ?? [];
return new GraphQLInputObjectType({
...config,
fields: () => ({
...mapValue(config.fields, (field) => ({
...field,
type: replaceType(field.type),
})),
...buildInputFieldMap(extensions),
}),
extensionASTNodes: config.extensionASTNodes.concat(extensions),
});
}
function extendEnumType(type: GraphQLEnumType): GraphQLEnumType {
const config = type.toConfig();
const extensions = typeExtensionsMap[type.name] ?? [];
return new GraphQLEnumType({
...config,
values: {
...config.values,
...buildEnumValueMap(extensions),
},
extensionASTNodes: config.extensionASTNodes.concat(extensions),
});
}
function extendScalarType(type: GraphQLScalarType): GraphQLScalarType {
const config = type.toConfig();
const extensions = typeExtensionsMap[config.name] ?? [];
let specifiedByURL = config.specifiedByURL;
for (const extensionNode of extensions) {
specifiedByURL = getSpecifiedByURL(extensionNode) ?? specifiedByURL;
}
return new GraphQLScalarType({
...config,
specifiedByURL,
extensionASTNodes: config.extensionASTNodes.concat(extensions),
});
}
function extendObjectType(type: GraphQLObjectType): GraphQLObjectType {
const config = type.toConfig();
const extensions = typeExtensionsMap[config.name] ?? [];
return new GraphQLObjectType({
...config,
interfaces: () => [
...type.getInterfaces().map(replaceNamedType),
...buildInterfaces(extensions),
],
fields: () => ({
...mapValue(config.fields, extendField),
...buildFieldMap(extensions),
}),
extensionASTNodes: config.extensionASTNodes.concat(extensions),
});
}
function extendInterfaceType(
type: GraphQLInterfaceType,
): GraphQLInterfaceType {
const config = type.toConfig();
const extensions = typeExtensionsMap[config.name] ?? [];
return new GraphQLInterfaceType({
...config,
interfaces: () => [
...type.getInterfaces().map(replaceNamedType),
...buildInterfaces(extensions),
],
fields: () => ({
...mapValue(config.fields, extendField),
...buildFieldMap(extensions),
}),
extensionASTNodes: config.extensionASTNodes.concat(extensions),
});
}
function extendUnionType(type: GraphQLUnionType): GraphQLUnionType {
const config = type.toConfig();
const extensions = typeExtensionsMap[config.name] ?? [];
return new GraphQLUnionType({
...config,
types: () => [
...type.getTypes().map(replaceNamedType),
...buildUnionTypes(extensions),
],
extensionASTNodes: config.extensionASTNodes.concat(extensions),
});
}
function extendField(
field: GraphQLFieldConfig<unknown, unknown>,
): GraphQLFieldConfig<unknown, unknown> {
return {
...field,
type: replaceType(field.type),
args: field.args && mapValue(field.args, extendArg),
};
}
function extendArg(arg: GraphQLArgumentConfig) {
return {
...arg,
type: replaceType(arg.type),
};
}
function getOperationTypes(
nodes: ReadonlyArray<SchemaDefinitionNode | SchemaExtensionNode>,
): {
query?: Maybe<GraphQLObjectType>;
mutation?: Maybe<GraphQLObjectType>;
subscription?: Maybe<GraphQLObjectType>;
} {
const opTypes = {};
for (const node of nodes) {
// istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2203')
const operationTypesNodes = node.operationTypes ?? [];
for (const operationType of operationTypesNodes) {
// Note: While this could make early assertions to get the correctly
// typed values below, that would throw immediately while type system
// validation with validateSchema() will produce more actionable results.
// @ts-expect-error
opTypes[operationType.operation] = getNamedType(operationType.type);
}
}
return opTypes;
}
function getNamedType(node: NamedTypeNode): GraphQLNamedType {
const name = node.name.value;
const type = stdTypeMap[name] ?? typeMap[name];
if (type === undefined) {
throw new Error(`Unknown type: "${name}".`);
}
return type;
}
function getWrappedType(node: TypeNode): GraphQLType {
if (node.kind === Kind.LIST_TYPE) {
return new GraphQLList(getWrappedType(node.type));
}
if (node.kind === Kind.NON_NULL_TYPE) {
return new GraphQLNonNull(getWrappedType(node.type));
}
return getNamedType(node);
}
function buildDirective(node: DirectiveDefinitionNode): GraphQLDirective {
return new GraphQLDirective({
name: node.name.value,
description: node.description?.value,
// @ts-expect-error
locations: node.locations.map(({ value }) => value),
isRepeatable: node.repeatable,
args: buildArgumentMap(node.arguments),
astNode: node,
});
}
function buildFieldMap(
nodes: ReadonlyArray<
| InterfaceTypeDefinitionNode
| InterfaceTypeExtensionNode
| ObjectTypeDefinitionNode
| ObjectTypeExtensionNode
>,
): GraphQLFieldConfigMap<unknown, unknown> {
const fieldConfigMap = Object.create(null);
for (const node of nodes) {
// istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2203')
const nodeFields = node.fields ?? [];
for (const field of nodeFields) {
fieldConfigMap[field.name.value] = {
// Note: While this could make assertions to get the correctly typed
// value, that would throw immediately while type system validation
// with validateSchema() will produce more actionable results.
type: getWrappedType(field.type),
description: field.description?.value,
args: buildArgumentMap(field.arguments),
deprecationReason: getDeprecationReason(field),
astNode: field,
};
}
}
return fieldConfigMap;
}
function buildArgumentMap(
args: Maybe<ReadonlyArray<InputValueDefinitionNode>>,
): GraphQLFieldConfigArgumentMap {
// istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2203')
const argsNodes = args ?? [];
const argConfigMap = Object.create(null);
for (const arg of argsNodes) {
// Note: While this could make assertions to get the correctly typed
// value, that would throw immediately while type system validation
// with validateSchema() will produce more actionable results.
const type: any = getWrappedType(arg.type);
argConfigMap[arg.name.value] = {
type,
description: arg.description?.value,
defaultValue: valueFromAST(arg.defaultValue, type),
deprecationReason: getDeprecationReason(arg),
astNode: arg,
};
}
return argConfigMap;
}
function buildInputFieldMap(
nodes: ReadonlyArray<
InputObjectTypeDefinitionNode | InputObjectTypeExtensionNode
>,
): GraphQLInputFieldConfigMap {
const inputFieldMap = Object.create(null);
for (const node of nodes) {
// istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2203')
const fieldsNodes = node.fields ?? [];
for (const field of fieldsNodes) {
// Note: While this could make assertions to get the correctly typed
// value, that would throw immediately while type system validation
// with validateSchema() will produce more actionable results.
const type: any = getWrappedType(field.type);
inputFieldMap[field.name.value] = {
type,
description: field.description?.value,
defaultValue: valueFromAST(field.defaultValue, type),
deprecationReason: getDeprecationReason(field),
astNode: field,
};
}
}
return inputFieldMap;
}
function buildEnumValueMap(
nodes: ReadonlyArray<EnumTypeDefinitionNode | EnumTypeExtensionNode>,
): GraphQLEnumValueConfigMap {
const enumValueMap = Object.create(null);
for (const node of nodes) {
// istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2203')
const valuesNodes = node.values ?? [];
for (const value of valuesNodes) {
enumValueMap[value.name.value] = {
description: value.description?.value,
deprecationReason: getDeprecationReason(value),
astNode: value,
};
}
}
return enumValueMap;
}
function buildInterfaces(
nodes: ReadonlyArray<
| InterfaceTypeDefinitionNode
| InterfaceTypeExtensionNode
| ObjectTypeDefinitionNode
| ObjectTypeExtensionNode
>,
): Array<GraphQLInterfaceType> {
// Note: While this could make assertions to get the correctly typed
// values below, that would throw immediately while type system
// validation with validateSchema() will produce more actionable results.
// @ts-expect-error
return nodes.flatMap(
// istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2203')
(node) => node.interfaces?.map(getNamedType) ?? [],
);
}
function buildUnionTypes(
nodes: ReadonlyArray<UnionTypeDefinitionNode | UnionTypeExtensionNode>,
): Array<GraphQLObjectType> {
// Note: While this could make assertions to get the correctly typed
// values below, that would throw immediately while type system
// validation with validateSchema() will produce more actionable results.
// @ts-expect-error
return nodes.flatMap(
// istanbul ignore next (See: 'https://github.com/graphql/graphql-js/issues/2203')
(node) => node.types?.map(getNamedType) ?? [],
);
}
function buildType(astNode: TypeDefinitionNode): GraphQLNamedType {
const name = astNode.name.value;
const extensionASTNodes = typeExtensionsMap[name] ?? [];
switch (astNode.kind) {
case Kind.OBJECT_TYPE_DEFINITION: {
const allNodes = [astNode, ...extensionASTNodes];
return new GraphQLObjectType({
name,
description: astNode.description?.value,
interfaces: () => buildInterfaces(allNodes),
fields: () => buildFieldMap(allNodes),
astNode,
extensionASTNodes,
});
}
case Kind.INTERFACE_TYPE_DEFINITION: {
const allNodes = [astNode, ...extensionASTNodes];
return new GraphQLInterfaceType({
name,
description: astNode.description?.value,
interfaces: () => buildInterfaces(allNodes),
fields: () => buildFieldMap(allNodes),
astNode,
extensionASTNodes,
});
}
case Kind.ENUM_TYPE_DEFINITION: {
const allNodes = [astNode, ...extensionASTNodes];
return new GraphQLEnumType({
name,
description: astNode.description?.value,
values: buildEnumValueMap(allNodes),
astNode,
extensionASTNodes,
});
}
case Kind.UNION_TYPE_DEFINITION: {
const allNodes = [astNode, ...extensionASTNodes];
return new GraphQLUnionType({
name,
description: astNode.description?.value,
types: () => buildUnionTypes(allNodes),
astNode,
extensionASTNodes,
});
}
case Kind.SCALAR_TYPE_DEFINITION: {
return new GraphQLScalarType({
name,
description: astNode.description?.value,
specifiedByURL: getSpecifiedByURL(astNode),
astNode,
extensionASTNodes,
});
}
case Kind.INPUT_OBJECT_TYPE_DEFINITION: {
const allNodes = [astNode, ...extensionASTNodes];
return new GraphQLInputObjectType({
name,
description: astNode.description?.value,
fields: () => buildInputFieldMap(allNodes),
astNode,
extensionASTNodes,
});
}
}
// istanbul ignore next (Not reachable. All possible type definition nodes have been considered)
invariant(false, 'Unexpected type definition node: ' + inspect(astNode));
}
}
const stdTypeMap = keyMap(
[...specifiedScalarTypes, ...introspectionTypes],
(type) => type.name,
);
/**
* Given a field or enum value node, returns the string value for the
* deprecation reason.
*/
function getDeprecationReason(
node:
| EnumValueDefinitionNode
| FieldDefinitionNode
| InputValueDefinitionNode,
): Maybe<string> {
const deprecated = getDirectiveValues(GraphQLDeprecatedDirective, node);
// @ts-expect-error validated by `getDirectiveValues`
return deprecated?.reason;
}
/**
* Given a scalar node, returns the string value for the specifiedByURL.
*/
function getSpecifiedByURL(
node: ScalarTypeDefinitionNode | ScalarTypeExtensionNode,
): Maybe<string> {
const specifiedBy = getDirectiveValues(GraphQLSpecifiedByDirective, node);
// @ts-expect-error validated by `getDirectiveValues`
return specifiedBy?.url;
} | the_stack |
import assert = require("assert")
import services=require("../definition-system/ramlServices");
import apiLoader = require("../apiLoader")
import RamlWrapper = require("../artifacts/raml10parserapi")
import _=require("underscore")
import path=require("path")
import util = require("./test-utils")
import tools = require("./testTools")
import core = require("../wrapped-ast/parserCore")
var dir=path.resolve(__dirname,"../../../src/parser/test/")
describe('To Runtime Tests',function(){
this.timeout(15000);
it ("Basic inheritance",function(){
var rsm=apiLoader.loadApi(path.resolve(dir,"data/typeSystem.raml"));
var mt=_.find((<RamlWrapper.Api>util.expandWrapperIfNeeded(rsm.getOrElse(null))).types(),x=>x.name()=="AnotherType");
var supers=mt.runtimeType().superTypes();
assert.equal(supers.length,1);
});
it ("Inheritance 1",function(){
var rsm=apiLoader.loadApi(path.resolve(dir,"data/typeSystem.raml"));
var mt=_.find((<RamlWrapper.Api>util.expandWrapperIfNeeded(rsm.getOrElse(null))).types(),x=>x.name()=="AnotherType2");
var supers=mt.runtimeType().superTypes();
assert.equal(supers.length,1);
});
it ("Runtime Prop",function(){
var rsm=apiLoader.loadApi(path.resolve(dir,"data/typeSystem.raml"));
var mt=_.find((<RamlWrapper.Api>util.expandWrapperIfNeeded(rsm.getOrElse(null))).types(),x=>x.name()=="AnotherType2");
var props=mt.runtimeType().properties();
assert.equal(props.length,1);
});
it ("Runtime Prop type",function(){
var rsm=apiLoader.loadApi(path.resolve(dir,"data/typeSystem.raml"));
var mt=_.find((<RamlWrapper.Api>util.expandWrapperIfNeeded(rsm.getOrElse(null))).types(),x=>x.name()=="AnotherType2");
var props=mt.runtimeType().properties();
assert.equal(props[0].range().hasValueTypeInHierarchy(),true);
});
it ("Array type",function(){
var rsm=apiLoader.loadApi(path.resolve(dir,"data/typeSystem.raml"));
var mt=_.find((<RamlWrapper.Api>util.expandWrapperIfNeeded(rsm.getOrElse(null))).types(),x=>x.name()=="Arr");
var props=mt.runtimeType().properties();
assert.equal(props.length,0);
assert.equal(mt.runtimeType().hasArrayInHierarchy(),true);
assert.equal(mt.runtimeType().arrayInHierarchy().componentType().properties().length,1)
});
it ("Array type 2",function(){
var rsm=apiLoader.loadApi(path.resolve(dir,"data/typeSystem.raml"));
var mt=_.find((<RamlWrapper.Api>util.expandWrapperIfNeeded(rsm.getOrElse(null))).types(),x=>x.name()=="Arr");
var props=mt.runtimeType().properties();
assert.equal(props.length,0);
assert.equal(mt.runtimeType().isArray(),true);
assert.equal(mt.runtimeType().array().componentType().properties().length,1)
});
//it ("Array type 3",function(){
// var rsm=util.loadApiWrapper1("typeSystem.raml");
// var resource = tools.collectionItem(rsm.resources(), 1);
// var method = tools.collectionItem(resource.methods(), 0);
// var body = tools.collectionItem(method.body(), 0);
//
// var runtimeType = body.runtimeDefinition();
//
// assert.equal(runtimeType.isArray(), false);
//});
it ("Union Type",function(){
var rsm=apiLoader.loadApi(path.resolve(dir,"data/typeSystem.raml"));
var mt=_.find((<RamlWrapper.Api>util.expandWrapperIfNeeded(rsm.getOrElse(null))).types(),x=>x.name()=="Un");
var props=mt.runtimeType().properties();
assert.equal(props.length,0);
assert.equal(mt.runtimeType().hasUnionInHierarchy(),true);
assert.equal(mt.runtimeType().unionInHierarchy().leftType().arrayInHierarchy().componentType().properties().length,1)
});
it ("Union Type 2",function(){
var rsm=apiLoader.loadApi(path.resolve(dir,"data/typeSystem.raml"));
var mt=_.find((<RamlWrapper.Api>util.expandWrapperIfNeeded(rsm.getOrElse(null))).types(),x=>x.name()=="Un");
var props=mt.runtimeType().properties();
assert.equal(props.length,0);
assert.equal(mt.runtimeDefinition().isUnion(),true);
assert.equal(mt.runtimeDefinition().union().leftType().arrayInHierarchy().componentType().properties().length,1)
});
//it ("Union Type 3",function(){
// var rsm=util.loadApiWrapper1("typeSystem.raml");
// var resource = tools.collectionItem(rsm.resources(), 0);
// var method = tools.collectionItem(resource.methods(), 0);
// var body = tools.collectionItem(method.body(), 0);
//
// var runtimeType = body.runtimeDefinition();
//
// assert.equal(runtimeType.isUnion(), false);
//});
//it ("Facet access",function(){
// var rsm=apiLoader.loadApi(path.resolve(dir,"data/typeSystem.raml"));
// var mt=_.find((<RamlWrapper.Api>util.expandWrapperIfNeeded(rsm.getOrElse(null))).types(),x=>x.name()=="Facet");
// var z=mt.runtimeType();
// var f=z.getAdapter(services.RAMLService).getRepresentationOf().getFixedFacets();
// assert.equal(Object.keys(f).length,3);
//}); Not relevant any more
it ("Value type 1",function(){
var rsm=apiLoader.loadApi(path.resolve(dir,"data/typeSystem.raml"));
var mt=_.find((<RamlWrapper.Api>util.expandWrapperIfNeeded(rsm.getOrElse(null))).types(),x=>x.name()=="Facet");
var z=mt.runtimeType();
assert.equal(z.hasValueTypeInHierarchy(), true);
});
it ("Value type 2",function(){
var rsm=apiLoader.loadApi(path.resolve(dir,"data/typeSystem.raml"));
var mt=_.find((<RamlWrapper.Api>util.expandWrapperIfNeeded(rsm.getOrElse(null))).types(),x=>x.name()=="Facet");
var z=mt.runtimeType();
assert.equal(z.isValueType(), true);
});
it ("Value type 3",function(){
var rsm=apiLoader.loadApi(path.resolve(dir,"data/typeSystem.raml")).getOrElse(null);
var resource = tools.collectionItem(rsm.resources(), 2);
var method = tools.collectionItem(resource.methods(), 0);
var body = tools.collectionItem(method.body(), 0);
var runtimeType = body.runtimeDefinition();
assert.equal(runtimeType.isUnion(), false);
});
it ("Multiple inheritance",function(){
var rsm=apiLoader.loadApi(path.resolve(dir,"data/typeSystem.raml"));
var mt=_.find((<RamlWrapper.Api>util.expandWrapperIfNeeded(rsm.getOrElse(null))).types(),x=>x.name()=="T4");
var z=mt.runtimeType();
var f=z.allProperties();
assert.equal(f.length,3);
});
it ("Inheritance loop",function(){
var rsm=apiLoader.loadApi(path.resolve(dir,"data/typeSystem.raml"));
var mt=_.find((<RamlWrapper.Api>util.expandWrapperIfNeeded(rsm.getOrElse(null))).types(),x=>x.name()=="T6");
var z=mt.runtimeType();
var f=z.allProperties();
assert.equal(f.length,3);
});
it('Node by runtime type', function () {
var api = apiLoader.loadApi(path.resolve(dir,"data/typeSystem.raml")).getOrElse(null);
var typeNode1 = tools.collectionItem((<any>api).types(), 0);
var runtimeType = typeNode1.runtimeType();
var nodeByType = apiLoader.getLanguageElementByRuntimeType(runtimeType);
assert.equal(typeNode1.name(), (<any>nodeByType).name())
});
});
describe('Nominal Hierarchy Genuine User Defined Tests',function(){
this.timeout(15000);
it ("Genuine User Defined 1",function(){
var rsm=apiLoader.loadApi(path.resolve(dir,"data/typesystem/genuine.raml"));
var type=_.find((<RamlWrapper.Api>util.expandWrapperIfNeeded(rsm.getOrElse(null))).types(),x=>x.name()=="TestType1");
var runtimeType = type.runtimeType();
assert.equal(runtimeType.isGenuineUserDefinedType(), true);
});
it ("Genuine User Defined 2",function(){
var rsm=apiLoader.loadApi(path.resolve(dir,"data/typesystem/genuine.raml"));
var type=_.find((<RamlWrapper.Api>util.expandWrapperIfNeeded(rsm.getOrElse(null))).types(),x=>x.name()=="TestType2");
var runtimeType = type.runtimeType();
assert.equal(runtimeType.isGenuineUserDefinedType(), true);
});
it ("Genuine User Defined 3",function(){
var rsm=apiLoader.loadApi(path.resolve(dir,"data/typesystem/genuine.raml"));
var type=_.find((<RamlWrapper.Api>util.expandWrapperIfNeeded(rsm.getOrElse(null))).types(),x=>x.name()=="TestType3");
var runtimeType = type.runtimeType();
assert.equal(runtimeType.isGenuineUserDefinedType(), true);
});
it ("Genuine User Defined 4",function(){
var rsm=apiLoader.loadApi(path.resolve(dir,"data/typesystem/genuine.raml"));
var type=_.find((<RamlWrapper.Api>util.expandWrapperIfNeeded(rsm.getOrElse(null))).types(),x=>x.name()=="TestType4");
var runtimeType = type.runtimeType();
assert.equal(runtimeType.isGenuineUserDefinedType(), true);
});
it ("Genuine User Defined 5",function(){
var rsm=apiLoader.loadApi(path.resolve(dir,"data/typesystem/genuine.raml"));
var type=_.find((<RamlWrapper.Api>util.expandWrapperIfNeeded(rsm.getOrElse(null))).types(),x=>x.name()=="TestType5");
var runtimeType = type.runtimeType();
assert.equal(runtimeType.isGenuineUserDefinedType(), true);
});
it ("Genuine User Defined 6",function(){
var rsm=apiLoader.loadApi(path.resolve(dir,"data/typesystem/genuine.raml"));
var type=_.find((<RamlWrapper.Api>util.expandWrapperIfNeeded(rsm.getOrElse(null))).types(),x=>x.name()=="TestType6");
var runtimeType = type.runtimeType();
assert.equal(runtimeType.isGenuineUserDefinedType(), true);
});
it ("Genuine User Defined 7",function(){
var rsm=apiLoader.loadApi(path.resolve(dir,"data/typesystem/genuine.raml"));
var type=_.find((<RamlWrapper.Api>util.expandWrapperIfNeeded(rsm.getOrElse(null))).types(),x=>x.name()=="TestType7");
var runtimeType = type.runtimeType();
assert.equal(runtimeType.isGenuineUserDefinedType(), true);
});
it ("Genuine User Defined Method Response 1",function(){
var api=apiLoader.loadApi(path.resolve(dir,"data/typesystem/genuine.raml")).getOrElse(null);
var method = api.resources()[0].methods()[0];
var response = method.responses()[0];
var type = response.body()[0];
var runtimeType = (<RamlWrapper.TypeDeclaration>type).runtimeType();
console.log("----DEBUG: " + runtimeType.nameId()+"/"+runtimeType.isGenuineUserDefinedType())
assert.equal(runtimeType.isGenuineUserDefinedType(), false);
});
it ("Genuine User Defined Method Response 2",function(){
var api=apiLoader.loadApi(path.resolve(dir,"data/typesystem/genuine.raml")).getOrElse(null);
var method = api.resources()[0].methods()[0];
var response = method.responses()[1];
var type = response.body()[0];
var runtimeType = (<RamlWrapper.TypeDeclaration>type).runtimeType();
assert.equal(runtimeType.isGenuineUserDefinedType(), false);
});
it ("Genuine User Defined Method Response 3",function(){
var api=apiLoader.loadApi(path.resolve(dir,"data/typesystem/genuine.raml")).getOrElse(null);
var method = api.resources()[0].methods()[0];
var response = method.responses()[2];
var type = response.body()[0];
var runtimeType = (<RamlWrapper.TypeDeclaration>type).runtimeType();
assert.equal(runtimeType.isGenuineUserDefinedType(), false);
});
it ("Genuine User Defined Method Response 4",function(){
var api=apiLoader.loadApi(path.resolve(dir,"data/typesystem/genuine.raml")).getOrElse(null);
var method = api.resources()[0].methods()[0];
var response = method.responses()[3];
var type = response.body()[0];
var runtimeType = (<RamlWrapper.TypeDeclaration>type).runtimeType();
assert.equal(runtimeType.isGenuineUserDefinedType(), false);
});
it ("Genuine User Defined Method Response 5",function(){
var api=apiLoader.loadApi(path.resolve(dir,"data/typesystem/genuine.raml")).getOrElse(null);
var method = api.resources()[0].methods()[0];
var response = method.responses()[4];
var type = response.body()[0];
var runtimeType = (<RamlWrapper.TypeDeclaration>type).runtimeType();
assert.equal(runtimeType.isGenuineUserDefinedType(), false);
});
it ("Genuine User Defined Method Response 6",function(){
var api=apiLoader.loadApi(path.resolve(dir,"data/typesystem/genuine.raml")).getOrElse(null);
var method = api.resources()[0].methods()[0];
var response = method.responses()[5];
var type = response.body()[0];
var runtimeType = (<RamlWrapper.TypeDeclaration>type).runtimeType();
assert.equal(runtimeType.isGenuineUserDefinedType(), true);
});
it ("Genuine User Defined Method Response 7",function(){
var api=apiLoader.loadApi(path.resolve(dir,"data/typesystem/genuine.raml")).getOrElse(null);
var method = api.resources()[0].methods()[0];
var response = method.responses()[6];
var type = response.body()[0];
var runtimeType = (<RamlWrapper.TypeDeclaration>type).runtimeType();
assert.equal(runtimeType.isGenuineUserDefinedType(), false);
});
it ("Genuine User Defined Method Response 7",function(){
var api=apiLoader.loadApi(path.resolve(dir,"data/typesystem/genuine.raml")).getOrElse(null);
var method = api.resources()[0].methods()[0];
var response = method.responses()[7];
var type = response.body()[0];
var runtimeType = (<RamlWrapper.TypeDeclaration>type).runtimeType();
assert.equal(runtimeType.isGenuineUserDefinedType(), true);
});
it ("Genuine User Defined Method Response In hierarchy 1",function(){
var api=apiLoader.loadApi(path.resolve(dir,"data/typesystem/genuine.raml")).getOrElse(null);
var method = api.resources()[0].methods()[0];
var response = method.responses()[0];
var type = response.body()[0];
var runtimeType = (<RamlWrapper.TypeDeclaration>type).runtimeType();
assert.equal(runtimeType.hasGenuineUserDefinedTypeInHierarchy(), true);
var userDefinedType = runtimeType.genuineUserDefinedTypeInHierarchy();
assert.notEqual(userDefinedType, null);
assert.equal(userDefinedType.nameId(), "TestType1")
});
it ("Genuine User Defined Method Response In hierarchy 2",function(){
var api=apiLoader.loadApi(path.resolve(dir,"data/typesystem/genuine.raml")).getOrElse(null);
var method = api.resources()[0].methods()[0];
var response = method.responses()[1];
var type = response.body()[0];
var runtimeType = (<RamlWrapper.TypeDeclaration>type).runtimeType();
assert.equal(runtimeType.hasGenuineUserDefinedTypeInHierarchy(), true);
var userDefinedType = runtimeType.genuineUserDefinedTypeInHierarchy();
assert.notEqual(userDefinedType, null);
assert.equal(userDefinedType.nameId(), "TestType2")
});
it ("Genuine User Defined Method Response In hierarchy 3",function(){
var api=apiLoader.loadApi(path.resolve(dir,"data/typesystem/genuine.raml")).getOrElse(null);
var method = api.resources()[0].methods()[0];
var response = method.responses()[2];
var type = response.body()[0];
var runtimeType = (<RamlWrapper.TypeDeclaration>type).runtimeType();
assert.equal(runtimeType.hasGenuineUserDefinedTypeInHierarchy(), true);
var userDefinedType = runtimeType.genuineUserDefinedTypeInHierarchy();
assert.notEqual(userDefinedType, null);
assert.equal(userDefinedType.nameId(), "TestType3")
});
it ("Genuine User Defined Method Response In hierarchy 4",function(){
var api=apiLoader.loadApi(path.resolve(dir,"data/typesystem/genuine.raml")).getOrElse(null);
var method = api.resources()[0].methods()[0];
var response = method.responses()[3];
var type = response.body()[0];
var runtimeType = (<RamlWrapper.TypeDeclaration>type).runtimeType();
assert.equal(runtimeType.hasGenuineUserDefinedTypeInHierarchy(), true);
var userDefinedType = runtimeType.genuineUserDefinedTypeInHierarchy();
assert.notEqual(userDefinedType, null);
assert.equal(userDefinedType.nameId(), "TestType4")
});
it ("Genuine User Defined Method Response In hierarchy 5",function(){
var api=apiLoader.loadApi(path.resolve(dir,"data/typesystem/genuine.raml")).getOrElse(null);
var method = api.resources()[0].methods()[0];
var response = method.responses()[4];
var type = response.body()[0];
var runtimeType = (<RamlWrapper.TypeDeclaration>type).runtimeType();
assert.equal(runtimeType.hasGenuineUserDefinedTypeInHierarchy(), true);
var userDefinedType = runtimeType.genuineUserDefinedTypeInHierarchy();
assert.notEqual(userDefinedType, null);
assert.equal(userDefinedType.nameId(), "TestType5")
});
it ("Genuine User Defined Method Response In hierarchy 6",function(){
var api=apiLoader.loadApi(path.resolve(dir,"data/typesystem/genuine.raml")).getOrElse(null);
var method = api.resources()[0].methods()[0];
var response = method.responses()[5];
var type = response.body()[0];
var runtimeType = (<RamlWrapper.TypeDeclaration>type).runtimeType();
assert.equal(runtimeType.hasGenuineUserDefinedTypeInHierarchy(), true);
var userDefinedType = runtimeType.genuineUserDefinedTypeInHierarchy();
assert.notEqual(userDefinedType, null);
assert.equal(userDefinedType.nameId(), "application/xml")
});
it ("Genuine User Defined Method Response In hierarchy 7",function(){
var api=apiLoader.loadApi(path.resolve(dir,"data/typesystem/genuine.raml")).getOrElse(null);
var method = api.resources()[0].methods()[0];
var response = method.responses()[6];
var type = response.body()[0];
var runtimeType = (<RamlWrapper.TypeDeclaration>type).runtimeType();
assert.equal(runtimeType.hasGenuineUserDefinedTypeInHierarchy(), true);
var userDefinedType = runtimeType.genuineUserDefinedTypeInHierarchy();
assert.notEqual(userDefinedType, null);
assert.equal(userDefinedType.nameId(), "TestType7")
});
it ("Genuine User Defined Method Response In hierarchy 8",function(){
var api=apiLoader.loadApi(path.resolve(dir,"data/typesystem/genuine.raml")).getOrElse(null);
var method = api.resources()[0].methods()[0];
var response = method.responses()[7];
var type = response.body()[0];
var runtimeType = (<RamlWrapper.TypeDeclaration>type).runtimeType();
assert.equal(runtimeType.hasGenuineUserDefinedTypeInHierarchy(), true);
var userDefinedType = runtimeType.genuineUserDefinedTypeInHierarchy();
assert.notEqual(userDefinedType, null);
assert.equal(userDefinedType.nameId(), "application/json")
});
it ("Built-in facets for Object type",function(){
var api=apiLoader.loadApi(path.resolve(dir,"data/typesystem/facets.raml")).getOrElse(null);
var type = (<RamlWrapper.Api>api).types()[0];
var expected = {
"displayName": "Test Object Type",
"description": "test object type. type for testing object type built in facets.",
"minProperties": 1,
"maxProperties": 2,
"discriminator": "kind",
"discriminatorValue": "__MyObjectType__",
"additionalProperties": false
};
var ignore:any = {
properties: true,
enum: true
};
testFacets(type,expected,ignore);
});
it ("Pattern Property RegExp",function(){
var api=apiLoader.loadApi(path.resolve(dir,"data/typesystem/facets.raml")).getOrElse(null);
var type = (<RamlWrapper.Api>api).types()[0];
var prop = type.runtimeType().properties()[1];
var regExp = prop.getKeyRegexp();
assert(regExp=="/[a-z]+/");
});
it ("Built-in facets for File type",function(){
var api=apiLoader.loadApi(path.resolve(dir,"data/typesystem/facets.raml")).getOrElse(null);
var type = (<RamlWrapper.Api>api).types()[1];
var expected = {
"displayName": "Test File Type",
"description": "test file type. type for testing file type built in facets.",
"minLength" : 1024,
"maxLength" : 8192,
"fileTypes" : [ "text/txt", "text/doc" ]
};
testFacets(type,expected);
});
it ("Built-in facets for Array type",function(){
var api=apiLoader.loadApi(path.resolve(dir,"data/typesystem/facets.raml")).getOrElse(null);
var type = (<RamlWrapper.Api>api).types()[2];
var expected = {
"displayName": "Test Array Type",
"description": "test array type. type for testing array type built in facets.",
"minItems": 1,
"maxItems": 10,
"uniqueItems": true
};
var ignore:any = {
items: true
};
testFacets(type,expected,ignore);
});
it ("Built-in facets for String type",function(){
var api=apiLoader.loadApi(path.resolve(dir,"data/typesystem/facets.raml")).getOrElse(null);
var type = (<RamlWrapper.Api>api).types()[3];
var expected = {
"displayName": "Test String Type",
"description": "test string type. type for testing string type built in facets.",
"minLength": 3,
"maxLength": 128,
"enum": [ "abcd", "12345" ],
"pattern": "[a-zA-Z0-9]{3,128}",
"default": "abcd"
};
var ignore:any = {
items: true
};
testFacets(type,expected,ignore);
});
it ("Built-in facets for Number type",function(){
var api=apiLoader.loadApi(path.resolve(dir,"data/typesystem/facets.raml")).getOrElse(null);
var type = (<RamlWrapper.Api>api).types()[4];
var expected = {
"displayName": "Test Number Type",
"description": "test number type. type for testing number type built in facets.",
"minimum": 1,
"maximum": 1000,
"multipleOf": 5,
"enum": [ 15, 20, 25, 30 ],
"format": "int8",
"default": 15
};
testFacets(type,expected);
});
it ("Built-in 'allowedTargets' facet",function(){
var api=apiLoader.loadApi(path.resolve(dir,"data/typesystem/facets.raml")).getOrElse(null);
var type = (<RamlWrapper.Api>api).annotationTypes()[0];
var expected = {
"displayName": "Test Annotation Type",
"description": "test Annotation type. type for testing annotation type built in 'allowedTarget' facet.",
"allowedTargets": [ "Method", "Resource" ]
};
var ignore: any = {};
api.highLevel().definition().universe().type("StringTypeDeclaration")
.properties().forEach(x=>ignore[x.nameId()] = true);
testFacets(type,expected,ignore,true);
});
});
function testFacets(typeNode:core.BasicNode,expected:any,ignoredProperties:any={},all=false){
var runtimeType = (<RamlWrapper.TypeDeclaration>typeNode).runtimeType();
var fixedBuiltInFacets:any = all ? runtimeType.allFixedBuiltInFacets() : runtimeType.fixedBuiltInFacets();
var props = [ "displayName", "description" ];
typeNode.highLevel().definition().universe().type(typeNode.kind())
.properties().filter(x=>!ignoredProperties[x.nameId()]).forEach(x=>{
props.push(x.nameId())
});
for(var pName of props){
var eVal = expected[pName];
var aVal = fixedBuiltInFacets[pName];
assert.notEqual(eVal, null);
if (Array.isArray(aVal) && Array.isArray(eVal)) {
aVal = aVal.toString();
eVal = eVal.toString();
}
assert.equal(aVal, eVal);
}
} | the_stack |
import {CSS_PREFIX} from '../const';
import {GrammarRegistry} from '../grammar-registry';
import {LayerLabels} from './decorators/layer-labels';
import * as utils from '../utils/utils';
import * as utilsDom from '../utils/utils-dom';
import * as utilsDraw from '../utils/utils-draw';
import * as d3Quadtree from 'd3-quadtree';
import * as d3Select from 'd3-selection';
const d3 = {
...d3Quadtree,
...d3Select,
};
import {
d3_setAttrs as attrs,
d3_setClasses as classes,
d3_transition
} from '../utils/d3-decorators';
import {
d3Selection,
GrammarElement,
GrammarModel,
GrammarRule
} from '../definitions';
interface Bounds {
left: number;
right: number;
top: number;
bottom: number;
}
interface PointInfo {
node: Element;
data;
x: number;
y: number;
r: number;
}
interface BoundsInfo {
bounds: Bounds;
tree: d3.Quadtree<PointInfo[]>;
}
interface PointClass extends GrammarElement {
_getBoundsInfo(dots: Element[]): BoundsInfo;
highlight(filter: HighlightFilter);
_sortElements(filter: HighlightFilter);
}
interface PointInstance extends PointClass {
_boundsInfo: BoundsInfo;
_getGroupOrder: (g: any[]) => number;
}
type HighlightFilter = (row) => boolean | null;
const Point: PointClass = {
init(xConfig) {
const config = Object.assign({}, xConfig);
config.guide = utils.defaults(
(config.guide || {}),
{
animationSpeed: 0,
avoidScalesOverflow: true,
enableColorToBarPosition: false,
maxHighlightDistance: 32
});
config.guide.size = (config.guide.size || {});
config.guide.label = utils.defaults(
(config.guide.label || {}),
{
position: [
'auto:avoid-label-label-overlap',
'auto:avoid-label-anchor-overlap',
'auto:adjust-on-label-overflow',
'auto:hide-on-label-label-overlap',
'auto:hide-on-label-anchor-overlap'
]
});
const avoidScalesOverflow = config.guide.avoidScalesOverflow;
const enableColorPositioning = config.guide.enableColorToBarPosition;
config.transformRules = [
((prevModel: GrammarModel) => {
const bestBaseScale = [prevModel.scaleX, prevModel.scaleY]
.sort((a, b) => {
var discreteA = a.discrete ? 1 : 0;
var discreteB = b.discrete ? 1 : 0;
return (discreteB * b.domain().length) - (discreteA * a.domain().length);
})
[0];
const isHorizontal = (prevModel.scaleY === bestBaseScale);
return isHorizontal ?
GrammarRegistry.get('flip')(prevModel) :
GrammarRegistry.get('identity')(prevModel);
}),
config.stack && GrammarRegistry.get('stack'),
enableColorPositioning && GrammarRegistry.get('positioningByColor')
]
.filter(x => x);
config.adjustRules = [
(config.stack && GrammarRegistry.get('adjustYScale')),
((prevModel: GrammarModel, args) => {
const isEmptySize = prevModel.scaleSize.isEmptyScale();
const sizeCfg = utils.defaults(
(config.guide.size),
{
defMinSize: 10,
defMaxSize: isEmptySize ? 10 : 40,
enableDistributeEvenly: !isEmptySize
});
const params = Object.assign(
{},
args,
{
defMin: sizeCfg.defMinSize,
defMax: sizeCfg.defMaxSize,
minLimit: sizeCfg.minSize,
maxLimit: sizeCfg.maxSize
});
const method = (sizeCfg.enableDistributeEvenly ?
GrammarRegistry.get('adjustSigmaSizeScale') :
GrammarRegistry.get('adjustStaticSizeScale'));
return method(prevModel, params);
}),
(avoidScalesOverflow && ((prevModel: GrammarModel, args) => {
const params = Object.assign({}, args, {
sizeDirection: 'xy'
});
return GrammarRegistry.get('avoidScalesOverflow')(prevModel, params);
}))
].filter(x => x);
return config;
},
addInteraction() {
const node: PointClass = this.node();
const createFilter = ((data, falsy) => ((row) => row === data ? true : falsy));
node.on('highlight', (sender, filter) => this.highlight(filter));
node.on('data-hover', ((sender, e) => this.highlight(createFilter(e.data, null))));
},
draw(this: PointInstance) {
const node = this.node() as PointClass;
const config = node.config;
const options = config.options;
// TODO: hide it somewhere
options.container = options.slot(config.uid);
const transition = (sel) => {
return d3_transition(sel, config.guide.animationSpeed);
};
const prefix = `${CSS_PREFIX}dot dot i-role-element i-role-datum`;
const screenModel = node.screenModel;
const kRound = 10000;
const circleAttrs = {
fill: ((d) => screenModel.color(d)),
class: ((d) => `${prefix} ${screenModel.class(d)}`)
};
const circleTransAttrs = {
r: ((d) => (Math.round(kRound * screenModel.size(d) / 2) / kRound)),
cx: ((d) => screenModel.x(d)),
cy: ((d) => screenModel.y(d))
};
const activeDots = [];
const updateGroups = function (g: d3Selection) {
g.attr('class', 'frame')
.call(function (c) {
var dots = c
.selectAll('circle')
.data((fiber) => fiber, screenModel.id);
var dotsEnter = dots.enter().append('circle')
.call(attrs(circleTransAttrs));
var dotsMerge = dotsEnter
.merge(dots)
.call(attrs(circleAttrs));
transition(dotsMerge)
.call(attrs(circleTransAttrs));
transition(dots.exit())
.attr('r', 0)
.remove();
activeDots.push(...dotsMerge.nodes());
node.subscribe(dotsMerge as d3Selection);
});
transition(g)
.attr('opacity', 1);
};
const fibers = screenModel.toFibers();
this._getGroupOrder = (() => {
var map = fibers.reduce((map, f, i) => {
map.set(f, i);
return map;
}, new Map());
return ((g) => map.get(g));
})();
const frameGroups = options
.container
.selectAll('.frame')
.data(fibers, (f) => screenModel.group(f[0]));
const merged = frameGroups
.enter()
.append('g')
.attr('opacity', 0)
.merge(frameGroups)
.call(updateGroups);
this._boundsInfo = this._getBoundsInfo(activeDots);
transition(frameGroups.exit())
.attr('opacity', 0)
.remove()
.selectAll('circle')
.attr('r', 0);
node.subscribe(
new LayerLabels(
screenModel.model,
screenModel.flip,
config.guide.label,
options
).draw(fibers)
);
},
_getBoundsInfo(this: PointInstance, dots: Element[]) {
if (dots.length === 0) {
return null;
}
const screenModel = this.node().screenModel;
const items = dots
.map((node) => {
const data = d3.select(node).data()[0] as any;
const x = screenModel.x(data);
const y = screenModel.y(data);
const r = screenModel.size(data) / 2;
return <PointInfo>{node, data, x, y, r};
})
// TODO: Removed elements should not be passed to this function.
.filter((item) => !isNaN(item.x) && !isNaN(item.y));
const bounds = items.reduce(
(bounds, {x, y}) => {
bounds.left = Math.min(x, bounds.left);
bounds.right = Math.max(x, bounds.right);
bounds.top = Math.min(y, bounds.top);
bounds.bottom = Math.max(y, bounds.bottom);
return bounds;
}, {
left: Number.MAX_VALUE,
right: Number.MIN_VALUE,
top: Number.MAX_VALUE,
bottom: Number.MIN_VALUE
});
// NOTE: There can be multiple items at the same point, but
// D3 quad tree seems to ignore them.
const coordinates = items.reduce((coordinates, item) => {
const c = `${item.x},${item.y}`;
if (!coordinates[c]) {
coordinates[c] = [];
}
coordinates[c].push(item);
return coordinates;
}, {});
const tree = d3.quadtree<PointInfo[]>()
.x((d) => d[0].x)
.y((d) => d[0].y)
.addAll(Object.keys(coordinates).map((c) => coordinates[c]));
return {bounds, tree};
},
getClosestElement(this: PointInstance, _cursorX, _cursorY) {
if (!this._boundsInfo) {
return null;
}
const {bounds, tree} = this._boundsInfo;
const container = this.node().config.options.container;
const translate = utilsDraw.getDeepTransformTranslate(container.node());
const cursorX = (_cursorX - translate.x);
const cursorY = (_cursorY - translate.y);
const {maxHighlightDistance} = this.node().config.guide;
if ((cursorX < bounds.left - maxHighlightDistance) ||
(cursorX > bounds.right + maxHighlightDistance) ||
(cursorY < bounds.top - maxHighlightDistance) ||
(cursorY > bounds.bottom + maxHighlightDistance)
) {
return null;
}
const items = (tree.find(cursorX, cursorY) || [])
.map((item) => {
const distance = Math.sqrt(
Math.pow(cursorX - item.x, 2) +
Math.pow(cursorY - item.y, 2));
if (distance > maxHighlightDistance) {
return null;
}
const secondaryDistance = (distance < item.r ? item.r - distance : distance);
return {
node: item.node,
data: item.data,
x: item.x,
y: item.y,
distance,
secondaryDistance
};
})
.filter((d) => d)
.sort((a, b) => (a.secondaryDistance - b.secondaryDistance));
const largerDistIndex = items.findIndex((d) => (
(d.distance !== items[0].distance) ||
(d.secondaryDistance !== items[0].secondaryDistance)
));
const sameDistItems = (largerDistIndex < 0 ? items : items.slice(0, largerDistIndex));
if (sameDistItems.length === 1) {
return sameDistItems[0];
}
const mx = (sameDistItems.reduce((sum, item) => sum + item.x, 0) / sameDistItems.length);
const my = (sameDistItems.reduce((sum, item) => sum + item.y, 0) / sameDistItems.length);
const angle = (Math.atan2(my - cursorY, mx - cursorX) + Math.PI);
const closest = sameDistItems[Math.round((sameDistItems.length - 1) * angle / 2 / Math.PI)];
return closest;
},
highlight(this: PointClass, filter: HighlightFilter) {
const x = 'tau-chart__highlighted';
const _ = 'tau-chart__dimmed';
const container = this.node().config.options.container;
const classed = {
[x]: ((d) => filter(d) === true),
[_]: ((d) => filter(d) === false)
};
container
.selectAll('.dot')
.call(classes(classed));
container
.selectAll('.i-role-label')
.call(classes(classed));
this._sortElements(filter);
},
_sortElements(this: PointInstance, filter: HighlightFilter) {
const container = this.node().config.options.container;
// Sort frames
const filters = new Map();
const groups = new Map();
container
.selectAll('.frame')
.each(function (d: any[]) {
filters.set(this, d.some(filter));
groups.set(this, d);
});
const compareFilterThenGroupId = utils.createMultiSorter(
(a, b) => (filters.get(a) - filters.get(b)),
(a, b) => (this._getGroupOrder(groups.get(a)) - this._getGroupOrder(groups.get(b)))
);
utilsDom.sortChildren(container.node(), (a, b) => {
if (a.tagName === 'g' && b.tagName === 'g') {
return compareFilterThenGroupId(a, b);
}
return a.tagName.localeCompare(b.tagName); // Note: raise <text> over <g>.
});
// Raise filtered dots over others
utilsDraw.raiseElements(container, '.dot', filter);
}
};
export {Point}; | the_stack |
import { EntityQueryContext } from './EntityQueryContext';
import ReadonlyEntity from './ReadonlyEntity';
import ViewerContext from './ViewerContext';
import EntityNotAuthorizedError from './errors/EntityNotAuthorizedError';
import IEntityMetricsAdapter, {
EntityMetricsAuthorizationResult,
} from './metrics/IEntityMetricsAdapter';
import PrivacyPolicyRule, { RuleEvaluationResult } from './rules/PrivacyPolicyRule';
export enum EntityPrivacyPolicyEvaluationMode {
ENFORCE,
DRY_RUN,
ENFORCE_AND_LOG,
}
export type EntityPrivacyPolicyEvaluator<
TFields,
TID extends NonNullable<TFields[TSelectedFields]>,
TViewerContext extends ViewerContext,
TEntity extends ReadonlyEntity<TFields, TID, TViewerContext, TSelectedFields>,
TSelectedFields extends keyof TFields = keyof TFields
> =
| {
mode: EntityPrivacyPolicyEvaluationMode.ENFORCE;
}
| {
mode: EntityPrivacyPolicyEvaluationMode.DRY_RUN;
denyHandler: (
error: EntityNotAuthorizedError<TFields, TID, TViewerContext, TEntity, TSelectedFields>
) => void;
}
| {
mode: EntityPrivacyPolicyEvaluationMode.ENFORCE_AND_LOG;
denyHandler: (
error: EntityNotAuthorizedError<TFields, TID, TViewerContext, TEntity, TSelectedFields>
) => void;
};
export enum EntityAuthorizationAction {
CREATE,
READ,
UPDATE,
DELETE,
}
/**
* Privacy policy for an entity.
*
* @remarks
*
* A privacy policy declares lists of {@link PrivacyPolicyRule} for create, read, update, and delete actions
* for an entity and provides logic for authorizing an entity against rules.
*
* Evaluation of a list of rules is performed according the following example. This allows constructing of
* complex yet testable permissioning logic for an entity.
*
* @example
*
* ```
* foreach rule in rules:
* return authorized if rule allows
* return not authorized if rule denies
* continue to next rule if rule skips
* return not authorized if all rules skip
* ```
*/
export default abstract class EntityPrivacyPolicy<
TFields,
TID extends NonNullable<TFields[TSelectedFields]>,
TViewerContext extends ViewerContext,
TEntity extends ReadonlyEntity<TFields, TID, TViewerContext, TSelectedFields>,
TSelectedFields extends keyof TFields = keyof TFields
> {
protected readonly createRules: readonly PrivacyPolicyRule<
TFields,
TID,
TViewerContext,
TEntity,
TSelectedFields
>[] = [];
protected readonly readRules: readonly PrivacyPolicyRule<
TFields,
TID,
TViewerContext,
TEntity,
TSelectedFields
>[] = [];
protected readonly updateRules: readonly PrivacyPolicyRule<
TFields,
TID,
TViewerContext,
TEntity,
TSelectedFields
>[] = [];
protected readonly deleteRules: readonly PrivacyPolicyRule<
TFields,
TID,
TViewerContext,
TEntity,
TSelectedFields
>[] = [];
/**
* Get the privacy policy evaluation mode and deny handler for this policy.
* Defaults to normal enforcing policy.
*
* @remarks
*
* Override to enable dry run evaluation of the policy.
*/
protected getPrivacyPolicyEvaluator(
_viewerContext: TViewerContext
): EntityPrivacyPolicyEvaluator<TFields, TID, TViewerContext, TEntity, TSelectedFields> {
return {
mode: EntityPrivacyPolicyEvaluationMode.ENFORCE,
};
}
/**
* Authorize an entity against creation policy.
* @param viewerContext - viewer context of user creating the entity
* @param queryContext - query context in which to perform the create authorization
* @param entity - entity to authorize
* @returns entity if authorized
* @throws {@link EntityNotAuthorizedError} when not authorized
*/
async authorizeCreateAsync(
viewerContext: TViewerContext,
queryContext: EntityQueryContext,
entity: TEntity,
metricsAdapter: IEntityMetricsAdapter
): Promise<TEntity> {
return await this.authorizeForRulesetAsync(
this.createRules,
viewerContext,
queryContext,
entity,
EntityAuthorizationAction.CREATE,
metricsAdapter
);
}
/**
* Authorize an entity against read policy.
* @param viewerContext - viewer context of user reading the entity
* @param queryContext - query context in which to perform the read authorization
* @param entity - entity to authorize
* @returns entity if authorized
* @throws {@link EntityNotAuthorizedError} when not authorized
*/
async authorizeReadAsync(
viewerContext: TViewerContext,
queryContext: EntityQueryContext,
entity: TEntity,
metricsAdapter: IEntityMetricsAdapter
): Promise<TEntity> {
return await this.authorizeForRulesetAsync(
this.readRules,
viewerContext,
queryContext,
entity,
EntityAuthorizationAction.READ,
metricsAdapter
);
}
/**
* Authorize an entity against update policy.
* @param viewerContext - viewer context of user updating the entity
* @param queryContext - query context in which to perform the update authorization
* @param entity - entity to authorize
* @returns entity if authorized
* @throws {@link EntityNotAuthorizedError} when not authorized
*/
async authorizeUpdateAsync(
viewerContext: TViewerContext,
queryContext: EntityQueryContext,
entity: TEntity,
metricsAdapter: IEntityMetricsAdapter
): Promise<TEntity> {
return await this.authorizeForRulesetAsync(
this.updateRules,
viewerContext,
queryContext,
entity,
EntityAuthorizationAction.UPDATE,
metricsAdapter
);
}
/**
* Authorize an entity against deletion policy.
* @param viewerContext - viewer context of user deleting the entity
* @param queryContext - query context in which to perform the delete authorization
* @param entity - entity to authorize
* @returns entity if authorized
* @throws {@link EntityNotAuthorizedError} when not authorized
*/
async authorizeDeleteAsync(
viewerContext: TViewerContext,
queryContext: EntityQueryContext,
entity: TEntity,
metricsAdapter: IEntityMetricsAdapter
): Promise<TEntity> {
return await this.authorizeForRulesetAsync(
this.deleteRules,
viewerContext,
queryContext,
entity,
EntityAuthorizationAction.DELETE,
metricsAdapter
);
}
private async authorizeForRulesetAsync(
ruleset: readonly PrivacyPolicyRule<TFields, TID, TViewerContext, TEntity, TSelectedFields>[],
viewerContext: TViewerContext,
queryContext: EntityQueryContext,
entity: TEntity,
action: EntityAuthorizationAction,
metricsAdapter: IEntityMetricsAdapter
): Promise<TEntity> {
const privacyPolicyEvaluator = this.getPrivacyPolicyEvaluator(viewerContext);
switch (privacyPolicyEvaluator.mode) {
case EntityPrivacyPolicyEvaluationMode.ENFORCE:
try {
const result = await this.authorizeForRulesetInnerAsync(
ruleset,
viewerContext,
queryContext,
entity,
action
);
metricsAdapter.logAuthorizationEvent({
entityClassName: entity.constructor.name,
action,
evaluationResult: EntityMetricsAuthorizationResult.ALLOW,
privacyPolicyEvaluationMode: privacyPolicyEvaluator.mode,
});
return result;
} catch (e) {
if (!(e instanceof EntityNotAuthorizedError)) {
throw e;
}
metricsAdapter.logAuthorizationEvent({
entityClassName: entity.constructor.name,
action,
evaluationResult: EntityMetricsAuthorizationResult.DENY,
privacyPolicyEvaluationMode: privacyPolicyEvaluator.mode,
});
throw e;
}
case EntityPrivacyPolicyEvaluationMode.ENFORCE_AND_LOG:
try {
const result = await this.authorizeForRulesetInnerAsync(
ruleset,
viewerContext,
queryContext,
entity,
action
);
metricsAdapter.logAuthorizationEvent({
entityClassName: entity.constructor.name,
action,
evaluationResult: EntityMetricsAuthorizationResult.ALLOW,
privacyPolicyEvaluationMode: privacyPolicyEvaluator.mode,
});
return result;
} catch (e) {
if (!(e instanceof EntityNotAuthorizedError)) {
throw e;
}
privacyPolicyEvaluator.denyHandler(e);
metricsAdapter.logAuthorizationEvent({
entityClassName: entity.constructor.name,
action,
evaluationResult: EntityMetricsAuthorizationResult.DENY,
privacyPolicyEvaluationMode: privacyPolicyEvaluator.mode,
});
throw e;
}
case EntityPrivacyPolicyEvaluationMode.DRY_RUN:
try {
const result = await this.authorizeForRulesetInnerAsync(
ruleset,
viewerContext,
queryContext,
entity,
action
);
metricsAdapter.logAuthorizationEvent({
entityClassName: entity.constructor.name,
action,
evaluationResult: EntityMetricsAuthorizationResult.ALLOW,
privacyPolicyEvaluationMode: privacyPolicyEvaluator.mode,
});
return result;
} catch (e) {
if (!(e instanceof EntityNotAuthorizedError)) {
throw e;
}
privacyPolicyEvaluator.denyHandler(e);
metricsAdapter.logAuthorizationEvent({
entityClassName: entity.constructor.name,
action,
evaluationResult: EntityMetricsAuthorizationResult.DENY,
privacyPolicyEvaluationMode: privacyPolicyEvaluator.mode,
});
return entity;
}
}
}
private async authorizeForRulesetInnerAsync(
ruleset: readonly PrivacyPolicyRule<TFields, TID, TViewerContext, TEntity, TSelectedFields>[],
viewerContext: TViewerContext,
queryContext: EntityQueryContext,
entity: TEntity,
action: EntityAuthorizationAction
): Promise<TEntity> {
for (let i = 0; i < ruleset.length; i++) {
const rule = ruleset[i]!;
const ruleEvaluationResult = await rule.evaluateAsync(viewerContext, queryContext, entity);
switch (ruleEvaluationResult) {
case RuleEvaluationResult.DENY:
throw new EntityNotAuthorizedError<
TFields,
TID,
TViewerContext,
TEntity,
TSelectedFields
>(entity, viewerContext, action, i);
case RuleEvaluationResult.SKIP:
continue;
case RuleEvaluationResult.ALLOW:
return entity;
default:
throw new Error('should not be a fourth type of rule evaluation result');
}
}
throw new EntityNotAuthorizedError<TFields, TID, TViewerContext, TEntity, TSelectedFields>(
entity,
viewerContext,
action,
-1
);
}
} | the_stack |
import { ILokiComparer } from "./comparators";
/** Hash interface for named LokiOperatorPackage registration */
export interface ILokiOperatorPackageMap {
[name: string]: LokiOperatorPackage;
}
/**
* Helper function for determining 'loki' abstract equality which is a little more abstract than ==
* aeqHelper(5, '5') === true
* aeqHelper(5.0, '5') === true
* aeqHelper(new Date("1/1/2011"), new Date("1/1/2011")) === true
* aeqHelper({a:1}, {z:4}) === true (all objects sorted equally)
* aeqHelper([1, 2, 3], [1, 3]) === false
* aeqHelper([1, 2, 3], [1, 2, 3]) === true
* aeqHelper(undefined, null) === true
* @param {any} prop1
* @param {any} prop2
* @returns {boolean}
* @hidden
*/
export function aeqHelper(prop1: any, prop2: any): boolean {
if (prop1 === prop2) return true;
// 'falsy' and Boolean handling
if (!prop1 || !prop2 || prop1 === true || prop2 === true || prop1 !== prop1 || prop2 !== prop2) {
let t1: number;
let t2: number;
// dates and NaN conditions (typed dates before serialization)
switch (prop1) {
case undefined:
t1 = 1;
break;
case null:
t1 = 1;
break;
case false:
t1 = 3;
break;
case true:
t1 = 4;
break;
case "":
t1 = 5;
break;
default:
t1 = (prop1 === prop1) ? 9 : 0;
break;
}
switch (prop2) {
case undefined:
t2 = 1;
break;
case null:
t2 = 1;
break;
case false:
t2 = 3;
break;
case true:
t2 = 4;
break;
case "":
t2 = 5;
break;
default:
t2 = (prop2 === prop2) ? 9 : 0;
break;
}
// one or both is edge case
if (t1 !== 9 || t2 !== 9) {
return (t1 === t2);
}
}
// Handle 'Number-like' comparisons
let cv1 = Number(prop1);
let cv2 = Number(prop2);
// if one or both are 'number-like'...
if (cv1 === cv1 || cv2 === cv2) {
return (cv1 === cv2);
}
// not strict equal nor less than nor gt so must be mixed types, convert to string and use that to compare
cv1 = prop1.toString();
cv2 = prop2.toString();
return (cv1 == cv2);
}
/**
* Helper function for determining 'less-than' conditions for ops, sorting, and binary indices.
* In the future we might want $lt and $gt ops to use their own functionality/helper.
* Since binary indices on a property might need to index [12, NaN, new Date(), Infinity], we
* need this function (as well as gtHelper) to always ensure one value is LT, GT, or EQ to another.
* @hidden
*/
export function ltHelper(prop1: any, prop2: any, equal: boolean): boolean {
// if one of the params is falsy or strictly true or not equal to itself
// 0, 0.0, "", NaN, null, undefined, not defined, false, true
if (!prop1 || !prop2 || prop1 === true || prop2 === true || prop1 !== prop1 || prop2 !== prop2) {
let t1: number;
let t2: number;
switch (prop1) {
case undefined:
t1 = 1;
break;
case null:
t1 = 1;
break;
case false:
t1 = 3;
break;
case true:
t1 = 4;
break;
case "":
t1 = 5;
break;
// if strict equal probably 0 so sort higher, otherwise probably NaN so sort lower than even null
default:
t1 = (prop1 === prop1) ? 9 : 0;
break;
}
switch (prop2) {
case undefined:
t2 = 1;
break;
case null:
t2 = 1;
break;
case false:
t2 = 3;
break;
case true:
t2 = 4;
break;
case "":
t2 = 5;
break;
default:
t2 = (prop2 === prop2) ? 9 : 0;
break;
}
// one or both is edge case
if (t1 !== 9 || t2 !== 9) {
return (t1 === t2) ? equal : (t1 < t2);
}
}
// if both are numbers (string encoded or not), compare as numbers
let cv1 = Number(prop1);
let cv2 = Number(prop2);
if (cv1 === cv1 && cv2 === cv2) {
if (cv1 < cv2) return true;
if (cv1 > cv2) return false;
return equal;
}
if (cv1 === cv1 && cv2 !== cv2) {
return true;
}
if (cv2 === cv2 && cv1 !== cv1) {
return false;
}
if (prop1 < prop2) return true;
if (prop1 > prop2) return false;
if (prop1 == prop2) return equal;
// not strict equal nor less than nor gt so must be mixed types, convert to string and use that to compare
cv1 = prop1.toString();
cv2 = prop2.toString();
if (cv1 < cv2) {
return true;
}
if (cv1 == cv2) {
return equal;
}
return false;
}
/**
* @hidden
* @param {any} prop1
* @param {any} prop2
* @param {boolean} equal
* @returns {boolean}
*/
export function gtHelper(prop1: any, prop2: any, equal: boolean): boolean {
// 'falsy' and Boolean handling
if (!prop1 || !prop2 || prop1 === true || prop2 === true || prop1 !== prop1 || prop2 !== prop2) {
let t1: number;
let t2: number;
switch (prop1) {
case undefined:
t1 = 1;
break;
case null:
t1 = 1;
break;
case false:
t1 = 3;
break;
case true:
t1 = 4;
break;
case "":
t1 = 5;
break;
// NaN 0
default:
t1 = (prop1 === prop1) ? 9 : 0;
break;
}
switch (prop2) {
case undefined:
t2 = 1;
break;
case null:
t2 = 1;
break;
case false:
t2 = 3;
break;
case true:
t2 = 4;
break;
case "":
t2 = 5;
break;
default:
t2 = (prop2 === prop2) ? 9 : 0;
break;
}
// one or both is edge case
if (t1 !== 9 || t2 !== 9) {
return (t1 === t2) ? equal : (t1 > t2);
}
}
// if both are numbers (string encoded or not), compare as numbers
let cv1 = Number(prop1);
let cv2 = Number(prop2);
if (cv1 === cv1 && cv2 === cv2) {
if (cv1 > cv2) return true;
if (cv1 < cv2) return false;
return equal;
}
if (cv1 === cv1 && cv2 !== cv2) {
return false;
}
if (cv2 === cv2 && cv1 !== cv1) {
return true;
}
if (prop1 > prop2) return true;
if (prop1 < prop2) return false;
if (prop1 == prop2) return equal;
// not strict equal nor less than nor gt so must be dates or mixed types
// convert to string and use that to compare
cv1 = prop1.toString();
cv2 = prop2.toString();
if (cv1 > cv2) {
return true;
}
if (cv1 == cv2) {
return equal;
}
return false;
}
/**
* @param {any} prop1
* @param {any} prop2
* @param {boolean} descending
* @returns {number}
* @hidden
*/
export function sortHelper(prop1: any, prop2: any, descending: boolean): number {
if (aeqHelper(prop1, prop2)) {
return 0;
}
if (ltHelper(prop1, prop2, false)) {
return descending ? 1 : -1;
}
if (gtHelper(prop1, prop2, false)) {
return descending ? -1 : 1;
}
// not lt, not gt so implied equality-- date compatible
return 0;
}
/**
* Default implementation of LokiOperatorPackage, using fastest javascript comparison operators.
*/
export class LokiOperatorPackage {
// comparison operators
// a is the value in the collection
// b is the query value
$eq(a: any, b: any): boolean {
return a === b;
}
$ne(a: any, b: any): boolean {
return a !== b;
}
$gt(a: any, b: any): boolean {
return a > b;
}
$gte(a: any, b: any): boolean {
return a >= b;
}
$lt(a: any, b: any): boolean {
return a < b;
}
$lte(a: any, b: any): boolean {
return a <= b;
}
$between(a: any, range: [any, any]): boolean {
if (a === undefined || a === null) return false;
return a >= range[0] && a <= range[1];
}
$in(a: any, b: any): boolean {
return b.indexOf(a) !== -1;
}
$nin(a: any, b: any): boolean {
return b.indexOf(a) === -1;
}
$keyin(a: string, b: object): boolean {
return a in b;
}
$nkeyin(a: string, b: object): boolean {
return !(a in b);
}
$definedin(a: string, b: object): boolean {
return b[a] !== undefined;
}
$undefinedin(a: string, b: object): boolean {
return b[a] === undefined;
}
$regex(a: string, b: RegExp): boolean {
return b.test(a);
}
$containsNone(a: any, b: any): boolean {
return !this.$containsAny(a, b);
}
$containsAny(a: any, b: any): boolean {
const checkFn = this.containsCheckFn(a);
if (checkFn !== null) {
return (Array.isArray(b)) ? (b.some(checkFn)) : (checkFn(b));
}
return false;
}
$contains(a: any, b: any): boolean {
const checkFn = this.containsCheckFn(a);
if (checkFn !== null) {
return (Array.isArray(b)) ? (b.every(checkFn)) : (checkFn(b));
}
return false;
}
$type(a: any, b: any): boolean {
let type: string = typeof a;
if (type === "object") {
if (Array.isArray(a)) {
type = "array";
} else if (a instanceof Date) {
type = "date";
}
}
return (typeof b !== "object") ? (type === b) : this.doQueryOp(type, b);
}
$finite(a: number, b: boolean): boolean {
return (b === isFinite(a));
}
$size(a: any, b: any): boolean {
if (Array.isArray(a)) {
return (typeof b !== "object") ? (a.length === b) : this.doQueryOp(a.length, b);
}
return false;
}
$len(a: any, b: any): boolean {
if (typeof a === "string") {
return (typeof b !== "object") ? (a.length === b) : this.doQueryOp(a.length, b);
}
return false;
}
$where(a: any, b: any): boolean {
return b(a) === true;
}
// field-level logical operators
// a is the value in the collection
// b is the nested query operation (for '$not')
// or an array of nested query operations (for '$and' and '$or')
$not(a: any, b: any): boolean {
return !this.doQueryOp(a, b);
}
$and(a: any, b: any): boolean {
for (let idx = 0, len = b.length; idx < len; idx++) {
if (!this.doQueryOp(a, b[idx])) {
return false;
}
}
return true;
}
$or(a: any, b: any): boolean {
for (let idx = 0, len = b.length; idx < len; idx++) {
if (this.doQueryOp(a, b[idx])) {
return true;
}
}
return false;
}
private doQueryOp(val: any, op: object) {
for (let p in op) {
if (Object.hasOwnProperty.call(op, p)) {
return this[p](val, op[p]);
}
}
return false;
}
private containsCheckFn(a: any) {
if (typeof a === "string" || Array.isArray(a)) {
return (b: any) => (a as any).indexOf(b) !== -1;
} else if (typeof a === "object" && a !== null) {
return (b: string) => Object.hasOwnProperty.call(a, b);
}
return null;
}
}
/**
* LokiOperatorPackage which utilizes abstract 'loki' comparisons for basic relational equality op implementations.
*/
export class LokiAbstractOperatorPackage extends LokiOperatorPackage {
constructor() {
super();
}
$eq(a: any, b: any): boolean {
return aeqHelper(a, b);
}
$ne(a: any, b: any): boolean {
return !aeqHelper(a, b);
}
$gt(a: any, b: any): boolean {
return gtHelper(a, b, false);
}
$gte(a: any, b: any): boolean {
return gtHelper(a, b, true);
}
$lt(a: any, b: any): boolean {
return ltHelper(a, b, false);
}
$lte(a: any, b: any): boolean {
return ltHelper(a, b, true);
}
$between(a: any, range: [any, any]): boolean {
if (a === undefined || a === null) return false;
return gtHelper(a, range[0], true) && ltHelper(a, range[1], true);
}
}
/**
* LokiOperatorPackage which utilizes provided comparator for basic relational equality op implementations.
*/
export class ComparatorOperatorPackage<T> extends LokiOperatorPackage {
comparator: ILokiComparer<T>;
constructor(comparator: ILokiComparer<T>) {
super();
this.comparator = comparator;
}
$eq(a: any, b: any): boolean {
return this.comparator(a, b) === 0;
}
$ne(a: any, b: any): boolean {
return this.comparator(a, b) !== 0;
}
$gt(a: any, b: any): boolean {
return this.comparator(a, b) === 1;
}
$gte(a: any, b: any): boolean {
return this.comparator(a, b) > -1;
}
$lt(a: any, b: any): boolean {
return this.comparator(a, b) === -1;
}
$lte(a: any, b: any): boolean {
return this.comparator(a, b) < 1;
}
$between(a: any, range: [any, any]): boolean {
if (a === undefined || a === null) return false;
return this.comparator(a, range[0]) > -1 && this.comparator(a, range[1]) < 1;
}
}
/**
* Map/Register of named LokiOperatorPackages which implement all unindexed query ops within 'find' query objects
*/
export let LokiOperatorPackageMap : ILokiOperatorPackageMap = {
"js" : new LokiOperatorPackage(),
"loki" : new LokiAbstractOperatorPackage()
}; | the_stack |
import type { SharedTimeProps } from './panels/TimePanel';
import TimePanel from './panels/TimePanel';
import DatetimePanel from './panels/DatetimePanel';
import DatePanel from './panels/DatePanel';
import WeekPanel from './panels/WeekPanel';
import MonthPanel from './panels/MonthPanel';
import QuarterPanel from './panels/QuarterPanel';
import YearPanel from './panels/YearPanel';
import DecadePanel from './panels/DecadePanel';
import type { GenerateConfig } from './generate';
import type {
Locale,
PanelMode,
PanelRefProps,
PickerMode,
DisabledTime,
OnPanelChange,
Components,
} from './interface';
import { isEqual } from './utils/dateUtil';
import { useInjectPanel, useProvidePanel } from './PanelContext';
import type { DateRender } from './panels/DatePanel/DateBody';
import { PickerModeMap } from './utils/uiUtil';
import type { MonthCellRender } from './panels/MonthPanel/MonthBody';
import { useInjectRange } from './RangeContext';
import getExtraFooter from './utils/getExtraFooter';
import getRanges from './utils/getRanges';
import { getLowerBoundTime, setDateTime, setTime } from './utils/timeUtil';
import type { VueNode } from '../_util/type';
import { computed, createVNode, defineComponent, ref, toRef, watch, watchEffect } from 'vue';
import useMergedState from '../_util/hooks/useMergedState';
import { warning } from '../vc-util/warning';
import KeyCode from '../_util/KeyCode';
import classNames from '../_util/classNames';
export type PickerPanelSharedProps<DateType> = {
prefixCls?: string;
// className?: string;
// style?: React.CSSProperties;
/** @deprecated Will be removed in next big version. Please use `mode` instead */
mode?: PanelMode;
tabindex?: number;
// Locale
locale: Locale;
generateConfig: GenerateConfig<DateType>;
// Value
value?: DateType | null;
defaultValue?: DateType;
/** [Legacy] Set default display picker view date */
pickerValue?: DateType;
/** [Legacy] Set default display picker view date */
defaultPickerValue?: DateType;
// Date
disabledDate?: (date: DateType) => boolean;
// Render
dateRender?: DateRender<DateType>;
monthCellRender?: MonthCellRender<DateType>;
renderExtraFooter?: (mode: PanelMode) => VueNode;
// Event
onSelect?: (value: DateType) => void;
onChange?: (value: DateType) => void;
onPanelChange?: OnPanelChange<DateType>;
onMousedown?: (e: MouseEvent) => void;
onOk?: (date: DateType) => void;
direction?: 'ltr' | 'rtl';
/** @private This is internal usage. Do not use in your production env */
hideHeader?: boolean;
/** @private This is internal usage. Do not use in your production env */
onPickerValueChange?: (date: DateType) => void;
/** @private Internal usage. Do not use in your production env */
components?: Components;
};
export type PickerPanelBaseProps<DateType> = {
picker: Exclude<PickerMode, 'date' | 'time'>;
} & PickerPanelSharedProps<DateType>;
export type PickerPanelDateProps<DateType> = {
picker?: 'date';
showToday?: boolean;
showNow?: boolean;
// Time
showTime?: boolean | SharedTimeProps<DateType>;
disabledTime?: DisabledTime<DateType>;
} & PickerPanelSharedProps<DateType>;
export type PickerPanelTimeProps<DateType> = {
picker: 'time';
} & PickerPanelSharedProps<DateType> &
SharedTimeProps<DateType>;
export type PickerPanelProps<DateType> =
| PickerPanelBaseProps<DateType>
| PickerPanelDateProps<DateType>
| PickerPanelTimeProps<DateType>;
// TMP type to fit for ts 3.9.2
type OmitType<DateType> = Omit<PickerPanelBaseProps<DateType>, 'picker'> &
Omit<PickerPanelDateProps<DateType>, 'picker'> &
Omit<PickerPanelTimeProps<DateType>, 'picker'>;
type MergedPickerPanelProps<DateType> = {
picker?: PickerMode;
} & OmitType<DateType>;
function PickerPanel<DateType>() {
return defineComponent<MergedPickerPanelProps<DateType>>({
name: 'PickerPanel',
inheritAttrs: false,
props: {
prefixCls: String,
locale: Object,
generateConfig: Object,
value: Object,
defaultValue: Object,
pickerValue: Object,
defaultPickerValue: Object,
disabledDate: Function,
mode: String,
picker: { type: String, default: 'date' },
tabindex: { type: [Number, String], default: 0 },
showNow: { type: Boolean, default: undefined },
showTime: [Boolean, Object],
showToday: Boolean,
renderExtraFooter: Function,
dateRender: Function,
hideHeader: { type: Boolean, default: undefined },
onSelect: Function,
onChange: Function,
onPanelChange: Function,
onMousedown: Function,
onPickerValueChange: Function,
onOk: Function,
components: Object,
direction: String,
hourStep: { type: Number, default: 1 },
minuteStep: { type: Number, default: 1 },
secondStep: { type: Number, default: 1 },
} as any,
setup(props, { attrs }) {
const needConfirmButton = computed(
() => (props.picker === 'date' && !!props.showTime) || props.picker === 'time',
);
const isHourStepValid = computed(() => 24 % props.hourStep === 0);
const isMinuteStepValid = computed(() => 60 % props.minuteStep === 0);
const isSecondStepValid = computed(() => 60 % props.secondStep === 0);
if (process.env.NODE_ENV !== 'production') {
watchEffect(() => {
const { generateConfig, value, hourStep = 1, minuteStep = 1, secondStep = 1 } = props;
warning(!value || generateConfig.isValidate(value), 'Invalidate date pass to `value`.');
warning(
!value || generateConfig.isValidate(value),
'Invalidate date pass to `defaultValue`.',
);
warning(
isHourStepValid.value,
`\`hourStep\` ${hourStep} is invalid. It should be a factor of 24.`,
);
warning(
isMinuteStepValid.value,
`\`minuteStep\` ${minuteStep} is invalid. It should be a factor of 60.`,
);
warning(
isSecondStepValid.value,
`\`secondStep\` ${secondStep} is invalid. It should be a factor of 60.`,
);
});
}
const panelContext = useInjectPanel();
const {
operationRef,
panelRef: panelDivRef,
onSelect: onContextSelect,
hideRanges,
defaultOpenValue,
} = panelContext;
const { inRange, panelPosition, rangedValue, hoverRangedValue } = useInjectRange();
const panelRef = ref<PanelRefProps>({});
// Value
const [mergedValue, setInnerValue] = useMergedState<DateType | null>(null, {
value: toRef(props, 'value'),
defaultValue: props.defaultValue,
postState: val => {
if (!val && defaultOpenValue?.value && props.picker === 'time') {
return defaultOpenValue.value;
}
return val;
},
});
// View date control
const [viewDate, setInnerViewDate] = useMergedState<DateType | null>(null, {
value: toRef(props, 'pickerValue'),
defaultValue: props.defaultPickerValue || mergedValue.value,
postState: date => {
const { generateConfig, showTime, defaultValue } = props;
const now = generateConfig.getNow();
if (!date) return now;
// When value is null and set showTime
if (!mergedValue.value && props.showTime) {
if (typeof showTime === 'object') {
return setDateTime(generateConfig, date, showTime.defaultValue || now);
}
if (defaultValue) {
return setDateTime(generateConfig, date, defaultValue);
}
return setDateTime(generateConfig, date, now);
}
return date;
},
});
const setViewDate = (date: DateType) => {
setInnerViewDate(date);
if (props.onPickerValueChange) {
props.onPickerValueChange(date);
}
};
// Panel control
const getInternalNextMode = (nextMode: PanelMode): PanelMode => {
const getNextMode = PickerModeMap[props.picker!];
if (getNextMode) {
return getNextMode(nextMode);
}
return nextMode;
};
// Save panel is changed from which panel
const [mergedMode, setInnerMode] = useMergedState(
() => {
if (props.picker === 'time') {
return 'time';
}
return getInternalNextMode('date');
},
{
value: toRef(props, 'mode'),
},
);
watch(
() => props.picker,
() => {
setInnerMode(props.picker);
},
);
const sourceMode = ref(mergedMode.value);
const setSourceMode = (val: PanelMode) => {
sourceMode.value = val;
};
const onInternalPanelChange = (newMode: PanelMode | null, viewValue: DateType) => {
const { onPanelChange, generateConfig } = props;
const nextMode = getInternalNextMode(newMode || mergedMode.value);
setSourceMode(mergedMode.value);
setInnerMode(nextMode);
if (
onPanelChange &&
(mergedMode.value !== nextMode || isEqual(generateConfig, viewDate.value, viewDate.value))
) {
onPanelChange(viewValue, nextMode);
}
};
const triggerSelect = (
date: DateType,
type: 'key' | 'mouse' | 'submit',
forceTriggerSelect = false,
) => {
const { picker, generateConfig, onSelect, onChange, disabledDate } = props;
if (mergedMode.value === picker || forceTriggerSelect) {
setInnerValue(date);
if (onSelect) {
onSelect(date);
}
if (onContextSelect) {
onContextSelect(date, type);
}
if (
onChange &&
!isEqual(generateConfig, date, mergedValue.value) &&
!disabledDate?.(date)
) {
onChange(date);
}
}
};
// ========================= Interactive ==========================
const onInternalKeydown = (e: KeyboardEvent) => {
if (panelRef.value && panelRef.value.onKeydown) {
if (
[
KeyCode.LEFT,
KeyCode.RIGHT,
KeyCode.UP,
KeyCode.DOWN,
KeyCode.PAGE_UP,
KeyCode.PAGE_DOWN,
KeyCode.ENTER,
].includes(e.which)
) {
e.preventDefault();
}
return panelRef.value.onKeydown(e);
}
/* istanbul ignore next */
/* eslint-disable no-lone-blocks */
{
warning(
false,
'Panel not correct handle keyDown event. Please help to fire issue about this.',
);
return false;
}
/* eslint-enable no-lone-blocks */
};
const onInternalBlur = (e: FocusEvent) => {
if (panelRef.value && panelRef.value.onBlur) {
panelRef.value.onBlur(e);
}
};
const onNow = () => {
const { generateConfig, hourStep, minuteStep, secondStep } = props;
const now = generateConfig.getNow();
const lowerBoundTime = getLowerBoundTime(
generateConfig.getHour(now),
generateConfig.getMinute(now),
generateConfig.getSecond(now),
isHourStepValid.value ? hourStep : 1,
isMinuteStepValid.value ? minuteStep : 1,
isSecondStepValid.value ? secondStep : 1,
);
const adjustedNow = setTime(
generateConfig,
now,
lowerBoundTime[0], // hour
lowerBoundTime[1], // minute
lowerBoundTime[2], // second
);
triggerSelect(adjustedNow, 'submit');
};
const classString = computed(() => {
const { prefixCls, direction } = props;
return classNames(`${prefixCls}-panel`, {
[`${prefixCls}-panel-has-range`]:
rangedValue && rangedValue.value && rangedValue.value[0] && rangedValue.value[1],
[`${prefixCls}-panel-has-range-hover`]:
hoverRangedValue &&
hoverRangedValue.value &&
hoverRangedValue.value[0] &&
hoverRangedValue.value[1],
[`${prefixCls}-panel-rtl`]: direction === 'rtl',
});
});
useProvidePanel({
...panelContext,
mode: mergedMode,
hideHeader: computed(() =>
props.hideHeader !== undefined ? props.hideHeader : panelContext.hideHeader?.value,
),
hidePrevBtn: computed(() => inRange.value && panelPosition.value === 'right'),
hideNextBtn: computed(() => inRange.value && panelPosition.value === 'left'),
});
watch(
() => props.value,
() => {
if (props.value) {
setInnerViewDate(props.value);
}
},
);
return () => {
const {
prefixCls = 'ant-picker',
locale,
generateConfig,
disabledDate,
picker = 'date',
tabindex = 0,
showNow,
showTime,
showToday,
renderExtraFooter,
onMousedown,
onOk,
components,
} = props;
if (operationRef && panelPosition.value !== 'right') {
operationRef.value = {
onKeydown: onInternalKeydown,
onClose: () => {
if (panelRef.value && panelRef.value.onClose) {
panelRef.value.onClose();
}
},
};
}
// ============================ Panels ============================
let panelNode: VueNode;
const pickerProps = {
...attrs,
...(props as MergedPickerPanelProps<DateType>),
operationRef: panelRef,
prefixCls,
viewDate: viewDate.value,
value: mergedValue.value,
onViewDateChange: setViewDate,
sourceMode: sourceMode.value,
onPanelChange: onInternalPanelChange,
disabledDate,
};
delete pickerProps.onChange;
delete pickerProps.onSelect;
switch (mergedMode.value) {
case 'decade':
panelNode = (
<DecadePanel<DateType>
{...pickerProps}
onSelect={(date, type) => {
setViewDate(date);
triggerSelect(date, type);
}}
/>
);
break;
case 'year':
panelNode = (
<YearPanel<DateType>
{...pickerProps}
onSelect={(date, type) => {
setViewDate(date);
triggerSelect(date, type);
}}
/>
);
break;
case 'month':
panelNode = (
<MonthPanel<DateType>
{...pickerProps}
onSelect={(date, type) => {
setViewDate(date);
triggerSelect(date, type);
}}
/>
);
break;
case 'quarter':
panelNode = (
<QuarterPanel<DateType>
{...pickerProps}
onSelect={(date, type) => {
setViewDate(date);
triggerSelect(date, type);
}}
/>
);
break;
case 'week':
panelNode = (
<WeekPanel
{...pickerProps}
onSelect={(date, type) => {
setViewDate(date);
triggerSelect(date, type);
}}
/>
);
break;
case 'time':
delete pickerProps.showTime;
panelNode = (
<TimePanel<DateType>
{...pickerProps}
{...(typeof showTime === 'object' ? showTime : null)}
onSelect={(date, type) => {
setViewDate(date);
triggerSelect(date, type);
}}
/>
);
break;
default:
if (showTime) {
panelNode = (
<DatetimePanel
{...pickerProps}
onSelect={(date, type) => {
setViewDate(date);
triggerSelect(date, type);
}}
/>
);
} else {
panelNode = (
<DatePanel<DateType>
{...pickerProps}
onSelect={(date, type) => {
setViewDate(date);
triggerSelect(date, type);
}}
/>
);
}
}
// ============================ Footer ============================
let extraFooter: VueNode;
let rangesNode: VueNode;
if (!hideRanges?.value) {
extraFooter = getExtraFooter(prefixCls, mergedMode.value, renderExtraFooter);
rangesNode = getRanges({
prefixCls,
components,
needConfirmButton: needConfirmButton.value,
okDisabled: !mergedValue.value || (disabledDate && disabledDate(mergedValue.value)),
locale,
showNow,
onNow: needConfirmButton.value && onNow,
onOk: () => {
if (mergedValue.value) {
triggerSelect(mergedValue.value, 'submit', true);
if (onOk) {
onOk(mergedValue.value);
}
}
},
});
}
let todayNode: VueNode;
if (showToday && mergedMode.value === 'date' && picker === 'date' && !showTime) {
const now = generateConfig.getNow();
const todayCls = `${prefixCls}-today-btn`;
const disabled = disabledDate && disabledDate(now);
todayNode = (
<a
class={classNames(todayCls, disabled && `${todayCls}-disabled`)}
aria-disabled={disabled}
onClick={() => {
if (!disabled) {
triggerSelect(now, 'mouse', true);
}
}}
>
{locale.today}
</a>
);
}
return (
<div
tabindex={tabindex}
class={classNames(classString.value, attrs.class)}
style={attrs.style}
onKeydown={onInternalKeydown}
onBlur={onInternalBlur}
onMousedown={onMousedown}
ref={panelDivRef}
>
{panelNode}
{extraFooter || rangesNode || todayNode ? (
<div class={`${prefixCls}-footer`}>
{extraFooter}
{rangesNode}
{todayNode}
</div>
) : null}
</div>
);
};
},
});
}
const InterPickerPanel = PickerPanel<any>();
export default <DateType extends any>(props: MergedPickerPanelProps<DateType>): JSX.Element =>
createVNode(InterPickerPanel, props); | the_stack |
import { AlertService } from "./alert.service";
import { AfterViewChecked, Component, OnDestroy, OnInit } from "@angular/core";
import { AlertGroup, ElasticSearchService } from "./elasticsearch.service";
import { ActivatedRoute, Router } from "@angular/router";
import { MousetrapService } from "./mousetrap.service";
import { AppEvent, AppEventCode, AppService } from "./app.service";
import { EventService } from "./event.service";
import { ToastrService } from "./toastr.service";
import { TopNavService } from "./topnav.service";
import { loadingAnimation } from "./animations";
import { SETTING_ALERTS_PER_PAGE, SettingsService } from "./settings.service";
import { debounce } from "rxjs/operators";
import { combineLatest, interval } from "rxjs";
import { transformEcsEvent } from "./events/events.component";
import * as moment from "moment";
import { ApiService } from "./api.service";
declare var window: any;
declare var $: any;
export interface AlertsState {
rows: any[];
allRows: any[];
activeRow: number;
route: string;
queryString: string;
scrollOffset: number;
}
const DEFAULT_SORT_ORDER = "desc";
const DEFAULT_SORT_BY = "timestamp";
@Component({
templateUrl: "./alerts.component.html",
animations: [
loadingAnimation,
]
})
export class AlertsComponent implements OnInit, OnDestroy, AfterViewChecked {
windowSize = 100;
offset = 0;
rows: any[] = [];
allRows: any[] = [];
activeRow = 0;
queryString = "";
loading = false;
dispatcherSubscription: any;
silentRefresh = false;
sortBy: string = DEFAULT_SORT_BY;
sortOrder: string = DEFAULT_SORT_ORDER;
constructor(private alertService: AlertService,
private elasticSearchService: ElasticSearchService,
private router: Router,
private route: ActivatedRoute,
private mousetrap: MousetrapService,
private appService: AppService,
private eventService: EventService,
private toastr: ToastrService,
private topNavService: TopNavService,
private api: ApiService,
private settings: SettingsService) {
}
ngOnInit(): any {
this.windowSize = this.settings.getInt(SETTING_ALERTS_PER_PAGE, 100);
combineLatest([
this.route.queryParams,
this.route.params,
]).pipe(debounce(() => interval(100))).subscribe(([queryParams, params]) => {
console.log("Got params and query params...");
if (params.sortBy) {
this.sortBy = params.sortBy;
} else {
this.sortBy = DEFAULT_SORT_BY;
}
if (params.sortOrder) {
this.sortOrder = params.sortOrder;
} else {
this.sortOrder = DEFAULT_SORT_ORDER;
}
this.queryString = queryParams.q || "";
if (!this.restoreState()) {
this.refresh();
}
});
this.mousetrap.bind(this, "/", () => this.focusFilterInput());
this.mousetrap.bind(this, "r", () => this.refresh());
this.mousetrap.bind(this, "o", () => this.openActiveEvent());
this.mousetrap.bind(this, "f8", () => this.archiveActiveEvent());
this.mousetrap.bind(this, "s", () =>
this.toggleEscalatedState(this.getActiveRow()));
this.mousetrap.bind(this, "* a", () => this.selectAllRows());
this.mousetrap.bind(this, "* n", () => this.deselectAllRows());
this.mousetrap.bind(this, "* 1", () => {
this.selectBySignatureId(this.rows[this.activeRow]);
});
// Escalate then archive event.
this.mousetrap.bind(this, "f9", () => {
this.escalateAndArchiveEvent(this.getActiveRow());
});
this.mousetrap.bind(this, "x", () =>
this.toggleSelectedState(this.getActiveRow()));
this.mousetrap.bind(this, "e", () => this.archiveEvents());
this.mousetrap.bind(this, ">", () => {
this.older();
});
this.mousetrap.bind(this, "<", () => {
this.newer();
});
// CTRL >
this.mousetrap.bind(this, "ctrl+shift+.", () => {
this.oldest();
});
// CTRL <
this.mousetrap.bind(this, "ctrl+shift+,", () => {
this.newest();
});
this.dispatcherSubscription = this.appService.subscribe((event: any) => {
this.appEventHandler(event);
});
// Bind "." to open the dropdown menu for the specific event.
this.mousetrap.bind(this, ".", () => {
this.openDropdownMenu();
});
}
ngOnDestroy(): any {
this.mousetrap.unbind(this);
this.dispatcherSubscription.unsubscribe();
}
ngAfterViewChecked(): void {
// This seems to be required to activate the dropdowns when used in
// an event table row. Probably something to do with the stopPropagations.
$(".dropdown-toggle").dropdown();
}
buildState(): any {
const state: AlertsState = {
rows: this.rows,
allRows: this.allRows,
activeRow: this.activeRow,
queryString: this.queryString,
route: this.appService.getRoute(),
scrollOffset: window.pageYOffset,
};
return state;
}
restoreState(): boolean {
const state: AlertsState = this.alertService.popState();
if (!state) {
return false;
}
console.log("Restoring previous state.");
if (state.route !== this.appService.getRoute()) {
console.log("Saved state route differs.");
return false;
}
if (state.queryString !== this.queryString) {
console.log("Query strings differ, previous state not being restored.");
return false;
}
this.rows = state.rows;
this.allRows = state.allRows;
this.activeRow = state.activeRow;
// If in inbox, remove any archived events.
if (this.isInbox()) {
const archived = this.rows.filter((row: any) => {
return row.event.event._source.tags && row.event.event._source.tags.indexOf("archived") > -1;
});
console.log(`Found ${archived.length} archived events.`);
archived.forEach((row: any) => {
this.removeRow(row);
});
} else if (this.appService.getRoute() === "/escalated") {
const deEscalated = this.rows.filter(row => {
return row.event.escalatedCount === 0;
});
deEscalated.forEach(row => {
this.removeRow(row);
});
}
setTimeout(() => {
window.scrollTo(0, state.scrollOffset);
}, 0);
return true;
}
isInbox(): boolean {
return this.appService.getRoute() === "/inbox";
}
older(): void {
this.offset += this.windowSize;
this.rows = this.allRows.slice(this.offset, this.offset + this.windowSize);
}
oldest(): void {
while (this.offset + this.windowSize < this.allRows.length) {
this.offset += this.windowSize;
}
this.rows = this.allRows.slice(this.offset, this.offset + this.windowSize);
}
newest(): void {
this.offset = 0;
this.rows = this.allRows.slice(this.offset, this.offset + this.windowSize);
}
newer(): void {
if (this.offset > this.windowSize) {
this.offset -= this.windowSize;
} else {
this.offset = 0;
}
this.rows = this.allRows.slice(this.offset, this.offset + this.windowSize);
}
showAll(): void {
this.rows = this.allRows;
}
min(a: number, b: number): number {
return Math.min(a, b);
}
private compare(a: any, b: any): number {
if (a < b) {
return -1;
} else if (a > b) {
return 1;
}
return 0;
}
onSort(column: string): void {
console.log("Sorting by: " + column);
if (column !== this.sortBy) {
this.sortBy = column;
this.sortOrder = "desc";
} else {
if (this.sortOrder === "desc") {
this.sortOrder = "asc";
} else {
this.sortOrder = "desc";
}
}
this.appService.updateParams(this.route, {sortBy: this.sortBy, sortOrder: this.sortOrder});
this.sort();
}
sort(): void {
switch (this.sortBy) {
case "signature":
this.allRows.sort((a: any, b: any) => {
return this.compare(
a.event.event._source.alert.signature.toUpperCase(),
b.event.event._source.alert.signature.toUpperCase());
});
break;
case "count":
this.allRows.sort((a: any, b: any) => {
return a.event.count - b.event.count;
});
break;
case "source":
this.allRows.sort((a: any, b: any) => {
return this.compare(
a.event.event._source.src_ip,
b.event.event._source.src_ip);
});
break;
case "dest":
this.allRows.sort((a: any, b: any) => {
return this.compare(
a.event.event._source.dest_ip,
b.event.event._source.dest_ip);
});
break;
case "timestamp":
this.allRows.sort((a: any, b: any) => {
return this.compare(a.event.maxTs, b.event.maxTs);
});
break;
}
if (this.sortOrder === "desc") {
this.allRows.reverse();
}
this.rows = this.allRows.slice(this.offset, this.windowSize);
}
escalateAndArchiveEvent(row: any): void {
this.archiveAlertGroup(row).then(() => {
this.escalateAlertGroup(row);
});
}
appEventHandler(event: AppEvent): void {
switch (event.event) {
case AppEventCode.TIME_RANGE_CHANGED:
this.refresh();
break;
case AppEventCode.IDLE:
if (this.loading) {
return;
}
if (this.rows.length > 0 && event.data < 60) {
return;
}
if (this.rows.length === 0 && event.data < 5) {
return;
}
// Don't auto-refresh if Elastic Search jobs are in progress,
// could result in reloading events waiting to be archived.
// TODO: Limit to archive jobs only.
if (this.elasticSearchService.jobSize() > 0) {
console.log("Elastic Search jobs active, not refreshing.");
return;
}
if (this.rows.length > 0 && this.getSelectedRows().length > 0) {
return;
}
this.refresh(true);
break;
}
}
openActiveEvent(): void {
this.openEvent(this.getActiveRow().event);
}
archiveActiveEvent(): void {
if (this.getActiveRowIndex() >= 0) {
this.archiveAlertGroup(this.getActiveRow());
}
}
getActiveRow(): any {
return this.rows[this.getActiveRowIndex()];
}
getActiveRowIndex(): number {
return this.activeRow;
}
toggleSelectedState(row: any): void {
row.selected = !row.selected;
}
escalateSelected(): void {
const selected = this.rows.filter((row: any) => {
return row.selected;
});
selected.forEach((row: any) => {
// Optimistically mark as all escalated.
row.event.escalatedCount = row.event.count;
this.elasticSearchService.escalateAlertGroup(row.event);
});
}
archiveSelected(): void {
const selected = this.rows.filter((row: any) => {
return row.selected &&
row.event.event._source.tags &&
row.event.event._source.tags.indexOf("archived") < 0;
});
selected.forEach((row: any) => {
this.archiveAlertGroup(row);
});
}
archiveAlertGroup(row: any): Promise<any> {
if (!row) {
return;
}
// Optimistically mark the event as archived.
if (!row.event.event._source.tags) {
row.event.event._source.tags = [];
}
row.event.event._source.tags.push("archived");
// If in inbox, also remove it from view.
if (this.appService.getRoute() === "/inbox") {
this.removeRow(row);
}
return this.elasticSearchService.archiveAlertGroup(row.event);
}
archiveEvents(): void {
// If rows are selected, archive the selected rows, otherwise archive
// the current active event.
if (this.getSelectedCount() > 0) {
this.archiveSelected();
} else if (this.getActiveRowIndex() > -1) {
this.archiveAlertGroup(this.getActiveRow());
}
}
removeRow(row: any): void {
const rowIndex = this.rows.indexOf(row);
if (this.rows === this.allRows) {
this.allRows = this.allRows.filter((row0: any) => {
if (row0 === row) {
return false;
}
return true;
});
this.rows = this.allRows;
} else {
// Remove the list of all alerts.
this.allRows = this.allRows.filter((row0: any) => {
if (row0 === row) {
return false;
}
return true;
});
// Remove the event from the visible alerts.
this.rows = this.rows.filter((row0: any) => {
if (row0 === row) {
return false;
}
return true;
});
// Attempt to slide in an event from the next page.
this.rows = this.allRows.slice(this.offset, this.offset + this.windowSize);
}
// If out of rows, attempt to slide in a portion of the complete result
// set.
if (this.rows.length === 0) {
if (this.offset > 0) {
this.offset -= this.windowSize;
}
this.rows = this.allRows.slice(this.offset, this.offset + this.windowSize);
this.activeRow = 0;
// And scroll to the top.
window.scrollTo(0, 0);
} else {
// Otherwise, do some updating of the active row.
if (rowIndex < this.activeRow) {
this.activeRow--;
}
if (this.activeRow >= this.rows.length) {
this.activeRow--;
}
}
}
focusFilterInput(): void {
document.getElementById("filter-input").focus();
}
/**
* Return true if all rows are selected.
*/
allSelected(): boolean {
return this.rows.every((row: any) => {
return row.selected;
});
}
getSelectedRows(): any[] {
return this.rows.filter((row: any) => {
return row.selected;
});
}
getSelectedCount(): number {
return this.getSelectedRows().length;
}
selectAllRows(): void {
this.rows.forEach((row: any) => {
row.selected = true;
});
}
deselectAllRows(): void {
this.rows.forEach((row: any) => {
row.selected = false;
});
}
submitFilter(): void {
const queryParams: any = {};
if (this.queryString !== "") {
queryParams.q = this.queryString;
}
this.router.navigate([], {
queryParams,
});
document.getElementById("filter-input").blur();
}
clearFilter(): void {
this.queryString = "";
this.submitFilter();
}
openEvent(event: AlertGroup): void {
// Save the current state of this.
this.alertService.pushState(this.buildState());
this.eventService.pushAlertGroup(event);
this.router.navigate(["/event", event.event._id, {
referer: this.appService.getRoute()
}]);
}
rowClicked(row: any): void {
this.openEvent(row.event);
}
toggleEscalatedState(row: any, event?: any): void {
if (event) {
event.stopPropagation();
}
const alertGroup: AlertGroup = row.event;
if (alertGroup.escalatedCount < alertGroup.count) {
// Optimistically mark as all escalated.
alertGroup.escalatedCount = alertGroup.count;
this.elasticSearchService.escalateAlertGroup(alertGroup);
} else if (alertGroup.escalatedCount == alertGroup.count) {
// Optimistically mark all as de-escalated.
alertGroup.escalatedCount = 0;
this.elasticSearchService.removeEscalatedStateFromAlertGroup(alertGroup);
}
}
escalateAlertGroup(row: any): Promise<void> {
const alertGroup: any = row.event;
// Optimistically mark as all escalated.
alertGroup.escalatedCount = alertGroup.count;
return this.elasticSearchService.escalateAlertGroup(alertGroup);
}
refresh(silent = false): void {
this.loading = true;
this.silentRefresh = silent;
const queryOptions: any = {
mustHaveTags: [],
mustNotHaveTags: [],
timeRange: "",
queryString: this.queryString,
};
// Add filters depending on view.
switch (this.appService.getRoute()) {
case "/inbox":
// Limit to non-archived events.
queryOptions.mustNotHaveTags.push("archived");
break;
case "/escalated":
// Limit to escalated events only, no time range applied.
queryOptions.mustHaveTags.push("escalated");
break;
default:
break;
}
// Set a time range on all but escalated.
switch (this.appService.getRoute()) {
case "/escalated":
break;
default:
if (this.topNavService.timeRange) {
queryOptions.timeRange = `${this.topNavService.getTimeRangeAsSeconds()}s`;
}
break;
}
this.api.alertQuery(queryOptions).toPromise().then((response: any) => {
const rows = response.alerts.map((alert: AlertGroup) => {
if (response.ecs) {
transformEcsEvent(alert.event);
}
return {
event: alert,
selected: false,
date: moment(alert.maxTs).toDate(),
ecs: response.ecs,
};
});
this.allRows = rows;
this.rows = this.allRows.slice(this.offset, this.windowSize);
this.offset = 0;
this.activeRow = 0;
this.sort();
setTimeout(() => {
this.loading = false;
}, 0);
this.appService.resetIdleTime();
this.silentRefresh = false;
}, (error: any) => {
this.silentRefresh = false;
this.loading = false;
if (error === false) {
console.log("Got error 'false', ignoring.");
return;
}
this.rows = [];
try {
if (error.error.error) {
console.log(error.error.error);
this.toastr.error(error.error.error);
return;
}
} catch (e) {
}
// Check for a reason.
try {
this.toastr.error(error.message);
} catch (err) {
this.toastr.error("An error occurred while executing query.");
}
});
}
// Event handler to show the dropdown menu for the active row.
openDropdownMenu(): void {
// Toggle.
const element = $("#row-" + this.activeRow + " .dropdown-toggle");
element.dropdown("toggle");
// Focus.
element.next().find("a:first").focus();
}
isArchived(row: any): boolean {
if (row.event.event._source.tags) {
if (row.event.event._source.tags.indexOf("archived") > -1) {
return true;
}
}
return false;
}
selectBySignatureId(row: any): void {
const signatureId = row.event.event._source.alert.signature_id;
this.rows.forEach((row: any) => {
if (row.event.event._source.alert.signature_id === signatureId) {
row.selected = true;
}
});
// Close the dropdown. Bootstraps toggle method didn't work quite
// right here, so remove the "show" class.
$(".dropdown-menu.show").removeClass("show");
}
filterBySignatureId(row: any): void {
const signatureId = row.event.event._source.alert.signature_id;
this.appService.updateParams(this.route, {
q: `alert.signature_id:${signatureId}`
});
// Close the dropdown. Bootstraps toggle method didn't work quite
// right here, so remove the "show" class.
$(".dropdown-menu.show").removeClass("show");
}
} | the_stack |
import type { Builder } from "./meta";
// Shared values
// ============================================================================
const commandType = {
type: "array",
items: {
type: ["array", "object", "string"],
properties: {
command: {
type: "string",
},
args: {},
},
required: ["command"],
},
};
const builtinModesAreDeprecatedMessage =
"Built-in modes are deprecated. Use `#dance.modes#` instead.";
const modeNamePattern = {
pattern: /^[a-zA-Z]\w*$/.source,
patternErrorMessage: "",
};
const colorPattern = {
pattern: /^(#[a-fA-F0-9]{3}|#[a-fA-F0-9]{6}|#[a-fA-F0-9]{8}|\$([a-zA-Z]+(\.[a-zA-Z]+)+))$/.source,
patternErrorMessage: "Color should be an hex color or a '$' sign followed by a color identifier.",
};
const selectionDecorationType = {
type: "object",
properties: {
applyTo: {
enum: ["all", "main", "secondary"],
default: "all",
description: "The selections to apply this style to.",
enumDescriptions: [
"Apply to all selections.",
"Apply to main selection only.",
"Apply to all selections except main selection.",
],
},
backgroundColor: {
type: "string",
...colorPattern,
},
borderColor: {
type: "string",
...colorPattern,
},
borderStyle: {
type: "string",
},
borderWidth: {
type: "string",
},
borderRadius: {
type: "string",
},
isWholeLine: {
type: "boolean",
default: false,
},
after: {
type: "object",
},
before: {
type: "object",
},
},
};
// Package information
// ============================================================================
export const pkg = (modules: Builder.ParsedModule[]) => ({
// Common package.json properties.
// ==========================================================================
name: "dance",
description: "Kakoune-inspired key bindings, modes, menus and scripting.",
version: "0.5.7",
license: "ISC",
author: {
name: "Grégoire Geis",
email: "opensource@gregoirege.is",
},
repository: {
type: "git",
url: "https://github.com/71/dance.git",
},
main: "./out/src/extension.js",
browser: "./out/web/extension.js",
engines: {
vscode: "^1.56.0",
},
scripts: {
"check": "eslint . && depcruise -v .dependency-cruiser.js src",
"format": "eslint . --fix",
"generate": "ts-node ./meta.ts",
"generate:watch": "ts-node ./meta.ts --watch",
"vscode:prepublish": "yarn run generate && yarn run compile && yarn run compile-web",
"compile": "tsc -p ./",
"compile:watch": "tsc -watch -p ./",
"compile-web": "webpack --mode production --devtool hidden-source-map --config ./webpack.web.config.js",
"compile-web:watch": "webpack --watch --config ./webpack.web.config.js",
"test": "yarn run compile && node ./out/test/run.js",
"package": "vsce package",
"publish": "vsce publish",
},
devDependencies: {
"@types/glob": "^7.1.1",
"@types/mocha": "^8.0.3",
"@types/node": "^14.6.0",
"@types/vscode": "^1.56.0",
"@typescript-eslint/eslint-plugin": "^4.18.0",
"@typescript-eslint/parser": "^4.18.0",
"chokidar": "^3.5.1",
"dependency-cruiser": "^10.0.5",
"eslint": "^7.22.0",
"glob": "^7.1.6",
"mocha": "^8.1.1",
"source-map-support": "^0.5.19",
"ts-loader": "^9.2.5",
"ts-node": "^9.1.1",
"typescript": "^4.2.4",
"unexpected": "^12.0.0",
"vsce": "^1.99.0",
"vscode-test": "^1.5.2",
"webpack": "^5.52.1",
"webpack-cli": "^4.8.0",
},
// VS Code-specific properties.
// ==========================================================================
displayName: "Dance",
publisher: "gregoire",
categories: ["Keymaps", "Other"],
readme: "README.md",
icon: "assets/dance.png",
activationEvents: ["*"],
extensionKind: ["ui", "workspace"],
// Dance-specific properties.
// ==========================================================================
// The two properties below can be set when distributing Dance to ensure it
// cannot execute arbitrary code (with `dance.run`) or system commands (with
// `dance.selections.{filter,pipe}`).
"dance.disableArbitraryCodeExecution": false,
"dance.disableArbitraryCommandExecution": false,
// Capabilities.
// ==========================================================================
capabilities: {
untrustedWorkspaces: {
supported: "limited",
description:
"Existing menu items and mode commands can only be updated if the current workspace is "
+ "trusted in order to ensure untrusted workspaces do not execute malicious commands.",
},
virtualWorkspaces: true,
},
contributes: {
// Configuration.
// ========================================================================
configuration: {
type: "object",
title: "Dance",
properties: {
"dance.defaultMode": {
type: "string",
scope: "language-overridable",
default: "normal",
description: "Controls which mode is set by default when an editor is opened.",
...modeNamePattern,
},
"dance.modes": {
type: "object",
scope: "language-overridable",
additionalProperties: {
type: "object",
propertyNames: modeNamePattern,
properties: {
inheritFrom: {
type: ["string", "null"],
description:
"Controls how default configuration options are obtained for this mode. "
+ "Specify a string to inherit from the mode with the given name, "
+ "and null to inherit from the VS Code configuration.",
...modeNamePattern,
},
cursorStyle: {
enum: [
"line",
"block",
"underline",
"line-thin",
"block-outline",
"underline-thin",
"inherit",
null,
],
description: "Controls the cursor style.",
},
lineHighlight: {
type: ["string", "null"],
markdownDescription:
"Controls the line highlighting applied to active lines. "
+ "Can be an hex color, a [theme color]("
+ "https://code.visualstudio.com/api/references/theme-color) or null.",
deprecationMessage:
"`lineHighlight` is deprecated. Use `dance.modes.*.backgroundColor` instead.",
markdownDeprecationMessage:
"`lineHighlight` is deprecated. Use `#dance.modes#.*.backgroundColor` instead.",
...colorPattern,
},
lineNumbers: {
enum: ["off", "on", "relative", "inherit", null],
description: "Controls the display of line numbers.",
enumDescriptions: [
"No line numbers.",
"Absolute line numbers.",
"Relative line numbers.",
"Inherit from `editor.lineNumbers`.",
],
},
onEnterMode: {
...commandType,
description:
"Controls what commands should be executed upon entering this mode.",
},
onLeaveMode: {
...commandType,
description:
"Controls what commands should be executed upon leaving this mode.",
},
selectionBehavior: {
enum: ["caret", "character", null],
default: "caret",
description: "Controls how selections behave within VS Code.",
markdownEnumDescriptions: [
"Selections are anchored to carets, which is the native VS Code behavior; "
+ "that is, they are positioned *between* characters and can therefore be "
+ "empty.",
"Selections are anchored to characters, like Kakoune; that is, they are "
+ "positioned *on* characters, and therefore cannot be empty. "
+ "Additionally, one-character selections will behave as if they were "
+ "non-directional, like Kakoune.",
],
},
decorations: {
...selectionDecorationType,
type: ["array", "object", "null"],
description: "The decorations to apply to selections.",
items: selectionDecorationType,
},
hiddenSelectionsIndicatorsDecoration: {
...selectionDecorationType,
type: ["object", "null"],
description:
"The decorations to apply to the hidden selections indicator, shown when "
+ "some selections are below or above the lines currently shown in the editor. "
+ "Specify an empty object {} to disable this indicator.",
},
},
additionalProperties: false,
},
default: {
"": {
hiddenSelectionsIndicatorsDecoration: {
after: {
color: "$list.warningForeground",
},
backgroundColor: "$inputValidation.warningBackground",
borderColor: "$inputValidation.warningBorder",
borderStyle: "solid",
borderWidth: "1px",
isWholeLine: true,
},
},
input: {
cursorStyle: "underline-thin",
},
insert: {
onLeaveMode: [
[".selections.save", {
register: " insert",
}],
],
},
normal: {
lineNumbers: "relative",
decorations: {
applyTo: "main",
backgroundColor: "$editor.hoverHighlightBackground",
isWholeLine: true,
},
onEnterMode: [
[".selections.restore", { register: " ^", try: true }],
],
onLeaveMode: [
[".selections.save", {
register: " ^",
style: {
borderColor: "$editor.selectionBackground",
borderStyle: "solid",
borderWidth: "2px",
borderRadius: "1px",
},
until: [
["mode-did-change", { include: "normal" }],
["selections-did-change"],
],
}],
],
},
},
description: "Controls the different modes available in Dance.",
},
"dance.menus": {
type: "object",
scope: "language-overridable",
description: "Controls the different menus available in Dance.",
additionalProperties: {
type: "object",
properties: {
items: {
type: "object",
additionalProperties: {
type: "object",
properties: {
text: {
type: "string",
description: "Text shown in the menu.",
},
command: {
type: "string",
description: "Command to execute on item selection.",
},
args: {
type: "array",
description: "Arguments to the command to execute.",
},
},
required: ["command"],
},
},
},
additionalProperties: false,
},
default: {
"object": {
items: ((command = "dance.seek.object") => ({
"b()": {
command,
args: [{ input: "\\((?#inner)\\)" }],
text: "parenthesis block",
},
"B{}": {
command,
args: [{ input: "\\{(?#inner)\\}" }],
text: "braces block",
},
"r[]": {
command,
args: [{ input: "\\[(?#inner)\\]" }],
text: "brackets block",
},
"a<>": {
command,
args: [{ input: "<(?#inner)>" }],
text: "angle block",
},
'Q"': {
command,
args: [{ input: "(?#noescape)\"(?#inner)(?#noescape)\"" }],
text: "double quote string",
},
"q'": {
command,
args: [{ input: "(?#noescape)'(?#inner)(?#noescape)'" }],
text: "single quote string",
},
"g`": {
command,
args: [{ input: "(?#noescape)`(?#inner)(?#noescape)`" }],
text: "grave quote string",
},
"w": {
command,
args: [{ input: "[\\p{L}_\\d]+(?<after>[^\\S\\n]+)" }],
text: "word",
},
"W": {
command,
args: [{ input: "[\\S]+(?<after>[^\\S\\n]+)" }],
text: "WORD",
},
"s": {
command,
args: [{ input: "(?#predefined=sentence)" }],
text: "sentence",
},
"p": {
command,
args: [{ input: "(?#predefined=paragraph)" }],
text: "paragraph",
},
" ": {
command,
args: [{ input: "(?<before>[\\s]+)[^\\S\\n]+(?<after>[\\s]+)" }],
text: "whitespaces",
},
"i": {
command,
args: [{ input: "(?#predefined=indent)" }],
text: "indent",
},
"n": {
command,
args: [{ input: "(?#singleline)-?[\\d_]+(\\.[0-9]+)?([eE]\\d+)?" }],
text: "number",
},
"u": {
command,
args: [{ input: "(?#predefined=argument)" }],
text: "argument",
},
"c": {
command,
text: "custom object desc",
},
}))(),
},
"goto": {
items: {
"h": {
text: "to line start",
command: "dance.select.lineStart",
},
"l": {
text: "to line end",
command: "dance.select.lineEnd",
},
"i": {
text: "to non-blank line start",
command: "dance.select.lineStart",
args: [{ skipBlank: true }],
},
"gk": {
text: "to first line",
command: "dance.select.lineStart",
args: [{ count: 1 }],
},
"j": {
text: "to last line",
command: "dance.select.lastLine",
},
"e": {
text: "to last char of last line",
command: "dance.select.lineEnd",
args: [{ count: 2 ** 31 - 1 }],
},
"t": {
text: "to first displayed line",
command: "dance.select.firstVisibleLine",
},
"c": {
text: "to middle displayed line",
command: "dance.select.middleVisibleLine",
},
"b": {
text: "to last displayed line",
command: "dance.select.lastVisibleLine",
},
"f": {
text: "to file whose name is selected",
command: "dance.selections.open",
},
".": {
text: "to last buffer modification position",
command: "dance.selections.restore",
args: [{ register: " insert" }],
},
},
},
"view": {
items: {
// AFAIK, we can't implement these yet since VS Code only
// exposes vertical view ranges:
// - m, center cursor horizontally
// - h, scroll left
// - l, scroll right
"vc": {
text: "center cursor vertically",
command: "dance.view.line",
args: [{ at: "center" }],
},
"t": {
text: "cursor on top",
command: "dance.view.line",
args: [{ at: "top" }],
},
"b": {
text: "cursor on bottom",
command: "dance.view.line",
args: [{ at: "bottom" }],
},
"j": {
text: "scroll down",
command: "editorScroll",
args: [{ to: "down", by: "line", revealCursor: true }],
},
"k": {
text: "scroll up",
command: "editorScroll",
args: [{ to: "up", by: "line", revealCursor: true }],
},
},
},
} as Record<string,
{ items: Record<string, { text: string; command: string; args?: any[] }>}>,
},
// Deprecated configuration:
"dance.enabled": {
type: "boolean",
default: true,
description: "Controls whether the Dance keybindings are enabled.",
deprecationMessage: "dance.enabled is deprecated; disable the Dance extension instead.",
},
"dance.normalMode.lineHighlight": {
type: ["string", "null"],
default: "editor.hoverHighlightBackground",
markdownDescription:
"Controls the line highlighting applied to active lines in normal mode. "
+ "Can be an hex color, a [theme color]("
+ "https://code.visualstudio.com/api/references/theme-color) or null.",
markdownDeprecationMessage: builtinModesAreDeprecatedMessage,
},
"dance.insertMode.lineHighlight": {
type: ["string", "null"],
default: null,
markdownDescription:
"Controls the line highlighting applied to active lines in insert mode. "
+ "Can be an hex color, a [theme color]("
+ "https://code.visualstudio.com/api/references/theme-color) or null.",
markdownDeprecationMessage: builtinModesAreDeprecatedMessage,
},
"dance.normalMode.lineNumbers": {
enum: ["off", "on", "relative", "inherit"],
default: "relative",
description: "Controls the display of line numbers in normal mode.",
enumDescriptions: [
"No line numbers.",
"Absolute line numbers.",
"Relative line numbers.",
"Inherit from `editor.lineNumbers`.",
],
markdownDeprecationMessage: builtinModesAreDeprecatedMessage,
},
"dance.insertMode.lineNumbers": {
enum: ["off", "on", "relative", "inherit"],
default: "inherit",
description: "Controls the display of line numbers in insert mode.",
enumDescriptions: [
"No line numbers.",
"Absolute line numbers.",
"Relative line numbers.",
"Inherit from `editor.lineNumbers`.",
],
markdownDeprecationMessage: builtinModesAreDeprecatedMessage,
},
"dance.normalMode.cursorStyle": {
enum: [
"line",
"block",
"underline",
"line-thin",
"block-outline",
"underline-thin",
"inherit",
],
default: "inherit",
description: "Controls the cursor style in normal mode.",
markdownDeprecationMessage: builtinModesAreDeprecatedMessage,
},
"dance.insertMode.cursorStyle": {
enum: [
"line",
"block",
"underline",
"line-thin",
"block-outline",
"underline-thin",
"inherit",
],
default: "inherit",
description: "Controls the cursor style in insert mode.",
markdownDeprecationMessage: builtinModesAreDeprecatedMessage,
},
"dance.insertMode.selectionStyle": {
type: "object",
default: {
borderColor: "$editor.selectionBackground",
borderStyle: "solid",
borderWidth: "2px",
borderRadius: "1px",
},
description: "The style to apply to selections in insert mode.",
properties: (Object as any).fromEntries(
[
"backgroundColor",
"borderColor",
"borderStyle",
"borderWidth",
"borderRadius",
].map((x) => [x, { type: "string" }]),
),
markdownDeprecationMessage: builtinModesAreDeprecatedMessage,
},
"dance.selectionBehavior": {
enum: ["caret", "character"],
default: "caret",
description: "Controls how selections behave within VS Code.",
markdownEnumDescriptions: [
"Selections are anchored to carets, which is the native VS Code behavior; that is, "
+ "they are positioned *between* characters and can therefore be empty.",
"Selections are anchored to characters, like Kakoune; that is, they are positioned "
+ "*on* characters, and therefore cannot be empty. Additionally, one-character "
+ "selections will behave as if they were non-directional, like Kakoune.",
],
markdownDeprecationMessage: builtinModesAreDeprecatedMessage,
},
},
},
// Commands.
// ========================================================================
commands: modules.flatMap((module) => module.commands.map((x) => ({
command: x.id,
title: x.title,
category: "Dance",
}))),
menus: {
commandPalette: modules.flatMap((module) => module.commands.map((x) => ({
command: x.id,
when: x.when,
}))),
},
// Keybindings.
// ========================================================================
keybindings: (() => {
const keybindings = modules.flatMap((module) => module.keybindings),
alphanum = [..."ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"],
keysToAssign = new Set([...alphanum, ...alphanum.map((x) => `Shift+${x}`), ...",'"]);
for (const keybinding of keybindings) {
keysToAssign.delete(keybinding.key);
}
for (const keyToAssign of keysToAssign) {
keybindings.push({
command: "dance.ignore",
key: keyToAssign,
when: "editorTextFocus && dance.mode == 'normal'",
});
}
return keybindings;
})(),
},
});
// Save to package.json
// ============================================================================
export async function build(builder: Builder) {
const fs = await import("fs/promises");
await fs.writeFile(
`${__dirname}/package.json`,
JSON.stringify(pkg(await builder.getCommandModules()), undefined, 2) + "\n",
"utf-8",
);
} | the_stack |
import type { languages } from '../fillers/monaco-editor-core';
export const conf: languages.LanguageConfiguration = {
comments: {
lineComment: '//',
blockComment: ['/*', '*/']
},
brackets: [
['[', ']'],
['(', ')'],
['{', '}']
],
autoClosingPairs: [
{ open: '"', close: '"', notIn: ['string', 'comment', 'identifier'] },
{ open: '[', close: ']', notIn: ['string', 'comment', 'identifier'] },
{ open: '(', close: ')', notIn: ['string', 'comment', 'identifier'] },
{ open: '{', close: '}', notIn: ['string', 'comment', 'identifier'] }
]
};
export const language = <languages.IMonarchLanguage>{
defaultToken: '',
tokenPostfix: '.pq',
ignoreCase: false,
brackets: [
{ open: '[', close: ']', token: 'delimiter.square' },
{ open: '{', close: '}', token: 'delimiter.brackets' },
{ open: '(', close: ')', token: 'delimiter.parenthesis' }
],
operatorKeywords: ['and', 'not', 'or'],
keywords: [
'as',
'each',
'else',
'error',
'false',
'if',
'in',
'is',
'let',
'meta',
'otherwise',
'section',
'shared',
'then',
'true',
'try',
'type'
],
constructors: [
'#binary',
'#date',
'#datetime',
'#datetimezone',
'#duration',
'#table',
'#time'
],
constants: ['#infinity', '#nan', '#sections', '#shared'],
typeKeywords: [
'action',
'any',
'anynonnull',
'none',
'null',
'logical',
'number',
'time',
'date',
'datetime',
'datetimezone',
'duration',
'text',
'binary',
'list',
'record',
'table',
'function'
],
builtinFunctions: [
'Access.Database',
'Action.Return',
'Action.Sequence',
'Action.Try',
'ActiveDirectory.Domains',
'AdoDotNet.DataSource',
'AdoDotNet.Query',
'AdobeAnalytics.Cubes',
'AnalysisServices.Database',
'AnalysisServices.Databases',
'AzureStorage.BlobContents',
'AzureStorage.Blobs',
'AzureStorage.Tables',
'Binary.Buffer',
'Binary.Combine',
'Binary.Compress',
'Binary.Decompress',
'Binary.End',
'Binary.From',
'Binary.FromList',
'Binary.FromText',
'Binary.InferContentType',
'Binary.Length',
'Binary.ToList',
'Binary.ToText',
'BinaryFormat.7BitEncodedSignedInteger',
'BinaryFormat.7BitEncodedUnsignedInteger',
'BinaryFormat.Binary',
'BinaryFormat.Byte',
'BinaryFormat.ByteOrder',
'BinaryFormat.Choice',
'BinaryFormat.Decimal',
'BinaryFormat.Double',
'BinaryFormat.Group',
'BinaryFormat.Length',
'BinaryFormat.List',
'BinaryFormat.Null',
'BinaryFormat.Record',
'BinaryFormat.SignedInteger16',
'BinaryFormat.SignedInteger32',
'BinaryFormat.SignedInteger64',
'BinaryFormat.Single',
'BinaryFormat.Text',
'BinaryFormat.Transform',
'BinaryFormat.UnsignedInteger16',
'BinaryFormat.UnsignedInteger32',
'BinaryFormat.UnsignedInteger64',
'Byte.From',
'Character.FromNumber',
'Character.ToNumber',
'Combiner.CombineTextByDelimiter',
'Combiner.CombineTextByEachDelimiter',
'Combiner.CombineTextByLengths',
'Combiner.CombineTextByPositions',
'Combiner.CombineTextByRanges',
'Comparer.Equals',
'Comparer.FromCulture',
'Comparer.Ordinal',
'Comparer.OrdinalIgnoreCase',
'Csv.Document',
'Cube.AddAndExpandDimensionColumn',
'Cube.AddMeasureColumn',
'Cube.ApplyParameter',
'Cube.AttributeMemberId',
'Cube.AttributeMemberProperty',
'Cube.CollapseAndRemoveColumns',
'Cube.Dimensions',
'Cube.DisplayFolders',
'Cube.Measures',
'Cube.Parameters',
'Cube.Properties',
'Cube.PropertyKey',
'Cube.ReplaceDimensions',
'Cube.Transform',
'Currency.From',
'DB2.Database',
'Date.AddDays',
'Date.AddMonths',
'Date.AddQuarters',
'Date.AddWeeks',
'Date.AddYears',
'Date.Day',
'Date.DayOfWeek',
'Date.DayOfWeekName',
'Date.DayOfYear',
'Date.DaysInMonth',
'Date.EndOfDay',
'Date.EndOfMonth',
'Date.EndOfQuarter',
'Date.EndOfWeek',
'Date.EndOfYear',
'Date.From',
'Date.FromText',
'Date.IsInCurrentDay',
'Date.IsInCurrentMonth',
'Date.IsInCurrentQuarter',
'Date.IsInCurrentWeek',
'Date.IsInCurrentYear',
'Date.IsInNextDay',
'Date.IsInNextMonth',
'Date.IsInNextNDays',
'Date.IsInNextNMonths',
'Date.IsInNextNQuarters',
'Date.IsInNextNWeeks',
'Date.IsInNextNYears',
'Date.IsInNextQuarter',
'Date.IsInNextWeek',
'Date.IsInNextYear',
'Date.IsInPreviousDay',
'Date.IsInPreviousMonth',
'Date.IsInPreviousNDays',
'Date.IsInPreviousNMonths',
'Date.IsInPreviousNQuarters',
'Date.IsInPreviousNWeeks',
'Date.IsInPreviousNYears',
'Date.IsInPreviousQuarter',
'Date.IsInPreviousWeek',
'Date.IsInPreviousYear',
'Date.IsInYearToDate',
'Date.IsLeapYear',
'Date.Month',
'Date.MonthName',
'Date.QuarterOfYear',
'Date.StartOfDay',
'Date.StartOfMonth',
'Date.StartOfQuarter',
'Date.StartOfWeek',
'Date.StartOfYear',
'Date.ToRecord',
'Date.ToText',
'Date.WeekOfMonth',
'Date.WeekOfYear',
'Date.Year',
'DateTime.AddZone',
'DateTime.Date',
'DateTime.FixedLocalNow',
'DateTime.From',
'DateTime.FromFileTime',
'DateTime.FromText',
'DateTime.IsInCurrentHour',
'DateTime.IsInCurrentMinute',
'DateTime.IsInCurrentSecond',
'DateTime.IsInNextHour',
'DateTime.IsInNextMinute',
'DateTime.IsInNextNHours',
'DateTime.IsInNextNMinutes',
'DateTime.IsInNextNSeconds',
'DateTime.IsInNextSecond',
'DateTime.IsInPreviousHour',
'DateTime.IsInPreviousMinute',
'DateTime.IsInPreviousNHours',
'DateTime.IsInPreviousNMinutes',
'DateTime.IsInPreviousNSeconds',
'DateTime.IsInPreviousSecond',
'DateTime.LocalNow',
'DateTime.Time',
'DateTime.ToRecord',
'DateTime.ToText',
'DateTimeZone.FixedLocalNow',
'DateTimeZone.FixedUtcNow',
'DateTimeZone.From',
'DateTimeZone.FromFileTime',
'DateTimeZone.FromText',
'DateTimeZone.LocalNow',
'DateTimeZone.RemoveZone',
'DateTimeZone.SwitchZone',
'DateTimeZone.ToLocal',
'DateTimeZone.ToRecord',
'DateTimeZone.ToText',
'DateTimeZone.ToUtc',
'DateTimeZone.UtcNow',
'DateTimeZone.ZoneHours',
'DateTimeZone.ZoneMinutes',
'Decimal.From',
'Diagnostics.ActivityId',
'Diagnostics.Trace',
'DirectQueryCapabilities.From',
'Double.From',
'Duration.Days',
'Duration.From',
'Duration.FromText',
'Duration.Hours',
'Duration.Minutes',
'Duration.Seconds',
'Duration.ToRecord',
'Duration.ToText',
'Duration.TotalDays',
'Duration.TotalHours',
'Duration.TotalMinutes',
'Duration.TotalSeconds',
'Embedded.Value',
'Error.Record',
'Excel.CurrentWorkbook',
'Excel.Workbook',
'Exchange.Contents',
'Expression.Constant',
'Expression.Evaluate',
'Expression.Identifier',
'Facebook.Graph',
'File.Contents',
'Folder.Contents',
'Folder.Files',
'Function.From',
'Function.Invoke',
'Function.InvokeAfter',
'Function.IsDataSource',
'GoogleAnalytics.Accounts',
'Guid.From',
'HdInsight.Containers',
'HdInsight.Contents',
'HdInsight.Files',
'Hdfs.Contents',
'Hdfs.Files',
'Informix.Database',
'Int16.From',
'Int32.From',
'Int64.From',
'Int8.From',
'ItemExpression.From',
'Json.Document',
'Json.FromValue',
'Lines.FromBinary',
'Lines.FromText',
'Lines.ToBinary',
'Lines.ToText',
'List.Accumulate',
'List.AllTrue',
'List.Alternate',
'List.AnyTrue',
'List.Average',
'List.Buffer',
'List.Combine',
'List.Contains',
'List.ContainsAll',
'List.ContainsAny',
'List.Count',
'List.Covariance',
'List.DateTimeZones',
'List.DateTimes',
'List.Dates',
'List.Difference',
'List.Distinct',
'List.Durations',
'List.FindText',
'List.First',
'List.FirstN',
'List.Generate',
'List.InsertRange',
'List.Intersect',
'List.IsDistinct',
'List.IsEmpty',
'List.Last',
'List.LastN',
'List.MatchesAll',
'List.MatchesAny',
'List.Max',
'List.MaxN',
'List.Median',
'List.Min',
'List.MinN',
'List.Mode',
'List.Modes',
'List.NonNullCount',
'List.Numbers',
'List.PositionOf',
'List.PositionOfAny',
'List.Positions',
'List.Product',
'List.Random',
'List.Range',
'List.RemoveFirstN',
'List.RemoveItems',
'List.RemoveLastN',
'List.RemoveMatchingItems',
'List.RemoveNulls',
'List.RemoveRange',
'List.Repeat',
'List.ReplaceMatchingItems',
'List.ReplaceRange',
'List.ReplaceValue',
'List.Reverse',
'List.Select',
'List.Single',
'List.SingleOrDefault',
'List.Skip',
'List.Sort',
'List.StandardDeviation',
'List.Sum',
'List.Times',
'List.Transform',
'List.TransformMany',
'List.Union',
'List.Zip',
'Logical.From',
'Logical.FromText',
'Logical.ToText',
'MQ.Queue',
'MySQL.Database',
'Number.Abs',
'Number.Acos',
'Number.Asin',
'Number.Atan',
'Number.Atan2',
'Number.BitwiseAnd',
'Number.BitwiseNot',
'Number.BitwiseOr',
'Number.BitwiseShiftLeft',
'Number.BitwiseShiftRight',
'Number.BitwiseXor',
'Number.Combinations',
'Number.Cos',
'Number.Cosh',
'Number.Exp',
'Number.Factorial',
'Number.From',
'Number.FromText',
'Number.IntegerDivide',
'Number.IsEven',
'Number.IsNaN',
'Number.IsOdd',
'Number.Ln',
'Number.Log',
'Number.Log10',
'Number.Mod',
'Number.Permutations',
'Number.Power',
'Number.Random',
'Number.RandomBetween',
'Number.Round',
'Number.RoundAwayFromZero',
'Number.RoundDown',
'Number.RoundTowardZero',
'Number.RoundUp',
'Number.Sign',
'Number.Sin',
'Number.Sinh',
'Number.Sqrt',
'Number.Tan',
'Number.Tanh',
'Number.ToText',
'OData.Feed',
'Odbc.DataSource',
'Odbc.Query',
'OleDb.DataSource',
'OleDb.Query',
'Oracle.Database',
'Percentage.From',
'PostgreSQL.Database',
'RData.FromBinary',
'Record.AddField',
'Record.Combine',
'Record.Field',
'Record.FieldCount',
'Record.FieldNames',
'Record.FieldOrDefault',
'Record.FieldValues',
'Record.FromList',
'Record.FromTable',
'Record.HasFields',
'Record.RemoveFields',
'Record.RenameFields',
'Record.ReorderFields',
'Record.SelectFields',
'Record.ToList',
'Record.ToTable',
'Record.TransformFields',
'Replacer.ReplaceText',
'Replacer.ReplaceValue',
'RowExpression.Column',
'RowExpression.From',
'Salesforce.Data',
'Salesforce.Reports',
'SapBusinessWarehouse.Cubes',
'SapHana.Database',
'SharePoint.Contents',
'SharePoint.Files',
'SharePoint.Tables',
'Single.From',
'Soda.Feed',
'Splitter.SplitByNothing',
'Splitter.SplitTextByAnyDelimiter',
'Splitter.SplitTextByDelimiter',
'Splitter.SplitTextByEachDelimiter',
'Splitter.SplitTextByLengths',
'Splitter.SplitTextByPositions',
'Splitter.SplitTextByRanges',
'Splitter.SplitTextByRepeatedLengths',
'Splitter.SplitTextByWhitespace',
'Sql.Database',
'Sql.Databases',
'SqlExpression.SchemaFrom',
'SqlExpression.ToExpression',
'Sybase.Database',
'Table.AddColumn',
'Table.AddIndexColumn',
'Table.AddJoinColumn',
'Table.AddKey',
'Table.AggregateTableColumn',
'Table.AlternateRows',
'Table.Buffer',
'Table.Column',
'Table.ColumnCount',
'Table.ColumnNames',
'Table.ColumnsOfType',
'Table.Combine',
'Table.CombineColumns',
'Table.Contains',
'Table.ContainsAll',
'Table.ContainsAny',
'Table.DemoteHeaders',
'Table.Distinct',
'Table.DuplicateColumn',
'Table.ExpandListColumn',
'Table.ExpandRecordColumn',
'Table.ExpandTableColumn',
'Table.FillDown',
'Table.FillUp',
'Table.FilterWithDataTable',
'Table.FindText',
'Table.First',
'Table.FirstN',
'Table.FirstValue',
'Table.FromColumns',
'Table.FromList',
'Table.FromPartitions',
'Table.FromRecords',
'Table.FromRows',
'Table.FromValue',
'Table.Group',
'Table.HasColumns',
'Table.InsertRows',
'Table.IsDistinct',
'Table.IsEmpty',
'Table.Join',
'Table.Keys',
'Table.Last',
'Table.LastN',
'Table.MatchesAllRows',
'Table.MatchesAnyRows',
'Table.Max',
'Table.MaxN',
'Table.Min',
'Table.MinN',
'Table.NestedJoin',
'Table.Partition',
'Table.PartitionValues',
'Table.Pivot',
'Table.PositionOf',
'Table.PositionOfAny',
'Table.PrefixColumns',
'Table.Profile',
'Table.PromoteHeaders',
'Table.Range',
'Table.RemoveColumns',
'Table.RemoveFirstN',
'Table.RemoveLastN',
'Table.RemoveMatchingRows',
'Table.RemoveRows',
'Table.RemoveRowsWithErrors',
'Table.RenameColumns',
'Table.ReorderColumns',
'Table.Repeat',
'Table.ReplaceErrorValues',
'Table.ReplaceKeys',
'Table.ReplaceMatchingRows',
'Table.ReplaceRelationshipIdentity',
'Table.ReplaceRows',
'Table.ReplaceValue',
'Table.ReverseRows',
'Table.RowCount',
'Table.Schema',
'Table.SelectColumns',
'Table.SelectRows',
'Table.SelectRowsWithErrors',
'Table.SingleRow',
'Table.Skip',
'Table.Sort',
'Table.SplitColumn',
'Table.ToColumns',
'Table.ToList',
'Table.ToRecords',
'Table.ToRows',
'Table.TransformColumnNames',
'Table.TransformColumnTypes',
'Table.TransformColumns',
'Table.TransformRows',
'Table.Transpose',
'Table.Unpivot',
'Table.UnpivotOtherColumns',
'Table.View',
'Table.ViewFunction',
'TableAction.DeleteRows',
'TableAction.InsertRows',
'TableAction.UpdateRows',
'Tables.GetRelationships',
'Teradata.Database',
'Text.AfterDelimiter',
'Text.At',
'Text.BeforeDelimiter',
'Text.BetweenDelimiters',
'Text.Clean',
'Text.Combine',
'Text.Contains',
'Text.End',
'Text.EndsWith',
'Text.Format',
'Text.From',
'Text.FromBinary',
'Text.Insert',
'Text.Length',
'Text.Lower',
'Text.Middle',
'Text.NewGuid',
'Text.PadEnd',
'Text.PadStart',
'Text.PositionOf',
'Text.PositionOfAny',
'Text.Proper',
'Text.Range',
'Text.Remove',
'Text.RemoveRange',
'Text.Repeat',
'Text.Replace',
'Text.ReplaceRange',
'Text.Select',
'Text.Split',
'Text.SplitAny',
'Text.Start',
'Text.StartsWith',
'Text.ToBinary',
'Text.ToList',
'Text.Trim',
'Text.TrimEnd',
'Text.TrimStart',
'Text.Upper',
'Time.EndOfHour',
'Time.From',
'Time.FromText',
'Time.Hour',
'Time.Minute',
'Time.Second',
'Time.StartOfHour',
'Time.ToRecord',
'Time.ToText',
'Type.AddTableKey',
'Type.ClosedRecord',
'Type.Facets',
'Type.ForFunction',
'Type.ForRecord',
'Type.FunctionParameters',
'Type.FunctionRequiredParameters',
'Type.FunctionReturn',
'Type.Is',
'Type.IsNullable',
'Type.IsOpenRecord',
'Type.ListItem',
'Type.NonNullable',
'Type.OpenRecord',
'Type.RecordFields',
'Type.ReplaceFacets',
'Type.ReplaceTableKeys',
'Type.TableColumn',
'Type.TableKeys',
'Type.TableRow',
'Type.TableSchema',
'Type.Union',
'Uri.BuildQueryString',
'Uri.Combine',
'Uri.EscapeDataString',
'Uri.Parts',
'Value.Add',
'Value.As',
'Value.Compare',
'Value.Divide',
'Value.Equals',
'Value.Firewall',
'Value.FromText',
'Value.Is',
'Value.Metadata',
'Value.Multiply',
'Value.NativeQuery',
'Value.NullableEquals',
'Value.RemoveMetadata',
'Value.ReplaceMetadata',
'Value.ReplaceType',
'Value.Subtract',
'Value.Type',
'ValueAction.NativeStatement',
'ValueAction.Replace',
'Variable.Value',
'Web.Contents',
'Web.Page',
'WebAction.Request',
'Xml.Document',
'Xml.Tables'
],
builtinConstants: [
'BinaryEncoding.Base64',
'BinaryEncoding.Hex',
'BinaryOccurrence.Optional',
'BinaryOccurrence.Repeating',
'BinaryOccurrence.Required',
'ByteOrder.BigEndian',
'ByteOrder.LittleEndian',
'Compression.Deflate',
'Compression.GZip',
'CsvStyle.QuoteAfterDelimiter',
'CsvStyle.QuoteAlways',
'Culture.Current',
'Day.Friday',
'Day.Monday',
'Day.Saturday',
'Day.Sunday',
'Day.Thursday',
'Day.Tuesday',
'Day.Wednesday',
'ExtraValues.Error',
'ExtraValues.Ignore',
'ExtraValues.List',
'GroupKind.Global',
'GroupKind.Local',
'JoinAlgorithm.Dynamic',
'JoinAlgorithm.LeftHash',
'JoinAlgorithm.LeftIndex',
'JoinAlgorithm.PairwiseHash',
'JoinAlgorithm.RightHash',
'JoinAlgorithm.RightIndex',
'JoinAlgorithm.SortMerge',
'JoinKind.FullOuter',
'JoinKind.Inner',
'JoinKind.LeftAnti',
'JoinKind.LeftOuter',
'JoinKind.RightAnti',
'JoinKind.RightOuter',
'JoinSide.Left',
'JoinSide.Right',
'MissingField.Error',
'MissingField.Ignore',
'MissingField.UseNull',
'Number.E',
'Number.Epsilon',
'Number.NaN',
'Number.NegativeInfinity',
'Number.PI',
'Number.PositiveInfinity',
'Occurrence.All',
'Occurrence.First',
'Occurrence.Last',
'Occurrence.Optional',
'Occurrence.Repeating',
'Occurrence.Required',
'Order.Ascending',
'Order.Descending',
'Precision.Decimal',
'Precision.Double',
'QuoteStyle.Csv',
'QuoteStyle.None',
'RelativePosition.FromEnd',
'RelativePosition.FromStart',
'RoundingMode.AwayFromZero',
'RoundingMode.Down',
'RoundingMode.ToEven',
'RoundingMode.TowardZero',
'RoundingMode.Up',
'SapHanaDistribution.All',
'SapHanaDistribution.Connection',
'SapHanaDistribution.Off',
'SapHanaDistribution.Statement',
'SapHanaRangeOperator.Equals',
'SapHanaRangeOperator.GreaterThan',
'SapHanaRangeOperator.GreaterThanOrEquals',
'SapHanaRangeOperator.LessThan',
'SapHanaRangeOperator.LessThanOrEquals',
'SapHanaRangeOperator.NotEquals',
'TextEncoding.Ascii',
'TextEncoding.BigEndianUnicode',
'TextEncoding.Unicode',
'TextEncoding.Utf16',
'TextEncoding.Utf8',
'TextEncoding.Windows',
'TraceLevel.Critical',
'TraceLevel.Error',
'TraceLevel.Information',
'TraceLevel.Verbose',
'TraceLevel.Warning',
'WebMethod.Delete',
'WebMethod.Get',
'WebMethod.Head',
'WebMethod.Patch',
'WebMethod.Post',
'WebMethod.Put'
],
builtinTypes: [
'Action.Type',
'Any.Type',
'Binary.Type',
'BinaryEncoding.Type',
'BinaryOccurrence.Type',
'Byte.Type',
'ByteOrder.Type',
'Character.Type',
'Compression.Type',
'CsvStyle.Type',
'Currency.Type',
'Date.Type',
'DateTime.Type',
'DateTimeZone.Type',
'Day.Type',
'Decimal.Type',
'Double.Type',
'Duration.Type',
'ExtraValues.Type',
'Function.Type',
'GroupKind.Type',
'Guid.Type',
'Int16.Type',
'Int32.Type',
'Int64.Type',
'Int8.Type',
'JoinAlgorithm.Type',
'JoinKind.Type',
'JoinSide.Type',
'List.Type',
'Logical.Type',
'MissingField.Type',
'None.Type',
'Null.Type',
'Number.Type',
'Occurrence.Type',
'Order.Type',
'Password.Type',
'Percentage.Type',
'Precision.Type',
'QuoteStyle.Type',
'Record.Type',
'RelativePosition.Type',
'RoundingMode.Type',
'SapHanaDistribution.Type',
'SapHanaRangeOperator.Type',
'Single.Type',
'Table.Type',
'Text.Type',
'TextEncoding.Type',
'Time.Type',
'TraceLevel.Type',
'Type.Type',
'Uri.Type',
'WebMethod.Type'
],
tokenizer: {
root: [
// quoted identifier
[/#"[\w \.]+"/, 'identifier.quote'],
// numbers
[/\d*\.\d+([eE][\-+]?\d+)?/, 'number.float'],
[/0[xX][0-9a-fA-F]+/, 'number.hex'],
[/\d+([eE][\-+]?\d+)?/, 'number'],
// keywords
[
/(#?[a-z]+)\b/,
{
cases: {
'@typeKeywords': 'type',
'@keywords': 'keyword',
'@constants': 'constant',
'@constructors': 'constructor',
'@operatorKeywords': 'operators',
'@default': 'identifier'
}
}
],
// built-in types
[
/\b([A-Z][a-zA-Z0-9]+\.Type)\b/,
{
cases: {
'@builtinTypes': 'type',
'@default': 'identifier'
}
}
],
// other built-ins
[
/\b([A-Z][a-zA-Z0-9]+\.[A-Z][a-zA-Z0-9]+)\b/,
{
cases: {
'@builtinFunctions': 'keyword.function',
'@builtinConstants': 'constant',
'@default': 'identifier'
}
}
],
// other identifiers
[/\b([a-zA-Z_][\w\.]*)\b/, 'identifier'],
{ include: '@whitespace' },
{ include: '@comments' },
{ include: '@strings' },
[/[{}()\[\]]/, '@brackets'],
[/([=\+<>\-\*&@\?\/!])|([<>]=)|(<>)|(=>)|(\.\.\.)|(\.\.)/, 'operators'],
[/[,;]/, 'delimiter']
],
whitespace: [[/\s+/, 'white']],
comments: [
['\\/\\*', 'comment', '@comment'],
['\\/\\/+.*', 'comment']
],
comment: [
['\\*\\/', 'comment', '@pop'],
['.', 'comment']
],
strings: [['"', 'string', '@string']],
string: [
['""', 'string.escape'],
['"', 'string', '@pop'],
['.', 'string']
]
}
}; | the_stack |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.