text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
* Comment list component * @file 评论列表组件 * @module app/components/comment-list * @author Surmon <https://github.com/surmon-china> */ import React, { Component, RefObject } from 'react' import { FlatList, StyleSheet, View, Alert, NativeSyntheticEvent, NativeScrollEvent, Linking } from 'react-native' import { observable, action, computed } from 'mobx' import { Observer } from 'mobx-react' import { observer } from 'mobx-react' import { boundMethod } from 'autobind-decorator' import { LANGUAGE_KEYS } from '@app/constants/language' import { IComment, IAuthor } from '@app/types/business' import { IHttpPaginate, IHttpResultPaginate } from '@app/types/http' import { webUrl, IS_IOS } from '@app/config' import { likeStore } from '@app/stores/like' import { optionStore } from '@app/stores/option' import { Iconfont } from '@app/components/common/iconfont' import { Text } from '@app/components/common/text' import { TouchableView } from '@app/components/common/touchable-view' import { AutoActivityIndicator } from '@app/components/common/activity-indicator' import { CommentItem } from './item' import fetch from '@app/services/fetch' import i18n from '@app/services/i18n' import colors from '@app/style/colors' import sizes from '@app/style/sizes' import fonts from '@app/style/fonts' import mixins from '@app/style/mixins' export type TCommentListElement = RefObject<FlatList<IComment>> type THttpResultPaginateComments = IHttpResultPaginate<IComment[]> interface ICommentProps { postId: number onScroll?(event: NativeSyntheticEvent<NativeScrollEvent>): void } @observer export class Comment extends Component<ICommentProps> { constructor(props: ICommentProps) { super(props) this.fetchComments() } private listElement: TCommentListElement = React.createRef() @boundMethod scrollToListTop() { const listElement = this.listElement.current if (this.commentListData.length) { listElement && listElement.scrollToIndex({ index: 0, viewOffset: 0 }) } } @observable.ref private isLoading: boolean = false @observable.ref private isSortByHot: boolean = false @observable.ref private pagination: IHttpPaginate | null = null @observable.shallow private comments: IComment[] = [] @computed private get commentListData(): IComment[] { return this.comments.slice() || [] } @computed private get isNoMoreData(): boolean { return !!this.pagination && this.pagination.current_page === this.pagination.total_page } @action private updateLoadingState(loading: boolean) { this.isLoading = loading } @action private updateResultData(resultData: THttpResultPaginateComments) { const { data, pagination } = resultData this.updateLoadingState(false) this.pagination = pagination if (pagination.current_page > 1) { this.comments.push(...data) } else { this.comments = data } } @boundMethod private fetchComments(page: number = 1): Promise<any> { this.updateLoadingState(true) const params = { sort: this.isSortByHot ? 2 : -1, post_id: this.props.postId, per_page: 66, page } return fetch.get<THttpResultPaginateComments>('/comment', params) .then(comment => { this.updateResultData(comment.result) return comment }) .catch(error => { this.updateLoadingState(false) console.warn('Fetch comment list error:', error) return Promise.reject(error) }) } private getCommentKey(comment: IComment, index?: number): string { return `index:${index}:sep:${comment.id}` } // 切换排序模式 @boundMethod private handleToggleSortType() { // 归顶 if (this.pagination && this.pagination.total > 0) { this.scrollToListTop() } // 修正参数 action(() => { this.isSortByHot = !this.isSortByHot })() // 重新请求数据 setTimeout(this.fetchComments, 266) } @boundMethod private handleLoadmoreArticle() { if (!this.isNoMoreData && !this.isLoading && this.pagination) { this.fetchComments(this.pagination.current_page + 1) } } @boundMethod private handlePressAuthor(author: IAuthor) { const url = author?.site if (url && url !== webUrl) { Linking.canOpenURL(url).then( canOpen => canOpen && Linking.openURL(url) ) } } @boundMethod private handleReplyComment(comment: IComment) { Alert.alert( optionStore.isEnLang ? 'More action on PC.' : '回复评论要去 Web 端操作' ) } @boundMethod private handleLikeComment(comment: IComment) { const comment_id = comment.id const doLike = () => { const targetCommentIndex = this.comments.findIndex(item => item.id === comment_id) likeStore.likeComment(comment_id) this.comments.splice(targetCommentIndex, 1, { ...comment, likes: comment.likes + 1 }) } fetch.patch<boolean>('/like/comment', { comment_id }) .then(doLike) .catch(error => { doLike() console.warn('Like comment error:', error) }) } // 渲染评论列表为空时的状态:无数据 @boundMethod private renderListEmptyView(): JSX.Element | null { const { styles } = obStyles const commonIconOptions = { name: 'tobottom', size: 19, color: colors.textSecondary } if (this.isLoading) { return null } return ( <Observer render={() => ( <View style={styles.centerContainer}> <Text style={styles.normalTitle}> {i18n.t(LANGUAGE_KEYS.NO_RESULT_RETRY)} </Text> <View style={{ marginTop: sizes.gap }}> <Iconfont {...commonIconOptions} /> <Iconfont {...commonIconOptions} style={{ marginTop: -14 }} /> </View> </View> )} /> ) } // 渲染列表脚部的三种状态:空、加载中、无更多、上拉加载 @boundMethod private renderListFooterView(): JSX.Element | null { const { styles } = obStyles if (!this.commentListData.length) { return null } if (this.isLoading) { return ( <Observer render={() => ( <View style={[styles.centerContainer, styles.loadmoreViewContainer]}> <AutoActivityIndicator style={{ marginRight: sizes.gap / 4 }} /> <Text style={styles.smallTitle}>{i18n.t(LANGUAGE_KEYS.LOADING)}</Text> </View> )} /> ) } if (this.isNoMoreData) { return ( <Observer render={() => ( <View style={[styles.centerContainer, styles.loadmoreViewContainer]}> <Text style={styles.smallTitle}>{i18n.t(LANGUAGE_KEYS.NO_MORE)}</Text> </View> )} /> ) } return ( <Observer render={() => ( <View style={[styles.centerContainer, styles.loadmoreViewContainer]}> <Iconfont name="next-bottom" color={colors.textSecondary} /> <Text style={[styles.smallTitle, { marginLeft: sizes.gap / 4 }]}> {i18n.t(LANGUAGE_KEYS.LOADMORE)} </Text> </View> )} /> ) } private renderToolBoxView(): JSX.Element { const { isLoading, pagination } = this const { styles } = obStyles return ( <View style={styles.toolBox}> {pagination && pagination.total ? ( <Text>{pagination.total} {i18n.t(LANGUAGE_KEYS.TOTAL)}</Text> ) : ( <Text>{i18n.t(isLoading ? LANGUAGE_KEYS.LOADING : LANGUAGE_KEYS.EMPTY)}</Text> )} <TouchableView accessibilityLabel="切换排序模式" disabled={isLoading} onPress={this.handleToggleSortType} > <Iconfont name={this.isSortByHot ? 'mood' : 'clock-stroke'} color={this.isSortByHot ? colors.primary : colors.textDefault} size={16} style={styles.toolSort} /> </TouchableView> </View> ) } render() { const { styles } = obStyles return ( <View style={styles.container}> {this.renderToolBoxView()} <FlatList style={styles.commentListView} data={this.commentListData} ref={this.listElement} // 首屏渲染多少个数据 initialNumToRender={16} // 列表为空时渲染 ListEmptyComponent={this.renderListEmptyView} // 加载更多时渲染 ListFooterComponent={this.renderListFooterView} // 当前列表 loading 状态 refreshing={this.isLoading} // 刷新 onRefresh={this.fetchComments} // 加载更多安全距离(相对于屏幕高度的比例) onEndReachedThreshold={IS_IOS ? 0.02 : 0.2} // 加载更多 onEndReached={this.handleLoadmoreArticle} // 手势滚动 onScroll={this.props.onScroll} // 唯一 ID keyExtractor={this.getCommentKey} // 单个主体 renderItem={({ item: comment, index }) => { return ( <Observer render={() => ( <CommentItem key={this.getCommentKey(comment, index)} darkTheme={optionStore.darkTheme} language={optionStore.language} comment={comment} liked={likeStore.comments.includes(comment.id)} onLike={this.handleLikeComment} onReply={this.handleReplyComment} onPressAuthor={this.handlePressAuthor} /> )} /> ) }} /> </View> ) } } const obStyles = observable({ get styles() { return StyleSheet.create({ container: { flex: 1, position: 'relative' }, toolBox: { ...mixins.rowCenter, justifyContent: 'space-between', height: sizes.gap * 2, paddingHorizontal: sizes.gap, borderColor: colors.border, borderTopWidth: sizes.borderWidth, borderBottomWidth: sizes.borderWidth, backgroundColor: colors.cardBackground }, toolSort: { color: colors.textDefault }, commentListView: { backgroundColor: colors.cardBackground }, centerContainer: { justifyContent: 'center', alignItems: 'center', padding: sizes.gap }, loadmoreViewContainer: { flexDirection: 'row', padding: sizes.goldenRatioGap }, normalTitle: { ...fonts.base, color: colors.textSecondary }, smallTitle: { ...fonts.small, color: colors.textSecondary } }) } })
the_stack
* Information about the input and output stack map frames of a basic block. * * @author Eric Bruneton */ import { Opcodes } from "./Opcodes"; import { ClassWriter } from "./ClassWriter"; import { MethodWriter } from "./MethodWriter"; import { Type } from "./Type"; import { Label } from "./Label"; import { Item } from "./Item"; import { assert } from "./utils"; export class Frame { static __static_initialized: boolean = false; static __static_initialize() { if (!Frame.__static_initialized) { Frame.__static_initialized = true; Frame.__static_initializer_0(); } } /** * Mask to get the dimension of a frame type. This dimension is a signed * integer between -8 and 7. */ static DIM: number = -268435456; /** * Constant to be added to a type to get a type with one more dimension. */ static ARRAY_OF: number = 268435456; /** * Constant to be added to a type to get a type with one less dimension. */ static ELEMENT_OF: number = -268435456; /** * Mask to get the kind of a frame type. * * @see #BASE * @see #LOCAL * @see #STACK */ static KIND: number = 251658240; /** * Flag used for LOCAL and STACK types. Indicates that if this type happens * to be a long or double type (during the computations of input frames), * then it must be set to TOP because the second word of this value has been * reused to store other data in the basic block. Hence the first word no * longer stores a valid long or double value. */ static TOP_IF_LONG_OR_DOUBLE: number = 8388608; /** * Mask to get the value of a frame type. */ static VALUE: number = 8388607; /** * Mask to get the kind of base types. */ static BASE_KIND: number = 267386880; /** * Mask to get the value of base types. */ static BASE_VALUE: number = 1048575; /** * Kind of the types that are not relative to an input stack map frame. */ static BASE: number = 16777216; /** * Base kind of the base reference types. The BASE_VALUE of such types is an * index into the type table. */ static OBJECT: number; public static OBJECT_$LI$(): number { Frame.__static_initialize(); if (Frame.OBJECT == null) { Frame.OBJECT = Frame.BASE | 7340032; } return Frame.OBJECT; }; /** * Base kind of the uninitialized base types. The BASE_VALUE of such types * in an index into the type table (the Item at that index contains both an * instruction offset and an internal class name). */ static UNINITIALIZED: number; public static UNINITIALIZED_$LI$(): number { Frame.__static_initialize(); if (Frame.UNINITIALIZED == null) { Frame.UNINITIALIZED = Frame.BASE | 8388608; } return Frame.UNINITIALIZED; }; /** * Kind of the types that are relative to the local variable types of an * input stack map frame. The value of such types is a local variable index. */ static LOCAL: number = 33554432; /** * Kind of the the types that are relative to the stack of an input stack * map frame. The value of such types is a position relatively to the top of * this stack. */ static STACK: number = 50331648; /** * The TOP type. This is a BASE type. */ static TOP: number; public static TOP_$LI$(): number { Frame.__static_initialize(); if (Frame.TOP == null) { Frame.TOP = Frame.BASE | 0; } return Frame.TOP; }; /** * The BOOLEAN type. This is a BASE type mainly used for array types. */ static BOOLEAN: number; public static BOOLEAN_$LI$(): number { Frame.__static_initialize(); if (Frame.BOOLEAN == null) { Frame.BOOLEAN = Frame.BASE | 9; } return Frame.BOOLEAN; }; /** * The BYTE type. This is a BASE type mainly used for array types. */ static BYTE: number; public static BYTE_$LI$(): number { Frame.__static_initialize(); if (Frame.BYTE == null) { Frame.BYTE = Frame.BASE | 10; } return Frame.BYTE; }; /** * The CHAR type. This is a BASE type mainly used for array types. */ static CHAR: number; public static CHAR_$LI$(): number { Frame.__static_initialize(); if (Frame.CHAR == null) { Frame.CHAR = Frame.BASE | 11; } return Frame.CHAR; }; /** * The SHORT type. This is a BASE type mainly used for array types. */ static SHORT: number; public static SHORT_$LI$(): number { Frame.__static_initialize(); if (Frame.SHORT == null) { Frame.SHORT = Frame.BASE | 12; } return Frame.SHORT; }; /** * The INTEGER type. This is a BASE type. */ static INTEGER: number; public static INTEGER_$LI$(): number { Frame.__static_initialize(); if (Frame.INTEGER == null) { Frame.INTEGER = Frame.BASE | 1; } return Frame.INTEGER; }; /** * The FLOAT type. This is a BASE type. */ static FLOAT: number; public static FLOAT_$LI$(): number { Frame.__static_initialize(); if (Frame.FLOAT == null) { Frame.FLOAT = Frame.BASE | 2; } return Frame.FLOAT; }; /** * The DOUBLE type. This is a BASE type. */ static DOUBLE: number; public static DOUBLE_$LI$(): number { Frame.__static_initialize(); if (Frame.DOUBLE == null) { Frame.DOUBLE = Frame.BASE | 3; } return Frame.DOUBLE; }; /** * The LONG type. This is a BASE type. */ static LONG: number; public static LONG_$LI$(): number { Frame.__static_initialize(); if (Frame.LONG == null) { Frame.LONG = Frame.BASE | 4; } return Frame.LONG; }; /** * The NULL type. This is a BASE type. */ static NULL: number; public static NULL_$LI$(): number { Frame.__static_initialize(); if (Frame.NULL == null) { Frame.NULL = Frame.BASE | 5; } return Frame.NULL; }; /** * The UNINITIALIZED_THIS type. This is a BASE type. */ static UNINITIALIZED_THIS: number; public static UNINITIALIZED_THIS_$LI$(): number { Frame.__static_initialize(); if (Frame.UNINITIALIZED_THIS == null) { Frame.UNINITIALIZED_THIS = Frame.BASE | 6; } return Frame.UNINITIALIZED_THIS; }; /** * The stack size variation corresponding to each JVM instruction. This * stack variation is equal to the size of the values produced by an * instruction, minus the size of the values consumed by this instruction. */ static SIZE: number[]; public static SIZE_$LI$(): number[] { Frame.__static_initialize(); return Frame.SIZE; }; static __static_initializer_0() { let i: number; let b: number[] = new Array(202); let s: string = "EFFFFFFFFGGFFFGGFFFEEFGFGFEEEEEEEEEEEEEEEEEEEEDEDEDDDDDCDCDEEEEEEEEEEEEEEEEEEEEBABABBBBDCFFFGGGEDCDCDCDCDCDCDCDCDCDCEEEEDDDDDDDCDCDCEFEFDDEEFFDEDEEEBDDBBDDDDDDCCCCCCCCEFEDDDCDCDEEEEEEEEEEFEEEEEEDDEEDDEE"; for (i = 0; i < b.length; ++i) { b[i] = (s.charAt(i)).charCodeAt(0) - ("E").charCodeAt(0); } Frame.SIZE = b; } /** * The label (i.e. basic block) to which these input and output stack map * frames correspond. */ owner: Label; /** * The input stack map frame locals. */ inputLocals: number[] = []; /** * The input stack map frame stack. */ inputStack: number[] = []; /** * The output stack map frame locals. */ private outputLocals: number[] = []; /** * The output stack map frame stack. */ private outputStack: number[] = []; /** * Relative size of the output stack. The exact semantics of this field * depends on the algorithm that is used. * * When only the maximum stack size is computed, this field is the size of * the output stack relatively to the top of the input stack. * * When the stack map frames are completely computed, this field is the * actual number of types in {@link #outputStack}. */ outputStackTop: number; /** * Number of types that are initialized in the basic block. * * @see #initializations */ private initializationCount: number; /** * The types that are initialized in the basic block. A constructor * invocation on an UNINITIALIZED or UNINITIALIZED_THIS type must replace * <i>every occurence</i> of this type in the local variables and in the * operand stack. This cannot be done during the first phase of the * algorithm since, during this phase, the local variables and the operand * stack are not completely computed. It is therefore necessary to store the * types on which constructors are invoked in the basic block, in order to * do this replacement during the second phase of the algorithm, where the * frames are fully computed. Note that this array can contain types that * are relative to input locals or to the input stack (see below for the * description of the algorithm). */ private initializations: number[] | null = null; /** * Sets this frame to the given value. * * @param cw * the ClassWriter to which this label belongs. * @param nLocal * the number of local variables. * @param local * the local variable types. Primitive types are represented by * {@link Opcodes#TOP}, {@link Opcodes#INTEGER}, * {@link Opcodes#FLOAT}, {@link Opcodes#LONG}, * {@link Opcodes#DOUBLE},{@link Opcodes#NULL} or * {@link Opcodes#UNINITIALIZED_THIS} (long and double are * represented by a single element). Reference types are * represented by String objects (representing internal names), * and uninitialized types by Label objects (this label * designates the NEW instruction that created this uninitialized * value). * @param nStack * the number of operand stack elements. * @param stack * the operand stack types (same format as the "local" array). */ public set(cw?: any, nLocal?: any, local?: any, nStack?: any, stack?: any): any { if (((cw != null && cw instanceof ClassWriter) || cw === null) && ((typeof nLocal === "number") || nLocal === null) && ((local != null && local instanceof Array) || local === null) && ((typeof nStack === "number") || nStack === null) && ((stack != null && stack instanceof Array) || stack === null)) { let __args = Array.prototype.slice.call(arguments); return <any>(() => { let i: number = Frame.convert(cw, nLocal, local, this.inputLocals); while ((i < local.length)) { this.inputLocals[i++] = Frame.TOP_$LI$(); }; let nStackTop: number = 0; for (let j: number = 0; j < nStack; ++j) { if (stack[j] === Opcodes.LONG || stack[j] === Opcodes.DOUBLE) { ++nStackTop; } } this.inputStack = new Array(nStack + nStackTop); Frame.convert(cw, nStack, stack, this.inputStack); this.outputStackTop = 0; this.initializationCount = 0; })(); } else if (((typeof cw === "number") || cw === null) && ((typeof nLocal === "number") || nLocal === null) && local === undefined && nStack === undefined && stack === undefined) { return <any>this.set$int$int(cw, nLocal); } else if (((cw != null && cw instanceof Frame) || cw === null) && nLocal === undefined && local === undefined && nStack === undefined && stack === undefined) { return <any>this.set$Frame(cw); } else { throw new Error("invalid overload"); } } /** * Converts types from the MethodWriter.visitFrame() format to the Frame * format. * * @param cw * the ClassWriter to which this label belongs. * @param nInput * the number of types to convert. * @param input * the types to convert. Primitive types are represented by * {@link Opcodes#TOP}, {@link Opcodes#INTEGER}, * {@link Opcodes#FLOAT}, {@link Opcodes#LONG}, * {@link Opcodes#DOUBLE},{@link Opcodes#NULL} or * {@link Opcodes#UNINITIALIZED_THIS} (long and double are * represented by a single element). Reference types are * represented by String objects (representing internal names), * and uninitialized types by Label objects (this label * designates the NEW instruction that created this uninitialized * value). * @param output * where to store the converted types. * @return the number of output elements. */ private static convert(cw: ClassWriter, nInput: number, input: any[], output: number[]): number { let i: number = 0; for (let j: number = 0; j < nInput; ++j) { if (typeof input[j] === "number") { output[i++] = Frame.BASE | /* intValue */((<number>input[j]) | 0); if (input[j] === Opcodes.LONG || input[j] === Opcodes.DOUBLE) { output[i++] = Frame.TOP_$LI$(); } } else if (typeof input[j] === "string") { output[i++] = Frame.type(cw, Type.getObjectType(<string>input[j]).getDescriptor()); } else { output[i++] = Frame.UNINITIALIZED_$LI$() | cw.addUninitializedType("", (<Label>input[j]).position); } } return i; } /** * Sets this frame to the value of the given frame. WARNING: after this * method is called the two frames share the same data structures. It is * recommended to discard the given frame f to avoid unexpected side * effects. * * @param f * The new frame value. */ set$Frame(f: Frame) { this.inputLocals = f.inputLocals; this.inputStack = f.inputStack; this.outputLocals = f.outputLocals; this.outputStack = f.outputStack; this.outputStackTop = f.outputStackTop; this.initializationCount = f.initializationCount; this.initializations = f.initializations; } /** * Returns the output frame local variable type at the given index. * * @param local * the index of the local that must be returned. * @return the output frame local variable type at the given index. */ private get(local: number): number { if (this.outputLocals == null || local >= this.outputLocals.length) { return Frame.LOCAL | local; } else { let type: number = this.outputLocals[local]; if (type === 0) { type = this.outputLocals[local] = Frame.LOCAL | local; } return type; } } /** * Sets the output frame local variable type at the given index. * * @param local * the index of the local that must be set. * @param type * the value of the local that must be set. */ private set$int$int(local: number, type: number) { if (this.outputLocals == null) { this.outputLocals = new Array(10); } let n: number = this.outputLocals.length; if (local >= n) { let t: number[] = new Array(Math.max(local + 1, 2 * n)); for (let i = 0; i < n; i++) { t[i] = this.outputLocals[i]; } // java.lang.System.arraycopy(this.outputLocals, 0, t, 0, n); this.outputLocals = t; } this.outputLocals[local] = type; } /** * Pushes a new type onto the output frame stack. * * @param type * the type that must be pushed. */ private push$int(type: number) { if (this.outputStack == null) { this.outputStack = new Array(10); } let n: number = this.outputStack.length; if (this.outputStackTop >= n) { let t: number[] = new Array(Math.max(this.outputStackTop + 1, 2 * n)); for (let i = 0; i < n; i++) { t[i] = this.outputStack[i]; } // java.lang.System.arraycopy(this.outputStack, 0, t, 0, n); this.outputStack = t; } this.outputStack[this.outputStackTop++] = type; assert(this.owner); let top: number = this.owner.inputStackTop + this.outputStackTop; if (top > this.owner.outputStackMax) { this.owner.outputStackMax = top; } } /** * Pushes a new type onto the output frame stack. * * @param cw * the ClassWriter to which this label belongs. * @param desc * the descriptor of the type to be pushed. Can also be a method * descriptor (in this case this method pushes its return type * onto the output frame stack). */ public push(cw?: any, desc?: any): any { if (((cw != null && cw instanceof ClassWriter) || cw === null) && ((typeof desc === "string") || desc === null)) { let __args = Array.prototype.slice.call(arguments); return <any>(() => { let type: number = Frame.type(cw, desc); if (type !== 0) { this.push(type); if (type === Frame.LONG_$LI$() || type === Frame.DOUBLE_$LI$()) { this.push(Frame.TOP_$LI$()); } } })(); } else if (((typeof cw === "number") || cw === null) && desc === undefined) { return <any>this.push$int(cw); } else { throw new Error("invalid overload"); } } /** * Returns the int encoding of the given type. * * @param cw * the ClassWriter to which this label belongs. * @param desc * a type descriptor. * @return the int encoding of the given type. */ private static type(cw: ClassWriter, desc: string): number { let t: string; let index: number = desc.charAt(0) === "(" ? desc.indexOf(")") + 1 : 0; switch ((desc.charAt(index))) { case "V": return 0; case "Z": case "C": case "B": case "S": case "I": return Frame.INTEGER_$LI$(); case "F": return Frame.FLOAT_$LI$(); case "J": return Frame.LONG_$LI$(); case "D": return Frame.DOUBLE_$LI$(); case "L": t = desc.substring(index + 1, desc.length - 1); return Frame.OBJECT_$LI$() | cw.addType(t); default: let data: number; let dims: number = index + 1; while ((desc.charAt(dims) === "[")) { ++dims; }; switch ((desc.charAt(dims))) { case "Z": data = Frame.BOOLEAN_$LI$(); break; case "C": data = Frame.CHAR_$LI$(); break; case "B": data = Frame.BYTE_$LI$(); break; case "S": data = Frame.SHORT_$LI$(); break; case "I": data = Frame.INTEGER_$LI$(); break; case "F": data = Frame.FLOAT_$LI$(); break; case "J": data = Frame.LONG_$LI$(); break; case "D": data = Frame.DOUBLE_$LI$(); break; default: t = desc.substring(dims + 1, desc.length - 1); data = Frame.OBJECT_$LI$() | cw.addType(t); } return (dims - index) << 28 | data; } } /** * Pops a type from the output frame stack and returns its value. * * @return the type that has been popped from the output frame stack. */ private pop$(): number { if (this.outputStackTop > 0) { return this.outputStack[--this.outputStackTop]; } else { return Frame.STACK | -(--this.owner.inputStackTop); } } /** * Pops the given number of types from the output frame stack. * * @param elements * the number of types that must be popped. */ private pop$int(elements: number) { if (this.outputStackTop >= elements) { this.outputStackTop -= elements; } else { this.owner.inputStackTop -= elements - this.outputStackTop; this.outputStackTop = 0; } } /** * Pops a type from the output frame stack. * * @param desc * the descriptor of the type to be popped. Can also be a method * descriptor (in this case this method pops the types * corresponding to the method arguments). */ public pop(desc?: string | number): any { if (((typeof desc === "string") || desc === null)) { let __args = Array.prototype.slice.call(arguments); return <any>(() => { let c: string = desc.charAt(0); if (c === "(") { this.pop((Type.getArgumentsAndReturnSizes(desc) >> 2) - 1); } else if (c === "J" || c === "D") { this.pop(2); } else { this.pop(1); } })(); } else if (((typeof desc === "number") || desc === null)) { return this.pop$int(desc); } else if (desc === undefined) { return this.pop$(); } else { throw new Error("invalid overload"); } } /** * Adds a new type to the list of types on which a constructor is invoked in * the basic block. * * @param var * a type on a which a constructor is invoked. */ private init$int(__var: number) { if (this.initializations == null) { this.initializations = new Array(2); } let n: number = this.initializations.length; if (this.initializationCount >= n) { let t: number[] = new Array(Math.max(this.initializationCount + 1, 2 * n)); for (let i = 0; i < n; i++) { t[i] = this.initializations[i]; } // java.lang.System.arraycopy(this.initializations, 0, t, 0, n); this.initializations = t; } this.initializations[this.initializationCount++] = __var; } /** * Replaces the given type with the appropriate type if it is one of the * types on which a constructor is invoked in the basic block. * * @param cw * the ClassWriter to which this label belongs. * @param t * a type * @return t or, if t is one of the types on which a constructor is invoked * in the basic block, the type corresponding to this constructor. */ public init(cw?: any, t?: any): any { if (((cw != null && cw instanceof ClassWriter) || cw === null) && ((typeof t === "number") || t === null)) { let __args = Array.prototype.slice.call(arguments); return (() => { let s: number; if (t === Frame.UNINITIALIZED_THIS_$LI$()) { s = Frame.OBJECT_$LI$() | cw.addType(cw.thisName); } else if ((t & (Frame.DIM | Frame.BASE_KIND)) === Frame.UNINITIALIZED_$LI$()) { let type: string = cw.typeTable[t & Frame.BASE_VALUE].strVal1; s = Frame.OBJECT_$LI$() | cw.addType(type); } else { return t; } for (let j: number = 0; j < this.initializationCount; ++j) { let u: number = this.initializations![j]; let dim: number = u & Frame.DIM; let kind: number = u & Frame.KIND; if (kind === Frame.LOCAL) { u = dim + this.inputLocals[u & Frame.VALUE]; } else if (kind === Frame.STACK) { u = dim + this.inputStack[this.inputStack.length - (u & Frame.VALUE)]; } if (t === u) { return s; } } return t; })(); } else if (((typeof cw === "number") || cw === null) && t === undefined) { return <any>this.init$int(cw); } else { throw new Error("invalid overload"); } } /** * Initializes the input frame of the first basic block from the method * descriptor. * * @param cw * the ClassWriter to which this label belongs. * @param access * the access flags of the method to which this label belongs. * @param args * the formal parameter types of this method. * @param maxLocals * the maximum number of local variables of this method. */ initInputFrame(cw: ClassWriter, access: number, args: Type[], maxLocals: number) { this.inputLocals = new Array(maxLocals); this.inputStack = new Array(0); let i: number = 0; if ((access & Opcodes.ACC_STATIC) === 0) { if ((access & MethodWriter.ACC_CONSTRUCTOR) === 0) { this.inputLocals[i++] = Frame.OBJECT_$LI$() | cw.addType(cw.thisName); } else { this.inputLocals[i++] = Frame.UNINITIALIZED_THIS_$LI$(); } } for (let j: number = 0; j < args.length; ++j) { let t: number = Frame.type(cw, args[j].getDescriptor()); this.inputLocals[i++] = t; if (t === Frame.LONG_$LI$() || t === Frame.DOUBLE_$LI$()) { this.inputLocals[i++] = Frame.TOP_$LI$(); } } while ((i < maxLocals)) { this.inputLocals[i++] = Frame.TOP_$LI$(); }; } /** * Simulates the action of the given instruction on the output stack frame. * * @param opcode * the opcode of the instruction. * @param arg * the operand of the instruction, if any. * @param cw * the class writer to which this label belongs. * @param item * the operand of the instructions, if any. */ execute(opcode: number, arg: number, cw: ClassWriter | null, item: Item | null) { let t1: number; let t2: number; let t3: number; let t4: number; switch ((opcode)) { case Opcodes.NOP: case Opcodes.INEG: case Opcodes.LNEG: case Opcodes.FNEG: case Opcodes.DNEG: case Opcodes.I2B: case Opcodes.I2C: case Opcodes.I2S: case Opcodes.GOTO: case Opcodes.RETURN: break; case Opcodes.ACONST_NULL: this.push(Frame.NULL_$LI$()); break; case Opcodes.ICONST_M1: case Opcodes.ICONST_0: case Opcodes.ICONST_1: case Opcodes.ICONST_2: case Opcodes.ICONST_3: case Opcodes.ICONST_4: case Opcodes.ICONST_5: case Opcodes.BIPUSH: case Opcodes.SIPUSH: case Opcodes.ILOAD: this.push(Frame.INTEGER_$LI$()); break; case Opcodes.LCONST_0: case Opcodes.LCONST_1: case Opcodes.LLOAD: this.push(Frame.LONG_$LI$()); this.push(Frame.TOP_$LI$()); break; case Opcodes.FCONST_0: case Opcodes.FCONST_1: case Opcodes.FCONST_2: case Opcodes.FLOAD: this.push(Frame.FLOAT_$LI$()); break; case Opcodes.DCONST_0: case Opcodes.DCONST_1: case Opcodes.DLOAD: this.push(Frame.DOUBLE_$LI$()); this.push(Frame.TOP_$LI$()); break; case Opcodes.LDC: assert(cw); assert(item); switch ((item.type)) { case ClassWriter.INT: this.push(Frame.INTEGER_$LI$()); break; case ClassWriter.LONG: this.push(Frame.LONG_$LI$()); this.push(Frame.TOP_$LI$()); break; case ClassWriter.FLOAT: this.push(Frame.FLOAT_$LI$()); break; case ClassWriter.DOUBLE: this.push(Frame.DOUBLE_$LI$()); this.push(Frame.TOP_$LI$()); break; case ClassWriter.CLASS: this.push(Frame.OBJECT_$LI$() | cw.addType("java/lang/Class")); break; case ClassWriter.STR: this.push(Frame.OBJECT_$LI$() | cw.addType("java/lang/String")); break; case ClassWriter.MTYPE: this.push(Frame.OBJECT_$LI$() | cw.addType("java/lang/invoke/MethodType")); break; default: this.push(Frame.OBJECT_$LI$() | cw.addType("java/lang/invoke/MethodHandle")); } break; case Opcodes.ALOAD: this.push(this.get(arg)); break; case Opcodes.IALOAD: case Opcodes.BALOAD: case Opcodes.CALOAD: case Opcodes.SALOAD: this.pop(2); this.push(Frame.INTEGER_$LI$()); break; case Opcodes.LALOAD: case Opcodes.D2L: this.pop(2); this.push(Frame.LONG_$LI$()); this.push(Frame.TOP_$LI$()); break; case Opcodes.FALOAD: this.pop(2); this.push(Frame.FLOAT_$LI$()); break; case Opcodes.DALOAD: case Opcodes.L2D: this.pop(2); this.push(Frame.DOUBLE_$LI$()); this.push(Frame.TOP_$LI$()); break; case Opcodes.AALOAD: this.pop(1); t1 = this.pop(); this.push(Frame.ELEMENT_OF + t1); break; case Opcodes.ISTORE: case Opcodes.FSTORE: case Opcodes.ASTORE: t1 = this.pop(); this.set(arg, t1); if (arg > 0) { t2 = this.get(arg - 1); if (t2 === Frame.LONG_$LI$() || t2 === Frame.DOUBLE_$LI$()) { this.set(arg - 1, Frame.TOP_$LI$()); } else if ((t2 & Frame.KIND) !== Frame.BASE) { this.set(arg - 1, t2 | Frame.TOP_IF_LONG_OR_DOUBLE); } } break; case Opcodes.LSTORE: case Opcodes.DSTORE: this.pop(1); t1 = this.pop(); this.set(arg, t1); this.set(arg + 1, Frame.TOP_$LI$()); if (arg > 0) { t2 = this.get(arg - 1); if (t2 === Frame.LONG_$LI$() || t2 === Frame.DOUBLE_$LI$()) { this.set(arg - 1, Frame.TOP_$LI$()); } else if ((t2 & Frame.KIND) !== Frame.BASE) { this.set(arg - 1, t2 | Frame.TOP_IF_LONG_OR_DOUBLE); } } break; case Opcodes.IASTORE: case Opcodes.BASTORE: case Opcodes.CASTORE: case Opcodes.SASTORE: case Opcodes.FASTORE: case Opcodes.AASTORE: this.pop(3); break; case Opcodes.LASTORE: case Opcodes.DASTORE: this.pop(4); break; case Opcodes.POP: case Opcodes.IFEQ: case Opcodes.IFNE: case Opcodes.IFLT: case Opcodes.IFGE: case Opcodes.IFGT: case Opcodes.IFLE: case Opcodes.IRETURN: case Opcodes.FRETURN: case Opcodes.ARETURN: case Opcodes.TABLESWITCH: case Opcodes.LOOKUPSWITCH: case Opcodes.ATHROW: case Opcodes.MONITORENTER: case Opcodes.MONITOREXIT: case Opcodes.IFNULL: case Opcodes.IFNONNULL: this.pop(1); break; case Opcodes.POP2: case Opcodes.IF_ICMPEQ: case Opcodes.IF_ICMPNE: case Opcodes.IF_ICMPLT: case Opcodes.IF_ICMPGE: case Opcodes.IF_ICMPGT: case Opcodes.IF_ICMPLE: case Opcodes.IF_ACMPEQ: case Opcodes.IF_ACMPNE: case Opcodes.LRETURN: case Opcodes.DRETURN: this.pop(2); break; case Opcodes.DUP: t1 = this.pop(); this.push(t1); this.push(t1); break; case Opcodes.DUP_X1: t1 = this.pop(); t2 = this.pop(); this.push(t1); this.push(t2); this.push(t1); break; case Opcodes.DUP_X2: t1 = this.pop(); t2 = this.pop(); t3 = this.pop(); this.push(t1); this.push(t3); this.push(t2); this.push(t1); break; case Opcodes.DUP2: t1 = this.pop(); t2 = this.pop(); this.push(t2); this.push(t1); this.push(t2); this.push(t1); break; case Opcodes.DUP2_X1: t1 = this.pop(); t2 = this.pop(); t3 = this.pop(); this.push(t2); this.push(t1); this.push(t3); this.push(t2); this.push(t1); break; case Opcodes.DUP2_X2: t1 = this.pop(); t2 = this.pop(); t3 = this.pop(); t4 = this.pop(); this.push(t2); this.push(t1); this.push(t4); this.push(t3); this.push(t2); this.push(t1); break; case Opcodes.SWAP: t1 = this.pop(); t2 = this.pop(); this.push(t1); this.push(t2); break; case Opcodes.IADD: case Opcodes.ISUB: case Opcodes.IMUL: case Opcodes.IDIV: case Opcodes.IREM: case Opcodes.IAND: case Opcodes.IOR: case Opcodes.IXOR: case Opcodes.ISHL: case Opcodes.ISHR: case Opcodes.IUSHR: case Opcodes.L2I: case Opcodes.D2I: case Opcodes.FCMPL: case Opcodes.FCMPG: this.pop(2); this.push(Frame.INTEGER_$LI$()); break; case Opcodes.LADD: case Opcodes.LSUB: case Opcodes.LMUL: case Opcodes.LDIV: case Opcodes.LREM: case Opcodes.LAND: case Opcodes.LOR: case Opcodes.LXOR: this.pop(4); this.push(Frame.LONG_$LI$()); this.push(Frame.TOP_$LI$()); break; case Opcodes.FADD: case Opcodes.FSUB: case Opcodes.FMUL: case Opcodes.FDIV: case Opcodes.FREM: case Opcodes.L2F: case Opcodes.D2F: this.pop(2); this.push(Frame.FLOAT_$LI$()); break; case Opcodes.DADD: case Opcodes.DSUB: case Opcodes.DMUL: case Opcodes.DDIV: case Opcodes.DREM: this.pop(4); this.push(Frame.DOUBLE_$LI$()); this.push(Frame.TOP_$LI$()); break; case Opcodes.LSHL: case Opcodes.LSHR: case Opcodes.LUSHR: this.pop(3); this.push(Frame.LONG_$LI$()); this.push(Frame.TOP_$LI$()); break; case Opcodes.IINC: this.set(arg, Frame.INTEGER_$LI$()); break; case Opcodes.I2L: case Opcodes.F2L: this.pop(1); this.push(Frame.LONG_$LI$()); this.push(Frame.TOP_$LI$()); break; case Opcodes.I2F: this.pop(1); this.push(Frame.FLOAT_$LI$()); break; case Opcodes.I2D: case Opcodes.F2D: this.pop(1); this.push(Frame.DOUBLE_$LI$()); this.push(Frame.TOP_$LI$()); break; case Opcodes.F2I: case Opcodes.ARRAYLENGTH: case Opcodes.INSTANCEOF: this.pop(1); this.push(Frame.INTEGER_$LI$()); break; case Opcodes.LCMP: case Opcodes.DCMPL: case Opcodes.DCMPG: this.pop(4); this.push(Frame.INTEGER_$LI$()); break; case Opcodes.JSR: case Opcodes.RET: throw new Error("JSR/RET are not supported with computeFrames option"); case Opcodes.GETSTATIC: assert(item); this.push(cw, item.strVal3); break; case Opcodes.PUTSTATIC: assert(item); this.pop(item.strVal3); break; case Opcodes.GETFIELD: assert(item); this.pop(1); this.push(cw, item.strVal3); break; case Opcodes.PUTFIELD: assert(item); this.pop(item.strVal3); this.pop(); break; case Opcodes.INVOKEVIRTUAL: case Opcodes.INVOKESPECIAL: case Opcodes.INVOKESTATIC: case Opcodes.INVOKEINTERFACE: assert(item); this.pop(item.strVal3); if (opcode !== Opcodes.INVOKESTATIC) { t1 = this.pop(); if (opcode === Opcodes.INVOKESPECIAL && item.strVal2.charAt(0) === "<") { this.init(t1); } } this.push(cw, item.strVal3); break; case Opcodes.INVOKEDYNAMIC: assert(item); this.pop(item.strVal2); this.push(cw, item.strVal2); break; case Opcodes.NEW: assert(item); assert(cw); this.push(Frame.UNINITIALIZED_$LI$() | cw.addUninitializedType(item.strVal1, arg)); break; case Opcodes.NEWARRAY: this.pop(); switch ((arg)) { case Opcodes.T_BOOLEAN: this.push(Frame.ARRAY_OF | Frame.BOOLEAN_$LI$()); break; case Opcodes.T_CHAR: this.push(Frame.ARRAY_OF | Frame.CHAR_$LI$()); break; case Opcodes.T_BYTE: this.push(Frame.ARRAY_OF | Frame.BYTE_$LI$()); break; case Opcodes.T_SHORT: this.push(Frame.ARRAY_OF | Frame.SHORT_$LI$()); break; case Opcodes.T_INT: this.push(Frame.ARRAY_OF | Frame.INTEGER_$LI$()); break; case Opcodes.T_FLOAT: this.push(Frame.ARRAY_OF | Frame.FLOAT_$LI$()); break; case Opcodes.T_DOUBLE: this.push(Frame.ARRAY_OF | Frame.DOUBLE_$LI$()); break; default: this.push(Frame.ARRAY_OF | Frame.LONG_$LI$()); break; } break; case Opcodes.ANEWARRAY: assert(item); assert(cw); let s: string = item.strVal1; this.pop(); if (s.charAt(0) === "[") { this.push(cw, "[" + s); } else { this.push(Frame.ARRAY_OF | Frame.OBJECT_$LI$() | cw.addType(s)); } break; case Opcodes.CHECKCAST: assert(item); s = item.strVal1; this.pop(); if (s.charAt(0) === "[") { this.push(cw, s); } else { assert(cw); this.push(Frame.OBJECT_$LI$() | cw.addType(s)); } break; default: assert(item); this.pop(arg); this.push(cw, item.strVal1); break; } } /** * Merges the input frame of the given basic block with the input and output * frames of this basic block. Returns <tt>true</tt> if the input frame of * the given label has been changed by this operation. * * @param cw * the ClassWriter to which this label belongs. * @param frame * the basic block whose input frame must be updated. * @param edge * the kind of the {@link Edge} between this label and 'label'. * See {@link Edge#info}. * @return <tt>true</tt> if the input frame of the given label has been * changed by this operation. */ merge(cw: ClassWriter, frame: Frame, edge: number): boolean { let changed: boolean = false; let i: number; let s: number; let dim: number; let kind: number; let t: number; let nLocal: number = this.inputLocals.length; let nStack: number = this.inputStack.length; if (frame.inputLocals == null) { frame.inputLocals = new Array(nLocal); changed = true; } for (i = 0; i < nLocal; ++i) { if (this.outputLocals != null && i < this.outputLocals.length) { s = this.outputLocals[i]; if (s === 0) { t = this.inputLocals[i]; } else { dim = s & Frame.DIM; kind = s & Frame.KIND; if (kind === Frame.BASE) { t = s; } else { if (kind === Frame.LOCAL) { t = dim + this.inputLocals[s & Frame.VALUE]; } else { t = dim + this.inputStack[nStack - (s & Frame.VALUE)]; } if ((s & Frame.TOP_IF_LONG_OR_DOUBLE) !== 0 && (t === Frame.LONG_$LI$() || t === Frame.DOUBLE_$LI$())) { t = Frame.TOP_$LI$(); } } } } else { t = this.inputLocals[i]; } if (this.initializations != null) { t = this.init(cw, t); } changed = changed || Frame.merge(cw, t, frame.inputLocals, i); } if (edge > 0) { for (i = 0; i < nLocal; ++i) { t = this.inputLocals[i]; changed = changed || Frame.merge(cw, t, frame.inputLocals, i); } if (frame.inputStack == null) { frame.inputStack = new Array(1); changed = true; } changed = changed || Frame.merge(cw, edge, frame.inputStack, 0); return changed; } let nInputStack: number = this.inputStack.length + this.owner.inputStackTop; if (frame.inputStack == null) { frame.inputStack = new Array(nInputStack + this.outputStackTop); changed = true; } for (i = 0; i < nInputStack; ++i) { t = this.inputStack[i]; if (this.initializations != null) { t = this.init(cw, t); } changed = changed || Frame.merge(cw, t, frame.inputStack, i); } for (i = 0; i < this.outputStackTop; ++i) { s = this.outputStack[i]; dim = s & Frame.DIM; kind = s & Frame.KIND; if (kind === Frame.BASE) { t = s; } else { if (kind === Frame.LOCAL) { t = dim + this.inputLocals[s & Frame.VALUE]; } else { t = dim + this.inputStack[nStack - (s & Frame.VALUE)]; } if ((s & Frame.TOP_IF_LONG_OR_DOUBLE) !== 0 && (t === Frame.LONG_$LI$() || t === Frame.DOUBLE_$LI$())) { t = Frame.TOP_$LI$(); } } if (this.initializations != null) { t = this.init(cw, t); } changed = changed || Frame.merge(cw, t, frame.inputStack, nInputStack + i); } return changed; } /** * Merges the type at the given index in the given type array with the given * type. Returns <tt>true</tt> if the type array has been modified by this * operation. * * @param cw * the ClassWriter to which this label belongs. * @param t * the type with which the type array element must be merged. * @param types * an array of types. * @param index * the index of the type that must be merged in 'types'. * @return <tt>true</tt> if the type array has been modified by this * operation. */ private static merge(cw: ClassWriter, t: number, types: number[], index: number): boolean { let u: number = types[index]; if (u === t) { return false; } if ((t & ~Frame.DIM) === Frame.NULL_$LI$()) { if (u === Frame.NULL_$LI$()) { return false; } t = Frame.NULL_$LI$(); } if (u === 0) { types[index] = t; return true; } let v: number; if ((u & Frame.BASE_KIND) === Frame.OBJECT_$LI$() || (u & Frame.DIM) !== 0) { if (t === Frame.NULL_$LI$()) { return false; } else if ((t & (Frame.DIM | Frame.BASE_KIND)) === (u & (Frame.DIM | Frame.BASE_KIND))) { if ((u & Frame.BASE_KIND) === Frame.OBJECT_$LI$()) { v = (t & Frame.DIM) | Frame.OBJECT_$LI$() | cw.getMergedType(t & Frame.BASE_VALUE, u & Frame.BASE_VALUE); } else { let vdim: number = Frame.ELEMENT_OF + (u & Frame.DIM); v = vdim | Frame.OBJECT_$LI$() | cw.addType("java/lang/Object"); } } else if ((t & Frame.BASE_KIND) === Frame.OBJECT_$LI$() || (t & Frame.DIM) !== 0) { let tdim: number = (((t & Frame.DIM) === 0 || (t & Frame.BASE_KIND) === Frame.OBJECT_$LI$()) ? 0 : Frame.ELEMENT_OF) + (t & Frame.DIM); let udim: number = (((u & Frame.DIM) === 0 || (u & Frame.BASE_KIND) === Frame.OBJECT_$LI$()) ? 0 : Frame.ELEMENT_OF) + (u & Frame.DIM); v = Math.min(tdim, udim) | Frame.OBJECT_$LI$() | cw.addType("java/lang/Object"); } else { v = Frame.TOP_$LI$(); } } else if (u === Frame.NULL_$LI$()) { v = (t & Frame.BASE_KIND) === Frame.OBJECT_$LI$() || (t & Frame.DIM) !== 0 ? t : Frame.TOP_$LI$(); } else { v = Frame.TOP_$LI$(); } if (u !== v) { types[index] = v; return true; } return false; } constructor(owner: Label) { this.outputStackTop = 0; this.initializationCount = 0; this.owner = owner; } } Frame.SIZE_$LI$(); Frame.UNINITIALIZED_THIS_$LI$(); Frame.NULL_$LI$(); Frame.LONG_$LI$(); Frame.DOUBLE_$LI$(); Frame.FLOAT_$LI$(); Frame.INTEGER_$LI$(); Frame.SHORT_$LI$(); Frame.CHAR_$LI$(); Frame.BYTE_$LI$(); Frame.BOOLEAN_$LI$(); Frame.TOP_$LI$(); Frame.UNINITIALIZED_$LI$(); Frame.OBJECT_$LI$(); Frame.__static_initialize();
the_stack
import { EventEmitter } from "events"; import { defaultFluidObjectRequestHandler } from "@fluidframework/aqueduct"; import { IFluidLoadable, IFluidRouter, IRequest, IResponse, IFluidHandle, } from "@fluidframework/core-interfaces"; import { FluidObjectHandle, mixinRequestHandler, } from "@fluidframework/datastore"; import { ISharedMap, SharedMap } from "@fluidframework/map"; import { MergeTreeDeltaType, TextSegment, ReferenceType, reservedTileLabelsKey, Marker, } from "@fluidframework/merge-tree"; import { IFluidDataStoreContext, IFluidDataStoreFactory } from "@fluidframework/runtime-definitions"; import { IFluidDataStoreRuntime } from "@fluidframework/datastore-definitions"; import { SharedString, SequenceDeltaEvent } from "@fluidframework/sequence"; import { IFluidHTMLOptions, IFluidHTMLView } from "@fluidframework/view-interfaces"; import CodeMirror from "codemirror"; /* eslint-disable @typescript-eslint/no-require-imports, import/no-internal-modules, import/no-unassigned-import */ require("codemirror/lib/codemirror.css"); require("./style.css"); require("codemirror/mode/javascript/javascript.js"); /* eslint-enable @typescript-eslint/no-require-imports, import/no-internal-modules, import/no-unassigned-import */ import { CodeMirrorPresenceManager } from "./presence"; class CodemirrorView implements IFluidHTMLView { private textArea: HTMLTextAreaElement | undefined; private codeMirror: CodeMirror.EditorFromTextArea | undefined; private presenceManager: CodeMirrorPresenceManager | undefined; // TODO would be nice to be able to distinguish local edits across different uses of a sequence so that when // bridging to another model we know which one to update private updatingSequence: boolean = false; private updatingCodeMirror: boolean = false; private sequenceDeltaCb: any; public get IFluidHTMLView() { return this; } constructor(private readonly text: SharedString, private readonly runtime: IFluidDataStoreRuntime) { } public remove(): void { // Text area being removed will dispose of CM // https://stackoverflow.com/questions/18828658/how-to-kill-a-codemirror-instance if (this.sequenceDeltaCb) { this.text.removeListener("sequenceDelta", this.sequenceDeltaCb); this.sequenceDeltaCb = undefined; } if (this.presenceManager) { this.presenceManager.removeAllListeners(); this.presenceManager = undefined; } } public render(elm: HTMLElement, options?: IFluidHTMLOptions): void { // Create base textarea if (!this.textArea) { this.textArea = document.createElement("textarea"); } // Reparent if needed if (this.textArea.parentElement !== elm) { this.textArea.remove(); elm.appendChild(this.textArea); } if (!this.codeMirror) { this.setupEditor(); } } private setupEditor() { this.codeMirror = CodeMirror.fromTextArea( // eslint-disable-next-line @typescript-eslint/no-non-null-assertion this.textArea!, { lineNumbers: true, mode: "text/typescript", viewportMargin: Infinity, }); this.presenceManager = new CodeMirrorPresenceManager(this.codeMirror, this.runtime); const { parallelText } = this.text.getTextAndMarkers("pg"); const text = parallelText.join("\n"); this.codeMirror.setValue(text); this.codeMirror.on( "beforeChange", (instance, changeObj) => { // Ignore this callback if it is a local change if (this.updatingSequence) { return; } // Mark that our editor is making the edit this.updatingCodeMirror = true; const doc = instance.getDoc(); // We add in line to adjust for paragraph markers let from = doc.indexFromPos(changeObj.from); const to = doc.indexFromPos(changeObj.to); if (from !== to) { this.text.removeText(from, to); } const changeText = changeObj.text; changeText.forEach((value, index) => { // Insert the updated text if (value) { this.text.insertText(from, value); from += value.length; } // Add in a paragraph marker if this is a multi-line update if (index !== changeText.length - 1) { this.text.insertMarker( from, ReferenceType.Tile, { [reservedTileLabelsKey]: ["pg"] }); from++; } }); this.updatingCodeMirror = false; }); this.sequenceDeltaCb = (ev: SequenceDeltaEvent) => { // If in the middle of making an editor change to our instance we can skip this update if (this.updatingCodeMirror) { return; } // Mark that we are making a local edit so that when "beforeChange" fires we don't attempt // to submit new ops this.updatingSequence = true; // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const doc = this.codeMirror!.getDoc(); for (const range of ev.ranges) { const segment = range.segment; if (range.operation === MergeTreeDeltaType.INSERT) { if (TextSegment.is(segment)) { doc.replaceRange( segment.text, doc.posFromIndex(range.position)); } else if (Marker.is(segment)) { doc.replaceRange( "\n", doc.posFromIndex(range.position)); } } else if (range.operation === MergeTreeDeltaType.REMOVE) { if (TextSegment.is(segment)) { const textSegment = range.segment as TextSegment; doc.replaceRange( "", doc.posFromIndex(range.position), doc.posFromIndex(range.position + textSegment.text.length)); } else if (Marker.is(segment)) { doc.replaceRange( "", doc.posFromIndex(range.position), doc.posFromIndex(range.position + 1)); } } } // And then flip the bit back since we are done making codemirror changes this.updatingSequence = false; }; this.text.on("sequenceDelta", this.sequenceDeltaCb); } } /** * CodeMirrorComponent builds a Fluid collaborative code editor on top of the open source code editor CodeMirror. * It has its own implementation of IFluidLoadable and does not extend PureDataObject / DataObject. This is * done intentionally to serve as an example of exposing the URL and handle via IFluidLoadable. */ export class CodeMirrorComponent extends EventEmitter implements IFluidLoadable, IFluidRouter, IFluidHTMLView { public static async load(runtime: IFluidDataStoreRuntime, context: IFluidDataStoreContext, existing: boolean) { const collection = new CodeMirrorComponent(runtime, context); await collection.initialize(existing); return collection; } public get IFluidLoadable() { return this; } public get IFluidRouter() { return this; } public get IFluidHTMLView() { return this; } public get handle(): IFluidHandle<this> { return this.innerHandle; } private text: SharedString | undefined; private root: ISharedMap | undefined; private readonly innerHandle: IFluidHandle<this>; constructor( private readonly runtime: IFluidDataStoreRuntime, /* Private */ context: IFluidDataStoreContext, ) { super(); this.innerHandle = new FluidObjectHandle(this, "", runtime.objectsRoutingContext); } public async request(request: IRequest): Promise<IResponse> { return defaultFluidObjectRequestHandler(this, request); } private async initialize(existing: boolean) { if (!existing) { this.root = SharedMap.create(this.runtime, "root"); const text = SharedString.create(this.runtime); // Initial paragraph marker text.insertMarker( 0, ReferenceType.Tile, { [reservedTileLabelsKey]: ["pg"] }); this.root.set("text", text.handle); this.root.bindToContext(); } this.root = await this.runtime.getChannel("root") as ISharedMap; this.text = await this.root.get<IFluidHandle<SharedString>>("text")?.get(); } public render(elm: HTMLElement): void { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const codemirrorView = new CodemirrorView(this.text!, this.runtime); codemirrorView.render(elm); } } class SmdeFactory implements IFluidDataStoreFactory { public static readonly type = "@fluid-example/codemirror"; public readonly type = SmdeFactory.type; public get IFluidDataStoreFactory() { return this; } public async instantiateDataStore(context: IFluidDataStoreContext, existing: boolean) { const runtimeClass = mixinRequestHandler( async (request: IRequest) => { const router = await routerP; return router.request(request); }); const runtime = new runtimeClass( context, new Map([ SharedMap.getFactory(), SharedString.getFactory(), ].map((factory) => [factory.type, factory])), existing, ); const routerP = CodeMirrorComponent.load(runtime, context, existing); return runtime; } } export const fluidExport = new SmdeFactory();
the_stack
* @hidden * @deprecated */ export const CLS_RTE: string = 'e-richtexteditor'; /** * @hidden * @deprecated */ export const CLS_RTL: string = 'e-rtl'; /** * @hidden * @deprecated */ export const CLS_CONTENT: string = 'e-content'; /** * @hidden * @deprecated */ export const CLS_DISABLED: string = 'e-disabled'; /** * @hidden * @deprecated */ export const CLS_SCRIPT_SHEET: string = 'rte-iframe-script-sheet'; /** * @hidden * @deprecated */ export const CLS_STYLE_SHEET: string = 'rte-iframe-style-sheet'; /** * @hidden * @deprecated */ export const CLS_TOOLBAR: string = 'e-rte-toolbar'; /** * @hidden * @deprecated */ export const CLS_TB_FIXED: string = 'e-rte-tb-fixed'; /** * @hidden * @deprecated */ export const CLS_TB_FLOAT: string = 'e-rte-tb-float'; /** * @hidden * @deprecated */ export const CLS_TB_ABS_FLOAT: string = 'e-rte-tb-abs-float'; /** * @hidden * @deprecated */ export const CLS_INLINE: string = 'e-rte-inline'; /** * @hidden * @deprecated */ export const CLS_TB_INLINE: string = 'e-rte-tb-inline'; /** * @hidden * @deprecated */ export const CLS_RTE_EXPAND_TB: string = 'e-rte-tb-expand'; /** * @hidden * @deprecated */ export const CLS_FULL_SCREEN: string = 'e-rte-full-screen'; /** * @hidden * @deprecated */ export const CLS_QUICK_TB: string = 'e-rte-quick-toolbar'; /** * @hidden * @deprecated */ export const CLS_POP: string = 'e-rte-pop'; /** * @hidden * @deprecated */ export const CLS_TB_STATIC: string = 'e-tb-static'; /** * @hidden * @deprecated */ export const CLS_QUICK_POP: string = 'e-rte-quick-popup'; /** * @hidden * @deprecated */ export const CLS_QUICK_DROPDOWN: string = 'e-quick-dropdown'; /** * @hidden * @deprecated */ export const CLS_IMAGE_POP: string = 'e-rte-image-popup'; /** * @hidden * @deprecated */ export const CLS_INLINE_POP: string = 'e-rte-inline-popup'; /** * @hidden * @deprecated */ export const CLS_INLINE_DROPDOWN: string = 'e-rte-inline-dropdown'; /** * @hidden * @deprecated */ export const CLS_DROPDOWN_POPUP: string = 'e-rte-dropdown-popup'; /** * @hidden * @deprecated */ export const CLS_DROPDOWN_ICONS: string = 'e-rte-dropdown-icons'; /** * @hidden * @deprecated */ export const CLS_DROPDOWN_ITEMS: string = 'e-rte-dropdown-items'; /** * @hidden * @deprecated */ export const CLS_DROPDOWN_BTN: string = 'e-rte-dropdown-btn'; /** * @hidden * @deprecated */ export const CLS_RTE_CONTENT: string = 'e-rte-content'; /** * @hidden * @deprecated */ export const CLS_TB_ITEM: string = 'e-toolbar-item'; /** * @hidden * @deprecated */ export const CLS_TB_EXTENDED: string = 'e-toolbar-extended'; /** * @hidden * @deprecated */ export const CLS_TB_WRAP: string = 'e-toolbar-wrapper'; /** * @hidden * @deprecated */ export const CLS_POPUP: string = 'e-popup'; /** * @hidden * @deprecated */ export const CLS_SEPARATOR: string = 'e-separator'; /** * @hidden * @deprecated */ export const CLS_MINIMIZE: string = 'e-minimize'; /** * @hidden * @deprecated */ export const CLS_MAXIMIZE: string = 'e-maximize'; /** * @hidden * @deprecated */ export const CLS_BACK: string = 'e-back'; /** * @hidden * @deprecated */ export const CLS_SHOW: string = 'e-show'; /** * @hidden * @deprecated */ export const CLS_HIDE: string = 'e-hide'; /** * @hidden * @deprecated */ export const CLS_VISIBLE: string = 'e-visible'; /** * @hidden * @deprecated */ export const CLS_FOCUS: string = 'e-focused'; /** * @hidden * @deprecated */ export const CLS_RM_WHITE_SPACE: string = 'e-remove-white-space'; /** * @hidden * @deprecated */ export const CLS_IMGRIGHT: string = 'e-imgright'; /** * @hidden * @deprecated */ export const CLS_IMGLEFT: string = 'e-imgleft'; /** * @hidden * @deprecated */ export const CLS_IMGCENTER: string = 'e-imgcenter'; /** * @hidden * @deprecated */ export const CLS_IMGBREAK: string = 'e-imgbreak'; /** * @hidden * @deprecated */ export const CLS_CAPTION: string = 'e-img-caption'; /** * @hidden * @deprecated */ export const CLS_RTE_CAPTION: string = 'e-rte-img-caption'; /** * @hidden * @deprecated */ export const CLS_CAPINLINE: string = 'e-caption-inline'; /** * @hidden * @deprecated */ export const CLS_IMGINLINE: string = 'e-imginline'; /** * @hidden * @deprecated */ export const CLS_COUNT: string = 'e-rte-character-count'; /** * @hidden * @deprecated */ export const CLS_WARNING: string = 'e-warning'; /** * @hidden * @deprecated */ export const CLS_ERROR: string = 'e-error'; /** * @hidden * @deprecated */ export const CLS_ICONS: string = 'e-icons'; /** * @hidden * @deprecated */ export const CLS_ACTIVE: string = 'e-active'; /** * @hidden * @deprecated */ export const CLS_EXPAND_OPEN: string = 'e-expand-open'; /** * @hidden * @deprecated */ export const CLS_RTE_ELEMENTS: string = 'e-rte-elements'; /** * @hidden * @deprecated */ export const CLS_TB_BTN: string = 'e-tbar-btn'; /** * @hidden * @deprecated */ export const CLS_HR_SEPARATOR: string = 'e-rte-horizontal-separator'; /** * @hidden * @deprecated */ export const CLS_TB_IOS_FIX: string = 'e-tbar-ios-fixed'; /** * @hidden * @deprecated */ export const CLS_LIST_PRIMARY_CONTENT: string = 'e-rte-list-primary-content'; /** * @hidden * @deprecated */ export const CLS_NUMBERFORMATLIST_TB_BTN: string = 'e-rte-numberformatlist-dropdown'; /** * @hidden * @deprecated */ export const CLS_BULLETFORMATLIST_TB_BTN: string = 'e-rte-bulletformatlist-dropdown'; /** * @hidden * @deprecated */ export const CLS_FORMATS_TB_BTN: string = 'e-formats-tbar-btn'; /** * @hidden * @deprecated */ export const CLS_FONT_NAME_TB_BTN: string = 'e-font-name-tbar-btn'; /** * @hidden * @deprecated */ export const CLS_FONT_SIZE_TB_BTN: string = 'e-font-size-tbar-btn'; /** * @hidden * @deprecated */ export const CLS_ALIGN_TB_BTN: string = 'e-alignment-tbar-btn'; /** * @hidden * @deprecated */ export const CLS_FONT_COLOR_TARGET: string = 'e-rte-fontcolor-element'; /** * @hidden * @deprecated */ export const CLS_BACKGROUND_COLOR_TARGET: string = 'e-rte-backgroundcolor-element'; /** * @hidden * @deprecated */ export const CLS_COLOR_CONTENT: string = 'e-rte-color-content'; /** * @hidden * @deprecated */ export const CLS_FONT_COLOR_DROPDOWN: string = 'e-rte-fontcolor-dropdown'; /** * @hidden * @deprecated */ export const CLS_BACKGROUND_COLOR_DROPDOWN: string = 'e-rte-backgroundcolor-dropdown'; /** * @hidden * @deprecated */ export const CLS_COLOR_PALETTE: string = 'e-rte-square-palette'; /** * @hidden * @deprecated */ export const CLS_FONT_COLOR_PICKER: string = 'e-rte-fontcolor-colorpicker'; /** * @hidden * @deprecated */ export const CLS_BACKGROUND_COLOR_PICKER: string = 'e-rte-backgroundcolor-colorpicker'; /** * @hidden * @deprecated */ export const CLS_RTE_READONLY: string = 'e-rte-readonly'; /** * @hidden * @deprecated */ export const CLS_TABLE_SEL: string = 'e-cell-select'; /** * @hidden * @deprecated */ export const CLS_TB_DASH_BOR: string = 'e-dashed-border'; /** * @hidden * @deprecated */ export const CLS_TB_ALT_BOR: string = 'e-alternate-border'; /** * @hidden * @deprecated */ export const CLS_TB_COL_RES: string = 'e-column-resize'; /** * @hidden * @deprecated */ export const CLS_TB_ROW_RES: string = 'e-row-resize'; /** * @hidden * @deprecated */ export const CLS_TB_BOX_RES: string = 'e-table-box'; /** * @hidden * @deprecated */ export const CLS_RTE_HIDDEN: string = 'e-rte-hidden'; /** * @hidden * @deprecated */ export const CLS_RTE_PASTE_KEEP_FORMAT: string = 'e-rte-keepformat'; /** * @hidden * @deprecated */ export const CLS_RTE_PASTE_REMOVE_FORMAT: string = 'e-rte-removeformat'; /** * @hidden * @deprecated */ export const CLS_RTE_PASTE_PLAIN_FORMAT: string = 'e-rte-plainformat'; /** * @hidden * @deprecated */ export const CLS_RTE_PASTE_OK: string = 'e-rte-pasteok'; /** * @hidden * @deprecated */ export const CLS_RTE_PASTE_CANCEL: string = 'e-rte-pastecancel'; /** * @hidden * @deprecated */ export const CLS_RTE_DIALOG_MIN_HEIGHT: string = 'e-rte-dialog-minheight'; /** * @hidden * @deprecated */ export const CLS_RTE_RES_HANDLE: string = 'e-resize-handle'; /** * @hidden * @deprecated */ export const CLS_RTE_RES_EAST: string = 'e-south-east'; /** * @hidden * @deprecated */ export const CLS_RTE_IMAGE: string = 'e-rte-image'; /** * @hidden * @deprecated */ export const CLS_RESIZE: string = 'e-resize'; /** * @hidden * @deprecated */ export const CLS_IMG_FOCUS: string = 'e-img-focus'; /** * @hidden * @deprecated */ export const CLS_RTE_DRAG_IMAGE: string = 'e-rte-drag-image'; /** * @hidden * @deprecated */ export const CLS_RTE_UPLOAD_POPUP: string = 'e-rte-upload-popup'; /** * @hidden * @deprecated */ export const CLS_POPUP_OPEN: string = 'e-popup-open'; /** * @hidden * @deprecated */ export const CLS_IMG_RESIZE: string = 'e-img-resize'; /** * @hidden * @deprecated */ export const CLS_DROPAREA: string = 'e-droparea'; /** * @hidden * @deprecated */ export const CLS_IMG_INNER: string = 'e-img-inner'; /** * @hidden * @deprecated */ export const CLS_UPLOAD_FILES: string = 'e-upload-files'; /** * @hidden * @deprecated */ export const CLS_RTE_DIALOG_UPLOAD: string = 'e-rte-dialog-upload'; /** * @hidden * @deprecated */ export const CLS_RTE_RES_CNT: string = 'e-rte-resize'; /** * @hidden * @deprecated */ export const CLS_CUSTOM_TILE: string = 'e-custom-tile'; /** * @hidden * @deprecated */ export const CLS_NOCOLOR_ITEM: string = 'e-nocolor-item'; /** * @hidden * @deprecated */ export const CLS_TABLE: string = 'e-rte-table'; /** * @hidden * @deprecated */ export const CLS_TABLE_BORDER: string = 'e-rte-table-border'; /** * @hidden * @deprecated */ export const CLS_RTE_TABLE_RESIZE: string = 'e-rte-table-resize'; /** * @hidden * @deprecated */ export const CLS_RTE_FIXED_TB_EXPAND: string = 'e-rte-fixed-tb-expand'; /** * @hidden * @deprecated */ export const CLS_RTE_TB_ENABLED: string = 'e-rte-toolbar-enabled';
the_stack
import MathUtils from '@/utils/MathUtils'; import RectUtils from '@/utils/tool/RectUtils'; import { DEFAULT_TEXT_OFFSET, EDragStatus, EDragTarget, ERotateDirection, ESortDirection, TEXT_ATTRIBUTE_OFFSET, } from '../../constant/annotation'; import EKeyCode from '../../constant/keyCode'; import { edgeAdsorptionScope, EPolygonPattern, EToolName } from '../../constant/tool'; import locale from '../../locales'; import { EMessage } from '../../locales/constants'; import { IPolygonConfig, IPolygonData, IPolygonPoint } from '../../types/tool/polygon'; import ActionsHistory from '../../utils/ActionsHistory'; import AttributeUtils from '../../utils/tool/AttributeUtils'; import AxisUtils from '../../utils/tool/AxisUtils'; import CanvasUtils from '../../utils/tool/CanvasUtils'; import CommonToolUtils from '../../utils/tool/CommonToolUtils'; import DrawUtils from '../../utils/tool/DrawUtils'; import PolygonUtils from '../../utils/tool/PolygonUtils'; import StyleUtils from '../../utils/tool/StyleUtils'; import uuid from '../../utils/uuid'; import { BasicToolOperation, IBasicToolOperationProps } from './basicToolOperation'; import TextAttributeClass from './textAttributeClass'; const TEXT_MAX_WIDTH = 164; interface IPolygonOperationProps extends IBasicToolOperationProps {} class PolygonOperation extends BasicToolOperation { public config: IPolygonConfig; // RENDER public drawingPointList: IPolygonPoint[]; // 正在绘制的多边形,在 zoom 底下 public polygonList: IPolygonData[]; public hoverID?: string; public hoverPointIndex: number; public hoverEdgeIndex: number; public selectedID?: string; public editPolygonID?: string; // 是否进入编辑模式 public pattern: EPolygonPattern; // 当前多边形标注形式 private dragInfo?: { dragStartCoord: ICoordinate; initPointList: IPolygonPoint[]; changePointIndex?: number[]; // 用于存储拖拽点 / 边的下标 dragTarget: EDragTarget; }; private drawingHistory: ActionsHistory; // 用于正在编辑中的历史记录 private isCtrl: boolean; // 当前的是否按住了 ctrl private isAlt: boolean; // 当前是否按住了 alt private _textAttributInstance?: TextAttributeClass; constructor(props: IPolygonOperationProps) { super(props); this.config = CommonToolUtils.jsonParser(props.config); this.drawingPointList = []; this.polygonList = []; this.hoverPointIndex = -1; this.hoverEdgeIndex = -1; this.drawingHistory = new ActionsHistory(); this.isCtrl = false; this.isAlt = false; this.pattern = EPolygonPattern.Normal; this.getCurrentSelectedData = this.getCurrentSelectedData.bind(this); this.updateSelectedTextAttribute = this.updateSelectedTextAttribute.bind(this); } public eventBinding() { super.eventBinding(); // 解绑原本的 onMouseUp,将 onMoueUp 用于 dblClickListener ß进行绑定 this.container.removeEventListener('mouseup', this.onMouseUp); this.container.addEventListener('mouseup', this.dragMouseUp); this.dblClickListener.addEvent(this.onMouseUp, this.onLeftDblClick, this.onRightDblClick, this.isAllowDouble); } public eventUnbinding() { super.eventUnbinding(); this.container.removeEventListener('mouseup', this.dragMouseUp); } public destroy() { super.destroy(); if (this._textAttributInstance) { this._textAttributInstance.clearTextAttribute(); } } public get selectedPolygon() { return PolygonUtils.getPolygonByID(this.polygonList, this.selectedID); } public get polygonListUnderZoom() { return this.polygonList.map((polygon) => ({ ...polygon, pointList: AxisUtils.changePointListByZoom(polygon.pointList, this.zoom), })); } public get selectedText() { return this.selectedPolygon?.textAttribute; } // 是否直接执行操作 public isAllowDouble = (e: MouseEvent) => { const { selectedID } = this; const currentSelectedID = this.getHoverID(e); // 仅在选中的时候需要 double click if (selectedID && selectedID === currentSelectedID) { return true; } return false; }; public get dataList() { return this.polygonList; } // 更改当前标注模式 public setPattern(pattern: EPolygonPattern) { if (this.drawingPointList?.length > 0) { // 编辑中不允许直接跳出 return; } this.pattern = pattern; } /** * 当前页面展示的框体 */ public get currentShowList() { let polygon: IPolygonData[] = []; const [showingPolygon, selectdPolygon] = CommonToolUtils.getRenderResultList<IPolygonData>( this.polygonList, CommonToolUtils.getSourceID(this.basicResult), this.attributeLockList, this.selectedID, ); polygon = showingPolygon; if (this.isHidden) { polygon = []; } if (selectdPolygon) { polygon.push(selectdPolygon); } return polygon; } /** * 当前依赖状态下本页的所有框 * * @readonly * @memberof RectOperation */ public get currentPageResult() { const [showingPolygon] = CommonToolUtils.getRenderResultList<IPolygonData>( this.polygonList, CommonToolUtils.getSourceID(this.basicResult), [], ); return showingPolygon; } public setResult(polygonList: IPolygonData[]) { this.clearActiveStatus(); this.setPolygonList(polygonList); this.render(); } /** * 外层 sidabr 调用 * @param v * @returns */ public textChange = (v: string) => { if (this.config.textConfigurable === false || !this.selectedID) { return; } this.setPolygonList(AttributeUtils.textChange(v, this.selectedID, this.polygonList)); this.emit('selectedChange'); // 触发外层的更新 this.render(); }; /** * 设定指定多边形的信息 * @param id * @param newPolygonData * @returns */ public setPolygonDataByID(newPolygonData: Partial<IPolygonData>, id?: string) { return this.polygonList.map((polygon) => { if (polygon.id === id) { return { ...polygon, ...newPolygonData, }; } return polygon; }); } public rotatePolygon(angle: number = 1, direction = ERotateDirection.Clockwise, selectedID = this.selectedID) { if (!selectedID) { return; } const selectedPolygon = PolygonUtils.getPolygonByID(this.polygonList, selectedID); if (!selectedPolygon) { return; } const rotatePointList = PolygonUtils.updatePolygonByRotate(direction, angle, selectedPolygon?.pointList); this.setPolygonList(this.setPolygonDataByID({ pointList: rotatePointList }, selectedID)); this.render(); } public addPointInDrawing(e: MouseEvent) { if (!this.imgInfo) { return; } const { upperLimitPointNum, edgeAdsorption } = this.config; if (upperLimitPointNum && this.drawingPointList.length >= upperLimitPointNum) { // 小于对应的下限点, 大于上限点无法添加 this.emit( 'messageInfo', `${locale.getMessagesByLocale(EMessage.UpperLimitErrorNotice, this.lang)}${upperLimitPointNum}`, ); return; } this.setSelectedID(''); const coordinateZoom = this.getCoordinateUnderZoom(e); const coordinate = AxisUtils.changeDrawOutsideTarget( coordinateZoom, { x: 0, y: 0 }, this.imgInfo, this.config.drawOutsideTarget, this.basicResult, this.zoom, ); // 判断是否的初始点,是则进行闭合 const calculateHoverPointIndex = AxisUtils.returnClosePointIndex( coordinate, AxisUtils.changePointListByZoom(this.drawingPointList, this.zoom), ); if (calculateHoverPointIndex === 0) { this.addDrawingPointToPolygonList(); return; } const { dropFoot } = PolygonUtils.getClosestPoint( coordinate, this.polygonListUnderZoom, this.config.lineType, edgeAdsorptionScope, ); const coordinateWithOrigin = AxisUtils.changePointByZoom( dropFoot && e.altKey === false && edgeAdsorption ? dropFoot : coordinate, 1 / this.zoom, ); if (this.pattern === EPolygonPattern.Rect && this.drawingPointList.length === 2) { const rect = MathUtils.getRectangleByRightAngle(coordinateWithOrigin, this.drawingPointList); this.drawingPointList = rect; // 边缘判断 - 仅限支持图片下范围下 if (this.config.drawOutsideTarget === false && this.imgInfo) { const isOutSide = this.isPolygonOutSide(this.drawingPointList); if (isOutSide) { // 边缘外直接跳出 this.emit( 'messageInfo', `${locale.getMessagesByLocale(EMessage.ForbiddenCreationOutsideBoundary, this.lang)}`, ); this.drawingPointList = []; return; } } // 创建多边形 this.addDrawingPointToPolygonList(true); return; } this.drawingPointList.push(coordinateWithOrigin); if (this.drawingPointList.length === 1) { this.drawingHistory.initRecord(this.drawingPointList); } else { this.drawingHistory.pushHistory(this.drawingPointList); } } // 全局操作 public clearResult() { this.setPolygonList([]); this.setSelectedID(undefined); this.render(); } /** * 清除多边形拖拽的中间状态 */ public clearPolygonDrag() { this.drawingPointList = []; this.dragInfo = undefined; this.dragInfo = undefined; this.dragStatus = EDragStatus.Wait; this.hoverEdgeIndex = -1; this.hoverPointIndex = -1; this.hoverID = ''; } /** * 清楚所有的中间状态 */ public clearActiveStatus() { this.clearPolygonDrag(); this.setSelectedID(undefined); } // SET DATA public setPolygonList(polygonList: IPolygonData[]) { const oldLen = this.polygonList.length; this.polygonList = polygonList; if (oldLen !== polygonList.length) { // 件数发生改变 this.emit('updatePageNumber'); } } public setSelectedID(newID?: string) { const oldID = this.selectedID; if (newID !== oldID && oldID) { // 触发文本切换的操作 this._textAttributInstance?.changeSelected(); } if (!newID) { this._textAttributInstance?.clearTextAttribute(); } this.selectedID = newID; this.render(); this.emit('selectedChange'); } public setDefaultAttribute(defaultAttribute: string = '') { const oldDefault = this.defaultAttribute; this.defaultAttribute = defaultAttribute; if (oldDefault !== defaultAttribute) { // 如果更改 attribute 需要同步更改 style 的样式 this.changeStyle(defaultAttribute); // 触发侧边栏同步 this.emit('changeAttributeSidebar'); // 如有选中目标,则需更改当前选中的属性 const { selectedID } = this; if (selectedID) { if (this.selectedPolygon) { this.selectedPolygon.attribute = defaultAttribute; } this.history.pushHistory(this.polygonList); this.render(); } if (this._textAttributInstance) { if (this.attributeLockList.length > 0 && !this.attributeLockList.includes(defaultAttribute)) { // 属性隐藏 this._textAttributInstance.clearTextAttribute(); return; } this._textAttributInstance.updateIcon(this.getTextIconSvg(defaultAttribute)); } } } public setStyle(toolStyle: any) { super.setStyle(toolStyle); // 当存在文本 icon 的时候需要更改当前样式 if (this._textAttributInstance && this.config.attributeConfigurable === false) { this._textAttributInstance?.updateIcon(this.getTextIconSvg()); } } public setPolygonValidAndRender(id: string) { if (!id) { return; } const newPolygonList = this.polygonList.map((polygon) => { if (polygon.id === id) { return { ...polygon, valid: !polygon.valid, }; } return polygon; }); this.setPolygonList(newPolygonList); this.history.pushHistory(this.polygonList); this.render(); // 同步外层 this.emit('updateResult'); } /** * 初始化的添加的数据 * @returns */ public addDrawingPointToPolygonList(isRect?: boolean) { let { lowerLimitPointNum = 3 } = this.config; if (lowerLimitPointNum < 3) { lowerLimitPointNum = 3; } if (this.drawingPointList.length < lowerLimitPointNum) { // 小于下线点无法闭合, 直接清除数据 this.drawingPointList = []; this.editPolygonID = ''; return; } const basicSourceID = CommonToolUtils.getSourceID(this.basicResult); const polygonList = [...this.polygonList]; if (this.editPolygonID) { const samePolygon = polygonList.find((polygon) => polygon.id === this.editPolygonID); if (!samePolygon) { return; } samePolygon.pointList = this.drawingPointList; this.editPolygonID = ''; } else { const id = uuid(8, 62); let newPolygon: IPolygonData = { id, sourceID: basicSourceID, valid: !this.isCtrl, textAttribute: '', pointList: this.drawingPointList, attribute: this.defaultAttribute, order: CommonToolUtils.getMaxOrder( polygonList.filter((v) => CommonToolUtils.isSameSourceID(v.sourceID, basicSourceID)), ) + 1, }; if (this.config.textConfigurable) { let textAttribute = ''; textAttribute = AttributeUtils.getTextAttribute( this.polygonList.filter((polygon) => CommonToolUtils.isSameSourceID(polygon.sourceID, basicSourceID)), this.config.textCheckType, ); newPolygon = { ...newPolygon, textAttribute, }; } if (this.pattern === EPolygonPattern.Rect && isRect === true) { newPolygon = { ...newPolygon, isRect: true, }; } polygonList.push(newPolygon); this.setSelectedIdAfterAddingDrawing(id); } this.setPolygonList(polygonList); this.isCtrl = false; this.drawingPointList = []; this.history.pushHistory(polygonList); } public setSelectedIdAfterAddingDrawing(newID: string) { if (this.drawingPointList.length === 0) { return; } if (this.config.textConfigurable) { this.setSelectedID(newID); } else { this.setSelectedID(); } } /** * 获取当前 hover 多边形的 ID * @param e * @returns */ public getHoverID(e: MouseEvent) { const coordinate = this.getCoordinateUnderZoom(e); const polygonListWithZoom = this.currentShowList.map((polygon) => ({ ...polygon, pointList: AxisUtils.changePointListByZoom(polygon.pointList, this.zoom), })); return PolygonUtils.getHoverPolygonID(coordinate, polygonListWithZoom, 10, this.config?.lineType); } public getHoverEdgeIndex(e: MouseEvent) { if (!this.selectedID) { return -1; } const selectPolygon = this.selectedPolygon; if (!selectPolygon) { return -1; } const currentCoord = this.getCoordinateUnderZoom(e); const editPointListUnderZoom = AxisUtils.changePointListByZoom(selectPolygon.pointList, this.zoom); return PolygonUtils.getHoverEdgeIndex(currentCoord, editPointListUnderZoom, this.config?.lineType); } public getHoverPointIndex(e: MouseEvent) { if (!this.selectedID) { return -1; } const selectPolygon = this.selectedPolygon; if (!selectPolygon) { return -1; } const currentCoord = this.getCoordinateUnderZoom(e); const editPointListUnderZoom = AxisUtils.changePointListByZoom(selectPolygon.pointList, this.zoom); return AxisUtils.returnClosePointIndex(currentCoord, editPointListUnderZoom); } public deletePolygon(id?: string) { if (!id) { return; } this.setPolygonList(this.polygonList.filter((polygon) => polygon.id !== id)); this.history.pushHistory(this.polygonList); this._textAttributInstance?.clearTextAttribute(); this.emit('selectedChange'); this.render(); } public deletePolygonPoint(index: number) { if (!this.selectedID) { return; } const { selectedPolygon } = this; if (!selectedPolygon) { return; } let { lowerLimitPointNum } = this.config; if (lowerLimitPointNum < 3) { lowerLimitPointNum = 3; } if (selectedPolygon.pointList.length <= lowerLimitPointNum) { this.emit( 'messageInfo', `${locale.getMessagesByLocale(EMessage.LowerLimitErrorNotice, this.lang)}${lowerLimitPointNum}`, ); return; } selectedPolygon?.pointList.splice(index, 1); this.history.pushHistory(this.polygonList); this.render(); } // OPERATION public spaceKeydown() { // 续标检测 if (this.selectedID) { // 矩形模式无法续标 if (this.selectedPolygon?.isRect === true) { this.emit('messageInfo', `${locale.getMessagesByLocale(EMessage.UnableToReannotation, this.lang)}`); return; } this.editPolygonID = this.selectedID; this.drawingPointList = this.selectedPolygon?.pointList ?? []; this.drawingHistory.empty(); this.drawingHistory.initRecord(this.drawingPointList); this.hoverID = ''; this.setSelectedID(''); this.render(); } } public onTabKeyDown(e: KeyboardEvent) { e.preventDefault(); if (this.drawingPointList.length > 0) { // 如果正在编辑则不允许使用 Tab 切换 return; } let sort = ESortDirection.ascend; if (e.shiftKey) { sort = ESortDirection.descend; } const [showingResult, selectedResult] = CommonToolUtils.getRenderResultList<IPolygonData>( this.polygonList, CommonToolUtils.getSourceID(this.basicResult), this.attributeLockList, this.selectedID, ); let polygonList = [...showingResult]; if (selectedResult) { polygonList = [...polygonList, selectedResult]; } const viewPort = CanvasUtils.getViewPort(this.canvas, this.currentPos, this.zoom); const sortList = polygonList .map((v) => ({ ...v, x: v.pointList[0]?.x ?? 0, y: v.pointList[0]?.y ?? 0, })) .filter((polygon) => CanvasUtils.inViewPort({ x: polygon.x, y: polygon.y }, viewPort)); const nextSelectedResult = CommonToolUtils.getNextSelectedRectID(sortList, sort, this.selectedID); if (nextSelectedResult) { this.setSelectedID(nextSelectedResult.id); const { selectedPolygon } = this; if (selectedPolygon) { this.setDefaultAttribute(selectedPolygon.attribute); } } this.render(); } public onKeyDown(e: KeyboardEvent) { if (!CommonToolUtils.hotkeyFilter(e)) { // 如果为输入框则进行过滤 return; } if (super.onKeyDown(e) === false) { return; } const { keyCode } = e; switch (keyCode) { case EKeyCode.Space: this.spaceKeydown(); break; case EKeyCode.Esc: this.drawingPointList = []; this.editPolygonID = ''; break; case EKeyCode.F: if (this.selectedID) { this.setPolygonValidAndRender(this.selectedID); } break; case EKeyCode.Z: this.setIsHidden(!this.isHidden); this.render(); break; case EKeyCode.Delete: this.deletePolygon(this.selectedID); this.render(); break; case EKeyCode.Ctrl: this.isCtrl = true; break; case EKeyCode.Alt: if (this.isAlt === false) { e.preventDefault(); this.isAlt = true; this.render(); } break; case EKeyCode.Tab: { this.onTabKeyDown(e); break; } default: { if (this.config.attributeConfigurable) { const keyCode2Attribute = AttributeUtils.getAttributeByKeycode(keyCode, this.config.attributeList); if (keyCode2Attribute !== undefined) { this.setDefaultAttribute(keyCode2Attribute); } } break; } } } public onKeyUp(e: KeyboardEvent) { super.onKeyUp(e); switch (e.keyCode) { case EKeyCode.Ctrl: this.isCtrl = false; break; case EKeyCode.Alt: { const oldAlt = this.isAlt; this.isAlt = false; if (oldAlt === true) { this.render(); } break; } default: { break; } } } public rightMouseUp() { // 标注中的数据结束 if (this.drawingPointList.length > 0) { // this.addDrawingPointToPolygonList(); return; } // 右键选中设置 this.setSelectedID(this.hoverID); const { selectedPolygon } = this; if (selectedPolygon) { this.setDefaultAttribute(selectedPolygon.attribute); } } public onLeftDblClick(e: MouseEvent) { if (this.hoverEdgeIndex > -1) { const currentCoord = this.getCoordinateUnderZoom(e); const { selectedPolygon } = this; if (!selectedPolygon) { return; } const { dropFoot } = PolygonUtils.getClosestPoint( currentCoord, this.polygonListUnderZoom, this.config.lineType, edgeAdsorptionScope, ); if (!dropFoot) { return; } const { upperLimitPointNum } = this.config; if (upperLimitPointNum && selectedPolygon.pointList.length >= upperLimitPointNum) { // 小于对应的下限点, 大于上限点无法添加 this.emit( 'messageInfo', `${locale.getMessagesByLocale(EMessage.UpperLimitErrorNotice, this.lang)}${upperLimitPointNum}`, ); this.clearPolygonDrag(); return; } selectedPolygon?.pointList.splice( this.hoverEdgeIndex + 1, 0, AxisUtils.changePointByZoom(dropFoot, 1 / this.zoom), ); this.setPolygonDataByID(selectedPolygon, this.selectedID); this.history.pushHistory(this.polygonList); this.hoverPointIndex = -1; this.hoverEdgeIndex = -1; this.render(); } this.dragInfo = undefined; } public onRightDblClick(e: MouseEvent) { this.dragInfo = undefined; this.clearImgDrag(); const hoverID = this.getHoverID(e); const hoverPointIndex = this.getHoverPointIndex(e); if (this.hoverPointIndex > -1 && this.hoverPointIndex === hoverPointIndex) { this.deletePolygonPoint(hoverPointIndex); this.dragInfo = undefined; this.hoverPointIndex = -1; this.render(); return; } if (this.hoverID === this.selectedID) { this.deletePolygon(hoverID); } this.render(); } public onMouseDown(e: MouseEvent) { if (super.onMouseDown(e) || this.forbidMouseOperation || e.ctrlKey === true) { return; } const firstPolygon = this.selectedPolygon; if (!firstPolygon || e.button !== 0) { return; } const hoverID = this.getHoverID(e); if (hoverID !== this.selectedID) { // 无选中则无法进行拖拽,提前退出 return; } const initPointList = firstPolygon.pointList; const dragStartCoord = this.getCoordinateUnderZoom(e); let changePointIndex = [0]; let dragTarget = EDragTarget.Plane; this.dragStatus = EDragStatus.Start; const closePointIndex = this.getHoverPointIndex(e); const closeEdgeIndex = this.getHoverEdgeIndex(e); if (closePointIndex > -1) { dragTarget = EDragTarget.Point; changePointIndex = [closePointIndex]; } else if (closeEdgeIndex > -1 && this.hoverEdgeIndex > -1) { dragTarget = EDragTarget.Line; changePointIndex = [closeEdgeIndex, (closeEdgeIndex + 1) % initPointList.length]; } this.dragInfo = { dragStartCoord, dragTarget, initPointList, changePointIndex, }; return true; } /** * 判断是否在边界外 * @param selectedPointList * @returns */ public isPolygonOutSide(selectedPointList: IPolygonPoint[]) { // 边缘判断 - 仅限支持图片下范围下 if (this.dependToolName && this.basicCanvas && this.basicResult) { let isOutSide = false; switch (this.dependToolName) { case EToolName.Rect: { // 依赖拉框 isOutSide = selectedPointList.filter((v) => !RectUtils.isInRect(v, this.basicResult)).length > 0; break; } case EToolName.Polygon: { isOutSide = PolygonUtils.isPointListOutSidePolygon( selectedPointList, this.basicResult.pointList, this.config.lineType, ); break; } default: { // } } return isOutSide; } if (!this.imgInfo) { return false; } const { left, top, right, bottom } = MathUtils.calcViewportBoundaries( AxisUtils.changePointListByZoom(selectedPointList, this.zoom), ); const scope = 0.00001; if (left < 0 || top < 0 || right > this.imgInfo.width + scope || bottom > this.imgInfo.height + scope) { // 超出范围则不进行编辑 return true; } return false; } public onDragMove(e: MouseEvent) { if (!this.dragInfo || !this.selectedID) { return; } const { selectedPolygon } = this; let selectedPointList: IPolygonPoint[] | undefined = selectedPolygon?.pointList; if (!selectedPointList) { return; } const { initPointList, dragStartCoord, dragTarget, changePointIndex } = this.dragInfo; const coordinate = this.getCoordinateUnderZoom(e); let offset = { x: (coordinate.x - dragStartCoord.x) / this.zoom, y: (coordinate.y - dragStartCoord.y) / this.zoom, }; /** * 矩形拖动 * 1. 模式匹配 * 2. 当前选中多边形是否为矩形 * 3. 是否带有拖动 * */ if ( this.pattern === EPolygonPattern.Rect && selectedPolygon?.isRect === true && changePointIndex && [EDragTarget.Line].includes(dragTarget) ) { const firstPointIndex = MathUtils.getArrayIndex(changePointIndex[0] - 2, 4); const secondPointIndex = MathUtils.getArrayIndex(changePointIndex[0] - 1, 4); const basicLine: [ICoordinate, ICoordinate] = [initPointList[firstPointIndex], initPointList[secondPointIndex]]; offset = MathUtils.getRectPerpendicularOffset(dragStartCoord, coordinate, basicLine); } this.dragStatus = EDragStatus.Move; switch (dragTarget) { case EDragTarget.Plane: selectedPointList = selectedPointList.map((v, i) => ({ ...v, x: initPointList[i].x + offset.x, y: initPointList[i].y + offset.y, })); break; case EDragTarget.Point: case EDragTarget.Line: selectedPointList = selectedPointList.map((n, i) => { if (changePointIndex && changePointIndex.includes(i)) { return { ...n, x: initPointList[i].x + offset.x, y: initPointList[i].y + offset.y, }; } return n; }); break; default: { break; } } if ( this.pattern === EPolygonPattern.Rect && selectedPolygon?.isRect === true && dragTarget === EDragTarget.Point && changePointIndex ) { const newPointList = MathUtils.getPointListFromPointOffset( initPointList as [ICoordinate, ICoordinate, ICoordinate, ICoordinate], changePointIndex[0], offset, ); selectedPointList = newPointList; } // 边缘判断 - 仅限支持图片下范围下 if (this.config.drawOutsideTarget === false && this.imgInfo) { const isOutSide = this.isPolygonOutSide(selectedPointList); if (isOutSide) { // 边缘外直接跳出 return; } } const newPolygonList = this.polygonList.map((v) => { if (v.id === this.selectedID) { const newData = { ...v, pointList: selectedPointList as IPolygonPoint[], }; // 非矩形模式下拖动,矩形模式下生成的框将会转换为非矩形框 if (v.isRect === true && this.pattern === EPolygonPattern.Normal) { Object.assign(newData, { isRect: false }); } return newData; } return v; }); this.setPolygonList(newPolygonList); this.render(); } public onMouseMove(e: MouseEvent) { if (super.onMouseMove(e) || this.forbidMouseOperation || !this.imgInfo) { return; } if (this.selectedID && this.dragInfo) { this.onDragMove(e); return; } let hoverPointIndex = -1; let hoverEdgeIndex = -1; const { selectedID } = this; if (selectedID) { this.hoverEdgeIndex = -1; this.hoverPointIndex = -1; hoverPointIndex = this.getHoverPointIndex(e); // 注意: 点的优先级大于边 if (hoverPointIndex > -1) { this.hoverPointIndex = hoverPointIndex; } else { hoverEdgeIndex = this.getHoverEdgeIndex(e); this.hoverEdgeIndex = hoverEdgeIndex; } } if (this.drawingPointList.length > 0) { // 编辑中无需 hover操作 return; } const newHoverID = this.getHoverID(e); if (this.hoverID !== newHoverID) { this.hoverID = newHoverID; this.render(); } } public leftMouseUp(e: MouseEvent) { const hoverID = this.getHoverID(e); if (this.drawingPointList.length === 0 && e.ctrlKey === true && hoverID) { // ctrl + 左键 + hover存在,更改框属性 this.setPolygonValidAndRender(hoverID); return; } // 创建多边形 this.addPointInDrawing(e); } public onMouseUp(e: MouseEvent) { if (super.onMouseUp(e) || this.forbidMouseOperation || !this.imgInfo) { return undefined; } if (this.dragInfo && this.dragStatus === EDragStatus.Move) { // 拖拽停止 this.dragInfo = undefined; this.dragStatus = EDragStatus.Wait; this.history.pushHistory(this.polygonList); // 同步 结果 this.emit('updateResult'); return; } switch (e.button) { case 0: { this.leftMouseUp(e); break; } case 2: { this.rightMouseUp(); break; } default: { break; } } this.render(); } public dragMouseUp() { if (this.dragStatus === EDragStatus.Start) { this.dragInfo = undefined; this.dragStatus = EDragStatus.Wait; } } public exportData() { const { polygonList } = this; return [polygonList, this.basicImgInfo]; } /** * 获取当前配置下的 icon svg * @param attribute */ public getTextIconSvg(attribute = '') { return AttributeUtils.getTextIconSvg( attribute, this.config.attributeList, this.config.attributeConfigurable, this.baseIcon, ); } public getCurrentSelectedData() { const { selectedPolygon } = this; if (!selectedPolygon) { return; } const toolColor = this.getColor(selectedPolygon.attribute); const color = selectedPolygon.valid ? toolColor?.valid.stroke : toolColor?.invalid.stroke; return { width: TEXT_MAX_WIDTH, textAttribute: selectedPolygon.textAttribute, color, }; } /** 更新文本输入,并且进行关闭 */ public updateSelectedTextAttribute(newTextAttribute?: string) { if (this._textAttributInstance && newTextAttribute && this.selectedID) { // 切换的时候如果存在 let textAttribute = newTextAttribute; if (AttributeUtils.textAttributeValidate(this.config.textCheckType, '', textAttribute) === false) { this.emit('messageError', AttributeUtils.getErrorNotice(this.config.textCheckType, this.lang)); textAttribute = ''; } this.setPolygonList(AttributeUtils.textChange(textAttribute, this.selectedID, this.polygonList)); this.emit('updateTextAttribute'); this.render(); } } public renderTextAttribute() { const { selectedPolygon } = this; if (!this.ctx || this.config.textConfigurable === false || !selectedPolygon) { return; } const { pointList, attribute, valid, textAttribute } = selectedPolygon; const { x, y } = pointList[pointList.length - 1]; const newWidth = TEXT_MAX_WIDTH; const coordinate = AxisUtils.getOffsetCoordinate({ x, y }, this.currentPos, this.zoom); const toolColor = this.getColor(attribute); const color = valid ? toolColor?.valid.stroke : toolColor?.invalid.stroke; if (!this._textAttributInstance) { // 属性文本示例 this._textAttributInstance = new TextAttributeClass({ width: newWidth, container: this.container, icon: this.getTextIconSvg(attribute), color, getCurrentSelectedData: this.getCurrentSelectedData, updateSelectedTextAttribute: this.updateSelectedTextAttribute, }); } if (this._textAttributInstance && !this._textAttributInstance?.isExit) { this._textAttributInstance.appendToContainer(); } this._textAttributInstance.update(`${textAttribute}`, { left: coordinate.x, top: coordinate.y, color, width: newWidth, }); } public renderPolygon() { // 1. 静态多边形 if (this.isHidden === false) { this.polygonList?.forEach((polygon) => { if ([this.selectedID, this.editPolygonID].includes(polygon.id)) { return; } const { textAttribute, attribute } = polygon; const toolColor = this.getColor(attribute); const toolData = StyleUtils.getStrokeAndFill(toolColor, polygon.valid); const transformPointList = AxisUtils.changePointListByZoom(polygon.pointList || [], this.zoom, this.currentPos); DrawUtils.drawPolygonWithFillAndLine(this.canvas, transformPointList, { fillColor: toolData.fill, strokeColor: toolData.stroke, pointColor: 'white', thickness: this.style?.width ?? 2, lineCap: 'round', isClose: true, lineType: this.config?.lineType, }); let showText = `${AttributeUtils.getAttributeShowText(attribute, this.config.attributeList) ?? ''}`; if (this.config?.isShowOrder && polygon?.order > 0) { showText = `${polygon.order} ${showText}`; } DrawUtils.drawText(this.canvas, transformPointList[0], showText, { color: toolData.stroke, ...DEFAULT_TEXT_OFFSET, }); const endPoint = transformPointList[transformPointList.length - 1]; DrawUtils.drawText( this.canvas, { x: endPoint.x + TEXT_ATTRIBUTE_OFFSET.x, y: endPoint.y + TEXT_ATTRIBUTE_OFFSET.y }, textAttribute, { color: toolData.stroke, ...DEFAULT_TEXT_OFFSET, }, ); }); } // 2. hover 多边形 if (this.hoverID && this.hoverID !== this.editPolygonID) { const hoverPolygon = this.polygonList.find((v) => v.id === this.hoverID && v.id !== this.selectedID); if (hoverPolygon) { let color = ''; const toolColor = this.getColor(hoverPolygon.attribute); if (hoverPolygon.valid) { color = toolColor.validHover.fill; } else { color = StyleUtils.getStrokeAndFill(toolColor, false, { isHover: true }).fill; } DrawUtils.drawPolygonWithFill( this.canvas, AxisUtils.changePointListByZoom(hoverPolygon.pointList, this.zoom, this.currentPos), { color, lineType: this.config?.lineType, }, ); } } // 3. 选中多边形的渲染 if (this.selectedID) { const selectdPolygon = this.selectedPolygon; if (selectdPolygon) { const toolColor = this.getColor(selectdPolygon.attribute); const toolData = StyleUtils.getStrokeAndFill(toolColor, selectdPolygon.valid, { isSelected: true }); DrawUtils.drawSelectedPolygonWithFillAndLine( this.canvas, AxisUtils.changePointListByZoom(selectdPolygon.pointList, this.zoom, this.currentPos), { fillColor: toolData.fill, strokeColor: toolData.stroke, pointColor: 'white', thickness: 2, lineCap: 'round', isClose: true, lineType: this.config?.lineType, }, ); let showText = `${ AttributeUtils.getAttributeShowText(selectdPolygon.attribute, this.config.attributeList) ?? '' }`; if (this.config?.isShowOrder && selectdPolygon?.order > 0) { showText = `${selectdPolygon.order} ${showText}`; } DrawUtils.drawText( this.canvas, AxisUtils.changePointByZoom(selectdPolygon.pointList[0], this.zoom, this.currentPos), showText, { color: toolData.stroke, ...DEFAULT_TEXT_OFFSET, }, ); this.renderTextAttribute(); } } const defaultColor = this.getColor(this.defaultAttribute); const toolData = StyleUtils.getStrokeAndFill(defaultColor, !this.isCtrl); // 4. 编辑中的多边形 if (this.drawingPointList?.length > 0) { // 渲染绘制中的多边形 let drawingPointList = [...this.drawingPointList]; let coordinate = AxisUtils.getOriginCoordinateWithOffsetCoordinate(this.coord, this.zoom, this.currentPos); if (this.pattern === EPolygonPattern.Rect && drawingPointList.length === 2) { // 矩形模式特殊绘制 drawingPointList = MathUtils.getRectangleByRightAngle(coordinate, drawingPointList); } else { if (this.config?.edgeAdsorption && this.isAlt === false) { const { dropFoot } = PolygonUtils.getClosestPoint( coordinate, this.polygonList, this.config?.lineType, edgeAdsorptionScope / this.zoom, ); if (dropFoot) { coordinate = dropFoot; } } drawingPointList.push(coordinate); } DrawUtils.drawSelectedPolygonWithFillAndLine( this.canvas, AxisUtils.changePointListByZoom(drawingPointList, this.zoom, this.currentPos), { fillColor: toolData.fill, strokeColor: toolData.stroke, pointColor: 'white', thickness: 2, lineCap: 'round', isClose: false, lineType: this.config.lineType, }, ); } // 5. 编辑中高亮的点 if (this.hoverPointIndex > -1 && this.selectedID) { const selectdPolygon = this.selectedPolygon; if (!selectdPolygon) { return; } const hoverColor = StyleUtils.getStrokeAndFill(defaultColor, selectdPolygon.valid, { isSelected: true }); const point = selectdPolygon?.pointList[this.hoverPointIndex]; if (point) { const { x, y } = AxisUtils.changePointByZoom(point, this.zoom, this.currentPos); DrawUtils.drawCircleWithFill(this.canvas, { x, y }, 5, { color: hoverColor.fill, }); } } // 6. 编辑中高亮的边 if (this.hoverEdgeIndex > -1 && this.selectedID) { const selectdPolygon = this.selectedPolygon; if (!selectdPolygon) { return; } const selectedColor = StyleUtils.getStrokeAndFill(defaultColor, selectdPolygon.valid, { isSelected: true }); DrawUtils.drawLineWithPointList( this.canvas, AxisUtils.changePointListByZoom(selectdPolygon.pointList, this.zoom, this.currentPos), { color: selectedColor.stroke, thickness: 10, hoverEdgeIndex: this.hoverEdgeIndex, lineType: this.config?.lineType, }, ); } } public render() { if (!this.ctx) { return; } super.render(); this.renderCursorLine(this.getLineColor(this.defaultAttribute)); this.renderPolygon(); } /** 撤销 */ public undo() { if (this.drawingPointList.length > 0) { // 绘制中进行 const drawingPointList = this.drawingHistory.undo(); if (!drawingPointList) { return; } this.drawingPointList = drawingPointList; this.render(); return; } const polygonList = this.history.undo(); if (polygonList) { if (polygonList.length !== this.polygonList.length) { this.setSelectedID(''); } this.setPolygonList(polygonList); this.render(); } } /** 重做 */ public redo() { if (this.drawingPointList.length > 0) { // 绘制中进行 const drawingPointList = this.drawingHistory.redo(); if (!drawingPointList) { return; } this.drawingPointList = drawingPointList; this.render(); return; } const polygonList = this.history.redo(); if (polygonList) { if (polygonList.length !== this.polygonList.length) { this.setSelectedID(''); } this.setPolygonList(polygonList); this.render(); } } } export default PolygonOperation;
the_stack
import { Polymer } from '../../tools/definitions/polymer'; declare const BrowserAPI: BrowserAPI; declare const browserAPI: browserAPI; declare const window: SharedWindow; export interface PromiseConstructor<T = {}> { constructor(initializer: (resolve: (result: T) => void, reject: (reason: any) => void) => Promise<T>): Promise<T>; constructor(initializer: (resolve: (result: T) => void, reject: (reason: any) => void) => void): Promise<T>; constructor(initializer: (resolve: (result: T) => void, reject: (reason: any) => void) => void|Promise<T>): Promise<T>; all<T>(values: Promise<T>[]): Promise<T[]>; race<T>(values: Promise<T>[]): Promise<T>; resolve<T>(value?: T): Promise<T>; reject<T>(reason?: Error): Promise<T>; } interface Withable { (): void; } export interface Prom<T> extends Promise<T> { new <T>(executor: (resolve: (value?: T | PromiseLike<T>) => void, reject: (reason?: any) => void) => void): Prom<T> } export const enum LANGS { EN = 'en' }; export interface I18N { (key: string, ...replacements: (string|number)[]): Promise<string>; sync(key: string, ...replacements: (string|number)[]): string; getLang(): Promise<LANGS>; setLang(lang: LANGS): Promise<void>; ready(): Promise<void>; addListener(fn: () => void): void; SUPPORTED_LANGS: LANGS[]; }; export interface I18NClass { /** * Fired when a language is going to change but hasn't been loaded yet * * @param {LANGS} newLang - The name of the new language * @param {LANGS} oldLang - The name of the old language */ onLangChange?(newLang: LANGS, oldLang: LANGS): void; /** * Fired when a language is going to change and has been loaded * * @param {LANGS} newLang - The name of the new language * @param {LANGS} oldLang - The name of the old language */ onLangChanged?(newLang: LANGS, oldLang: LANGS): void; } interface I18NElement { /** * Fired when a language is going to change but hasn't been loaded yet * * @param {LANGS} newLang - The name of the new language * @param {LANGS} oldLang - The name of the old language */ onLangChange?(newLang: LANGS, oldLang: LANGS): void; /** * Fired when a language is going to change and has been loaded * * @param {LANGS} newLang - The name of the new language * @param {LANGS} oldLang - The name of the old language */ onLangChanged?(newLang: LANGS, oldLang: LANGS): void; lang: LANGS; langReady: boolean; } declare global { interface Window { Promise: typeof Promise; onExists<T extends keyof C, C = Window>(key: T, container?: C): PromiseLike<C[T]>; onExistsChain<C, T1 extends keyof C, T2 extends keyof C[T1], T3 extends keyof C[T1][T2], T4 extends keyof C[T1][T2][T3], T5 extends keyof C[T1][T2][T3][T4]>(container: C, key1: T1): PromiseLike<C[T1]>; onExistsChain<C, T1 extends keyof C, T2 extends keyof C[T1], T3 extends keyof C[T1][T2], T4 extends keyof C[T1][T2][T3], T5 extends keyof C[T1][T2][T3][T4]>(container: C, key1: T1, key2: T2): PromiseLike<C[T1][T2]>; onExistsChain<C, T1 extends keyof C, T2 extends keyof C[T1], T3 extends keyof C[T1][T2], T4 extends keyof C[T1][T2][T3], T5 extends keyof C[T1][T2][T3][T4]>(container: C, key1: T1, key2: T2, key3: T3): PromiseLike<C[T1][T2][T3]>; onExistsChain<C, T1 extends keyof C, T2 extends keyof C[T1], T3 extends keyof C[T1][T2], T4 extends keyof C[T1][T2][T3], T5 extends keyof C[T1][T2][T3][T4]>(container: C, key1: T1, key2: T2, key3: T3, key4: T4): PromiseLike<C[T1][T2][T3][T4]>; onExistsChain<C, T1 extends keyof C, T2 extends keyof C[T1], T3 extends keyof C[T1][T2], T4 extends keyof C[T1][T2][T3], T5 extends keyof C[T1][T2][T3][T4]>(container: C, key1: T1, key2: T2, key3: T3, key4: T4, key5: T5): PromiseLike<C[T1][T2][T3][T4][T5]>; onExistsChain<C, T1 extends keyof C, T2 extends keyof C[T1], T3 extends keyof C[T1][T2], T4 extends keyof C[T1][T2][T3], T5 extends keyof C[T1][T2][T3][T4]>(container: C, key1: T1, key2?: T2, key3?: T3, key4?: T4, key5?: T5): PromiseLike<C[T1][T2][T3][T4][T5]>| PromiseLike<C[T1][T2][T3][T4]>|PromiseLike<C[T1][T2][T3]>|PromiseLike<C[T1][T2]>|PromiseLike<C[T1]>; objectify<T>(fn: T): T; register(...fns: any[]): void; with<T>(initializer: () => Withable, fn: () => T): T; withAsync<T>(initializer: () => Promise<Withable>, fn: () => Promise<T>): Promise<T>; setDisplayFlex(el: { style: CSSStyleDeclaration; }): void; setTransform(el: HTMLElement|SVGElement, value: string): void; animateTransform(el: HTMLElement|Polymer.PolymerElement, properties: { propName: string; postfix?: string; from: number; to: number; }, options: { duration?: number; easing?: string; fill?: 'forwards'|'backwards'|'both'; }): Animation; __: I18N; } } export type SharedWindow = Window & { Promise: typeof Promise; onExists<T extends keyof C, C = Window>(key: T, container?: C): PromiseLike<C[T]>; onExistsChain<C, T1 extends keyof C, T2 extends keyof C[T1], T3 extends keyof C[T1][T2], T4 extends keyof C[T1][T2][T3], T5 extends keyof C[T1][T2][T3][T4]>(container: C, key1: T1): PromiseLike<C[T1]>; onExistsChain<C, T1 extends keyof C, T2 extends keyof C[T1], T3 extends keyof C[T1][T2], T4 extends keyof C[T1][T2][T3], T5 extends keyof C[T1][T2][T3][T4]>(container: C, key1: T1, key2: T2): PromiseLike<C[T1][T2]>; onExistsChain<C, T1 extends keyof C, T2 extends keyof C[T1], T3 extends keyof C[T1][T2], T4 extends keyof C[T1][T2][T3], T5 extends keyof C[T1][T2][T3][T4]>(container: C, key1: T1, key2: T2, key3: T3): PromiseLike<C[T1][T2][T3]>; onExistsChain<C, T1 extends keyof C, T2 extends keyof C[T1], T3 extends keyof C[T1][T2], T4 extends keyof C[T1][T2][T3], T5 extends keyof C[T1][T2][T3][T4]>(container: C, key1: T1, key2: T2, key3: T3, key4: T4): PromiseLike<C[T1][T2][T3][T4]>; onExistsChain<C, T1 extends keyof C, T2 extends keyof C[T1], T3 extends keyof C[T1][T2], T4 extends keyof C[T1][T2][T3], T5 extends keyof C[T1][T2][T3][T4]>(container: C, key1: T1, key2: T2, key3: T3, key4: T4, key5: T5): PromiseLike<C[T1][T2][T3][T4][T5]>; onExistsChain<C, T1 extends keyof C, T2 extends keyof C[T1], T3 extends keyof C[T1][T2], T4 extends keyof C[T1][T2][T3], T5 extends keyof C[T1][T2][T3][T4]>(container: C, key1: T1, key2?: T2, key3?: T3, key4?: T4, key5?: T5): PromiseLike<C[T1][T2][T3][T4][T5]>| PromiseLike<C[T1][T2][T3][T4]>|PromiseLike<C[T1][T2][T3]>|PromiseLike<C[T1][T2]>|PromiseLike<C[T1]>; objectify<T>(fn: T): T; register(...fns: any[]): void; with<T>(initializer: () => Withable, fn: () => T): T; withAsync<T>(initializer: () => Promise<Withable>, fn: () => Promise<T>): Promise<T>; setDisplayFlex(el: { style: CSSStyleDeclaration; }): void; setTransform(el: HTMLElement|SVGElement, value: string): void; animateTransform(el: HTMLElement, properties: { propName: string; postfix?: string; from: number; to: number; }, options: { duration?: number; easing?: string; fill?: 'forwards'|'backwards'|'both'; }): Animation; __: I18N; }; (() => { if (window.onExists) { return; } function isUndefined(val: any): val is void { return typeof val === 'undefined' || val === null; } class RoughPromise<T> implements PromiseLike<T> { private _val: T = null; private _state: 'pending'|'resolved'|'rejected' = 'pending'; private _done: boolean = false; private _resolveListeners: ((value: T) => void)[] = []; private _rejectListeners: ((value: T) => void)[] = []; constructor(initializer: (resolve: (value: T) => void, reject: (err: any) => void) => void) { initializer((val: T) => { if (this._done) { return; } this._done = true; this._val = val; this._state = 'resolved'; this._resolveListeners.forEach((listener) => { listener(val); }); }, (err) => { if (this._done) { return; } this._done = true; this._val = err; this._state = 'rejected'; this._rejectListeners.forEach((listener) => { listener(err); }); }); } then<TResult1 = T, TResult2 = never>(onfulfilled?: ((value: T) => TResult1 | PromiseLike<TResult1>) | undefined | null, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | undefined | null): PromiseLike<TResult1 | TResult2> { if (!onfulfilled) { return this as any; } if (this._done && this._state === 'resolved') { onfulfilled(this._val); } else { this._resolveListeners.push(onfulfilled); } if (!onrejected) { return this as any; } if (this._done && this._state === 'rejected') { onrejected(this._val); } else { this._rejectListeners.push(onrejected); } return this as any; } static chain<T>(initializers: (() => RoughPromise<any>)[]) { return new RoughPromise<T>((resolve) => { if (!initializers[0]) { resolve(null); return; } initializers[0]().then((result) => { if (initializers[1]) { RoughPromise.chain<T>(initializers.slice(1)).then((result) => { resolve(result); }); } else { resolve(result); } }); }); } } window.onExists = <T extends keyof C, C = Window>(key: T, container?: C): PromiseLike<C[T]> => { if (!container) { container = window as any; } const prom = (window.Promise || RoughPromise) as any; return new prom((resolve: (result: C[T]) => void) => { if (key in container && !isUndefined(container[key])) { resolve(container[key]); return; } const interval = window.setInterval(() => { if (key in container && !isUndefined(container[key])) { window.clearInterval(interval); resolve(container[key]); } }, 50); }); } const objectify = <T>(fn: T): T => { const obj: Partial<T> = {}; Object.getOwnPropertyNames(fn).forEach((key: string) => { obj[key as keyof T] = fn[key as keyof T]; }); return obj as T; } const ElementI18nManager = (() => { interface RawLangFile { [key: string]: { message: string; description?: string; placeholders?: { [key: string]: { key: string; example?: string; content: string; } } } } interface LangItem { message: string; placeholders: { index: number; expr: RegExp; content: string; }[]; }; interface LangFile { [key: string]: LangItem; }; class Lang { static readonly DEFAULT_LANG = LANGS.EN; static readonly SUPPORTED_LANGS: LANGS[] = [LANGS.EN]; private _currentLangFile: LangFile = null; private _lang: LANGS = null; private _listeners: I18NElement[] = []; private _languageChangeListeners: (() => void)[] = []; ready = (async () => { // Load the "current" language this._lang = await this.fetchLang(); this._currentLangFile = await this.Files.loadLang(this._lang); this._listeners.forEach((listener) => { listener.langReady = true; listener.onLangChanged && listener.onLangChanged.call(listener, this._lang, null); }); })(); Files = class LangFiles { private static _loadedLangs: { [key in LANGS]?: LangFile; } = {}; private static _isWebPageEnv() { return location.protocol === 'http:' || location.protocol === 'https:'; } private static _loadFile(name: string): Promise<string> { return new window.Promise((resolve, reject) => { const xhr: XMLHttpRequest = new window.XMLHttpRequest(); const url = this._isWebPageEnv() ? `../${name}` : browserAPI.runtime.getURL(name); xhr.open('GET', url); xhr.onreadystatechange = () => { if (xhr.readyState === window.XMLHttpRequest.DONE) { if (xhr.status === 200) { resolve(xhr.responseText); } else { reject(new Error('Failed XHR')); } } } xhr.send(); }); } private static _parseLang(str: string): LangFile { const rawParsed = JSON.parse(str) as RawLangFile; const parsed: LangFile = {}; for (const key in rawParsed) { if (key === '$schema' || key === 'comments') continue; const item = rawParsed[key]; const placeholders: { content: string; expr: RegExp; index: number; }[] = []; for (const key in item.placeholders || {}) { const { content } = item.placeholders[key]; placeholders.push({ index: placeholders.length, content, expr: new RegExp(`\\$${key}\\$`, 'gi') }); } parsed[key] = { message: item.message || `{{${key}}}`, placeholders: placeholders }; } return parsed; } static async loadLang(lang: LANGS) { if (this._loadedLangs[lang]) { return this._loadedLangs[lang]; } try { const langData = await this._loadFile(`_locales/${lang}/messages.json`); const parsed = this._parseLang(langData); this._loadedLangs[lang] = parsed; return parsed; } catch(e) { throw e; } } static getLangFile(lang: LANGS): LangFile|undefined { return this._loadedLangs[lang]; } } private async _getDefaultLang() { const acceptLangs = await browserAPI.i18n.getAcceptLanguages(); if (acceptLangs.indexOf(Lang.DEFAULT_LANG) > -1) return Lang.DEFAULT_LANG; const availableLangs = acceptLangs .filter(i => Lang.SUPPORTED_LANGS.indexOf(i as LANGS) !== -1); return availableLangs[0] || Lang.DEFAULT_LANG; } async fetchLang() { await window.onExists('browserAPI'); const { lang } = await browserAPI.storage.local.get('lang') as { lang?: LANGS; }; if (!lang) { const newLang = await this._getDefaultLang(); browserAPI.storage.local.set({ lang: newLang }); return newLang as LANGS; } return lang; } async getLang() { if (this._lang) return this._lang; return this.fetchLang(); } async setLang(lang: LANGS) { const prevLang = await this.getLang(); await browserAPI.storage.local.set({ lang: lang }); this._listeners.forEach(l => l.onLangChange && l.onLangChange.call(l, lang, prevLang)); this.ready = (async () => { this._currentLangFile = await this.Files.loadLang(lang); this._listeners.forEach((listener) => { this._lang = lang; listener.lang = lang; listener.langReady = true; this._languageChangeListeners.forEach(fn => fn()); this._listeners .forEach(l => l.onLangChanged && l.onLangChanged.call(l, lang, prevLang)); }); })(); } async langReady(lang: LANGS) { return this.Files.getLangFile(lang) !== undefined; } static readonly INDEX_REGEXPS = [ new RegExp(/\$1/g), new RegExp(/\$2/g), new RegExp(/\$3/g), new RegExp(/\$4/g), new RegExp(/\$5/g), new RegExp(/\$6/g), new RegExp(/\$7/g), new RegExp(/\$8/g), new RegExp(/\$9/g) ]; // Basically the same as __sync but optimistic private _getMessage(key: string, ...replacements: string[]): string { const entryData = this._currentLangFile[key]; if (!entryData) return `{{${key}}}`; let { message, placeholders } = entryData; let placeholderContents = placeholders.map(p => p.content); if (!message) return `{{${key}}}`; for (let i = 0; i < replacements.length; i++) { const expr = Lang.INDEX_REGEXPS[i]; message = message.replace(expr, replacements[i]); placeholderContents = placeholderContents.map((placeholder) => { return placeholder.replace(expr, replacements[i]); }); } for (const { expr, index } of placeholders) { message = message.replace(expr, placeholderContents[index]); } return message; } __sync(key: string, ...replacements: (string|number)[]) { if (!this._lang || !this._currentLangFile) return `{{${key}}}`; return this._getMessage( key, ...replacements.map(s => s + '')); } async __(key: string, ...replacements: (string|number)[]): Promise<string> { await this.ready; const msg = this._getMessage(key, ...replacements.map(s => s + '')); return msg; } addLoadListener(fn: I18NElement) { if (this._listeners.indexOf(fn) !== -1) return; this._listeners.push(fn); if (this._lang) { fn.lang = this._lang; if (this.Files.getLangFile(this._lang)) { fn.langReady = true; } } } addLanguageChangeListener(fn: () => void) { this._languageChangeListeners.push(fn); } } const langInstance = new Lang(); const boundGetMessage = langInstance.__.bind(langInstance); const __: I18N = ((key: string, ...replacements: (string|number)[]) => { return boundGetMessage(key, ...replacements); }) as I18N; __.sync = langInstance.__sync.bind(langInstance); __.getLang = langInstance.getLang.bind(langInstance); __.setLang = langInstance.setLang.bind(langInstance); __.SUPPORTED_LANGS = Lang.SUPPORTED_LANGS; __.addListener = langInstance.addLanguageChangeListener.bind(langInstance); __.ready = () => langInstance.ready; window.__ = __; class ElementI18nManager { static instance = langInstance; static __(_lang: string, _langReady: boolean, key: string, ...replacements: (string|number)[]): string { this.instance.addLoadListener(this as any); return this.instance.__sync(key, ...replacements); } static __exec(_lang: string, _langReady: boolean, key: string, ...replacements: (string|number|((...args: string[]) => string|number))[]): string { const finalArgs = []; for (let i = 0; i < replacements.length; i++) { const arg = replacements[i]; if (typeof arg === 'string') { finalArgs.push(arg); } else if (typeof arg === 'function') { // Use the next N replacements as parameters const result = arg.bind(this)(...replacements.slice(i + 1, i + 1 + arg.length) as string[]); finalArgs.push(result); } } this.instance.addLoadListener(this as any); return this.instance.__sync(key, ...finalArgs); } static __async(key: string, ...replacements: (string|number)[]): Promise<string> { this.instance.addLoadListener(this as any); return this.instance.__(key, ...replacements); } static ___(key: string, ...replacements: (string|number)[]): string { this.instance.addLoadListener(this as any); return this.instance.__sync(key, ...replacements); } } return ElementI18nManager; })(); function addI18nHook(object: any) { object.properties = object.properties || {}; object.properties.lang = { type: String, notify: true, value: null }; object.properties.langReady = { type: Boolean, notify: true, value: false }; } const register = (fn: any) => { let objectified = {...fn, ...ElementI18nManager}; const prevReady = objectified.ready; addI18nHook(objectified); window.Polymer({...objectified, ...{ ready(this: Polymer.InitializerProperties & Polymer.PolymerElement) { this.classList.add(`browser-${BrowserAPI.getBrowser()}`); if (prevReady && typeof prevReady === 'function') { prevReady.apply(this, []); } } }}); } window.withAsync = async <T>(initializer: () => Promise<Withable>, fn: () => Promise<T>): Promise<T> => { const toRun = await initializer(); const res = await fn(); await toRun(); return res; } window.with = <T>(initializer: () => Withable, fn: () => T): T => { const toRun = initializer(); const res = fn(); toRun(); return res; } function propertyPersists<T extends keyof CSSStyleDeclaration>(property: T, value: CSSStyleDeclaration[T]) { const dummyEl = document.createElement('div'); dummyEl.style[property] = value; return dummyEl.style[property] === value; } let _supportsFlexUnprefixed: boolean = null; let _supportsTransformUnprefixed: boolean = window.getComputedStyle && 'transform' in window.getComputedStyle(document.documentElement, ''); window.setDisplayFlex = (el: HTMLElement|SVGElement) => { if (_supportsFlexUnprefixed === null) { _supportsFlexUnprefixed = propertyPersists('display', 'flex'); } if (_supportsFlexUnprefixed) { el.style.display = 'flex'; } else { el.style.display = '-webkit-flex'; } } window.setTransform = (el: HTMLElement|SVGElement, value: string) => { if (_supportsTransformUnprefixed) { el.style.transform = value; } else { el.style.webkitTransform = value; } } function createAnimation(from: string, to: string, doAnimation: (from: string, to: string, done: () => void) => { cancel(): void; }): Animation { let currentAnimation: { cancel(): void; } = null; var retVal: Animation = { onfinish: null, oncancel: null, cancel() { currentAnimation && currentAnimation.cancel(); this.oncancel && this.oncancel.apply(this, { currentTime: Date.now(), timelineTime: null }); }, play() { currentAnimation && currentAnimation.cancel(); currentAnimation = doAnimation(from, to, () => { this.onfinish && this.onfinish.apply(this, { currentTime: Date.now(), timelineTime: null }); }); }, reverse() { currentAnimation && currentAnimation.cancel(); currentAnimation = doAnimation(to, from, () => { this.onfinish && this.onfinish.apply(this, { currentTime: Date.now(), timelineTime: null }); }); }, pause() {}, finish() {}, currentTime: 0, effect: { getTiming(): EffectTiming { return { delay: 0, direction: 'normal', fill: 'both' } }, updateTiming(_timing?: OptionalEffectTiming) { }, getComputedTiming() { return { endTime: 0, activeDuration: 0, currentIteration: 0, localTime: 0, progress: null } } }, updatePlaybackRate(_playbackRate: number) {}, addEventListener(_type: string, _listener: EventListenerOrEventListenerObject) {}, removeEventListener(_type: string, _listener: EventListenerOrEventListenerObject) {}, dispatchEvent(_event: Event) { return true }, finished: Promise.resolve(retVal), pending: false, startTime: Date.now(), id: '', ready: Promise.resolve(retVal), playState: 'finished', playbackRate: 1.0, timeline: { currentTime: Date.now() }, } doAnimation(from, to, () => { retVal.onfinish && retVal.onfinish.apply(retVal, { currentTime: Date.now(), timelineTime: null }); }); return retVal; } window.animateTransform = (el: HTMLElement, properties: { propName: string; postfix?: string; from: number; to: number; }, options: { duration?: number; easing?: string; fill?: 'forwards'|'backwards'|'both'; }) => { const { from, propName, to, postfix } = properties; if (_supportsTransformUnprefixed && !el.__isAnimationJqueryPolyfill) { return el.animate([{ transform: `${propName}(${from}${postfix})` }, { transform: `${propName}(${to}${postfix})` }], options); } else { const diff = to - from; const diffPercentage = diff / 100; el.style.webkitTransform = `${propName}(${from}${postfix})`; const dummy = document.createElement('div'); return createAnimation('0px', '100px', (fromDummy, toDummy, done) => { dummy.style.height = fromDummy; $(dummy).animate({ height: toDummy }, { duration: options.duration || 500, step(now: number) { const progress = from + (diffPercentage * now); el.style.webkitTransform = `${propName}(${progress}${postfix})`; }, complete() { el.style.webkitTransform = `${propName}(${toDummy}${postfix})`; done(); } }); return { cancel() { $(dummy).stop(); } } }); } } if (typeof Event !== 'undefined' && location.href.indexOf('background.html') === -1) { window.onExists('Promise').then(() => { window.onExists('Polymer').then(() => { window.objectify = objectify; window.register = register; const event = new Event('RegisterReady'); window.dispatchEvent(event); }); }); } window.onExistsChain = <C, T1 extends keyof C, T2 extends keyof C[T1], T3 extends keyof C[T1][T2], T4 extends keyof C[T1][T2][T3], T5 extends keyof C[T1][T2][T3][T4]>(container: C, key1: T1, key2?: T2, key3?: T3, key4?: T4, key5?: T5): PromiseLike<C[T1][T2][T3][T4][T5]>| PromiseLike<C[T1][T2][T3][T4]>|PromiseLike<C[T1][T2][T3]>|PromiseLike<C[T1][T2]>|PromiseLike<C[T1]> => { const prom = (window.Promise || RoughPromise) as any; return new prom((resolve: (result: C[T1][T2][T3][T4]) => void) => { let state: any = container; const keys = [key1, key2, key3, key4, key5]; RoughPromise.chain(keys.filter(key => !!key).map((key) => { return () => { return new prom((resolveInner: (result: any) => void) => { window.onExists(key as keyof typeof state, state).then((result) => { state = result; resolveInner(result); }); }); } })).then((finalResult) => { resolve(finalResult as any); }); }); }; })();
the_stack
import { assertCardRule, assertAssignmentRule, assertFlagRule, assertOnlyRule, assertBindingRule, assertContainsRule, assertCaretValueRule, assertObeysRule, assertInsertRule } from '../testhelpers/asserts'; import { FshCanonical, FshCode, FshQuantity, FshRatio, FshReference, ParamRuleSet } from '../../src/fshtypes'; import { loggerSpy } from '../testhelpers/loggerSpy'; import { stats } from '../../src/utils/FSHLogger'; import { importSingleText } from '../testhelpers/importSingleText'; import { FSHImporter, importText, RawFSH } from '../../src/import'; import { EOL } from 'os'; import { leftAlign } from '../utils/leftAlign'; describe('FSHImporter', () => { describe('Profile', () => { describe('#sdMetadata', () => { it('should parse the simplest possible profile', () => { const input = leftAlign(` Profile: ObservationProfile Parent: Observation `); const result = importSingleText(input, 'Simple.fsh'); expect(result.profiles.size).toBe(1); const profile = result.profiles.get('ObservationProfile'); expect(profile.name).toBe('ObservationProfile'); expect(profile.parent).toBe('Observation'); // if no id is explicitly set, should default to name expect(profile.id).toBe('ObservationProfile'); expect(profile.sourceInfo.location).toEqual({ startLine: 2, startColumn: 1, endLine: 3, endColumn: 19 }); expect(profile.sourceInfo.file).toBe('Simple.fsh'); }); it('should parse profile with name matching various possible tokens recognized as name', () => { // This basically exercises all the tokens we accept for name: // SEQUENCE | NUMBER | KW_MS | KW_SU | KW_TU | KW_NORMATIVE | KW_DRAFT | KW_CODES | KW_VSREFERENCE | KW_SYSTEM; // Since we'll do the same thing over and over (and over), create a function for it const testToken = (token: string) => { const input = leftAlign(` Profile: ${token} Parent: Observation * value[x] only boolean `); const result = importSingleText(input); expect(loggerSpy.getAllLogs('error')).toHaveLength(0); expect(result).toBeDefined(); expect(result.profiles.size).toBe(1); const profile = result.profiles.get(token); expect(profile).toBeDefined(); expect(profile.name).toBe(token); }; testToken('MyProfile'); // SEQUENCE testToken('123'); // NUMBER testToken('MS'); // KW_MS testToken('SU'); // KW_SU testToken('TU'); // KW_TU testToken('N'); // KW_NORMATIVE testToken('D'); // KW_DRAFT testToken('codes'); // KW_CODES testToken('valueset'); // KW_VSREFERENCE testToken('system'); // KW_SYSTEM }); it('should parse profile with additional metadata properties', () => { const input = leftAlign(` Profile: ObservationProfile Parent: Observation Id: observation-profile Title: "An Observation Profile" Description: "A profile on Observation" `); const result = importSingleText(input); expect(result.profiles.size).toBe(1); const profile = result.profiles.get('ObservationProfile'); expect(profile.name).toBe('ObservationProfile'); expect(profile.parent).toBe('Observation'); expect(profile.id).toBe('observation-profile'); expect(profile.title).toBe('An Observation Profile'); expect(profile.description).toBe('A profile on Observation'); expect(profile.sourceInfo.location).toEqual({ startLine: 2, startColumn: 1, endLine: 6, endColumn: 39 }); }); it('should parse profile with numeric name, parent, and id', () => { const input = leftAlign(` Profile: 123 Parent: 456 Id: 789 `); const result = importSingleText(input); expect(result.profiles.size).toBe(1); const profile = result.profiles.get('123'); expect(profile.name).toBe('123'); expect(profile.parent).toBe('456'); expect(profile.id).toBe('789'); }); it('should properly parse a multi-string description', () => { const input = leftAlign(` Profile: ObservationProfile Parent: Observation Description: """ This is a multi-string description with a couple of paragraphs. This is the second paragraph. It has bullet points w/ indentation: * Bullet 1 * Bullet A * Bullet B * Bullet i * Bullet C * Bullet 2 """ `); const result = importSingleText(input); expect(result.profiles.size).toBe(1); const profile = result.profiles.get('ObservationProfile'); const expectedDescriptionLines = [ 'This is a multi-string description', 'with a couple of paragraphs.', '', 'This is the second paragraph. It has bullet points w/ indentation:', '', '* Bullet 1', ' * Bullet A', ' * Bullet B', ' * Bullet i', ' * Bullet C', '* Bullet 2' ]; expect(profile.description).toBe(expectedDescriptionLines.join('\n')); }); it('should accept and translate an alias for the parent', () => { const input = leftAlign(` Alias: OBS = http://hl7.org/fhir/StructureDefinition/Observation Profile: ObservationProfile Parent: OBS `); const result = importSingleText(input); expect(result.profiles.size).toBe(1); const profile = result.profiles.get('ObservationProfile'); expect(profile.name).toBe('ObservationProfile'); expect(profile.parent).toBe('http://hl7.org/fhir/StructureDefinition/Observation'); }); it('should only apply each metadata attribute the first time it is declared', () => { const input = leftAlign(` Profile: ObservationProfile Parent: Observation Id: observation-profile Title: "An Observation Profile" Description: "A profile on Observation" Parent: DuplicateObservation Id: duplicate-observation-profile Title: "Duplicate Observation Profile" Description: "A duplicated profile on Observation" `); const result = importSingleText(input); expect(result.profiles.size).toBe(1); const profile = result.profiles.get('ObservationProfile'); expect(profile.name).toBe('ObservationProfile'); expect(profile.id).toBe('observation-profile'); expect(profile.title).toBe('An Observation Profile'); expect(profile.description).toBe('A profile on Observation'); }); it('should log an error when encountering a duplicate metadata attribute', () => { const input = leftAlign(` Profile: ObservationProfile Parent: Observation Id: observation-profile Title: "An Observation Profile" Description: "A profile on Observation" Title: "Duplicate Observation Profile" Description: "A duplicated profile on Observation" `); importSingleText(input, 'Dupe.fsh'); expect(loggerSpy.getMessageAtIndex(-2, 'error')).toMatch(/File: Dupe\.fsh.*Line: 7\D*/s); expect(loggerSpy.getLastMessage('error')).toMatch(/File: Dupe\.fsh.*Line: 8\D*/s); }); it('should log an error and skip the profile when encountering a profile with a name used by another profile', () => { const input = leftAlign(` Profile: ObservationProfile Parent: Observation Title: "First Observation Profile" Profile: ObservationProfile Parent: Observation Title: "Second Observation Profile" `); const result = importSingleText(input, 'SameName.fsh'); expect(result.profiles.size).toBe(1); const profile = result.profiles.get('ObservationProfile'); expect(profile.title).toBe('First Observation Profile'); expect(loggerSpy.getLastMessage('error')).toMatch( /Profile named ObservationProfile already exists/s ); expect(loggerSpy.getLastMessage('error')).toMatch(/File: SameName\.fsh.*Line: 6 - 8\D*/s); }); it('should log an error and skip the profile when encountering an profile with a name used by another profile in another file', () => { const input1 = ` Profile: SameProfile Title: "First Profile" Parent: Observation `; const input2 = ` Profile: SameProfile Title: "Second Profile" Parent: Observation `; const result = importText([ new RawFSH(input1, 'File1.fsh'), new RawFSH(input2, 'File2.fsh') ]); expect(result.reduce((sum, d2) => sum + d2.profiles.size, 0)).toBe(1); const p = result[0].profiles.get('SameProfile'); expect(p.title).toBe('First Profile'); expect(loggerSpy.getLastMessage('error')).toMatch( /Profile named SameProfile already exists/s ); expect(loggerSpy.getLastMessage('error')).toMatch(/File: File2\.fsh.*Line: 2 - 4\D*/s); }); it('should log an error when the deprecated Mixins keyword is used', () => { const input = leftAlign(` Profile: SomeProfile Parent: Observation Mixins: RuleSet1 and RuleSet2 `); const result = importSingleText(input, 'Deprecated.fsh'); expect(result.profiles.size).toBe(1); const extension = result.profiles.get('SomeProfile'); expect(extension.name).toBe('SomeProfile'); expect(loggerSpy.getLastMessage('error')).toMatch( /The 'Mixins' keyword is no longer supported\./s ); expect(loggerSpy.getLastMessage('error')).toMatch(/File: Deprecated\.fsh.*Line: 4\D*/s); }); }); describe('#cardRule', () => { it('should parse simple card rules', () => { const input = leftAlign(` Profile: ObservationProfile Parent: Observation * category 1..5 * value[x] 1..1 * component 2..* `); const result = importSingleText(input); const profile = result.profiles.get('ObservationProfile'); expect(profile.rules).toHaveLength(3); assertCardRule(profile.rules[0], 'category', 1, 5); assertCardRule(profile.rules[1], 'value[x]', 1, 1); assertCardRule(profile.rules[2], 'component', 2, '*'); }); it('should parse card rule with only min', () => { const input = leftAlign(` Profile: ObservationProfile Parent: Observation * category 1.. `); const result = importSingleText(input); const profile = result.profiles.get('ObservationProfile'); expect(profile.rules).toHaveLength(1); assertCardRule(profile.rules[0], 'category', 1, ''); // Unspecified max }); it('should parse card rule with only max', () => { const input = leftAlign(` Profile: ObservationProfile Parent: Observation * category ..5 `); const result = importSingleText(input); const profile = result.profiles.get('ObservationProfile'); expect(profile.rules).toHaveLength(1); assertCardRule(profile.rules[0], 'category', NaN, '5'); // Unspecified min }); it('should log an error if neither side is specified', () => { const input = leftAlign(` Profile: ObservationProfile Parent: Observation * category .. `); const result = importSingleText(input, 'BadCard.fsh'); const profile = result.profiles.get('ObservationProfile'); expect(profile.rules).toHaveLength(1); // Rule is still set and element's current cardinalities will be used at export expect(loggerSpy.getLastMessage('error')).toMatch( /Neither side of the cardinality was specified on path \"category\". A min, max, or both need to be specified.\D*/s ); expect(loggerSpy.getLastMessage('error')).toMatch(/File: BadCard\.fsh.*Line: 4\D*/s); }); it('should parse card rules w/ flags', () => { const input = leftAlign(` Profile: ObservationProfile Parent: Observation * category 1..5 MS * value[x] 1..1 ?! * component 2..* SU * interpretation 1..* TU * note 0..11 N * bodySite 1..1 D `); const result = importSingleText(input); const profile = result.profiles.get('ObservationProfile'); expect(profile.rules).toHaveLength(12); assertCardRule(profile.rules[0], 'category', 1, 5); assertFlagRule( profile.rules[1], 'category', true, undefined, undefined, undefined, undefined, undefined ); assertCardRule(profile.rules[2], 'value[x]', 1, 1); assertFlagRule( profile.rules[3], 'value[x]', undefined, undefined, true, undefined, undefined, undefined ); assertCardRule(profile.rules[4], 'component', 2, '*'); assertFlagRule( profile.rules[5], 'component', undefined, true, undefined, undefined, undefined, undefined ); assertCardRule(profile.rules[6], 'interpretation', 1, '*'); assertFlagRule( profile.rules[7], 'interpretation', undefined, undefined, undefined, true, undefined, undefined ); assertCardRule(profile.rules[8], 'note', 0, '11'); assertFlagRule( profile.rules[9], 'note', undefined, undefined, undefined, undefined, true, undefined ); assertCardRule(profile.rules[10], 'bodySite', 1, '1'); assertFlagRule( profile.rules[11], 'bodySite', undefined, undefined, undefined, undefined, undefined, true ); }); it('should parse card rules w/ multiple flags', () => { const input = leftAlign(` Profile: ObservationProfile Parent: Observation * category 1..5 MS ?! TU * value[x] 1..1 ?! SU N * component 2..* SU MS D `); const result = importSingleText(input); const profile = result.profiles.get('ObservationProfile'); expect(profile.rules).toHaveLength(6); assertCardRule(profile.rules[0], 'category', 1, 5); assertFlagRule( profile.rules[1], 'category', true, undefined, true, true, undefined, undefined ); assertCardRule(profile.rules[2], 'value[x]', 1, 1); assertFlagRule( profile.rules[3], 'value[x]', undefined, true, true, undefined, true, undefined ); assertCardRule(profile.rules[4], 'component', 2, '*'); assertFlagRule( profile.rules[5], 'component', true, true, undefined, undefined, undefined, true ); }); }); describe('#flagRule', () => { it('should parse single-path single-value flag rules', () => { const input = leftAlign(` Profile: ObservationProfile Parent: Observation * category MS * value[x] ?! * component SU * interpretation TU * note N * bodySite D `); const result = importSingleText(input); const profile = result.profiles.get('ObservationProfile'); expect(profile.rules).toHaveLength(6); assertFlagRule( profile.rules[0], 'category', true, undefined, undefined, undefined, undefined, undefined ); assertFlagRule( profile.rules[1], 'value[x]', undefined, undefined, true, undefined, undefined, undefined ); assertFlagRule( profile.rules[2], 'component', undefined, true, undefined, undefined, undefined, undefined ); assertFlagRule( profile.rules[3], 'interpretation', undefined, undefined, undefined, true, undefined, undefined ); assertFlagRule( profile.rules[4], 'note', undefined, undefined, undefined, undefined, true, undefined ); assertFlagRule( profile.rules[5], 'bodySite', undefined, undefined, undefined, undefined, undefined, true ); }); it('should parse single-path multi-value flag rules', () => { const input = leftAlign(` Profile: ObservationProfile Parent: Observation * category MS ?! N * value[x] ?! SU D * component MS SU ?! TU `); const result = importSingleText(input); const profile = result.profiles.get('ObservationProfile'); expect(profile.rules).toHaveLength(3); assertFlagRule( profile.rules[0], 'category', true, undefined, true, undefined, true, undefined ); assertFlagRule( profile.rules[1], 'value[x]', undefined, true, true, undefined, undefined, true ); assertFlagRule(profile.rules[2], 'component', true, true, true, true, undefined, undefined); }); it('should parse multi-path single-value flag rules', () => { const input = leftAlign(` Profile: ObservationProfile Parent: Observation * category and value[x] and component MS * subject and focus ?! * interpretation and note N `); const result = importSingleText(input); const profile = result.profiles.get('ObservationProfile'); expect(profile.rules).toHaveLength(7); assertFlagRule( profile.rules[0], 'category', true, undefined, undefined, undefined, undefined, undefined ); assertFlagRule( profile.rules[1], 'value[x]', true, undefined, undefined, undefined, undefined, undefined ); assertFlagRule( profile.rules[2], 'component', true, undefined, undefined, undefined, undefined, undefined ); assertFlagRule( profile.rules[3], 'subject', undefined, undefined, true, undefined, undefined, undefined ); assertFlagRule( profile.rules[4], 'focus', undefined, undefined, true, undefined, undefined, undefined ); assertFlagRule( profile.rules[5], 'interpretation', undefined, undefined, undefined, undefined, true, undefined ); assertFlagRule( profile.rules[6], 'note', undefined, undefined, undefined, undefined, true, undefined ); }); it('should parse multi-path multi-value flag rules', () => { const input = leftAlign(` Profile: ObservationProfile Parent: Observation * category and value[x] and component MS SU N * subject and focus ?! SU TU `); const result = importSingleText(input); const profile = result.profiles.get('ObservationProfile'); expect(profile.rules).toHaveLength(5); assertFlagRule( profile.rules[0], 'category', true, true, undefined, undefined, true, undefined ); assertFlagRule( profile.rules[1], 'value[x]', true, true, undefined, undefined, true, undefined ); assertFlagRule( profile.rules[2], 'component', true, true, undefined, undefined, true, undefined ); assertFlagRule( profile.rules[3], 'subject', undefined, true, true, true, undefined, undefined ); assertFlagRule( profile.rules[4], 'focus', undefined, true, true, true, undefined, undefined ); }); it('should log an error when paths are listed with commas', () => { const input = leftAlign(` Profile: ObservationProfile Parent: Observation * category, value[x] , component MS SU N `); const result = importSingleText(input, 'Deprecated.fsh'); const profile = result.profiles.get('ObservationProfile'); expect(profile).toBeDefined(); expect(loggerSpy.getLastMessage('error')).toMatch( /Using ',' to list items is no longer supported/s ); expect(loggerSpy.getLastMessage('error')).toMatch(/File: Deprecated\.fsh.*Line: 4\D*/s); }); }); describe('#BindingRule', () => { it('should parse value set rules w/ names and strengths', () => { const input = leftAlign(` Profile: ObservationProfile Parent: Observation * category from CategoryValueSet (required) * code from CodeValueSet (extensible) * valueCodeableConcept from ValueValueSet (preferred) * component.code from ComponentCodeValueSet (example) `); const result = importSingleText(input); const profile = result.profiles.get('ObservationProfile'); expect(profile.rules).toHaveLength(4); assertBindingRule(profile.rules[0], 'category', 'CategoryValueSet', 'required'); assertBindingRule(profile.rules[1], 'code', 'CodeValueSet', 'extensible'); assertBindingRule(profile.rules[2], 'valueCodeableConcept', 'ValueValueSet', 'preferred'); assertBindingRule(profile.rules[3], 'component.code', 'ComponentCodeValueSet', 'example'); }); it('should parse value set rules w/ urls and strengths', () => { const input = leftAlign(` Profile: ObservationProfile Parent: Observation * category from http://example.org/fhir/ValueSet/CategoryValueSet (required) * code from http://example.org/fhir/ValueSet/CodeValueSet (extensible) * valueCodeableConcept from http://example.org/fhir/ValueSet/ValueValueSet (preferred) * component.code from http://example.org/fhir/ValueSet/ComponentCodeValueSet (example) `); const result = importSingleText(input); const profile = result.profiles.get('ObservationProfile'); expect(profile.rules).toHaveLength(4); assertBindingRule( profile.rules[0], 'category', 'http://example.org/fhir/ValueSet/CategoryValueSet', 'required' ); assertBindingRule( profile.rules[1], 'code', 'http://example.org/fhir/ValueSet/CodeValueSet', 'extensible' ); assertBindingRule( profile.rules[2], 'valueCodeableConcept', 'http://example.org/fhir/ValueSet/ValueValueSet', 'preferred' ); assertBindingRule( profile.rules[3], 'component.code', 'http://example.org/fhir/ValueSet/ComponentCodeValueSet', 'example' ); }); it('should accept and translate aliases for value set URLs', () => { const input = leftAlign(` Alias: CAT = http://example.org/fhir/ValueSet/CategoryValueSet Alias: CODE = http://example.org/fhir/ValueSet/CodeValueSet Alias: VALUE = http://example.org/fhir/ValueSet/ValueValueSet Alias: COMP = http://example.org/fhir/ValueSet/ComponentCodeValueSet Profile: ObservationProfile Parent: Observation * category from CAT (required) * code from CODE (extensible) * valueCodeableConcept from VALUE (preferred) * component.code from COMP (example) `); const result = importSingleText(input); const profile = result.profiles.get('ObservationProfile'); expect(profile.rules).toHaveLength(4); assertBindingRule( profile.rules[0], 'category', 'http://example.org/fhir/ValueSet/CategoryValueSet', 'required' ); assertBindingRule( profile.rules[1], 'code', 'http://example.org/fhir/ValueSet/CodeValueSet', 'extensible' ); assertBindingRule( profile.rules[2], 'valueCodeableConcept', 'http://example.org/fhir/ValueSet/ValueValueSet', 'preferred' ); assertBindingRule( profile.rules[3], 'component.code', 'http://example.org/fhir/ValueSet/ComponentCodeValueSet', 'example' ); }); it('should parse value set rules w/ numeric names', () => { const input = leftAlign(` Profile: ObservationProfile Parent: Observation * category from 123 (required) * code from 456 (extensible) `); const result = importSingleText(input); const profile = result.profiles.get('ObservationProfile'); expect(profile.rules).toHaveLength(2); assertBindingRule(profile.rules[0], 'category', '123', 'required'); assertBindingRule(profile.rules[1], 'code', '456', 'extensible'); }); it('should parse value set rules w/ no strength and default to required', () => { const input = leftAlign(` Profile: ObservationProfile Parent: Observation * category from CategoryValueSet * code from http://example.org/fhir/ValueSet/CodeValueSet `); const result = importSingleText(input); const profile = result.profiles.get('ObservationProfile'); expect(profile.rules).toHaveLength(2); assertBindingRule(profile.rules[0], 'category', 'CategoryValueSet', 'required'); assertBindingRule( profile.rules[1], 'code', 'http://example.org/fhir/ValueSet/CodeValueSet', 'required' ); }); it('should parse value set rules on Quantity', () => { const input = leftAlign(` Profile: ObservationProfile Parent: Observation * valueQuantity from http://unitsofmeasure.org `); const result = importSingleText(input, 'UselessQuant.fsh'); const profile = result.profiles.get('ObservationProfile'); expect(profile.rules).toHaveLength(1); assertBindingRule( profile.rules[0], 'valueQuantity', 'http://unitsofmeasure.org', 'required' ); }); it('should log an error when parsing value set rules using the unit keyword', () => { const input = leftAlign(` Profile: ObservationProfile Parent: Observation * valueQuantity units from http://unitsofmeasure.org `); const result = importSingleText(input, 'Deprecated.fsh'); const profile = result.profiles.get('ObservationProfile'); expect(profile).toBeDefined(); expect(loggerSpy.getLastMessage('error')).toMatch( /The 'units' keyword is no longer supported.*File: Deprecated\.fsh.*Line: 4\D*/s ); }); }); describe('#assignmentRule', () => { it('should parse assigned value boolean rule', () => { const input = leftAlign(` Profile: ObservationProfile Parent: Observation * valueBoolean = true `); const result = importSingleText(input); const profile = result.profiles.get('ObservationProfile'); expect(profile.rules).toHaveLength(1); assertAssignmentRule(profile.rules[0], 'valueBoolean', true); }); it('should parse assigned value boolean rule with (exactly) modifier', () => { const input = leftAlign(` Profile: ObservationProfile Parent: Observation * valueBoolean = true (exactly) `); const result = importSingleText(input); const profile = result.profiles.get('ObservationProfile'); expect(profile.rules).toHaveLength(1); assertAssignmentRule(profile.rules[0], 'valueBoolean', true, true); }); it('should parse assigned value number (decimal) rule', () => { const input = leftAlign(` Profile: ObservationProfile Parent: Observation * valueDecimal = 1.23 `); const result = importSingleText(input); const profile = result.profiles.get('ObservationProfile'); expect(profile.rules).toHaveLength(1); assertAssignmentRule(profile.rules[0], 'valueDecimal', 1.23); }); it('should parse assigned value number (integer) rule', () => { const input = leftAlign(` Profile: ObservationProfile Parent: Observation * valueInteger = 123 `); const result = importSingleText(input); const profile = result.profiles.get('ObservationProfile'); expect(profile.rules).toHaveLength(1); assertAssignmentRule(profile.rules[0], 'valueInteger', BigInt(123)); }); it('should parse assigned value string rule', () => { const input = leftAlign(` Profile: ObservationProfile Parent: Observation * valueString = "hello world" `); const result = importSingleText(input); const profile = result.profiles.get('ObservationProfile'); expect(profile.rules).toHaveLength(1); assertAssignmentRule(profile.rules[0], 'valueString', 'hello world'); }); it('should parse assigned value multi-line string rule', () => { const input = leftAlign(` Profile: ObservationProfile Parent: Observation * valueString = """ hello world """ `); const result = importSingleText(input); const profile = result.profiles.get('ObservationProfile'); expect(profile.rules).toHaveLength(1); assertAssignmentRule(profile.rules[0], 'valueString', 'hello\nworld'); }); it('should parse assigned value date rule', () => { const input = leftAlign(` Profile: ObservationProfile Parent: Observation * valueDateTime = 2019-11-01T12:30:01.999Z `); const result = importSingleText(input); const profile = result.profiles.get('ObservationProfile'); expect(profile.rules).toHaveLength(1); // For now, treating dates like strings assertAssignmentRule(profile.rules[0], 'valueDateTime', '2019-11-01T12:30:01.999Z'); }); it('should parse assigned value time rule', () => { const input = leftAlign(` Profile: ObservationProfile Parent: Observation * valueTime = 12:30:01.999-05:00 `); const result = importSingleText(input); const profile = result.profiles.get('ObservationProfile'); expect(profile.rules).toHaveLength(1); // For now, treating dates like strings assertAssignmentRule(profile.rules[0], 'valueTime', '12:30:01.999-05:00'); }); it('should parse assigned value code rule', () => { const input = leftAlign(` Alias: LOINC = http://loinc.org Profile: ObservationProfile Parent: Observation * status = #final `); const result = importSingleText(input); const profile = result.profiles.get('ObservationProfile'); expect(profile.rules).toHaveLength(1); const expectedCode = new FshCode('final').withLocation([6, 12, 6, 17]).withFile(''); assertAssignmentRule(profile.rules[0], 'status', expectedCode); }); it('should parse assigned value CodeableConcept rule', () => { const input = leftAlign(` Alias: LOINC = http://loinc.org Profile: ObservationProfile Parent: Observation * valueCodeableConcept = LOINC#718-7 "Hemoglobin [Mass/volume] in Blood" `); const result = importSingleText(input); const profile = result.profiles.get('ObservationProfile'); expect(profile.rules).toHaveLength(1); const expectedCode = new FshCode( '718-7', 'http://loinc.org', 'Hemoglobin [Mass/volume] in Blood' ) .withLocation([6, 26, 6, 72]) .withFile(''); assertAssignmentRule(profile.rules[0], 'valueCodeableConcept', expectedCode); }); it('should parse assigned value CodeableConcept rule with (exactly) modifier', () => { const input = leftAlign(` Alias: LOINC = http://loinc.org Profile: ObservationProfile Parent: Observation * valueCodeableConcept = LOINC#718-7 "Hemoglobin [Mass/volume] in Blood" (exactly) `); const result = importSingleText(input); const profile = result.profiles.get('ObservationProfile'); expect(profile.rules).toHaveLength(1); const expectedCode = new FshCode( '718-7', 'http://loinc.org', 'Hemoglobin [Mass/volume] in Blood' ) .withLocation([6, 26, 6, 72]) .withFile(''); assertAssignmentRule(profile.rules[0], 'valueCodeableConcept', expectedCode, true); }); it('should parse an assigned value FSHCode rule with units on Quantity', () => { const input = leftAlign(` Profile: ObservationProfile Parent: Observation * valueQuantity = http://unitsofmeasure.org#cGy `); const result = importSingleText(input, 'UselessUnits.fsh'); const profile = result.profiles.get('ObservationProfile'); expect(profile.rules).toHaveLength(1); const expectedCode = new FshCode('cGy', 'http://unitsofmeasure.org') .withLocation([4, 19, 4, 47]) .withFile('UselessUnits.fsh'); assertAssignmentRule(profile.rules[0], 'valueQuantity', expectedCode); }); it('should log an error when parsing an assigned value FSHCode rule using the unit keyword', () => { const input = leftAlign(` Profile: ObservationProfile Parent: Observation * valueQuantity units = http://unitsofmeasure.org#cGy `); const result = importSingleText(input, 'Deprecated.fsh'); const profile = result.profiles.get('ObservationProfile'); expect(profile).toBeDefined(); expect(loggerSpy.getLastMessage('error')).toMatch( /The 'units' keyword is no longer supported.*File: Deprecated\.fsh.*Line: 4\D*/s ); }); it('should parse assigned value Quantity rule', () => { const input = leftAlign(` Profile: ObservationProfile Parent: Observation * valueQuantity = 1.5 'mm' `); const result = importSingleText(input); const profile = result.profiles.get('ObservationProfile'); expect(profile.rules).toHaveLength(1); const expectedQuantity = new FshQuantity( 1.5, new FshCode('mm', 'http://unitsofmeasure.org').withLocation([5, 23, 5, 26]).withFile('') ) .withLocation([5, 19, 5, 26]) .withFile(''); assertAssignmentRule(profile.rules[0], 'valueQuantity', expectedQuantity); }); it('should parse assigned value Quantity rule with unit display', () => { const input = leftAlign(` Profile: ObservationProfile Parent: Observation * valueQuantity = 155.0 '[lb_av]' "lb" `); const result = importSingleText(input); const profile = result.profiles.get('ObservationProfile'); expect(profile.rules).toHaveLength(1); const expectedQuantity = new FshQuantity( 155.0, new FshCode('[lb_av]', 'http://unitsofmeasure.org', 'lb') .withLocation([5, 25, 5, 33]) .withFile('') ) .withLocation([5, 19, 5, 38]) .withFile(''); assertAssignmentRule(profile.rules[0], 'valueQuantity', expectedQuantity); }); it('should parse assigned value Ratio rule', () => { const input = leftAlign(` Profile: ObservationProfile Parent: Observation * valueRatio = 130 'mg' : 1 'dL' `); const result = importSingleText(input); const profile = result.profiles.get('ObservationProfile'); expect(profile.rules).toHaveLength(1); const expectedRatio = new FshRatio( new FshQuantity( 130, new FshCode('mg', 'http://unitsofmeasure.org').withLocation([5, 20, 5, 23]).withFile('') ) .withLocation([5, 16, 5, 23]) .withFile(''), new FshQuantity( 1, new FshCode('dL', 'http://unitsofmeasure.org').withLocation([5, 29, 5, 32]).withFile('') ) .withLocation([5, 27, 5, 32]) .withFile('') ) .withLocation([5, 16, 5, 32]) .withFile(''); assertAssignmentRule(profile.rules[0], 'valueRatio', expectedRatio); }); it('should parse assigned value Ratio rule w/ numeric numerator', () => { const input = leftAlign(` Profile: ObservationProfile Parent: Observation * valueRatio = 130 : 1 'dL' `); const result = importSingleText(input); const profile = result.profiles.get('ObservationProfile'); expect(profile.rules).toHaveLength(1); const expectedRatio = new FshRatio( new FshQuantity(130).withLocation([5, 16, 5, 18]).withFile(''), new FshQuantity( 1, new FshCode('dL', 'http://unitsofmeasure.org').withLocation([5, 24, 5, 27]).withFile('') ) .withLocation([5, 22, 5, 27]) .withFile('') ) .withLocation([5, 16, 5, 27]) .withFile(''); assertAssignmentRule(profile.rules[0], 'valueRatio', expectedRatio); }); it('should parse assigned value Ratio rule w/ numeric denominator', () => { const input = leftAlign(` Profile: ObservationProfile Parent: Observation * valueRatio = 130 'mg' : 1 `); const result = importSingleText(input); const profile = result.profiles.get('ObservationProfile'); expect(profile.rules).toHaveLength(1); const expectedRatio = new FshRatio( new FshQuantity( 130, new FshCode('mg', 'http://unitsofmeasure.org').withLocation([5, 20, 5, 23]).withFile('') ) .withLocation([5, 16, 5, 23]) .withFile(''), new FshQuantity(1).withLocation([5, 27, 5, 27]).withFile('') ) .withLocation([5, 16, 5, 27]) .withFile(''); assertAssignmentRule(profile.rules[0], 'valueRatio', expectedRatio); }); it('should parse assigned value Ratio rule w/ numeric numerator and denominator', () => { const input = leftAlign(` Profile: ObservationProfile Parent: Observation * valueRatio = 130 : 1 `); const result = importSingleText(input); const profile = result.profiles.get('ObservationProfile'); expect(profile.rules).toHaveLength(1); const expectedRatio = new FshRatio( new FshQuantity(130).withLocation([5, 16, 5, 18]).withFile(''), new FshQuantity(1).withLocation([5, 22, 5, 22]).withFile('') ) .withLocation([5, 16, 5, 22]) .withFile(''); assertAssignmentRule(profile.rules[0], 'valueRatio', expectedRatio); }); it('should parse assigned value Reference rule', () => { const input = leftAlign(` Profile: ObservationProfile Parent: Observation * basedOn = Reference(fooProfile) `); const result = importSingleText(input); const profile = result.profiles.get('ObservationProfile'); expect(profile.rules).toHaveLength(1); const expectedReference = new FshReference('fooProfile') .withLocation([5, 13, 5, 33]) .withFile(''); assertAssignmentRule(profile.rules[0], 'basedOn', expectedReference); }); it('should parse assigned value Reference rules while allowing and translating aliases', () => { const input = leftAlign(` Alias: FOO = http://hl7.org/fhir/StructureDefinition/Foo Profile: ObservationProfile Parent: Observation * basedOn = Reference(FOO) "bar" `); const result = importSingleText(input); const profile = result.profiles.get('ObservationProfile'); expect(profile.rules).toHaveLength(1); const expectedReference = new FshReference( 'http://hl7.org/fhir/StructureDefinition/Foo', 'bar' ) .withLocation([6, 13, 6, 32]) .withFile(''); assertAssignmentRule(profile.rules[0], 'basedOn', expectedReference); }); it('should parse assigned value Reference rule with a display string', () => { const input = leftAlign(` Profile: ObservationProfile Parent: Observation * basedOn = Reference(fooProfile) "bar" `); const result = importSingleText(input); const profile = result.profiles.get('ObservationProfile'); expect(profile.rules).toHaveLength(1); const expectedReference = new FshReference('fooProfile', 'bar') .withLocation([5, 13, 5, 39]) .withFile(''); assertAssignmentRule(profile.rules[0], 'basedOn', expectedReference); }); it('should parse assigned value Reference rule with whitespace', () => { const input = leftAlign(` Profile: ObservationProfile Parent: Observation * basedOn = Reference( fooProfile ) `); const result = importSingleText(input); const profile = result.profiles.get('ObservationProfile'); expect(profile.rules).toHaveLength(1); const expectedReference = new FshReference('fooProfile') .withLocation([5, 13, 5, 39]) .withFile(''); assertAssignmentRule(profile.rules[0], 'basedOn', expectedReference); }); it('should log an error when an assigned value Reference rule has a choice of references', () => { const input = leftAlign(` Profile: ObservationProfile Parent: Observation * basedOn = Reference(cakeProfile or pieProfile) `); const result = importSingleText(input); const profile = result.profiles.get('ObservationProfile'); expect(profile.rules).toHaveLength(1); const expectedReference = new FshReference('cakeProfile') .withLocation([5, 13, 5, 48]) .withFile(''); assertAssignmentRule(profile.rules[0], 'basedOn', expectedReference); expect(loggerSpy.getLastMessage('error')).toMatch( /Multiple choices of references are not allowed when setting a value.*Line: 5\D*/s ); }); it('should parse assigned value using Canonical', () => { const input = leftAlign(` CodeSystem: Example * #first * #second Profile: ObservationProfile Parent: Observation * code.coding.system = Canonical(Example) `); const result = importSingleText(input); const profile = result.profiles.get('ObservationProfile'); expect(profile.rules).toHaveLength(1); const expectedCanonical = new FshCanonical('Example') .withLocation([8, 24, 8, 41]) .withFile(''); assertAssignmentRule(profile.rules[0], 'code.coding.system', expectedCanonical); }); it('should parse assigned value using Canonical with spaces around entity name', () => { const input = leftAlign(` CodeSystem: SpaceyExample * #first * #second Profile: ObservationProfile Parent: Observation * code.coding.system = Canonical( SpaceyExample ) `); const result = importSingleText(input); const profile = result.profiles.get('ObservationProfile'); expect(profile.rules).toHaveLength(1); const expectedCanonical = new FshCanonical('SpaceyExample') // No spaces are included in the entityName .withLocation([8, 24, 8, 51]) .withFile(''); assertAssignmentRule(profile.rules[0], 'code.coding.system', expectedCanonical); }); it('should parse assigned value using Canonical with a version', () => { const input = leftAlign(` CodeSystem: Example * #first * #second Profile: ObservationProfile Parent: Observation * code.coding.system = Canonical(Example|1.2.3) `); const result = importSingleText(input); const profile = result.profiles.get('ObservationProfile'); expect(profile.rules).toHaveLength(1); const expectedCanonical = new FshCanonical('Example') .withLocation([8, 24, 8, 47]) .withFile(''); expectedCanonical.version = '1.2.3'; assertAssignmentRule(profile.rules[0], 'code.coding.system', expectedCanonical); }); it('should parse assigned value using Canonical with a version which contains a |', () => { const input = leftAlign(` CodeSystem: Example * #first * #second Profile: ObservationProfile Parent: Observation * code.coding.system = Canonical( Example|1.2.3|aWeirdVersion ) `); const result = importSingleText(input); const profile = result.profiles.get('ObservationProfile'); expect(profile.rules).toHaveLength(1); const expectedCanonical = new FshCanonical('Example') .withLocation([8, 24, 8, 65]) .withFile(''); expectedCanonical.version = '1.2.3|aWeirdVersion'; assertAssignmentRule(profile.rules[0], 'code.coding.system', expectedCanonical); }); it('should log an error when an assigned value Canonical rule has a choice of canonicals', () => { const input = leftAlign(` CodeSystem: Example * #first * #second Profile: ObservationProfile Parent: Observation * code.coding.system = Canonical(Example or OtherExample) `); const result = importSingleText(input); const profile = result.profiles.get('ObservationProfile'); expect(profile.rules).toHaveLength(1); const expectedCanonical = new FshCanonical('Example') .withLocation([8, 24, 8, 57]) .withFile(''); assertAssignmentRule(profile.rules[0], 'code.coding.system', expectedCanonical); expect(loggerSpy.getLastMessage('error')).toMatch( /Multiple choices of canonicals are not allowed when setting a value.*Line: 8\D*/s ); }); it('should parse assigned values that are an alias', () => { const input = leftAlign(` Alias: EXAMPLE = http://example.org Profile: PatientProfile Parent: Patient * identifier.system = EXAMPLE `); const result = importSingleText(input); const profile = result.profiles.get('PatientProfile'); expect(profile.rules).toHaveLength(1); assertAssignmentRule(profile.rules[0], 'identifier.system', 'http://example.org'); }); it('should parse an assigned value Resource rule', () => { const input = leftAlign(` Profile: ObservationProfile Parent: Observation * contained[0] = SomeInstance `); const result = importSingleText(input); const profile = result.profiles.get('ObservationProfile'); expect(profile.rules).toHaveLength(1); assertAssignmentRule(profile.rules[0], 'contained[0]', 'SomeInstance', false, true); }); }); describe('#onlyRule', () => { it('should parse an only rule with one type', () => { const input = leftAlign(` Profile: ObservationProfile Parent: Observation * value[x] only Quantity `); const result = importSingleText(input); const profile = result.profiles.get('ObservationProfile'); expect(profile.rules).toHaveLength(1); assertOnlyRule(profile.rules[0], 'value[x]', { type: 'Quantity' }); }); it('should parse an only rule with multiple types', () => { const input = leftAlign(` Profile: ObservationProfile Parent: Observation * value[x] only Quantity or CodeableConcept or string `); const result = importSingleText(input); const profile = result.profiles.get('ObservationProfile'); expect(profile.rules).toHaveLength(1); assertOnlyRule( profile.rules[0], 'value[x]', { type: 'Quantity' }, { type: 'CodeableConcept' }, { type: 'string' } ); }); it('should parse an only rule with one numeric type name', () => { const input = leftAlign(` Profile: ObservationProfile Parent: Observation * value[x] only 123 `); const result = importSingleText(input); const profile = result.profiles.get('ObservationProfile'); expect(profile.rules).toHaveLength(1); assertOnlyRule(profile.rules[0], 'value[x]', { type: '123' }); }); it('should parse an only rule with multiple numeric type names', () => { const input = leftAlign(` Profile: ObservationProfile Parent: Observation * value[x] only 123 or 456 or 789 `); const result = importSingleText(input); const profile = result.profiles.get('ObservationProfile'); expect(profile.rules).toHaveLength(1); assertOnlyRule( profile.rules[0], 'value[x]', { type: '123' }, { type: '456' }, { type: '789' } ); }); it('should parse an only rule with a reference to one type', () => { const input = leftAlign(` Profile: ObservationProfile Parent: Observation * performer only Reference(Practitioner) `); const result = importSingleText(input); const profile = result.profiles.get('ObservationProfile'); expect(profile.rules).toHaveLength(1); assertOnlyRule(profile.rules[0], 'performer', { type: 'Practitioner', isReference: true }); }); it('should parse an only rule with a reference to multiple types', () => { const input = leftAlign(` Profile: ObservationProfile Parent: Observation * performer only Reference(Organization or CareTeam) `); const result = importSingleText(input); const profile = result.profiles.get('ObservationProfile'); expect(profile.rules).toHaveLength(1); assertOnlyRule( profile.rules[0], 'performer', { type: 'Organization', isReference: true }, { type: 'CareTeam', isReference: true } ); }); it('should parse an only rule with a reference to multiple types with whitespace', () => { const input = leftAlign(` Profile: ObservationProfile Parent: Observation * performer only Reference( Organization or CareTeam) `); const result = importSingleText(input); const profile = result.profiles.get('ObservationProfile'); expect(profile.rules).toHaveLength(1); assertOnlyRule( profile.rules[0], 'performer', { type: 'Organization', isReference: true }, { type: 'CareTeam', isReference: true } ); }); it('should parse an only rule with a canonical to one type', () => { const input = leftAlign(` Profile: PlanDefinitionProfile Parent: PlanDefinition * action.definition[x] only Canonical(ActivityDefinition) `); const result = importSingleText(input); const profile = result.profiles.get('PlanDefinitionProfile'); expect(profile.rules).toHaveLength(1); assertOnlyRule(profile.rules[0], 'action.definition[x]', { type: 'ActivityDefinition', isCanonical: true }); }); it('should parse an only rule with a canonical to multiple types', () => { const input = leftAlign(` Profile: PlanDefinitionProfile Parent: PlanDefinition * action.definition[x] only Canonical(ActivityDefinition or PlanDefinition) `); const result = importSingleText(input); const profile = result.profiles.get('PlanDefinitionProfile'); expect(profile.rules).toHaveLength(1); assertOnlyRule( profile.rules[0], 'action.definition[x]', { type: 'ActivityDefinition', isCanonical: true }, { type: 'PlanDefinition', isCanonical: true } ); }); it('should parse an only rule with a canonical to multiple types with whitespace', () => { const input = leftAlign(` Profile: PlanDefinitionProfile Parent: PlanDefinition * action.definition[x] only Canonical( ActivityDefinition or PlanDefinition ) `); const result = importSingleText(input); const profile = result.profiles.get('PlanDefinitionProfile'); expect(profile.rules).toHaveLength(1); assertOnlyRule( profile.rules[0], 'action.definition[x]', { type: 'ActivityDefinition', isCanonical: true }, { type: 'PlanDefinition', isCanonical: true } ); }); it('should parse an only rule with a canonical to multiple types with versions', () => { const input = leftAlign(` Profile: PlanDefinitionProfile Parent: PlanDefinition * action.definition[x] only Canonical(ActivityDefinition|4.0.1 or PlanDefinition|4.0.1) `); const result = importSingleText(input); const profile = result.profiles.get('PlanDefinitionProfile'); expect(profile.rules).toHaveLength(1); assertOnlyRule( profile.rules[0], 'action.definition[x]', { type: 'ActivityDefinition|4.0.1', isCanonical: true }, { type: 'PlanDefinition|4.0.1', isCanonical: true } ); }); it('should allow and translate aliases for only types', () => { const input = leftAlign(` Alias: QUANTITY = http://hl7.org/fhir/StructureDefinition/Quantity Alias: CODING = http://hl7.org/fhir/StructureDefinition/Coding Profile: ObservationProfile Parent: Observation * value[x] only CodeableConcept or CODING or string or QUANTITY `); const result = importSingleText(input); const profile = result.profiles.get('ObservationProfile'); expect(profile.rules).toHaveLength(1); assertOnlyRule( profile.rules[0], 'value[x]', { type: 'CodeableConcept' }, { type: 'http://hl7.org/fhir/StructureDefinition/Coding' }, { type: 'string' }, { type: 'http://hl7.org/fhir/StructureDefinition/Quantity' } ); }); it('should log an error when references are listed with pipes', () => { const input = leftAlign(` Profile: ObservationProfile Parent: Observation * performer only Reference(Organization | CareTeam) `); const result = importSingleText(input); const profile = result.profiles.get('ObservationProfile'); expect(profile).toBeDefined(); expect(loggerSpy.getLastMessage('error')).toMatch( /Using '\|' to list references is no longer supported\..*Line: 4\D*/s ); }); it('should log an error when references are listed with pipes with whitespace', () => { const input = leftAlign(` Profile: ObservationProfile Parent: Observation * performer only Reference( Organization | CareTeam) `); const result = importSingleText(input); const profile = result.profiles.get('ObservationProfile'); expect(profile).toBeDefined(); expect(loggerSpy.getLastMessage('error')).toMatch( /Using '\|' to list references is no longer supported\..*Line: 4\D*/s ); }); }); describe('#containsRule', () => { it('should parse contains rule with one item', () => { const input = leftAlign(` Profile: ObservationProfile Parent: Observation * component contains SystolicBP 1..1 `); const result = importSingleText(input); const profile = result.profiles.get('ObservationProfile'); expect(profile.rules).toHaveLength(2); assertContainsRule(profile.rules[0], 'component', 'SystolicBP'); assertCardRule(profile.rules[1], 'component[SystolicBP]', 1, 1); }); it('should parse contains rule with one item declaring an aliased type', () => { const input = leftAlign(` Alias: OffsetExtension = http://hl7.org/fhir/StructureDefinition/observation-timeOffset Profile: ObservationProfile Parent: Observation * component.extension contains OffsetExtension named offset 0..1 `); const result = importSingleText(input); const profile = result.profiles.get('ObservationProfile'); expect(profile.rules).toHaveLength(2); assertContainsRule(profile.rules[0], 'component.extension', { name: 'offset', type: 'http://hl7.org/fhir/StructureDefinition/observation-timeOffset' }); assertCardRule(profile.rules[1], 'component.extension[offset]', 0, 1); }); it('should parse contains rule with one item declaring an FSH extension type', () => { const input = leftAlign(` Profile: ObservationProfile Parent: Observation * component.extension contains ComponentExtension named compext 0..1 Extension: ComponentExtension Id: component-extension * value[x] only CodeableConcept `); const result = importSingleText(input); const profile = result.profiles.get('ObservationProfile'); expect(profile.rules).toHaveLength(2); assertContainsRule(profile.rules[0], 'component.extension', { name: 'compext', type: 'ComponentExtension' }); assertCardRule(profile.rules[1], 'component.extension[compext]', 0, 1); }); it('should parse contains rules with multiple items', () => { const input = leftAlign(` Profile: ObservationProfile Parent: Observation * component contains SystolicBP 1..1 and DiastolicBP 2..* `); const result = importSingleText(input); const profile = result.profiles.get('ObservationProfile'); expect(profile.rules).toHaveLength(3); assertContainsRule(profile.rules[0], 'component', 'SystolicBP', 'DiastolicBP'); assertCardRule(profile.rules[1], 'component[SystolicBP]', 1, 1); assertCardRule(profile.rules[2], 'component[DiastolicBP]', 2, '*'); }); it('should parse contains rule with mutliple items, some declaring types', () => { const input = leftAlign(` Alias: FocusCodeExtension = http://hl7.org/fhir/StructureDefinition/observation-focusCode Alias: PreconditionExtension = http://hl7.org/fhir/StructureDefinition/observation-precondition Profile: ObservationProfile Parent: Observation * extension contains foo 0..1 and FocusCodeExtension named focus 1..1 and bar 0..* and PreconditionExtension named pc 1..* `); const result = importSingleText(input); const profile = result.profiles.get('ObservationProfile'); expect(profile.rules).toHaveLength(5); assertContainsRule( profile.rules[0], 'extension', 'foo', { name: 'focus', type: 'http://hl7.org/fhir/StructureDefinition/observation-focusCode' }, 'bar', { name: 'pc', type: 'http://hl7.org/fhir/StructureDefinition/observation-precondition' } ); assertCardRule(profile.rules[1], 'extension[foo]', 0, 1); assertCardRule(profile.rules[2], 'extension[focus]', 1, 1); assertCardRule(profile.rules[3], 'extension[bar]', 0, '*'); assertCardRule(profile.rules[4], 'extension[pc]', 1, '*'); }); it('should parse contains rules with flags', () => { const input = leftAlign(` Profile: ObservationProfile Parent: Observation * component contains SystolicBP 1..1 MS D and DiastolicBP 2..* MS SU `); const result = importSingleText(input); const profile = result.profiles.get('ObservationProfile'); expect(profile.rules).toHaveLength(5); assertContainsRule(profile.rules[0], 'component', 'SystolicBP', 'DiastolicBP'); assertCardRule(profile.rules[1], 'component[SystolicBP]', 1, 1); assertFlagRule( profile.rules[2], 'component[SystolicBP]', true, undefined, undefined, undefined, undefined, true ); assertCardRule(profile.rules[3], 'component[DiastolicBP]', 2, '*'); assertFlagRule( profile.rules[4], 'component[DiastolicBP]', true, true, undefined, undefined, undefined, undefined ); }); it('should parse contains rule with item declaring a type and flags', () => { const input = leftAlign(` Alias: OffsetExtension = http://hl7.org/fhir/StructureDefinition/observation-timeOffset Profile: ObservationProfile Parent: Observation * component.extension contains OffsetExtension named offset 0..1 MS TU `); const result = importSingleText(input); const profile = result.profiles.get('ObservationProfile'); expect(profile.rules).toHaveLength(3); assertContainsRule(profile.rules[0], 'component.extension', { name: 'offset', type: 'http://hl7.org/fhir/StructureDefinition/observation-timeOffset' }); assertCardRule(profile.rules[1], 'component.extension[offset]', 0, 1); assertFlagRule( profile.rules[2], 'component.extension[offset]', true, undefined, undefined, true, undefined, undefined ); }); }); describe('#caretValueRule', () => { it('should parse caret value rules with no path', () => { const input = leftAlign(` Profile: ObservationProfile Parent: Observation * ^description = "foo" * ^experimental = false * ^keyword[0] = foo#bar "baz" `); const result = importSingleText(input); const profile = result.profiles.get('ObservationProfile'); assertCaretValueRule(profile.rules[0], '', 'description', 'foo', false); assertCaretValueRule(profile.rules[1], '', 'experimental', false, false); assertCaretValueRule( profile.rules[2], '', 'keyword[0]', new FshCode('bar', 'foo', 'baz').withLocation([6, 17, 6, 29]).withFile(''), false ); }); it('should parse caret value rules with a . path', () => { const input = leftAlign(` Profile: ObservationProfile Parent: Observation * . ^definition = "foo" `); const result = importSingleText(input); const profile = result.profiles.get('ObservationProfile'); assertCaretValueRule(profile.rules[0], '.', 'definition', 'foo', false, ['.']); }); it('should parse caret value rules with a path', () => { const input = leftAlign(` Profile: ObservationProfile Parent: Observation * status ^short = "foo" * status ^sliceIsConstraining = false * status ^code[0] = foo#bar "baz" `); const result = importSingleText(input); const profile = result.profiles.get('ObservationProfile'); assertCaretValueRule(profile.rules[0], 'status', 'short', 'foo', false); assertCaretValueRule(profile.rules[1], 'status', 'sliceIsConstraining', false, false); assertCaretValueRule( profile.rules[2], 'status', 'code[0]', new FshCode('bar', 'foo', 'baz').withLocation([6, 21, 6, 33]).withFile(''), false ); }); it('should not include non-breaking spaces as part of the caret path', () => { const input = leftAlign(` Profile: ObservationProfile Parent: Observation * status ^short\u00A0= "Non-breaking" `); const result = importSingleText(input); const profile = result.profiles.get('ObservationProfile'); assertCaretValueRule(profile.rules[0], 'status', 'short', 'Non-breaking', false); }); it('should add resources to the contained array using a CaretValueRule', () => { const input = leftAlign(` Profile: ObservationProfile Parent: Observation * ^contained = myResource `); const result = importSingleText(input); const profile = result.profiles.get('ObservationProfile'); assertCaretValueRule(profile.rules[0], '', 'contained', 'myResource', true); }); }); describe('#obeysRule', () => { it('should parse an obeys rule with one invariant and no path', () => { const input = leftAlign(` Profile: ObservationProfile Parent: Observation * obeys SomeInvariant `); const result = importSingleText(input, 'Obeys.fsh'); const profile = result.profiles.get('ObservationProfile'); expect(profile.rules).toHaveLength(1); assertObeysRule(profile.rules[0], '', 'SomeInvariant'); }); it('should parse an obeys rule with one invariant and a path', () => { const input = leftAlign(` Profile: ObservationProfile Parent: Observation * category obeys SomeInvariant `); const result = importSingleText(input, 'Obeys.fsh'); const profile = result.profiles.get('ObservationProfile'); expect(profile.rules).toHaveLength(1); assertObeysRule(profile.rules[0], 'category', 'SomeInvariant'); }); it('should parse an obeys rule with multiple invariants and no path', () => { const input = leftAlign(` Profile: ObservationProfile Parent: Observation * obeys SomeInvariant and ThisInvariant and ThatInvariant `); const result = importSingleText(input, 'Obeys.fsh'); const profile = result.profiles.get('ObservationProfile'); expect(profile.rules).toHaveLength(3); assertObeysRule(profile.rules[0], '', 'SomeInvariant'); assertObeysRule(profile.rules[1], '', 'ThisInvariant'); assertObeysRule(profile.rules[2], '', 'ThatInvariant'); }); it('should parse an obeys rule with multiple invariants and a path', () => { const input = leftAlign(` Profile: ObservationProfile Parent: Observation * category obeys SomeInvariant and ThisInvariant and ThatInvariant `); const result = importSingleText(input, 'Obeys.fsh'); const profile = result.profiles.get('ObservationProfile'); expect(profile.rules).toHaveLength(3); assertObeysRule(profile.rules[0], 'category', 'SomeInvariant'); assertObeysRule(profile.rules[1], 'category', 'ThisInvariant'); assertObeysRule(profile.rules[2], 'category', 'ThatInvariant'); }); it('should parse an obeys rule with a numeric invariant name', () => { const input = leftAlign(` Profile: ObservationProfile Parent: Observation * obeys 123 `); const result = importSingleText(input, 'Obeys.fsh'); const profile = result.profiles.get('ObservationProfile'); expect(profile.rules).toHaveLength(1); assertObeysRule(profile.rules[0], '', '123'); }); }); describe('#pathRule', () => { it('should parse a pathRule', () => { const input = leftAlign(` Profile: PatientProfile Parent: Patient * name `); const result = importSingleText(input, 'Path.fsh'); const profile = result.profiles.get('PatientProfile'); expect(profile.rules).toHaveLength(0); }); }); describe('#insertRule', () => { let importer: FSHImporter; beforeEach(() => { // To explain a bit about why stats are used here and not in other tests: // When parsing generated documents, the logging level is temporarily raised // in order to suppress console output. However, messages still go to the logger // and therefore are detected by loggerSpy. However, the stats should provide an // accurate reflection of the number of times that errors and warnings were logged // while the logger is at the normal level. loggerSpy.reset(); stats.reset(); importer = new FSHImporter(); // RuleSet: OneParamRuleSet (val) // * status = {val} const oneParamRuleSet = new ParamRuleSet('OneParamRuleSet') .withFile('RuleSet.fsh') .withLocation([1, 12, 2, 27]); oneParamRuleSet.parameters = ['val']; oneParamRuleSet.contents = '* status = {val}'; importer.paramRuleSets.set(oneParamRuleSet.name, oneParamRuleSet); // RuleSet: MultiParamRuleSet (status, value, maxNote) // * status = {status} // * valueString = {value} // * note 0..{maxNote} const multiParamRuleSet = new ParamRuleSet('MultiParamRuleSet') .withFile('RuleSet.fsh') .withLocation([4, 12, 7, 30]); multiParamRuleSet.parameters = ['status', 'value', 'maxNote']; multiParamRuleSet.contents = [ '* status = {status}', '* valueString = {value}', '* note 0..{maxNote}' ].join(EOL); importer.paramRuleSets.set(multiParamRuleSet.name, multiParamRuleSet); // RuleSet: EntryRules (continuation) // * insert {continuation}Rules (5) const entryRules = new ParamRuleSet('EntryRules') .withFile('RuleSet.fsh') .withLocation([9, 12, 10, 43]); entryRules.parameters = ['continuation']; entryRules.contents = '* insert {continuation}Rules (5)'; importer.paramRuleSets.set(entryRules.name, entryRules); // RuleSet: RecursiveRules (value) // * interpretation 0..{value} // * insert EntryRules (BaseCase) const recursiveRules = new ParamRuleSet('RecursiveRules') .withFile('RuleSet.fsh') .withLocation([12, 12, 14, 41]); recursiveRules.parameters = ['value']; recursiveRules.contents = [ '* interpretation 0..{value}', '* insert EntryRules (BaseCase)' ].join(EOL); importer.paramRuleSets.set(recursiveRules.name, recursiveRules); // RuleSet: BaseCaseRules (value) // * note 0..{value} const baseCaseRules = new ParamRuleSet('BaseCaseRules') .withFile('RuleSet.fsh') .withLocation([16, 12, 17, 28]); baseCaseRules.parameters = ['value']; baseCaseRules.contents = '* note 0..{value}'; importer.paramRuleSets.set(baseCaseRules.name, baseCaseRules); // RuleSet: CardRuleSet (path, min, max) // * {path} {min}..{max} // * note {min}..{max} const cardRuleSet = new ParamRuleSet('CardRuleSet') .withFile('RuleSet.fsh') .withLocation([19, 12, 21, 30]); cardRuleSet.parameters = ['path', 'min', 'max']; cardRuleSet.contents = ['* {path} {min}..{max}', '* note {min}..{max}'].join(EOL); importer.paramRuleSets.set(cardRuleSet.name, cardRuleSet); // RuleSet: FirstRiskyRuleSet (value) // * note ={value} // * insert SecondRiskyRuleSet({value}) const firstRiskyRuleSet = new ParamRuleSet('FirstRiskyRuleSet') .withFile('RuleSet.fsh') .withLocation([23, 12, 25, 47]); firstRiskyRuleSet.parameters = ['value']; firstRiskyRuleSet.contents = [ '* note ={value}', '* insert SecondRiskyRuleSet({value})' ].join(EOL); importer.paramRuleSets.set(firstRiskyRuleSet.name, firstRiskyRuleSet); // RuleSet: SecondRiskyRuleSet(value) // * status ={value} const secondRiskyRuleSet = new ParamRuleSet('SecondRiskyRuleSet') .withFile('RuleSet.fsh') .withLocation([27, 12, 28, 28]); secondRiskyRuleSet.parameters = ['value']; secondRiskyRuleSet.contents = '* status ={value}'; importer.paramRuleSets.set(secondRiskyRuleSet.name, secondRiskyRuleSet); // RuleSet: WarningRuleSet(value) // * focus[0] only Reference(Patient | {value}) // * focus[1] only Reference(Group | {value}) // NOTE: This now causes ERRORS (not warnings), so associated test is skipped! const warningRuleSet = new ParamRuleSet('WarningRuleSet') .withFile('RuleSet.fsh') .withLocation([30, 12, 32, 53]); warningRuleSet.parameters = ['value']; warningRuleSet.contents = [ '* focus[0] only Reference(Patient | {value})', '* focus[1] only Reference(Group | {value})' ].join(EOL); importer.paramRuleSets.set(warningRuleSet.name, warningRuleSet); }); it('should parse an insert rule with a single RuleSet', () => { const input = leftAlign(` Profile: ObservationProfile Parent: Observation * insert MyRuleSet `); const result = importSingleText(input, 'Insert.fsh'); const profile = result.profiles.get('ObservationProfile'); expect(profile.rules).toHaveLength(1); assertInsertRule(profile.rules[0], '', 'MyRuleSet'); }); it('should parse an insert rule with a single RuleSet and a path', () => { const input = leftAlign(` Profile: ObservationProfile Parent: Observation * code insert MyRuleSet `); const result = importSingleText(input, 'Insert.fsh'); const profile = result.profiles.get('ObservationProfile'); expect(profile.rules).toHaveLength(1); assertInsertRule(profile.rules[0], 'code', 'MyRuleSet'); }); it('should parse an insert rule with a RuleSet with one parameter', () => { const input = leftAlign(` Profile: ObservationProfile Parent: Observation * insert OneParamRuleSet (#final) `); const allDocs = importer.import([new RawFSH(input, 'Insert.fsh')]); expect(loggerSpy.getAllMessages('error')).toHaveLength(0); expect(allDocs).toHaveLength(1); const doc = allDocs[0]; const profile = doc.profiles.get('ObservationProfile'); expect(profile.rules).toHaveLength(1); assertInsertRule(profile.rules[0], '', 'OneParamRuleSet', ['#final']); const appliedRuleSet = doc.appliedRuleSets.get( JSON.stringify(['OneParamRuleSet', '#final']) ); expect(appliedRuleSet).toBeDefined(); expect(appliedRuleSet.sourceInfo).toEqual({ file: 'RuleSet.fsh', location: { startLine: 1, startColumn: 12, endLine: 2, endColumn: 27 } }); expect(appliedRuleSet.rules[0].sourceInfo).toEqual({ file: 'RuleSet.fsh', location: { startLine: 2, startColumn: 1, endLine: 2, endColumn: 17 } }); }); it('should parse an insert rule with a RuleSet with one parameter and a path', () => { const input = leftAlign(` Profile: ObservationProfile Parent: Observation * code insert OneParamRuleSet (#final) `); const allDocs = importer.import([new RawFSH(input, 'Insert.fsh')]); expect(loggerSpy.getAllMessages('error')).toHaveLength(0); expect(allDocs).toHaveLength(1); const doc = allDocs[0]; const profile = doc.profiles.get('ObservationProfile'); expect(profile.rules).toHaveLength(1); assertInsertRule(profile.rules[0], 'code', 'OneParamRuleSet', ['#final']); const appliedRuleSet = doc.appliedRuleSets.get( JSON.stringify(['OneParamRuleSet', '#final']) ); expect(appliedRuleSet).toBeDefined(); expect(appliedRuleSet.sourceInfo).toEqual({ file: 'RuleSet.fsh', location: { startLine: 1, startColumn: 12, endLine: 2, endColumn: 27 } }); expect(appliedRuleSet.rules[0].sourceInfo).toEqual({ file: 'RuleSet.fsh', location: { startLine: 2, startColumn: 1, endLine: 2, endColumn: 17 } }); }); it('should parse an insert rule with a RuleSet with multiple parameters', () => { const input = leftAlign(` Profile: ObservationProfile Parent: Observation * insert MultiParamRuleSet (#preliminary, "this is a string value\\, right?", 4) `); const allDocs = importer.import([new RawFSH(input, 'Insert.fsh')]); expect(loggerSpy.getAllMessages('error')).toHaveLength(0); expect(allDocs).toHaveLength(1); const doc = allDocs[0]; const profile = doc.profiles.get('ObservationProfile'); expect(profile.rules).toHaveLength(1); assertInsertRule(profile.rules[0], '', 'MultiParamRuleSet', [ '#preliminary', '"this is a string value, right?"', '4' ]); const appliedRuleSet = doc.appliedRuleSets.get( JSON.stringify([ 'MultiParamRuleSet', '#preliminary', '"this is a string value, right?"', '4' ]) ); expect(appliedRuleSet).toBeDefined(); expect(appliedRuleSet.sourceInfo).toEqual({ file: 'RuleSet.fsh', location: { startLine: 4, startColumn: 12, endLine: 7, endColumn: 30 } }); expect(appliedRuleSet.rules).toHaveLength(3); assertAssignmentRule( appliedRuleSet.rules[0], 'status', new FshCode('preliminary').withFile('Insert.fsh').withLocation([2, 12, 2, 23]), false, false ); expect(appliedRuleSet.rules[0].sourceInfo.file).toBe('RuleSet.fsh'); expect(appliedRuleSet.rules[0].sourceInfo.location.startLine).toBe(5); expect(appliedRuleSet.rules[0].sourceInfo.location.endLine).toBe(5); assertAssignmentRule( appliedRuleSet.rules[1], 'valueString', 'this is a string value, right?', false, false ); expect(appliedRuleSet.rules[1].sourceInfo.file).toBe('RuleSet.fsh'); expect(appliedRuleSet.rules[1].sourceInfo.location.startLine).toBe(6); expect(appliedRuleSet.rules[1].sourceInfo.location.endLine).toBe(6); assertCardRule(appliedRuleSet.rules[2], 'note', 0, '4'); expect(appliedRuleSet.rules[2].sourceInfo.file).toBe('RuleSet.fsh'); expect(appliedRuleSet.rules[2].sourceInfo.location.startLine).toBe(7); expect(appliedRuleSet.rules[2].sourceInfo.location.endLine).toBe(7); }); it('should parse an insert rule with a parameter that contains right parenthesis', () => { const input = leftAlign(` Profile: ObservationProfile Parent: Observation * insert OneParamRuleSet (#final "(Final\\)") `); const allDocs = importer.import([new RawFSH(input, 'Insert.fsh')]); expect(loggerSpy.getAllMessages('error')).toHaveLength(0); expect(allDocs).toHaveLength(1); const doc = allDocs[0]; const profile = doc.profiles.get('ObservationProfile'); expect(profile.rules).toHaveLength(1); assertInsertRule(profile.rules[0], '', 'OneParamRuleSet', ['#final "(Final)"']); const appliedRuleSet = doc.appliedRuleSets.get( JSON.stringify(['OneParamRuleSet', '#final "(Final)"']) ); expect(appliedRuleSet).toBeDefined(); expect(appliedRuleSet.rules).toHaveLength(1); expect(appliedRuleSet.sourceInfo).toEqual({ file: 'RuleSet.fsh', location: { startLine: 1, startColumn: 12, endLine: 2, endColumn: 27 } }); assertAssignmentRule( appliedRuleSet.rules[0], 'status', new FshCode('final', undefined, '(Final)') .withFile('Insert.fsh') .withLocation([2, 12, 2, 27]), false, false ); }); it('should parse an insert rule with parameters that contain newline, tab, or backslash characters', () => { const input = leftAlign(` Profile: ObservationProfile Parent: Observation * insert MultiParamRuleSet (#final, "very\\nstrange\\rvalue\\\\\\tindeed", 1) `); const allDocs = importer.import([new RawFSH(input, 'Insert.fsh')]); expect(loggerSpy.getAllMessages('error')).toHaveLength(0); expect(allDocs).toHaveLength(1); const doc = allDocs[0]; const profile = doc.profiles.get('ObservationProfile'); expect(profile.rules).toHaveLength(1); assertInsertRule(profile.rules[0], '', 'MultiParamRuleSet', [ '#final', '"very\\nstrange\\rvalue\\\\\\tindeed"', '1' ]); const appliedRuleSet = doc.appliedRuleSets.get( JSON.stringify([ 'MultiParamRuleSet', '#final', '"very\\nstrange\\rvalue\\\\\\tindeed"', '1' ]) ); expect(appliedRuleSet).toBeDefined(); expect(appliedRuleSet.sourceInfo).toEqual({ file: 'RuleSet.fsh', location: { startLine: 4, startColumn: 12, endLine: 7, endColumn: 30 } }); expect(appliedRuleSet.rules).toHaveLength(3); assertAssignmentRule( appliedRuleSet.rules[0], 'status', new FshCode('final').withFile('Insert.fsh').withLocation([2, 12, 2, 17]), false, false ); assertAssignmentRule( appliedRuleSet.rules[1], 'valueString', 'very\nstrange\rvalue\\\tindeed', false, false ); assertCardRule(appliedRuleSet.rules[2], 'note', 0, '1'); }); it('should parse an insert rule that separates its parameters onto multiple lines', () => { const input = leftAlign(` Profile: ObservationProfile Parent: Observation * insert MultiParamRuleSet ( #final, "string value", 7 ) `); const allDocs = importer.import([new RawFSH(input, 'Insert.fsh')]); expect(loggerSpy.getAllMessages('error')).toHaveLength(0); expect(allDocs).toHaveLength(1); const doc = allDocs[0]; const profile = doc.profiles.get('ObservationProfile'); expect(profile.rules).toHaveLength(1); assertInsertRule(profile.rules[0], '', 'MultiParamRuleSet', [ '#final', '"string value"', '7' ]); const appliedRuleSet = doc.appliedRuleSets.get( JSON.stringify(['MultiParamRuleSet', '#final', '"string value"', '7']) ); expect(appliedRuleSet).toBeDefined(); expect(appliedRuleSet.sourceInfo).toEqual({ file: 'RuleSet.fsh', location: { startLine: 4, startColumn: 12, endLine: 7, endColumn: 30 } }); expect(appliedRuleSet.rules).toHaveLength(3); assertAssignmentRule( appliedRuleSet.rules[0], 'status', new FshCode('final').withFile('Insert.fsh').withLocation([2, 12, 2, 17]), false, false ); assertAssignmentRule(appliedRuleSet.rules[1], 'valueString', 'string value', false, false); assertCardRule(appliedRuleSet.rules[2], 'note', 0, '7'); }); it('should generate a RuleSet only once when inserted with the same parameters multiple times in the same document', () => { const input = leftAlign(` Profile: ObservationProfile Parent: Observation * insert MultiParamRuleSet (#preliminary, "something", 3) * insert MultiParamRuleSet (#preliminary, "something", 3) `); const visitDocSpy = jest.spyOn(importer, 'visitDoc'); const allDocs = importer.import([new RawFSH(input, 'Insert.fsh')]); expect(loggerSpy.getAllMessages('error')).toHaveLength(0); expect(allDocs).toHaveLength(1); const doc = allDocs[0]; expect(doc.appliedRuleSets.size).toBe(1); // expect one call to visitDoc for the Profile, and one for the generated RuleSet expect(visitDocSpy).toHaveBeenCalledTimes(2); // ensure the insert rules are still there (once upon a time, a bug caused the repeated rules to be omitted) const profile = doc.profiles.get('ObservationProfile'); expect(profile).toBeDefined(); expect(profile.rules).toHaveLength(2); assertInsertRule(profile.rules[0], '', 'MultiParamRuleSet', [ '#preliminary', '"something"', '3' ]); assertInsertRule(profile.rules[1], '', 'MultiParamRuleSet', [ '#preliminary', '"something"', '3' ]); }); it('should parse an insert rule with parameters that will use the same RuleSet more than once with different parameters each time', () => { const input = leftAlign(` Profile: ObservationProfile Parent: Observation * insert EntryRules (Recursive) `); const allDocs = importer.import([new RawFSH(input, 'Insert.fsh')]); expect(loggerSpy.getAllMessages('error')).toHaveLength(0); expect(allDocs).toHaveLength(1); const doc = allDocs[0]; expect(doc.appliedRuleSets.size).toBe(4); const firstEntryRules = doc.appliedRuleSets.get( JSON.stringify(['EntryRules', 'Recursive']) ); expect(firstEntryRules).toBeDefined(); expect(firstEntryRules.sourceInfo).toEqual({ file: 'RuleSet.fsh', location: { startLine: 9, startColumn: 12, endLine: 10, endColumn: 43 } }); expect(firstEntryRules.rules).toHaveLength(1); assertInsertRule(firstEntryRules.rules[0], '', 'RecursiveRules', ['5']); const recursiveRules = doc.appliedRuleSets.get(JSON.stringify(['RecursiveRules', '5'])); expect(recursiveRules).toBeDefined(); expect(recursiveRules.sourceInfo).toEqual({ file: 'RuleSet.fsh', location: { startLine: 12, startColumn: 12, endLine: 14, endColumn: 41 } }); expect(recursiveRules.rules).toHaveLength(2); assertCardRule(recursiveRules.rules[0], 'interpretation', 0, '5'); assertInsertRule(recursiveRules.rules[1], '', 'EntryRules', ['BaseCase']); const secondEntryRules = doc.appliedRuleSets.get( JSON.stringify(['EntryRules', 'BaseCase']) ); expect(secondEntryRules.sourceInfo).toEqual({ file: 'RuleSet.fsh', location: { startLine: 9, startColumn: 12, endLine: 10, endColumn: 43 } }); expect(secondEntryRules.rules).toHaveLength(1); assertInsertRule(secondEntryRules.rules[0], '', 'BaseCaseRules', ['5']); const baseCaseRules = doc.appliedRuleSets.get(JSON.stringify(['BaseCaseRules', '5'])); expect(baseCaseRules).toBeDefined(); expect(baseCaseRules.sourceInfo).toEqual({ file: 'RuleSet.fsh', location: { startLine: 16, startColumn: 12, endLine: 17, endColumn: 28 } }); expect(baseCaseRules.rules).toHaveLength(1); assertCardRule(baseCaseRules.rules[0], 'note', 0, '5'); }); it('should log an error and not add a rule when an insert rule has the wrong number of parameters', () => { const input = leftAlign(` Profile: ObservationProfile Parent: Observation * insert OneParamRuleSet (#final, "Final") `); const allDocs = importer.import([new RawFSH(input, 'Insert.fsh')]); const doc = allDocs[0]; const profile = doc.profiles.get('ObservationProfile'); expect(profile.rules).toHaveLength(0); expect(loggerSpy.getLastMessage('error')).toMatch( /Incorrect number of parameters applied to RuleSet/s ); expect(loggerSpy.getLastMessage('error')).toMatch(/File: Insert\.fsh.*Line: 4/s); }); it('should log an error and not add a rule when an insert rule with parameters refers to an undefined parameterized RuleSet', () => { const input = leftAlign(` Profile: ObservationProfile Parent: Observation * insert MysteriousRuleSet ("mystery") `); const allDocs = importer.import([new RawFSH(input, 'Insert.fsh')]); const doc = allDocs[0]; const profile = doc.profiles.get('ObservationProfile'); expect(profile.rules).toHaveLength(0); expect(loggerSpy.getLastMessage('error')).toMatch( /Could not find parameterized RuleSet named MysteriousRuleSet/s ); expect(loggerSpy.getLastMessage('error')).toMatch(/File: Insert\.fsh.*Line: 4/s); }); it('should log an error when an insert rule with parameters results in a parser error in the generated RuleSet', () => { const input = leftAlign(` Profile: MyObservation Parent: Observation * insert CardRuleSet(path with spaces, 1, *) `); importer.import([new RawFSH(input, 'Insert.fsh')]); expect(stats.numError).toBe(1); expect(loggerSpy.getLastMessage('error')).toMatch( /Error parsing insert rule with parameterized RuleSet CardRuleSet/s ); expect(loggerSpy.getLastMessage('error')).toMatch(/File: Insert\.fsh.*Line: 4/s); }); it('should log one error when nested insert rules with parameters result in multiple parser errors in the generated RuleSets', () => { const input = leftAlign(` Profile: MyObservation Parent: Observation * note 0..1 * insert FirstRiskyRuleSet("Observation.id") `); importer.import([new RawFSH(input, 'Insert.fsh')]); expect(stats.numError).toBe(1); expect(loggerSpy.getLastMessage('error')).toMatch( /Error parsing insert rule with parameterized RuleSet FirstRiskyRuleSet/s ); expect(loggerSpy.getLastMessage('error')).toMatch(/File: Insert\.fsh.*Line: 5/s); }); it('should not log an error when an insert rule with parameters results in rules that are syntactically correct but semantically invalid', () => { const input = leftAlign(` Profile: MyObservation Parent: Observation * insert CardRuleSet(nonExistentPath, 7, 4) `); const allDocs = importer.import([new RawFSH(input, 'Insert.fsh')]); expect(allDocs).toHaveLength(1); const doc = allDocs[0]; expect(doc.appliedRuleSets.size).toBe(1); const appliedRuleSet = doc.appliedRuleSets.get( JSON.stringify(['CardRuleSet', 'nonExistentPath', '7', '4']) ); expect(appliedRuleSet).toBeDefined(); expect(appliedRuleSet.sourceInfo).toEqual({ file: 'RuleSet.fsh', location: { startLine: 19, startColumn: 12, endLine: 21, endColumn: 30 } }); // This rule is nonsense, of course, but figuring that out is the job of the exporter, not the importer. assertCardRule(appliedRuleSet.rules[0], 'nonExistentPath', 7, '4'); assertCardRule(appliedRuleSet.rules[1], 'note', 7, '4'); expect(loggerSpy.getAllMessages('error')).toHaveLength(0); }); // Skipping the following rule because SUSHI no longer has any warnings associated w/ parsing rules. // All deprecated syntaxes are now errors (not warnings). We can re-enable if/when the importer // produces warnings on rules. it.skip('should log one warning when an insert rule with parameters results in warnings', () => { const input = leftAlign(` Profile: MyObservation Parent: Observation * insert WarningRuleSet(Device) `); importer.import([new RawFSH(input, 'Insert.fsh')]); expect(stats.numWarn).toBe(1); expect(loggerSpy.getLastMessage('warn')).toMatch( /Warnings parsing insert rule with parameterized RuleSet WarningRuleSet/s ); expect(loggerSpy.getLastMessage('warn')).toMatch(/File: Insert\.fsh.*Line: 4/s); }); it('should log one error when an insert rule with parameters results in non-parser errors', () => { const input = leftAlign(` Profile: MyObservation Parent: Observation * insert CardRuleSet(nonExistentPath, , ) `); importer.import([new RawFSH(input, 'Insert.fsh')]); expect(stats.numError).toBe(1); expect(loggerSpy.getLastMessage('error')).toMatch( /Errors parsing insert rule with parameterized RuleSet CardRuleSet/s ); expect(loggerSpy.getLastMessage('error')).toMatch(/File: Insert\.fsh.*Line: 4/s); }); }); }); });
the_stack
import * as pulumi from "@pulumi/pulumi"; import { input as inputs, output as outputs } from "../types"; import * as utilities from "../utilities"; /** * A FhirStore is a datastore inside a Healthcare dataset that conforms to the FHIR (https://www.hl7.org/fhir/STU3/) * standard for Healthcare information exchange * * To get more information about FhirStore, see: * * * [API documentation](https://cloud.google.com/healthcare/docs/reference/rest/v1/projects.locations.datasets.fhirStores) * * How-to Guides * * [Creating a FHIR store](https://cloud.google.com/healthcare/docs/how-tos/fhir) * * ## Example Usage * ### Healthcare Fhir Store Basic * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as gcp from "@pulumi/gcp"; * * const topic = new gcp.pubsub.Topic("topic", {}); * const dataset = new gcp.healthcare.Dataset("dataset", {location: "us-central1"}); * const _default = new gcp.healthcare.FhirStore("default", { * dataset: dataset.id, * version: "R4", * enableUpdateCreate: false, * disableReferentialIntegrity: false, * disableResourceVersioning: false, * enableHistoryImport: false, * notificationConfig: { * pubsubTopic: topic.id, * }, * labels: { * label1: "labelvalue1", * }, * }); * ``` * ### Healthcare Fhir Store Streaming Config * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as gcp from "@pulumi/gcp"; * * const dataset = new gcp.healthcare.Dataset("dataset", {location: "us-central1"}); * const bqDataset = new gcp.bigquery.Dataset("bqDataset", { * datasetId: "bq_example_dataset", * friendlyName: "test", * description: "This is a test description", * location: "US", * deleteContentsOnDestroy: true, * }); * const _default = new gcp.healthcare.FhirStore("default", { * dataset: dataset.id, * version: "R4", * enableUpdateCreate: false, * disableReferentialIntegrity: false, * disableResourceVersioning: false, * enableHistoryImport: false, * labels: { * label1: "labelvalue1", * }, * streamConfigs: [{ * resourceTypes: ["Observation"], * bigqueryDestination: { * datasetUri: pulumi.interpolate`bq://${bqDataset.project}.${bqDataset.datasetId}`, * schemaConfig: { * recursiveStructureDepth: 3, * }, * }, * }], * }); * const topic = new gcp.pubsub.Topic("topic", {}); * ``` * * ## Import * * FhirStore can be imported using any of these accepted formats * * ```sh * $ pulumi import gcp:healthcare/fhirStore:FhirStore default {{dataset}}/fhirStores/{{name}} * ``` * * ```sh * $ pulumi import gcp:healthcare/fhirStore:FhirStore default {{dataset}}/{{name}} * ``` */ export class FhirStore extends pulumi.CustomResource { /** * Get an existing FhirStore resource's state with the given name, ID, and optional extra * properties used to qualify the lookup. * * @param name The _unique_ name of the resulting resource. * @param id The _unique_ provider ID of the resource to lookup. * @param state Any extra arguments used during the lookup. * @param opts Optional settings to control the behavior of the CustomResource. */ public static get(name: string, id: pulumi.Input<pulumi.ID>, state?: FhirStoreState, opts?: pulumi.CustomResourceOptions): FhirStore { return new FhirStore(name, <any>state, { ...opts, id: id }); } /** @internal */ public static readonly __pulumiType = 'gcp:healthcare/fhirStore:FhirStore'; /** * Returns true if the given object is an instance of FhirStore. This is designed to work even * when multiple copies of the Pulumi SDK have been loaded into the same process. */ public static isInstance(obj: any): obj is FhirStore { if (obj === undefined || obj === null) { return false; } return obj['__pulumiType'] === FhirStore.__pulumiType; } /** * Identifies the dataset addressed by this request. Must be in the format * 'projects/{project}/locations/{location}/datasets/{dataset}' */ public readonly dataset!: pulumi.Output<string>; /** * Whether to disable referential integrity in this FHIR store. This field is immutable after FHIR store * creation. The default value is false, meaning that the API will enforce referential integrity and fail the * requests that will result in inconsistent state in the FHIR store. When this field is set to true, the API * will skip referential integrity check. Consequently, operations that rely on references, such as * Patient.get$everything, will not return all the results if broken references exist. * ** Changing this property may recreate the FHIR store (removing all data) ** */ public readonly disableReferentialIntegrity!: pulumi.Output<boolean | undefined>; /** * Whether to disable resource versioning for this FHIR store. This field can not be changed after the creation * of FHIR store. If set to false, which is the default behavior, all write operations will cause historical * versions to be recorded automatically. The historical versions can be fetched through the history APIs, but * cannot be updated. If set to true, no historical versions will be kept. The server will send back errors for * attempts to read the historical versions. * ** Changing this property may recreate the FHIR store (removing all data) ** */ public readonly disableResourceVersioning!: pulumi.Output<boolean | undefined>; /** * Whether to allow the bulk import API to accept history bundles and directly insert historical resource * versions into the FHIR store. Importing resource histories creates resource interactions that appear to have * occurred in the past, which clients may not want to allow. If set to false, history bundles within an import * will fail with an error. * ** Changing this property may recreate the FHIR store (removing all data) ** * ** This property can be changed manually in the Google Cloud Healthcare admin console without recreating the FHIR store ** */ public readonly enableHistoryImport!: pulumi.Output<boolean | undefined>; /** * Whether this FHIR store has the updateCreate capability. This determines if the client can use an Update * operation to create a new resource with a client-specified ID. If false, all IDs are server-assigned through * the Create operation and attempts to Update a non-existent resource will return errors. Please treat the audit * logs with appropriate levels of care if client-specified resource IDs contain sensitive data such as patient * identifiers, those IDs will be part of the FHIR resource path recorded in Cloud audit logs and Cloud Pub/Sub * notifications. */ public readonly enableUpdateCreate!: pulumi.Output<boolean | undefined>; /** * User-supplied key-value pairs used to organize FHIR stores. * Label keys must be between 1 and 63 characters long, have a UTF-8 encoding of maximum 128 bytes, and must * conform to the following PCRE regular expression: [\p{Ll}\p{Lo}][\p{Ll}\p{Lo}\p{N}_-]{0,62} * Label values are optional, must be between 1 and 63 characters long, have a UTF-8 encoding of maximum 128 * bytes, and must conform to the following PCRE regular expression: [\p{Ll}\p{Lo}\p{N}_-]{0,63} * No more than 64 labels can be associated with a given store. * An object containing a list of "key": value pairs. * Example: { "name": "wrench", "mass": "1.3kg", "count": "3" }. */ public readonly labels!: pulumi.Output<{[key: string]: string} | undefined>; /** * The resource name for the FhirStore. * ** Changing this property may recreate the FHIR store (removing all data) ** */ public readonly name!: pulumi.Output<string>; /** * A nested object resource * Structure is documented below. */ public readonly notificationConfig!: pulumi.Output<outputs.healthcare.FhirStoreNotificationConfig | undefined>; /** * The fully qualified name of this dataset */ public /*out*/ readonly selfLink!: pulumi.Output<string>; /** * A list of streaming configs that configure the destinations of streaming export for every resource mutation in * this FHIR store. Each store is allowed to have up to 10 streaming configs. After a new config is added, the next * resource mutation is streamed to the new location in addition to the existing ones. When a location is removed * from the list, the server stops streaming to that location. Before adding a new config, you must add the required * bigquery.dataEditor role to your project's Cloud Healthcare Service Agent service account. Some lag (typically on * the order of dozens of seconds) is expected before the results show up in the streaming destination. * Structure is documented below. */ public readonly streamConfigs!: pulumi.Output<outputs.healthcare.FhirStoreStreamConfig[] | undefined>; /** * The FHIR specification version. * Default value is `STU3`. * Possible values are `DSTU2`, `STU3`, and `R4`. */ public readonly version!: pulumi.Output<string | undefined>; /** * Create a FhirStore resource with the given unique name, arguments, and options. * * @param name The _unique_ name of the resource. * @param args The arguments to use to populate this resource's properties. * @param opts A bag of options that control this resource's behavior. */ constructor(name: string, args: FhirStoreArgs, opts?: pulumi.CustomResourceOptions) constructor(name: string, argsOrState?: FhirStoreArgs | FhirStoreState, opts?: pulumi.CustomResourceOptions) { let inputs: pulumi.Inputs = {}; opts = opts || {}; if (opts.id) { const state = argsOrState as FhirStoreState | undefined; inputs["dataset"] = state ? state.dataset : undefined; inputs["disableReferentialIntegrity"] = state ? state.disableReferentialIntegrity : undefined; inputs["disableResourceVersioning"] = state ? state.disableResourceVersioning : undefined; inputs["enableHistoryImport"] = state ? state.enableHistoryImport : undefined; inputs["enableUpdateCreate"] = state ? state.enableUpdateCreate : undefined; inputs["labels"] = state ? state.labels : undefined; inputs["name"] = state ? state.name : undefined; inputs["notificationConfig"] = state ? state.notificationConfig : undefined; inputs["selfLink"] = state ? state.selfLink : undefined; inputs["streamConfigs"] = state ? state.streamConfigs : undefined; inputs["version"] = state ? state.version : undefined; } else { const args = argsOrState as FhirStoreArgs | undefined; if ((!args || args.dataset === undefined) && !opts.urn) { throw new Error("Missing required property 'dataset'"); } inputs["dataset"] = args ? args.dataset : undefined; inputs["disableReferentialIntegrity"] = args ? args.disableReferentialIntegrity : undefined; inputs["disableResourceVersioning"] = args ? args.disableResourceVersioning : undefined; inputs["enableHistoryImport"] = args ? args.enableHistoryImport : undefined; inputs["enableUpdateCreate"] = args ? args.enableUpdateCreate : undefined; inputs["labels"] = args ? args.labels : undefined; inputs["name"] = args ? args.name : undefined; inputs["notificationConfig"] = args ? args.notificationConfig : undefined; inputs["streamConfigs"] = args ? args.streamConfigs : undefined; inputs["version"] = args ? args.version : undefined; inputs["selfLink"] = undefined /*out*/; } if (!opts.version) { opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()}); } super(FhirStore.__pulumiType, name, inputs, opts); } } /** * Input properties used for looking up and filtering FhirStore resources. */ export interface FhirStoreState { /** * Identifies the dataset addressed by this request. Must be in the format * 'projects/{project}/locations/{location}/datasets/{dataset}' */ dataset?: pulumi.Input<string>; /** * Whether to disable referential integrity in this FHIR store. This field is immutable after FHIR store * creation. The default value is false, meaning that the API will enforce referential integrity and fail the * requests that will result in inconsistent state in the FHIR store. When this field is set to true, the API * will skip referential integrity check. Consequently, operations that rely on references, such as * Patient.get$everything, will not return all the results if broken references exist. * ** Changing this property may recreate the FHIR store (removing all data) ** */ disableReferentialIntegrity?: pulumi.Input<boolean>; /** * Whether to disable resource versioning for this FHIR store. This field can not be changed after the creation * of FHIR store. If set to false, which is the default behavior, all write operations will cause historical * versions to be recorded automatically. The historical versions can be fetched through the history APIs, but * cannot be updated. If set to true, no historical versions will be kept. The server will send back errors for * attempts to read the historical versions. * ** Changing this property may recreate the FHIR store (removing all data) ** */ disableResourceVersioning?: pulumi.Input<boolean>; /** * Whether to allow the bulk import API to accept history bundles and directly insert historical resource * versions into the FHIR store. Importing resource histories creates resource interactions that appear to have * occurred in the past, which clients may not want to allow. If set to false, history bundles within an import * will fail with an error. * ** Changing this property may recreate the FHIR store (removing all data) ** * ** This property can be changed manually in the Google Cloud Healthcare admin console without recreating the FHIR store ** */ enableHistoryImport?: pulumi.Input<boolean>; /** * Whether this FHIR store has the updateCreate capability. This determines if the client can use an Update * operation to create a new resource with a client-specified ID. If false, all IDs are server-assigned through * the Create operation and attempts to Update a non-existent resource will return errors. Please treat the audit * logs with appropriate levels of care if client-specified resource IDs contain sensitive data such as patient * identifiers, those IDs will be part of the FHIR resource path recorded in Cloud audit logs and Cloud Pub/Sub * notifications. */ enableUpdateCreate?: pulumi.Input<boolean>; /** * User-supplied key-value pairs used to organize FHIR stores. * Label keys must be between 1 and 63 characters long, have a UTF-8 encoding of maximum 128 bytes, and must * conform to the following PCRE regular expression: [\p{Ll}\p{Lo}][\p{Ll}\p{Lo}\p{N}_-]{0,62} * Label values are optional, must be between 1 and 63 characters long, have a UTF-8 encoding of maximum 128 * bytes, and must conform to the following PCRE regular expression: [\p{Ll}\p{Lo}\p{N}_-]{0,63} * No more than 64 labels can be associated with a given store. * An object containing a list of "key": value pairs. * Example: { "name": "wrench", "mass": "1.3kg", "count": "3" }. */ labels?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; /** * The resource name for the FhirStore. * ** Changing this property may recreate the FHIR store (removing all data) ** */ name?: pulumi.Input<string>; /** * A nested object resource * Structure is documented below. */ notificationConfig?: pulumi.Input<inputs.healthcare.FhirStoreNotificationConfig>; /** * The fully qualified name of this dataset */ selfLink?: pulumi.Input<string>; /** * A list of streaming configs that configure the destinations of streaming export for every resource mutation in * this FHIR store. Each store is allowed to have up to 10 streaming configs. After a new config is added, the next * resource mutation is streamed to the new location in addition to the existing ones. When a location is removed * from the list, the server stops streaming to that location. Before adding a new config, you must add the required * bigquery.dataEditor role to your project's Cloud Healthcare Service Agent service account. Some lag (typically on * the order of dozens of seconds) is expected before the results show up in the streaming destination. * Structure is documented below. */ streamConfigs?: pulumi.Input<pulumi.Input<inputs.healthcare.FhirStoreStreamConfig>[]>; /** * The FHIR specification version. * Default value is `STU3`. * Possible values are `DSTU2`, `STU3`, and `R4`. */ version?: pulumi.Input<string>; } /** * The set of arguments for constructing a FhirStore resource. */ export interface FhirStoreArgs { /** * Identifies the dataset addressed by this request. Must be in the format * 'projects/{project}/locations/{location}/datasets/{dataset}' */ dataset: pulumi.Input<string>; /** * Whether to disable referential integrity in this FHIR store. This field is immutable after FHIR store * creation. The default value is false, meaning that the API will enforce referential integrity and fail the * requests that will result in inconsistent state in the FHIR store. When this field is set to true, the API * will skip referential integrity check. Consequently, operations that rely on references, such as * Patient.get$everything, will not return all the results if broken references exist. * ** Changing this property may recreate the FHIR store (removing all data) ** */ disableReferentialIntegrity?: pulumi.Input<boolean>; /** * Whether to disable resource versioning for this FHIR store. This field can not be changed after the creation * of FHIR store. If set to false, which is the default behavior, all write operations will cause historical * versions to be recorded automatically. The historical versions can be fetched through the history APIs, but * cannot be updated. If set to true, no historical versions will be kept. The server will send back errors for * attempts to read the historical versions. * ** Changing this property may recreate the FHIR store (removing all data) ** */ disableResourceVersioning?: pulumi.Input<boolean>; /** * Whether to allow the bulk import API to accept history bundles and directly insert historical resource * versions into the FHIR store. Importing resource histories creates resource interactions that appear to have * occurred in the past, which clients may not want to allow. If set to false, history bundles within an import * will fail with an error. * ** Changing this property may recreate the FHIR store (removing all data) ** * ** This property can be changed manually in the Google Cloud Healthcare admin console without recreating the FHIR store ** */ enableHistoryImport?: pulumi.Input<boolean>; /** * Whether this FHIR store has the updateCreate capability. This determines if the client can use an Update * operation to create a new resource with a client-specified ID. If false, all IDs are server-assigned through * the Create operation and attempts to Update a non-existent resource will return errors. Please treat the audit * logs with appropriate levels of care if client-specified resource IDs contain sensitive data such as patient * identifiers, those IDs will be part of the FHIR resource path recorded in Cloud audit logs and Cloud Pub/Sub * notifications. */ enableUpdateCreate?: pulumi.Input<boolean>; /** * User-supplied key-value pairs used to organize FHIR stores. * Label keys must be between 1 and 63 characters long, have a UTF-8 encoding of maximum 128 bytes, and must * conform to the following PCRE regular expression: [\p{Ll}\p{Lo}][\p{Ll}\p{Lo}\p{N}_-]{0,62} * Label values are optional, must be between 1 and 63 characters long, have a UTF-8 encoding of maximum 128 * bytes, and must conform to the following PCRE regular expression: [\p{Ll}\p{Lo}\p{N}_-]{0,63} * No more than 64 labels can be associated with a given store. * An object containing a list of "key": value pairs. * Example: { "name": "wrench", "mass": "1.3kg", "count": "3" }. */ labels?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; /** * The resource name for the FhirStore. * ** Changing this property may recreate the FHIR store (removing all data) ** */ name?: pulumi.Input<string>; /** * A nested object resource * Structure is documented below. */ notificationConfig?: pulumi.Input<inputs.healthcare.FhirStoreNotificationConfig>; /** * A list of streaming configs that configure the destinations of streaming export for every resource mutation in * this FHIR store. Each store is allowed to have up to 10 streaming configs. After a new config is added, the next * resource mutation is streamed to the new location in addition to the existing ones. When a location is removed * from the list, the server stops streaming to that location. Before adding a new config, you must add the required * bigquery.dataEditor role to your project's Cloud Healthcare Service Agent service account. Some lag (typically on * the order of dozens of seconds) is expected before the results show up in the streaming destination. * Structure is documented below. */ streamConfigs?: pulumi.Input<pulumi.Input<inputs.healthcare.FhirStoreStreamConfig>[]>; /** * The FHIR specification version. * Default value is `STU3`. * Possible values are `DSTU2`, `STU3`, and `R4`. */ version?: pulumi.Input<string>; }
the_stack
import { BigNumber } from "bignumber.js"; import * as t from "io-ts"; import * as Knex from "knex"; import { AccountTransactionHistoryRow, Action, Coin, SortLimitParams } from "../../types"; import { Price, Shares, Tokens } from "../../utils/dimension-quantity"; import { getTotalFees, getTradeCost } from "../../utils/financial-math"; import { queryModifier } from "./database"; export const GetAccountTransactionHistoryParams = t.intersection([ SortLimitParams, t.type({ universe: t.string, account: t.string, earliestTransactionTime: t.number, latestTransactionTime: t.number, coin: t.string, action: t.union([t.string, t.null, t.undefined]), }), ]); type GetAccountTransactionHistoryParamsType = t.TypeOf<typeof GetAccountTransactionHistoryParams>; async function transformQueryResults(db: Knex, queryResults: Array<AccountTransactionHistoryRow<BigNumber>>) { return await Promise.all(queryResults.map(async (queryResult: AccountTransactionHistoryRow<BigNumber>) => { const divisor = new BigNumber(10 ** 18); if (queryResult.action === Action.BUY || queryResult.action === Action.SELL) { const { tradeCost } = getTradeCost({ marketMinPrice: new Price(queryResult.minPrice), marketMaxPrice: new Price(queryResult.maxPrice), tradeBuyOrSell: queryResult.action === Action.BUY ? "buy" : "sell", tradeQuantity: new Shares(queryResult.quantity), tradePrice: new Price(queryResult.price), }); const { totalFees } = getTotalFees({ reporterFees: new Tokens(queryResult.reporterFees), marketCreatorFees: new Tokens(queryResult.marketCreatorFees), }); queryResult.fee = totalFees.magnitude; queryResult.total = tradeCost.magnitude; } else if (queryResult.action === Action.DISPUTE || queryResult.action === Action.INITIAL_REPORT) { queryResult.quantity = queryResult.quantity.dividedBy(divisor); } else if ( queryResult.action === Action.CLAIM_MARKET_CREATOR_FEES || queryResult.action === Action.CLAIM_PARTICIPATION_TOKENS || queryResult.action === Action.CLAIM_TRADING_PROCEEDS || queryResult.action === Action.CLAIM_WINNING_CROWDSOURCERS ) { if (queryResult.action === Action.CLAIM_TRADING_PROCEEDS) { const payoutKey = `payout${queryResult.outcome}` as keyof AccountTransactionHistoryRow<BigNumber>; const payoutAmount = queryResult[payoutKey] as BigNumber; if (payoutAmount) { queryResult.fee = queryResult.numShares.times(new BigNumber(payoutAmount)).minus(queryResult.numPayoutTokens).dividedBy(divisor); if (queryResult.fee.isLessThan(0)) { queryResult.fee = new BigNumber(0); } } } queryResult.quantity = queryResult.quantity.dividedBy(divisor); queryResult.total = queryResult.total.dividedBy(divisor); } else if (queryResult.action === Action.COMPLETE_SETS) { queryResult.price = queryResult.marketType === "scalar" ? queryResult.maxPrice.minus(queryResult.minPrice) : new BigNumber(1); queryResult.total = queryResult.quantity.times(queryResult.price); // Calculate total before subtracting fees queryResult.fee = (queryResult.fee.times(queryResult.total)).plus((queryResult.marketCreatorFees).times(queryResult.total)); // (reporting fee rate * total) + (creator fee rate * total) queryResult.total = queryResult.total.minus(queryResult.fee); // Subtract fees from total } // Ensure outcome is set if (queryResult.payout0 !== null) { if (queryResult.isInvalid) { queryResult.outcomeDescription = "Invalid"; } else { if (queryResult.marketType === "yesNo") { queryResult.outcome = queryResult.payout0.isGreaterThanOrEqualTo(queryResult.payout1) ? 0 : 1; } else if (queryResult.marketType === "scalar") { queryResult.outcome = queryResult.payout0.isGreaterThanOrEqualTo(queryResult.payout1) ? queryResult.payout0.toNumber() : queryResult.payout1.toNumber(); } else if (queryResult.marketType === "categorical") { queryResult.outcome = 0; const maxPayouts = 8; for (let payoutIndex = 1; payoutIndex < maxPayouts; payoutIndex++) { const payoutKey = `payout${payoutIndex}` as keyof AccountTransactionHistoryRow<BigNumber>; if (queryResult[payoutKey] !== null) { const payoutAmount = queryResult[payoutKey] as BigNumber; if (payoutAmount.isGreaterThan(new BigNumber(queryResult.outcome))) { queryResult.outcome = payoutIndex; break; } } } } } } // Ensure outcomeDescription is set if (queryResult.outcome !== null && queryResult.outcomeDescription === null) { if (queryResult.isInvalid) { queryResult.outcomeDescription = "Invalid"; } else if (queryResult.marketType === "yesNo") { if (queryResult.outcome === 0) { queryResult.outcomeDescription = "No"; } else { queryResult.outcomeDescription = "Yes"; } } else if (queryResult.marketType === "scalar") { queryResult.outcomeDescription = queryResult.scalarDenomination; } else if (queryResult.marketType === "categorical") { const outcomeInfo = await db.select("*") .from((qb: Knex.QueryBuilder) => { return qb.select("outcomes.description") .from("outcomes") .where({ marketId: queryResult.marketId, outcome: queryResult.outcome, }); }); queryResult.outcomeDescription = outcomeInfo[0].description; } } delete queryResult.marketId; delete queryResult.marketCreatorFees; delete queryResult.marketType; delete queryResult.minPrice; delete queryResult.maxPrice; delete queryResult.numPayoutTokens; delete queryResult.numShares; delete queryResult.reporterFees; delete queryResult.scalarDenomination; delete queryResult.payout0; delete queryResult.payout1; delete queryResult.payout2; delete queryResult.payout3; delete queryResult.payout4; delete queryResult.payout5; delete queryResult.payout6; delete queryResult.payout7; delete queryResult.isInvalid; return queryResult; })); } function queryBuy(db: Knex, qb: Knex.QueryBuilder, params: GetAccountTransactionHistoryParamsType) { qb.union((qb: Knex.QueryBuilder) => { qb.select( db.raw("? as action", Action.BUY), db.raw("'ETH' as coin"), db.raw("'Buy order' as details"), "markets.marketId", "trades.marketCreatorFees", "markets.marketType", "markets.minPrice", "markets.maxPrice", db.raw("NULL as numPayoutTokens"), db.raw("NULL as numShares"), "trades.reporterFees", "markets.scalarDenomination", db.raw("NULL as fee"), "markets.shortDescription as marketDescription", "outcomes.outcome", db.raw("outcomes.description as outcomeDescription"), db.raw("NULL as payout0"), db.raw("NULL as payout1"), db.raw("NULL as payout2"), db.raw("NULL as payout3"), db.raw("NULL as payout4"), db.raw("NULL as payout5"), db.raw("NULL as payout6"), db.raw("NULL as payout7"), db.raw("NULL as isInvalid"), "trades.price", db.raw("trades.amount as quantity"), db.raw("NULL as total"), "trades.transactionHash", "trades.blockNumber") .from("trades") .join("markets", "markets.marketId", "trades.marketId") .join("outcomes", function() { this .on("outcomes.marketId", "trades.marketId") .on("outcomes.outcome", "trades.outcome"); }) .where({ "trades.orderType": "buy", "trades.creator": params.account, "markets.universe": params.universe, }); }); qb.union((qb: Knex.QueryBuilder) => { qb.select( db.raw("? as action", Action.BUY), db.raw("'ETH' as coin"), db.raw("'Buy order' as details"), "markets.marketId", "trades.marketCreatorFees", "markets.marketType", "markets.minPrice", "markets.maxPrice", db.raw("NULL as numPayoutTokens"), db.raw("NULL as numShares"), "trades.reporterFees", "markets.scalarDenomination", db.raw("NULL as fee"), "markets.shortDescription as marketDescription", "outcomes.outcome", db.raw("outcomes.description as outcomeDescription"), db.raw("NULL as payout0"), db.raw("NULL as payout1"), db.raw("NULL as payout2"), db.raw("NULL as payout3"), db.raw("NULL as payout4"), db.raw("NULL as payout5"), db.raw("NULL as payout6"), db.raw("NULL as payout7"), db.raw("NULL as isInvalid"), "trades.price", db.raw("trades.amount as quantity"), db.raw("NULL as total"), "trades.transactionHash", "trades.blockNumber") .from("trades") .join("markets", "markets.marketId", "trades.marketId") .join("outcomes", function() { this .on("outcomes.marketId", "trades.marketId") .on("outcomes.outcome", "trades.outcome"); }) .where({ "trades.orderType": "sell", "trades.filler": params.account, "markets.universe": params.universe, }); }); return qb; } function querySell(db: Knex, qb: Knex.QueryBuilder, params: GetAccountTransactionHistoryParamsType) { qb.union((qb: Knex.QueryBuilder) => { qb.select( db.raw("? as action", Action.SELL), db.raw("'ETH' as coin"), db.raw("'Sell order' as details"), "markets.marketId", "trades.marketCreatorFees", "markets.marketType", "markets.minPrice", "markets.maxPrice", db.raw("NULL as numPayoutTokens"), db.raw("NULL as numShares"), "trades.reporterFees", "markets.scalarDenomination", db.raw("NULL as fee"), "markets.shortDescription as marketDescription", "outcomes.outcome", db.raw("outcomes.description as outcomeDescription"), db.raw("NULL as payout0"), db.raw("NULL as payout1"), db.raw("NULL as payout2"), db.raw("NULL as payout3"), db.raw("NULL as payout4"), db.raw("NULL as payout5"), db.raw("NULL as payout6"), db.raw("NULL as payout7"), db.raw("NULL as isInvalid"), "trades.price", db.raw("trades.amount as quantity"), db.raw("NULL as total"), "trades.transactionHash", "trades.blockNumber") .from("trades") .join("markets", "markets.marketId", "trades.marketId") .join("outcomes", function() { this .on("outcomes.marketId", "trades.marketId") .on("outcomes.outcome", "trades.outcome"); }) .where({ "trades.orderType": "sell", "trades.creator": params.account, "markets.universe": params.universe, }); }); qb.union((qb: Knex.QueryBuilder) => { qb.select( db.raw("? as action", Action.SELL), db.raw("'ETH' as coin"), db.raw("'Sell order' as details"), "markets.marketId", "trades.marketCreatorFees", "markets.marketType", "markets.minPrice", "markets.maxPrice", db.raw("NULL as numPayoutTokens"), db.raw("NULL as numShares"), "trades.reporterFees", "markets.scalarDenomination", db.raw("NULL as fee"), "markets.shortDescription as marketDescription", "outcomes.outcome", db.raw("outcomes.description as outcomeDescription"), db.raw("NULL as payout0"), db.raw("NULL as payout1"), db.raw("NULL as payout2"), db.raw("NULL as payout3"), db.raw("NULL as payout4"), db.raw("NULL as payout5"), db.raw("NULL as payout6"), db.raw("NULL as payout7"), db.raw("NULL as isInvalid"), "trades.price", db.raw("trades.amount as quantity"), db.raw("NULL as total"), "trades.transactionHash", "trades.blockNumber") .from("trades") .join("markets", "markets.marketId", "trades.marketId") .join("outcomes", function() { this .on("outcomes.marketId", "trades.marketId") .on("outcomes.outcome", "trades.outcome"); }) .where({ "trades.orderType": "buy", "trades.filler": params.account, "markets.universe": params.universe, }); }); return qb; } function queryCanceled(db: Knex, qb: Knex.QueryBuilder, params: GetAccountTransactionHistoryParamsType) { return qb.select( db.raw("? as action", Action.CANCEL), db.raw("'ETH' as coin"), db.raw("'Canceled order' as details"), "markets.marketId", db.raw("NULL as marketCreatorFees"), "markets.marketType", db.raw("NULL as minPrice"), db.raw("NULL as maxPrice"), db.raw("NULL as numPayoutTokens"), db.raw("NULL as numShares"), db.raw("NULL as reporterFees"), "markets.scalarDenomination", db.raw("'0' as fee"), "markets.shortDescription as marketDescription", "outcomes.outcome", db.raw("outcomes.description as outcomeDescription"), db.raw("NULL as payout0"), db.raw("NULL as payout1"), db.raw("NULL as payout2"), db.raw("NULL as payout3"), db.raw("NULL as payout4"), db.raw("NULL as payout5"), db.raw("NULL as payout6"), db.raw("NULL as payout7"), db.raw("NULL as isInvalid"), db.raw("orders.price as price"), db.raw("orders.amount as quantity"), db.raw("'0' as total"), "orders_canceled.transactionHash", "orders_canceled.blockNumber") .from("orders_canceled") .join("markets", "markets.marketId", "orders.marketId") .join("orders", "orders.orderId", "orders_canceled.orderId") .join("outcomes", function() { this .on("outcomes.marketId", "orders.marketId") .on("outcomes.outcome", "orders.outcome"); }) .where({ "orders.orderCreator": params.account, "markets.universe": params.universe, }); } function queryClaimMarketCreatorFees(db: Knex, qb: Knex.QueryBuilder, params: GetAccountTransactionHistoryParamsType) { return qb.select( db.raw("? as action", Action.CLAIM_MARKET_CREATOR_FEES), db.raw("'ETH' as coin"), db.raw("'Claimed market creator fees' as details"), "markets.marketId", db.raw("NULL as marketCreatorFees"), "markets.marketType", db.raw("NULL as minPrice"), db.raw("NULL as maxPrice"), db.raw("NULL as numPayoutTokens"), db.raw("NULL as numShares"), db.raw("NULL as reporterFees"), "markets.scalarDenomination", db.raw("'0' as fee"), db.raw("markets.shortDescription as marketDescription"), db.raw("NULL as outcome"), db.raw("NULL as outcomeDescription"), db.raw("NULL as payout0"), db.raw("NULL as payout1"), db.raw("NULL as payout2"), db.raw("NULL as payout3"), db.raw("NULL as payout4"), db.raw("NULL as payout5"), db.raw("NULL as payout6"), db.raw("NULL as payout7"), db.raw("NULL as isInvalid"), db.raw("'0' as price"), db.raw("'0' as quantity"), db.raw("transfers.value as total"), "transfers.transactionHash", "transfers.blockNumber") .from("transfers") .join("markets", "markets.marketCreatorMailbox", "transfers.sender") .whereNull("transfers.recipient") .where({ "markets.marketCreator": params.account, "markets.universe": params.universe, }); } function queryClaimParticipationTokens(db: Knex, qb: Knex.QueryBuilder, params: GetAccountTransactionHistoryParamsType) { return qb.select( db.raw("? as action", Action.CLAIM_PARTICIPATION_TOKENS), db.raw("'ETH' as coin"), db.raw("'Claimed reporting fees from participation tokens' as details"), db.raw("NULL as marketId"), db.raw("NULL as marketCreatorFees"), db.raw("NULL as marketType"), db.raw("NULL as minPrice"), db.raw("NULL as maxPrice"), db.raw("NULL as numPayoutTokens"), db.raw("NULL as numShares"), db.raw("NULL as reporterFees"), db.raw("NULL as scalarDenomination"), db.raw("'0' as fee"), db.raw("'' as marketDescription"), db.raw("NULL as outcome"), db.raw("NULL as outcomeDescription"), db.raw("NULL as payout0"), db.raw("NULL as payout1"), db.raw("NULL as payout2"), db.raw("NULL as payout3"), db.raw("NULL as payout4"), db.raw("NULL as payout5"), db.raw("NULL as payout6"), db.raw("NULL as payout7"), db.raw("NULL as isInvalid"), db.raw("'0' as price"), db.raw("'0' as quantity"), db.raw("participation_token_redeemed.reportingFeesReceived as total"), "participation_token_redeemed.transactionHash", "participation_token_redeemed.blockNumber") .from("participation_token_redeemed") .join("fee_windows", "fee_windows.feeWindow", "participation_token_redeemed.feeWindow") .where({ "participation_token_redeemed.reporter": params.account, "fee_windows.universe": params.universe, }); } function queryClaimTradingProceeds(db: Knex, qb: Knex.QueryBuilder, params: GetAccountTransactionHistoryParamsType) { return qb.select( db.raw("? as action", Action.CLAIM_TRADING_PROCEEDS), db.raw("'ETH' as coin"), db.raw("'Claimed trading proceeds' as details"), "markets.marketId", db.raw("NULL as marketCreatorFees"), "markets.marketType", db.raw("NULL as minPrice"), db.raw("NULL as maxPrice"), "trading_proceeds.numPayoutTokens", "trading_proceeds.numShares", db.raw("NULL as reporterFees"), "markets.scalarDenomination", db.raw("NULL as fee"), "markets.shortDescription as marketDescription", "outcomes.outcome", db.raw("outcomes.description as outcomeDescription"), "payouts.payout0", "payouts.payout1", "payouts.payout2", "payouts.payout3", "payouts.payout4", "payouts.payout5", "payouts.payout6", "payouts.payout7", "payouts.isInvalid", "outcomes.price", db.raw("trading_proceeds.numShares as quantity"), db.raw("trading_proceeds.numPayoutTokens as total"), "trading_proceeds.transactionHash", "trading_proceeds.blockNumber") .from("trading_proceeds") .join("markets", "markets.marketId", "trading_proceeds.marketId") .join("payouts", "payouts.marketId", "markets.marketId") .join("tokens", "tokens.contractAddress", "trading_proceeds.shareToken") .join("outcomes", function() { this .on("outcomes.marketId", "tokens.marketId") .on("outcomes.outcome", "tokens.outcome"); }) .where({ "trading_proceeds.account": params.account, "markets.universe": params.universe, }); } function queryClaimWinningCrowdsourcers(db: Knex, qb: Knex.QueryBuilder, params: GetAccountTransactionHistoryParamsType) { if (params.coin === Coin.ETH || params.coin === Coin.ALL) { // Get ETH reporting fees claimed from winning crowdsourcers qb.union((qb: Knex.QueryBuilder) => { qb.select( db.raw("? as action", Action.CLAIM_WINNING_CROWDSOURCERS), db.raw("'ETH' as coin"), db.raw("'Claimed reporting fees from crowdsourcers' as details"), "markets.marketId", db.raw("NULL as marketCreatorFees"), "markets.marketType", db.raw("NULL as minPrice"), db.raw("NULL as maxPrice"), db.raw("NULL as numPayoutTokens"), db.raw("NULL as numShares"), db.raw("NULL as reporterFees"), "markets.scalarDenomination", db.raw("'0' as fee"), "markets.shortDescription as marketDescription", db.raw("NULL as outcome"), db.raw("NULL as outcomeDescription"), "payouts.payout0", "payouts.payout1", "payouts.payout2", "payouts.payout3", "payouts.payout4", "payouts.payout5", "payouts.payout6", "payouts.payout7", "payouts.isInvalid", db.raw("'0' as price"), db.raw("'0' as quantity"), db.raw("crowdsourcer_redeemed.reportingFeesReceived as total"), "crowdsourcer_redeemed.transactionHash", "crowdsourcer_redeemed.blockNumber") .from("crowdsourcer_redeemed") .join("markets", "markets.marketId", "crowdsourcers.marketId") .join("crowdsourcers", "crowdsourcers.crowdsourcerId", "crowdsourcer_redeemed.crowdsourcer") .join("payouts", function() { this .on("payouts.payoutId", "crowdsourcers.payoutId") .on("payouts.marketId", "markets.marketId"); }) .where({ "crowdsourcer_redeemed.reporter": params.account, "markets.universe": params.universe, }); }); } if (params.coin === Coin.REP || params.coin === Coin.ALL) { // Get REP claimed from winning crowdsourcers qb.union((qb: Knex.QueryBuilder) => { qb.select( db.raw("? as action", Action.CLAIM_WINNING_CROWDSOURCERS), db.raw("'REP' as coin"), db.raw("'Claimed REP fees from crowdsourcers' as details"), "markets.marketId", db.raw("NULL as marketCreatorFees"), "markets.marketType", db.raw("NULL as minPrice"), db.raw("NULL as maxPrice"), db.raw("NULL as numPayoutTokens"), db.raw("NULL as numShares"), db.raw("NULL as reporterFees"), "markets.scalarDenomination", db.raw("'0' as fee"), "markets.shortDescription as marketDescription", db.raw("NULL as outcome"), db.raw("NULL as outcomeDescription"), "payouts.payout0", "payouts.payout1", "payouts.payout2", "payouts.payout3", "payouts.payout4", "payouts.payout5", "payouts.payout6", "payouts.payout7", "payouts.isInvalid", db.raw("'0' as price"), db.raw("'0' as quantity"), db.raw("crowdsourcer_redeemed.repReceived as total"), "crowdsourcer_redeemed.transactionHash", "crowdsourcer_redeemed.blockNumber") .from("crowdsourcer_redeemed") .join("markets", "markets.marketId", "crowdsourcers.marketId") .join("crowdsourcers", "crowdsourcers.crowdsourcerId", "crowdsourcer_redeemed.crowdsourcer") .join("payouts", function() { this .on("payouts.payoutId", "crowdsourcers.payoutId") .on("payouts.marketId", "markets.marketId"); }) .where({ "crowdsourcer_redeemed.reporter": params.account, "markets.universe": params.universe, }); }); } return qb; } function queryDispute(db: Knex, qb: Knex.QueryBuilder, params: GetAccountTransactionHistoryParamsType) { // Get REP staked in dispute crowdsourcers return qb.select( db.raw("? as action", Action.DISPUTE), db.raw("'REP' as coin"), db.raw("'REP staked in dispute crowdsourcers' as details"), "markets.marketId", db.raw("NULL as marketCreatorFees"), "markets.marketType", db.raw("NULL as minPrice"), db.raw("NULL as maxPrice"), db.raw("NULL as numPayoutTokens"), db.raw("NULL as numShares"), db.raw("NULL as reporterFees"), "markets.scalarDenomination", db.raw("'0' as fee"), "markets.shortDescription as marketDescription", db.raw("NULL as outcome"), db.raw("NULL as outcomeDescription"), "payouts.payout0", "payouts.payout1", "payouts.payout2", "payouts.payout3", "payouts.payout4", "payouts.payout5", "payouts.payout6", "payouts.payout7", "payouts.isInvalid", db.raw("'0' as price"), db.raw("disputes.amountStaked as quantity"), db.raw("'0' as total"), "disputes.transactionHash", "disputes.blockNumber") .from("disputes") .join("crowdsourcers", "crowdsourcers.crowdsourcerId", "disputes.crowdsourcerId") .join("payouts", "payouts.payoutId", "crowdsourcers.payoutId") .join("markets", "markets.marketId", "crowdsourcers.marketId") .where({ "disputes.reporter": params.account, "markets.universe": params.universe, }); } function queryInitialReport(db: Knex, qb: Knex.QueryBuilder, params: GetAccountTransactionHistoryParamsType) { // Get REP staked in initial reports return qb.select( db.raw("? as action", Action.INITIAL_REPORT), db.raw("'REP' as coin"), db.raw("'REP staked in initial reports' as details"), "markets.marketId", db.raw("NULL as marketCreatorFees"), "markets.marketType", db.raw("NULL as minPrice"), db.raw("NULL as maxPrice"), db.raw("NULL as numPayoutTokens"), db.raw("NULL as numShares"), db.raw("NULL as reporterFees"), "markets.scalarDenomination", db.raw("'0' as fee"), "markets.shortDescription as marketDescription", db.raw("NULL as outcome"), db.raw("NULL as outcomeDescription"), "payouts.payout0", "payouts.payout1", "payouts.payout2", "payouts.payout3", "payouts.payout4", "payouts.payout5", "payouts.payout6", "payouts.payout7", "payouts.isInvalid", db.raw("'0' as price"), "initial_reports.amountStaked as quantity", db.raw("'0' as total"), "initial_reports.transactionHash", "initial_reports.blockNumber") .from("initial_reports") .join("payouts", "payouts.payoutId", "initial_reports.payoutId") .join("markets", "markets.marketId", "initial_reports.marketId") .where({ "initial_reports.reporter": params.account, "markets.universe": params.universe, }); } function queryMarketCreation(db: Knex, qb: Knex.QueryBuilder, params: GetAccountTransactionHistoryParamsType) { return qb.select( db.raw("? as action", Action.MARKET_CREATION), db.raw("'ETH' as coin"), db.raw("'ETH validity bond for market creation' as details"), "markets.marketId", db.raw("NULL as marketCreatorFees"), "markets.marketType", db.raw("NULL as minPrice"), db.raw("NULL as maxPrice"), db.raw("NULL as numPayoutTokens"), db.raw("NULL as numShares"), db.raw("NULL as reporterFees"), "markets.scalarDenomination", db.raw("markets.creationFee as fee"), "markets.shortDescription as marketDescription", db.raw("NULL as outcome"), db.raw("NULL as outcomeDescription"), db.raw("NULL as payout0"), db.raw("NULL as payout1"), db.raw("NULL as payout2"), db.raw("NULL as payout3"), db.raw("NULL as payout4"), db.raw("NULL as payout5"), db.raw("NULL as payout6"), db.raw("NULL as payout7"), db.raw("NULL as isInvalid"), db.raw("'0' as price"), db.raw("'0' as quantity"), db.raw("'0' as total"), "markets.transactionHash", db.raw("markets.creationBlockNumber as blockNumber")) .from("markets") .where({ "markets.marketCreator": params.account, "markets.universe": params.universe, }); } function queryCompleteSets(db: Knex, qb: Knex.QueryBuilder, params: GetAccountTransactionHistoryParamsType) { // Get complete sets bought qb.union((qb: Knex.QueryBuilder) => { qb.select( db.raw("? as action", Action.COMPLETE_SETS), db.raw("'ETH' as coin"), db.raw("'Buy complete sets' as details"), "markets.marketId", db.raw("NULL as marketCreatorFees"), "markets.marketType", "markets.minPrice", "markets.maxPrice", db.raw("NULL as numPayoutTokens"), db.raw("NULL as numShares"), db.raw("NULL as reporterFees"), "markets.scalarDenomination", db.raw("'0' as fee"), "markets.shortDescription as marketDescription", db.raw("NULL as outcome"), db.raw("NULL as outcomeDescription"), db.raw("NULL as payout0"), db.raw("NULL as payout1"), db.raw("NULL as payout2"), db.raw("NULL as payout3"), db.raw("NULL as payout4"), db.raw("NULL as payout5"), db.raw("NULL as payout6"), db.raw("NULL as payout7"), db.raw("NULL as isInvalid"), db.raw("markets.numTicks as price"), db.raw("completeSets.numCompleteSets as quantity"), db.raw("'0' as total"), "completeSets.transactionHash", "completeSets.blockNumber") .from("completeSets") .join("markets", "markets.marketId", "completeSets.marketId") .where({ "completeSets.eventName": "CompleteSetsPurchased", "completeSets.account": params.account, "markets.universe": params.universe, }); }); // Get complete sets sold qb.union((qb: Knex.QueryBuilder) => { qb.select( db.raw("? as action", Action.COMPLETE_SETS), db.raw("'ETH' as coin"), db.raw("'Sell complete sets' as details"), "markets.marketId", db.raw("markets.marketCreatorFeeRate as marketCreatorFees"), "markets.marketType", "markets.minPrice", "markets.maxPrice", db.raw("NULL as numPayoutTokens"), db.raw("NULL as numShares"), db.raw("NULL as reporterFees"), "markets.scalarDenomination", db.raw("fee_windows.fees as fee"), "markets.shortDescription as marketDescription", db.raw("NULL as outcome"), db.raw("NULL as outcomeDescription"), db.raw("NULL as payout0"), db.raw("NULL as payout1"), db.raw("NULL as payout2"), db.raw("NULL as payout3"), db.raw("NULL as payout4"), db.raw("NULL as payout5"), db.raw("NULL as payout6"), db.raw("NULL as payout7"), db.raw("NULL as isInvalid"), "markets.numTicks as price", "completeSets.numCompleteSets as quantity", db.raw("'0' as total"), "completeSets.transactionHash", "completeSets.blockNumber") .from("completeSets") .join("markets", "markets.marketId", "completeSets.marketId") .join("fee_windows", "fee_windows.universe", "markets.universe") .join("blocks", "blocks.blockNumber", "completeSets.blockNumber") .whereRaw("blocks.timestamp between fee_windows.startTime and fee_windows.endTime") .where({ "completeSets.eventName": "CompleteSetsSold", "completeSets.account": params.account, "markets.universe": params.universe, }); }); return qb; } export async function getAccountTransactionHistory(db: Knex, augur: {}, params: GetAccountTransactionHistoryParamsType) { params.account = params.account.toLowerCase(); params.universe = params.universe.toLowerCase(); const query = db.select("data.*", "blocks.timestamp").from((qb: Knex.QueryBuilder) => { if ((params.action === Action.BUY || params.action === Action.ALL) && (params.coin === Coin.ETH || params.coin === Coin.ALL)) { qb.union((qb: Knex.QueryBuilder) => { queryBuy(db, qb, params); }); } if ((params.action === Action.SELL || params.action === Action.ALL) && (params.coin === Coin.ETH || params.coin === Coin.ALL)) { qb.union((qb: Knex.QueryBuilder) => { querySell(db, qb, params); }); } if ((params.action === Action.CANCEL || params.action === Action.ALL) && (params.coin === Coin.ETH || params.coin === Coin.ALL)) { qb.union((qb: Knex.QueryBuilder) => { queryCanceled(db, qb, params); }); } if ((params.action === Action.CLAIM_MARKET_CREATOR_FEES || params.action === Action.ALL) && (params.coin === Coin.ETH || params.coin === Coin.ALL)) { qb.union((qb: Knex.QueryBuilder) => { queryClaimMarketCreatorFees(db, qb, params); }); } if ((params.action === Action.CLAIM_PARTICIPATION_TOKENS || params.action === Action.ALL) && (params.coin === Coin.ETH || params.coin === Coin.ALL)) { qb.union((qb: Knex.QueryBuilder) => { queryClaimParticipationTokens(db, qb, params); }); } if ((params.action === Action.CLAIM_TRADING_PROCEEDS || params.action === Action.ALL) && (params.coin === Coin.ETH || params.coin === Coin.ALL)) { qb.union((qb: Knex.QueryBuilder) => { queryClaimTradingProceeds(db, qb, params); }); } if (params.action === Action.CLAIM_WINNING_CROWDSOURCERS || params.action === Action.ALL) { qb.union((qb: Knex.QueryBuilder) => { queryClaimWinningCrowdsourcers(db, qb, params); }); } if ((params.action === Action.MARKET_CREATION || params.action === Action.ALL) && (params.coin === Coin.ETH || params.coin === Coin.ALL)) { qb.union((qb: Knex.QueryBuilder) => { queryMarketCreation(db, qb, params); }); } if ((params.action === Action.DISPUTE || params.action === Action.ALL) && (params.coin === Coin.REP || params.coin === Coin.ALL)) { qb.union((qb: Knex.QueryBuilder) => { queryDispute(db, qb, params); }); } if ((params.action === Action.INITIAL_REPORT || params.action === Action.ALL) && (params.coin === Coin.REP || params.coin === Coin.ALL)) { qb.union((qb: Knex.QueryBuilder) => { queryInitialReport(db, qb, params); }); } if ((params.action === Action.COMPLETE_SETS || params.action === Action.ALL) && (params.coin === Coin.ETH || params.coin === Coin.ALL)) { qb.union((qb: Knex.QueryBuilder) => { queryCompleteSets(db, qb, params); }); } if (qb.toString() === "select *") { throw new Error("Invalid action/coin combination"); } qb.as("data"); }) .join("blocks", "data.blockNumber", "blocks.blockNumber") .whereBetween("blocks.timestamp", [params.earliestTransactionTime, params.latestTransactionTime]); const accountTransactionHistory: Array<AccountTransactionHistoryRow<BigNumber>> = await queryModifier<AccountTransactionHistoryRow<BigNumber>>(db, query, "blocks.timestamp", "desc", params); return await transformQueryResults(db, accountTransactionHistory); }
the_stack
import { HttpClientTestingModule } from '@angular/common/http/testing'; import { fakeAsync, TestBed, tick, waitForAsync } from '@angular/core/testing'; import { EditableExplorationBackendApiService } from 'domain/exploration/editable-exploration-backend-api.service'; import { FetchExplorationBackendResponse, ReadOnlyExplorationBackendApiService } from 'domain/exploration/read-only-exploration-backend-api.service'; import { PretestQuestionBackendApiService } from 'domain/question/pretest-question-backend-api.service'; import { QuestionBackendApiService } from 'domain/question/question-backend-api.service'; import { Question, QuestionBackendDict, QuestionObjectFactory } from 'domain/question/QuestionObjectFactory'; import { ContextService } from 'services/context.service'; import { UrlService } from 'services/contextual/url.service'; import { ExplorationFeatures, ExplorationFeaturesBackendApiService } from 'services/exploration-features-backend-api.service'; import { ExplorationFeaturesService } from 'services/exploration-features.service'; import { PlaythroughService } from 'services/playthrough.service'; import { ExplorationPlayerConstants } from '../exploration-player-page.constants'; import { ExplorationEngineService } from './exploration-engine.service'; import { ExplorationPlayerStateService } from './exploration-player-state.service'; import { NumberAttemptsService } from './number-attempts.service'; import { PlayerCorrectnessFeedbackEnabledService } from './player-correctness-feedback-enabled.service'; import { PlayerTranscriptService } from './player-transcript.service'; import { QuestionPlayerEngineService } from './question-player-engine.service'; import { StatsReportingService } from './stats-reporting.service'; describe('Exploration Player State Service', () => { let explorationPlayerStateService: ExplorationPlayerStateService; let playerTranscriptService: PlayerTranscriptService; let statsReportingService: StatsReportingService; let playthroughService: PlaythroughService; let playerCorrectnessFeedbackEnabledService: PlayerCorrectnessFeedbackEnabledService; let explorationEngineService: ExplorationEngineService; let questionPlayerEngineService: QuestionPlayerEngineService; let editableExplorationBackendApiService: EditableExplorationBackendApiService; let explorationFeaturesBackendApiService: ExplorationFeaturesBackendApiService; let explorationFeaturesService: ExplorationFeaturesService; let numberAttemptsService: NumberAttemptsService; let questionBackendApiService: QuestionBackendApiService; let pretestQuestionBackendApiService: PretestQuestionBackendApiService; let questionObjectFactory: QuestionObjectFactory; let urlService: UrlService; let questionObject: Question; let returnDict = { can_edit: true, exploration: { init_state_name: 'state_name', param_changes: [], param_specs: {}, states: {}, title: '', language_code: '', objective: '', correctness_feedback_enabled: false }, exploration_id: 'test_id', is_logged_in: true, session_id: 'test_session', version: 1, preferred_audio_language_code: 'en', preferred_language_codes: [], auto_tts_enabled: false, correctness_feedback_enabled: true, record_playthrough_probability: 1 }; let questionBackendDict: QuestionBackendDict = { id: '', question_state_data: { classifier_model_id: null, param_changes: [], next_content_id_index: 1, solicit_answer_details: false, content: { content_id: '1', html: 'Question 1' }, written_translations: { translations_mapping: { 1: {}, ca_placeholder_0: {}, feedback_id: {}, solution: {}, hint_1: {} } }, interaction: { answer_groups: [{ outcome: { dest: 'State 1', feedback: { content_id: 'feedback_1', html: '<p>Try Again.</p>' }, param_changes: [], refresher_exploration_id: null, missing_prerequisite_skill_id: null, labelled_as_correct: true, }, rule_specs: [{ rule_type: 'Equals', inputs: {x: 0} }], training_data: null, tagged_skill_misconception_id: null, }, { outcome: { dest: 'State 2', feedback: { content_id: 'feedback_2', html: '<p>Try Again.</p>' }, param_changes: [], refresher_exploration_id: null, missing_prerequisite_skill_id: null, labelled_as_correct: true, }, rule_specs: [{ rule_type: 'Equals', inputs: {x: 0} }], training_data: null, tagged_skill_misconception_id: 'misconceptionId', }], default_outcome: { dest: null, labelled_as_correct: true, missing_prerequisite_skill_id: null, refresher_exploration_id: null, param_changes: [], feedback: { content_id: 'feedback_id', html: '<p>Dummy Feedback</p>' } }, id: 'TextInput', customization_args: { rows: { value: 1 }, placeholder: { value: { unicode_str: '', content_id: 'ca_placeholder_0' } } }, confirmed_unclassified_answers: [], hints: [ { hint_content: { content_id: 'hint_1', html: '<p>This is a hint.</p>' } } ], solution: { correct_answer: 'Solution', explanation: { content_id: 'solution', html: '<p>This is a solution.</p>' }, answer_is_exclusive: false } }, linked_skill_id: null, card_is_checkpoint: true, recorded_voiceovers: { voiceovers_mapping: { 1: {}, ca_placeholder_0: {}, feedback_id: {}, solution: {}, hint_1: {} } } }, question_state_data_schema_version: 2, language_code: '', version: 1, linked_skill_ids: [], inapplicable_skill_misconception_ids: [] }; class MockContextService { isInExplorationEditorPage(): boolean { return false; } isInQuestionPlayerMode(): boolean { return false; } getExplorationId(): string { return '123'; } } class MockReadOnlyExplorationBackendApiService { async loadLatestExplorationAsync(explorationId: string): Promise<FetchExplorationBackendResponse> { return Promise.resolve(returnDict); } async loadExplorationAsync(explorationId: string, version: number): Promise<FetchExplorationBackendResponse> { return Promise.resolve(returnDict); } } beforeEach(waitForAsync(() => { TestBed.configureTestingModule({ imports: [HttpClientTestingModule], providers: [ ExplorationPlayerStateService, PlayerTranscriptService, StatsReportingService, { provide: ContextService, useClass: MockContextService }, UrlService, { provide: ReadOnlyExplorationBackendApiService, useClass: MockReadOnlyExplorationBackendApiService } ] }).compileComponents(); })); beforeEach(() => { explorationPlayerStateService = TestBed .inject(ExplorationPlayerStateService); playerTranscriptService = TestBed.inject(PlayerTranscriptService); playerTranscriptService = (playerTranscriptService as unknown) as jasmine.SpyObj<PlayerTranscriptService>; statsReportingService = TestBed.inject(StatsReportingService); statsReportingService = (statsReportingService as unknown) as jasmine.SpyObj<StatsReportingService>; playthroughService = TestBed.inject(PlaythroughService); playthroughService = (playthroughService as unknown) as jasmine.SpyObj<PlaythroughService>; playerCorrectnessFeedbackEnabledService = TestBed.inject( PlayerCorrectnessFeedbackEnabledService); playerCorrectnessFeedbackEnabledService = ( playerCorrectnessFeedbackEnabledService as unknown) as jasmine.SpyObj<PlayerCorrectnessFeedbackEnabledService>; explorationEngineService = TestBed.inject(ExplorationEngineService); explorationEngineService = (explorationEngineService as unknown) as jasmine.SpyObj<ExplorationEngineService>; questionPlayerEngineService = TestBed.inject(QuestionPlayerEngineService); questionPlayerEngineService = (questionPlayerEngineService as unknown) as jasmine.SpyObj<QuestionPlayerEngineService>; editableExplorationBackendApiService = TestBed.inject( EditableExplorationBackendApiService); editableExplorationBackendApiService = ( editableExplorationBackendApiService as unknown) as jasmine.SpyObj<EditableExplorationBackendApiService>; explorationFeaturesBackendApiService = TestBed.inject( ExplorationFeaturesBackendApiService); explorationFeaturesBackendApiService = ( explorationFeaturesBackendApiService as unknown) as jasmine.SpyObj<ExplorationFeaturesBackendApiService>; explorationFeaturesService = TestBed.inject(ExplorationFeaturesService); explorationFeaturesService = ( explorationFeaturesService as unknown) as jasmine.SpyObj<ExplorationFeaturesService>; numberAttemptsService = TestBed.inject(NumberAttemptsService); numberAttemptsService = ( numberAttemptsService as unknown) as jasmine.SpyObj<NumberAttemptsService>; questionBackendApiService = TestBed.inject(QuestionBackendApiService); questionBackendApiService = ( questionBackendApiService as unknown) as jasmine.SpyObj<QuestionBackendApiService>; pretestQuestionBackendApiService = TestBed.inject( PretestQuestionBackendApiService); pretestQuestionBackendApiService = ( pretestQuestionBackendApiService as unknown) as jasmine.SpyObj<PretestQuestionBackendApiService>; questionObjectFactory = TestBed.inject(QuestionObjectFactory); questionObject = questionObjectFactory.createFromBackendDict( questionBackendDict); urlService = (TestBed.inject(UrlService) as unknown) as jasmine.SpyObj<UrlService>; }); it('should properly initialize player', () => { spyOn(playerTranscriptService, 'init'); spyOn(explorationPlayerStateService, 'initExplorationPreviewPlayer'); let callback = () => {}; explorationPlayerStateService.editorPreviewMode = true; explorationPlayerStateService.initializePlayer(callback); expect(playerTranscriptService.init).toHaveBeenCalled(); expect(explorationPlayerStateService.initExplorationPreviewPlayer) .toHaveBeenCalledWith(callback); explorationPlayerStateService.editorPreviewMode = false; explorationPlayerStateService.initializePlayer(callback); expect(playerTranscriptService.init).toHaveBeenCalled(); expect(explorationPlayerStateService.initExplorationPreviewPlayer) .toHaveBeenCalledWith(callback); }); it('should initialize exploration services', () => { spyOn(statsReportingService, 'initSession'); spyOn(playthroughService, 'initSession'); spyOn(playerCorrectnessFeedbackEnabledService, 'init'); spyOn(explorationEngineService, 'init'); explorationPlayerStateService.initializeExplorationServices( returnDict, false, () => {}); expect(statsReportingService.initSession).toHaveBeenCalled(); expect(playthroughService.initSession).toHaveBeenCalled(); expect(playerCorrectnessFeedbackEnabledService.init).toHaveBeenCalled(); expect(explorationEngineService.init).toHaveBeenCalled(); }); it('should initialize pretest services', () => { spyOn(playerCorrectnessFeedbackEnabledService, 'init'); spyOn(questionPlayerEngineService, 'init'); let pretestQuestionObjects = []; let callback = () => {}; explorationPlayerStateService.initializePretestServices( pretestQuestionObjects, callback); expect(playerCorrectnessFeedbackEnabledService.init) .toHaveBeenCalledWith(true); expect(questionPlayerEngineService.init).toHaveBeenCalled(); }); it('should initialize question player services', () => { spyOn(playerCorrectnessFeedbackEnabledService, 'init'); spyOn(questionPlayerEngineService, 'init'); let questions = [questionBackendDict]; let questionObjects = [questionObject]; let successCallback = () => {}; let errorCallback = () => {}; explorationPlayerStateService.initializeQuestionPlayerServices( questions, successCallback, errorCallback); expect(playerCorrectnessFeedbackEnabledService.init) .toHaveBeenCalledWith(true); expect(questionPlayerEngineService.init).toHaveBeenCalledWith( questionObjects, successCallback, errorCallback); }); it('should set exploration mode', () => { explorationPlayerStateService.setExplorationMode(); expect(explorationPlayerStateService.explorationMode).toEqual( ExplorationPlayerConstants .EXPLORATION_MODE.EXPLORATION); expect(explorationPlayerStateService.currentEngineService) .toEqual(explorationEngineService); }); it('should set pretest mode', () => { explorationPlayerStateService.setPretestMode(); expect(explorationPlayerStateService.explorationMode).toEqual( ExplorationPlayerConstants .EXPLORATION_MODE.PRETEST); expect(explorationPlayerStateService.currentEngineService) .toEqual(questionPlayerEngineService); }); it('should set question player mode', () => { explorationPlayerStateService.setQuestionPlayerMode(); expect(explorationPlayerStateService.explorationMode).toEqual( ExplorationPlayerConstants .EXPLORATION_MODE.QUESTION_PLAYER); expect(explorationPlayerStateService.currentEngineService) .toEqual(questionPlayerEngineService); }); it('should set story chapter mode', () => { explorationPlayerStateService.setStoryChapterMode(); expect(explorationPlayerStateService.explorationMode).toEqual( ExplorationPlayerConstants .EXPLORATION_MODE.STORY_CHAPTER); expect(explorationPlayerStateService.currentEngineService) .toEqual(explorationEngineService); }); it('should init exploration preview player', fakeAsync(() => { spyOn(explorationPlayerStateService, 'setExplorationMode'); spyOn( editableExplorationBackendApiService, 'fetchApplyDraftExplorationAsync') .and.returnValue(Promise.resolve({ correctness_feedback_enabled: false, draft_changes: [], is_version_of_draft_valid: true, init_state_name: '', param_changes: [], param_specs: null, states: null, title: '', language_code: '' })); spyOn(explorationFeaturesBackendApiService, 'fetchExplorationFeaturesAsync') .and.returnValue(Promise.resolve({ isExplorationWhitelisted: true, alwaysAskLearnersForAnswerDetails: false })); spyOn(explorationFeaturesService, 'init'); spyOn(explorationEngineService, 'init'); spyOn(playerCorrectnessFeedbackEnabledService, 'init'); spyOn(numberAttemptsService, 'reset'); explorationPlayerStateService.initExplorationPreviewPlayer(() => {}); tick(); expect(explorationFeaturesService.init).toHaveBeenCalled(); expect(explorationEngineService.init).toHaveBeenCalled(); expect(playerCorrectnessFeedbackEnabledService.init).toHaveBeenCalled(); expect(numberAttemptsService.reset).toHaveBeenCalled(); })); it('should init question player', fakeAsync(() => { spyOn(explorationPlayerStateService, 'setQuestionPlayerMode'); spyOn(questionBackendApiService, 'fetchQuestionsAsync') .and.returnValue(Promise.resolve([questionBackendDict])); spyOn(explorationPlayerStateService.onTotalQuestionsReceived, 'emit'); spyOn(explorationPlayerStateService, 'initializeQuestionPlayerServices'); let successCallback = () => {}; let errorCallback = () => {}; explorationPlayerStateService.initQuestionPlayer({ skillList: [], questionCount: 1, questionsSortedByDifficulty: true }, successCallback, errorCallback); tick(); expect( explorationPlayerStateService .onTotalQuestionsReceived.emit) .toHaveBeenCalled(); expect(explorationPlayerStateService.initializeQuestionPlayerServices) .toHaveBeenCalled(); })); it('should init exploration player', fakeAsync(() => { let explorationFeatures: ExplorationFeatures = { isExplorationWhitelisted: true, alwaysAskLearnersForAnswerDetails: false }; spyOn(explorationFeaturesBackendApiService, 'fetchExplorationFeaturesAsync') .and.returnValue(Promise.resolve(explorationFeatures)); spyOn(pretestQuestionBackendApiService, 'fetchPretestQuestionsAsync') .and.returnValue(Promise.resolve([questionObject])); spyOn(explorationFeaturesService, 'init'); spyOn(explorationPlayerStateService, 'initializePretestServices'); spyOn(explorationPlayerStateService, 'setPretestMode'); spyOn(explorationPlayerStateService, 'initializeExplorationServices'); let successCallback = () => {}; explorationPlayerStateService.initExplorationPlayer(successCallback); tick(); expect(explorationFeaturesService.init).toHaveBeenCalled(); expect(explorationPlayerStateService.setPretestMode).toHaveBeenCalled(); expect(explorationPlayerStateService.initializeExplorationServices) .toHaveBeenCalled(); expect(explorationPlayerStateService.initializePretestServices) .toHaveBeenCalled(); })); it('should init exploration player without pretests', fakeAsync(() => { let explorationFeatures: ExplorationFeatures = { isExplorationWhitelisted: true, alwaysAskLearnersForAnswerDetails: false }; spyOn(explorationFeaturesBackendApiService, 'fetchExplorationFeaturesAsync') .and.returnValue(Promise.resolve(explorationFeatures)); spyOn(pretestQuestionBackendApiService, 'fetchPretestQuestionsAsync') .and.returnValue(Promise.resolve([])); spyOn(explorationFeaturesService, 'init'); spyOn(explorationPlayerStateService, 'setExplorationMode'); spyOn(explorationPlayerStateService, 'initializeExplorationServices'); let successCallback = () => {}; explorationPlayerStateService.initExplorationPlayer(successCallback); tick(); expect(explorationPlayerStateService.setExplorationMode).toHaveBeenCalled(); expect(explorationPlayerStateService.initializeExplorationServices) .toHaveBeenCalled(); })); it('should init exploration player with story chapter mode', fakeAsync(() => { let explorationFeatures: ExplorationFeatures = { isExplorationWhitelisted: true, alwaysAskLearnersForAnswerDetails: false }; spyOn(urlService, 'getUrlParams').and.returnValue({ story_url_fragment: 'fragment', node_id: 'id' }); spyOn( explorationFeaturesBackendApiService, 'fetchExplorationFeaturesAsync') .and.returnValue(Promise.resolve(explorationFeatures)); spyOn(pretestQuestionBackendApiService, 'fetchPretestQuestionsAsync') .and.returnValue(Promise.resolve([])); spyOn(explorationFeaturesService, 'init'); spyOn(explorationPlayerStateService, 'setStoryChapterMode'); spyOn(explorationPlayerStateService, 'initializeExplorationServices'); let successCallback = () => {}; explorationPlayerStateService.initExplorationPlayer(successCallback); tick(); expect(explorationPlayerStateService.setStoryChapterMode) .toHaveBeenCalled(); expect(explorationPlayerStateService.initializeExplorationServices) .toHaveBeenCalled(); })); it('should intialize question player', () => { spyOn(playerTranscriptService, 'init'); spyOn(explorationPlayerStateService, 'initQuestionPlayer'); let successCallback = () => {}; let errorCallback = () => {}; explorationPlayerStateService.initializeQuestionPlayer({ skillList: [], questionCount: 1, questionsSortedByDifficulty: true }, successCallback, errorCallback); }); it('should get current engine service', () => { explorationPlayerStateService.setExplorationMode(); expect(explorationPlayerStateService.getCurrentEngineService()) .toEqual(explorationPlayerStateService.currentEngineService); }); it('should tell if is in pretest mode', () => { explorationPlayerStateService.setPretestMode(); expect(explorationPlayerStateService.isInPretestMode()).toBeTrue(); }); it('should tell if is in question mode', () => { explorationPlayerStateService.setQuestionPlayerMode(); expect(explorationPlayerStateService.isInQuestionMode()).toBeTrue(); }); it('should tell if is in question player mode', () => { explorationPlayerStateService.setQuestionPlayerMode(); expect(explorationPlayerStateService.isInQuestionPlayerMode()).toBeTrue(); }); it('should tell if in story chapter mode', () => { explorationPlayerStateService.setStoryChapterMode(); expect(explorationPlayerStateService.isInStoryChapterMode()).toBeTrue(); }); it('should move to exploration', () => { spyOn(explorationEngineService, 'moveToExploration'); spyOn(explorationPlayerStateService, 'setStoryChapterMode'); spyOn(urlService, 'getUrlParams').and.returnValue({ story_url_fragment: 'fragment', node_id: 'id' }); let callback = () => {}; explorationPlayerStateService.moveToExploration(callback); expect(explorationPlayerStateService.setStoryChapterMode) .toHaveBeenCalled(); expect(explorationEngineService.moveToExploration).toHaveBeenCalled(); }); it('should move to exploration with chapter mode', () => { spyOn(explorationEngineService, 'moveToExploration'); let callback = () => {}; explorationPlayerStateService.moveToExploration(callback); expect(explorationEngineService.moveToExploration).toHaveBeenCalled(); }); it('should get language code', () => { let languageCode: string = 'test_lang_code'; spyOn(explorationEngineService, 'getLanguageCode') .and.returnValue(languageCode); explorationPlayerStateService.setExplorationMode(); expect(explorationPlayerStateService.getLanguageCode()) .toEqual(languageCode); }); it('should record new card added', () => { explorationPlayerStateService.setExplorationMode(); spyOn(explorationEngineService, 'recordNewCardAdded'); explorationPlayerStateService.recordNewCardAdded(); expect(explorationEngineService.recordNewCardAdded).toHaveBeenCalled(); }); it('should test getters', () => { expect(explorationPlayerStateService.onTotalQuestionsReceived) .toBeDefined(); expect(explorationPlayerStateService.onPlayerStateChange).toBeDefined(); expect(explorationPlayerStateService.onOppiaFeedbackAvailable) .toBeDefined(); }); it('should set exploration version from url if the url' + 'has exploration context when initialized', () => { // Here exploration context consists of 'explore', 'create', // 'skill_editor' and 'embed'. spyOn(urlService, 'getPathname') .and.returnValue('/create/in/path/name'); spyOn(urlService, 'getExplorationVersionFromUrl') .and.returnValue(2); explorationPlayerStateService.version = null; explorationPlayerStateService.init(); expect(explorationPlayerStateService.version).toBe(2); }); it('should set exploration version to default value if the url' + 'does not have exploration context when initialized', () => { // Here default value is 1. spyOn(urlService, 'getPathname') .and.returnValue('/create_is_not/in/path/name'); explorationPlayerStateService.version = null; explorationPlayerStateService.init(); expect(explorationPlayerStateService.version).toBe(1); }); });
the_stack
import * as git from 'isomorphic-git'; import path from 'path'; import { GIT_CLONE_DIR, GIT_INSOMNIA_DIR, GitVCS } from '../git-vcs'; import { MemClient } from '../mem-client'; import { setupDateMocks } from './util'; describe('Git-VCS', () => { let fooTxt = ''; let barTxt = ''; beforeAll(() => { fooTxt = path.join(GIT_INSOMNIA_DIR, 'foo.txt'); barTxt = path.join(GIT_INSOMNIA_DIR, 'bar.txt'); }); afterAll(() => jest.restoreAllMocks()); beforeEach(setupDateMocks); describe('common operations', () => { it('listFiles()', async () => { const fsClient = MemClient.createClient(); const vcs = new GitVCS(); await vcs.init({ directory: GIT_CLONE_DIR, fs: fsClient, }); await vcs.setAuthor('Karen Brown', 'karen@example.com'); // No files exist yet const files1 = await vcs.listFiles(); expect(files1).toEqual([]); // File does not exist in git index await fsClient.promises.writeFile('foo.txt', 'bar'); const files2 = await vcs.listFiles(); expect(files2).toEqual([]); }); it('stage and unstage file', async () => { const fsClient = MemClient.createClient(); await fsClient.promises.mkdir(GIT_INSOMNIA_DIR); await fsClient.promises.writeFile(fooTxt, 'foo'); await fsClient.promises.writeFile(barTxt, 'bar'); // Files outside namespace should be ignored await fsClient.promises.writeFile('/other.txt', 'other'); const vcs = new GitVCS(); await vcs.init({ directory: GIT_CLONE_DIR, fs: fsClient, }); await vcs.setAuthor('Karen Brown', 'karen@example.com'); expect(await vcs.status(barTxt)).toBe('*added'); expect(await vcs.status(fooTxt)).toBe('*added'); await vcs.add(fooTxt); expect(await vcs.status(barTxt)).toBe('*added'); expect(await vcs.status(fooTxt)).toBe('added'); await vcs.remove(fooTxt); expect(await vcs.status(barTxt)).toBe('*added'); expect(await vcs.status(fooTxt)).toBe('*added'); }); it('Returns empty log without first commit', async () => { const fsClient = MemClient.createClient(); const vcs = new GitVCS(); await vcs.init({ directory: GIT_CLONE_DIR, fs: fsClient, }); await vcs.setAuthor('Karen Brown', 'karen@example.com'); expect(await vcs.log()).toEqual([]); }); it('commit file', async () => { const fsClient = MemClient.createClient(); await fsClient.promises.mkdir(GIT_INSOMNIA_DIR); await fsClient.promises.writeFile(fooTxt, 'foo'); await fsClient.promises.writeFile(barTxt, 'bar'); await fsClient.promises.writeFile('other.txt', 'should be ignored'); const vcs = new GitVCS(); await vcs.init({ directory: GIT_CLONE_DIR, fs: fsClient, }); await vcs.setAuthor('Karen Brown', 'karen@example.com'); await vcs.add(fooTxt); await vcs.commit('First commit!'); expect(await vcs.status(barTxt)).toBe('*added'); expect(await vcs.status(fooTxt)).toBe('unmodified'); expect(await vcs.log()).toEqual([ { commit: { author: { email: 'karen@example.com', name: 'Karen Brown', timestamp: 1000000000, timezoneOffset: 0, }, committer: { email: 'karen@example.com', name: 'Karen Brown', timestamp: 1000000000, timezoneOffset: 0, }, message: 'First commit!\n', parent: [], tree: '14819d8019f05edb70a29850deb09a4314ad0afc', }, oid: '76f804a23eef9f52017bf93f4bc0bfde45ec8a93', payload: `tree 14819d8019f05edb70a29850deb09a4314ad0afc author Karen Brown <karen@example.com> 1000000000 +0000 committer Karen Brown <karen@example.com> 1000000000 +0000 First commit! `, }, ]); await fsClient.promises.unlink(fooTxt); expect(await vcs.status(barTxt)).toBe('*added'); expect(await vcs.status(fooTxt)).toBe('*deleted'); await vcs.remove(fooTxt); expect(await vcs.status(barTxt)).toBe('*added'); expect(await vcs.status(fooTxt)).toBe('deleted'); await vcs.remove(fooTxt); expect(await vcs.status(barTxt)).toBe('*added'); expect(await vcs.status(fooTxt)).toBe('deleted'); }); it('create branch', async () => { const fsClient = MemClient.createClient(); await fsClient.promises.mkdir(GIT_INSOMNIA_DIR); await fsClient.promises.writeFile(fooTxt, 'foo'); await fsClient.promises.writeFile(barTxt, 'bar'); const vcs = new GitVCS(); await vcs.init({ directory: GIT_CLONE_DIR, fs: fsClient, }); await vcs.setAuthor('Karen Brown', 'karen@example.com'); await vcs.add(fooTxt); await vcs.commit('First commit!'); expect((await vcs.log()).length).toBe(1); await vcs.checkout('new-branch'); expect((await vcs.log()).length).toBe(1); await vcs.add(barTxt); await vcs.commit('Second commit!'); expect((await vcs.log()).length).toBe(2); await vcs.checkout('master'); expect((await vcs.log()).length).toBe(1); }); }); describe('push()', () => { it('should throw an exception when push response contains errors', async () => { git.push.mockReturnValue({ ok: ['unpack'], errors: ['refs/heads/master pre-receive hook declined'], }); const vcs = new GitVCS(); await expect(vcs.push()).rejects.toThrowError( 'Push rejected with errors: ["refs/heads/master pre-receive hook declined"].\n\nGo to View > Toggle DevTools > Console for more information.', ); }); }); describe('undoPendingChanges()', () => { it('should remove pending changes from all tracked files', async () => { const folder = path.join(GIT_INSOMNIA_DIR, 'folder'); const folderBarTxt = path.join(folder, 'bar.txt'); const originalContent = 'content'; const fsClient = MemClient.createClient(); await fsClient.promises.mkdir(GIT_INSOMNIA_DIR); await fsClient.promises.writeFile(fooTxt, originalContent); await fsClient.promises.mkdir(folder); await fsClient.promises.writeFile(folderBarTxt, originalContent); const vcs = new GitVCS(); await vcs.init({ directory: GIT_CLONE_DIR, fs: fsClient, }); // Commit await vcs.setAuthor('Karen Brown', 'karen@example.com'); await vcs.add(fooTxt); await vcs.add(folderBarTxt); await vcs.commit('First commit!'); // Change the file await fsClient.promises.writeFile(fooTxt, 'changedContent'); await fsClient.promises.writeFile(folderBarTxt, 'changedContent'); expect(await vcs.status(fooTxt)).toBe('*modified'); expect(await vcs.status(folderBarTxt)).toBe('*modified'); // Undo await vcs.undoPendingChanges(); // Ensure git doesn't recognize a change anymore expect(await vcs.status(fooTxt)).toBe('unmodified'); expect(await vcs.status(folderBarTxt)).toBe('unmodified'); // Expect original doc to have reverted expect((await fsClient.promises.readFile(fooTxt)).toString()).toBe(originalContent); expect((await fsClient.promises.readFile(folderBarTxt)).toString()).toBe(originalContent); }); it('should remove pending changes from select tracked files', async () => { const foo1Txt = path.join(GIT_INSOMNIA_DIR, 'foo1.txt'); const foo2Txt = path.join(GIT_INSOMNIA_DIR, 'foo2.txt'); const foo3Txt = path.join(GIT_INSOMNIA_DIR, 'foo3.txt'); const files = [foo1Txt, foo2Txt, foo3Txt]; const originalContent = 'content'; const changedContent = 'changedContent'; const fsClient = MemClient.createClient(); await fsClient.promises.mkdir(GIT_INSOMNIA_DIR); const vcs = new GitVCS(); await vcs.init({ directory: GIT_CLONE_DIR, fs: fsClient, }); // Write to all files await Promise.all(files.map(f => fsClient.promises.writeFile(f, originalContent))); // Commit all files await vcs.setAuthor('Karen Brown', 'karen@example.com'); await Promise.all(files.map(f => vcs.add(f, originalContent))); await vcs.commit('First commit!'); // Change all files await Promise.all(files.map(f => fsClient.promises.writeFile(f, changedContent))); await Promise.all(files.map(() => expect(vcs.status(foo1Txt)).resolves.toBe('*modified'))); // Undo foo1 and foo2, but not foo3 await vcs.undoPendingChanges([foo1Txt, foo2Txt]); expect(await vcs.status(foo1Txt)).toBe('unmodified'); expect(await vcs.status(foo2Txt)).toBe('unmodified'); // Expect original doc to have reverted for foo1 and foo2 expect((await fsClient.promises.readFile(foo1Txt)).toString()).toBe(originalContent); expect((await fsClient.promises.readFile(foo2Txt)).toString()).toBe(originalContent); // Expect changed content for foo3 expect(await vcs.status(foo3Txt)).toBe('*modified'); expect((await fsClient.promises.readFile(foo3Txt)).toString()).toBe(changedContent); }); }); describe('readObjectFromTree()', () => { it('reads an object from tree', async () => { const fsClient = MemClient.createClient(); const dir = path.join(GIT_INSOMNIA_DIR, 'dir'); const dirFooTxt = path.join(dir, 'foo.txt'); await fsClient.promises.mkdir(GIT_INSOMNIA_DIR); await fsClient.promises.mkdir(dir); await fsClient.promises.writeFile(dirFooTxt, 'foo'); const vcs = new GitVCS(); await vcs.init({ directory: GIT_CLONE_DIR, fs: fsClient, }); await vcs.setAuthor('Karen Brown', 'karen@example.com'); await vcs.add(dirFooTxt); await vcs.commit('First'); await fsClient.promises.writeFile(dirFooTxt, 'foo bar'); await vcs.add(dirFooTxt); await vcs.commit('Second'); const log = await vcs.log(); expect(await vcs.readObjFromTree(log[0].commit.tree, dirFooTxt)).toBe('foo bar'); expect(await vcs.readObjFromTree(log[1].commit.tree, dirFooTxt)).toBe('foo'); // Some extra checks expect(await vcs.readObjFromTree(log[1].commit.tree, 'missing')).toBe(null); expect(await vcs.readObjFromTree('missing', 'missing')).toBe(null); }); }); });
the_stack
import BoxClient from '../box-client'; import urlPath from '../util/url-path'; import errors from '../util/errors'; // ----------------------------------------------------------------------------- // Typedefs // ----------------------------------------------------------------------------- // ------------------------------------------------------------------------------ // Private // ------------------------------------------------------------------------------ const BASE_PATH = '/folders', FOLDER_LOCK = '/folder_locks', WATERMARK_SUBRESOURCE = '/watermark'; // ------------------------------------------------------------------------------ // Public // ------------------------------------------------------------------------------ /** * Simple manager for interacting with all 'Folder' endpoints and actions. * * @constructor * @param {BoxClient} client - The Box API Client that is responsible for making calls to the API * @returns {void} */ class Folders { client: BoxClient; constructor(client: BoxClient) { this.client = client; } /** * Requests a folder object with the given ID. * * API Endpoint: '/folders/:folderID' * Method: GET * * @param {string} folderID - Box ID of the folder being requested * @param {Object} [options] - Additional options for the request. Can be left null in most cases. * @param {Function} [callback] - Passed the folder information if it was acquired successfully * @returns {Promise<Object>} A promise resolving to the folder object */ get(folderID: string, options?: Record<string, any>, callback?: Function) { var params = { qs: options, }; var apiPath = urlPath(BASE_PATH, folderID); return this.client.wrapWithDefaultHandler(this.client.get)( apiPath, params, callback ); } /** * Requests items contained within a given folder. * * API Endpoint: '/folders/:folderID/items' * Method: GET * * @param {string} folderID - Box ID of the folder being requested * @param {Object} [options] - Additional options for the request. Can be left null in most cases. * @param {Function} [callback] - Passed the folder information if it was acquired successfully * @returns {Promise<Object>} A promise resolving to the collection of the items in the folder */ getItems( folderID: string, options?: Record<string, any>, callback?: Function ) { var params = { qs: options, }; var apiPath = urlPath(BASE_PATH, folderID, '/items'); return this.client.wrapWithDefaultHandler(this.client.get)( apiPath, params, callback ); } /** * Requests collaborations on a given folder. * * API Endpoint: '/folders/:folderID/collaborations' * Method: GET * * @param {string} folderID - Box ID of the folder being requested * @param {Object} [options] - Additional options for the request. Can be left null in most cases. * @param {Function} [callback] - Passed the folder information if it was acquired successfully * @returns {Promise<Object>} A promise resolving to the collection of collaborations */ getCollaborations( folderID: string, options?: Record<string, any>, callback?: Function ) { var params = { qs: options, }; var apiPath = urlPath(BASE_PATH, folderID, '/collaborations'); return this.client.wrapWithDefaultHandler(this.client.get)( apiPath, params, callback ); } /** * Creates a new Folder within a parent folder * * API Endpoint: '/folders * Method: POST * * @param {string} parentFolderID - Box folder id of the folder to add into * @param {string} name - The name for the new folder * @param {Function} [callback] - passed the new folder info if call was successful * @returns {Promise<Object>} A promise resolving to the created folder object */ create(parentFolderID: string, name: string, callback?: Function) { var params = { body: { name, parent: { id: parentFolderID, }, }, }; return this.client.wrapWithDefaultHandler(this.client.post)( BASE_PATH, params, callback ); } /** * Copy a folder into a new, different folder * * API Endpoint: '/folders/:folderID/copy * Method: POST * * @param {string} folderID - The Box ID of the folder being requested * @param {string} newParentID - The Box ID for the new parent folder. '0' to copy to All Files. * @param {Object} [options] - Optional parameters for the copy operation, can be left null in most cases * @param {string} [options.name] - A new name to use if there is an identically-named item in the new parent folder * @param {Function} [callback] - passed the new folder info if call was successful * @returns {Promise<Object>} A promise resolving to the new folder object */ copy( folderID: string, newParentID: string, options?: | { [key: string]: any; name?: string; } | Function, callback?: Function ) { // @NOTE(mwiller) 2016-10-25: Shuffle arguments to maintain backward compatibility // This can be removed at the v2.0 update if (typeof options === 'function') { callback = options; options = {}; } options = options || {}; options.parent = { id: newParentID, }; var params = { body: options, }; var apiPath = urlPath(BASE_PATH, folderID, '/copy'); return this.client.wrapWithDefaultHandler(this.client.post)( apiPath, params, callback ); } /** * Update some information about a given folder. * * API Endpoint: '/folders/:folderID' * Method: PUT * * @param {string} folderID - The Box ID of the folder being requested * @param {Object} updates - Folder fields to update * @param {string} [updates.etag] Only update the folder if the ETag matches * @param {Function} [callback] - Passed the updated folder information if it was acquired successfully * @returns {Promise<Object>} A promise resolving to the updated folder object */ update( folderID: string, updates: { [key: string]: any; etag?: string; }, callback?: Function ) { var params: Record<string, any> = { body: updates, }; if (updates && updates.etag) { params.headers = { 'If-Match': updates.etag, }; delete updates.etag; } var apiPath = urlPath(BASE_PATH, folderID); return this.client.wrapWithDefaultHandler(this.client.put)( apiPath, params, callback ); } /** * Add a folder to a given collection * * API Endpoint: '/folders/:folderID' * Method: PUT * * @param {string} folderID - The folder to add to the collection * @param {string} collectionID - The collection to add the folder to * @param {Function} [callback] - Passed the updated folder if successful, error otherwise * @returns {Promise<Object>} A promise resolving to the updated folder object */ addToCollection(folderID: string, collectionID: string, callback?: Function) { return this.get(folderID, { fields: 'collections' }) .then((data: any /* FIXME */) => { var collections = data.collections || []; // Convert to correct format collections = collections.map((c: any /* FIXME */) => ({ id: c.id })); if (!collections.find((c: any /* FIXME */) => c.id === collectionID)) { collections.push({ id: collectionID }); } return this.update(folderID, { collections }); }) .asCallback(callback); } /** * Remove a folder from a given collection * * API Endpoint: '/folders/:folderID' * Method: PUT * * @param {string} folderID - The folder to remove from the collection * @param {string} collectionID - The collection to remove the folder from * @param {Function} [callback] - Passed the updated folder if successful, error otherwise * @returns {Promise<Object>} A promise resolving to the updated folder object */ removeFromCollection( folderID: string, collectionID: string, callback?: Function ) { return this.get(folderID, { fields: 'collections' }) .then((data: any /* FIXME */) => { var collections = data.collections || []; // Convert to correct object format and remove the specified collection collections = collections .map((c: any /* FIXME */) => ({ id: c.id })) .filter((c: any /* FIXME */) => c.id !== collectionID); return this.update(folderID, { collections }); }) .asCallback(callback); } /** * Move a folder into a new parent folder. * * API Endpoint: '/folders/:folderID' * Method: PUT * * @param {string} folderID - The Box ID of the folder being requested * @param {string} newParentID - The Box ID for the new parent folder. '0' to move to All Files. * @param {Function} [callback] - Passed the updated folder information if it was acquired successfully * @returns {Promise<Object>} A promise resolving to the updated folder object */ move(folderID: string, newParentID: string, callback?: Function) { var params = { body: { parent: { id: newParentID, }, }, }; var apiPath = urlPath(BASE_PATH, folderID); return this.client.wrapWithDefaultHandler(this.client.put)( apiPath, params, callback ); } /** * Delete a given folder. * * API Endpoint: '/folders/:folderID' * Method: DELETE * * @param {string} folderID - Box ID of the folder being requested * @param {Object} [options] - Additional options for the request. Can be left null in most cases. * @param {string} [options.etag] Only delete the folder if the ETag matches * @param {Function} [callback] - Empty response body passed if successful. * @returns {Promise<void>} A promise resolving to nothing */ delete( folderID: string, options?: { [key: string]: any; etag?: string; }, callback?: Function ) { var params: Record<string, any> = { qs: options, }; if (options && options.etag) { params.headers = { 'If-Match': options.etag, }; delete options.etag; } var apiPath = urlPath(BASE_PATH, folderID); return this.client.wrapWithDefaultHandler(this.client.del)( apiPath, params, callback ); } /** * Retrieves all metadata associated with a folder. * * API Endpoint: '/folders/:folderID/metadata' * Method: GET * * @param {string} folderID - the ID of the folder to get metadata for * @param {Function} [callback] - called with an array of metadata when successful * @returns {Promise<Object>} A promise resolving to the collection of metadata on the folder */ getAllMetadata(folderID: string, callback?: Function) { var apiPath = urlPath(BASE_PATH, folderID, 'metadata'); return this.client.wrapWithDefaultHandler(this.client.get)( apiPath, null, callback ); } /** * Retrieve a single metadata template instance for a folder. * * API Endpoint: '/folders/:folderID/metadata/:scope/:template' * Method: GET * * @param {string} folderID - The ID of the folder to retrive the metadata of * @param {string} scope - The scope of the metadata template, e.g. "global" * @param {string} template - The metadata template to retrieve * @param {Function} [callback] - Passed the metadata template if successful * @returns {Promise<Object>} A promise resolving to the metadata template */ getMetadata( folderID: string, scope: string, template: string, callback?: Function ) { var apiPath = urlPath(BASE_PATH, folderID, 'metadata', scope, template); return this.client.wrapWithDefaultHandler(this.client.get)( apiPath, null, callback ); } /** * Adds metadata to a folder. Metadata must either match a template schema or * be placed into the unstructured "properties" template in global scope. * * API Endpoint: '/folders/:folderID/metadata/:scope/:template' * Method: POST * * @param {string} folderID - The ID of the folder to add metadata to * @param {string} scope - The scope of the metadata template, e.g. "enterprise" * @param {string} template - The metadata template schema to add * @param {Object} data - Key/value pairs to add as metadata * @param {Function} [callback] - Called with error if unsuccessful * @returns {Promise<Object>} A promise resolving to the created metadata */ addMetadata( folderID: string, scope: string, template: string, data: Record<string, any>, callback?: Function ) { var apiPath = urlPath(BASE_PATH, folderID, 'metadata', scope, template), params = { body: data, }; return this.client.wrapWithDefaultHandler(this.client.post)( apiPath, params, callback ); } /** * Updates a metadata template instance with JSON Patch-formatted data. * * API Endpoint: '/folders/:folderID/metadata/:scope/:template' * Method: PUT * * @param {string} folderID - The folder to update metadata for * @param {string} scope - The scope of the template to update * @param {string} template - The template to update * @param {Object} patch - The patch data * @param {Function} [callback] - Called with updated metadata if successful * @returns {Promise<Object>} A promise resolving to the updated metadata */ updateMetadata( folderID: string, scope: string, template: string, patch: Record<string, any>, callback?: Function ) { var apiPath = urlPath(BASE_PATH, folderID, 'metadata', scope, template), params = { body: patch, headers: { 'Content-Type': 'application/json-patch+json', }, }; return this.client.wrapWithDefaultHandler(this.client.put)( apiPath, params, callback ); } /** * Sets metadata on a folder, overwriting any metadata that exists for the provided keys. * * @param {string} folderID - The folder to set metadata on * @param {string} scope - The scope of the metadata template * @param {string} template - The key of the metadata template * @param {Object} metadata - The metadata to set * @param {Function} [callback] - Called with updated metadata if successful * @returns {Promise<Object>} A promise resolving to the updated metadata */ setMetadata( folderID: string, scope: string, template: string, metadata: Record<string, any>, callback?: Function ) { return this.addMetadata(folderID, scope, template, metadata) .catch((err: any /* FIXME */) => { if (err.statusCode !== 409) { throw err; } // Metadata already exists on the file; update instead var updates = Object.keys(metadata).map((key) => ({ op: 'add', path: `/${key}`, value: metadata[key], })); return this.updateMetadata(folderID, scope, template, updates); }) .asCallback(callback); } /** * Deletes a metadata template from a folder. * * API Endpoint: '/folders/:folderID/metadata/:scope/:template' * Method: DELETE * * @param {string} folderID - The ID of the folder to remove metadata from * @param {string} scope - The scope of the metadata template * @param {string} template - The template to remove from the folder * @param {Function} [callback] - Called with nothing if successful, error otherwise * @returns {Promise<void>} A promise resolving to nothing */ deleteMetadata( folderID: string, scope: string, template: string, callback?: Function ) { var apiPath = urlPath(BASE_PATH, folderID, 'metadata', scope, template); return this.client.wrapWithDefaultHandler(this.client.del)( apiPath, null, callback ); } /** * Retrieves a folder that has been moved to the trash * * API Endpoint: '/folders/:folderID/trash' * Method: GET * * @param {string} folderID - The ID of the folder being requested * @param {Object} [options] - Additional options for the request. Can be left null in most cases. * @param {Funnction} [callback] - Passed the folder information if it was acquired successfully * @returns {Promise<Object>} A promise resolving to the trashed folder object */ getTrashedFolder( folderID: string, options?: Record<string, any>, callback?: Function ) { var params = { qs: options, }; var apiPath = urlPath(BASE_PATH, folderID, 'trash'); return this.client.wrapWithDefaultHandler(this.client.get)( apiPath, params, callback ); } /** * Restores an item that has been moved to the trash. Default behavior is to restore the item * to the folder it was in before it was moved to the trash. If that parent folder no longer * exists or if there is now an item with the same name in that parent folder, the new parent * older and/or new name will need to be included in the request. * * API Endpoint: '/folders/:folderID' * Method: POST * * @param {string} folderID - The ID of the folder to restore * @param {Object} [options] - Optional parameters, can be left null * @param {?string} [options.name] - The new name for this item * @param {string} [options.parent_id] - The new parent folder for this item * @param {Function} [callback] - Called with folder information if successful, error otherwise * @returns {Promise<Object>} A promise resolving to the restored folder object */ restoreFromTrash( folderID: string, options?: { [key: string]: any; name?: string; parent_id?: string; }, callback?: Function ) { // Set up the parent_id parameter if (options && options.parent_id) { options.parent = { id: options.parent_id, }; delete options.parent_id; } var apiPath = urlPath(BASE_PATH, folderID), params = { body: options || {}, }; return this.client.wrapWithDefaultHandler(this.client.post)( apiPath, params, callback ); } /** * Permanently deletes an folder that is in the trash. The item will no longer exist in Box. This action cannot be undone * * API Endpoint: '/folders/:folderID/trash' * Method: DELETE * * @param {string} folderID Box ID of the folder being requested * @param {Object} [options] Optional parameters * @param {string} [options.etag] Only delete the folder if the ETag matches * @param {Function} [callback] Called with nothing if successful, error otherwise * @returns {Promise<void>} A promise resolving to nothing */ deletePermanently( folderID: string, options?: { [key: string]: any; etag?: string; }, callback?: Function ) { // Switch around arguments if necessary for backwards compatibility if (typeof options === 'function') { callback = options; options = {}; } var params: Record<string, any> = {}; if (options && options.etag) { params.headers = { 'If-Match': options.etag, }; } var apiPath = urlPath(BASE_PATH, folderID, '/trash'); return this.client.wrapWithDefaultHandler(this.client.del)( apiPath, params, callback ); } /** * Used to retrieve the watermark for a corresponding Box folder. * * API Endpoint: '/folders/:folderID/watermark' * Method: GET * * @param {string} folderID - The Box ID of the folder to get watermark for * @param {Object} [options] - Additional options for the request. Can be left null in most cases. * @param {Function} [callback] - Passed the watermark information if successful, error otherwise * @returns {Promise<Object>} A promise resolving to the watermark info */ getWatermark( folderID: string, options?: Record<string, any>, callback?: Function ) { var apiPath = urlPath(BASE_PATH, folderID, WATERMARK_SUBRESOURCE), params = { qs: options, }; return this.client .get(apiPath, params) .then((response: any /* FIXME */) => { if (response.statusCode !== 200) { throw errors.buildUnexpectedResponseError(response); } return response.body.watermark; }) .asCallback(callback); } /** * Used to apply or update the watermark for a corresponding Box folder. * * API Endpoint: '/folders/:folderID/watermark' * Method: PUT * * @param {string} folderID - The Box ID of the folder to update watermark for * @param {Object} [options] - Optional parameters, can be left null * @param {Function} [callback] - Passed the watermark information if successful, error otherwise * @returns {Promise<Object>} A promise resolving to the watermark info */ applyWatermark( folderID: string, options?: Record<string, any>, callback?: Function ) { var apiPath = urlPath(BASE_PATH, folderID, WATERMARK_SUBRESOURCE), params = { body: { watermark: { imprint: 'default', // Currently the API only supports default imprint }, }, }; Object.assign(params.body.watermark, options); return this.client.wrapWithDefaultHandler(this.client.put)( apiPath, params, callback ); } /** * Used to remove the watermark for a corresponding Box folder. * * API Endpoint: '/folders/:folderID/watermark' * Method: DELETE * * @param {string} folderID - The Box ID of the folder to remove watermark from * @param {Function} [callback] - Empty response body passed if successful, error otherwise * @returns {Promise<void>} A promise resolving to nothing */ removeWatermark(folderID: string, callback?: Function) { var apiPath = urlPath(BASE_PATH, folderID, WATERMARK_SUBRESOURCE); return this.client.wrapWithDefaultHandler(this.client.del)( apiPath, null, callback ); } /** * Used to lock a Box folder. * * API Endpoint: '/folder_locks' * Method: POST * * @param {string} folderID - The Box ID of the folder to lock * @param {Function} [callback] - Passed the folder lock object if successful, error otherwise * @returns {Promise<void>} A promise resolving to a folder lock object */ lock(folderID: string, callback?: Function) { var params = { body: { folder: { type: 'folder', id: folderID, }, locked_operations: { move: true, delete: true, }, }, }; return this.client.wrapWithDefaultHandler(this.client.post)( FOLDER_LOCK, params, callback ); } /** * Used to get all locks on a folder. * * API Endpoint: '/folder_locks' * Method: GET * * @param {string} folderID - The Box ID of the folder to lock * @param {Function} [callback] - Passed a collection of folder lock objects if successful, error otherwise * @returns {Promise<void>} A promise resolving to a collection of folder lock objects */ getLocks(folderID: string, callback?: Function) { var params = { qs: { folder_id: folderID, }, }; return this.client.wrapWithDefaultHandler(this.client.get)( FOLDER_LOCK, params, callback ); } /** * Used to delete a lock on a folder. * * API Endpoint: '/folder_locks/:folderLockID' * Method: DELETE * * @param {string} folderLockID - The Box ID of the folder lock * @param {Function} [callback] - Empty response body passed if successful, error otherwise * @returns {Promise<void>} A promise resolving to nothing */ deleteLock(folderLockID: string, callback?: Function) { var apiPath = urlPath(FOLDER_LOCK, folderLockID); return this.client.wrapWithDefaultHandler(this.client.del)( apiPath, null, callback ); } } /** * @module box-node-sdk/lib/managers/folders * @see {@Link Folders} */ export = Folders;
the_stack
import { INodeProperties, } from 'n8n-workflow'; export const caseOperations: INodeProperties[] = [ { displayName: 'Operation', name: 'operation', noDataExpression: true, type: 'options', displayOptions: { show: { resource: [ 'case', ], }, }, options: [ { name: 'Create', value: 'create', description: 'Create a case', }, { name: 'Delete', value: 'delete', description: 'Delete a case', }, { name: 'Get', value: 'get', description: 'Get a case', }, { name: 'Get All', value: 'getAll', description: 'Retrieve all cases', }, { name: 'Get Status', value: 'getStatus', description: 'Retrieve a summary of all case activity', }, { name: 'Update', value: 'update', description: 'Update a case', }, ], default: 'create', }, ]; export const caseFields: INodeProperties[] = [ // ---------------------------------------- // case: create // ---------------------------------------- { displayName: 'Title', name: 'title', type: 'string', required: true, default: '', displayOptions: { show: { resource: [ 'case', ], operation: [ 'create', ], }, }, }, { displayName: 'Connector Name', name: 'connectorId', description: 'Connectors allow you to send Elastic Security cases into other systems (only ServiceNow, Jira, or IBM Resilient)', type: 'options', required: true, default: '', typeOptions: { loadOptionsMethod: 'getConnectors', }, displayOptions: { show: { resource: [ 'case', ], operation: [ 'create', ], }, }, }, { displayName: 'Connector Type', name: 'connectorType', type: 'options', required: true, default: '.jira', options: [ { name: 'IBM Resilient', value: '.resilient', }, { name: 'Jira', value: '.jira', }, { name: 'ServiceNow ITSM', value: '.servicenow', }, ], displayOptions: { show: { resource: [ 'case', ], operation: [ 'create', ], }, }, }, { displayName: 'Issue Type', name: 'issueType', description: 'Type of the Jira issue to create for this case', type: 'string', placeholder: 'Task', required: true, default: '', displayOptions: { show: { resource: [ 'case', ], operation: [ 'create', ], connectorType: [ '.jira', ], }, }, }, { displayName: 'Priority', name: 'priority', description: 'Priority of the Jira issue to create for this case', type: 'string', placeholder: 'High', required: true, default: '', displayOptions: { show: { resource: [ 'case', ], operation: [ 'create', ], connectorType: [ '.jira', ], }, }, }, { displayName: 'Urgency', name: 'urgency', description: 'Urgency of the ServiceNow ITSM issue to create for this case', type: 'options', required: true, default: 1, options: [ { name: 'Low', value: 1, }, { name: 'Medium', value: 2, }, { name: 'High', value: 3, }, ], displayOptions: { show: { resource: [ 'case', ], operation: [ 'create', ], connectorType: [ '.servicenow', ], }, }, }, { displayName: 'Severity', name: 'severity', description: 'Severity of the ServiceNow ITSM issue to create for this case', type: 'options', required: true, default: 1, options: [ { name: 'Low', value: 1, }, { name: 'Medium', value: 2, }, { name: 'High', value: 3, }, ], displayOptions: { show: { resource: [ 'case', ], operation: [ 'create', ], connectorType: [ '.servicenow', ], }, }, }, { displayName: 'Impact', name: 'impact', description: 'Impact of the ServiceNow ITSM issue to create for this case', type: 'options', required: true, default: 1, options: [ { name: 'Low', value: 1, }, { name: 'Medium', value: 2, }, { name: 'High', value: 3, }, ], displayOptions: { show: { resource: [ 'case', ], operation: [ 'create', ], connectorType: [ '.servicenow', ], }, }, }, { displayName: 'Category', name: 'category', type: 'string', description: 'Category of the ServiceNow ITSM issue to create for this case', required: true, default: '', placeholder: 'Helpdesk', displayOptions: { show: { resource: [ 'case', ], operation: [ 'create', ], connectorType: [ '.servicenow', ], }, }, }, { displayName: 'Issue Types', name: 'issueTypes', description: 'Comma-separated list of numerical types of the IBM Resilient issue to create for this case', type: 'string', placeholder: '123,456', required: true, default: '', displayOptions: { show: { resource: [ 'case', ], operation: [ 'create', ], connectorType: [ '.resilient', ], }, }, }, { displayName: 'Severity Code', name: 'severityCode', description: 'Severity code of the IBM Resilient issue to create for this case', type: 'number', typeOptions: { minValue: 0, }, required: true, default: 1, displayOptions: { show: { resource: [ 'case', ], operation: [ 'create', ], connectorType: [ '.resilient', ], }, }, }, { displayName: 'Additional Fields', name: 'additionalFields', type: 'collection', placeholder: 'Add Field', default: {}, displayOptions: { show: { resource: [ 'case', ], operation: [ 'create', ], }, }, options: [ { displayName: 'Description', name: 'description', type: 'string', default: '', }, { displayName: 'Owner', name: 'owner', type: 'string', description: 'Valid application owner registered within the Cases Role Based Access Control system', default: '', }, { displayName: 'Sync Alerts', name: 'syncAlerts', description: 'Whether to synchronize with alerts', type: 'boolean', default: false, }, ], }, // ---------------------------------------- // case: delete // ---------------------------------------- { displayName: 'Case ID', name: 'caseId', type: 'string', required: true, default: '', displayOptions: { show: { resource: [ 'case', ], operation: [ 'delete', ], }, }, }, // ---------------------------------------- // case: get // ---------------------------------------- { displayName: 'Case ID', name: 'caseId', type: 'string', required: true, default: '', displayOptions: { show: { resource: [ 'case', ], operation: [ 'get', ], }, }, }, // ---------------------------------------- // case: getAll // ---------------------------------------- { displayName: 'Return All', name: 'returnAll', type: 'boolean', default: false, description: 'Whether to return all results or only up to a given limit', displayOptions: { show: { resource: [ 'case', ], operation: [ 'getAll', ], }, }, }, { displayName: 'Limit', name: 'limit', type: 'number', default: 50, description: 'Max number of results to return', typeOptions: { minValue: 1, }, displayOptions: { show: { resource: [ 'case', ], operation: [ 'getAll', ], returnAll: [ false, ], }, }, }, { displayName: 'Filters', name: 'filters', type: 'collection', default: {}, placeholder: 'Add Filter', displayOptions: { show: { resource: [ 'case', ], operation: [ 'getAll', ], }, }, options: [ { displayName: 'Status', name: 'status', type: 'options', options: [ { name: 'Open', value: 'open', }, { name: 'In Progress', value: 'in-progress', }, { name: 'Closed', value: 'closed', }, ], default: 'open', }, { displayName: 'Tags', name: 'tags', type: 'multiOptions', default: [], typeOptions: { loadOptionsMethod: 'getTags', }, }, ], }, { displayName: 'Sort', name: 'sortOptions', type: 'fixedCollection', placeholder: 'Add Sort Options', default: {}, displayOptions: { show: { resource: [ 'case', ], operation: [ 'getAll', ], }, }, options: [ { displayName: 'Sort Options', name: 'sortOptionsProperties', values: [ { displayName: 'Sort Key', name: 'sortField', type: 'options', options: [ { name: 'Created At', value: 'createdAt', }, { name: 'Updated At', value: 'updatedAt', }, ], default: 'createdAt', }, { displayName: 'Sort Order', name: 'sortOrder', type: 'options', options: [ { name: 'Ascending', value: 'asc', }, { name: 'Descending', value: 'desc', }, ], default: 'asc', }, ], }, ], }, // ---------------------------------------- // case: update // ---------------------------------------- { displayName: 'Case ID', name: 'caseId', type: 'string', required: true, default: '', displayOptions: { show: { resource: [ 'case', ], operation: [ 'update', ], }, }, }, { displayName: 'Update Fields', name: 'updateFields', type: 'collection', placeholder: 'Add Field', default: {}, displayOptions: { show: { resource: [ 'case', ], operation: [ 'update', ], }, }, options: [ { displayName: 'Description', name: 'description', type: 'string', default: '', }, { displayName: 'Status', name: 'status', type: 'options', default: 'open', options: [ { name: 'Closed', value: 'closed', }, { name: 'Open', value: 'open', }, { name: 'In Progress', value: 'in-progress', }, ], }, { displayName: 'Sync Alerts', name: 'syncAlerts', description: 'Whether to synchronize with alerts', type: 'boolean', default: false, }, { displayName: 'Title', name: 'title', type: 'string', default: '', }, { displayName: 'Version', name: 'version', type: 'string', default: '', }, ], }, ];
the_stack
import React from "react"; import { createFragmentContainer } from "react-relay"; import graphql from "babel-plugin-relay/macro"; import styled from "@emotion/styled/macro"; import MarkdownView from "react-showdown"; import _sanitizeHtml from "sanitize-html"; import { useFragment } from "relay-hooks"; import { HStack, IconButton, Popover, PopoverBody, PopoverCloseButton, PopoverContent, PopoverHeader, PopoverTrigger, Portal, Table, Thead, Tr, Th, Tbody, Td, Code, } from "@chakra-ui/react"; import { useNoteWindowActions } from "../dm-area/token-info-aside"; import { SharableImage } from "../dm-area/components/sharable-image"; import { ChakraIcon } from "../feather-icons"; import * as Button from "../button"; import { chatMessageComponents } from "../user-content-components"; import type { chatMessage_message } from "./__generated__/chatMessage_message.graphql"; import { chatMessage_SharedResourceChatMessageFragment$key } from "./__generated__/chatMessage_SharedResourceChatMessageFragment.graphql"; import { DiceRoll, FormattedDiceRoll } from "./formatted-dice-roll"; const Container = styled.div` padding-bottom: 4px; > * { line-height: 24px; } `; const AuthorName = styled.div` display: block; font-weight: bold; `; type ReactComponent = (props: any) => React.ReactElement | null; const { sanitizeHtml, components } = (() => { const allowedTags = [ "div", "blockquote", "span", "em", "strong", "pre", "code", "img", "FormattedDiceRoll", ]; const allowedAttributes: Record<string, Array<string>> = { span: ["style"], div: ["style"], img: ["src"], FormattedDiceRoll: ["index", "reference"], }; const components: Record<string, ReactComponent> = {}; for (const [name, config] of Object.entries(chatMessageComponents)) { if (typeof config === "function") { allowedTags.push(name); components[name] = config; continue; } if (typeof config === "object") { if (config.allowedAttributes != null) { allowedAttributes[name] = config.allowedAttributes; allowedTags.push(name); components[name] = config.Component; } } } const sanitizeHtml = (html: string) => _sanitizeHtml(html, { allowedTags, allowedAttributes, transformTags: { // since our p element could also contain div elements and that makes react/the browser go brrrt // we simply convert them to div elements for now // in the future we might have a better solution. p: "div", }, selfClosing: ["FormattedDiceRoll"], parser: { lowerCaseTags: false, }, }); return { sanitizeHtml, components }; })(); const TextRenderer: React.FC<{ text: string }> = ({ text }) => { return <MarkdownView markdown={text} sanitizeHtml={sanitizeHtml} />; }; type DiceRollResultArray = Extract< chatMessage_message, { __typename: "UserChatMessage" } >["diceRolls"]; export type DiceRollType = DiceRollResultArray[number]; type DiceRollResultContextValue = { diceRolls: DiceRollResultArray; referencedDiceRolls: DiceRollResultArray; }; export const DiceRollResultContext = React.createContext<DiceRollResultContextValue>( // TODO: Use context that throws by default undefined as any ); const UserMessageRenderer = ({ authorName, content, diceRolls, referencedDiceRolls, }: { authorName: string; content: string; diceRolls: DiceRollResultArray; referencedDiceRolls: DiceRollResultArray; }) => { const markdown = React.useMemo( () => content.replace( /{(r)?(\d*)}/g, // prettier-ignore (_, isReferenced, index) => `<FormattedDiceRoll index="${index}"${isReferenced ? ` reference="yes"` : ``} />` ), [content] ); return ( <DiceRollResultContext.Provider value={{ diceRolls, referencedDiceRolls }}> <Container> <HStack justifyContent="space-between"> <AuthorName>{authorName}: </AuthorName> {diceRolls.length || referencedDiceRolls.length ? ( <Popover placement="left"> <PopoverTrigger> <IconButton aria-label="Show Info" icon={<ChakraIcon.Info />} size="sm" variant="unstyled" /> </PopoverTrigger> <Portal> <PopoverContent> <PopoverHeader>Dice Rolls</PopoverHeader> <PopoverCloseButton /> <PopoverBody> <Table size="sm"> <Thead> <Tr> <Th>ID</Th> <Th>Result</Th> </Tr> </Thead> <Tbody> {[...diceRolls, ...referencedDiceRolls].map((roll) => ( <Tr key={roll.rollId}> <Td> <Code>{roll.rollId}</Code> </Td> <Td> <DiceRoll diceRoll={roll} /> </Td> </Tr> ))} </Tbody> </Table> </PopoverBody> </PopoverContent> </Portal> </Popover> ) : null} </HStack> <MarkdownView markdown={markdown} components={{ ...chatMessageComponents, FormattedDiceRoll }} sanitizeHtml={sanitizeHtml} options={{ simpleLineBreaks: true, }} /> </Container> </DiceRollResultContext.Provider> ); }; const ChatMessage_SharedResourceChatMessageFragment = graphql` fragment chatMessage_SharedResourceChatMessageFragment on SharedResourceChatMessage { __typename authorName resource { ... on Note { __typename id documentId title contentPreview } ... on Image { __typename id imageId } } } `; const NoteCard = styled.div` border: 0.5px solid lightgrey; border-radius: 2px; `; const NoteTitle = styled.div` font-weight: bold; padding: 8px; padding-bottom: 4px; `; const NoteBody = styled.div` padding: 8px; padding-top: 0; `; const NoteFooter = styled.div` padding: 8px; `; const NotePreview: React.FC<{ documentId: string; title: string; contentPreview: string; }> = ({ documentId, title, contentPreview }) => { const noteWindowActions = useNoteWindowActions(); return ( <NoteCard> <NoteTitle>{title}</NoteTitle> <NoteBody>{contentPreview}</NoteBody> <NoteFooter> <Button.Primary small onClick={() => noteWindowActions.focusOrShowNoteInNewWindow(documentId) } > Show </Button.Primary> </NoteFooter> </NoteCard> ); }; const SharedResourceRenderer: React.FC<{ message: chatMessage_SharedResourceChatMessageFragment$key; }> = ({ message: messageKey }) => { const message = useFragment( ChatMessage_SharedResourceChatMessageFragment, messageKey ); let resourceContent: React.ReactNode = <strong>CONTENT UNAVAILABLE</strong>; if (message.resource) { switch (message.resource.__typename) { case "Note": resourceContent = ( <NotePreview documentId={message.resource.documentId} title={message.resource.title} contentPreview={message.resource.contentPreview} /> ); break; case "Image": resourceContent = <SharableImage id={message.resource.imageId} />; } } return ( <Container> <AuthorName>{message.authorName} shared </AuthorName> {resourceContent} </Container> ); }; const ChatMessageRenderer: React.FC<{ message: chatMessage_message; }> = React.memo(({ message }) => { switch (message.__typename) { case "UserChatMessage": return ( <UserMessageRenderer authorName={message.authorName} content={message.content} diceRolls={message.diceRolls} referencedDiceRolls={message.referencedDiceRolls} /> ); case "OperationalChatMessage": return ( <Container> <TextRenderer text={message.content} /> </Container> ); case "SharedResourceChatMessage": return <SharedResourceRenderer message={message} />; default: return null; } }); export const ChatMessage = createFragmentContainer(ChatMessageRenderer, { message: graphql` fragment chatMessage_message on ChatMessage { ... on UserChatMessage { __typename authorName content diceRolls { rollId result detail { ... on DiceRollOperatorNode { __typename content } ... on DiceRollConstantNode { __typename content } ... on DiceRollOpenParenNode { __typename content } ... on DiceRollCloseParenNode { __typename content } ... on DiceRollDiceRollNode { __typename content rollResults { dice result category crossedOut } } } } referencedDiceRolls { rollId result detail { ... on DiceRollOperatorNode { __typename content } ... on DiceRollConstantNode { __typename content } ... on DiceRollOpenParenNode { __typename content } ... on DiceRollCloseParenNode { __typename content } ... on DiceRollDiceRollNode { __typename content rollResults { dice result category crossedOut } } } } } ... on OperationalChatMessage { __typename content } ... on SharedResourceChatMessage { __typename ...chatMessage_SharedResourceChatMessageFragment } } `, });
the_stack
declare var window: any; import { guid, Subscription, THandler, Logger } from 'chipmunk.client.toolkit'; import { IPCMessagePackage } from './service.electron.ipc.messagepackage'; import { IService } from '../interfaces/interface.service'; import { IPC } from '../interfaces/interface.ipc'; import { CommonInterfaces } from '../interfaces/interface.common'; export { IPC, Subscription, THandler }; export type TResponseFunc = (message: Required<IPC.Interface>) => Promise<Required<IPC.Interface>>; interface IPendingTask<T extends IPC.Interface> { resolver: (message: T) => any; rejector: (error: Error) => void; signature: string; created: number; } class ElectronIpcService implements IService { static PENDING_ERR_DURATION: number = 600 * 1000; // 10 mins before report error about pending tasks. static PENDING_WARN_DURATION: number = 120 * 1000; // 2 mins before report warn about pending tasks. static QUEUE_CHECK_DELAY: number = 5 * 1000; private _logger: Logger = new Logger('ElectronIpcService'); private _subscriptions: Map<string, Subscription> = new Map(); private _pending: Map<string, IPendingTask<any>> = new Map(); private _handlers: Map<string, Map<string, THandler>> = new Map(); private _listeners: Map<string, boolean> = new Map(); private _ipcRenderer: CommonInterfaces.Electron.IpcRenderer; constructor() { if ((window as any) === undefined || typeof (window as any).require !== 'function') { throw new Error( this._logger.error( `"window" object isn't available or "require" function isn't found`, ), ); } const mod = (window as any).require('electron'); if (mod === undefined) { throw new Error(this._logger.error(`Fail to get access to "electron" module.`)); } this._ipcRenderer = mod.ipcRenderer; } public init(): Promise<void> { return new Promise((resolve, reject) => { this._report(); resolve(); }); } public getName(): string { return 'ElectronIpcService'; } public sendToPluginHost(message: any, token: string, stream?: string): void { const pluginMessage: IPC.PluginInternalMessage = new IPC.PluginInternalMessage({ data: message, token: token, stream: stream, }); this._sendWithoutResponse(pluginMessage); } public requestToPluginHost(message: any, token: string, stream?: string): Promise<any> { return new Promise((resolve, reject) => { const pluginMessage: IPC.PluginInternalMessage = new IPC.PluginInternalMessage({ data: message, token: token, stream: stream, }); this.request(pluginMessage, IPC.PluginError) .then((response: IPC.TMessage | undefined) => { if ( !(response instanceof IPC.PluginInternalMessage) && !(response instanceof IPC.PluginError) ) { return reject( new Error( `From plugin host was gotten incorrect responce: ${typeof response}/${response}`, ), ); } if (response instanceof IPC.PluginError) { return reject(response); } resolve(response.data); }) .catch((sendingError: Error) => { reject(sendingError); }); }); } public send(message: Required<IPC.Interface>): Promise<void> { return new Promise((resolve, reject) => { const ref: Function | undefined = this._getRefToMessageClass(message); if (ref === undefined) { return reject(new Error(`Incorrect type of message`)); } this._sendWithoutResponse(message); resolve(undefined); }); } public response(sequence: string, message: Required<IPC.Interface>): Promise<void> { return new Promise((resolve, reject) => { const ref: Function | undefined = this._getRefToMessageClass(message); if (ref === undefined) { return reject(new Error(`Incorrect type of message`)); } this._sendWithoutResponse(message, sequence); resolve(undefined); }); } public request<T extends IPC.Interface>( message: Required<IPC.Interface>, expected?: Required<IPC.Interface>, ): Promise<T> { return new Promise((resolve, reject) => { const ref: Function | undefined = this._getRefToMessageClass(message); if (ref === undefined) { return reject(new Error(`Incorrect type of message`)); } this._subscribeIPCMessage( expected === undefined ? message.signature : expected.signature, ); this._sendWithResponse<T>({ message: message, sequence: guid() }) .then(resolve) .catch(reject); }); } public subscribe(message: Function, handler: THandler): Subscription { if (!this._isValidMessageClassRef(message)) { throw new Error(this._logger.error('Incorrect reference to message class.', message)); } const signature: string = (message as any).signature; return this._setSubscription(signature, handler); } public subscribeOnPluginMessage(handler: THandler): Promise<Subscription> { return new Promise((resolve) => { resolve(this._setSubscription(IPC.PluginInternalMessage.signature, handler)); }); } public destroy() { this._subscriptions.forEach((subscription: Subscription) => { subscription.destroy(); }); this._subscriptions.clear(); } private _setSubscription(signature: string, handler: THandler): Subscription { const subscriptionId: string = guid(); let handlers: Map<string, THandler> | undefined = this._handlers.get(signature); if (handlers === undefined) { handlers = new Map(); this._subscribeIPCMessage(signature); } handlers.set(subscriptionId, handler); this._handlers.set(signature, handlers); const subscription: Subscription = new Subscription( signature, () => { this._unsubscribe(signature, subscriptionId); }, subscriptionId, ); this._subscriptions.set(subscriptionId, subscription); return subscription; } private _emitIncomePluginMessage(message: any) { const handlers: Map<string, THandler> | undefined = this._handlers.get( IPC.PluginInternalMessage.signature, ); if (handlers === undefined) { return; } handlers.forEach((handler: THandler) => { handler(message); }); } private _subscribeIPCMessage(messageAlias: string): boolean { if (this._listeners.has(messageAlias)) { return false; } this._listeners.set(messageAlias, true); this._ipcRenderer.on(messageAlias, this._onIPCMessage.bind(this)); return true; } private _onIPCMessage(ipcEvent: Event, eventName: string, data: any) { const messagePackage: IPCMessagePackage = new IPCMessagePackage(data); const pending: IPendingTask<any> | undefined = this._pending.get(messagePackage.sequence); this._pending.delete(messagePackage.sequence); const refMessageClass = this._getRefToMessageClass(messagePackage.message); if (refMessageClass === undefined) { return this._logger.warn( `Cannot find ref to class of message. Event: ${eventName}; data: ${data}.`, ); } const instance: IPC.TMessage = new (refMessageClass as any)(messagePackage.message); if (pending !== undefined) { return pending.resolver(instance); } if (instance instanceof IPC.PluginInternalMessage || instance instanceof IPC.PluginError) { if (typeof instance.token !== 'string' || instance.token.trim() === '') { return this._logger.warn( `Was gotten message "PluginInternalMessage", but message doesn't have token. Message will be ignored.`, instance, ); } // This is plugin message. Do not pass into common stream of messages this._emitIncomePluginMessage(instance); return; } const handlers = this._handlers.get(instance.signature); if (handlers === undefined) { return; } // TODO: try / catch should be only on production handlers.forEach((handler: THandler) => { handler(instance, this.response.bind(this, messagePackage.sequence)); }); } private _sendWithResponse<T extends IPC.Interface>(params: { message: Required<IPC.Interface>; sequence: string; }): Promise<T> { return new Promise((resolve, reject) => { const messagePackage: IPCMessagePackage = new IPCMessagePackage({ message: params.message, sequence: params.sequence, }); const signature: string = params.message.signature; this._pending.set(params.sequence, { resolver: resolve, rejector: reject, signature: signature, created: new Date().getTime(), }); // Format: | channel | event | instance | this._ipcRenderer.send(signature, signature, messagePackage); }); } private _sendWithoutResponse(message: Required<IPC.Interface>, sequence?: string): void { const messagePackage: IPCMessagePackage = new IPCMessagePackage({ message: message, sequence: sequence, }); const signature: string = message.signature; // Format: | channel | event | instance | this._ipcRenderer.send(signature, signature, messagePackage); } private _isValidMessageClassRef(messageRef: Function): boolean { let result: boolean = false; if ( typeof (messageRef as any).signature !== 'string' || (messageRef as any).signature.trim() === '' ) { return false; } Object.keys(IPC.Map).forEach((alias: string) => { if (result) { return; } if ((messageRef as any).signature === (IPC.Map as any)[alias].signature) { result = true; } }); return result; } private _getRefToMessageClass(message: any): Function | undefined { let ref: Function | undefined; Object.keys(IPC.Map).forEach((alias: string) => { if (ref) { return; } if ( message instanceof (IPC.Map as any)[alias] || message.signature === (IPC.Map as any)[alias].signature ) { ref = (IPC.Map as any)[alias]; } }); return ref; } private _unsubscribe(signature: string, subscriptionId: string) { this._subscriptions.delete(subscriptionId); const handlers: Map<string, THandler> | undefined = this._handlers.get(signature); if (handlers === undefined) { return; } handlers.delete(subscriptionId); if (handlers.size === 0) { this._ipcRenderer.removeAllListeners(signature); this._handlers.delete(signature); this._listeners.delete(signature); } else { this._handlers.set(signature, handlers); } } private _report() { const current = new Date().getTime(); this._pending.forEach((task: IPendingTask<any>) => { const duration = current - task.created; if (duration > ElectronIpcService.PENDING_ERR_DURATION) { this._logger.error( `Pending task "${task.signature}" too long stay in queue: ${( duration / 1000 ).toFixed(2)}s.`, ); } else if (duration > ElectronIpcService.PENDING_WARN_DURATION) { this._logger.warn( `Pending task "${task.signature}" is in a queue for ${(duration / 1000).toFixed( 2, )}s.`, ); } }); if (this._pending.size > 0) { this._logger.debug(`Pending task queue has ${this._pending.size} tasks.`); this._logger.debug( `\n\t -${Array.from(this._pending.values()) .map((t) => `${t.signature}:: ${t.created}`) .join(`\n\t -`)}`, ); } setTimeout(this._report.bind(this), ElectronIpcService.QUEUE_CHECK_DELAY); } } export default new ElectronIpcService();
the_stack
import * as vscode from 'vscode'; import { CSharpProjectedDocumentContentProvider } from './CSharp/CSharpProjectedDocumentContentProvider'; import { HtmlProjectedDocumentContentProvider } from './Html/HtmlProjectedDocumentContentProvider'; import { IProjectedDocument } from './IProjectedDocument'; import { IRazorDocumentChangeEvent } from './IRazorDocumentChangeEvent'; import { RazorDocumentChangeKind } from './RazorDocumentChangeKind'; import { RazorDocumentManager } from './RazorDocumentManager'; import { RazorLogger } from './RazorLogger'; import { getUriPath } from './UriPaths'; export class RazorDocumentSynchronizer { private readonly synchronizations: { [uri: string]: SynchronizationContext[] } = {}; private synchronizationIdentifier = 0; constructor( private readonly documentManager: RazorDocumentManager, private readonly logger: RazorLogger) { } public register() { const documentManagerRegistration = this.documentManager.onChange( event => this.documentChanged(event)); const textDocumentChangeRegistration = vscode.workspace.onDidChangeTextDocument( event => this.textDocumentChanged(event)); return vscode.Disposable.from(documentManagerRegistration, textDocumentChangeRegistration); } public async trySynchronizeProjectedDocument( hostDocument: vscode.TextDocument, projectedDocument: IProjectedDocument, expectedHostDocumentVersion: number, token: vscode.CancellationToken) { const logId = ++this.synchronizationIdentifier; const documentKey = getUriPath(projectedDocument.uri); if (this.logger.verboseEnabled) { const ehdv = expectedHostDocumentVersion; this.logger.logVerbose( `${logId} - Synchronizing '${documentKey}': Currently at ${projectedDocument.hostDocumentSyncVersion}, synchronizing to version '${ehdv}'. Current host document version: '${hostDocument.version}' Current projected document version: '${projectedDocument.projectedDocumentSyncVersion}'`); } if (hostDocument.version !== expectedHostDocumentVersion) { if (this.logger.verboseEnabled) { this.logger.logVerbose( `${logId} - toHostDocumentVersion and hostDocument.version already out of date.`); } // Already out-of-date. Allowing synchronizations for now to see if this actually causes any issues. } const context: SynchronizationContext = this.createSynchronizationContext( documentKey, projectedDocument, expectedHostDocumentVersion, hostDocument, token); try { if (projectedDocument.hostDocumentSyncVersion !== expectedHostDocumentVersion) { if (this.logger.verboseEnabled) { this.logger.logVerbose( `${logId} - Projected document not in sync with host document, waiting for update... Current host document sync version: ${projectedDocument.hostDocumentSyncVersion}`); } await context.onProjectedDocumentSynchronized; } if (this.logger.verboseEnabled) { this.logger.logVerbose( `${logId} - Projected document in sync with host document`); } // Projected document is the one we expect. const projectedTextDocument = await vscode.workspace.openTextDocument(projectedDocument.uri); const projectedTextDocumentVersion = this.getProjectedTextDocumentVersion(projectedTextDocument); if (projectedDocument.projectedDocumentSyncVersion !== projectedTextDocumentVersion) { if (this.logger.verboseEnabled) { this.logger.logVerbose( `${logId} - Projected text document not in sync with data type, waiting for update... Current projected text document sync version: ${projectedTextDocumentVersion}`); } await context.onProjectedTextDocumentSynchronized; } if (this.logger.verboseEnabled) { this.logger.logVerbose( `${logId} - Projected text document in sync with data type`); } // Projected text document is the one we expect } catch (cancellationReason) { this.removeSynchronization(context); if (this.logger.verboseEnabled) { this.logger.logVerbose( `${logId} - Synchronization failed: ${cancellationReason}`); } return false; } this.removeSynchronization(context); if (this.logger.verboseEnabled) { this.logger.logVerbose( `${logId} - Synchronization successful!`); } return true; } private removeSynchronization(context: SynchronizationContext) { const documentKey = getUriPath(context.projectedDocument.uri); const synchronizations = this.synchronizations[documentKey]; clearTimeout(context.timeoutId); if (synchronizations.length === 1) { delete this.synchronizations[documentKey]; return; } this.synchronizations[documentKey] = synchronizations.filter(item => item !== context); } private createSynchronizationContext( documentKey: string, projectedDocument: IProjectedDocument, toHostDocumentVersion: number, hostDocument: vscode.TextDocument, token: vscode.CancellationToken) { const rejectionsForCancel: Array<(reason: string) => void> = []; let projectedDocumentSynchronized: () => void = Function; const onProjectedDocumentSynchronized = new Promise<void>((resolve, reject) => { projectedDocumentSynchronized = resolve; rejectionsForCancel.push(reject); }); let projectedTextDocumentSynchronized: () => void = Function; const onProjectedTextDocumentSynchronized = new Promise<void>((resolve, reject) => { projectedTextDocumentSynchronized = resolve; rejectionsForCancel.push(reject); }); token.onCancellationRequested((reason) => { context.cancel(`Token cancellation requested: ${reason}`); }); const timeoutId = setTimeout(() => { context.cancel('Synchronization timed out'); }, 2000); const context: SynchronizationContext = { projectedDocument, logIdentifier: this.synchronizationIdentifier, timeoutId, toHostDocumentVersion, hostDocumentVersion: hostDocument.version, cancel: (reason) => { for (const reject of rejectionsForCancel) { reject(reason); } }, projectedDocumentSynchronized, onProjectedDocumentSynchronized, projectedTextDocumentSynchronized, onProjectedTextDocumentSynchronized, }; let synchronizations = this.synchronizations[documentKey]; if (!synchronizations) { synchronizations = []; this.synchronizations[documentKey] = synchronizations; } synchronizations.push(context); return context; } private textDocumentChanged(event: vscode.TextDocumentChangeEvent) { if (event.document.uri.scheme !== CSharpProjectedDocumentContentProvider.scheme && event.document.uri.scheme !== HtmlProjectedDocumentContentProvider.scheme) { return; } const projectedTextDocumentVersion = this.getProjectedTextDocumentVersion(event.document); if (projectedTextDocumentVersion === null) { return; } const documentKey = getUriPath(event.document.uri); const synchronizationContexts = this.synchronizations[documentKey]; if (!synchronizationContexts) { return; } for (const context of synchronizationContexts) { if (context.projectedDocument.projectedDocumentSyncVersion === projectedTextDocumentVersion) { if (this.logger.verboseEnabled) { const li = context.logIdentifier; const ptdv = projectedTextDocumentVersion; this.logger.logVerbose(`${li} - Projected text document synchronized to ${ptdv}.`); } context.projectedTextDocumentSynchronized(); } } } private documentChanged(event: IRazorDocumentChangeEvent) { let projectedDocument: IProjectedDocument; if (event.kind === RazorDocumentChangeKind.csharpChanged) { projectedDocument = event.document.csharpDocument; } else if (event.kind === RazorDocumentChangeKind.htmlChanged) { projectedDocument = event.document.htmlDocument; } else { return; } const hostDocumentSyncVersion = projectedDocument.hostDocumentSyncVersion; if (hostDocumentSyncVersion === null) { return; } const documentKey = getUriPath(projectedDocument.uri); const synchronizationContexts = this.synchronizations[documentKey]; if (!synchronizationContexts) { return; } for (const context of synchronizationContexts) { if (context.toHostDocumentVersion === projectedDocument.hostDocumentSyncVersion) { context.projectedDocumentSynchronized(); } } } private getProjectedTextDocumentVersion(textDocument: vscode.TextDocument) { // Logic defined in this method is heavily dependent on the functionality in the projected // document content providers to append versions to the end of text documents. if (textDocument.lineCount <= 0) { return null; } const lastLine = textDocument.lineAt(textDocument.lineCount - 1); const versionString = lastLine.text.substring(3 /* //_ */); const textDocumentProjectedVersion = parseInt(versionString, 10); return textDocumentProjectedVersion; } } interface SynchronizationContext { readonly projectedDocument: IProjectedDocument; readonly logIdentifier: number; readonly toHostDocumentVersion: number; readonly hostDocumentVersion: number; readonly timeoutId: NodeJS.Timer; readonly projectedDocumentSynchronized: () => void; readonly onProjectedDocumentSynchronized: Promise<void>; readonly projectedTextDocumentSynchronized: () => void; readonly onProjectedTextDocumentSynchronized: Promise<void>; readonly cancel: (reason: string) => void; }
the_stack
import { spawn } from 'child_process'; import * as fs from 'fs'; import { inject, injectable } from 'inversify'; import * as path from 'path'; import * as apid from '../../../../api'; import Thumbnail from '../../../db/entities/Thumbnail'; import FileUtil from '../../../util/FileUtil'; import ProcessUtil from '../../../util/ProcessUtil'; import IVideoUtil from '../../api/video/IVideoUtil'; import IRecordedDB from '../../db/IRecordedDB'; import IThumbnailDB from '../../db/IThumbnailDB'; import IVideoFileDB from '../../db/IVideoFileDB'; import IThumbnailEvent from '../../event/IThumbnailEvent'; import IConfigFile from '../../IConfigFile'; import IConfiguration from '../../IConfiguration'; import ILogger from '../../ILogger'; import ILoggerModel from '../../ILoggerModel'; import { IPromiseQueue } from '../../IPromiseQueue'; import IThumbnailManageModel from './IThumbnailManageModel'; @injectable() export default class ThumbnailManageModel implements IThumbnailManageModel { private log: ILogger; private config: IConfigFile; private queue: IPromiseQueue; private recordedDB: IRecordedDB; private videoFileDB: IVideoFileDB; private thumbnailDB: IThumbnailDB; private thumbnailEvent: IThumbnailEvent; private videoUtil: IVideoUtil; constructor( @inject('ILoggerModel') logger: ILoggerModel, @inject('IConfiguration') configuration: IConfiguration, @inject('IPromiseQueue') queue: IPromiseQueue, @inject('IRecordedDB') recordedDB: IRecordedDB, @inject('IVideoFileDB') videoFileDB: IVideoFileDB, @inject('IThumbnailDB') thumbnailDB: IThumbnailDB, @inject('IThumbnailEvent') thumbnailEvent: IThumbnailEvent, @inject('IVideoUtil') videoUtil: IVideoUtil, ) { this.log = logger.getLogger(); this.config = configuration.getConfig(); this.queue = queue; this.recordedDB = recordedDB; this.videoFileDB = videoFileDB; this.thumbnailDB = thumbnailDB; this.thumbnailEvent = thumbnailEvent; this.videoUtil = videoUtil; } /** * サムネイル作成 Queue に追加する * @param videoFileId: apid.VideoFileId */ public add(videoFileId: apid.VideoFileId): void { this.log.system.info(`add thumbnail queue: ${videoFileId}`); this.queue.add<void>(() => { return this.create(videoFileId).catch(err => { this.log.system.error(`create thumbnail error: ${videoFileId}`); this.log.system.error(err); }); }); } /** * サムネイル生成をして生成したファイルを Thumbnail に登録する * @param videoFileId: apid.VideoFileId */ private async create(videoFileId: apid.VideoFileId): Promise<void> { const videoFile = await this.videoFileDB.findId(videoFileId); const videoFilePath = await this.videoUtil.getFullFilePathFromId(videoFileId); if (videoFile === null || videoFilePath === null) { this.log.system.error(`video file is not found: ${videoFileId}`); throw new Error('VideoFileIsNotFound'); } // check thumbnail dir try { await FileUtil.access(this.config.thumbnail, fs.constants.R_OK | fs.constants.W_OK); } catch (err) { if (typeof err.code !== 'undefined' && err.code === 'ENOENT') { // ディレクトリが存在しないので作成する this.log.system.warn(`mkdirp: ${this.config.thumbnail}`); await FileUtil.mkdir(this.config.thumbnail); } else { // アクセス権に Read or Write が無い this.log.system.fatal(`thumbnail dir permission error: ${this.config.thumbnail}`); this.log.system.fatal(err); throw err; } } const fileName = await this.getSaveFileName(videoFile.recordedId); const output = path.join(this.config.thumbnail, fileName); const cmdStr = this.config.thumbnailCmd.replace(/%FFMPEG%/g, this.config.ffmpeg); const cmds = ProcessUtil.parseCmdStr(cmdStr); // コマンドの引数準備 for (let i = 0; i < cmds.args.length; i++) { cmds.args[i] = cmds.args[i] .replace(/%INPUT%/, videoFilePath) .replace(/%OUTPUT%/, output) .replace(/%THUMBNAIL_POSITION%/, `${this.config.thumbnailPosition.toString(10)}`) .replace(/%THUMBNAIL_SIZE%/, this.config.thumbnailSize); } // run ffmpeg const child = spawn(cmds.bin, cmds.args); // debug 用 if (child.stderr !== null) { child.stderr.on('data', data => { this.log.system.debug(String(data)); }); } if (child.stdout !== null) { child.stdout.on('data', () => {}); } // プロセス終了処理 const endProcessing = async (code: number | null): Promise<boolean> => { if (code !== 0) { this.log.system.error(`create thumbnail cmd error: ${code}`); return false; } this.log.system.info(`create thumbnail: ${videoFileId}, ${output}`); // add DB const thumbnail = new Thumbnail(); thumbnail.filePath = fileName; thumbnail.recordedId = videoFile.recordedId; try { await this.thumbnailDB.insertOnce(thumbnail); } catch (err) { this.log.system.error(`thumbnail add DB error: ${videoFileId}`); this.log.system.error(err); // delete thumbnail file await FileUtil.unlink(output).catch(err => { this.log.system.error(`thumbnail delete error: ${videoFileId}, ${output}`); this.log.system.error(err); }); return false; } // event emit this.thumbnailEvent.emitAdded(videoFileId, videoFile.recordedId); return true; }; return new Promise<void>(async (resolve: () => void, reject: (err: Error) => void) => { child.on('exit', async code => { if ((await endProcessing(code)) === true) { resolve(); } else { reject(new Error('CreateThumbnailExitError')); } }); child.on('error', err => { this.log.system.error(`create thumbnail failed: ${videoFileId}`); reject(err); }); // プロセスの即時終了対応 if (ProcessUtil.isExited(child) === true) { child.removeAllListeners(); if ((await endProcessing(child.exitCode)) === true) { resolve(); } else { reject(new Error('CreateThumbnailExitError')); } } }); } /** * 重複しないサムネイルファイル名を返す * @param recordedId: recorded id * @param conflict: 重複数 * @return string */ private async getSaveFileName(recordedId: apid.RecordedId, conflict: number = 0): Promise<string> { const conflictStr = conflict === 0 ? '' : `(${conflict})`; const fileName = `${recordedId}${conflictStr}.jpg`; const filePath = path.join(this.config.thumbnail, fileName); try { await FileUtil.stat(filePath); return this.getSaveFileName(recordedId, conflict + 1); } catch (err) { return fileName; } } /** * 指定したサムネイルを削除する * @param thumbnailId: apid.ThumbnailId * @return Promise<void> */ public async delete(thumbnailId: apid.ThumbnailId): Promise<void> { const thumbnail = await this.thumbnailDB.findId(thumbnailId); if (thumbnail === null) { throw new Error('ThumbnailIsNotFound'); } this.log.system.info(`delete thumbnail ${thumbnailId}`); // DB から削除 await this.thumbnailDB.deleteOnce(thumbnailId).catch(err => { this.log.system.error(`delete thumbnail error: ${thumbnailId}`); this.log.system.error(err); throw err; }); // サムネイルファイルを削除 const filePath = path.join(this.config.thumbnail, thumbnail.filePath); await FileUtil.unlink(filePath).catch(err => { this.log.system.error(`delete thumbnail error: ${thumbnailId}`); this.log.system.error(err); throw err; }); this.thumbnailEvent.emitDeleted(); } /** * サムネイル再生性 * @return Promise<void> */ public async regenerate(): Promise<void> { this.log.system.info('start regenerate thumbnail'); const [recordeds] = await this.recordedDB.findAll( { isHalfWidth: false, }, { isNeedVideoFiles: true, isNeedThumbnails: true, isNeedsDropLog: false, isNeedTags: false, }, ); const videoFileIds: apid.VideoFileId[] = []; // サムネイル再生成リスト for (const recorded of recordeds) { if (typeof recorded.videoFiles === 'undefined' || recorded.videoFiles.length === 0) { continue; } if (typeof recorded.thumbnails === 'undefined' || recorded.thumbnails.length === 0) { // サムネイルが存在しないので生成リストに追加 videoFileIds.push(recorded.videoFiles[0].id); continue; } // ファイルが存在しないサムネイルデータを列挙する const nonExistingThumbnailIds: apid.ThumbnailId[] = []; let existingThumbnailCnt = 0; // サムネイルファイルが存在するか確認 for (const thumbnail of recorded.thumbnails) { const thumbnailPath = path.join(this.config.thumbnail, thumbnail.filePath); try { await FileUtil.stat(thumbnailPath); // ファイルが存在するので無視 existingThumbnailCnt++; continue; } catch (err) { // ファイルが存在しない nonExistingThumbnailIds.push(thumbnail.id); } } // 存在しないサムネイルデータを削除する for (const thumbnailId of nonExistingThumbnailIds) { await this.thumbnailDB.deleteOnce(thumbnailId).catch(err => { this.log.system.error(`failed to delete non-existing thumbnail data: ${thumbnailId}`); this.log.system.error(err); }); } // サムネイル情報が存在しなくなったので生成リストに追加 if (existingThumbnailCnt === 0) { videoFileIds.push(recorded.videoFiles[0].id); } } // 再生成リストにある videoFileId からサムネイルを再生成させる for (const videoFileId of videoFileIds) { this.add(videoFileId); } } /** * DB に登録されていないログファイル削除 & DB に登録されているが存在しないログ情報の削除 */ public async fileCleanup(): Promise<void> { this.log.system.info('start thumbnail files cleanup'); const thumbnails = await this.thumbnailDB.findAll(); // ファイル, ディレクトリ索引生成と DB 上に存在するが実ファイルが存在しないデータを削除する const fileIndex: { [filePath: string]: boolean } = {}; // ファイル索引 for (const thumbnail of thumbnails) { const filePath = path.join(this.config.thumbnail, thumbnail.filePath); if ((await this.checkFileExistence(filePath)) === true) { // ファイルが存在するなら索引に追加 fileIndex[filePath] = true; } else { this.log.system.warn(`thumbnail file is not exist: ${filePath}`); // ファイルが存在しないなら削除 await this.thumbnailDB.deleteOnce(thumbnail.id).catch(err => { this.log.system.error(err); }); } } // ファイル索引上に存在しないファイルを削除する const list = await FileUtil.getFileList(this.config.thumbnail); for (const file of list.files) { if (typeof fileIndex[file] !== 'undefined') { continue; } this.log.system.info(`delete thumbnail file: ${file}`); await FileUtil.unlink(file).catch(err => { this.log.system.error(`failed to thumbnail file: ${file}`); this.log.system.error(err); }); } this.log.system.info('start thumbnail files cleanup completed'); } /** * 指定したファイルパスにファイルが存在するか * @param filePath: string ファイルパス * @return Promise<boolean> ファイルが存在するなら true を返す */ private async checkFileExistence(filePath: string): Promise<boolean> { try { await FileUtil.stat(filePath); return true; } catch (err) { return false; } } }
the_stack
import sinon from 'sinon' import { ChildProcessWithoutNullStreams } from 'child_process' import { HttpProvider } from 'web3-core' import { ether } from '@openzeppelin/test-helpers' import { KnownRelaysManager, DefaultRelayScore, DefaultRelayFilter } from '@opengsn/provider/dist/KnownRelaysManager' import { ContractInteractor } from '@opengsn/common/dist/ContractInteractor' import { GSNConfig } from '@opengsn/provider/dist/GSNConfigurator' import { PenalizerInstance, RelayHubInstance, StakeManagerInstance, TestPaymasterConfigurableMisbehaviorInstance, TestRecipientInstance, TestTokenInstance } from '@opengsn/contracts/types/truffle-contracts' import { configureGSN, deployHub, evmMineMany, startRelay, stopRelay } from '../TestUtils' import { prepareTransaction } from './RelayProvider.test' import { LoggerInterface } from '@opengsn/common/dist/LoggerInterface' import { RelayInfoUrl, RelayRegisteredEventInfo } from '@opengsn/common/dist/types/GSNContractsDataTypes' import { createClientLogger } from '@opengsn/provider/dist/ClientWinstonLogger' import { registerForwarderForGsn } from '@opengsn/common/dist/EIP712/ForwarderUtil' import { defaultEnvironment } from '@opengsn/common/dist/Environments' import { toBN } from 'web3-utils' import { constants, splitRelayUrlForRegistrar } from '@opengsn/common' const StakeManager = artifacts.require('StakeManager') const Penalizer = artifacts.require('Penalizer') const TestRecipient = artifacts.require('TestRecipient') const TestToken = artifacts.require('TestToken') const TestPaymasterConfigurableMisbehavior = artifacts.require('TestPaymasterConfigurableMisbehavior') const Forwarder = artifacts.require('Forwarder') const RelayRegistrar = artifacts.require('RelayRegistrar') export async function stake (testToken: TestTokenInstance, stakeManager: StakeManagerInstance, relayHub: RelayHubInstance, manager: string, owner: string): Promise<void> { const stake = ether('1') await testToken.mint(stake, { from: owner }) await testToken.approve(stakeManager.address, stake, { from: owner }) await stakeManager.setRelayManagerOwner(owner, { from: manager }) await stakeManager.stakeForRelayManager(testToken.address, manager, 15000, stake, { from: owner }) await stakeManager.authorizeHubByOwner(manager, relayHub.address, { from: owner }) } export async function register (relayHub: RelayHubInstance, manager: string, worker: string, url: string, baseRelayFee?: string, pctRelayFee?: string): Promise<void> { await relayHub.addRelayWorkers([worker], { from: manager }) const relayRegistrar = await RelayRegistrar.at(await relayHub.getRelayRegistrar()) await relayRegistrar.registerRelayServer(relayHub.address, baseRelayFee ?? '0', pctRelayFee ?? '0', splitRelayUrlForRegistrar(url), { from: manager }) } contract('KnownRelaysManager', function ( [ activeRelayWorkersAdded, activeRelayServerRegistered, activePaymasterRejected, activeTransactionRelayed, notActiveRelay, workerPaymasterRejected, workerTransactionRelayed, owner, other, workerRelayWorkersAdded, workerRelayWorkersAdded2, workerRelayServerRegistered, workerNotActive ]) { const relayLookupWindowBlocks = 100 const pastEventsQueryMaxPageSize = 10 describe('#_fetchRecentlyActiveRelayManagers()', function () { let config: GSNConfig let logger: LoggerInterface let contractInteractor: ContractInteractor let stakeManager: StakeManagerInstance let penalizer: PenalizerInstance let relayHub: RelayHubInstance let testRecipient: TestRecipientInstance let testToken: TestTokenInstance let paymaster: TestPaymasterConfigurableMisbehaviorInstance const gas = 4e6 before(async function () { testToken = await TestToken.new() stakeManager = await StakeManager.new(defaultEnvironment.maxUnstakeDelay, 0, 0, constants.BURN_ADDRESS, constants.BURN_ADDRESS) penalizer = await Penalizer.new(defaultEnvironment.penalizerConfiguration.penalizeBlockDelay, defaultEnvironment.penalizerConfiguration.penalizeBlockExpiration) relayHub = await deployHub(stakeManager.address, penalizer.address, constants.ZERO_ADDRESS, testToken.address, ether('1').toString()) config = configureGSN({ loggerConfiguration: { logLevel: 'error' }, pastEventsQueryMaxPageSize }) logger = createClientLogger(config.loggerConfiguration) const maxPageSize = Number.MAX_SAFE_INTEGER contractInteractor = new ContractInteractor({ environment: defaultEnvironment, provider: web3.currentProvider as HttpProvider, maxPageSize, logger, deployment: { relayHubAddress: relayHub.address } }) await contractInteractor.init() const forwarderInstance = await Forwarder.new() const forwarderAddress = forwarderInstance.address testRecipient = await TestRecipient.new(forwarderAddress) await registerForwarderForGsn(forwarderInstance) paymaster = await TestPaymasterConfigurableMisbehavior.new() await paymaster.setTrustedForwarder(forwarderAddress) await paymaster.setRelayHub(relayHub.address) await paymaster.deposit({ value: ether('1') }) await stake(testToken, stakeManager, relayHub, activeRelayWorkersAdded, owner) await stake(testToken, stakeManager, relayHub, activeRelayServerRegistered, owner) await stake(testToken, stakeManager, relayHub, activePaymasterRejected, owner) await stake(testToken, stakeManager, relayHub, activeTransactionRelayed, owner) await stake(testToken, stakeManager, relayHub, notActiveRelay, owner) const txPaymasterRejected = await prepareTransaction(testRecipient, other, workerPaymasterRejected, paymaster.address, web3) const txTransactionRelayed = await prepareTransaction(testRecipient, other, workerTransactionRelayed, paymaster.address, web3) const relayRegistrar = await RelayRegistrar.at(await relayHub.getRelayRegistrar()) /** events that are not supposed to be visible to the manager */ await relayHub.addRelayWorkers([workerRelayServerRegistered], { from: activeRelayServerRegistered }) await relayHub.addRelayWorkers([workerRelayWorkersAdded], { from: activeRelayWorkersAdded }) await relayHub.addRelayWorkers([workerNotActive], { from: notActiveRelay }) await relayHub.addRelayWorkers([workerTransactionRelayed], { from: activeTransactionRelayed }) await relayHub.addRelayWorkers([workerPaymasterRejected], { from: activePaymasterRejected }) await relayRegistrar.registerRelayServer(relayHub.address, '0', '0', splitRelayUrlForRegistrar(''), { from: activeTransactionRelayed }) await relayRegistrar.registerRelayServer(relayHub.address, '0', '0', splitRelayUrlForRegistrar(''), { from: activePaymasterRejected }) await relayRegistrar.registerRelayServer(relayHub.address, '0', '0', splitRelayUrlForRegistrar(''), { from: activeRelayWorkersAdded }) await evmMineMany(relayLookupWindowBlocks) /** events that are supposed to be visible to the manager */ await relayRegistrar.registerRelayServer(relayHub.address, '0', '0', splitRelayUrlForRegistrar(''), { from: activeRelayServerRegistered }) await relayHub.addRelayWorkers([workerRelayWorkersAdded2], { from: activeRelayWorkersAdded }) await relayHub.relayCall(10e6, txTransactionRelayed.relayRequest, txTransactionRelayed.signature, '0x', { from: workerTransactionRelayed, gas, gasPrice: txTransactionRelayed.relayRequest.relayData.maxFeePerGas }) await paymaster.setReturnInvalidErrorCode(true) await relayHub.relayCall(10e6, txPaymasterRejected.relayRequest, txPaymasterRejected.signature, '0x', { from: workerPaymasterRejected, gas, gasPrice: txPaymasterRejected.relayRequest.relayData.maxFeePerGas }) }) it('should contain all relay managers only if their workers were active in the last \'relayLookupWindowBlocks\' blocks', async function () { const knownRelaysManager = new KnownRelaysManager(contractInteractor, logger, config) const infos = await knownRelaysManager.getRelayInfoForManagers() const actual = infos.map(info => info.relayManager) assert.equal(actual.length, 4) assert.equal(actual[0], activeTransactionRelayed) assert.equal(actual[1], activePaymasterRejected) assert.equal(actual[2], activeRelayWorkersAdded) assert.equal(actual[3], activeRelayServerRegistered) }) }) }) contract('KnownRelaysManager 2', function (accounts) { let contractInteractor: ContractInteractor let logger: LoggerInterface const transactionDetails = { gas: '0x10000000', maxFeePerGas: '0x300000', maxPriorityFeePerGas: '0x300000', from: '', data: '', to: '', forwarder: '', paymaster: '' } before(async function () { logger = createClientLogger({ logLevel: 'error' }) const maxPageSize = Number.MAX_SAFE_INTEGER contractInteractor = new ContractInteractor({ environment: defaultEnvironment, provider: web3.currentProvider as HttpProvider, maxPageSize, logger }) await contractInteractor.init() }) describe('#refresh()', function () { let relayProcess: ChildProcessWithoutNullStreams let knownRelaysManager: KnownRelaysManager let contractInteractor: ContractInteractor let stakeManager: StakeManagerInstance let penalizer: PenalizerInstance let testToken: TestTokenInstance let relayHub: RelayHubInstance let config: GSNConfig before(async function () { testToken = await TestToken.new() stakeManager = await StakeManager.new(defaultEnvironment.maxUnstakeDelay, 0, 0, constants.BURN_ADDRESS, constants.BURN_ADDRESS) penalizer = await Penalizer.new(defaultEnvironment.penalizerConfiguration.penalizeBlockDelay, defaultEnvironment.penalizerConfiguration.penalizeBlockExpiration) relayHub = await deployHub(stakeManager.address, penalizer.address, constants.ZERO_ADDRESS, testToken.address, ether('1').toString()) config = configureGSN({ preferredRelays: ['http://localhost:8090'] }) const deployment = { relayHubAddress: relayHub.address } await testToken.mint(ether('1'), { from: accounts[1] }) await testToken.approve(stakeManager.address, ether('1'), { from: accounts[1] }) relayProcess = await startRelay(relayHub.address, testToken, stakeManager, { stake: 1e18.toString(), url: 'asd', confirmationsNeeded: 1, relayOwner: accounts[1], relaylog: process.env.relaylog, ethereumNodeUrl: (web3.currentProvider as HttpProvider).host }) const maxPageSize = Number.MAX_SAFE_INTEGER contractInteractor = new ContractInteractor({ environment: defaultEnvironment, provider: web3.currentProvider as HttpProvider, logger, maxPageSize, deployment }) await contractInteractor.init() knownRelaysManager = new KnownRelaysManager(contractInteractor, logger, config) await stake(testToken, stakeManager, relayHub, accounts[1], accounts[0]) await stake(testToken, stakeManager, relayHub, accounts[2], accounts[0]) await stake(testToken, stakeManager, relayHub, accounts[3], accounts[0]) await stake(testToken, stakeManager, relayHub, accounts[4], accounts[0]) await register(relayHub, accounts[1], accounts[6], 'stakeAndAuthorization1') await register(relayHub, accounts[2], accounts[7], 'stakeAndAuthorization2') await register(relayHub, accounts[3], accounts[8], 'stakeUnlocked') await register(relayHub, accounts[4], accounts[9], 'hubUnauthorized') await stakeManager.unlockStake(accounts[3]) await stakeManager.unauthorizeHubByOwner(accounts[4], relayHub.address) }) after(async function () { await stopRelay(relayProcess) }) it('should consider all relay managers with stake and authorization as active', async function () { await knownRelaysManager.refresh() const preferredRelays = knownRelaysManager.preferredRelayers const activeRelays = knownRelaysManager.allRelayers assert.equal(preferredRelays.length, 1) assert.equal(preferredRelays[0].relayUrl, 'http://localhost:8090') assert.deepEqual(activeRelays.map((r: any) => r.relayUrl), [ 'http://localhost:8090', 'stakeAndAuthorization1', 'stakeAndAuthorization2' ]) }) it('should use \'relayFilter\' to remove unsuitable relays', async function () { const relayFilter = (registeredEventInfo: RelayRegisteredEventInfo): boolean => { return registeredEventInfo.relayUrl.includes('2') } const knownRelaysManagerWithFilter = new KnownRelaysManager(contractInteractor, logger, config, relayFilter) await knownRelaysManagerWithFilter.refresh() const relays = knownRelaysManagerWithFilter.allRelayers assert.equal(relays.length, 1) assert.equal(relays[0].relayUrl, 'stakeAndAuthorization2') }) it('should use DefaultRelayFilter to remove unsuitable relays when none was provided', async function () { const knownRelaysManagerWithFilter = new KnownRelaysManager(contractInteractor, logger, config) // @ts-ignore assert.equal(knownRelaysManagerWithFilter.relayFilter.toString(), DefaultRelayFilter.toString()) }) describe('DefaultRelayFilter', function () { it('should filter expensive relayers', function () { const eventInfo = { relayUrl: 'url', relayManager: accounts[0] } assert.isFalse(DefaultRelayFilter({ ...eventInfo, pctRelayFee: '101', baseRelayFee: 1e16.toString() })) assert.isFalse(DefaultRelayFilter({ ...eventInfo, pctRelayFee: '99', baseRelayFee: 2e17.toString() })) assert.isFalse(DefaultRelayFilter({ ...eventInfo, pctRelayFee: '101', baseRelayFee: 2e17.toString() })) assert.isTrue(DefaultRelayFilter({ ...eventInfo, pctRelayFee: '100', baseRelayFee: 1e17.toString() })) assert.isTrue(DefaultRelayFilter({ ...eventInfo, pctRelayFee: '50', baseRelayFee: '0' })) }) }) }) describe('#getRelaysSortedForTransaction()', function () { const relayInfoLowFee = { relayManager: accounts[0], relayUrl: 'lowFee', baseRelayFee: '1000000', pctRelayFee: '10' } const relayInfoHighFee = { relayManager: accounts[0], relayUrl: 'highFee', baseRelayFee: '100000000', pctRelayFee: '50' } const knownRelaysManager = new KnownRelaysManager(contractInteractor, logger, configureGSN({})) describe('#_refreshFailures()', function () { let lastErrorTime: number before(function () { knownRelaysManager.saveRelayFailure(100, 'rm1', 'url1') knownRelaysManager.saveRelayFailure(500, 'rm2', 'url2') lastErrorTime = Date.now() knownRelaysManager.saveRelayFailure(lastErrorTime, 'rm3', 'url3') }) it('should remove the failures that occurred more than \'relayTimeoutGrace\' seconds ago', function () { // @ts-ignore knownRelaysManager.relayFailures.forEach(failures => { assert.equal(failures.length, 1) }) knownRelaysManager._refreshFailures() // @ts-ignore assert.equal(knownRelaysManager.relayFailures.get('url1').length, 0) // @ts-ignore assert.equal(knownRelaysManager.relayFailures.get('url2').length, 0) // @ts-ignore assert.deepEqual(knownRelaysManager.relayFailures.get('url3'), [{ lastErrorTime, relayManager: 'rm3', relayUrl: 'url3' }]) }) }) describe('DefaultRelayScore', function () { const failure = { lastErrorTime: 100, relayManager: 'rm3', relayUrl: 'url3' } it('should subtract penalty from a relay for each known failure', async function () { const relayScoreNoFailures = await DefaultRelayScore(relayInfoHighFee, transactionDetails, []) const relayScoreOneFailure = await DefaultRelayScore(relayInfoHighFee, transactionDetails, [failure]) const relayScoreTenFailures = await DefaultRelayScore(relayInfoHighFee, transactionDetails, Array(10).fill(failure)) const relayScoreLowFees = await DefaultRelayScore(relayInfoLowFee, transactionDetails, []) assert.isTrue(relayScoreNoFailures.gt(relayScoreOneFailure)) assert.isTrue(relayScoreOneFailure.gt(relayScoreTenFailures)) assert.isTrue(relayScoreLowFees.gt(relayScoreNoFailures)) }) it('should use DefaultRelayScore to remove unsuitable relays when none was provided', async function () { const knownRelaysManagerWithFilter = new KnownRelaysManager(contractInteractor, logger, configureGSN({})) // @ts-ignore assert.equal(knownRelaysManagerWithFilter.scoreCalculator.toString(), DefaultRelayScore.toString()) }) }) }) describe('getRelaysSortedForTransaction', function () { const biasedRelayScore = async function (relay: RelayRegisteredEventInfo): Promise<BN> { if (relay.relayUrl === 'alex') { return await Promise.resolve(toBN(1000)) } else { return await Promise.resolve(toBN(100)) } } const knownRelaysManager = new KnownRelaysManager(contractInteractor, logger, configureGSN({}), undefined, biasedRelayScore) before(function () { const activeRelays: RelayRegisteredEventInfo[] = [{ relayManager: accounts[0], relayUrl: 'alex', baseRelayFee: '100000000', pctRelayFee: '50' }, { relayManager: accounts[0], relayUrl: 'joe', baseRelayFee: '100', pctRelayFee: '5' }, { relayManager: accounts[1], relayUrl: 'joe', baseRelayFee: '10', pctRelayFee: '4' }] sinon.stub(knownRelaysManager, 'allRelayers').value(activeRelays) }) it('should use provided score calculation method to sort the known relays', async function () { const sortedRelays = (await knownRelaysManager.getRelaysSortedForTransaction(transactionDetails)) as RelayRegisteredEventInfo[][] assert.equal(sortedRelays[1][0].relayUrl, 'alex') // checking the relayers are sorted AND they cannot overshadow each other's url assert.equal(sortedRelays[1][1].relayUrl, 'joe') assert.equal(sortedRelays[1][1].baseRelayFee, '100') assert.equal(sortedRelays[1][1].pctRelayFee, '5') assert.equal(sortedRelays[1][2].relayUrl, 'joe') assert.equal(sortedRelays[1][2].baseRelayFee, '10') assert.equal(sortedRelays[1][2].pctRelayFee, '4') }) }) describe('#getAuditors()', function () { const auditorsCount = 2 let knownRelaysManager: KnownRelaysManager before(function () { const activeRelays: RelayInfoUrl[] = [{ relayUrl: 'alice' }, { relayUrl: 'bob' }, { relayUrl: 'charlie' }, { relayUrl: 'alice' }] const preferredRelayers: RelayInfoUrl[] = [{ relayUrl: 'alice' }, { relayUrl: 'david' }] knownRelaysManager = new KnownRelaysManager(contractInteractor, logger, configureGSN({ auditorsCount })) sinon.stub(knownRelaysManager, 'preferredRelayers').value(preferredRelayers) sinon.stub(knownRelaysManager, 'allRelayers').value(activeRelays) }) it('should give correct number of unique random relay URLs', function () { const auditors = knownRelaysManager.getAuditors([]) const unique = auditors.filter((value, index, self) => { return self.indexOf(value) === index }) assert.equal(unique.length, auditorsCount) assert.equal(auditors.length, auditorsCount) }) it('should give all unique relays URLS if requested more then available', function () { // @ts-ignore knownRelaysManager.config.auditorsCount = 7 const auditors = knownRelaysManager.getAuditors([]) assert.deepEqual(auditors.sort(), ['alice', 'bob', 'charlie', 'david']) }) it('should not include explicitly excluded URLs', function () { // @ts-ignore knownRelaysManager.config.auditorsCount = 7 const auditors = knownRelaysManager.getAuditors(['charlie']) assert.deepEqual(auditors.sort(), ['alice', 'bob', 'david']) }) }) })
the_stack
* This is a helper library for synchronously writing logs to any transport. */ import arrify = require('arrify'); import {Logging} from '.'; import {Entry, LABELS_KEY, LogEntry, StructuredJson} from './entry'; import {Writable} from 'stream'; import { LogSeverityFunctions, assignSeverityToEntries, snakecaseKeys, formatLogName, WriteOptions, } from './utils/log-common'; /** * A logSync is a named collection of entries in structured log format. In Cloud * Logging, structured logs refer to log entries that use the jsonPayload field * to add structure to their payloads. In most GCP environments, like GKE and * Cloud Functions, structured logs written to process.stdout are automatically * picked up and formatted by logging agents. * * Recommended for Serverless environment logging, especially where async log * calls made by the `Log` class can be dropped by the CPU. * * See {@link https://cloud.google.com/logging/docs/structured-logging|Structured Logging} * * @class * * @param {Logging} logging {@link Logging} instance. * @param {string} name Name of the logSync. * @param {Writable} [transport] transport A custom writable transport stream. * Default: process.stdout. * * @example * ``` * const {Logging} = require('@google-cloud/logging'); * const logging = new Logging(); * const log = logging.logSync('mylog'); * ``` */ class LogSync implements LogSeverityFunctions { formattedName_: string; logging: Logging; name: string; transport: Writable; // not projectId, formattedname is expected constructor(logging: Logging, name: string, transport?: Writable) { this.formattedName_ = formatLogName(logging.projectId, name); this.logging = logging; /** * @name Log#name * @type {string} */ this.name = this.formattedName_.split('/').pop()!; // Default to writing to stdout this.transport = transport || process.stdout; } /** * Write a log entry with a severity of "ALERT". * * This is a simple wrapper around {@link LogSync#write}. All arguments are * the same as documented there. * * @param {Entry|Entry[]} entry A log entry, or array of entries, to write. * @param {?WriteOptions} [options] Write options * @example * ``` * const {Logging} = require('@google-cloud/logging'); * const logging = new Logging(); * const log = logging.logSync('my-log'); * * const entry = log.entry('gce_instance', { * instance: 'my_instance' * }); * * log.alert(entry); * ``` */ alert(entry: Entry | Entry[], options?: WriteOptions) { this.write( assignSeverityToEntries(entry, 'ALERT'), options! as WriteOptions ); } /** * Write a log entry with a severity of "CRITICAL". * * This is a simple wrapper around {@link LogSync#write}. All arguments are * the same as documented there. * * @param {Entry|Entry[]} entry A log entry, or array of entries, to write. * @param {?WriteOptions} [options] Write options * @example * ``` * const {Logging} = require('@google-cloud/logging'); * const logging = new Logging(); * const log = logging.logSync('my-log'); * * const entry = log.entry('gce_instance', { * instance: 'my_instance' * }); * * log.critical(entry); * ``` */ critical(entry: Entry | Entry[], options?: WriteOptions) { this.write( assignSeverityToEntries(entry, 'CRITICAL'), options! as WriteOptions ); } /** * Write a log entry with a severity of "DEBUG". * * This is a simple wrapper around {@link LogSync#write}. All arguments are * the same as documented there. * * @param {Entry|Entry[]} entry A log entry, or array of entries, to write. * @param {?WriteOptions} [options] Write options * @example * ``` * const {Logging} = require('@google-cloud/logging'); * const logging = new Logging(); * const log = logging.logSync('my-log'); * * const entry = log.entry('gce_instance', { * instance: 'my_instance' * }); * * log.debug(entry); * ``` */ debug(entry: Entry | Entry[], options?: WriteOptions) { this.write( assignSeverityToEntries(entry, 'DEBUG'), options! as WriteOptions ); } /** * Write a log entry with a severity of "EMERGENCY". * * This is a simple wrapper around {@link LogSync#write}. All arguments are * the same as documented there. * * @param {Entry|Entry[]} entry A log entry, or array of entries, to write. * @param {?WriteOptions} [options] Write options * @example * ``` * const {Logging} = require('@google-cloud/logging'); * const logging = new Logging(); * const log = logging.logSync('my-log'); * * const entry = log.entry('gce_instance', { * instance: 'my_instance' * }); * * log.emergency(entry); * ``` */ emergency(entry: Entry | Entry[], options?: WriteOptions) { this.write( assignSeverityToEntries(entry, 'EMERGENCY'), options as WriteOptions ); } // TODO(future): dedupe entry code across LogSync & Log classes. /** * Create an entry object for this log. * * Using this method will not itself do any logging. * * See {@link https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry|LogEntry JSON representation} * * @param {?object} metadata See a * [LogEntry * Resource](https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry). * @param {object|string} data The data to use as the value for this log * entry. * @returns {Entry} * * @example * ``` * const {Logging} = require('@google-cloud/logging'); * const logging = new Logging(); * const log = logging.logSync('my-log'); * * const metadata = { * resource: { * type: 'gce_instance', * labels: { * zone: 'global', * instance_id: '3' * } * } * }; * * const entry = log.entry(metadata, { * delegate: 'my_username' * }); * ``` */ entry(metadata?: LogEntry): Entry; entry(data?: string | {}): Entry; entry(metadata?: LogEntry, data?: string | {}): Entry; entry(metadataOrData?: LogEntry | string | {}, data?: string | {}) { let metadata: LogEntry; if (!data && metadataOrData?.hasOwnProperty('httpRequest')) { // If user logs entry(metadata.httpRequest) metadata = metadataOrData as LogEntry; data = {}; } else if (!data) { // If user logs entry(message) data = metadataOrData as string | {}; metadata = {}; } else { // If user logs entry(metadata, message) metadata = metadataOrData as LogEntry; } return this.logging.entry(metadata, data); } /** * Write a log entry with a severity of "ERROR". * * This is a simple wrapper around {@link LogSync#write}. All arguments are * the same as documented there. * * @param {Entry|Entry[]} entry A log entry, or array of entries, to write. * @param {?WriteOptions} [options] Write options * @example * ``` * const {Logging} = require('@google-cloud/logging'); * const logging = new Logging(); * const log = logging.logSync('my-log'); * * const entry = log.entry('gce_instance', { * instance: 'my_instance' * }); * * log.error(entry); * ``` */ error(entry: Entry | Entry[], options?: WriteOptions) { this.write( assignSeverityToEntries(entry, 'ERROR'), options! as WriteOptions ); } /** * Write a log entry with a severity of "INFO". * * This is a simple wrapper around {@link LogSync#write}. All arguments are * the same as documented there. * * @param {Entry|Entry[]} entry A log entry, or array of entries, to write. * @param {?WriteOptions} [options] Write options * @example * ``` * const {Logging} = require('@google-cloud/logging'); * const logging = new Logging(); * const log = logging.logSync('my-log'); * * const entry = log.entry('gce_instance', { * instance: 'my_instance' * }); * * log.info(entry); * ``` */ info(entry: Entry | Entry[], options?: WriteOptions) { this.write( assignSeverityToEntries(entry, 'INFO'), options! as WriteOptions ); } /** * Write a log entry with a severity of "NOTICE". * * This is a simple wrapper around {@link LogSync#write}. All arguments are * the same as documented there. * * @param {Entry|Entry[]} entry A log entry, or array of entries, to write. * @param {?WriteOptions} [options] Write options * @example * ``` * const {Logging} = require('@google-cloud/logging'); * const logging = new Logging(); * const log = logging.logSync('my-log'); * * const entry = log.entry('gce_instance', { * instance: 'my_instance' * }); * * log.notice(entry); * ``` */ notice(entry: Entry | Entry[], options?: WriteOptions) { this.write( assignSeverityToEntries(entry, 'NOTICE'), options! as WriteOptions ); } /** * Write a log entry with a severity of "WARNING". * * This is a simple wrapper around {@link LogSync#write}. All arguments are * the same as documented there. * * @param {Entry|Entry[]} entry A log entry, or array of entries, to write. * @param {?WriteOptions} [options] Write options * @example * ``` * const {Logging} = require('@google-cloud/logging'); * const logging = new Logging(); * const log = logging.logSync('my-log'); * * const entry = log.entry('gce_instance', { * instance: 'my_instance' * }); * * log.warning(entry); * ``` */ warning(entry: Entry | Entry[], options?: WriteOptions) { this.write( assignSeverityToEntries(entry, 'WARNING'), options as WriteOptions ); } /** * Write log entries to a custom transport (default: process.stdout). * * @param {Entry|Entry[]} entry A log entry, or array of entries, to write. * @param {?WriteOptions} [options] Write options * * @example * ``` * const entry = log.entry('gce_instance', { * instance: 'my_instance' * }); * * log.write(entry); * * //- * // You may also pass multiple log entries to write. * //- * const secondEntry = log.entry('compute.googleapis.com', { * user: 'my_username' * }); * * log.write([entry, secondEntry]); * * //- * // To save some steps, you can also pass in plain values as your entries. * // Note, however, that you must provide a configuration object to specify * // the resource. * //- * const entries = [ * { * user: 'my_username' * }, * { * home: process.env.HOME * } * ]; * * const options = { * resource: 'compute.googleapis.com' * }; * * log.write(entries, options); * * log.write(entries); * }); * ``` */ write(entry: Entry | Entry[], opts?: WriteOptions) { const options = opts ? (opts as WriteOptions) : {}; // We expect projectId and resource to be set before this fn is called... let structuredEntries: StructuredJson[]; this.formattedName_ = formatLogName(this.logging.projectId, this.name); try { structuredEntries = (arrify(entry) as Entry[]).map(entry => { if (!(entry instanceof Entry)) { entry = this.entry(entry); } return entry.toStructuredJSON(this.logging.projectId); }); for (const entry of structuredEntries) { entry.logName = this.formattedName_; entry.resource = snakecaseKeys(options.resource?.labels) || entry.resource || this.logging.detectedResource; entry[LABELS_KEY] = options.labels || entry[LABELS_KEY]; this.transport.write(JSON.stringify(entry) + '\n'); } } catch (err) { // Ignore errors (client libraries do not panic). } } } /** * Reference to the {@link LogSync} class. * @name module:@google-cloud/logging.LogSync * @see LogSync */ export {LogSync};
the_stack
import { ChildProcess } from 'child_process'; import path from 'path'; import os from 'os'; import fs, { WriteStream } from 'fs'; import treekill from 'tree-kill'; import { Logger } from '../Logger'; import { AgentFileError, AgentDirectoryError, AgentMissingIDError, AgentInstallTimeoutError, AgentCompileTimeoutError, AgentCompileError, AgentInstallError, } from '../DimensionError'; import { Tournament } from '../Tournament'; import { MatchEngine } from '../MatchEngine'; import { deepMerge } from '../utils/DeepMerge'; import { processIsRunning, dockerCopy } from '../utils/System'; import { deepCopy } from '../utils/DeepCopy'; import { DeepPartial } from '../utils/DeepPartial'; import { Writable, Readable, Stream, Duplex } from 'stream'; import { EventEmitter } from 'events'; // eslint-disable-next-line @typescript-eslint/no-unused-vars import Dockerode, { HostConfig } from 'dockerode'; import { isChildProcess, AgentClassTypeGuards } from '../utils/TypeGuards'; import pidusage from 'pidusage'; import DefaultSeccompProfileJSON from '../Security/seccomp/default.json'; import { noop } from '../utils'; import spawn from 'cross-spawn'; import processExists from 'process-exists'; const DefaultSeccompProfileString = JSON.stringify(DefaultSeccompProfileJSON); const containerBotFolder = '/code'; /** * @class Agent * @classdesc The agent is what participates in a match and contains details on the files powering the agent, the * process associated and many other details. * * Reads in a file source for the code and copies the bot folder to a temporary directory in secure modes * and creates an `Agent` for use in the {@link MatchEngine} and {@link Match} * * This is a class that should not be broken. If something goes wrong, this should always throw a error. It is * expected that agents are used knowing beforehand that the file given is validated */ export class Agent extends EventEmitter { /** * This agent's ID in a match. It is always a non-negative integer and agents in a match are always numbered * `0, 1, 2, ...n` where there are `n` agents. */ public id: Agent.ID = 0; /** * A tournmanet ID if Agent is generated from within a {@link Tournament} */ public tournamentID: Tournament.ID = null; /** * Name of the agent * @default `agent_[agent.id]` */ public name: string; /** The source path to the file that runs the agent */ public src: string; /** The extension of the file */ public ext: string; /** file without extension */ public srcNoExt: string; /** * The current working directory of the source file. If in insecure mode, this is always a temporary directory that * will get deleted later. */ public cwd: string; /** The command used to run the file */ public cmd: string = null; /** * The original file path provided */ public file: string; /** * The agent's options */ public options: Agent.Options = deepCopy(Agent.OptionDefaults); /** * Creation date of the agent */ public creationDate: Date; /** internal buffer to store stdout from an agent that has yet to be delimited / used */ public _buffer: Array<string> = []; /** Interval that periodically watches the memory usage of the process associated with this agent */ public memoryWatchInterval = null; /** * The associated process running the Agent */ private process: ChildProcess = null; /** * Associated docker container running the agent */ private container: Dockerode.Container = null; /** * Streams associated with the agent */ public streams: Agent.Streams = { in: null, out: null, err: null, }; /** * Current status of the agent */ public status: Agent.Status = Agent.Status.UNINITIALIZED; /** The commands collected so far for the current move */ public currentMoveCommands: Array<string> = []; /** a promise that resolves when the Agent's current move in the {@link Match} is finished */ public _currentMovePromise: Promise<void>; /* istanbul ignore next */ public _currentMoveResolve: Function = noop; // set as a dummy function public _currentMoveReject: Function; /** A number that counts the number of times the agent has essentially interacted with the {@link MatchEngine} */ public agentTimeStep = 0; /** Clears out the timer associated with the agent during a match */ public _clearTimer: Function = noop; errorLogWriteStream: WriteStream = null; private log = new Logger(); /** * Key used to retrieve the error logs of this agent */ public logkey: string = null; /** whether agent is allowed to send commands. Used to help ignore extra output from agents */ private allowedToSendCommands = true; /** Agent version, used by tournament */ public version = 0; /** Size of agent's logs so far */ public _logsize = 0; public _trimmed = false; /** List of all messages written to this agent are directly pushed to here when in detached mode */ public messages: Array<string> = []; constructor( file: string, options: Partial<Agent.Options>, languageSpecificOptions: Agent.LanguageSpecificOptions = {} ) { super(); this.creationDate = new Date(); this.options = deepMerge(this.options, deepCopy(options)); this.log.level = this.options.loggingLevel; if (!this.options.detached) { this.ext = path.extname(file); if (languageSpecificOptions[this.ext]) { this.options = deepMerge( this.options, deepCopy(languageSpecificOptions[this.ext]) ); } this.cwd = path.dirname(file); this.src = path.basename(file); this.srcNoExt = this.src.slice(0, -this.ext.length); // check if folder is valid if (!fs.existsSync(this.cwd)) { throw new AgentDirectoryError( `${this.cwd} directory does not exist, check if directory provided through the file is correct`, this.id ); } // check if file exists if (!fs.existsSync(file)) { throw new AgentFileError( `${file} does not exist, check if file path provided is correct`, this.id ); } this.file = file; switch (this.ext) { case '.py': this.cmd = 'python'; break; case '.js': case '.ts': this.cmd = 'node'; break; case '.java': this.cmd = 'java'; break; case '.php': this.cmd = 'php'; break; case '.c': case '.cpp': case '.go': this.cmd = ''; break; default: } } if (this.options.id !== null) { this.id = options.id; } else { throw new AgentMissingIDError( `No id provided for agent using ${file}`, this.id ); } if (this.options.name) { this.name = this.options.name; } else { this.name = `agent_${this.id}`; } if (this.options.tournamentID) { this.tournamentID = options.tournamentID; this.name = this.tournamentID.name; } this.log.system(`Created agent: ${this.name}`); // set agent as ready this.status = Agent.Status.READY; } async setupContainer( name: string, docker: Dockerode, engineOptions: MatchEngine.EngineOptions ): Promise<void> { const HostConfig: HostConfig = { // apply seccomp profile for security SecurityOpt: [`seccomp=${DefaultSeccompProfileString}`], }; if (engineOptions.memory.active) { HostConfig.Memory = engineOptions.memory.limit; } const container = await docker.createContainer({ Image: this.options.image, name: name, OpenStdin: true, StdinOnce: true, HostConfig, }); this.log.system(`Created container ${name}`); // store container this.container = container; await container.start(); this.log.system(`Started container ${name}`); // copy bot directory into container await dockerCopy(this.cwd + '/.', name, '/code'); this.log.system(`Copied bot into container ${name}`); } /** * Install whatever is needed through a `install.sh` file in the root of the bot folder */ _install( stderrWritestream: Writable, stdoutWritestream: Writable, engineOptions: MatchEngine.EngineOptions ): Promise<void> { // eslint-disable-next-line no-async-promise-executor return new Promise(async (resolve, reject) => { // if there is a install.sh file, use it if (fs.existsSync(path.join(this.cwd, 'install.sh'))) { let stdout: Readable; let stderr: Readable; const installTimer = setTimeout(() => { const msg = 'Agent went over install time during the install stage\n'; this.writeToErrorLog(msg); reject(new AgentInstallTimeoutError(msg, this.id)); }, this.options.maxInstallTime); const chunks = []; const handleClose = (code: number) => { clearTimeout(installTimer); if (code === 0) { resolve(); } else { let msg = `A install time error occured. Install step for agent ${ this.id } exited with code: ${code}; Installing ${path.join( this.cwd, 'install.sh' )}; Install Output:\n${chunks.join('')}`; if (code === 137) { msg += `\nAgent likely ran out of memory, exceeded ${ engineOptions.memory.limit / 1000000 } MB`; } this.writeToErrorLog(msg + '\n'); reject(new AgentInstallError(msg, this.id)); } }; const handleError = (err: Error) => { clearTimeout(installTimer); reject(err); }; if (this.options.secureMode) { try { const exec = await this.container.exec({ Cmd: ['/bin/sh', '-c', 'chmod u+x install.sh'], WorkingDir: containerBotFolder, }); await exec.start({}); const data = await this.containerSpawn( path.join(containerBotFolder, 'install.sh') ); stderr = data.err; stdout = data.out; data.stream.on('end', async () => { const endRes = await data.exec.inspect(); handleClose(endRes.ExitCode); }); data.stream.on('error', (err) => { handleError(err); }); } catch (err) { handleError(err); return; } } else { const p = spawn('sh', ['install.sh'], { cwd: this.cwd, }); p.on('error', (err) => { handleError(err); }); p.on('close', (code) => { handleClose(code); }); stderr = p.stderr; stdout = p.stdout; } stdout.on('data', (chunk) => { chunks.push(chunk); }); stderr.on('data', (chunk) => { chunks.push(chunk); }); if (stderrWritestream) { stderr.pipe(stderrWritestream, { end: false, }); } if (stdoutWritestream) { stdout.pipe(stdoutWritestream, { end: false, }); } } else { resolve(); } }); } /** * Compile whatever is needed and validate files. Called by {@link MatchEngine} and has a timer set by the * maxCompileTime option in {@link Agent.Options} */ async _compile( stderrWritestream: Writable, stdoutWritestream: Writable, engineOptions: MatchEngine.EngineOptions ): Promise<void> { // eslint-disable-next-line no-async-promise-executor return new Promise(async (resolve, reject) => { let p: ChildProcess | Agent.ContainerExecData; let stdout: Readable; let stderr: Readable; const compileTimer = setTimeout(() => { const msg = 'Agent went over compile time during the compile stage\n'; this.writeToErrorLog(msg); reject(new AgentCompileTimeoutError(msg, this.id)); }, this.options.maxCompileTime); if (this.options.compileCommands[this.ext]) { const cmd1 = this.options.compileCommands[this.ext][0]; const restofCmds = this.options.compileCommands[this.ext].slice(1); p = await this._spawnCompileProcess(cmd1, [...restofCmds, this.src]); } else { switch (this.ext) { case '.py': case '.php': case '.js': clearTimeout(compileTimer); resolve(); return; case '.ts': // expect user to provide a tsconfig.json p = await this._spawnCompileProcess('tsc', []); break; case '.go': p = await this._spawnCompileProcess('go', [ 'build', '-o', `${this.srcNoExt}.out`, this.src, ]); break; case '.cpp': p = await this._spawnCompileProcess('g++', [ '-std=c++11', '-O3', '-o', `${this.srcNoExt}.out`, this.src, ]); break; case '.c': p = await this._spawnCompileProcess('gcc', [ '-O3', '-o', `${this.srcNoExt}.out`, this.src, ]); break; case '.java': p = await this._spawnCompileProcess('javac', [this.src]); break; default: this.log.system(`${this.ext} not recognized, skipping compilation`); // reject( // new NotSupportedError( // `Language with extension ${this.ext} is not supported at the moment` // ) // ); clearTimeout(compileTimer); resolve(); return; } } const chunks = []; const handleClose = (code: number) => { clearTimeout(compileTimer); if (code === 0) { resolve(); } else { let msg = `A compile time error occured. Compile step for agent ${ this.id } exited with code: ${code}; Compiling ${ this.file }; Compile Output:\n${chunks.join('')}`; if (code === 137) { msg += `\nAgent likely ran out of memory, exceeded ${ engineOptions.memory.limit / 1000000 } MB`; } this.writeToErrorLog(msg + '\n'); reject(new AgentCompileError(msg, this.id)); } }; const handleError = (err: Error) => { clearTimeout(compileTimer); reject(err); }; if (isChildProcess(p)) { stdout = p.stdout; stderr = p.stderr; p.on('error', (err) => { handleError(err); }); p.on('close', (code) => { handleClose(code); }); } else { stdout = p.out; stderr = p.err; const containerExec = p.exec; p.stream.on('error', (err) => { handleError(err); }); p.stream.on('end', async () => { const endRes = await containerExec.inspect(); handleClose(endRes.ExitCode); }); } stdout.on('data', (chunk) => { chunks.push(chunk); }); stderr.on('data', (chunk) => { chunks.push(chunk); }); if (stderrWritestream) { stderr.pipe(stderrWritestream, { end: false, }); } if (stdoutWritestream) { stdout.pipe(stdoutWritestream, { end: false, }); } }); } /** * Spawns the compilation process * @param command - command to compile with * @param args - argument for the compilation */ async _spawnCompileProcess( command: string, args: Array<string> ): Promise<ChildProcess | Agent.ContainerExecData> { return new Promise((resolve, reject) => { if (this.options.secureMode) { this.containerSpawn(`${command} ${args.join(' ')}`, containerBotFolder) .then(resolve) .catch(reject); } else { const p = spawn(command, [...args], { cwd: this.cwd, }).on('error', (err) => { reject(err); }); resolve(p); } }); } /** * Executes the given command string in the agent's container and attaches stdin, stdout, and stderr accordingly * @param command - the command to execute in the container */ async containerSpawn( command: string, workingDir = '/' ): Promise<Agent.ContainerExecData> { const exec = await this.container.exec({ Cmd: ['/bin/sh', '-c', command], AttachStdin: true, AttachStdout: true, AttachStderr: true, WorkingDir: workingDir, }); const stream = await exec.start({ stdin: true, hijack: true }); const instream = new Stream.PassThrough(); const outstream = new Stream.PassThrough(); const errstream = new Stream.PassThrough(); instream.pipe(stream); this.container.modem.demuxStream(stream, outstream, errstream); return { in: instream, out: outstream, err: errstream, stream, exec, }; } /** * Spawn the process and return the process */ async _spawn(): Promise<ChildProcess | Agent.ContainerExecData> { if (this.options.runCommands[this.ext]) { return this._spawnProcess(this.options.runCommands[this.ext][0], [ ...this.options.runCommands[this.ext].slice(1), this.src, ]); } else { switch (this.ext) { case '.py': case '.js': case '.php': { const p = this._spawnProcess(this.cmd, [this.src]); return p; } case '.ts': return this._spawnProcess(this.cmd, [this.srcNoExt + '.js']); case '.java': return this._spawnProcess(this.cmd, [this.srcNoExt]); case '.c': case '.cpp': case '.go': return this._spawnProcess('./' + this.srcNoExt + '.out', []); default: this.log.system( `${this.ext} not recognized, directly executing file` ); return this._spawnProcess('./' + this.src, []); // throw new NotSupportedError( // `Language with extension ${this.ext} is not supported yet` // ); } } } /** * Spawns process in this.cwd accordingly and uses the configs accordingly. * Resolves with the process if spawned succesfully * * Note, we are spawning detached so we can kill off all sub processes if they are made. See {@link _terminate} for * explanation */ _spawnProcess( command: string, args: Array<string> ): Promise<ChildProcess | Agent.ContainerExecData> { return new Promise((resolve, reject) => { if (this.options.secureMode) { this.containerSpawn(`${command} ${args.join(' ')}`, containerBotFolder) .then(resolve) .catch(reject); } else { const p = spawn(command, args, { cwd: this.cwd, detached: false, }).on('error', (err) => { reject(err); }); resolve(p); } }); } /** * Stop an agent provided it is not terminated. To terminate it, see {@link _terminate}; */ async stop(): Promise<void> { if (!this.isTerminated()) { if (this.options.secureMode) { await this.container.pause(); } else { if (os.platform() !== 'win32') { this.process.kill('SIGSTOP'); } } this.status = Agent.Status.STOPPED; } } /** * Resume an agent as long it is not terminated already */ async resume(): Promise<void> { if (!this.isTerminated()) { this._allowCommands(); if (this.options.secureMode) { // await this.container.unpause(); } else { if (os.platform() !== 'win32') { this.process.kill('SIGCONT'); } } this.status = Agent.Status.RUNNING; } } /** * timeout the agent */ timeout(): void { const msg = 'Agent timed out'; this.writeToErrorLog(msg); this.emit(Agent.AGENT_EVENTS.TIMEOUT); } /** * call out agent for exceeding memory limit */ overMemory(): void { const msg = 'Agent exceeded memory limit'; this.writeToErrorLog(msg); this.emit(Agent.AGENT_EVENTS.EXCEED_MEMORY_LIMIT); } /** * Whether or not input is destroyed */ inputDestroyed(): boolean { return this.streams.in.destroyed; } /** * Write to stdin of the process associated with the agent * @param message - the message * @param callback - callback function * * returns true if written, false if highWaterMark reached */ write(message: string, callback: (error: Error) => void): boolean { // in detached mode, simply keep track of messages sent. if (this.options.detached) { this.messages.push(message); process.nextTick(callback); return true; } /** * the following few lines are based on the suggestion at * https://nodejs.org/api/stream.html#stream_writable_write_chunk_encoding_callback */ if (!this.streams.in.write(message)) { return false; } else { process.nextTick(callback); } return true; } writeToErrorLog(message: string): void { if (this.errorLogWriteStream) { this._logsize += message.length; this.errorLogWriteStream.write(message); } } /** * Get process of agent */ _getProcess(): ChildProcess { return this.process; } /** * Store process for agent * @param p - process to store */ _storeProcess(p: ChildProcess): void { this.process = p; } /** * Returns true if this agent was terminated and no longer send or receive emssages */ isTerminated(): boolean { return this.status === Agent.Status.KILLED; } /** * Terminates this agent by stopping all related processes and remove any temporary directory. this is the only function allowed to * set the status value to killed. */ _terminate(): Promise<void> { this.status = Agent.Status.KILLED; // eslint-disable-next-line no-async-promise-executor return new Promise(async (resolve, reject) => { if (this.options.secureMode) { if (this.container) { try { const ins = await this.container.inspect(); this._clearTimer(); clearInterval(this.memoryWatchInterval); if (ins.State.Running) { await this.container.kill(); await this.container.remove(); } resolve(); } catch (err) { if (err.statusCode !== 409 && err.reason !== 'no such container') { reject(err); } else { resolve(); } } } else { resolve(); } } else { if (this.process) { let exists = true; if (os.platform() === 'win32') { // fix bug where on windows, would throw error when treekill fails exists = await processExists(this.process.pid); } if (exists) { treekill(this.process.pid, 'SIGKILL', (err) => { this._clearTimer(); clearInterval(this.memoryWatchInterval); if (err) { reject(err); } else { resolve(); } }); } } else { resolve(); } } }); } /** * Disallow an agent from sending more commands */ _disallowCommands(): void { this.allowedToSendCommands = false; } /** * Allow agent to send commands again */ _allowCommands(): void { this.allowedToSendCommands = true; } /** * Check if agent is set to be allowed to send commands. The {@link EngineOptions} affect when this is flipped */ isAllowedToSendCommands(): boolean { return this.allowedToSendCommands; } /** * Setup the agent timer clear out method */ _setTimeout(fn: Function, delay: number, ...args: any[]): void { const timer = setTimeout(() => { fn(...args); }, delay); this._clearTimer = () => { clearTimeout(timer); }; } /** * Stop this agent from more outputs and mark it as done for now and awaiting for updates. Effectively force agent to sync with match */ async _finishMove(): Promise<void> { this._clearTimer(); // Resolve move and tell engine in `getCommands` this agent is done outputting commands and awaits input this._currentMoveResolve(); // stop the process for now from sending more output and disallow commmands to ignore rest of output if (this.options.secureMode) { // TODO: Implement // await this.container.pause(); } else { if (os.platform() !== 'win32') { this.process.kill('SIGSTOP'); } } this._disallowCommands(); } // Start an Agent's move and setup the promise structures _setupMove(): void { // allows agent to send commands; increment time; clear past commands; reset the promise structure this.allowedToSendCommands = true; this.agentTimeStep++; this.currentMoveCommands = []; this._currentMovePromise = new Promise((resolve, reject) => { this._currentMoveResolve = resolve; this._currentMoveReject = reject; }); } /** * Used by {@link MatchEngine} only. Setups the memory watcher if docker is not used. * @param engineOptions - engine options to configure the agent with */ _setupMemoryWatcher(engineOptions: MatchEngine.EngineOptions): void { const checkAgentMemoryUsage = () => { // setting { maxage: 0 } because otherwise pidusage leaves interval "memory leaks" and process doesn't exit fast if (os.platform() !== 'win32' && processIsRunning(this.process.pid)) { pidusage(this.process.pid, { maxage: 0, usePs: engineOptions.memory.usePs, }) .then((stat) => { if (stat.memory > engineOptions.memory.limit) { this.overMemory(); } }) .catch((err) => { this.log.system(err); }); } }; checkAgentMemoryUsage(); this.memoryWatchInterval = setInterval( checkAgentMemoryUsage, engineOptions.memory.checkRate ); } /** * Generates a list of agents for use * @param files List of files to use to make agents or a list of objects with a file key for the file path to the bot * and a name key for the name of the agent * @param options - Options to first override with for all agents * @param languageSpecificOptions - Options to second overrided with for agents depending on language * @param agentSpecificOptions - Options to lastly override with depending on agent's index */ static generateAgents( files: Agent.GenerationMetaData, options: DeepPartial<Agent.Options>, languageSpecificOptions: Agent.LanguageSpecificOptions = {}, agentSpecificOptions: Array<DeepPartial<Agent.Options>> = [] ): Array<Agent> { if (files.length === 0) { throw new AgentFileError( 'No files provided to generate agents with!', -1 ); } const agents: Array<Agent> = []; if (AgentClassTypeGuards.isGenerationMetaData_FilesOnly(files)) { files.forEach((file, index: number) => { let configs = deepCopy(options); configs = deepMerge( configs, deepCopy( agentSpecificOptions[index] ? agentSpecificOptions[index] : {} ) ); configs.id = index; agents.push( new Agent(file, <Agent.Options>configs, languageSpecificOptions) ); }); } else if (AgentClassTypeGuards.isGenerationMetaData_CreateMatch(files)) { files.forEach((info, index: number) => { let configs = deepCopy(options); configs = deepMerge( configs, deepCopy( agentSpecificOptions[index] ? agentSpecificOptions[index] : {} ) ); configs.id = index; configs.name = info.name; agents.push( new Agent(info.file, <Agent.Options>configs, languageSpecificOptions) ); }); } else { files.forEach((info, index: number) => { let configs = deepCopy(options); configs = deepMerge( configs, deepCopy( agentSpecificOptions[index] ? agentSpecificOptions[index] : {} ) ); configs.id = index; configs.tournamentID = info.tournamentID; const newAgent = new Agent( info.file, <Agent.Options>configs, languageSpecificOptions ); newAgent.version = info.version; agents.push(newAgent); }); } return agents; } getAgentErrorLogFilename(): string { return `agent_${this.id}.log`; } } export namespace Agent { /** * Stream data for any process */ export interface Streams { in: Writable; out: Readable; err: Readable; } /** * data related to executing a command in a container, with stream data, and the exec object */ export interface ContainerExecData extends Streams { exec: Dockerode.Exec; stream: Duplex; } /** * Status enums for an Agent */ export enum Status { /** When agent is just created */ UNINITIALIZED = 'uninitialized', // just created agent /** Agent is ready too be used by the {@link MatchEngine} in a {@link Match} */ READY = 'ready', /** Agent is currently running */ RUNNING = 'running', /** Agent crashed somehow */ CRASHED = 'crashed', /** Agent is finished and no longer in use after {@link Match} ended or was prematurely killed */ KILLED = 'killed', /** Agent is currently not running */ STOPPED = 'stopped', } /** * Agent ID. Always a non-negative integer and all agents in a match have IDs that are strictly increasing from `0` * * For example, in a 4 agent match, the ids are `0, 1, 2, 3`. */ export type ID = number; /** * Agent options interface */ export interface Options { /** Name of agent */ name: string; /** * Whether or not to spawn agent securely and avoid malicious activity * * When set to true, the agent's file and the directory containing the file are copied over to a temporary directory * of which there is restricted access. By default this is false * * @default `false` (always inherited from the match configs, see {@link Match.Configs}) */ secureMode: boolean; /** A specified ID to use for the agent */ id: ID; /** A specified tournament ID linking an agent to the {@link Tournament} and {@link Player} it belongs to */ tournamentID: Tournament.ID; /** Logging level of this agent */ loggingLevel: Logger.LEVEL; /** * Maximium time allowed for an agent to spend on the installing step * @default 5 minutes (300,000 ms) */ maxInstallTime: number; /** * Maximum time allowed to be spent compiling * @default 1 minute (60,000 ms) */ maxCompileTime: number; /** * Map from extension type to set of commands used to compile this agent instead of the defaults. When there is no * mapping default commands are used * * @default `null` */ compileCommands: { [x in string]: Array<string> }; /** * Map from extension type to set of commands used to run this agent instead of the defaults. When there is no * mapping default commands are used * * @default `null` */ runCommands: { [x in string]: Array<string> }; /** * Image to use for docker container if Agent is being run in secureMode. The default is a standard image provided * by Dimensions that has all supported languages built in so agents can use them. The requirement for these images * is that they have bash installed. * * It is highly recommended * to use the {@link Match.Configs.languageSpecificAgentOptions} field and set specific images for each programming * language in a production environment to reduce overhead caused by docker. * * @default `docker.io/stonezt2000/dimensions_langs` */ image: string; /** * Whether or not to try and use a cached bot file. This is only relevant if a storage service is used as it helps * reduce the number of times a bot file is downloaded. * * @default `false` */ useCachedBotFile: boolean; /** * Limit of agent logs in bytes. * * @default `1e5 - 100 kb` */ logLimit: number; /** * Whether agent is to be run in detached mode. In detached mode, the agent simply stores messages that is written to it and clears the message queue * when a turn is finished * * @default `false` */ detached: boolean; } /** * Language specic options mapping programming language to the agent options to use for that programing language. * Used to customize options such as docker image, compile time limits etc. on a per language basis */ export type LanguageSpecificOptions = { [x in string]?: DeepPartial<Agent.Options>; }; /** * Agent events */ export enum AGENT_EVENTS { /** * Event emitted by process of {@link Agent} when memory limit is exceeded */ EXCEED_MEMORY_LIMIT = 'exceedMemoryLimit', /** * Event emitted by process of {@link Agent} when it times out. */ TIMEOUT = 'timeout', /** * event emitted when associated process or container for agent closes and agent effectively is terminated */ CLOSE = 'close', } /** * Default Agent options */ export const OptionDefaults: Agent.Options = { secureMode: false, loggingLevel: Logger.LEVEL.INFO, id: null, tournamentID: null, name: null, maxInstallTime: 300000, maxCompileTime: 60000, runCommands: {}, compileCommands: {}, image: 'docker.io/stonezt2000/dimensions_langs', useCachedBotFile: false, logLimit: 1e5, detached: false, }; export type GenerationMetaData = | GenerationMetaData_CreateMatch | GenerationMetaData_FilesOnly | GenerationMetaData_Tournament; /** * Agent Generation meta data with paths to files only */ export type GenerationMetaData_FilesOnly = Array<string>; /** * Agent generation meta data used by {@link Dimension.createMatch} */ export type GenerationMetaData_CreateMatch = Array<{ /** file path */ file: string; /** name of bot */ name: string; /** botkey for bots in storage */ botkey?: string; }>; // used in createMatch /** * Agent generation meta data used by tournaments */ export type GenerationMetaData_Tournament = Array<{ /** file path */ file: string; /** tournament ID containing playerId, username, and bot name */ tournamentID: Tournament.ID; /** botkey for bots in storage */ botkey?: string; /** track version # of the bot used */ version: number; }>; // used by tournaments }
the_stack
$(() => { const INVISIBLE = "invisible"; const SEL_CODE_DIAG = ".code-diagnostics"; const SEL_COMMENT_ICON = ".icon-comments"; const SEL_COMMENT_CELL = ".comment-cell"; let MessageIconAddedToDom = false; $(document).on("click", ".commentable", e => { showCommentBox(e.target.id); e.preventDefault(); }); $(document).on("click", ".line-comment-button", e => { let id = getElementId(e.target); if (id) { showCommentBox(id); } e.preventDefault(); }); $(document).on("click", ".comment-cancel-button", e => { let id = getElementId(e.target); if (id) { hideCommentBox(id); // if a comment was added and then cancelled, and there are no other // comments for the thread, we should remove the comments icon. if (getCommentsRow(id).find(SEL_COMMENT_CELL).length === 0) { getCodeRow(id).find(SEL_COMMENT_ICON).addClass(INVISIBLE); } } e.preventDefault(); }); $(document).on("click", "#show-comments-checkbox", e => { ensureMessageIconInDOM(); toggleAllCommentsAndDiagnosticsVisibility(e.target.checked); }); $(document).on("click", SEL_COMMENT_ICON, e => { let lineId = getElementId(e.target); if (lineId) { toggleSingleCommentAndDiagnostics(lineId); } e.preventDefault(); }); $(document).on("submit", "form[data-post-update='comments']", e => { const form = <HTMLFormElement><any>$(e.target); let lineId = getElementId(e.target); if (lineId) { let commentRow = getCommentsRow(lineId); let serializedForm = form.serializeArray(); serializedForm.push({ name: "elementId", value: lineId }); serializedForm.push({ name: "reviewId", value: getReviewId(e.target) }); serializedForm.push({ name: "revisionId", value: getRevisionId(e.target) }); $.ajax({ type: "POST", url: $(form).prop("action"), data: $.param(serializedForm) }).done(partialViewResult => { updateCommentThread(commentRow, partialViewResult); }); } e.preventDefault(); }); $(document).on("click", ".review-thread-reply-button", e => { let lineId = getElementId(e.target); if (lineId) { showCommentBox(lineId); } e.preventDefault(); }); $(document).on("click", ".toggle-comments", e => { let lineId = getElementId(e.target); if (lineId) { toggleComments(lineId); } e.preventDefault(); }); $(document).on("click", ".js-edit-comment", e => { let commentId = getCommentId(e.target); if (commentId) { editComment(commentId); } e.preventDefault(); }); $(document).on("click", ".js-github", e => { let target = $(e.target); let repo = target.attr("data-repo"); let language = getLanguage(e.target); // Fall back to the repo-language if we don't know the review language, // e.g.Go doesn't specify Language yet. if (!language) { language = target.attr("data-repo-language"); } let commentElement = getCommentElement(getCommentId(e.target)!); let comment = commentElement.find(".js-comment-raw").html(); let codeLine = commentElement.closest(".comment-row").prev(".code-line").find(".code"); let apiViewUrl = ""; // if creating issue from the convos tab, the link to the code element is in the DOM already. let commentUrlElem = codeLine.find(".comment-url"); if (commentUrlElem.length) { apiViewUrl = location.protocol + '//' + location.host + escape(commentUrlElem.attr("href")!); } else { // otherwise we construct the link from the current URL and the element ID // Double escape the element - this is used as the URL back to API View and GitHub will render one layer of the encoding. apiViewUrl = window.location.href.split("#")[0] + "%23" + escape(escape(getElementId(commentElement[0])!)); } let issueBody = escape("```" + language + "\n" + codeLine.text().trim() + "\n```\n#\n" + comment); // TODO uncomment below once the feature to support public ApiView Reviews is enabled. //+ "\n#\n") //+ "[Created from ApiView comment](" + apiViewUrl + ")"; window.open( "https://github.com/Azure/" + repo + "/issues/new?" + "&body=" + issueBody, '_blank'); e.preventDefault(); }); $(document).on("keydown", ".new-thread-comment-text", e => { if (e.ctrlKey && (e.keyCode === 10 || e.keyCode === 13)) { const form = $(e.target).closest("form"); if (form) { form.submit(); } e.preventDefault(); } }); addEventListener("hashchange", e => { highlightCurrentRow(); }); addEventListener("load", e => { highlightCurrentRow(); }); function highlightCurrentRow() { if (location.hash.length < 1) return; var row = getCodeRow(location.hash.substring(1)); row.addClass("active"); row.on("animationend", () => { row.removeClass("active"); }); } function getReviewId(element: HTMLElement) { return getParentData(element, "data-review-id"); } function getLanguage(element: HTMLElement) { return getParentData(element, "data-language"); } function getRevisionId(element: HTMLElement) { return getParentData(element, "data-revision-id"); } function getElementId(element: HTMLElement) { return getParentData(element, "data-line-id"); } function getCommentId(element: HTMLElement) { return getParentData(element, "data-comment-id"); } function getParentData(element: HTMLElement, name: string) { return $(element).closest(`[${name}]`).attr(name); } function toggleComments(id: string) { $(getCommentsRow(id)).find(".comment-holder").toggle(); } function editComment(commentId: string) { let commentElement = $(getCommentElement(commentId)); let commentText = commentElement.find(".js-comment-raw").html(); let template = createCommentEditForm(commentId, commentText); commentElement.replaceWith(template); } function getCommentElement(commentId: string) { return $(`.review-comment[data-comment-id='${commentId}']`); } function getCommentsRow(id: string) { return $(`.comment-row[data-line-id='${id}']`); } function getCodeRow(id: string) { return $(`.code-line[data-line-id='${id}']`); } function getDiagnosticsRow(id: string) { return $(`.code-diagnostics[data-line-id='${id}']`); } function hideCommentBox(id: string) { let commentsRow = getCommentsRow(id); commentsRow.find(".review-thread-reply").show(); commentsRow.find(".comment-form").hide(); } function showCommentBox(id: string) { let commentForm; let commentsRow = getCommentsRow(id); if (commentsRow.length === 0) { commentForm = createCommentForm(); commentsRow = $(`<tr class="comment-row" data-line-id="${id}">`) .append($("<td colspan=\"3\">") .append(commentForm)); commentsRow.insertAfter(getDiagnosticsRow(id).get(0) || getCodeRow(id).get(0)); } else { // there is a comment row - insert form let reply = $(commentsRow).find(".review-thread-reply"); commentForm = $(commentsRow).find(".comment-form"); if (commentForm.length === 0) { commentForm = $(createCommentForm()).insertAfter(reply); } reply.hide(); commentForm.show(); commentsRow.show(); // ensure that entire comment row isn't being hidden } $(getDiagnosticsRow(id)).show(); // ensure that any code diagnostic for this row is shown in case it was previously hidden // If comment checkbox is unchecked, show the icon for new comment if (!($("#show-comments-checkbox").prop("checked"))) { toggleCommentIcon(id, true); } commentForm.find(".new-thread-comment-text").focus(); } function createCommentForm() { return $("#js-comment-form-template").children().clone(); } function createCommentEditForm(commentId: string, text: string) { let form = $("#js-comment-edit-form-template").children().clone(); form.find(".js-comment-id").val(commentId); form.find(".new-thread-comment-text").html(text); return form; } function updateCommentThread(commentBox, partialViewResult) { partialViewResult = $.parseHTML(partialViewResult); $(commentBox).replaceWith(partialViewResult); return false; } function toggleAllCommentsAndDiagnosticsVisibility(showComments: boolean) { $(SEL_COMMENT_CELL + ", " + SEL_CODE_DIAG).each(function () { var id = getElementId(this); if (id) { getCommentsRow(id).toggle(showComments); getDiagnosticsRow(id).toggle(showComments); toggleCommentIcon(id, !showComments); } }); } function toggleSingleCommentAndDiagnostics(id: string) { getCommentsRow(id).toggle(); getDiagnosticsRow(id).toggle(); } function ensureMessageIconInDOM() { if (!MessageIconAddedToDom) { $(".line-comment-button-cell").append(`<span class="icon icon-comments ` + INVISIBLE + `">💬</span>`); MessageIconAddedToDom = true; } } function toggleCommentIcon(id, show: boolean) { getCodeRow(id).find(SEL_COMMENT_ICON).toggleClass(INVISIBLE, !show); } });
the_stack
import EventEmitter from 'events'; import { encryptionV2, tcrypto, utils } from '@tanker/crypto'; import { InternalError, InvalidVerification, UpgradeRequired, TankerError } from '@tanker/errors'; import { generateGhostDeviceKeys, extractGhostDevice, ghostDeviceToVerificationKey, ghostDeviceKeysFromVerificationKey, decryptVerificationKey, ghostDeviceToEncryptedVerificationKey, decryptUserKeyForGhostDevice } from './ghostDevice'; import type { IndexedProvisionalUserKeyPairs } from './KeySafe'; import type KeyStore from './KeyStore'; import LocalUser from './LocalUser'; import { formatVerificationRequest, isPreverifiedVerificationRequest } from './requests'; import type { VerificationMethod, VerificationWithToken, RemoteVerificationWithToken, LegacyEmailVerificationMethod, } from './types'; import { generateUserCreation, generateDeviceFromGhostDevice, makeDeviceRevocation } from './UserCreation'; import type { UserData, DelegationToken } from './UserData'; import type { Client, PullOptions } from '../Network/Client'; import { Status } from '../Session/status'; import type { Device } from '../Users/types'; import { makeSessionCertificate } from './SessionCertificate'; export type PrivateProvisionalKeys = { appEncryptionKeyPair: tcrypto.SodiumKeyPair; tankerEncryptionKeyPair: tcrypto.SodiumKeyPair; }; export class LocalUserManager extends EventEmitter { _localUser: LocalUser; _delegationToken: DelegationToken; _provisionalUserKeys: IndexedProvisionalUserKeyPairs; _keyStore: KeyStore; _client: Client; constructor(userData: UserData, client: Client, keyStore: KeyStore) { super(); this._client = client; this._keyStore = keyStore; const { localData, provisionalUserKeys } = this._keyStore; this._localUser = new LocalUser(userData.trustchainId, userData.userId, userData.userSecret, localData); this._delegationToken = userData.delegationToken; this._provisionalUserKeys = provisionalUserKeys; } init = async (): Promise<Status> => { if (!this._localUser.isInitialized) { const user = await this._client.getUser(); if (user === null) { return Status.IDENTITY_REGISTRATION_NEEDED; } return Status.IDENTITY_VERIFICATION_NEEDED; } // Authenticate device in background (no await) this._client.authenticateDevice(this._localUser.deviceId, this._localUser.deviceSignatureKeyPair).catch(e => this.emit('error', e)); return Status.READY; }; getVerificationMethods = async (): Promise<Array<VerificationMethod | LegacyEmailVerificationMethod>> => { const verificationMethods = await this._client.getVerificationMethods(); if (verificationMethods.length === 0) { return [{ type: 'verificationKey' }]; } return verificationMethods.map((method) => { switch (method.type) { case 'email': { // Compat: encrypted_email value might be missing. // verification method registered with SDK < 2.0.0 have encrypted_email set to NULL in out database if (!method.encrypted_email) { return { type: 'email' }; } const encryptedEmail = utils.fromBase64(method.encrypted_email!); const email = utils.toString(encryptionV2.decrypt(this._localUser.userSecret, encryptionV2.unserialize(encryptedEmail))); if (method.is_preverified) { return { type: 'preverifiedEmail', preverifiedEmail: email }; } return { type: 'email', email }; } case 'passphrase': { return { type: 'passphrase' }; } case 'oidc_id_token': { return { type: 'oidcIdToken' }; } case 'phone_number': { const encryptedPhoneNumber = utils.fromBase64(method.encrypted_phone_number); const phoneNumber = utils.toString(encryptionV2.decrypt(this._localUser.userSecret, encryptionV2.unserialize(encryptedPhoneNumber))); if (method.is_preverified) { return { type: 'preverifiedPhoneNumber', preverifiedPhoneNumber: phoneNumber }; } return { type: 'phoneNumber', phoneNumber }; } default: { // @ts-expect-error this verification method's type is introduced in a later version of the sdk throw new UpgradeRequired(`unsupported verification method type: ${method.type}`); } } }); }; setVerificationMethod = (verification: RemoteVerificationWithToken): Promise<void> => { const requestVerification = formatVerificationRequest(verification, this._localUser); if (!isPreverifiedVerificationRequest(requestVerification)) { requestVerification.with_token = verification.withToken; // May be undefined } return this._client.setVerificationMethod({ verification: requestVerification, }); }; updateDeviceInfo = async (id: Uint8Array, encryptionKeyPair: tcrypto.SodiumKeyPair, signatureKeyPair: tcrypto.SodiumKeyPair): Promise<void> => { this._localUser.deviceId = id; this._localUser.deviceEncryptionKeyPair = encryptionKeyPair; this._localUser.deviceSignatureKeyPair = signatureKeyPair; await this.updateLocalUser({ isLight: true, }); }; createUser = async (verification: VerificationWithToken): Promise<void> => { let ghostDeviceKeys; if ('verificationKey' in verification) { try { ghostDeviceKeys = ghostDeviceKeysFromVerificationKey(verification.verificationKey); } catch (e) { throw new InvalidVerification(e as Error); } } else { ghostDeviceKeys = generateGhostDeviceKeys(); } if (!this._delegationToken) { throw new InternalError('Assertion error, no delegation token for user creation'); } const { trustchainId, userId } = this._localUser; const { userCreationBlock, firstDeviceBlock, firstDeviceId, firstDeviceEncryptionKeyPair, firstDeviceSignatureKeyPair, ghostDevice } = generateUserCreation(trustchainId, userId, ghostDeviceKeys, this._delegationToken); const request: any = { ghost_device_creation: userCreationBlock, first_device_creation: firstDeviceBlock, }; if ('email' in verification || 'passphrase' in verification || 'oidcIdToken' in verification || 'phoneNumber' in verification) { request.v2_encrypted_verification_key = ghostDeviceToEncryptedVerificationKey(ghostDevice, this._localUser.userSecret); request.verification = formatVerificationRequest(verification, this._localUser); request.verification.with_token = verification.withToken; // May be undefined } await this._client.createUser(firstDeviceId, firstDeviceSignatureKeyPair, request); await this.updateDeviceInfo(firstDeviceId, firstDeviceEncryptionKeyPair, firstDeviceSignatureKeyPair); }; createNewDevice = async (verification: VerificationWithToken): Promise<void> => { try { const verificationKey = await this.getVerificationKey(verification); const ghostDevice = extractGhostDevice(verificationKey); const ghostSignatureKeyPair = tcrypto.getSignatureKeyPairFromPrivateKey(ghostDevice.privateSignatureKey); const encryptedUserKey = await this._client.getEncryptionKey(ghostSignatureKeyPair.publicKey); const userEncryptionKeyPair = decryptUserKeyForGhostDevice(ghostDevice, encryptedUserKey); const { trustchainId, userId } = this._localUser; const newDevice = await generateDeviceFromGhostDevice(trustchainId, userId, ghostDevice, encryptedUserKey.deviceId, userEncryptionKeyPair); const deviceId = newDevice.hash; const deviceSignatureKeyPair = newDevice.signatureKeyPair; await this._client.createDevice(deviceId, deviceSignatureKeyPair, { device_creation: newDevice.block }); await this.updateDeviceInfo(deviceId, newDevice.encryptionKeyPair, deviceSignatureKeyPair); } catch (err) { const e = err as Error; if (e instanceof TankerError) { throw e; } if ('verificationKey' in verification) { throw new InvalidVerification(e); } throw new InternalError(e.toString()); } }; revokeDevice = async (deviceToRevokeId: Uint8Array): Promise<void> => { await this.updateLocalUser({ isLight: false }); const { payload, nature } = makeDeviceRevocation(this._localUser.devices, this._localUser.currentUserKey, deviceToRevokeId); const block = this._localUser.makeBlock(payload, nature); await this._client.revokeDevice({ device_revocation: block }); }; listDevices = async (): Promise<Array<Device>> => { await this.updateLocalUser({ isLight: false }); const devices = this._localUser.devices; return devices.filter(d => !d.isGhostDevice); }; getSessionToken = async (verification: VerificationWithToken): Promise<string> => { await this.updateLocalUser({ isLight: true }); const { payload, nature } = makeSessionCertificate(verification); const block = this._localUser.makeBlock(payload, nature); if (!verification.withToken) throw new InternalError('Assertion error: Cannot get a session certificate without withToken'); return this._client.getSessionToken({ session_certificate: block, nonce: verification.withToken.nonce }); }; findUserKey = async (publicKey: Uint8Array): Promise<tcrypto.SodiumKeyPair | undefined> => { const userKey = this._localUser.findUserKey(publicKey); if (!userKey) { await this.updateLocalUser({ isLight: true }); } return this._localUser.findUserKey(publicKey); }; updateLocalUser = async (options: PullOptions = {}) => { // To update the local user, we can't just get our user because in light // mode, only the first device will be returned. So we pull by device to get // at least the first device and our device. const { root, histories } = await this._client.getUserHistoriesByDeviceIds([this._localUser.deviceId], options); const localUserBlocks = [root, ...histories]; this._localUser.initializeWithBlocks(localUserBlocks); await this._keyStore.save(this._localUser.localData, this._localUser.userSecret); }; get localUser(): LocalUser { return this._localUser; } findProvisionalUserKey = (appPublicSignatureKey: Uint8Array, tankerPublicSignatureKey: Uint8Array): PrivateProvisionalKeys | null => { const id = utils.concatArrays(appPublicSignatureKey, tankerPublicSignatureKey); const result = this._provisionalUserKeys[utils.toBase64(id)]; if (result) { const { appEncryptionKeyPair, tankerEncryptionKeyPair } = result; return { appEncryptionKeyPair, tankerEncryptionKeyPair }; } return null; }; addProvisionalUserKey = async (appPublicSignatureKey: Uint8Array, tankerPublicSignatureKey: Uint8Array, privateProvisionalKeys: PrivateProvisionalKeys): Promise<void> => { const id = utils.toBase64(utils.concatArrays(appPublicSignatureKey, tankerPublicSignatureKey)); this._provisionalUserKeys[id] = { id, appEncryptionKeyPair: privateProvisionalKeys.appEncryptionKeyPair, tankerEncryptionKeyPair: privateProvisionalKeys.tankerEncryptionKeyPair, }; return this._keyStore.saveProvisionalUserKeys(this._provisionalUserKeys, this._localUser.userSecret); }; hasProvisionalUserKey = (appPublicEncryptionKey: Uint8Array): boolean => { const puks = Object.values(this._provisionalUserKeys); return puks.some(puk => utils.equalArray(puk.appEncryptionKeyPair.publicKey, appPublicEncryptionKey)); }; generateVerificationKey = async () => { const ghostDeviceKeys = generateGhostDeviceKeys(); return ghostDeviceToVerificationKey({ privateSignatureKey: ghostDeviceKeys.signatureKeyPair.privateKey, privateEncryptionKey: ghostDeviceKeys.encryptionKeyPair.privateKey, }); }; getVerificationKey = async (verification: VerificationWithToken) => { if ('verificationKey' in verification) { return verification.verificationKey; } const remoteVerification: RemoteVerificationWithToken = (verification as any); const request = { verification: formatVerificationRequest(remoteVerification, this._localUser) }; if (!isPreverifiedVerificationRequest(request.verification)) { request.verification.with_token = verification.withToken; // May be undefined } const encryptedVerificationKey = await this._client.getVerificationKey(request); return decryptVerificationKey(encryptedVerificationKey, this._localUser.userSecret); }; } export default LocalUserManager;
the_stack
import { LoanMasterNodeRegTestContainer } from './loan_container' import { GenesisKeys } from '@defichain/testcontainers' import BigNumber from 'bignumber.js' import { TestingGroup } from '@defichain/jellyfish-testing' describe('Loan', () => { const tGroup = TestingGroup.create(2, i => new LoanMasterNodeRegTestContainer(GenesisKeys[i])) let vaultWithCollateralId: string // Vault with collateral token deposited let vaultWithoutCollateral1Id: string // Vaults without collateral token deposited let vaultWithoutCollateral2Id: string let vaultWithoutCollateral3Id: string let vaultWithLoanTakenId: string // Vault with loan taken let vaultWithPayBackLoanId: string // Vault with loan taken paid back let vaultWithLiquidationId: string // Vault with liquidation event triggered let vaultAddressWithoutCollateral2Id: string let oracleId: string beforeAll(async () => { await tGroup.start() await tGroup.get(0).container.waitForWalletCoinbaseMaturity() await setup() }) afterAll(async () => { await tGroup.stop() }) async function setup (): Promise<void> { // token setup const collateralAddress = await tGroup.get(0).container.getNewAddress() await tGroup.get(0).token.dfi({ address: collateralAddress, amount: 200000 }) // oracle setup const addr = await tGroup.get(0).generateAddress() const priceFeeds = [ { token: 'DFI', currency: 'USD' }, { token: 'TSLA', currency: 'USD' }, { token: 'DUSD', currency: 'USD' } ] oracleId = await tGroup.get(0).rpc.oracle.appointOracle(addr, priceFeeds, { weightage: 1 }) await tGroup.get(0).generate(1) await tGroup.get(0).rpc.oracle.setOracleData(oracleId, Math.floor(new Date().getTime() / 1000), { prices: [{ tokenAmount: '1@DFI', currency: 'USD' }] }) await tGroup.get(0).rpc.oracle.setOracleData(oracleId, Math.floor(new Date().getTime() / 1000), { prices: [{ tokenAmount: '2@TSLA', currency: 'USD' }] }) await tGroup.get(0).rpc.oracle.setOracleData(oracleId, Math.floor(new Date().getTime() / 1000), { prices: [{ tokenAmount: '1@DUSD', currency: 'USD' }] }) await tGroup.get(0).generate(1) // loan scheme setup await tGroup.get(0).rpc.loan.createLoanScheme({ minColRatio: 150, interestRate: new BigNumber(3), id: 'scheme' }) await tGroup.get(0).generate(1) // collateral token setup await tGroup.get(0).rpc.loan.setCollateralToken({ token: 'DFI', factor: new BigNumber(1), fixedIntervalPriceId: 'DFI/USD' }) await tGroup.get(0).generate(1) // DUSD proper set up await tGroup.get(0).rpc.loan.setLoanToken({ symbol: 'DUSD', fixedIntervalPriceId: 'DUSD/USD' }) await tGroup.get(0).generate(1) await tGroup.get(0).rpc.loan.createLoanScheme({ minColRatio: 150, interestRate: new BigNumber(1), id: 'default' }) await tGroup.get(0).generate(1) const aliceVaultAddr = await tGroup.get(0).generateAddress() const aliceVaultId = await tGroup.get(0).rpc.loan.createVault({ ownerAddress: aliceVaultAddr, loanSchemeId: 'default' }) await tGroup.get(0).generate(1) await tGroup.get(0).rpc.loan.depositToVault({ vaultId: aliceVaultId, from: collateralAddress, amount: '90000@DFI' }) await tGroup.get(0).generate(1) await tGroup.get(0).rpc.loan.takeLoan({ vaultId: aliceVaultId, to: collateralAddress, amounts: ['60000@DUSD'] }) await tGroup.get(0).generate(1) // DUSD set up END await tGroup.get(0).poolpair.create({ tokenA: 'DUSD', tokenB: 'DFI' }) await tGroup.get(0).generate(1) await tGroup.get(0).poolpair.add({ a: { symbol: 'DUSD', amount: 25000 }, b: { symbol: 'DFI', amount: 10000 } }) await tGroup.get(0).generate(1) // loan token setup await tGroup.get(0).rpc.loan.setLoanToken({ symbol: 'TSLA', fixedIntervalPriceId: 'TSLA/USD' }) await tGroup.get(0).generate(1) // Mint TSLA await tGroup.get(0).token.mint({ symbol: 'TSLA', amount: 30000 }) await tGroup.get(0).generate(1) await tGroup.get(0).poolpair.create({ tokenA: 'TSLA', tokenB: 'DUSD' }) await tGroup.get(0).generate(1) await tGroup.get(0).poolpair.add({ a: { symbol: 'TSLA', amount: 20000 }, b: { symbol: 'DUSD', amount: 10000 } }) await tGroup.get(0).generate(1) // Vaults setup // vaultWithCollateralId vaultWithCollateralId = await tGroup.get(0).rpc.loan.createVault({ ownerAddress: await tGroup.get(0).generateAddress(), loanSchemeId: 'scheme' }) await tGroup.get(0).generate(1) await tGroup.get(0).rpc.loan.depositToVault({ vaultId: vaultWithCollateralId, from: collateralAddress, amount: '2@DFI' }) await tGroup.get(0).generate(1) // vaultWithoutCollateral1Id vaultWithoutCollateral1Id = await tGroup.get(0).rpc.loan.createVault({ ownerAddress: await tGroup.get(0).generateAddress(), loanSchemeId: 'scheme' }) await tGroup.get(0).generate(1) // vaultWithoutCollateral2Id vaultAddressWithoutCollateral2Id = await tGroup.get(0).generateAddress() vaultWithoutCollateral2Id = await tGroup.get(0).rpc.loan.createVault({ ownerAddress: vaultAddressWithoutCollateral2Id, loanSchemeId: 'scheme' }) await tGroup.get(0).generate(1) // vaultWithoutCollateral3Id vaultWithoutCollateral3Id = await tGroup.get(0).rpc.loan.createVault({ ownerAddress: await tGroup.get(0).generateAddress(), loanSchemeId: 'scheme' }) await tGroup.get(0).generate(1) // vaultWithLoanTakenId vaultWithLoanTakenId = await tGroup.get(0).rpc.loan.createVault({ ownerAddress: await tGroup.get(0).generateAddress(), loanSchemeId: 'scheme' }) await tGroup.get(0).generate(1) await tGroup.get(0).rpc.loan.depositToVault({ vaultId: vaultWithLoanTakenId, from: collateralAddress, amount: '10000@DFI' }) await tGroup.get(0).generate(1) await tGroup.get(0).rpc.loan.takeLoan({ vaultId: vaultWithLoanTakenId, amounts: '1@TSLA' }) await tGroup.get(0).generate(1) // vaultWithPayBackLoanId const vaultWithPayBackLoanAddress = await tGroup.get(0).generateAddress() vaultWithPayBackLoanId = await tGroup.get(0).rpc.loan.createVault({ ownerAddress: vaultWithPayBackLoanAddress, loanSchemeId: 'scheme' }) await tGroup.get(0).generate(1) await tGroup.get(0).rpc.loan.depositToVault({ vaultId: vaultWithPayBackLoanId, from: collateralAddress, amount: '5@DFI' }) await tGroup.get(0).generate(1) await tGroup.get(0).rpc.loan.takeLoan({ vaultId: vaultWithPayBackLoanId, amounts: '1@TSLA' }) await tGroup.get(0).generate(1) // Send TSLA to vaultWithPayBackLoanAddress so it has enough TSLA to pay back loan await tGroup.get(0).rpc.account.sendTokensToAddress({}, { [vaultWithPayBackLoanAddress]: ['5@TSLA'] }) await tGroup.get(0).generate(1) await tGroup.get(0).rpc.container.call('paybackloan', [{ vaultId: vaultWithPayBackLoanId, from: vaultWithPayBackLoanAddress, amounts: '2@TSLA' }]) await tGroup.get(0).generate(1) // vaultWithLiquidationId vaultWithLiquidationId = await tGroup.get(0).rpc.loan.createVault({ ownerAddress: await tGroup.get(0).generateAddress(), loanSchemeId: 'scheme' }) await tGroup.get(0).generate(1) await tGroup.get(0).rpc.loan.depositToVault({ vaultId: vaultWithLiquidationId, from: collateralAddress, amount: '300@DFI' }) await tGroup.get(0).generate(1) await tGroup.get(0).rpc.loan.takeLoan({ vaultId: vaultWithLiquidationId, amounts: '100@TSLA' }) await tGroup.get(0).generate(1) await tGroup.waitForSync() } it('should closeVault', async () => { { const address = await tGroup.get(0).generateAddress() const addressAccountBefore = await tGroup.get(0).rpc.account.getAccount(address) expect(addressAccountBefore).toStrictEqual([]) // 0 DFI const txId = await tGroup.get(0).rpc.loan.closeVault({ vaultId: vaultWithCollateralId, to: address }) await tGroup.get(0).generate(1) const addressAccountAfter = await tGroup.get(0).rpc.account.getAccount(address) expect(addressAccountAfter).toStrictEqual(['2.50000000@DFI']) // 2 + 0.5 DFI (Get back collateral tokens and fee) expect(typeof txId).toStrictEqual('string') expect(txId.length).toStrictEqual(64) } { const address = await tGroup.get(0).generateAddress() const addressAccountBefore = await tGroup.get(0).rpc.account.getAccount(address) expect(addressAccountBefore).toStrictEqual([]) // 0 DFI const txId = await tGroup.get(0).rpc.loan.closeVault({ vaultId: vaultWithoutCollateral1Id, to: address }) await tGroup.get(0).generate(1) const addressAccountAfter = await tGroup.get(0).rpc.account.getAccount(address) expect(addressAccountAfter).toStrictEqual(['0.50000000@DFI']) // 0.5 DFI (Get back fee only) expect(typeof txId).toStrictEqual('string') expect(txId.length).toStrictEqual(64) } }) it('should closeVault if loan is paid back', async () => { const txId = await tGroup.get(0).rpc.loan.closeVault({ vaultId: vaultWithPayBackLoanId, to: await tGroup.get(0).generateAddress() }) expect(typeof txId).toStrictEqual('string') expect(txId.length).toStrictEqual(64) await tGroup.get(0).generate(1) }) it('should not closeVault as vault does not exist', async () => { const promise = tGroup.get(0).rpc.loan.closeVault({ vaultId: '0'.repeat(64), to: await tGroup.get(0).generateAddress() }) await expect(promise).rejects.toThrow(`RpcApiError: 'Vault <${'0'.repeat(64)}> does not found', code: -5, method: closevault`) }) it('should not closeVault for vault with loan taken', async () => { const promise = tGroup.get(0).rpc.loan.closeVault({ vaultId: vaultWithLoanTakenId, to: await tGroup.get(0).generateAddress() }) await expect(promise).rejects.toThrow(`RpcApiError: 'Test CloseVaultTx execution failed:\nVault <${vaultWithLoanTakenId}> has loans', code: -32600, method: closevault`) }) it('should not closeVault for mayliquidate vault', async () => { await tGroup.get(0).rpc.oracle.setOracleData(oracleId, Math.floor(new Date().getTime() / 1000), { prices: [{ tokenAmount: '2.1@TSLA', currency: 'USD' }] }) await tGroup.get(0).generate(1) await tGroup.get(0).container.waitForNextPrice('TSLA/USD', '2.1') const liqVault = await tGroup.get(0).container.call('getvault', [vaultWithLiquidationId]) expect(liqVault.state).toStrictEqual('mayLiquidate') const promise = tGroup.get(0).rpc.loan.closeVault({ vaultId: vaultWithLiquidationId, to: await tGroup.get(0).generateAddress() }) await expect(promise).rejects.toThrow(`RpcApiError: 'Test CloseVaultTx execution failed:\nVault <${vaultWithLiquidationId}> has loans', code: -32600, method: closevault`) await tGroup.get(0).rpc.oracle.setOracleData(oracleId, Math.floor(new Date().getTime() / 1000), { prices: [{ tokenAmount: '2@TSLA', currency: 'USD' }] }) await tGroup.get(0).generate(1) await tGroup.get(0).container.waitForActivePrice('TSLA/USD', '2') }) it('should not closeVault for frozen vault', async () => { await tGroup.get(0).rpc.oracle.setOracleData(oracleId, Math.floor(new Date().getTime() / 1000), { prices: [{ tokenAmount: '3@TSLA', currency: 'USD' }] }) await tGroup.get(0).generate(1) await tGroup.get(0).container.waitForPriceInvalid('TSLA/USD') const liqVault = await tGroup.get(0).container.call('getvault', [vaultWithLiquidationId]) expect(liqVault.state).toStrictEqual('frozen') const promise = tGroup.get(0).rpc.loan.closeVault({ vaultId: vaultWithLiquidationId, to: await tGroup.get(0).generateAddress() }) await expect(promise).rejects.toThrow(`RpcApiError: 'Test CloseVaultTx execution failed:\nVault <${vaultWithLiquidationId}> has loans', code: -32600, method: closevault`) await tGroup.get(0).container.waitForPriceValid('TSLA/USD') await tGroup.get(0).rpc.oracle.setOracleData(oracleId, Math.floor(new Date().getTime() / 1000), { prices: [{ tokenAmount: '2@TSLA', currency: 'USD' }] }) await tGroup.get(0).generate(1) await tGroup.get(0).container.waitForPriceInvalid('TSLA/USD') await tGroup.get(0).container.waitForPriceValid('TSLA/USD') }) it('should not closeVault for liquidated vault', async () => { await tGroup.get(0).rpc.oracle.setOracleData(oracleId, Math.floor(new Date().getTime() / 1000), { prices: [{ tokenAmount: '3@TSLA', currency: 'USD' }] }) await tGroup.get(0).generate(1) await tGroup.get(0).container.waitForPriceInvalid('TSLA/USD') await tGroup.get(0).container.waitForPriceValid('TSLA/USD') const liqVault = await tGroup.get(0).container.call('getvault', [vaultWithLiquidationId]) expect(liqVault.state).toStrictEqual('inLiquidation') const promise = tGroup.get(0).rpc.loan.closeVault({ vaultId: vaultWithLiquidationId, to: await tGroup.get(0).generateAddress() }) await expect(promise).rejects.toThrow('RpcApiError: \'Vault is under liquidation.\', code: -26, method: closevault') await tGroup.get(0).rpc.oracle.setOracleData(oracleId, Math.floor(new Date().getTime() / 1000), { prices: [{ tokenAmount: '2@TSLA', currency: 'USD' }] }) await tGroup.get(0).generate(1) await tGroup.get(0).container.waitForPriceInvalid('TSLA/USD') await tGroup.get(0).container.waitForPriceValid('TSLA/USD') }) it('should not closeVault by anyone other than the vault owner', async () => { const address = await tGroup.get(1).generateAddress() const promise = tGroup.get(1).rpc.loan.closeVault({ vaultId: vaultWithoutCollateral2Id, to: address }) await expect(promise).rejects.toThrow(`RpcApiError: 'Incorrect authorization for ${vaultAddressWithoutCollateral2Id}', code: -5, method: closevault`) }) it('should closeVault with utxos', async () => { const utxo = await tGroup.get(0).container.fundAddress(vaultAddressWithoutCollateral2Id, 10) const txId = await tGroup.get(0).rpc.loan.closeVault({ vaultId: vaultWithoutCollateral2Id, to: await tGroup.get(0).generateAddress() }, [utxo]) expect(typeof txId).toStrictEqual('string') expect(txId.length).toStrictEqual(64) const rawtx = await tGroup.get(0).container.call('getrawtransaction', [txId, true]) expect(rawtx.vin[0].txid).toStrictEqual(utxo.txid) expect(rawtx.vin[0].vout).toStrictEqual(utxo.vout) }) it('should not closeVault with arbitrary utxos', async () => { const utxo = await tGroup.get(0).container.fundAddress(await tGroup.get(0).generateAddress(), 10) const promise = tGroup.get(0).rpc.loan.closeVault({ vaultId: vaultWithoutCollateral3Id, to: await tGroup.get(0).generateAddress() }, [utxo]) await expect(promise).rejects.toThrow('tx must have at least one input from token owner') }) })
the_stack
export interface Float16Array { /** * The size in bytes of each element in the array. */ readonly BYTES_PER_ELEMENT: number; /** * The ArrayBuffer instance referenced by the array. */ readonly buffer: ArrayBufferLike; /** * The length in bytes of the array. */ readonly byteLength: number; /** * The offset in bytes of the array. */ readonly byteOffset: number; [Symbol.iterator](): IterableIterator<number>; /** * Returns an array of key, value pairs for every entry in the array */ entries(): IterableIterator<[number, number]>; /** * Returns an list of keys in the array */ keys(): IterableIterator<number>; /** * Returns an list of values in the array */ values(): IterableIterator<number>; /** * Access item by relative indexing. * @param index index to access. */ at(index: number): number; /** * Returns the this object after copying a section of the array identified by start and end * to the same array starting at position target * @param target If target is negative, it is treated as length+target where length is the * length of the array. * @param start If start is negative, it is treated as length+start. If end is negative, it * is treated as length+end. * @param end If not specified, length of the this object is used as its default value. */ copyWithin(target: number, start: number, end?: number): this; /** * Determines whether all the members of an array satisfy the specified test. * @param callbackfn A function that accepts up to three arguments. The every method calls * the callbackfn function for each element in the array until the callbackfn returns a value * which is coercible to the Boolean value false, or until the end of the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ every( callbackfn: (value: number, index: number, array: Float16Array) => unknown, thisArg?: any, ): boolean; /** * Returns the this object after filling the section identified by start and end with value * @param value value to fill array section with * @param start index to start filling the array at. If start is negative, it is treated as * length+start where length is the length of the array. * @param end index to stop filling the array at. If end is negative, it is treated as * length+end. */ fill(value: number, start?: number, end?: number): this; /** * Returns the elements of an array that meet the condition specified in a callback function. * @param predicate A function that accepts up to three arguments. The filter method calls * the predicate function one time for each element in the array. * @param thisArg An object to which the this keyword can refer in the predicate function. * If thisArg is omitted, undefined is used as the this value. */ filter( predicate: (value: number, index: number, array: Float16Array) => any, thisArg?: any, ): Float16Array; /** * Returns the value of the first element in the array where predicate is true, and undefined * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending * order, until it finds one where predicate returns true. If such an element is found, find * immediately returns that element value. Otherwise, find returns undefined. * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ find( predicate: (value: number, index: number, obj: Float16Array) => boolean, thisArg?: any, ): number | undefined; /** * Returns the index of the first element in the array where predicate is true, and -1 * otherwise. * @param predicate find calls predicate once for each element of the array, in ascending * order, until it finds one where predicate returns true. If such an element is found, * findIndex immediately returns that element index. Otherwise, findIndex returns -1. * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ findIndex( predicate: (value: number, index: number, obj: Float16Array) => boolean, thisArg?: any, ): number; /** * Returns the value of the last element in the array where predicate is true, and undefined * otherwise. * @param predicate find calls predicate once for each element of the array, in descending * order, until it finds one where predicate returns true. If such an element is found, find * immediately returns that element value. Otherwise, find returns undefined. * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ findLast( predicate: (value: number, index: number, obj: Float16Array) => boolean, thisArg?: any, ): number | undefined; /** * Returns the index of the last element in the array where predicate is true, and -1 * otherwise. * @param predicate find calls predicate once for each element of the array, in descending * order, until it finds one where predicate returns true. If such an element is found, * findIndex immediately returns that element index. Otherwise, findIndex returns -1. * @param thisArg If provided, it will be used as the this value for each invocation of * predicate. If it is not provided, undefined is used instead. */ findLastIndex( predicate: (value: number, index: number, obj: Float16Array) => boolean, thisArg?: any, ): number; /** * Performs the specified action for each element in an array. * @param callbackfn A function that accepts up to three arguments. forEach calls the * callbackfn function one time for each element in the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ forEach( callbackfn: (value: number, index: number, array: Float16Array) => void, thisArg?: any, ): void; /** * Determines whether an array includes a certain element, returning true or false as appropriate. * @param searchElement The element to search for. * @param fromIndex The position in this array at which to begin searching for searchElement. */ includes(searchElement: number, fromIndex?: number): boolean; /** * Returns the index of the first occurrence of a value in an array. * @param searchElement The value to locate in the array. * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the * search starts at index 0. */ indexOf(searchElement: number, fromIndex?: number): number; /** * Adds all the elements of an array separated by the specified separator string. * @param separator A string used to separate one element of an array from the next in the * resulting String. If omitted, the array elements are separated with a comma. */ join(separator?: string): string; /** * Returns the index of the last occurrence of a value in an array. * @param searchElement The value to locate in the array. * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the * search starts at index 0. */ lastIndexOf(searchElement: number, fromIndex?: number): number; /** * The length of the array. */ readonly length: number; /** * Calls a defined callback function on each element of an array, and returns an array that * contains the results. * @param callbackfn A function that accepts up to three arguments. The map method calls the * callbackfn function one time for each element in the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ map( callbackfn: (value: number, index: number, array: Float16Array) => number, thisArg?: any, ): Float16Array; /** * Calls the specified callback function for all the elements in an array. The return value of * the callback function is the accumulated result, and is provided as an argument in the next * call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduce method calls the * callbackfn function one time for each element in the array. * @param initialValue If initialValue is specified, it is used as the initial value to start * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ reduce( callbackfn: ( previousValue: number, currentValue: number, currentIndex: number, array: Float16Array, ) => number, ): number; reduce( callbackfn: ( previousValue: number, currentValue: number, currentIndex: number, array: Float16Array, ) => number, initialValue: number, ): number; /** * Calls the specified callback function for all the elements in an array. The return value of * the callback function is the accumulated result, and is provided as an argument in the next * call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduce method calls the * callbackfn function one time for each element in the array. * @param initialValue If initialValue is specified, it is used as the initial value to start * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ reduce<U>( callbackfn: ( previousValue: U, currentValue: number, currentIndex: number, array: Float16Array, ) => U, initialValue: U, ): U; /** * Calls the specified callback function for all the elements in an array, in descending order. * The return value of the callback function is the accumulated result, and is provided as an * argument in the next call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls * the callbackfn function one time for each element in the array. * @param initialValue If initialValue is specified, it is used as the initial value to start * the accumulation. The first call to the callbackfn function provides this value as an * argument instead of an array value. */ reduceRight( callbackfn: ( previousValue: number, currentValue: number, currentIndex: number, array: Float16Array, ) => number, ): number; reduceRight( callbackfn: ( previousValue: number, currentValue: number, currentIndex: number, array: Float16Array, ) => number, initialValue: number, ): number; /** * Calls the specified callback function for all the elements in an array, in descending order. * The return value of the callback function is the accumulated result, and is provided as an * argument in the next call to the callback function. * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls * the callbackfn function one time for each element in the array. * @param initialValue If initialValue is specified, it is used as the initial value to start * the accumulation. The first call to the callbackfn function provides this value as an argument * instead of an array value. */ reduceRight<U>( callbackfn: ( previousValue: U, currentValue: number, currentIndex: number, array: Float16Array, ) => U, initialValue: U, ): U; /** * Reverses the elements in an Array. */ reverse(): this; /** * Sets a value or an array of values. * @param array A typed or untyped array of values to set. * @param offset The index in the current array at which the values are to be written. */ set(array: ArrayLike<number>, offset?: number): void; /** * Returns a section of an array. * @param start The beginning of the specified portion of the array. * @param end The end of the specified portion of the array. This is exclusive of the element at the index 'end'. */ slice(start?: number, end?: number): Float16Array; /** * Determines whether the specified callback function returns true for any element of an array. * @param callbackfn A function that accepts up to three arguments. The some method calls * the callbackfn function for each element in the array until the callbackfn returns a value * which is coercible to the Boolean value true, or until the end of the array. * @param thisArg An object to which the this keyword can refer in the callbackfn function. * If thisArg is omitted, undefined is used as the this value. */ some( callbackfn: (value: number, index: number, array: Float16Array) => unknown, thisArg?: any, ): boolean; /** * Sorts an array. * @param compareFn Function used to determine the order of the elements. It is expected to return * a negative value if first argument is less than second argument, zero if they're equal and a positive * value otherwise. If omitted, the elements are sorted in ascending. */ sort(compareFn?: (a: number, b: number) => number): this; /** * Gets a new Float16Array view of the ArrayBuffer store for this array, referencing the elements * at begin, inclusive, up to end, exclusive. * @param begin The index of the beginning of the array. * @param end The index of the end of the array. */ subarray(begin?: number, end?: number): Float16Array; /** * Converts a number to a string by using the current locale. */ toLocaleString(): string; /** * Returns a string representation of an array. */ toString(): string; readonly [Symbol.toStringTag]: "Float16Array"; [index: number]: number; } export interface Float16ArrayConstructor { readonly prototype: Float16Array; new (): Float16Array; new (length: number): Float16Array; new (elements: Iterable<number>): Float16Array; new (array: ArrayLike<number> | ArrayBufferLike): Float16Array; new ( buffer: ArrayBufferLike, byteOffset: number, length?: number, ): Float16Array; /** * The size in bytes of each element in the array. */ readonly BYTES_PER_ELEMENT: number; /** * Returns a new array from a set of elements. * @param items A set of elements to include in the new array object. */ of(...items: number[]): Float16Array; /** * Creates an array from an array-like or iterable object. * @param elements An iterable object to convert to an array. */ from(elements: Iterable<number>): Float16Array; /** * Creates an array from an array-like or iterable object. * @param elements An iterable object to convert to an array. * @param mapfn A mapping function to call on every element of the array. * @param thisArg Value of 'this' used to invoke the mapfn. */ from<T>( elements: Iterable<T>, mapfn: (v: T, k: number) => number, thisArg?: any, ): Float16Array; /** * Creates an array from an array-like or iterable object. * @param arrayLike An array-like object to convert to an array. */ from(arrayLike: ArrayLike<number>): Float16Array; /** * Creates an array from an array-like or iterable object. * @param arrayLike An array-like object to convert to an array. * @param mapfn A mapping function to call on every element of the array. * @param thisArg Value of 'this' used to invoke the mapfn. */ from<T>( arrayLike: ArrayLike<T>, mapfn: (v: T, k: number) => number, thisArg?: any, ): Float16Array; } export declare const Float16Array: Float16ArrayConstructor; /** * Returns `true` if the value is a Float16Array instance. * @since v3.4.0 */ export declare function isFloat16Array(value: unknown): value is Float16Array; /** * Gets the Float16 value at the specified byte offset from the start of the view. There is * no alignment constraint; multi-byte values may be fetched from any offset. * @param byteOffset The place in the buffer at which the value should be retrieved. * @param littleEndian If false or undefined, a big-endian value should be read, * otherwise a little-endian value should be read. */ export declare function getFloat16( dataView: DataView, byteOffset: number, littleEndian?: boolean, ): number; /** * Stores an Float16 value at the specified byte offset from the start of the view. * @param byteOffset The place in the buffer at which the value should be set. * @param value The value to set. * @param littleEndian If false or undefined, a big-endian value should be written, * otherwise a little-endian value should be written. */ export declare function setFloat16( dataView: DataView, byteOffset: number, value: number, littleEndian?: boolean, ): void; /** * Returns the nearest half precision float representation of a number. * @param x A numeric expression. */ export declare function hfround(x: number): number;
the_stack
import { isMissing, isIterable, isInstance, isFunction } from "./utils"; export class LinkedListNode<T> { /*@internal*/ _list: LinkedList<T> | undefined = undefined; /*@internal*/ _previous: LinkedListNode<T> | undefined = undefined; /*@internal*/ _next: LinkedListNode<T> | undefined = undefined; public value: T | undefined; constructor(value?: T) { this.value = value; } public get list(): LinkedList<T> | undefined { return this._list; } public get previous(): LinkedListNode<T> | undefined { if (this._previous && this._list && this !== this._list.first) { return this._previous; } return undefined; } public get next(): LinkedListNode<T> | undefined { if (this._next && this._list && this._next !== this._list.first) { return this._next; } return undefined; } } const enum Position { before, after } export class LinkedList<T> { private _head: LinkedListNode<T> | undefined = undefined; private _size: number = 0; public constructor(iterable?: Iterable<T>) { if (!isIterable(iterable, /*optional*/ true)) throw new TypeError("Object not iterable: iterable."); if (!isMissing(iterable)) { for (const value of iterable) { this.push(value); } } } public get first(): LinkedListNode<T> | undefined { return this._head; } public get last(): LinkedListNode<T> | undefined { if (this._head) { return this._head._previous; } return undefined; } public get size(): number { return this._size; } public * values() { for (const node of this.nodes()) { yield node.value; } } public * nodes() { let node: LinkedListNode<T>; let next = this.first; while (next !== undefined) { node = next; next = node.next; yield node; } } public * drain() { for (const node of this.nodes()) { this.deleteNode(node); yield node.value; } } public find(value: T): LinkedListNode<T> | undefined { for (let node = this.first; node; node = node.next) { if (sameValue(node.value, value)) { return node; } } return undefined; } public findLast(value: T): LinkedListNode<T> | undefined { for (let node = this.last; node; node = node.previous) { if (sameValue(node.value, value)) { return node; } } return undefined; } public has(value: T): boolean { return this.find(value) !== undefined; } public insertBefore(node: LinkedListNode<T>, value: T): LinkedListNode<T> { if (!isInstance(node, LinkedListNode, /*optional*/ true)) throw new TypeError("LinkedListNode expected: node"); if (!isMissing(node) && node.list !== this) throw new Error("Wrong list."); return this._insertNode(node, new LinkedListNode(value), Position.before); } public insertNodeBefore(node: LinkedListNode<T>, newNode: LinkedListNode<T>): void { if (!isInstance(node, LinkedListNode, /*optional*/ true)) throw new TypeError("LinkedListNode expected: node"); if (!isInstance(newNode, LinkedListNode)) throw new TypeError("LinkedListNode expected: newNode"); if (!isMissing(node) && node.list !== this) throw new Error("Wrong list."); if (!isMissing(newNode.list)) throw new Error("Node is already attached to a list."); this._insertNode(node, newNode, Position.before); } public insertAfter(node: LinkedListNode<T>, value: T): LinkedListNode<T> { if (!isInstance(node, LinkedListNode, /*optional*/ true)) throw new TypeError("LinkedListNode expected: node"); if (!isMissing(node) && node.list !== this) throw new Error("Wrong list."); return this._insertNode(node, new LinkedListNode(value), Position.after); } public insertNodeAfter(node: LinkedListNode<T>, newNode: LinkedListNode<T>): void { if (!isInstance(node, LinkedListNode, /*optional*/ true)) throw new TypeError("LinkedListNode expected: node"); if (!isInstance(newNode, LinkedListNode)) throw new TypeError("LinkedListNode expected: newNode"); if (!isMissing(node) && node.list !== this) throw new Error("Wrong list."); if (!isMissing(newNode.list)) throw new Error("Node is already attached to a list."); this._insertNode(node, newNode, Position.after); } public push(value?: T): LinkedListNode<T> { return this._insertNode(undefined, new LinkedListNode(value), Position.after); } public pushNode(newNode: LinkedListNode<T>): void { if (!isInstance(newNode, LinkedListNode)) throw new TypeError("LinkedListNode expected: newNode"); if (!isMissing(newNode.list)) throw new Error("Node is already attached to a list."); this._insertNode(undefined, newNode, Position.after); } public pop(): T | undefined { let node = this.popNode(); return node ? node.value : undefined; } public popNode(): LinkedListNode<T> | undefined { let node = this.last; if (this.deleteNode(node)) { return node; } } public shift(): T | undefined { let node = this.shiftNode(); return node ? node.value : undefined; } public shiftNode(): LinkedListNode<T> | undefined { let node = this.first; if (this.deleteNode(node)) { return node; } } public unshift(value?: T): LinkedListNode<T> { return this._insertNode(undefined, new LinkedListNode(value), Position.before); } public unshiftNode(newNode: LinkedListNode<T>): void { if (!isInstance(newNode, LinkedListNode)) throw new TypeError("LinkedListNode expected: newNode"); if (!isMissing(newNode.list)) throw new Error("Node is already attached to a list."); this._insertNode(undefined, newNode, Position.before); } public delete(value: T): boolean { return this.deleteNode(this.find(value)); } public deleteNode(node: LinkedListNode<T> | undefined): boolean { if (isMissing(node) || node.list !== this) { return false; } return this._deleteNode(node); } public deleteAll(predicate: (value: T, node: LinkedListNode<T>, list: LinkedList<T>) => boolean, thisArg?: any) { if (!isFunction(predicate)) throw new TypeError("Function expected: predicate"); let count = 0; let node = this.first; while (node) { let next = node.next; if (predicate.call(thisArg, node.value!, node, this) && node.list === this) { this._deleteNode(node); ++count; } node = next; } return count; } public clear(): void { while (this.size > 0) { this.deleteNode(this.last); } } public forEach(callback: (value: T, node: LinkedListNode<T>, list: LinkedList<T>) => void, thisArg?: any) { if (!isFunction(callback)) throw new TypeError("Function expected: predicate"); for (const node of this.nodes()) { callback.call(thisArg, node.value!, node, this); } } private _deleteNode(node: LinkedListNode<T>): boolean { if (node._next === node) { this._head = undefined; } else { node._next!._previous = node._previous; node._previous!._next = node._next; if (this._head === node) { this._head = node._next; } } node._list = undefined; node._next = undefined; node._previous = undefined; this._size--; return true; } private _insertNode(adjacentNode: LinkedListNode<T> | undefined, newNode: LinkedListNode<T>, position: Position) { newNode._list = this; if (this._head === undefined) { newNode._next = newNode; newNode._previous = newNode; this._head = newNode; } else { switch (position) { case Position.before: if (adjacentNode === undefined) { adjacentNode = this._head; this._head = newNode; } else if (adjacentNode === this._head) { this._head = newNode; } newNode._next = adjacentNode; newNode._previous = adjacentNode._previous; adjacentNode._previous!._next = newNode; adjacentNode._previous = newNode; break; case Position.after: if (adjacentNode === undefined) { adjacentNode = this._head._previous!; } newNode._previous = adjacentNode; newNode._next = adjacentNode._next; adjacentNode._next!._previous = newNode; adjacentNode._next = newNode; break; } } this._size++; return newNode; } } export interface LinkedList<T> { [Symbol.iterator](): Iterator<T>; } LinkedList.prototype[Symbol.iterator] = LinkedList.prototype.values; function sameValue(x: any, y: any) { return (x === y) ? (x !== 0 || 1 / x === 1 / y) : (x !== x && y !== y); }
the_stack
import { Component } from '@angular/core'; import { state } from '@angular/core'; import { Observable } from 'rxjs/Observable'; import { Store } from '@ngrx/store'; import * as THREE from 'three'; import * as ThreeOrbitControls from 'three-orbit-controls'; import { AppStore } from '../../models/appstore.model'; import { AudioStream } from '../../audio-element'; import { AudioControlsActions } from '../../actions/audio-controls.actions'; @Component({ selector: 'three-d-frequencyBars', templateUrl: './three-d-sharedCanvas.component.html' }) export class ThreeDFrequencyBarsComponent { private audioCtx: any; private audioSrcNode: any; private scene: any; private camera: any; private renderer: any; private geometry: any; private material: any; private mesh: any; private OrbitControls: any; private audio: any; private controls: any; private reRender: boolean; constructor( private audioSrc: AudioStream, private store$: Store<AppStore> ) { this.audioCtx = audioSrc.audioCtx; this.audioSrcNode = audioSrc.audioSrcNode; this.reRender = true; } ngOnDestroy() { this.reRender = false; } ngOnInit() { // scene/environmental variables let scene, ambientLight, pointLight, lightCrazyTime, camera, renderer; // object/animation variables let geometry, material1, material2, material3, material4, material5, material6, material7, material8, material9, material10, mesh1, mesh2, mesh3, mesh4, mesh5, mesh6, mesh7, mesh8, mesh9, mesh10; let context = this; ////////////////////// Audio Set Up ///////////////////////////// ///////////////////////////////////////////////////////////////// // this.audioSrcNode.frequencyAnalyser.smoothingTimeConstant = 1; let frequencyData = new Uint8Array(this.audioSrc.frequencyAnalyser.frequencyBinCount); ////////////////////// Renderer and Scene /////////////////////// ///////////////////////////////////////////////////////////////// renderer = new THREE.WebGLRenderer( { canvas: <HTMLCanvasElement> document.getElementById('threeDCanvas'), antialias: true, alpha: true } ); renderer.setClearColor( 0x000000, 0 ); renderer.setPixelRatio(window.devicePixelRatio); renderer.setSize(window.innerWidth, window.innerHeight - 5); // -5 to keep from showing scroll bar on right // shadows for point light animation renderer.shadowMap.enabled = true; renderer.shadowMap.type = THREE.BasicShadowMap; // SCENE scene = new THREE.Scene(); ////////////////////////// Camera /////////////////////////////// ///////////////////////////////////////////////////////////////// camera = new THREE.PerspectiveCamera(35, window.innerWidth / window.innerHeight, 0.1, 3000); // camera = new THREE.OrthographicCamera(window.innerWidth / -2, window.innerWidth / 2, window.innerHeight / 2, window.innerHeight / -2, 0.1, 3000); camera.position.set( 0, 100, 1500 ); // scene.add(camera); // update on resize: renderer size, aspect ratio and projection matrix window.addEventListener('resize', function () { let WIDTH = window.innerWidth, HEIGHT = window.innerHeight; renderer.setSize(WIDTH, HEIGHT - 5); // -5 to keep from showing scroll bar on right camera.aspect = WIDTH / HEIGHT; camera.updateProjectionMatrix(); }); //////////////// Orbit Controls - In Development //////////////// ///////////////////////////////////////////////////////////////// let OrbitControls = ThreeOrbitControls(THREE); this.controls = new OrbitControls(camera, renderer.domElement); /////////////////////////// LIGHTS ////////////////////////////// ///////////////////////////////////////////////////////////////// // -Ambiant light globally illuminates all objects in the scene equally. // AmbientLight( color, intensity ) // -Point light gets emitted from a single point in all directions. // PointLight( color, intensity, distance, decay ) ambientLight = new THREE.AmbientLight(0xffffff, 0.5); pointLight = new THREE.PointLight(0xffffff, 0.5, -50, 10); // distance default === 0, decay default === 1 scene.add(ambientLight); scene.add(pointLight); /////////////////////////// Objects ///////////////////////////// ///////////////////////////////////////////////////////////////// // BoxGeometry(width, height, depth, widthSegments, heightSegments, depthSegments) geometry = new THREE.BoxGeometry(50, 50, 50); // segmented faces optional. Default is 1. // geometry.castShadow = true; // geometry.receiveShadow = true; // shinyMaterial = new THREE.MeshPhongMaterial({color:0x1A1A1A}); // for non-shiny surfaces use MeshLambertMaterial material1 = new THREE.MeshLambertMaterial({color: 0x1A1A1A}); material2 = new THREE.MeshLambertMaterial({color: 0x1A1A1A}); material3 = new THREE.MeshLambertMaterial({color: 0x1A1A1A}); material4 = new THREE.MeshLambertMaterial({color: 0x1A1A1A}); material5 = new THREE.MeshLambertMaterial({color: 0x1A1A1A}); material6 = new THREE.MeshLambertMaterial({color: 0x1A1A1A}); material7 = new THREE.MeshLambertMaterial({color: 0x1A1A1A}); material8 = new THREE.MeshLambertMaterial({color: 0x1A1A1A}); material9 = new THREE.MeshLambertMaterial({color: 0x1A1A1A}); material10 = new THREE.MeshLambertMaterial({color: 0x1A1A1A}); mesh1 = new THREE.Mesh(geometry, material1); mesh2 = new THREE.Mesh(geometry, material2); mesh3 = new THREE.Mesh(geometry, material3); mesh4 = new THREE.Mesh(geometry, material4); mesh5 = new THREE.Mesh(geometry, material5); mesh6 = new THREE.Mesh(geometry, material6); mesh7 = new THREE.Mesh(geometry, material7); mesh8 = new THREE.Mesh(geometry, material8); mesh9 = new THREE.Mesh(geometry, material9); mesh10 = new THREE.Mesh(geometry, material10); let zPosition = 0 mesh1.position.set(-450, 0, zPosition); mesh2.position.set(-350, 0, zPosition); mesh3.position.set(-250, 0, zPosition); mesh4.position.set(-150, 0, zPosition); mesh5.position.set(-50, 0, zPosition); mesh6.position.set(50, 0, zPosition); mesh7.position.set(150, 0, zPosition); mesh8.position.set(250, 0, zPosition); mesh9.position.set(350, 0, zPosition); mesh10.position.set(450, 0, zPosition); scene.add(mesh1); scene.add(mesh2); scene.add(mesh3); scene.add(mesh4); scene.add(mesh5); scene.add(mesh6); scene.add(mesh7); scene.add(mesh8); scene.add(mesh9); scene.add(mesh10); ///////////////////////// Render Loop /////////////////////////// ///////////////////////////////////////////////////////////////// requestAnimationFrame(render); function render() { //////////////////////// Generate New Data //////////////////// context.audioSrc.frequencyAnalyser.getByteFrequencyData(frequencyData); ///////// Helper function to sum up portions of the data array function getDat(arr, startIdx, endIdx) { let result = 0; for (let i = startIdx; i <= endIdx; i++) { result += arr[i]; } return result; } let getDatBass = getDat(frequencyData, 0, 100); let getDatMid1 = getDat(frequencyData, 100, 200); let getDatMid2 = getDat(frequencyData, 200, 300); let getDatMid3 = getDat(frequencyData, 300, 400); let getDatMid4 = getDat(frequencyData, 400, 500); let getDatMid5 = getDat(frequencyData, 500, 600); let getDatMid6 = getDat(frequencyData, 600, 700); let getDatMid7 = getDat(frequencyData, 700, 800); let getDatMid8 = getDat(frequencyData, 800, 900); let getDatTreble = getDat(frequencyData, 900, 1000); let totalSum = getDatBass + getDatMid1 + getDatMid2 + getDatMid3 + getDatMid4 + getDatMid5 + getDatMid6 + getDatMid7 + getDatMid8 + getDatTreble; //////////////////////// Animate Color ////////////////////// let colorOffset = 50; let colorAdjBass = Math.round(getDatBass / 150) + colorOffset; let colorAdjMid1 = Math.round(getDatMid1 / 150) + colorOffset; let colorAdjMid2 = Math.round(getDatMid2 / 150) + colorOffset; let colorAdjMid3 = Math.round(getDatMid2 / 150) + colorOffset; let colorAdjMid4 = Math.round(getDatMid4 / 150) + colorOffset; let colorAdjMid5 = Math.round(getDatMid5 / 150) + colorOffset; let colorAdjMid6 = Math.round(getDatMid6 / 150) + colorOffset; let colorAdjMid7 = Math.round(getDatMid7 / 150) + colorOffset; let colorAdjMid8 = Math.round(getDatMid8 / 150) + colorOffset; let colorAdjTreble = Math.round(getDatTreble / 150) + colorOffset; // mesh.material.color.setHex( adjment*0xff3300 ); // mesh.material.color.set( color ); // mesh.material.color.set( colorAdjment, colorAdjment, colorAdjment ); let colorString1 = 'rgb(' + colorAdjBass + ',' + colorAdjBass + ',' + colorAdjBass + ')'; let colorString2 = 'rgb(' + colorAdjMid1 + ',' + colorAdjMid1 + ',' + colorAdjMid1 + ')'; let colorString3 = 'rgb(' + colorAdjMid2 + ',' + colorAdjMid2 + ',' + colorAdjMid2 + ')'; let colorString4 = 'rgb(' + colorAdjMid3 + ',' + colorAdjMid3 + ',' + colorAdjMid3 + ')'; let colorString5 = 'rgb(' + colorAdjMid4 + ',' + colorAdjMid4 + ',' + colorAdjMid4 + ')'; let colorString6 = 'rgb(' + colorAdjMid5 + ',' + colorAdjMid5 + ',' + colorAdjMid5 + ')'; let colorString7 = 'rgb(' + colorAdjMid6 + ',' + colorAdjMid6 + ',' + colorAdjMid6 + ')'; let colorString8 = 'rgb(' + colorAdjMid7 + ',' + colorAdjMid7 + ',' + colorAdjMid7 + ')'; let colorString9 = 'rgb(' + colorAdjMid8 + ',' + colorAdjMid8 + ',' + colorAdjMid8 + ')'; let colorString10 = 'rgb(' + colorAdjTreble + ',' + colorAdjTreble + ',' + colorAdjTreble + ')'; mesh1.material.color.set(colorString1); mesh2.material.color.set(colorString2); mesh3.material.color.set(colorString3); mesh4.material.color.set(colorString4); mesh5.material.color.set(colorString5); mesh6.material.color.set(colorString6); mesh7.material.color.set(colorString7); mesh8.material.color.set(colorString8); mesh9.material.color.set(colorString9); mesh10.material.color.set(colorString10); /////////////////////// Animate Position ////////////////////// ///////// Geometry methods: https://threejs.org/docs/#Reference/Core/Geometry mesh1.scale.y = getDatBass / 3000 + 1; mesh2.scale.y = getDatMid1 / 3000 + 1; mesh3.scale.y = getDatMid2 / 3000 + 1; mesh4.scale.y = getDatMid3 / 3000 + 1; mesh5.scale.y = getDatMid4 / 3000 + 1; mesh6.scale.y = getDatMid5 / 3000 + 1; mesh7.scale.y = getDatMid6 / 3000 + 1; mesh8.scale.y = getDatMid7 / 3000 + 1; mesh9.scale.y = getDatMid8 / 3000 + 1; mesh10.scale.y = getDatTreble / 3000 + 1; let zPosition = 0; ////////////// position stated as (x, y, z) mesh1.position.set(-450, getDatBass / 120 - 100, zPosition); mesh2.position.set(-350, getDatMid1 / 120 - 100, zPosition); mesh3.position.set(-250, getDatMid2 / 120 - 100, zPosition); mesh4.position.set(-150, getDatMid3 / 120 - 100, zPosition); mesh5.position.set(-50, getDatMid4 / 120 - 100, zPosition); mesh6.position.set(50, getDatMid5 / 120 - 100, zPosition); mesh7.position.set(150, getDatMid6 / 120 - 100, zPosition); mesh8.position.set(250, getDatMid7 / 120 - 100, zPosition); mesh9.position.set(350, getDatMid8 / 120 - 100, zPosition); mesh10.position.set(450, getDatTreble / 120 - 100, zPosition); mesh1.rotation.y += 0.01; mesh2.rotation.y += 0.01; mesh3.rotation.y += 0.01; mesh4.rotation.y += 0.01; mesh5.rotation.y += 0.01; mesh6.rotation.y += 0.01; mesh7.rotation.y += 0.01; mesh8.rotation.y += 0.01; mesh9.rotation.y += 0.01; mesh10.rotation.y += 0.01; // mesh1.rotation.x += 0.01; // rotate about x to spin vertically /////////////////////// Animate Light ////////////////////// ambientLight.intensity = totalSum / 400000; // strobe effect? // pointLight.intensity = totalSum / 100000; if (context.reRender === true) { renderer.render(scene, camera); requestAnimationFrame(render); } } } }
the_stack
import _ from 'lodash'; import {BN, ChannelConstants, unreachable} from '@statechannels/wallet-core'; import {State} from '../models/channel/state'; import {SimpleAllocationOutcome} from '../models/channel/outcome'; import {RichLedgerRequest} from '../models/ledger-request'; interface ReadonlyChannel extends ChannelConstants { myIndex: number; latestTurnNum: number; uniqueStateAt(turn: number): State | undefined; } // Ledger Update algorithm: // ------------------------ // // Define the "leader" of the channel to be the first participant. // Let the other participant be the "follower". // // If both parties follow the protocol, the ledger exists in one of three possible states: // 1. Agreement (the latest state is double-signed) // 2. Proposal (latest states are: double-signed, leader-signed) // 3. Counter-proposal (latest states are: double-signed, leader-signed, follower-signed) // // If we ever find ourselves not in one of these states, declare a protocol violation and // exit the channel. // // The leader acts as follows: // * In Agreement, the leader takes all of their queued updates, formulates them into a new state // and sends it to the follower. The state is now Proposal // * In Proposal, does nothing // * In Counter-proposal, confirms that all the updates are in the queue, and double signs // The state is now Agreement. // // The follower acts as follows: // * In Agreement, does nothing // * In Proposal: // * If all updates are in the queue, double-signs. The state is now Agreement. // * Otherwise, removes the states that are not in queue and formulates new state. // The state is now Counter-proposal // * In Counter-proposal, does nothing // // // Managing the request queue: // --------------------------- // // Requests can exist in one of 6 states: // 1. queued - when waiting to go into a proposal // 2. pending - request included in current proposal/counter-proposal signed by us // (☝️ these two states are considered 'active') // 3. success - [terminal] when included in an agreed state // 4. cancelled - [terminal] if a defund is sent before the fund was included in the ledger // 5. insufficient-funds - [terminal] if there aren't enough funds in the ledger // 6. inconsistent - [terminal] requested channel is in the ledger but with a different amount // 7. failed - [terminal] if the ledger ends due to a closure or a protocol exception // // ┌────────────────────────┐ // │ v // queued <---> pending ---> success failed [from any state] // │ // ├──────────────────┐──────────────────────┐ // v v v // cancelled insufficient-funds inconsistent // // Requests also maintain a missedOpportunityCount and a lastAgreedStateSeen. // // The missedOpportunityCount tracks how many agreed states the request has failed to be // included in. Objectives can use this to determine whether a request has stalled (e.g. if // their counterparty isn't processing the objective anymore). // // The lastAgreedStateSeen is a piece of book-keeping to so that the LedgerManager can // accurately update the missedOpportunityCount. // export class LedgerProtocol { /** * * @param ledger Channel model **not mutated during cranking* * @param requests LedgerRequest model **to be mutated during cranking* * @returns states to sign for ledger channel */ crank(ledger: ReadonlyChannel, requests: RichLedgerRequest[]): State[] { // determine which state we're in const ledgerState = this.determineLedgerState(ledger); // what happens next depends on whether we're the leader or follower const amLeader = ledger.myIndex === 0; let statesToSign: State[]; switch (ledgerState.type) { case 'agreement': // could be in agreement through (1) follower accepting proposal, (2) leader accepting // counter-proposal, and having an empty queue. So both participants could be seeing // the agreedState for the first time statesToSign = amLeader ? this.crankAsLeaderInAgreement(ledgerState, requests) : this.crankAsFollowerInAgreement(ledgerState, requests); break; case 'proposal': // if leader, we must have created proposal, so no further action to take statesToSign = amLeader ? [] : this.crankAsFollowerInProposal(ledgerState, requests); break; case 'counter-proposal': // if follower, we must have created counter-proposal, so no further action to take statesToSign = amLeader ? this.crankAsLeaderInCounterProposal(ledgerState, requests) : []; break; case 'protocol-violation': throw new Error('protocol violation'); default: unreachable(ledgerState); } return statesToSign; } private crankAsLeaderInAgreement(ledgerState: Agreement, requests: RichLedgerRequest[]): State[] { const {agreed} = ledgerState; const statesToSign = []; this.processAgreedState(agreed, requests); if (_.some(requests, r => r.isQueued)) { const proposedOutcome = this.buildOutcome( agreed, requests.filter(r => r.isQueued) ); const proposed = agreed.advanceToOutcome(proposedOutcome); // need to check that we actually have a new outcome, as it could be that there wasn't // sufficient funding for any of the requests if (!proposedOutcome.isEqualTo(agreed.simpleAllocationOutcome)) { this.markIncludedRequestsAsPending(requests, proposed); statesToSign.push(proposed); } } return statesToSign; } private crankAsFollowerInAgreement( ledgerState: Agreement, requests: RichLedgerRequest[] ): State[] { // nothing to do here apart from update the requests according to the agreed state this.processAgreedState(ledgerState.agreed, requests); return []; } private crankAsLeaderInCounterProposal( ledgerState: CounterProposal, requests: RichLedgerRequest[] ): State[] { const {agreed, counterProposed} = ledgerState; const result = this.compareChangesWithRequests(requests, agreed, counterProposed); // if the follower is following the protocol, we should always agree with their counterProposal if (result.type !== 'full-agreement') throw new Error('protocol error'); // if so, sign their state const stateToSign = counterProposed; // and proceed as if we're in the AgreementState const otherStatesToSign = this.crankAsLeaderInAgreement( {type: 'agreement', agreed: counterProposed}, requests ); return [stateToSign, ...otherStatesToSign]; } private crankAsFollowerInProposal(ledgerState: Proposal, requests: RichLedgerRequest[]): State[] { const statesToSign = []; const {agreed, proposed} = ledgerState; this.processAgreedState(agreed, requests); const result = this.compareChangesWithRequests(requests, agreed, proposed); switch (result.type) { case 'full-agreement': statesToSign.push(proposed); this.processAgreedState(proposed, requests); break; case 'some-overlap': case 'no-overlap': { // in both cases we're going to make a counter-proposal either to return to the // original state, or to go to a state containing the overlap const counterProposed = proposed.advanceToOutcome(result.narrowedOutcome); statesToSign.push(counterProposed); this.markIncludedRequestsAsPending(requests, counterProposed); break; } default: unreachable(result); } return statesToSign; } private processAgreedState(agreedState: State, requests: RichLedgerRequest[]): void { // identify potential cancellations (defunds for which the fund is still queued or pending) const {cancellationDefunds, nonCancellations} = this.identifyPotentialCancellations(requests); // we exclude potential cancellation defunds when judging the success, otherwise a defund // where the fund isn't yet included would be marked a success this.markSuccessesAndInconsistencies(nonCancellations, agreedState); // in the case where we're the leader and we just approved a counterProposal, there will // be some pending requests that weren't included. Reset those now. this.resetPendingRequestsToQueued(requests); // cancel any pairs of matching funds/defunds that still both queued const nonApplicableCancellations = this.applyCancellations( cancellationDefunds, requests, agreedState.turnNum ); // it's possible that the matching fund was marked as inconsistent above, which means // we now need to assess if the defund is consistent // (this would happen if we had duplicate funds for the same channel. We have a db constraint // to protect against this, but that only works if we never garbage collect or lose the db) this.markSuccessesAndInconsistencies(nonApplicableCancellations, agreedState); this.updateStateSeenAndMissedOps(requests, agreedState.turnNum); } private markSuccessesAndInconsistencies(requests: RichLedgerRequest[], agreedState: State): void { const agreedOutcome = agreedState.simpleAllocationOutcome; if (!agreedOutcome) throw Error("Ledger state doesn't have a simple allocation outcome"); const [fundings, defundings] = _.partition(requests, r => r.isFund); // for defundings, one of three things is true: // 1. the channel doesn't appear => defunding successful // 2. the channel appears but with a different amount => inconsistent // 3. the channel appears with the same amount => no change for (const defund of defundings) { const matches = agreedOutcome.destinations.filter(d => d === defund.channelToBeFunded); if (matches.length > 1) { throw new Error(`Duplicate entries for destination`); } else if (matches.length === 0) { defund.status = 'succeeded'; defund.lastSeenAgreedState = agreedState.turnNum; } else { const outcomeBal = agreedOutcome.balanceFor(defund.channelToBeFunded); const amountsMatch = outcomeBal && BN.eq(outcomeBal, defund.totalAmount); if (!amountsMatch) { defund.status = 'inconsistent'; defund.lastSeenAgreedState = agreedState.turnNum; } } } // for fundings check which are present, and then check that the totals match const includedFundings = _.intersectionWith( fundings, agreedOutcome.destinations, (fund, dest) => fund.channelToBeFunded === dest ); includedFundings.forEach(f => { const outcomeBal = agreedOutcome.balanceFor(f.channelToBeFunded); const amountsMatch = outcomeBal && BN.eq(outcomeBal, f.totalAmount); f.status = amountsMatch ? 'succeeded' : 'inconsistent'; f.lastSeenAgreedState = agreedState.turnNum; }); } private updateStateSeenAndMissedOps(requests: RichLedgerRequest[], turnNum: number) { requests .filter(r => r.isQueued) .forEach(r => { if (r.lastSeenAgreedState !== turnNum) { if (r.lastSeenAgreedState) r.missedOpportunityCount = 1 + r.missedOpportunityCount; r.lastSeenAgreedState = turnNum; } }); } private resetPendingRequestsToQueued(requests: RichLedgerRequest[]) { requests.filter(r => r.isPending).forEach(r => (r.status = 'queued')); } private markIncludedRequestsAsPending(requests: RichLedgerRequest[], proposed: State): void { const proposedOutcome = proposed.simpleAllocationOutcome; if (!proposedOutcome) throw Error("Ledger state doesn't have a simple allocation outcome"); const [fundings, defundings] = _.partition( requests.filter(r => r.isQueued), r => r.isFund ); // for defundings, mark any the aren't present as successful const missingDefundings = _.differenceWith( defundings, proposedOutcome.destinations, (defund, dest) => defund.channelToBeFunded === dest ); missingDefundings.forEach(d => (d.status = 'pending')); // for fundings check which are present, and then check that the totals match const includedFundings = _.intersectionWith( fundings, proposedOutcome.destinations, (fund, dest) => fund.channelToBeFunded === dest ); includedFundings.forEach(f => { const outcomeBal = proposedOutcome.balanceFor(f.channelToBeFunded); const amountsMatch = outcomeBal && BN.eq(outcomeBal, f.totalAmount); // amounts sould always match, as proposedOutcome is always called with a state we constructed if (!amountsMatch) throw new Error("amounts don't match"); f.status = 'pending'; }); } private identifyPotentialCancellations( requests: RichLedgerRequest[] ): {cancellationDefunds: RichLedgerRequest[]; nonCancellations: RichLedgerRequest[]} { const [fundings, defundings] = _.partition(requests, r => r.isFund); const cancellationDefunds = _.intersectionWith( defundings, fundings, (x, y) => x.channelToBeFunded === y.channelToBeFunded ); const nonCancellations = _.difference(requests, cancellationDefunds); // sanity check: cancellationDefunds should always be queued for (const d of cancellationDefunds) { if (!d.isQueued) throw new Error(`cancellation defund is not in queued state: ${d.$id}`); } return {cancellationDefunds, nonCancellations}; } // find the corresponding fund for each defund and cancel it if it's in the queued state // returns the cancellations that can't be applied (becuase their parnter has already been confirmed) private applyCancellations( cancellations: RichLedgerRequest[], requests: RichLedgerRequest[], turnNum: number ): RichLedgerRequest[] { const nonApplicableCancellations = []; for (const defund of cancellations) { const fund = requests.find(r => r.isFund && r.channelToBeFunded === defund.channelToBeFunded); if (fund && fund.isQueued) { fund.status = 'cancelled'; fund.lastSeenAgreedState = turnNum; defund.status = 'cancelled'; defund.lastSeenAgreedState = turnNum; } else { nonApplicableCancellations.push(defund); } } return nonApplicableCancellations; } // compareChangesWithRequest // - fullAgreement => agree on channels and outcome // - someoverlap, narrowedOutcome => have removed // - noOverlap private compareChangesWithRequests( requests: RichLedgerRequest[], baselineState: State, candidateState: State ): CompareChangesWithRequestsResult { const baselineOutcome = baselineState.simpleAllocationOutcome; const candidateOutcome = candidateState.simpleAllocationOutcome; if (!baselineOutcome || !candidateOutcome) throw Error("Ledger state doesn't have simple allocation outcome"); const changedDestinations = _.xor(baselineOutcome.destinations, candidateOutcome.destinations); if (changedDestinations.length === 0) return {type: 'full-agreement'}; // we don't want to mistakenly think that defund cancellations are included in the state, so // we need to exclude them in what follows const {nonCancellations} = this.identifyPotentialCancellations(requests); // identify which changes from the proposal are also in our list of requests const overlappingRequests = nonCancellations.filter(req => changedDestinations.includes(req.channelToBeFunded) ); if (overlappingRequests.length === 0) return {type: 'no-overlap', narrowedOutcome: baselineOutcome}; // build the outcome const calculatedOutcome = this.buildOutcome(baselineState, overlappingRequests); if (overlappingRequests.length === changedDestinations.length) { // we've have full overlap if (candidateOutcome.isEqualTo(calculatedOutcome)) { // all agree. happy days. return {type: 'full-agreement'}; } else { // uh oh. We agree on the requests but not the outcome. Coding error alert throw new Error('Outcomes inconsistent'); } } else { return {type: 'some-overlap', narrowedOutcome: calculatedOutcome}; } } private determineLedgerState(ledger: ReadonlyChannel): LedgerState { const [leader, follower] = ledger.participants.map(p => p.signingAddress); const latestTurnNum = ledger.latestTurnNum; const latestState = ledger.uniqueStateAt(latestTurnNum); if (!latestState) return {type: 'protocol-violation'}; if (latestState.fullySigned) { return {type: 'agreement', agreed: latestState}; } const penultimateState = ledger.uniqueStateAt(latestTurnNum - 1); if (!penultimateState) return {type: 'protocol-violation'}; if (penultimateState.fullySigned) { if (latestState.signedBy(leader)) { return {type: 'proposal', proposed: latestState, agreed: penultimateState}; } else { return {type: 'protocol-violation'}; } } const antepenultimateState = ledger.uniqueStateAt(latestTurnNum - 2); if (!antepenultimateState) return {type: 'protocol-violation'}; if ( antepenultimateState.fullySigned && penultimateState.signedBy(leader) && latestState.signedBy(follower) ) { return { type: 'counter-proposal', counterProposed: latestState, proposed: penultimateState, agreed: antepenultimateState, }; } else { return {type: 'protocol-violation'}; } } private buildOutcome(state: State, requests: RichLedgerRequest[]): SimpleAllocationOutcome { if (!state.simpleAllocationOutcome) throw Error("Ledger doesn't have simple allocation outcome"); let currentOutcome = state.simpleAllocationOutcome.dup(); // we should do any defunds first for (const defundReq of requests.filter(r => r.isDefund)) { const updatedOutcome = currentOutcome.remove( defundReq.channelToBeFunded, state.participantDestinations, [defundReq.amountA, defundReq.amountB] ); if (updatedOutcome) { currentOutcome = updatedOutcome; } else { // the only way removal fails is if the refund amounts don't match the amount in the channel // in that case the request is not viable and should be marked as inconsistent defundReq.status = 'inconsistent'; } } // then we should do any fundings // NOTE: new requests MUST be appended in lexographical order by channelId // this isn't strictly necessary, but removes any ambiguity about the format of the state for (const fundingReq of _.sortBy( requests.filter(r => r.isFund), 'channelToBeFunded' )) { const updatedOutcome = currentOutcome.add( fundingReq.channelToBeFunded, state.participantDestinations, [fundingReq.amountA, fundingReq.amountB] ); if (updatedOutcome) { currentOutcome = updatedOutcome; } else { // if funding failed, it means that there aren't enough funds left in the channel // so mark the request as failed // TODO: do we actually want to do this here? fundingReq.status = 'insufficient-funds'; } } return currentOutcome; } } // LedgerState // =========== type LedgerState = Agreement | Proposal | CounterProposal | ProtocolViolation; type Agreement = {type: 'agreement'; agreed: State}; type Proposal = {type: 'proposal'; agreed: State; proposed: State}; type CounterProposal = { type: 'counter-proposal'; counterProposed: State; proposed: State; agreed: State; }; type ProtocolViolation = {type: 'protocol-violation'}; // CompareChangesWithRequestsResult // ================================ type CompareChangesWithRequestsResult = FullAgreement | SomeOverlap | NoOverlap; type FullAgreement = {type: 'full-agreement'}; type SomeOverlap = {type: 'some-overlap'; narrowedOutcome: SimpleAllocationOutcome}; type NoOverlap = {type: 'no-overlap'; narrowedOutcome: SimpleAllocationOutcome};
the_stack
import { buildWebpackBrowser } from '../../index'; import { BASE_OPTIONS, BROWSER_BUILDER_INFO, describeBuilder } from '../setup'; describeBuilder(buildWebpackBrowser, BROWSER_BUILDER_INFO, (harness) => { describe('Option: "scripts"', () => { beforeEach(async () => { // Application code is not needed for scripts tests await harness.writeFile('src/main.ts', ''); }); it('supports an empty array value', async () => { harness.useTarget('build', { ...BASE_OPTIONS, scripts: [], }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); }); describe('shorthand syntax', () => { it('processes a single script into a single output', async () => { await harness.writeFile('src/test-script-a.js', 'console.log("a");'); harness.useTarget('build', { ...BASE_OPTIONS, scripts: ['src/test-script-a.js'], }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/scripts.js').content.toContain('console.log("a")'); harness .expectFile('dist/index.html') .content.toContain('<script src="scripts.js" defer></script>'); }); it('processes multiple scripts into a single output', async () => { await harness.writeFile('src/test-script-a.js', 'console.log("a");'); await harness.writeFile('src/test-script-b.js', 'console.log("b");'); harness.useTarget('build', { ...BASE_OPTIONS, scripts: ['src/test-script-a.js', 'src/test-script-b.js'], }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/scripts.js').content.toContain('console.log("a")'); harness.expectFile('dist/scripts.js').content.toContain('console.log("b")'); harness .expectFile('dist/index.html') .content.toContain('<script src="scripts.js" defer></script>'); }); it('preserves order of multiple scripts in single output', async () => { await harness.writeFile('src/test-script-a.js', 'console.log("a");'); await harness.writeFile('src/test-script-b.js', 'console.log("b");'); await harness.writeFile('src/test-script-c.js', 'console.log("c");'); await harness.writeFile('src/test-script-d.js', 'console.log("d");'); harness.useTarget('build', { ...BASE_OPTIONS, scripts: [ 'src/test-script-c.js', 'src/test-script-d.js', 'src/test-script-b.js', 'src/test-script-a.js', ], }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness .expectFile('dist/scripts.js') .content.toMatch( /console\.log\("c"\)[;\s]+console\.log\("d"\)[;\s]+console\.log\("b"\)[;\s]+console\.log\("a"\)/, ); }); it('throws an exception if script does not exist', async () => { harness.useTarget('build', { ...BASE_OPTIONS, scripts: ['src/test-script-a.js'], }); const { result, error } = await harness.executeOnce({ outputLogsOnException: false }); expect(result).toBeUndefined(); expect(error).toEqual( jasmine.objectContaining({ message: jasmine.stringMatching(`Script file src/test-script-a.js does not exist.`), }), ); harness.expectFile('dist/scripts.js').toNotExist(); }); it('shows the output script as a chunk entry in the logging output', async () => { await harness.writeFile('src/test-script-a.js', 'console.log("a");'); harness.useTarget('build', { ...BASE_OPTIONS, scripts: ['src/test-script-a.js'], }); const { result, logs } = await harness.executeOnce(); expect(result?.success).toBe(true); expect(logs).toContain( jasmine.objectContaining({ message: jasmine.stringMatching(/scripts\.js.+\d+ bytes/) }), ); }); }); describe('longhand syntax', () => { it('processes a single script into a single output', async () => { await harness.writeFile('src/test-script-a.js', 'console.log("a");'); harness.useTarget('build', { ...BASE_OPTIONS, scripts: [{ input: 'src/test-script-a.js' }], }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/scripts.js').content.toContain('console.log("a")'); harness .expectFile('dist/index.html') .content.toContain('<script src="scripts.js" defer></script>'); }); it('processes a single script into a single output named with bundleName', async () => { await harness.writeFile('src/test-script-a.js', 'console.log("a");'); harness.useTarget('build', { ...BASE_OPTIONS, scripts: [{ input: 'src/test-script-a.js', bundleName: 'extra' }], }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/extra.js').content.toContain('console.log("a")'); harness .expectFile('dist/index.html') .content.toContain('<script src="extra.js" defer></script>'); }); it('uses default bundleName when bundleName is empty string', async () => { await harness.writeFile('src/test-script-a.js', 'console.log("a");'); harness.useTarget('build', { ...BASE_OPTIONS, scripts: [{ input: 'src/test-script-a.js', bundleName: '' }], }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/scripts.js').content.toContain('console.log("a")'); harness .expectFile('dist/index.html') .content.toContain('<script src="scripts.js" defer></script>'); }); it('processes multiple scripts with no bundleName into a single output', async () => { await harness.writeFiles({ 'src/test-script-a.js': 'console.log("a");', 'src/test-script-b.js': 'console.log("b");', }); harness.useTarget('build', { ...BASE_OPTIONS, scripts: [{ input: 'src/test-script-a.js' }, { input: 'src/test-script-b.js' }], }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/scripts.js').content.toContain('console.log("a")'); harness.expectFile('dist/scripts.js').content.toContain('console.log("b")'); harness .expectFile('dist/index.html') .content.toContain('<script src="scripts.js" defer></script>'); }); it('processes multiple scripts with same bundleName into a single output', async () => { await harness.writeFiles({ 'src/test-script-a.js': 'console.log("a");', 'src/test-script-b.js': 'console.log("b");', }); harness.useTarget('build', { ...BASE_OPTIONS, scripts: [ { input: 'src/test-script-a.js', bundleName: 'extra' }, { input: 'src/test-script-b.js', bundleName: 'extra' }, ], }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/extra.js').content.toContain('console.log("a")'); harness.expectFile('dist/extra.js').content.toContain('console.log("b")'); harness .expectFile('dist/index.html') .content.toContain('<script src="extra.js" defer></script>'); }); it('processes multiple scripts with different bundleNames into separate outputs', async () => { await harness.writeFiles({ 'src/test-script-a.js': 'console.log("a");', 'src/test-script-b.js': 'console.log("b");', }); harness.useTarget('build', { ...BASE_OPTIONS, scripts: [ { input: 'src/test-script-a.js', bundleName: 'extra' }, { input: 'src/test-script-b.js', bundleName: 'other' }, ], }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/extra.js').content.toContain('console.log("a")'); harness.expectFile('dist/other.js').content.toContain('console.log("b")'); harness .expectFile('dist/index.html') .content.toContain('<script src="extra.js" defer></script>'); harness .expectFile('dist/index.html') .content.toContain('<script src="other.js" defer></script>'); }); it('preserves order of multiple scripts in single output', async () => { await harness.writeFiles({ 'src/test-script-a.js': 'console.log("a");', 'src/test-script-b.js': 'console.log("b");', 'src/test-script-c.js': 'console.log("c");', 'src/test-script-d.js': 'console.log("d");', }); harness.useTarget('build', { ...BASE_OPTIONS, scripts: [ { input: 'src/test-script-c.js' }, { input: 'src/test-script-d.js' }, { input: 'src/test-script-b.js' }, { input: 'src/test-script-a.js' }, ], }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness .expectFile('dist/scripts.js') .content.toMatch( /console\.log\("c"\)[;\s]+console\.log\("d"\)[;\s]+console\.log\("b"\)[;\s]+console\.log\("a"\)/, ); }); it('preserves order of multiple scripts with different bundleNames', async () => { await harness.writeFiles({ 'src/test-script-a.js': 'console.log("a");', 'src/test-script-b.js': 'console.log("b");', 'src/test-script-c.js': 'console.log("c");', 'src/test-script-d.js': 'console.log("d");', }); harness.useTarget('build', { ...BASE_OPTIONS, scripts: [ { input: 'src/test-script-c.js', bundleName: 'other' }, { input: 'src/test-script-d.js', bundleName: 'extra' }, { input: 'src/test-script-b.js', bundleName: 'extra' }, { input: 'src/test-script-a.js', bundleName: 'other' }, ], }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness .expectFile('dist/other.js') .content.toMatch(/console\.log\("c"\)[;\s]+console\.log\("a"\)/); harness .expectFile('dist/extra.js') .content.toMatch(/console\.log\("d"\)[;\s]+console\.log\("b"\)/); harness .expectFile('dist/index.html') .content.toMatch( /<script src="other.js" defer><\/script>\s*<script src="extra.js" defer><\/script>/, ); }); it('adds script element to index when inject is true', async () => { await harness.writeFile('src/test-script-a.js', 'console.log("a");'); harness.useTarget('build', { ...BASE_OPTIONS, scripts: [{ input: 'src/test-script-a.js', inject: true }], }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/scripts.js').content.toContain('console.log("a")'); harness .expectFile('dist/index.html') .content.toContain('<script src="scripts.js" defer></script>'); }); it('does not add script element to index when inject is false', async () => { await harness.writeFile('src/test-script-a.js', 'console.log("a");'); harness.useTarget('build', { ...BASE_OPTIONS, scripts: [{ input: 'src/test-script-a.js', inject: false }], }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); // `inject: false` causes the bundleName to be the input file name harness.expectFile('dist/test-script-a.js').content.toContain('console.log("a")'); harness .expectFile('dist/index.html') .content.not.toContain('<script src="test-script-a.js" defer></script>'); }); it('does not add script element to index with bundleName when inject is false', async () => { await harness.writeFile('src/test-script-a.js', 'console.log("a");'); harness.useTarget('build', { ...BASE_OPTIONS, scripts: [{ input: 'src/test-script-a.js', bundleName: 'extra', inject: false }], }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/extra.js').content.toContain('console.log("a")'); harness .expectFile('dist/index.html') .content.not.toContain('<script src="extra.js" defer></script>'); }); it('shows the output script as a chunk entry in the logging output', async () => { await harness.writeFile('src/test-script-a.js', 'console.log("a");'); harness.useTarget('build', { ...BASE_OPTIONS, scripts: [{ input: 'src/test-script-a.js' }], }); const { result, logs } = await harness.executeOnce(); expect(result?.success).toBe(true); expect(logs).toContain( jasmine.objectContaining({ message: jasmine.stringMatching(/scripts\.js.+\d+ bytes/) }), ); }); it('shows the output script as a chunk entry with bundleName in the logging output', async () => { await harness.writeFile('src/test-script-a.js', 'console.log("a");'); harness.useTarget('build', { ...BASE_OPTIONS, scripts: [{ input: 'src/test-script-a.js', bundleName: 'extra' }], }); const { result, logs } = await harness.executeOnce(); expect(result?.success).toBe(true); expect(logs).toContain( jasmine.objectContaining({ message: jasmine.stringMatching(/extra\.js.+\d+ bytes/) }), ); }); }); }); });
the_stack
import { // Number Type IAbsoluteValue, INumber, // Custom Array Type IAllDeadPlayers, IAllLivingPlayers, IAllPlayers, IAllPlayersNotOnObjective, IAllPlayersOnObjective, IAllowedHeroes, IAllHeroes, IArccosineInDegrees, IArccosineInRadians, IArcsineInDegrees, IArcsineInRadians, IArctangentInDegrees, IArctangentInRadians, IAppendToArray, IArrayContains, IArraySlice, // Method Type IAltitudeOf, ILocalVectorOf, IWorldVectorOf, IVectorTowards, IAngleBetweenVectors, IAngleDifference, // Class Type IVector, IAttacker, // Operator Type IAnd, // Variable Type IGlobalVariable, IPlayerVariable, // Unclassified IClosestPlayerTo, ICompare, IControlModeScoringPercentage, IControlModeScoringTeam, ICosineFromDegrees, ICosineFromRadians, ICountOf, ICrossProduct, ICurrentArrayElement, IDirectionFromAngles, IDirectionTowards, IDistanceBetween, IDotProduct, IEmptyArray, IEntityExists, IEventDamage, IEventPlayer, IBackward, ITeam, IDown, IEventWasCriticalHit, IEyePosition, IFacingDirectionOf, IFalse, IFarthestPlayerFrom, IFilteredArray, IFirstOf, IFlagPosition, IForward, IHasSpawned, IHasStatus, IHealth, IHero, IHeroIconString, IHeroOf, IHorizontalAngleFromDirection, IHorizontalAngleTowards, IHorizontalFacingAngleOf, IHorizontalSpeedOf, IIndexOfArrayValue, IIsAlive, IIsAssemblingHeroes, IIsBetweenRounds, IIsButtonHeld, IIsCommunicating, IIsCommunicatingAny, IIsCommunicatingAnyEmote, IIsCommunicatingAnyVoiceLine, IIsControlModePointLocked, IIsCrouching, IIsCTFModeInSuddenDeath, IIsDead, IIsFiringPrimary, IIsFlagAtBase, IIsFlagBeingCarried, IIsGameInProgress, IIsHeroBeingPlayed, IIsInAir, IIsInLineOfSight, IIsInSetup, IIsInSpawnRoom, IIsInViewAngle, IIsMatchComplete, IIsMoving, IIsObjectiveComplete, IIsOnGround, IIsOnObjective, IIsOnWall, IIsPortraitOnFire, IIsStanding, IIsTeamOnDefense, IIsFiringSecondary, IIsTeamOnOffense, IIsTrueForAll, IIsTrueForAny, IIsUsingAbility1, IIsUsingAbility2, IIsUsingUltimate, IIsWaitingForPlayers, ILastCreatedEntity, ILastDamageModificationId, ILastDamageOverTimeId, ILastHealOverTimeId, ILastOf, ILastTextId, ILeft, IMatchRound, IMatchTime, IMax, IMaxHealth, IMin, IModulo, INearestWalkablePosition, INormalize, INormalizedHealth, INot, INull, INumberOfDeadPlayers, INumberOfDeaths, INumberOfEliminations, INumberOfFinalBlows, INumberOfHeroes, INumberOfLivingPlayers, INumberOfPlayers, INumberOfPlayersOnObjective, IObjectiveIndex, IObjectivePosition, IOppositeTeamOf, IOr, IPayloadPosition, IPayloadProgressPercentage, IPlayerCarryingFlag, IPlayerClosestToReticle, IPlayersInSlot, IPlayersInViewAngle, IPlayersOnHero, IPlayersWithinRadius, IPointCapturePercentage, IPositionOf, IRaiseToPower, IRandomInteger, IRandomReal, IRandomValueInArray, IRandomizedArray, IRayCastHitNormal, IRayCastHitPlayer, IRayCastHitPosition, IRemoveFromArray, IRight, IRoundToInteger, IScoreOf, ISineFromDegrees, ISineFromRadians, ISlotOf, ISortedArray, ISpeedOf, ISpeedOfInDirection, ISquareRoot, IString, ISubtract, IAdd, IDivide, IMultiply, ITangentFromDegrees, ITangentFromRadians, ITeamOf, ITeamScore, IThrottleOf, ITotalTimeElapsed, ITrue, IUltimateChargePercent, IUp, IValueInArray, IVelocityOf, IVerticalAngleFromDirection, IVerticalAngleTowards, IVerticalFacingAngleOf, IVerticalSpeedOf, IVictim, IXComponentOf, IYComponentOf, IZComponentOf, IServerLoad, IServerLoadAverage, IServerLoadPeak, IHealer, IHealee, IEventHealing, IHostPlayer, IIsDummyBot, } from './child' export interface IValue { /** * {342} */ absoluteValue: IAbsoluteValue /** * {343} */ add: IAdd /** * {344} */ allDeadPlayers: IAllDeadPlayers /** * {345} */ allHeroes: IAllHeroes /** * {346} */ allLivingPlayers: IAllLivingPlayers /** * {347} */ allPlayers: IAllPlayers /** * {348} */ allPlayersNotOnObjective: IAllPlayersNotOnObjective /** * {349} */ allPlayersOnObjective: IAllPlayersOnObjective /** * {350} */ allowedHeroes: IAllowedHeroes /** * {351} */ altitudeOf: IAltitudeOf /** * {352} */ and: IAnd /** * {353} */ angleBetweenVectors: IAngleBetweenVectors /** * {354} */ angleDifference: IAngleDifference /** * {355} */ appendToArray: IAppendToArray /** * {356} */ arccosineInDegrees: IArccosineInDegrees /** * {357} */ arccosineInRadians: IArccosineInRadians /** * {358} */ arcsineInDegrees: IArcsineInDegrees /** * {359} */ arcsineInRadians: IArcsineInRadians /** * {360} */ arctangentInDegrees: IArctangentInDegrees /** * {361} */ arctangentInRadians: IArctangentInRadians /** * {362} */ arrayContains: IArrayContains /** * {363} */ arraySlice: IArraySlice /** * {364} */ attacker: IAttacker /** * {365} */ backward: IBackward /** * {366} */ closestPlayerTo: IClosestPlayerTo /** * {367} */ compare: ICompare /** * {368} */ controlModeScoringPercentage: IControlModeScoringPercentage /** * {369} */ controlModeScoringTeam: IControlModeScoringTeam /** * {370} */ cosineFromDegrees: ICosineFromDegrees /** * {371} */ cosineFromRadians: ICosineFromRadians /** * {372} */ countOf: ICountOf /** * {373} */ crossProduct: ICrossProduct /** * {374} */ currentArrayElement: ICurrentArrayElement /** * {375} */ directionFromAngles: IDirectionFromAngles /** * {376} */ directionTowards: IDirectionTowards /** * {377} */ distanceBetween: IDistanceBetween /** * {378} */ divide: IDivide /** * {379} */ dotProduct: IDotProduct /** * {380} */ down: IDown /** * {381} */ emptyArray: IEmptyArray /** * {382} */ entityExists: IEntityExists /** * {383} */ eventDamage: IEventDamage /** * {384} */ eventPlayer: IEventPlayer /** * {385} */ eventWasCriticalHit: IEventWasCriticalHit /** * {386} */ eyePosition: IEyePosition /** * {387} */ facingDirectionOf: IFacingDirectionOf /** * {388} */ false: IFalse /** * {389} */ farthestPlayerFrom: IFarthestPlayerFrom /** * {390} */ filteredArray: IFilteredArray /** * {391} */ firstOf: IFirstOf /** * {392} */ flagPosition: IFlagPosition /** * {393} */ forward: IForward /** * {394} */ globalVariable: IGlobalVariable /** * {395} */ hasSpawned: IHasSpawned /** * {396} */ hasStatus: IHasStatus /** * {397} */ health: IHealth /** * {398} */ hero: IHero /** * {399} */ heroIconString: IHeroIconString /** * {400} */ heroOf: IHeroOf /** * {401} */ horizontalAngleFromDirection: IHorizontalAngleFromDirection /** * {402} */ horizontalAngleTowards: IHorizontalAngleTowards /** * {403} */ horizontalFacingAngleOf: IHorizontalFacingAngleOf /** * {404} */ horizontalSpeedOf: IHorizontalSpeedOf /** * {405} */ indexOfArrayValue: IIndexOfArrayValue /** * {406} */ isAlive: IIsAlive /** * {407} */ isAssemblingHeroes: IIsAssemblingHeroes /** * {408} */ isBetweenRounds: IIsBetweenRounds /** * {409} */ isButtonHeld: IIsButtonHeld /** * {410} */ isCommunicating: IIsCommunicating /** * {411} */ isCommunicatingAny: IIsCommunicatingAny /** * {412} */ isCommunicatingAnyEmote: IIsCommunicatingAnyEmote /** * {413} */ isCommunicatingAnyVoiceLine: IIsCommunicatingAnyVoiceLine /** * {414} */ isControlModePointLocked: IIsControlModePointLocked /** * {415} */ isCrouching: IIsCrouching /** * {416} */ isCTFModeInSuddenDeath: IIsCTFModeInSuddenDeath /** * {417} */ isDead: IIsDead /** * {418} */ isFiringPrimary: IIsFiringPrimary /** * {419} */ isFiringSecondary: IIsFiringSecondary /** * {420} */ isFlagAtBase: IIsFlagAtBase /** * {421} */ isFlagBeingCarried: IIsFlagBeingCarried /** * {422} */ isGameInProgress: IIsGameInProgress /** * {423} */ isHeroBeingPlayed: IIsHeroBeingPlayed /** * {424} */ isInAir: IIsInAir /** * {425} */ isInLineOfSight: IIsInLineOfSight /** * {426} */ isInSetup: IIsInSetup /** * {427} */ isInSpawnRoom: IIsInSpawnRoom /** * {428} */ isInViewAngle: IIsInViewAngle /** * {429} */ isMatchComplete: IIsMatchComplete /** * {430} */ isMoving: IIsMoving /** * {431} */ isObjectiveComplete: IIsObjectiveComplete /** * {432} */ isOnGround: IIsOnGround /** * {433} */ isOnObjective: IIsOnObjective /** * {434} */ isOnWall: IIsOnWall /** * {435} */ isPortraitOnFire: IIsPortraitOnFire /** * {436} */ isStanding: IIsStanding /** * {437} */ isTeamOnDefense: IIsTeamOnDefense /** * {438} */ isTeamOnOffense: IIsTeamOnOffense /** * {439} */ isTrueForAll: IIsTrueForAll /** * {440} */ isTrueForAny: IIsTrueForAny /** * {441} */ isUsingAbility1: IIsUsingAbility1 /** * {442} */ isUsingAbility2: IIsUsingAbility2 /** * {443} */ isUsingUltimate: IIsUsingUltimate /** * {444} */ isWaitingForPlayers: IIsWaitingForPlayers /** * {445} */ lastCreatedEntity: ILastCreatedEntity /** * {446} */ lastDamageModificationId: ILastDamageModificationId /** * {447} */ lastDamageOverTimeId: ILastDamageOverTimeId /** * {448} */ lastHealOverTimeId: ILastHealOverTimeId /** * {449} */ lastOf: ILastOf /** * {450} */ lastTextId: ILastTextId /** * {451} */ left: ILeft /** * {452} */ localVectorOf: ILocalVectorOf /** * {453} */ matchRound: IMatchRound /** * {454} */ matchTime: IMatchTime /** * {455} */ max: IMax /** * {456} */ maxHealth: IMaxHealth /** * {457} */ min: IMin /** * {458} */ modulo: IModulo /** * {459} */ multiply: IMultiply /** * {460} */ nearestWalkablePosition: INearestWalkablePosition /** * {461} */ normalize: INormalize /** * {462} */ normalizedHealth: INormalizedHealth /** * {463} */ not: INot /** * {464} */ null: INull /** * {465} */ number: INumber /** * {466} */ numberOfDeadPlayers: INumberOfDeadPlayers /** * {467} */ numberOfDeaths: INumberOfDeaths /** * {468} */ numberOfEliminations: INumberOfEliminations /** * {469} */ numberOfFinalBlows: INumberOfFinalBlows /** * {470} */ numberOfHeroes: INumberOfHeroes /** * {471} */ numberOfLivingPlayers: INumberOfLivingPlayers /** * {472} */ numberOfPlayers: INumberOfPlayers /** * {473} */ numberOfPlayersOnObjective: INumberOfPlayersOnObjective /** * {474} */ objectiveIndex: IObjectiveIndex /** * {475} */ objectivePosition: IObjectivePosition /** * {476} */ oppositeTeamOf: IOppositeTeamOf /** * {477} */ or: IOr /** * {478} */ payloadPosition: IPayloadPosition /** * {479} */ payloadProgressPercentage: IPayloadProgressPercentage /** * {480} */ playerCarryingFlag: IPlayerCarryingFlag /** * {481} */ playerClosestToReticle: IPlayerClosestToReticle /** * {482} */ playerVariable: IPlayerVariable /** * {483} */ playersInSlot: IPlayersInSlot /** * {484} */ playersInViewAngle: IPlayersInViewAngle /** * {485} */ playersOnHero: IPlayersOnHero /** * {486} */ playersWithinRadius: IPlayersWithinRadius /** * {487} */ pointCapturePercentage: IPointCapturePercentage /** * {488} */ positionOf: IPositionOf /** * {489} */ raiseToPower: IRaiseToPower /** * {490} */ randomInteger: IRandomInteger /** * {491} */ randomReal: IRandomReal /** * {492} */ randomValueInArray: IRandomValueInArray /** * {493} */ randomizedArray: IRandomizedArray /** * {494} */ rayCastHitNormal: IRayCastHitNormal /** * {495} */ rayCastHitPlayer: IRayCastHitPlayer /** * {496} */ rayCastHitPosition: IRayCastHitPosition /** * {497} */ removeFromArray: IRemoveFromArray /** * {498} */ right: IRight /** * {499} */ roundToInteger: IRoundToInteger /** * {500} */ scoreOf: IScoreOf /** * {501} */ serverLoad: IServerLoad /** * {502} */ serverLoadAverage: IServerLoadAverage /** * {503} */ serverLoadPeak: IServerLoadPeak /** * {504} */ sineFromDegrees: ISineFromDegrees /** * {505} */ sineFromRadians: ISineFromRadians /** * {506} */ slotOf: ISlotOf /** * {507} */ sortedArray: ISortedArray /** * {508} */ speedOf: ISpeedOf /** * {509} */ speedOfInDirection: ISpeedOfInDirection /** * {510} */ squareRoot: ISquareRoot /** * {511} */ string: IString /** * {512} */ subtract: ISubtract /** * {513} */ tangentFromDegrees: ITangentFromDegrees /** * {514} */ tangentFromRadians: ITangentFromRadians /** * {515} */ team: ITeam /** * {516} */ teamOf: ITeamOf /** * {517} */ teamScore: ITeamScore /** * {518} */ throttleOf: IThrottleOf /** * {519} */ totalTimeElapsed: ITotalTimeElapsed /** * {520} */ true: ITrue /** * {521} */ ultimateChargePercent: IUltimateChargePercent /** * {522} */ up: IUp /** * {523} */ valueInArray: IValueInArray /** * {524} */ vector: IVector /** * {525} */ vectorTowards: IVectorTowards /** * {526} */ velocityOf: IVelocityOf /** * {527} */ verticalAngleFromDirection: IVerticalAngleFromDirection /** * {528} */ verticalAngleTowards: IVerticalAngleTowards /** * {529} */ verticalFacingAngleOf: IVerticalFacingAngleOf /** * {530} */ verticalSpeedOf: IVerticalSpeedOf /** * {531} */ victim: IVictim /** * {532} */ worldVectorOf: IWorldVectorOf /** * {533} */ xComponentOf: IXComponentOf /** * {534} */ yComponentOf: IYComponentOf /** * {535} */ zComponentOf: IZComponentOf /** * {724} */ healer: IHealer /** * {725} */ healee: IHealee /** * {726} */ eventHealing: IEventHealing /** * {727} */ hostPlayer: IHostPlayer /** * {754} */ isDummyBot: IIsDummyBot }
the_stack
import React, { FC, useCallback, useContext, useEffect, useMemo, useRef, useState, } from 'react' import { ApolloError, useMutation } from '@apollo/client' import { Application, Answer, ExternalData, FormItemTypes, FormModes, FormValue, Schema, formatText, mergeAnswers, BeforeSubmitCallback, } from '@island.is/application/core' import { Box, GridColumn, Text, ToastContainer, } from '@island.is/island-ui/core' import { SUBMIT_APPLICATION, UPDATE_APPLICATION, } from '@island.is/application/graphql' import deepmerge from 'deepmerge' import { FormProvider, SubmitHandler, useForm } from 'react-hook-form' import { useLocale } from '@island.is/localization' import { useWindowSize } from 'react-use' import { theme } from '@island.is/island-ui/theme' import { findProblemInApolloError, ProblemType, } from '@island.is/shared/problem' import { handleServerError } from '@island.is/application/ui-components' import { FormScreen, ResolverContext } from '../types' import FormMultiField from './FormMultiField' import FormField from './FormField' import { resolver } from '../validation/resolver' import FormRepeater from './FormRepeater' import FormExternalDataProvider from './FormExternalDataProvider' import { extractAnswersToSubmitFromScreen, findSubmitField } from '../utils' import ScreenFooter from './ScreenFooter' import RefetchContext from '../context/RefetchContext' type ScreenProps = { activeScreenIndex: number addExternalData(data: ExternalData): void application: Application answerAndGoToNextScreen(answers: FormValue): void answerQuestions(answers: FormValue): void dataSchema: Schema expandRepeater(): void mode?: FormModes numberOfScreens: number prevScreen(): void screen: FormScreen renderLastScreenButton?: boolean renderLastScreenBackButton?: boolean goToScreen: (id: string) => void } const getServerValidationErrors = (error: ApolloError | undefined) => { const problem = findProblemInApolloError(error, [ ProblemType.VALIDATION_FAILED, ]) if (problem && problem.type === ProblemType.VALIDATION_FAILED) { return problem.fields } return null } const Screen: FC<ScreenProps> = ({ activeScreenIndex, addExternalData, answerQuestions, application, dataSchema, expandRepeater, goToScreen, answerAndGoToNextScreen, mode, numberOfScreens, prevScreen, renderLastScreenButton, renderLastScreenBackButton, screen, }) => { const { answers: formValue, externalData, id: applicationId } = application const { lang: locale, formatMessage } = useLocale() const hookFormData = useForm<FormValue, ResolverContext>({ mode: 'onBlur', reValidateMode: 'onBlur', defaultValues: formValue, shouldUnregister: false, resolver: (formValue, context) => resolver({ formValue, context, formatMessage }), context: { dataSchema, formNode: screen }, }) const [fieldLoadingState, setFieldLoadingState] = useState(false) const [isSubmitting, setIsSubmitting] = useState(false) const refetch = useContext<() => void>(RefetchContext) // eslint-disable-next-line @typescript-eslint/no-unused-vars const [ updateApplication, { loading, error: updateApplicationError }, ] = useMutation(UPDATE_APPLICATION, { onError: (e) => { // We handle validation problems separately. const problem = findProblemInApolloError(e) if (problem?.type === ProblemType.VALIDATION_FAILED) { return } return handleServerError(e, formatMessage) }, }) const [submitApplication, { loading: loadingSubmit }] = useMutation( SUBMIT_APPLICATION, { onError: (e) => handleServerError(e, formatMessage), }, ) const { handleSubmit, errors: formErrors, reset } = hookFormData const submitField = useMemo(() => findSubmitField(screen), [screen]) const [beforeSubmitError, setBeforeSubmitError] = useState({}) const beforeSubmitCallback = useRef<BeforeSubmitCallback | null>(null) const setBeforeSubmitCallback = useCallback( (callback: BeforeSubmitCallback | null) => { beforeSubmitCallback.current = callback }, [beforeSubmitCallback], ) const parsedUpdateApplicationError = getServerValidationErrors( updateApplicationError, ) const dataSchemaOrApiErrors = { ...parsedUpdateApplicationError, ...beforeSubmitError, ...formErrors, } const goBack = useCallback(() => { // using deepmerge to prevent some weird react-hook-form read-only bugs reset(deepmerge({}, formValue)) prevScreen() }, [formValue, prevScreen, reset]) const onSubmit: SubmitHandler<FormValue> = async (data, e) => { let response setIsSubmitting(true) setBeforeSubmitError({}) if (typeof beforeSubmitCallback.current === 'function') { const [canContinue, possibleError] = await beforeSubmitCallback.current() if (!canContinue) { setIsSubmitting(false) if (typeof possibleError === 'string' && screen && screen.id) { setBeforeSubmitError({ [screen.id]: possibleError }) } return } } if (submitField !== undefined) { const finalAnswers = { ...formValue, ...data } let event: string if (submitField.placement === 'screen') { event = (finalAnswers[submitField.id] as string) ?? 'SUBMIT' } else { if (submitField.actions.length === 1) { const actionEvent = submitField.actions[0].event event = typeof actionEvent === 'object' ? actionEvent.type : actionEvent } else { const nativeEvent = e?.nativeEvent as { submitter: { id: string } } event = nativeEvent?.submitter?.id ?? 'SUBMIT' } } response = await submitApplication({ variables: { input: { id: applicationId, event, answers: finalAnswers, }, }, }) if (response?.data) { addExternalData(response.data?.submitApplication.externalData) if (submitField.refetchApplicationAfterSubmit) { refetch() } } } else { const extractedAnswers = extractAnswersToSubmitFromScreen( mergeAnswers(formValue, data), screen, ) response = await updateApplication({ variables: { input: { id: applicationId, answers: extractedAnswers, }, locale, }, }) } if (response?.data) { answerAndGoToNextScreen(data) } setIsSubmitting(false) } const [isMobile, setIsMobile] = useState(false) const { width } = useWindowSize() const headerHeight = 85 useEffect(() => { if (width < theme.breakpoints.md) { return setIsMobile(true) } setIsMobile(false) }, [width]) useEffect(() => { const target = isMobile ? headerHeight : 0 window.scrollTo(0, target) if (beforeSubmitCallback.current !== null) { setBeforeSubmitCallback(null) } }, [activeScreenIndex, isMobile, setBeforeSubmitCallback]) const onUpdateRepeater = async (newRepeaterItems: unknown[]) => { if (!screen.id) { return {} } const newData = await updateApplication({ variables: { input: { id: applicationId, answers: { [screen.id]: newRepeaterItems }, }, locale, }, }) if (!!newData && !newData.errors) { answerQuestions(newData.data.updateApplication.answers) reset( deepmerge( {}, { ...formValue, [screen.id]: newRepeaterItems as Answer[], }, ), ) } return { errors: newData?.errors, } } const isLoadingOrPending = fieldLoadingState || loading || loadingSubmit || isSubmitting return ( <FormProvider {...hookFormData}> <Box component="form" display="flex" flexDirection="column" justifyContent="spaceBetween" key={screen.id} height="full" onSubmit={handleSubmit(onSubmit)} > <GridColumn span={['12/12', '12/12', '10/12', '7/9']} offset={['0', '0', '1/12', '1/9']} > <Text variant="h2" as="h2" marginBottom={1}> {formatText(screen.title, application, formatMessage)} </Text> <Box> {screen.type === FormItemTypes.REPEATER ? ( <FormRepeater application={application} errors={dataSchemaOrApiErrors} expandRepeater={expandRepeater} setBeforeSubmitCallback={setBeforeSubmitCallback} setFieldLoadingState={setFieldLoadingState} repeater={screen} onUpdateRepeater={onUpdateRepeater} /> ) : screen.type === FormItemTypes.MULTI_FIELD ? ( <FormMultiField answerQuestions={answerQuestions} setBeforeSubmitCallback={setBeforeSubmitCallback} setFieldLoadingState={setFieldLoadingState} errors={dataSchemaOrApiErrors} multiField={screen} application={application} goToScreen={goToScreen} refetch={refetch} /> ) : screen.type === FormItemTypes.EXTERNAL_DATA_PROVIDER ? ( <FormExternalDataProvider addExternalData={addExternalData} setBeforeSubmitCallback={setBeforeSubmitCallback} applicationId={applicationId} externalData={externalData} externalDataProvider={screen} formValue={formValue} errors={dataSchemaOrApiErrors} /> ) : ( <FormField autoFocus setBeforeSubmitCallback={setBeforeSubmitCallback} setFieldLoadingState={setFieldLoadingState} errors={dataSchemaOrApiErrors} field={screen} application={application} goToScreen={goToScreen} refetch={refetch} /> )} </Box> </GridColumn> <ToastContainer hideProgressBar closeButton useKeyframeStyles={false} /> <ScreenFooter application={application} renderLastScreenButton={renderLastScreenButton} renderLastScreenBackButton={renderLastScreenBackButton} activeScreenIndex={activeScreenIndex} numberOfScreens={numberOfScreens} mode={mode} goBack={goBack} submitField={submitField} loading={loading} canProceed={!isLoadingOrPending} /> </Box> </FormProvider> ) } export default Screen
the_stack
import 'converse.js/dist/converse.min.css'; import 'converse.js/dist/converse.min.js'; import 'converse.js/dist/emojis.js'; import 'converse.js/dist/icons.js'; import { converse } from './window'; import { appData, getDecodedJwt } from '../data/appData'; import { useJoinParticipant } from '../data/stores/useJoinParticipant'; import { useParticipantWorkflow } from '../data/stores/useParticipantWorkflow'; import { useVideo } from '../data/stores/useVideo'; import { Participant } from '../types/Participant'; import { Video } from '../types/tracks'; import { MessageType, EventType, XMPP } from '../types/XMPP'; export const converseMounter = () => { let hasBeenInitialized = false; return (containerName: string, xmpp: XMPP) => { if (hasBeenInitialized) { converse.insertInto(document.querySelector(containerName)!); } else { converse.initialize({ allow_contact_requests: false, allow_logout: false, allow_message_corrections: 'last', allow_message_retraction: 'all', allow_muc_invitations: false, allow_registration: false, authentication: 'anonymous', auto_login: true, auto_join_rooms: [xmpp.conference_url], bosh_service_url: xmpp.bosh_url, clear_cache_on_logout: true, discover_connection_methods: false, enable_smacks: !!xmpp.websocket_url, hide_muc_participants: true, jid: xmpp.jid, modtools_disable_assign: true, muc_instant_rooms: false, muc_show_join_leave: false, nickname: getDecodedJwt().user?.username, root: document.querySelector(containerName), show_client_info: false, singleton: true, theme: 'concord', view_mode: 'embedded', visible_toolbar_buttons: { call: false, emoji: true, spoiler: false, toggle_occupants: false, }, websocket_url: xmpp.websocket_url, whitelisted_plugins: ['marsha', 'marsha-join-discussion'], }); converse.plugins.add('marsha', { dependencies: ['converse-muc'], initialize() { const _converse = this._converse; window.addEventListener('beforeunload', () => { _converse.api.user.logout(); }); }, }); converse.plugins.add('marsha-join-discussion', { dependencies: ['converse-muc'], initialize() { const _converse = this._converse; let joinedRoom = false; _converse.on('chatRoomInitialized', (model: any) => { model.session.on( 'change:connection_status', (currentSession: any) => { if ( currentSession.get('connection_status') === converse.ROOMSTATUS.ENTERED ) { joinedRoom = true; } if ( currentSession.get('connection_status') === converse.ROOMSTATUS.DISCONNECTED ) { joinedRoom = false; } if ( currentSession.get('connection_status') === converse.ROOMSTATUS.NICKNAME_REQUIRED && useParticipantWorkflow.getState().asked ) { useParticipantWorkflow .getState() .setUsernameAlreadyExisting(); } }, ); }); _converse.on('enteredNewRoom', (model: any) => { joinedRoom = true; if (useParticipantWorkflow.getState().asked) { askParticipantToJoin(); } }); _converse.on('initialized', () => { _converse.connection.addHandler( (message: any) => { if ( getDecodedJwt().permissions.can_update && message.getAttribute('type') === MessageType.GROUPCHAT && message.getAttribute('event') === EventType.PARTICIPANT_ASK_TO_JOIN ) { const jid = message.getAttribute('from'); const username = converse.env.Strophe.getResourceFromJid(jid); useJoinParticipant .getState() .addParticipantAskingToJoin({ id: jid, name: username }); } else if ( getDecodedJwt().permissions.can_update && message.getAttribute('type') === MessageType.GROUPCHAT && message.getAttribute('event') === EventType.ACCEPTED ) { const participant = JSON.parse( message.getAttribute('participant'), ); useJoinParticipant .getState() .moveParticipantToDiscussion(participant); } else if ( message.getAttribute('type') === MessageType.EVENT && message.getAttribute('event') === EventType.ACCEPT ) { // retrieve current video in store const video = useVideo.getState().getVideo(appData.video!); // update video with jitsi info useVideo.getState().addResource({ ...video, live_info: { ...video.live_info, jitsi: JSON.parse(message.getAttribute('jitsi')), }, }); useParticipantWorkflow.getState().setAccepted(); } else if ( message.getAttribute('type') === MessageType.EVENT && message.getAttribute('event') === EventType.REJECT ) { useParticipantWorkflow.getState().setRejected(); } else if ( getDecodedJwt().permissions.can_update && message.getAttribute('type') === MessageType.GROUPCHAT && message.getAttribute('event') === EventType.REJECTED ) { const participant = JSON.parse( message.getAttribute('participant'), ); useJoinParticipant .getState() .removeParticipantAskingToJoin(participant); } else if ( message.getAttribute('type') === MessageType.EVENT && message.getAttribute('event') === EventType.KICK ) { useParticipantWorkflow.getState().setKicked(); } else if ( getDecodedJwt().permissions.can_update && message.getAttribute('type') === MessageType.GROUPCHAT && message.getAttribute('event') === EventType.KICKED ) { const participant = JSON.parse( message.getAttribute('participant'), ); useJoinParticipant .getState() .removeParticipantFromDiscussion(participant); } else if ( getDecodedJwt().permissions.can_update && message.getAttribute('type') === MessageType.GROUPCHAT && message.getAttribute('event') === EventType.LEAVE ) { const jid = message.getAttribute('from'); const username = converse.env.Strophe.getResourceFromJid(jid); useJoinParticipant .getState() .removeParticipantFromDiscussion({ id: jid, name: username, }); } return true; }, null, 'message', null, null, null, ); }); const askParticipantToJoin = async (username?: string) => { if (!joinedRoom && !username) { throw Error('must be in the room before asking to join'); } // test if current user joined the room if (!joinedRoom && username) { const room = await _converse.api.rooms.get( xmpp.conference_url, {}, false, ); // try to join the room return room.join(username); } const msg = converse.env.$msg({ from: _converse.connection.jid, to: xmpp.conference_url, type: MessageType.GROUPCHAT, event: EventType.PARTICIPANT_ASK_TO_JOIN, }); _converse.connection.send(msg); }; const acceptParticipantToJoin = ( participant: Participant, video: Video, ) => { // only instructors or admin has update permissions if (!getDecodedJwt().permissions.can_update) { return; } // send message to user to accept joining the discussion const msg = converse.env.$msg({ from: _converse.connection.jid, to: participant.id, type: MessageType.EVENT, event: EventType.ACCEPT, jitsi: JSON.stringify(video.live_info.jitsi), }); _converse.connection.send(msg); // broadcast message to other instructors to sync participant states const acceptedMsg = converse.env.$msg({ from: _converse.connection.jid, to: xmpp.conference_url, type: MessageType.GROUPCHAT, event: EventType.ACCEPTED, participant: JSON.stringify(participant), }); _converse.connection.send(acceptedMsg); }; const rejectParticipantToJoin = (participant: Participant) => { // only instructors or admin has update permissions if (!getDecodedJwt().permissions.can_update) { return; } const msg = converse.env.$msg({ from: _converse.connection.jid, to: participant.id, type: MessageType.EVENT, event: EventType.REJECT, }); _converse.connection.send(msg); const rejectedMsg = converse.env.$msg({ from: _converse.connection.jid, to: xmpp.conference_url, type: MessageType.GROUPCHAT, event: EventType.REJECTED, participant: JSON.stringify(participant), }); _converse.connection.send(rejectedMsg); }; const kickParticipant = (participant: Participant) => { // only instructors or admin has update permissions if (!getDecodedJwt().permissions.can_update) { return; } const msg = converse.env.$msg({ from: _converse.connection.jid, to: participant.id, type: MessageType.EVENT, event: EventType.KICK, }); _converse.connection.send(msg); const kickedMsg = converse.env.$msg({ from: _converse.connection.jid, to: xmpp.conference_url, type: MessageType.GROUPCHAT, event: EventType.KICKED, participant: JSON.stringify(participant), }); _converse.connection.send(kickedMsg); }; const participantLeaves = () => { const msg = converse.env.$msg({ from: _converse.connection.jid, to: xmpp.conference_url, type: MessageType.GROUPCHAT, event: EventType.LEAVE, }); _converse.connection.send(msg); }; Object.assign(converse, { acceptParticipantToJoin, askParticipantToJoin, kickParticipant, rejectParticipantToJoin, participantLeaves, }); }, }); hasBeenInitialized = true; } }; };
the_stack
import { App, createApp as createReactantApp } from 'reactant'; import { createTransport } from 'data-transport'; import { LastAction, LastActionOptions, ILastActionOptions, } from 'reactant-last-action'; import { Config, ISharedAppOptions, Port, Transports } from './interfaces'; import { handleServer } from './server'; import { handleClient } from './client'; import { createBroadcastTransport } from './createTransport'; import { isClientName, preloadedStateActionName, SharedAppOptions, } from './constants'; import { IPortDetectorOptions, PortDetector, PortDetectorOptions, } from './portDetector'; import { useLock } from './lock'; const createBaseApp = <T>({ share, ...options }: Config<T>): Promise<App<T>> => { options.modules ??= []; options.devOptions ??= {}; options.devOptions.enablePatches = true; options.modules.push( LastAction, { provide: LastActionOptions, useValue: { stateKey: `lastAction-${share.name}`, } as ILastActionOptions, }, { provide: PortDetectorOptions, useValue: { transports: share.transports, } as IPortDetectorOptions, }, { provide: SharedAppOptions, useValue: share as ISharedAppOptions, }, PortDetector ); return new Promise(async (resolve) => { let app: App<T>; let disposeServer: (() => void) | undefined; let disposeClient: (() => void) | undefined; const serverTransport = share.transports?.server; const clientTransport = share.transports?.client; const isServer = share.port === 'server'; const { transform } = share; share.transform = (changedPort: Port) => { if (changedPort === 'server') { if (!serverTransport) { throw new Error(`'transports.server' does not exist.`); } handleServer({ app, transport: serverTransport, disposeClient, enablePatchesChecker: share.enablePatchesChecker, }); } else { if (!clientTransport) { throw new Error(`'transports.client' does not exist.`); } handleClient({ app, transport: clientTransport, disposeServer, enablePatchesFilter: share.enablePatchesFilter, }); } transform?.(changedPort); }; if (isServer) { if (!serverTransport) { throw new Error(`'transports.server' does not exist.`); } app = createReactantApp(options); disposeServer = handleServer({ app, transport: serverTransport, enablePatchesChecker: share.enablePatchesChecker, }); resolve(app); } else { if (!clientTransport) { throw new Error(`'transports.client' does not exist.`); } clientTransport.emit(preloadedStateActionName).then((preloadedState) => { app = createReactantApp({ ...options, preloadedState, }); disposeClient = handleClient({ app, transport: clientTransport, enablePatchesFilter: share.enablePatchesFilter, preloadedState, }); resolve(app); }); } }); }; const createSharedTabApp = async <T>(options: Config<T>) => { /** * Performance issue with broadcast-channel repo in Safari. */ const isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent); if (isSafari) { options.share.transports ??= {}; options.share.transports.server = { emit() {}, listen() {} } as any; options.share.port = 'server'; const app = createBaseApp(options); return app; } options.share.transports ??= {}; options.share.transports.client ??= createBroadcastTransport( options.share.name ); options.share.transports.server ??= createBroadcastTransport( options.share.name ); if (options.share.port) { const app = await createBaseApp(options); return app; } let app: App<T>; app = await Promise.race([ new Promise<App<T>>((resolve) => { useLock(`reactant-share-app-lock:${options.share.name}`, async () => { if (!app) { options.share.port = 'server'; app = await createBaseApp(options); } else { options.share.transform?.('server'); } resolve(app); return new Promise(() => { // }); }); }), new Promise<App<T>>(async (resolve) => { const isClient = await options.share.transports?.client?.emit( isClientName ); if (isClient) { options.share.port = 'client'; const app = await createBaseApp(options); resolve(app); } }), ]); return app; }; /** * ## Description * * You can create an shared app with `createSharedApp()` passing app configuration, * which will asynchronously return an object including `instance`, `store`, * and `bootstrap()` method(You can run `bootstrap` to start the app inject into the browser or mobile). * * ## Example * * ```ts * import { createSharedApp, injectable, state, action, spawn, mockPairTransports } from 'reactant-share'; * * @injectable({ * name: 'counter', * }) * class Counter { * @state * count = 0; * * @action * increase() { * this.count += 1; * } * } * * (async () => { * const transports = mockPairTransports(); * * const server = await createSharedApp({ * modules: [], * main: Counter, * render: () => {}, * share: { * name: 'counter', * type: 'Base', * port: 'server', * transports: { * server: transports[0], * }, * }, * }); * * const client = await createSharedApp({ * modules: [], * main: Counter, * render: () => {}, * share: { * name: 'counter', * type: 'Base', * port: 'client', * transports: { * client: transports[1], * }, * }, * }); * * await spawn(client.instance, 'increase', []); * * expect(client.instance.count).toBe(1); * expect(server.instance.count).toBe(1); * * global.done(); * })(); * ``` */ export const createSharedApp = async <T>(options: Config<T>) => { let app: App<T>; let transports: Transports; if (typeof options.share === 'undefined') { throw new Error(`'createSharedApp(options)' should be set 'share' option.`); } // Check to minimized patch. options.share.enablePatchesChecker ??= __DEV__; switch (options.share.type) { case 'BrowserExtension': transports = { server: options.share.transports?.server, client: options.share.transports?.client, }; if (options.share.port === 'server') { transports.server ??= createTransport('BrowserExtensionsMain', { prefix: `reactant-share:${options.share.name}`, }); } else if (options.share.port === 'client') { transports.client ??= createTransport('BrowserExtensionsClient', { prefix: `reactant-share:${options.share.name}`, }); } options.share.transports = transports; app = await createBaseApp(options); break; case 'ServiceWorker': try { transports = { server: options.share.transports?.server, client: options.share.transports?.client, }; if (options.share.port === 'client' && options.share.worker) { transports.client ??= createTransport('ServiceWorkerClient', { worker: options.share.worker as ServiceWorker, prefix: `reactant-share:${options.share.name}`, }); } if (options.share.port === 'server') { transports.server ??= createTransport('ServiceWorkerService', { prefix: `reactant-share:${options.share.name}`, }); } else if (options.share.port === 'client' && !transports.client) { if (typeof options.share.workerURL !== 'string') { throw new Error( `The value of 'options.share.workerURL' should be a string.` ); } if ('serviceWorker' in navigator) { await new Promise((resolve) => { navigator.serviceWorker.register(options.share.workerURL!); navigator.serviceWorker.ready.then((registration) => { transports.client = createTransport('ServiceWorkerClient', { worker: registration.active!, prefix: `reactant-share:${options.share.name}`, }); resolve(null); }); }); } else { throw new Error( `The current browser does not support ServiceWorker.` ); } } options.share.transports = transports; app = await createBaseApp(options); } catch (e) { console.warn(e); const { port, workerURL, name, ...shareOptions } = options.share; app = await createSharedTabApp({ ...options, share: { ...shareOptions, type: 'SharedTab', name, }, }); } break; case 'SharedWorker': try { transports = { server: options.share.transports?.server, client: options.share.transports?.client, }; if (options.share.port === 'client' && options.share.worker) { transports.client ??= createTransport('SharedWorkerMain', { worker: options.share.worker as SharedWorker, prefix: `reactant-share:${options.share.name}`, }); } if (options.share.port === 'server') { transports.server ??= createTransport('SharedWorkerInternal', { prefix: `reactant-share:${options.share.name}`, }); } else if (options.share.port === 'client' && !transports.client) { if (typeof options.share.workerURL !== 'string') { throw new Error( `The value of 'options.share.workerURL' should be a string.` ); } transports.client = createTransport('SharedWorkerMain', { worker: new SharedWorker(options.share.workerURL), prefix: `reactant-share:${options.share.name}`, }); } options.share.transports = transports; app = await createBaseApp(options); } catch (e) { console.warn(e); const { port, workerURL, name, ...shareOptions } = options.share; app = await createSharedTabApp({ ...options, share: { ...shareOptions, type: 'SharedTab', name, }, }); } break; case 'SharedTab': app = await createSharedTabApp(options); break; case 'Base': app = await createBaseApp(options); break; default: throw new Error( `The value of 'options.share.type' be 'SharedTab', 'SharedWorker', 'BrowserExtension' or 'Base'.` ); } return app; };
the_stack
module TDev.AST { // a visitor to find the set of ``next'' statements after provided one // the next finder is conservative and can find false nodes! export class NextFinder extends NodeVisitor { constructor() { super(); } static enclosingStmt(stmt: Stmt) { return stmt.parentBlock() && stmt.parentBlock().parent; } static asLoop(stmt: Stmt): LoopStmt{ if (stmt instanceof While || stmt instanceof For || stmt instanceof Foreach) return <LoopStmt><any>stmt; else return null; } private nextInBlock(stmt: Stmt) { if (!stmt || !stmt.parentBlock()) return []; var container = stmt.parentBlock().stmts; var ix = container.indexOf(stmt); var enclosing = NextFinder.enclosingStmt(stmt); ++ix; while ((ix < container.length) && (container[ix].isPlaceholder() || container[ix].nodeType() === "comment")) ++ix; var ret = [] if(ix >= container.length) { // we are last child ret = this.nextInBlock(enclosing); } else { ret = [container[ix]]; } return ret.concat(this.visitLoop(NextFinder.asLoop(enclosing))); } static firstInCodeBlock(body: CodeBlock) { if (body == null) return null; var ix = 0; var container = body.stmts; while ((ix < container.length) && (container[ix].isPlaceholder() || container[ix].nodeType() === "comment"))++ix; if (ix >= container.length) { // nothing useful inside return null; } return container[ix]; } public visitCodeBlock(body: CodeBlock) { var ret = NextFinder.firstInCodeBlock(body); return ret ? [ret] : []; } private visitLoop(stmt: LoopStmt) { if (stmt == null) return []; var ret = this.visitCodeBlock(stmt.body); return ret.concat(this.nextInBlock(<Stmt><any>stmt)); } public visitFor(stmt: For) { return this.visitLoop(stmt); } public visitForeach(stmt: Foreach) { return this.visitLoop(stmt); } public visitWhile(stmt: While) { return this.visitLoop(stmt); } // TODO this is wrong for Return and Break public visitExprStmt(stmt: ExprStmt) { return this.nextInBlock(stmt); } public visitBox(box: Box) { return this.visitCodeBlock(box.body); } public visitInlineActions(ia: InlineActions) { return this.visitExprStmt(ia); } public visitAnyIf(stmt: If) { var arrs = stmt.parentIf.bodies().map(b => this.visitCodeBlock(b)) arrs.push(this.nextInBlock(stmt)) // this is not really the case most of the time, but whatever return Util.concatArraysVA(arrs) } static find(stmt: Stmt): Stmt[]{ if (!stmt) return []; var ret = new NextFinder().dispatch(stmt); if (!ret) { return []; } return ret; } } export class InnerNextFinder extends NodeVisitor { called: Action[] = []; visitAstNode(n: AstNode) { this.visitChildren(n); return null; } visitCall(n: Call) { var act = n.calledAction(); if (act && this.called.indexOf(act) < 0) { this.called.push(act); } else { super.visitCall(n); } } visitExprHolder(n: ExprHolder) { if (n.parsed) this.dispatch(n.parsed); } static find(stmt: Stmt): Stmt[]{ if (!stmt) return []; var finder = new InnerNextFinder(); finder.dispatch(stmt); return finder.called.filter(a => !!a.body).map(a => { var fst = NextFinder.firstInCodeBlock(a.body); return fst ? [fst] : []; }).reduce((a,b) => a.concat(b), []); } } class AwaitChecker extends NodeVisitor { private res = false; visitAstNode(n: AstNode) { if (!n) return; this.visitChildren(n); } visitExprHolder(eh: ExprHolder) { if (!eh) return; this.dispatch(eh.parsed); } visitCall(n: Call) { if (!n) return; super.visitCall(n); if (n.awaits()) this.res = true; } static isAwait(n: Stmt) { if (!n) return; var checker = new AwaitChecker(); checker.dispatch(n); return checker.res; } } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // Visitor classes that enable Dataflow Analyses to walk through the AST // PredecessorsFinder extracts the list of predecessors statements of another statement // by walking the AST. These are the predecessors when converting the AST to a CFG. // NOTE: Valid nodes for all dataflow analyses are Statement nodes // that contain an ExprHolder instance (therefore, consumes an expression). // PredecessorsFinder and SuccessorsFinder both walk through these nodes // and bypasses the rest (Box es, for instance). export class PredecessorsFinder extends NodeVisitor { constructor() { super(); } // Convenience methods static enclosingStmt(stmt: Stmt): Stmt { return stmt.parentBlock() && stmt.parentBlock().parent; } static asLoop(stmt: Stmt): Stmt { if (stmt instanceof While || stmt instanceof For || stmt instanceof Foreach) return stmt; else return null; } // Tries to dig the last statement of a block that belongs to the // current stmt. If it does not contain a block, returns itself. static unpeelAndGetLast(stmt: Stmt): Stmt[]{ var ret: Stmt[] = []; // Comments and placeholders are not excluded from the dataflow // visiting path. They just propagate the information through, // but we need to handle them. if (stmt instanceof Comment) { ret = [stmt]; } else if (stmt instanceof For) { ret = ret.concat(PredecessorsFinder.lastInCodeBlock((<For>stmt).body)); } else if (stmt instanceof Foreach) { ret = ret.concat(PredecessorsFinder.lastInCodeBlock((<Foreach>stmt).body)); } else if (stmt instanceof While) { ret = ret.concat(PredecessorsFinder.lastInCodeBlock((<While>stmt).body)); } else if (stmt instanceof If) { Util.assert(!((<If>stmt).isElseIf)); // "If" nodes contains many last statements, one for each block. This should // always return at least two nodes, even when else is empty - in this // case it returns the placeholder. ret = ret.concat(Util.concatArraysVA((<If>stmt).bodies().map(PredecessorsFinder.lastInCodeBlock))) } else if (stmt instanceof Box) { ret = ret.concat(PredecessorsFinder.lastInCodeBlock((<Box>stmt).body)); } else if (stmt instanceof ExprStmt) { ret = [stmt]; } if (ret.length == 0) ret = [stmt]; return ret; } // Find the previous IF statement (used only to find predecessors // of ifelse conditions). private findPreviousIf(ifstmt: If): Stmt[] { Util.assert(!!ifstmt && !!(ifstmt.parentBlock())); var container = ifstmt.parentBlock().stmts; var ix = container.indexOf(ifstmt); --ix; Util.assert(ix >= 0); var previous = container[ix]; Util.assert(previous instanceof If); return [previous]; } // Find the previous statement considering the enclosing block private previousInBlock(stmt: Stmt): Stmt[] { if (!stmt || !stmt.parentBlock()) return []; var container = stmt.parentBlock().stmts; var ix = container.indexOf(stmt); var enclosing = PredecessorsFinder.enclosingStmt(stmt); --ix; var ret = []; if (ix < 0) { // We are the first statement in a block // The previous is the loop condition check or if statement, // if they exist. Otherwise, we need to dig further and go for // the previous statement of the enclosing block. var l = PredecessorsFinder.asLoop(enclosing); if (!!l || (enclosing instanceof If)) { ret = ret.concat(enclosing); } else if (enclosing instanceof InlineAction) { ret = []; } else { ret = ret.concat(this.previousInBlock(enclosing)); } } else { var prev = container[ix]; // In case of a block of statements, we need to unpeel and go // inside it. For loops, the loop itself is the statement. if ((prev instanceof For) || (prev instanceof While) || (prev instanceof Foreach)) { ret = ret.concat([prev]); } else if ((prev instanceof If) && ((<If>prev).isElseIf)) { ret = ret.concat(PredecessorsFinder.unpeelAndGetLast((<If>prev).parentIf)); } else { ret = ret.concat(PredecessorsFinder.unpeelAndGetLast(prev)); } if (ret.length == 0) ret = this.previousInBlock(prev); } return ret; } // Extracts the last statement in a code block. Useful for finding // predecessors of loop structures. static lastInCodeBlock(body: CodeBlock): Stmt[] { if (body == null) return []; var enclosing = PredecessorsFinder.enclosingStmt(body); var container = body.stmts; var ix = container.length - 1; if (ix < 0) { return []; } var last = container[ix]; // In case of a block of statements, we need to unpeel and go // inside it. For loops, the loop itself is the statement. if ((last instanceof For) || (last instanceof While) || (last instanceof Foreach)) return [last]; if (last instanceof If && (<If>last).isElseIf) { return PredecessorsFinder.unpeelAndGetLast((<If>last).parentIf); } return PredecessorsFinder.unpeelAndGetLast(last); } public visitCodeBlock(body: CodeBlock): Stmt[] { return PredecessorsFinder.lastInCodeBlock(body); } // The predecessor of a loop is the pair of the previous statement in // its enclosing block and the last statement inside the loop private visitLoop(stmt: Stmt): Stmt[] { if (stmt == null) return []; var ret = this.previousInBlock(<Stmt><any>stmt); return ret.concat(PredecessorsFinder.unpeelAndGetLast(stmt)); } public visitFor(stmt: For): Stmt[] { return this.visitLoop(stmt); } public visitForeach(stmt: Foreach): Stmt[] { return this.visitLoop(stmt); } public visitWhile(stmt: While): Stmt[] { return this.visitLoop(stmt); } // The predecessor of a regular statement is simply the previous // statement in the block public visitStmt(stmt: Stmt): Stmt[] { return this.previousInBlock(stmt); } // The predecessor of an If is simply the previous statement in its // enclosing block. public visitIf(stmt: If): Stmt[]{ Util.assert(!stmt.isElseIf); return this.previousInBlock(stmt); } // If it is an Ifelse, then its predecessor is the previous If. public visitElseIf(n: If) { return this.findPreviousIf(n); } // Returns the list of predecessor statements for "stmt". Uses a // visitor to handle different node types. static find(stmt: Stmt): Stmt[] { if (!stmt) return []; return new PredecessorsFinder().dispatch(stmt); } } // Used for dataflow equations, analogous to the PredecessorFinder. // Predecessor and Successors Finders must satisfy the property that // Succs[ Preds[x] ] = x // Otherwise analyses will break. Successors are not just used in backward // analysis, but also in regular forward analysis in order to discover // which nodes to analyze when its Outs[] set is update, and vice-versa. // // NOTE: Valid nodes for all dataflow analyses are Statement nodes // that contain an ExprHolder instance (therefore, consumes an expression). // PredecessorsFinder and SuccessorsFinder both walk through these nodes // and bypasses the rest (Box es, for instance). export class SuccessorsFinder extends NodeVisitor { constructor() { super(); } // Convenience methods static enclosingStmt(stmt: Stmt): Stmt { return stmt.parentBlock() && stmt.parentBlock().parent; } static asLoop(stmt: Stmt): Stmt { if (stmt instanceof While || stmt instanceof For || stmt instanceof Foreach) return stmt; else return null; } // This is not the same as "unpeelAndGetLast" of Predecessors because // it rarely needs to actually unpeel and get the statements inside a // block. The reason is that the first statement of a "If" or loop node // are really the "If" or loop themselves, except for Boxes. static unpeelAndGetFirst(stmt: Stmt): Stmt[]{ var ret: Stmt[] = []; if (stmt instanceof Comment) { ret = ret.concat(stmt); } else if (stmt instanceof For) ret = ret.concat(stmt); else if (stmt instanceof Foreach) { ret = ret.concat(stmt); } else if (stmt instanceof While) { ret = ret.concat(stmt); } else if (stmt instanceof If) { ret = ret.concat(stmt); } else if (stmt instanceof Box) { ret = ret.concat(SuccessorsFinder.firstInCodeBlock((<Box>stmt).body)); } else if (stmt instanceof ExprStmt) { ret = ret.concat(stmt); } if (ret.length == 0) ret = [stmt]; return ret; } // Find the next IF statement (used only to find successors // of if/ifelse nodes). private findNextIf(ifstmt: If): Stmt[] { Util.assert(!!ifstmt && !!(ifstmt.parentBlock())); var container = ifstmt.parentBlock().stmts; var ix = container.indexOf(ifstmt); ++ix; if (ix >= container.length) return []; var next = container[ix]; if (!(next instanceof If) || !((<If>next).isElseIf)) return []; return [next]; } // clone of nextInBlock, but jumps over IFELSE stmts. // Goes to the next stmt after a sequence of ifelse. Useful to // jump to the end of the structure when finding the successors of // the last statement of a codeblock inside an if. private jumpToEndOfIfElse(ifstmt: Stmt): Stmt[] { Util.assert(!!ifstmt && !!(ifstmt.parentBlock())); var container = ifstmt.parentBlock().stmts; var ix = container.indexOf(ifstmt); var enclosing = PredecessorsFinder.enclosingStmt(ifstmt); ++ix; while (container[ix] && container[ix] instanceof If && (<If>(container[ix])).isElseIf) ++ix; var ret = []; if (ix >= container.length) { // We are the last statement, so we can only find the next // statement looking for our parents: it is either the // enclosing loop or the successor of our parent. NOTE: We do not // jump directly from the last statement of a loop to outside // the loop: it must first go to the loop node to check the // condition, therefore we only have a single successor in // this case. var l = SuccessorsFinder.asLoop(enclosing); if (!!l) { ret = ret.concat(enclosing); } else if (enclosing instanceof If) { ret = ret.concat(this.jumpToEndOfIfElse(enclosing)); } else if (enclosing instanceof InlineAction) { ret = []; } else { ret = ret.concat(this.nextInBlock(enclosing)); } } else { var next = container[ix]; // If this is a statement that contains statements, we want its children, // but first check if it is an statement that contains an ExprHolder ret = ret.concat(SuccessorsFinder.unpeelAndGetFirst(next)); if (ret.length == 0) ret = this.nextInBlock(next); } return ret; } // Look for the next statement considering its enclosing block. private nextInBlock(stmt: Stmt): Stmt[] { if (!stmt || !stmt.parentBlock()) return []; var container = stmt.parentBlock().stmts; var ix = container.indexOf(stmt); var enclosing = PredecessorsFinder.enclosingStmt(stmt); ++ix; var ret = []; if (ix >= container.length) { // We are the last statement, so we can only find the next // statement looking for our parents: it is either the // enclosing loop or the successor of our parent. NOTE: We do not // jump directly from the last statement of a loop to outside // the loop: it must first go to the loop node to check the // condition, therefore we only have a single successor in // this case. var l = SuccessorsFinder.asLoop(enclosing); if (!!l) { ret = ret.concat(enclosing); } else if (enclosing instanceof If) { ret = ret.concat(this.jumpToEndOfIfElse(enclosing)); } else if (enclosing instanceof InlineAction) { ret = []; } else { ret = ret.concat(this.nextInBlock(enclosing)); } } else { var next = container[ix]; // If this is a statement that contains statements, we want its children, // but first check if it is an statement that contains an ExprHolder ret = ret.concat(SuccessorsFinder.unpeelAndGetFirst(next)); if (ret.length == 0) ret = this.nextInBlock(next); } return ret; } // Extracts the first statement in a code block, useful for finding // successors of loop structures. static firstInCodeBlock(body: CodeBlock): Stmt[] { if (body == null) return []; var container = body.stmts; var ix = 0; var enclosing = SuccessorsFinder.enclosingStmt(body); if (ix >= container.length) { // nothing useful inside return []; } var first = container[ix]; return SuccessorsFinder.unpeelAndGetFirst(first); } public visitCodeBlock(body: CodeBlock): Stmt[] { return SuccessorsFinder.firstInCodeBlock(body); } // The successors of a loop is the pair of the first statement in its // body and the next statement after the loop, since the execution flow // skips the loop body after its condition evaluates to false. private visitLoop(stmt: Stmt): Stmt[] { if (stmt == null) return []; var ret = this.nextInBlock(stmt); return ret.concat(this.visitCodeBlock((<LoopStmt><any>stmt).body)); } public visitFor(stmt: For): Stmt[] { return this.visitLoop(stmt); } public visitForeach(stmt: Foreach): Stmt[] { return this.visitLoop(stmt); } public visitWhile(stmt: While): Stmt[] { return this.visitLoop(stmt); } // The succ for a generic statement is the next stmt in its enclosing // block. public visitStmt(stmt: Stmt): Stmt[] { return this.nextInBlock(stmt); } // Successors of the "If" node are the first statements of its child // code blocks ("then" and "else"). If the else path includes another // condition check (ifelse node), then the first statement of "then" // block and the next ifelse node are the successors. public visitIf(stmt: If): Stmt[]{ var ret = SuccessorsFinder.firstInCodeBlock(stmt.rawThenBody); if (stmt.displayElse) return ret.concat(SuccessorsFinder.firstInCodeBlock(stmt.rawElseBody)); return ret.concat(this.findNextIf(stmt)); } public visitElseIf(n: If) { return this.visitIf(n); } // Returns the list of successor statements for "stmt". Only returns // "valid" nodes as described in the note above (Statement nodes that // contains ExprHolder instances). static find(stmt: Stmt): Stmt[] { if (!stmt) return []; return new SuccessorsFinder().dispatch(stmt); } } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // Dataflow set data strucutes // An element may be anything worth storing in Ins/Outs sets for each point // of the program and depends on the analysis. Reaching definitions will // store the stringified def expression as the "key" and a reference to the // def expression itself. "Id" is bookkeeping maintained by the // SetElementsPool class. export class SetElement { constructor(public id: number, public key: string, public refNode: Expr) { } } // The pool keeps the elements alive and assign the lowest possible id // to reference them, and Set instances reference them using a lightweight // bitset representation. If IDs are large, more memory will be necessary // to represent the bitset. // After an analysis is done, a pool contains all elements generated by // Gen equations. class SetElementsPool { private map: { [s: string]: number; }; private pool: SetElement[]; constructor(private curId = 0) { this.map = {}; this.pool = []; } // Builds a new SetElement and assign to it the lowest possible id. Get // it if an element with the same id already exists. public getElm(key: string, refNode: Expr): SetElement { var idx = this.map[["a_", key].join("")]; if (idx == undefined) { idx = this.curId++; var elm = new SetElement(idx, key, refNode); this.pool.push(elm); this.map[["a_", key].join("")] = idx; } return this.pool[idx]; } public getElmById(id: number): SetElement { if (id >= this.pool.length) return null; return this.pool[id]; } public size(): number { return this.pool.length; } } // The memory representation of all Ins/Outs sets for all points of the // programs. export class BitSet { private _myset: number[]; private setSize: number; // largestIndex is important for bookkeeping and directly reflects // our current size, signaling when it should be expanded. It is also // used to limit which indexes to traverse when forEach is called for // an allSet set (that is supposed to contain all known elements). private largestIndex: number; // The allSet flag is meant to be used in a set that is supposed to // start containing all possible elements. Therefore, it expands // with 1s, meaning it contains even those elements that it has never // seen before. Useful for intersection-confluence analyses. constructor(public allSet = false) { this._myset = []; if (allSet) this._myset.push(0xFFFFFFFF); else this._myset.push(0); this.setSize = 1; this.largestIndex = -1; } // Helper function to expand the set when a large index is used // to access an element that is currently not being represented. private growSet(idx: number): void { idx -= this.setSize * 32; while (idx >= 0) { if (this.allSet) this._myset.push(0xFFFFFFFF); else this._myset.push(0); ++this.setSize; idx -= 32; } } private cloneSet(): number[]{ var a: number[] = []; for (var i = 0; i < this.setSize; ++i) { a.push(this._myset[i]); } return a; } // Makes this an allSet set (contains all elements). public makeAllSet(): void { this._myset = [0xFFFFFFFF]; this.setSize = 1; this.allSet = true; this.largestIndex = -1; } public add(elm: number): void { if (elm >= this.setSize * 32) this.growSet(elm); if (elm > this.largestIndex) this.largestIndex = elm; this._myset[Math.floor(elm / 32)] |= 1 << elm % 32; } public setLargestIndex(idx: number): void { if (idx > this.setSize * 32) this.growSet(idx); this.largestIndex = idx; } public remove(elm: number): void { if (elm >= this.setSize * 32) this.growSet(elm); if (elm > this.largestIndex) this.largestIndex = elm; this._myset[Math.floor(elm / 32)] &= ~(1 << elm % 32); } public contains(elm: number): boolean { if (elm >= this.setSize * 32) this.growSet(elm); if (elm > this.largestIndex) this.largestIndex = elm; return !!(this._myset[Math.floor(elm / 32)] & (1 << elm % 32)); } public union(a: BitSet): void { if (a.largestIndex > this.largestIndex) { this.setLargestIndex(a.largestIndex); } else if (this.largestIndex > a.largestIndex) { a.setLargestIndex(this.largestIndex); } for (var i = 0; i < a.setSize; ++i) { this._myset[i] |= a._myset[i]; } if (a.allSet) this.allSet = true; } public intersection(a: BitSet): void { if (a.largestIndex > this.largestIndex) { this.setLargestIndex(a.largestIndex); } else if (this.largestIndex > a.largestIndex) { a.setLargestIndex(this.largestIndex); } for (var i = 0; i < a.setSize; ++i) { this._myset[i] &= a._myset[i]; } if (this.allSet && !a.allSet) this.allSet = false; } public forEach(cb: (elm: number) => void ): void { if (this.largestIndex < 0) return; for (var i = 0; i <= this.largestIndex / 32; ++i) { var idx = i * 32; var val = this._myset[i]; while (val != 0 && idx <= this.largestIndex) { if (val & 1) cb(idx); ++idx; val = val >>> 1; } } } public clone(): BitSet { var a = new BitSet(this.allSet); a._myset = this.cloneSet(); a.setSize = this.setSize; a.largestIndex = this.largestIndex; return a; } public equals(a: BitSet): boolean { if ((this.allSet && !a.allSet) || (!this.allSet && a.allSet)) return false; if (a.largestIndex > this.largestIndex) { this.setLargestIndex(a.largestIndex); } else if (this.largestIndex > a.largestIndex) { a.setLargestIndex(this.largestIndex); } for (var i = 0; i < a.setSize; ++i) { if (this._myset[i] != a._myset[i]) return false; } return true; } } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // Dataflow framework classes // Every dataflow analysis should implement this interface. // DataflowVisitor will call your analysis for every Statement that // contains expressions (ExprHolder instances) to calculate gen/kill // sets. export interface IDataflowAnalysis { // Change _set to reflect the In set of the entry node of // the action (or exit node if backwards analysis). buildStartNodeSet(a: Action, _set: BitSet): void; // All sets are intialized by cloning the set specified by this // function. You should start with an allSet set for analysis that // use intersection confluence. buildStartingSet(a: Action, _set: BitSet): void; // Change _set to reflect Gen[n], where n is an expression. // inSet: the original set before Kill kicked in // isIV: true when this expression does not actually exist, but was // generated to simulate the behavior experienced by induction // variables of "For" nodes. gen(n: ExprHolder, _set: BitSet, inSet: BitSet, isIV: boolean): void; // Change _set to reflext Kill[n], where n is an expression. // isIV: true when this expression does not actually exist, but was // generated to simulate the behavior experienced by induction // variables when "For" nodes are executed. kill(n: ExprHolder, _set: BitSet, isIV: boolean): void; // Attach the calculated information from expression "n" in node "s", // which owns this expression. This should be the result of this // analysis and remains attached to the AST. updateNode(s: Stmt, n: ExprHolder): void; } // DataflowVisitor manages all common duties of a dataflow analysis, leaving // only the gen/kill sets calculation for the analysis itself. It works once // per Action and starts by determining the order of nodes to visit in this // action, but only consider nodes that are Statement and that contains // expressions (ExprHolder instances), skipping other nodes. // Uses BitSet for union and intersection set operations, topological sort // for the initial visit order and a worklist for the remaining visits // NOTE: If the analysis is backwards, notice that Ins/Outs sets are // reversed. class DataflowVisitor extends NodeVisitor { private worklist: Stmt[] = []; public Ins: { [k: number]: BitSet; } = {}; public Outs: { [k: number]: BitSet; } = {}; private startingSet: BitSet; private startNodeSet: BitSet; private starting: boolean = false; private changed: boolean = false; private visited: { [id: number]: boolean; } = {}; // df: Reference to the actual Analysis that will be called for each // expression. // pool: Reference to the pool to create/reference elements of sets. // backwards: direction, true if backwards. // intersection: confluence operator, false if union, true if // intersection // useWorklist: true if uses a worklist to visit nodes, false will // use the blind algorithm of revisiting all nodes each time a // modification is detected. constructor(public df: IDataflowAnalysis, public pool: SetElementsPool, public backwards: boolean = false, public intersection: boolean = false, public useWorklist = true) { super(); } // Keep the same id for generated assignzero expressions private genZeroMap: { [name: string]: Expr; } = {}; // Helper function to generate an expression that mimics the behavior // of a "For" node, initializing the induction variable with zero. private generateAssignZero(l: LocalDef): Expr { var res = this.genZeroMap[["d_", l.getName()].join("")]; if (res != undefined) return res; var localThing = mkThing(l.getName()); (<ThingRef>localThing).def = l; var initialVal = mkLit(0); res = mkCall(PropertyRef.mkProp(api.core.AssignmentProp), [localThing, initialVal]); this.genZeroMap[["d_", l.getName()].join("")] = res; return res; } // Keep the same id for generated inc expressions private genIncMap: { [name: string]: Expr; } = {}; // Helper function to generate an expression that mimics the behavior // of a "For" node, incrementing the induction variable private generateInc(l: LocalDef): Expr { var res = this.genIncMap[["d_", l.getName()].join("")]; if (res != undefined) return res; var localThing = mkThing(l.getName()); (<ThingRef>localThing).def = l; var incVal = mkLit(1); var sum = mkCall(PropertyRef.mkProp(api.core.Number.getProperty("+")), [localThing, incVal]); res = mkCall(PropertyRef.mkProp(api.core.AssignmentProp), [localThing, sum]); this.genIncMap[["d_", l.getName()].join("")] = res; return res; } public visitAstNode(node: AstNode): any { this.visitChildren(node); } // This is the core of DataflowVisitor and handles our subject of // interest: AST Statements that contains ExprHolder instances. private visitExprHolderHolder(stmt: Stmt) { var preds = this.backwards ? AST.SuccessorsFinder.find(stmt) : AST.PredecessorsFinder.find(stmt); var newIn: BitSet; if (this.starting) { newIn = this.startNodeSet.clone(); this.starting = false; } else { var validPreds = 0; newIn = this.intersection ? new BitSet(/*allset*/true) : new BitSet(); preds.forEach((x: Stmt) => { var nOut = this.Outs[x.nodeId]; if (nOut != undefined) { ++validPreds; if (this.intersection) newIn.intersection(nOut); else newIn.union(nOut); } }); if (validPreds == 0) { newIn = this.startingSet.clone(); } } this.Ins[stmt.nodeId] = newIn; var newOut = newIn.clone(); // Calculate kill/gen sets. Ignore placeholders. if (stmt instanceof ExprStmt && !stmt.isPlaceholder()) { this.df.kill((<ExprStmt>stmt).expr, newOut, false); this.df.gen((<ExprStmt>stmt).expr, newOut, newIn, false); } else if (!!stmt.calcNode()) { // A "For" node implicitly updates the induction variable each // time it is run, and some analyses need to know about this. // We generate fake expressions that represent this behavior. if (stmt instanceof For) { var forInitialAssgn = exprToStmt(this.generateAssignZero((<For>stmt).boundLocal)); var forIncAssgn = exprToStmt(this.generateInc((<For>stmt).boundLocal)); this.df.kill(forInitialAssgn.expr, newOut, true); this.df.kill(forIncAssgn.expr, newOut, true); this.df.gen(forIncAssgn.expr, newOut, newIn, true); this.df.gen(forInitialAssgn.expr, newOut, newIn, true); } this.df.kill(stmt.calcNode(), newOut, false); this.df.gen(stmt.calcNode(), newOut, newIn, false); } // Check to see if we are stuck at a fixed point or if we need // to continue running the analysis for succs nodes. var oldOut = this.Outs[stmt.nodeId]; if (!oldOut || !oldOut.equals(newOut)) { if (this.useWorklist) { if (this.backwards) { AST.PredecessorsFinder.find(stmt).forEach((s: Stmt) => { this.worklist.push(s); this.visited[s.nodeId] = false; }); } else { AST.SuccessorsFinder.find(stmt).forEach((s: Stmt) => { this.worklist.push(s); this.visited[s.nodeId] = false; }); } } else { this.changed = true; } this.Outs[stmt.nodeId] = newOut; } // Attach the analysis info into the AST if (stmt instanceof ExprStmt) { this.df.updateNode(stmt, (<ExprStmt>stmt).expr); } else if (!!stmt.calcNode()) { this.df.updateNode(stmt, stmt.calcNode()); } if (!this.useWorklist) this.visitChildren(stmt); } visitComment(n: Comment) { this.visitExprHolderHolder(n); } visitFor(n: For) { this.visitExprHolderHolder(n); } visitIf(n: If) { this.visitExprHolderHolder(n); } visitElseIf(n: If) { this.visitExprHolderHolder(n); } visitForeach(n: Foreach) { this.visitExprHolderHolder(n); } visitWhile(n: While) { this.visitExprHolderHolder(n); } visitExprStmt(n: ExprStmt) { this.visitExprHolderHolder(n); } // Non-recursive version of a topological sort to order our first // visit to the Action's nodes. Recursive versions are simpler // and more elegant but crash on shallow stack mobile Safari browsers. private topologicalSort(a: Action) { var incomingEdges : { [id: number]: number; } = { }; var visited: { [id: number]: boolean; } = {}; var noIncomingEdges: { [id: number]: boolean; } = {}; var idToNode: { [id: number]: Stmt; } = {}; var numNodesVisited = 0; // Populate map with frequency of incoming edges a.body.forEach((s: Stmt) => { var todo = this.backwards ? PredecessorsFinder.unpeelAndGetLast(s) : SuccessorsFinder.unpeelAndGetFirst(s); while (todo.length > 0) { var cur = todo.shift(); if (visited[cur.nodeId]) continue; visited[cur.nodeId] = true; ++numNodesVisited; idToNode[cur.nodeId] = cur; if (!(incomingEdges[cur.nodeId] > 0)) { noIncomingEdges[cur.nodeId] = true; } var succs = this.backwards ? AST.PredecessorsFinder.find(cur) : AST.SuccessorsFinder.find(cur); succs.forEach((x: ExprStmt) => { if (incomingEdges[x.nodeId] == undefined) incomingEdges[x.nodeId] = 1; else incomingEdges[x.nodeId]++; noIncomingEdges[x.nodeId] = false; todo.push(x); }); } }); // Get nodes with no incoming edges var s: Stmt[] = []; for (var key in noIncomingEdges) { if (noIncomingEdges[key]) { var node = idToNode[key]; Util.assert(node !== undefined); s.push(node); } } // Sort while (this.worklist.length < numNodesVisited) { if (s.length == 0) { var found = false; for (var key in visited) { var cand = idToNode[key]; if (cand !== undefined && incomingEdges[key] > 0) { incomingEdges[key] = 0; s.push(cand); found = true; break; } } Util.assert(found); } var cur = s.shift(); this.worklist.push(cur); var succs = this.backwards ? AST.PredecessorsFinder.find(cur) : AST.SuccessorsFinder.find(cur); for (var i = 0; i < succs.length; ++i) { var x = succs[i]; if (--incomingEdges[x.nodeId] == 0) s.unshift(x); else if (incomingEdges[x.nodeId] > 0 && i == succs.length - 1 && s.length == 0) { // break the cycle incomingEdges[x.nodeId] = 0; s.push(x); } } } } private dfTesting(s: Stmt) { // Testing to ensure x C Succs[Preds[x]] var preds = AST.PredecessorsFinder.find(s); var succs; for (var i = 0; i < preds.length; ++i) { var elmi = preds[i]; succs = AST.SuccessorsFinder.find(elmi); var found = false; for (var j = 0; j < succs.length; ++j) { var elmj = succs[j]; if (elmj === s) found = true; } Util.assert(found); } // Testing to ensure x C Preds[Succs[x]] succs = AST.SuccessorsFinder.find(s); for (var i = 0; i < succs.length; ++i) { var elmi2 = succs[i]; preds = AST.PredecessorsFinder.find(elmi2); var found = false; for (var j = 0; j < preds.length; ++j) { var elmj2 = preds[j]; if (elmj2 === s) found = true; } Util.assert(found); } } // Entry point for the dataflow analysis. Initialize all data // structures and start visiting the statements of Action n. visitAction(n: Action) { if (n instanceof LibraryRefAction) return; if (n.isPage()) return; if (this.useWorklist) { this.worklist = []; this.topologicalSort(n); this.visited = {}; this.startNodeSet = new BitSet(); this.df.buildStartNodeSet(n, this.startNodeSet); this.startingSet = new BitSet(); this.df.buildStartingSet(n, this.startingSet); this.starting = true; while (this.worklist.length > 0) { var cur = this.worklist.shift(); if (this.visited[cur.nodeId]) continue; this.visited[cur.nodeId] = true; //this.dfTesting(cur); // Check if preds/succs are alright cur.accept(this); } } else { this.startNodeSet = new BitSet(); this.df.buildStartNodeSet(n, this.startNodeSet); this.startingSet = new BitSet(); this.df.buildStartingSet(n, this.startingSet); this.changed = true; this.starting = true; while (this.changed) { this.changed = false; n.body.forEach((c) => { c.accept(this); }); } } } } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // Dataflow Analyses // * REACHING DEFINITIONS * // Motivation: RD seeks to eliminate "ok checks" that slows down script // execution in IE and Firefox by checking if the invalid definition // reaches an expression. // Flags to activate: options.okElimination, URL ?okElimination // Manages Reaching Definitions data attached to the AST as the result // of the analysis. export class ReachingDefsMgr { constructor(public defs: Expr[], public node: Stmt) { } private getLocal(e: Token): String { if (e instanceof ThingRef) { var d = (<ThingRef>e).def; if (d instanceof LocalDef) return (<LocalDef>d).getName(); } return null; } public toString(): string { return "RD #" + this.node.nodeId + ": {" + this.defs.join() + "}"; } // The compiler will ask whether this definition may be invalid, at // this point of the program. If it may be, then it needs to put an // "ok check". public mayBeInvalid(d: LocalDef): boolean { var ret = false; this.defs.forEach((e: Expr) => { var refcall = <Call>e; if (refcall.prop() != api.core.AssignmentProp) return; refcall.args[0].flatten(api.core.TupleProp).forEach((a) => { var l = this.getLocal(a); if (l && l == d.getName()) { if (refcall.args.length > 1) { refcall.args.slice(1).forEach((val: Expr) => { // check for invalid if (val instanceof Call && (<Call>val).args.length > 0 && (<Call>val).args[0] instanceof ThingRef && (<ThingRef>(<Call>val).args[0]).data == "invalid") { ret = true; } // check for non-robust call if (val instanceof Call && !((<Call>val).prop().getFlags() & PropertyFlags.Robust)) { ret = true; } }); } } }); }); return ret; } } // ReachingDefinitions is the classic analysis to compute local variable // definitions that reaches a certain point. It is used by the compiler // to detect whether an "invalid" definition reaches some point, in which // case we need to emit an "ok check" to dynamically detect if it is truly // invalid value and stop the script before it is used. // // Main characteristics: Forward, union confluence export class ReachingDefinitions implements IDataflowAnalysis { private df: DataflowVisitor; private curNode: Stmt; private pool: SetElementsPool; constructor() { } // Convenience methods private getLocal(e: Token): LocalDef { if (e instanceof ThingRef) { var d = (<ThingRef>e).def; if (d instanceof LocalDef) return <LocalDef>d; } return null; } private getLocalName(e: Token): String { var ld = this.getLocal(e); if (ld != null) { return ld.getName(); } return null; } // Helper function to calculate the Gen set when the expression // is a variable copy. We need to copy all the definitions of the // source variable to the destination variable. private handleCopy(c: Call, _set: BitSet): boolean { var bypassGen = false; // Check for a regular copy if (c.prop() == api.core.AssignmentProp && c.args.length == 2 && c.args[0] instanceof ThingRef && c.args[1] instanceof ThingRef) { var dst = this.getLocal(c.args[0]); var src = this.getLocal(c.args[1]); if (src != null && dst != null) { _set.forEach((idx: number) => { var elm = this.pool.getElmById(idx); var refcall = <Call> elm.refNode; if (refcall) { refcall.args[0].flatten(api.core.TupleProp).forEach((a) => { var l2 = this.getLocalName(a); if (l2 == src.getName()) { var newCall = this.cloneAndChangeDst(refcall, dst); var newElm = this.pool.getElm(newCall.getText(), newCall); _set.add(newElm.id); bypassGen = true; // we dont need to keep "x = y" definitions } }); } }); } } // Check for a conditional copy (or/and) if (c.prop() == api.core.AssignmentProp && c.args.length == 2 && c.args[0] instanceof ThingRef && c.args[1] instanceof Call) { var dst = this.getLocal(c.args[0]); var srcCall = <Call> c.args[1]; if (dst != null && srcCall != null && srcCall.args.length == 2 && (srcCall.prop() == api.core.AndProp || srcCall.prop() == api.core.OrProp) && srcCall.args[1] instanceof ThingRef) { var src = this.getLocal(srcCall.args[1]); if (src != null && dst != null) { _set.forEach((idx: number) => { var elm = this.pool.getElmById(idx); var refcall = <Call> elm.refNode; if (refcall) { refcall.args[0].flatten(api.core.TupleProp).forEach((a) => { var l2 = this.getLocalName(a); if (l2 == src.getName()) { var newCall = this.cloneAndChangeDst(refcall, dst); var newElm = this.pool.getElm(newCall.getText(), newCall); _set.add(newElm.id); } }); } }); } } } return bypassGen; } // The core function of this Analysis, calculates the GEN and KILL sets // for the expression "n". Updates "_set" to reflect this. private updateSet(n: ExprHolder, _set: BitSet, genKill: boolean): void { if (!n.parsed || !(n.parsed instanceof Call)) return; var c = <Call>n.parsed; //... Traverse nodes non-recursively var exprVisitQueue: Expr[] = []; exprVisitQueue.push(c); while (exprVisitQueue.length > 0) { var cur = exprVisitQueue.shift(); if (!(cur instanceof Call)) continue; var curCall = <Call> cur; exprVisitQueue = exprVisitQueue.concat(curCall.children()); var prop = curCall.prop(); // We are only looking for assignments to local variables if (prop == api.core.AssignmentProp) { c.args[0].flatten(api.core.TupleProp).forEach((e) => { var l = this.getLocalName(e); if (l) { if (genKill) { // Generate // First check if it is a local copy expression if (!this.handleCopy(curCall, _set)) { // If it is not, put this assignment into the Out set var elm = this.pool.getElm(curCall.getText(), curCall); _set.add(elm.id); } } else { // Remove all defs of the same var from the In set _set.forEach((idx: number) => { var elm = this.pool.getElmById(idx); var refcall = <Call> elm.refNode; var remove = false; if (refcall) { refcall.args[0].flatten(api.core.TupleProp).forEach((a) => { var l2 = this.getLocalName(a); if (l2 == l) remove = true; }); } if (remove) _set.remove(idx); }); } } }); } } } // Wrappers for updateSet gen(n: ExprHolder, _set: BitSet, inSet: BitSet, isIV = false): void { this.updateSet(n, _set, true); } kill(n: ExprHolder, _set: BitSet, isIV = false): void { this.updateSet(n, _set, false); } // Extract our calculated RD set by using Set and SetElementsPool data // structure, then stick this into the AST. updateNode(s: Stmt, n: ExprHolder) { n.reachingDefs = null; var defs:Expr[] = []; this.df.Ins[s.nodeId].forEach((idx: number) => { defs.push(this.pool.getElmById(idx).refNode); }); if (defs.length > 0) n.reachingDefs = new ReachingDefsMgr(defs, s); } // Helper function to generate a fake invalid assignment. private generateInvalidAssignmentFor(l: LocalDef): Expr { var localThing = mkThing(l.getName()); (<ThingRef>localThing).def = l; var invalidThing = mkThing("invalid"); (<ThingRef>invalidThing).def = api.getKind("Invalid").singleton; return mkCall(PropertyRef.mkProp(api.core.AssignmentProp), [localThing, mkCall(PropertyRef.mkProp(api.getKind("Invalid").getProperty("number")), [invalidThing])]); } // Helper function used when handling copy expressions, necessary // when copying all the definitions of the source variable to the // destination variable. private cloneAndChangeDst(c: Call, dst: LocalDef): Expr { var args = c.args.slice(0); args[0] = mkThing(dst.getName()); (<ThingRef>args[0]).def = dst; return mkCall(c.propRef, args); } // Our start node for the action assigns all input parameters to // invalid, assuming (conservatively) that they are undefined. buildStartNodeSet(a: Action, _set: BitSet): void { a.allLocals.forEach((e: Decl) => { if (!(e instanceof LocalDef)) return; var l = (<LocalDef>e).getName(); var elm = this.pool.getElm(l, this.generateInvalidAssignmentFor(<LocalDef>e)); _set.add(elm.id); }); } // All nodes start empty in this analysis. buildStartingSet(a: Action, _set: BitSet): void { } // Entry point for this analysis. Analyze the App Action-wise. visitApp(n: App) { n.things.forEach((a: Decl) => { if (a instanceof Action && !(<Action>a).isPage()) { this.pool = new SetElementsPool(); this.df = new DataflowVisitor(this, this.pool,/*backwards*/false, /*intersection*/false, /*useWorklist*/true); this.df.dispatch(a); } }); } } // * DOMINATOR SET * // Motivation: // The Dominator Set Analysis is used only to debug intersection-confluence // analysis, since it is the simplest analysis you can build with the // intersection confluence operator. May be used as boilerplate code for // other analyses as well. // Flags to activate: no one export class DominatorsMgr { constructor(public doms: Expr[], public node: Stmt) { } public toString() { var str = "DOMS(" + this.node.nodeId + ") : {"; str += this.doms.map((e: Expr) => { return e.nodeId.toString(); }).join(); return str + "}"; } } // Dominators will compute the set of statements that dominate each // other. A statement x dominates y if all paths from the start of // the action to y includes x. // // Main characteristics: Forward, intersection confluence export class Dominators implements IDataflowAnalysis { private df: DataflowVisitor; private curNode: Stmt; private pool: SetElementsPool; constructor() { } // Our gen set is simply our own expression id. gen(n: ExprHolder, _set: BitSet, inSet: BitSet, isIV = false): void { if (!n.parsed) return; var elm = this.pool.getElm(n.parsed.nodeId.toString(), n.parsed); _set.add(elm.id); } // We do not need to kill. The intersection confluence operator takes // care of eliminating IDs that do not dominate this statement. kill(n: ExprHolder, _set: BitSet, isIV = false): void { } // Put our calculated set into the AST node of this statement updateNode(s: Stmt, n: ExprHolder) { n.dominators = null; var doms: Expr[] = []; this.df.Ins[s.nodeId].forEach((idx: number) => { doms.push(this.pool.getElmById(idx).refNode); }); if (doms.length > 0) n.dominators = new DominatorsMgr(doms, s); } // We assume no one dominates the first node. buildStartNodeSet(a: Action, _set: BitSet): void { } // All nodes must be initialized with the set that contains all // elements (allSet), otherwise we will not reach the maximum // fixed point solution. buildStartingSet(a: Action, _set: BitSet): void { _set.makeAllSet(); } // Entry point for this analysis. Analyze the App Action-wise. visitApp(n: App) { n.things.forEach((a: Decl) => { if (a instanceof Action && !(<Action>a).isPage()) { this.pool = new SetElementsPool(); this.df = new DataflowVisitor(this, this.pool,/*backwards*/false, /*intersection*/true, /*useWorklist*/true); this.df.dispatch(a); } }); } } // * USED SET ANALYSIS * // Motivation: // ReachingDefinitions is not enough to eliminate all unnecessary "ok // checks". Since all checks are done once a value is used, there are // time in which the program already used the value and thus it was // already checked, and all the remaining checks may be eliminated. // Uset set analysis calculates the set of local variables that were // already used at a certain point of the program, but were not // redefined since the last use, therefore, enabling us to remove // redundant "ok checks". // Flags to activate: options.okElimination, URL ?okElimination // Manages the information we stick into the AST statament nodes. export class UsedSetMgr { constructor(public used: Expr[], public node: Stmt) { } // Convenience methods accessible for everyone public static getLocal(e: Token): LocalDef { if (e instanceof ThingRef) { var d = (<ThingRef>e).def; if (d instanceof LocalDef) return <LocalDef>d; } return null; } public static getLocalName(e: Token): String { var ld = this.getLocal(e); if (ld != null) { return ld.getName(); } return null; } // The compiler asks whether the local ld was already used at this // point in order to eliminate redundant "ok checks". public alreadyUsed(ld: LocalDef): boolean { var res = false; this.used.forEach((e: Expr) => { var name1 = UsedSetMgr.getLocalName(e); if (name1 && name1 == ld.getName()) { res = true; } }); return res; } // Debugging public toString() { var str = "USED(" + this.node.nodeId + ") : {"; str += this.used.map((e: Expr) => { return UsedSetMgr.getLocalName(e); }).join(); return str + "}"; } } // UsedAnalysis main class // // Main characteristics: Forward, intersection confluence // NOTE: gen/kill functions are reversed in order to compensate for the // calling order of DataflowVisitor. export class UsedAnalysis implements IDataflowAnalysis { private df: DataflowVisitor; private curNode: Stmt; private pool: SetElementsPool; constructor() { } // This is actually the kill set. Since, for UsedAnalysis, we need to // kill after generation (as opposed to the common case), we reverse // the gen/kill functions. gen(n: ExprHolder, _set: BitSet, inSet: BitSet, isIV = false): void { // We are only interested in Call expressions if (!n.parsed || !(n.parsed instanceof Call)) return; // .. Traverse nodes non-recursively var c = <Call>n.parsed; var exprVisitQueue: Expr[] = []; exprVisitQueue.push(c); while (exprVisitQueue.length > 0) { var cur = exprVisitQueue.shift(); if (!(cur instanceof Call)) continue; var curCall = <Call> cur; exprVisitQueue = exprVisitQueue.concat(curCall.children()); var prop = curCall.prop(); // We are only interested in assignments if (prop == api.core.AssignmentProp) { c.args[0].flatten(api.core.TupleProp).forEach((e) => { var l = UsedSetMgr.getLocalName(e); if (l) { { // Kill all uses of the var that was defined // in this expression, since it was redefined _set.forEach((idx: number) => { var elm = this.pool.getElmById(idx); if (elm.key == l) _set.remove(idx); }); } } }); } } } // This is actually the gen set. We look for all uses of local // variables and add them to the set. kill(n: ExprHolder, _set: BitSet, isIV = false): void { if (!n.parsed) return; var exprVisitQueue: Expr[] = []; exprVisitQueue.push(n.parsed); while (exprVisitQueue.length > 0) { var e = exprVisitQueue.shift(); var refcall = <Call>e; if (!(e instanceof Call)) { if (e instanceof ThingRef) { var ed = (<ThingRef> e).def; if (ed instanceof LocalDef) { var elm = this.pool.getElm((<LocalDef>ed).getName(), e); _set.add(elm.id); } } } else { if (refcall.prop() && refcall.prop().getName() == "is invalid") { // x->is_invalid is not a use of x } else if (refcall.prop() != api.core.AssignmentProp) { exprVisitQueue = exprVisitQueue.concat(refcall.children()); } else { exprVisitQueue = exprVisitQueue.concat(refcall.args.slice(1)); } } } } // Put our calculated UsedSet into the AST, so the compiler can query // later. updateNode(s: Stmt, n: ExprHolder) { n.usedSet = null; var usedSet: Expr[] = []; this.df.Ins[s.nodeId].forEach((idx: number) => { usedSet.push(this.pool.getElmById(idx).refNode); }); if (usedSet.length > 0) n.usedSet = new UsedSetMgr(usedSet, s); } // Our start node begins with no used variables. buildStartNodeSet(a: Action, _set: BitSet): void { } // All remaining nodes are initialized with allSet, necessary for // intersection analyses. buildStartingSet(a: Action, _set: BitSet): void { _set.makeAllSet(); } // Entry point for this analysis. Analyze the App Action-wise. visitApp(n: App) { n.things.forEach((a: Decl) => { if (a instanceof Action && !(<Action>a).isPage()) { this.pool = new SetElementsPool(); this.df = new DataflowVisitor(this, this.pool,/*backwards*/false, /*intersection*/true, /*useWorklist*/true); this.df.dispatch(a); } }); } } // * AVAILABLE EXPRESSIONS * // Motivation: // The Available Expressions classic analysis is used to detect // opportunities for common subexpression elimination. Since the compiler // may separate an action into several steps, each one being a different // native JavaScript function, the JIT engine will miss optimization // opportunities beyond the step granularity, and this analysis can help // in these cases by performing global common subexpression elimination. // Flags to activate: options.commonSubexprElim, URL ?commonSubexprElim export class AvailableExpressionsMgr { constructor(public aeSet: Expr[], public node: Stmt) { } // Helper method to check if the entire expression is idempotent, // which means there is no effect in recalculating it or not. private hasOnlyIdempotentNodes(e: Expr) { var exprVisitQueue: Expr[] = []; exprVisitQueue.push(e); while (exprVisitQueue.length > 0) { var e = exprVisitQueue.shift(); var refcall = <Call>e; if (!(e instanceof Call)) { if (!(e instanceof Literal || (e instanceof ThingRef && (<ThingRef>e).def.nodeType() == "localDef"))) return false; } else { if (refcall.prop() != api.core.AssignmentProp && refcall.prop().getFlags() & PropertyFlags.Idempotent) { exprVisitQueue = exprVisitQueue.concat(refcall.children()); } else { return false; } } } return true; } // The compiler will ask if this expression was already calculated at // this point and if they are idempotent. Returns the set of all such // expressions. public checkForIdenticalExpressions(e: Expr): Expr[]{ var res: Expr[] = []; if (e == undefined) return; this.aeSet.forEach((ae: Expr) => { if (ae.toString() == e.toString() && this.hasOnlyIdempotentNodes(e)) res.push(ae); }); return res; } // Debugging public toString() { var str = "AE(" + this.node.nodeId + ") : {"; str += this.aeSet.join(); return str + "}"; } } // Main characteriscs: Forward, intersection confluence // NOTE: gen/kill functions are reversed in order to compensate for the // calling order of DataflowVisitor. export class AvailableExpressions implements IDataflowAnalysis { private df: DataflowVisitor; private curNode: Stmt; private pool: SetElementsPool; constructor() { } // Helper function to detect whether expression "e" uses local variable // "l" private usesLocal(e: Expr, l: String): boolean { var exprVisitQueue: Expr[] = []; exprVisitQueue.push(e); while (exprVisitQueue.length > 0) { var e = exprVisitQueue.shift(); var refcall = <Call>e; if (!(e instanceof Call)) { if (UsedSetMgr.getLocalName(e) == l) return true; } else { if (refcall.prop() != api.core.AssignmentProp) { exprVisitQueue = exprVisitQueue.concat(refcall.children()); } else { exprVisitQueue = exprVisitQueue.concat(refcall.args.slice(1)); } } } return false; } // This is actually the kill set. Since, for AvailableExpressions, we // need to kill after generation (as opposed to the common case), we // reverse the gen/kill functions. gen(n: ExprHolder, _set: BitSet, inSet: BitSet, isIV = false): void { if (isIV) return; if (!n.parsed || !(n.parsed instanceof Call)) return; var c = <Call>n.parsed; var exprVisitQueue: Expr[] = []; exprVisitQueue.push(c); while (exprVisitQueue.length > 0) { var cur = exprVisitQueue.shift(); if (!(cur instanceof Call)) continue; var curCall = <Call> cur; exprVisitQueue = exprVisitQueue.concat(curCall.children()); var prop = curCall.prop(); if (prop == api.core.AssignmentProp) { c.args[0].flatten(api.core.TupleProp).forEach((e) => { var l = UsedSetMgr.getLocalName(e); if (l) { { // Kill all expressions that the same var _set.forEach((idx: number) => { var elm = this.pool.getElmById(idx); if (this.usesLocal(elm.refNode, l)) _set.remove(idx); }); } } }); } } } // This is actually the gen set. We look for all uses of local // variables and add them to the set. kill(n: ExprHolder, _set: BitSet, isIV = false): void { if (isIV) return; if (!n.parsed) return; var exprVisitQueue: Expr[] = []; exprVisitQueue.push(n.parsed); while (exprVisitQueue.length > 0) { var e = exprVisitQueue.shift(); var refcall = <Call>e; if (e instanceof Call) { if (refcall.prop() != api.core.AssignmentProp) { var elm = this.pool.getElm(refcall.toString(), refcall); _set.add(elm.id); exprVisitQueue = exprVisitQueue.concat(refcall.args.slice(1)); } else { exprVisitQueue = exprVisitQueue.concat(refcall.children()); } } } } // Put our calculated UsedSet into the AST, so the compiler can query // later. updateNode(s: Stmt, n: ExprHolder) { n.aeSet = null; var aeSet: Expr[] = []; this.df.Ins[s.nodeId].forEach((idx: number) => { aeSet.push(this.pool.getElmById(idx).refNode); }); if (aeSet.length > 0) n.aeSet = new AvailableExpressionsMgr(aeSet, s); } // Our start node begins with no available expressions. buildStartNodeSet(a: Action, _set: BitSet): void { } // All remaining nodes are initialized with allSet, necessary for // intersection analyses. buildStartingSet(a: Action, _set: BitSet): void { _set.makeAllSet(); } // Entry point for this analysis. Analyze the App Action-wise. visitApp(n: App) { n.things.forEach((a: Decl) => { if (a instanceof Action && !(<Action>a).isPage()) { this.pool = new SetElementsPool(); this.df = new DataflowVisitor(this, this.pool,/*backwards*/false, /*intersection*/true, /*useWorklist*/true); this.df.dispatch(a); } }); } } // * CONSTANT FOLDING/PROPAGATION FRAMEWORK * // Motivation: // This analysis computes the set of locals defined as constants, yielding // pairs <local, constant value>, and also folds an idempotent expression // that works with constants. A pair <local, constant value> may be the // result of many folded expressions. As with CSE, since the compiler // may separate an action into several steps, each one being a different // native JavaScript function, the JIT engine will miss optimization // opportunities beyond the step granularity, and this analysis can help // in these cases by performing global constant folding. // Flags to activate: options.constantPropagation, URL ?constantPropagation // Manages the information we stick into the AST statement nodes. It also // has the logic to perform folding for selected idempotent operators. export class ConstantPropagationMgr { constructor(public constantSet: Expr[], public node: Stmt) { } // Helper function. // Get the constant value of the local "d" by using the information // computed for this point of the program. public getLiteralValueFor(d: LocalDef) { var res = null; this.constantSet.forEach((e: Expr) => { if (e instanceof Call && (<Call>e).prop() == api.core.AssignmentProp && (<Call>e).args.length == 2 && (<Call>e).args[0] instanceof ThingRef && (<ThingRef>((<Call>e).args[0])).def instanceof LocalDef && (<LocalDef>((<ThingRef>((<Call>e).args[0])).def)).getName() == d.getName() && (<Call>e).args[1] instanceof Literal && (<Literal>((<Call>e).args[1])).data != null) res = (<Literal>((<Call>e).args[1])).data; }); return res; } // Helper function. // Avoids using JavaScript's "eval" and implement our own function // to evaluate expressions. Return null if we don't know how to // calculate this at compile time. public static evaluate(c: Call, args: any[]) { if (c.prop().getCategory() == PropertyCategory.Builtin) { if (c.prop().getSpecialApply() == "+") return args[0] + args[1]; else if (c.prop().getSpecialApply() == "-") return args[0] - args[1]; else if (c.prop().getSpecialApply() == "/") return args[0] / args[1]; else if (c.prop().getSpecialApply() == "*") return args[0] * args[1]; else if (c.prop().getSpecialApply() == "===") return args[0] === args[1]; } return null; } // Entry point for expression evaluation. By using the information // available at this point of the program (pairs <local, value>), // tries to evaluate the result of the expression "e". If it is // possible to know this at compile time, returns the value, // otherwise returns null. public precomputeLiteralExpression(e: Expr) { var visitExpr = (exp: Expr) => { var refcall = <Call>exp; if (!(exp instanceof Call)) { if (exp instanceof Literal) return (<Literal>exp).data; if (exp instanceof ThingRef && (<ThingRef>exp).def.nodeType() == "localDef" && this.getLiteralValueFor(<LocalDef>(<ThingRef>exp).def) != null) return this.getLiteralValueFor(<LocalDef>(<ThingRef>exp).def); } else { if (refcall.prop() != api.core.AssignmentProp && refcall.prop().getFlags() & PropertyFlags.Idempotent) { var values = refcall.children().map((ea: Expr) => visitExpr(ea)); var hasNull = false; values.forEach((ea: Expr) => { if (ea == null) hasNull = true; }); if (!hasNull) { return ConstantPropagationMgr.evaluate(refcall, values); } } return null; } }; return visitExpr(e); } // Debugging purposes public toString() { var str = "CP(" + this.node.nodeId + ") : {"; str += this.constantSet.join(); return str + "}"; } } // ConstantPropagation will compute gen/kill sets to achieve the maximum // number of constant folding/propagation for locals of the action. It // uses ConstantPropagationMgr methods to help fold expressions with // literal leaves, which are also used by the compiler when emitting // code. This differs from the other analysis because they leave their // Manager to be used solely by the compiler. // // Main characteristics: Forward, intersection confluence export class ConstantPropagation implements IDataflowAnalysis { private df: DataflowVisitor; private curNode: Stmt; private pool: SetElementsPool; constructor() { } // Helper function to generate a fake assignment of literal "value" // to local "l". We need to generate these assingments to express // the result of folding, since they don't really exist in the original // source code. private generateAssignmentFor(l: LocalDef, value: any): Expr { var localThing = mkThing(l.getName()); (<ThingRef>localThing).def = l; var literal = mkLit(value); return mkCall(PropertyRef.mkProp(api.core.AssignmentProp), [localThing, literal]); } // Helper function to handle copy assignments private cloneAndChangeDst(c: Call, dst: LocalDef): Expr { var args = c.args.slice(0); args[0] = mkThing(dst.getName()); (<ThingRef>args[0]).def = dst; return mkCall(c.propRef, args); } // Convenience methods private getLocal(e: Token): LocalDef { if (e instanceof ThingRef) { var d = (<ThingRef>e).def; if (d instanceof LocalDef) return <LocalDef>d; } return null; } private getLocalName(e: Token): String { var ld = this.getLocal(e); if (ld != null) { return ld.getName(); } return null; } // Handle copy. Copies the literal value of src to dst. private handleCopy(c: Call, _set: BitSet): boolean { var bypassGen = false; // Check for a regular copy if (c.prop() == api.core.AssignmentProp && c.args.length == 2 && c.args[0] instanceof ThingRef && c.args[1] instanceof ThingRef) { var dst = this.getLocal(c.args[0]); var src = this.getLocal(c.args[1]); if (src != null && dst != null) { // Find the literal value of src, if any _set.forEach((idx: number) => { var elm = this.pool.getElmById(idx); var refcall = <Call> elm.refNode; if (refcall) { refcall.args[0].flatten(api.core.TupleProp).forEach((a) => { var l2 = this.getLocalName(a); if (l2 == src.getName()) { // Found // Copy to the destination generating a fake assingment var newCall = this.cloneAndChangeDst(refcall, dst); var newElm = this.pool.getElm(newCall.getText(), newCall); _set.add(newElm.id); bypassGen = true; } }); } }); } } return bypassGen; } // Entry point for generating/killing elements. private updateSet(n: ExprHolder, _set: BitSet, genKill: boolean): void { if (!n.parsed || !(n.parsed instanceof Call)) return; var c = <Call>n.parsed; // Traverse all nodes of the expression non-recursively var exprVisitQueue: Expr[] = []; exprVisitQueue.push(c); while (exprVisitQueue.length > 0) { var cur = exprVisitQueue.shift(); if (!(cur instanceof Call)) continue; var curCall = <Call> cur; exprVisitQueue = exprVisitQueue.concat(curCall.children()); var prop = curCall.prop(); // Look for assignments if (prop == api.core.AssignmentProp) { c.args[0].flatten(api.core.TupleProp).forEach((e) => { var l = this.getLocalName(e); if (l) { if (genKill) { // Generate if (!this.handleCopy(curCall, _set)) { // Try to fold the src expression with the information we currently have // at this point and, if successful, assign it to the local var lit = (new ConstantPropagationMgr(this.generateCpSet(_set), null)).precomputeLiteralExpression(c.args[1]); if (lit != null) { var assgn = this.generateAssignmentFor(this.getLocal(e), lit); var elm = this.pool.getElm(assgn.getText(), assgn); _set.add(elm.id); } } } else { /// Kill all locals that this expression redefined _set.forEach((idx: number) => { var elm = this.pool.getElmById(idx); var refcall = <Call> elm.refNode; var remove = false; if (refcall) { refcall.args[0].flatten(api.core.TupleProp).forEach((a) => { var l2 = this.getLocalName(a); if (l2 == l) remove = true; }); } if (remove) _set.remove(idx); }); } } }); } } } // Wrappers to updateSet gen(n: ExprHolder, _set: BitSet, inSet: BitSet, isIV = false): void { if (!isIV) this.updateSet(n, _set, true); } kill(n: ExprHolder, _set: BitSet, isIV = false): void { if (!isIV) this.updateSet(n, _set, false); } // Helper function to compute the information the // ConstantPropagationMgr instance needs, converting the elements // of the BitSet into a regular JavaScript object array. private generateCpSet(_set: BitSet): Expr[] { var cpSet: Expr[] = []; _set.forEach((idx: number) => { cpSet.push(this.pool.getElmById(idx).refNode); }); return cpSet; } // Update the AST with the info we calculated for this node, // use generateCpSet updateNode(s: Stmt, n: ExprHolder) { var cpSet = this.generateCpSet(this.df.Ins[s.nodeId]); n.cpSet = new ConstantPropagationMgr(cpSet, s); } // We start with no definitions buildStartNodeSet(a: Action, _set: BitSet): void { } // Sets are initialized full buildStartingSet(a: Action, _set: BitSet): void { _set.makeAllSet(); } // Entry point for this analysis. Analyze the App Action-wise. visitApp(n: App) { n.things.forEach((a: Decl) => { if (a instanceof Action && !(<Action>a).isPage()) { this.pool = new SetElementsPool(); this.df = new DataflowVisitor(this, this.pool,/*backwards*/false, /*intersection*/true, /*useWorklist*/true); this.df.dispatch(a); } }); } } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // Non-Dataflow Analyses // * INLINE ANALYSIS * // Motivation: // The inline analysis looks for actions that can be inlined and flags them // to the compiler. This means these actions will be called as native // JavaScript functions in the final code, bypassing the interpreter and // saving time. // Flags to activate: options.inlining or URL: ?inlining export class CallGraphNode { constructor(public action: Action, public succs: CallGraphNode[], public preds: CallGraphNode[], public canInline: boolean = false) { } public addSucc(succ: CallGraphNode) { for (var i = 0; i < this.succs.length; ++i) { if (this.succs[i] == succ) return; } this.succs.push(succ); } public addPred(pred: CallGraphNode) { for (var i = 0; i < this.preds.length; ++i) { if (this.preds[i] == pred) return; } this.preds.push(pred); } } // InlineAnalysis (multi-level) // // Step1: Build a callgraph for the App using the // visitor pattern. While it is visiting each Action, it checks not only // for calls that helps to build the callgraph, but also for statements // that precludes an action from being inlined (i.e. loop statements). // // Step2: Afterwards, it sorts the callgraph using topological // sort, allowing it to easily perform a bottom-up traversal of the tree. // Then, it marks actions as inlined if they satisfy some // predefined properties in "actionHasDesiredProperties()", if it doesn't // have any unwanted statements and finally if all the actions it calls // are also inlined. export class InlineAnalysis extends NodeVisitor { public hasChanged = false; private nodeMap: { [s: string]: CallGraphNode; }; private nodes: CallGraphNode[]; private nowVisiting: CallGraphNode; constructor() { super(); this.nodes = []; this.nodeMap = {}; } visitAstNode(n: AstNode) { this.visitChildren(n); } visitExprHolder(n: ExprHolder) { if (n.parsed) this.dispatch(n.parsed); this.visitChildren(n); } // Unwanted statements in an inlined action visitFor(n: For) { this.nowVisiting.canInline = false; this.visitChildren(n); } visitForeach(n: Foreach) { this.nowVisiting.canInline = false; this.visitChildren(n); } visitWhile(n: While) { this.nowVisiting.canInline = false; this.visitChildren(n); } visitBox(n: Box) { this.nowVisiting.canInline = false; this.visitChildren(n); } visitForeachClause(n: ForeachClause) { this.nowVisiting.canInline = false; this.visitChildren(n); } visitInlineActions(n: InlineActions) { this.nowVisiting.canInline = false; this.visitChildren(n); } visitInlineAction(n: InlineAction) { this.nowVisiting.canInline = false; this.visitChildren(n); } visitOptionalParameter(n: OptionalParameter) { this.nowVisiting.canInline = false; this.visitChildren(n); } visitContinue(n: Call) { this.nowVisiting.canInline = false; this.visitChildren(n); } visitBreak(n: Call) { this.nowVisiting.canInline = false; this.visitChildren(n); } visitReturn(n: Call) { this.nowVisiting.canInline = false; this.visitChildren(n); } // Build a new edge of the callgraph if calling another action visitCall(n: Call) { var a = n.calledAction(); var prop = n.prop(); // Check for unwanted calls if (prop && prop.getCategory() == PropertyCategory.Library) { this.nowVisiting.canInline = false; return; } if (prop && prop.shouldPauseInterperter()) { this.nowVisiting.canInline = false; return; } if (prop && prop.getName() == "run" && prop.parentKind.isAction) { this.nowVisiting.canInline = false; return; } if (a == null) { this.visitChildren(n); return; } if (a instanceof LibraryRefAction) { this.nowVisiting.canInline = false; return; } // This is a call to another action inside this App, create the // callgraph node if not available and create the edge to it. var cgNode = this.nodeMap[["a_", a.getName()].join("")]; if (cgNode == undefined) { cgNode = new CallGraphNode(a, [], []); this.nodeMap[["a_", a.getName()].join("")] = cgNode; this.nodes.push(cgNode); } this.nowVisiting.addSucc(cgNode); cgNode.addPred(this.nowVisiting); this.visitChildren(n); } // Check if this action can be inlined (apart from the callgraph // analysis) actionHasDesiredProperties(a: Action) { return (a.isNormalAction() && a.isPrivate && !a.isLambda && !a.isTest() && a.isAtomic && a.getOutParameters().length <= 1); } // Create a new callgraph node to this action and start visiting it. visitAction(n: Action) { if (n instanceof LibraryRefAction) return; var cgNode = this.nodeMap[["a_", n.getName()].join("")]; if (cgNode == undefined) { cgNode = new CallGraphNode(n, [], []); this.nodeMap[["a_", n.getName()].join("")] = cgNode; this.nodes.push(cgNode); } this.nowVisiting = cgNode; this.nowVisiting.canInline = true; this.visitChildren(n); if (this.nowVisiting.canInline && this.actionHasDesiredProperties(n) && this.nowVisiting.succs.length == 0) { n.canBeInlined = true; } } // Sort the callgraph node to allow an easy bottom-up traversal of // of the call tree. public topologicalSort() : CallGraphNode[] { var traversalOrder : CallGraphNode[] = []; var visited : { [idx: number] : boolean; } = <any>{}; var indexMap: { [name: string] : number;} = {}; for (var i = 0; i < this.nodes.length; ++i) { visited[i] = false; indexMap[["a_", this.nodes[i].action.getName()].join("")] = i; } var visit = (cur: number) => { if (visited[cur]) return; visited[cur] = true; for (var i = 0; i < this.nodes[cur].preds.length; ++i) { visit(indexMap[["a_", this.nodes[cur].preds[i].action.getName()].join("")]); } traversalOrder.unshift(this.nodes[cur]); } for (var i = 0; i < this.nodes.length; ++i) { visit(i); } return traversalOrder; } // Entry point for the inline analysis. public nestedInlineAnalysis() { var sorted = this.topologicalSort(); for (var i = 0; i < sorted.length; ++i) { if (sorted[i].action.canBeInlined) continue; var canInline = this.actionHasDesiredProperties(sorted[i].action) && sorted[i].canInline; if (!canInline) continue; for (var j = 0; j < sorted[i].succs.length; ++j) { if (!sorted[i].succs[j].action.canBeInlined) canInline = false; } sorted[i].action.canBeInlined = canInline; } } // Debugging purposes public dumpCallGraph() { for (var i = 0; i < this.nodes.length; ++i) { if (this.nodes[i].action.canBeInlined) Util.log("Node " + i + ": " + this.nodes[i].action.toString() + " [can be inlined]"); else Util.log("Node " + i + ": " + this.nodes[i].action.toString()); for (var j = 0; j < this.nodes[i].succs.length; ++j) { Util.log(" |-> calls " + this.nodes[i].succs[j].action.toString()); } } } } }
the_stack
import * as assert from "@esfx/internal-assert"; import { Equaler } from "@esfx/equatable"; import { Grouping } from "@esfx/iter-grouping"; import { Lookup } from "@esfx/iter-lookup"; import { identity, tuple } from '@esfx/fn'; import { empty } from './queries'; import { union, map, defaultIfEmpty } from './subqueries'; import { createGroupings } from './internal/utils'; class GroupJoinIterable<O, I, K, R> implements Iterable<R> { private _outer: Iterable<O>; private _inner: Iterable<I>; private _outerKeySelector: (element: O) => K; private _innerKeySelector: (element: I) => K; private _resultSelector: (outer: O, inner: Iterable<I>) => R; private _keyEqualer?: Equaler<K> constructor(outer: Iterable<O>, inner: Iterable<I>, outerKeySelector: (element: O) => K, innerKeySelector: (element: I) => K, resultSelector: (outer: O, inner: Iterable<I>) => R, keyEqualer?: Equaler<K>) { this._outer = outer; this._inner = inner; this._outerKeySelector = outerKeySelector; this._innerKeySelector = innerKeySelector; this._resultSelector = resultSelector; this._keyEqualer = keyEqualer; } *[Symbol.iterator](): Iterator<R> { const outerKeySelector = this._outerKeySelector; const resultSelector = this._resultSelector; const map = createGroupings(this._inner, this._innerKeySelector, identity, this._keyEqualer); for (const outerElement of this._outer) { const outerKey = outerKeySelector(outerElement); const innerElements = map.get(outerKey) || empty<I>(); yield resultSelector(outerElement, innerElements); } } } /** * Creates a grouped `Iterable` for the correlated elements between an outer `Iterable` object and an inner `Iterable` object. * * @param outer An `Iterable` object. * @param inner An `Iterable` object. * @param outerKeySelector A callback used to select the key for an element in `outer`. * @param innerKeySelector A callback used to select the key for an element in `inner`. * @param resultSelector A callback used to select the result for the correlated elements. * @param keyEqualer An `Equaler` object used to compare key equality. * @category Join */ export function groupJoin<O, I, K, R>(outer: Iterable<O>, inner: Iterable<I>, outerKeySelector: (element: O) => K, innerKeySelector: (element: I) => K, resultSelector: (outer: O, inner: Iterable<I>) => R, keyEqualer?: Equaler<K>): Iterable<R> { assert.mustBeIterableObject(outer, "outer"); assert.mustBeIterableObject(inner, "inner"); assert.mustBeFunction(outerKeySelector, "outerKeySelector"); assert.mustBeFunction(innerKeySelector, "innerKeySelector"); assert.mustBeFunction(resultSelector, "resultSelector"); assert.mustBeTypeOrUndefined(Equaler.hasInstance, keyEqualer, "keyEqualer"); return new GroupJoinIterable(outer, inner, outerKeySelector, innerKeySelector, resultSelector, keyEqualer); } class JoinIterable<O, I, K, R> implements Iterable<R> { private _outer: Iterable<O>; private _inner: Iterable<I>; private _outerKeySelector: (element: O) => K; private _innerKeySelector: (element: I) => K; private _resultSelector: (outer: O, inner: I) => R; private _keyEqualer?: Equaler<K> constructor(outer: Iterable<O>, inner: Iterable<I>, outerKeySelector: (element: O) => K, innerKeySelector: (element: I) => K, resultSelector: (outer: O, inner: I) => R, keyEqualer?: Equaler<K>) { this._outer = outer; this._inner = inner; this._outerKeySelector = outerKeySelector; this._innerKeySelector = innerKeySelector; this._resultSelector = resultSelector; this._keyEqualer = keyEqualer; } *[Symbol.iterator](): Iterator<R> { const outerKeySelector = this._outerKeySelector; const resultSelector = this._resultSelector; const map = createGroupings(this._inner, this._innerKeySelector, identity, this._keyEqualer); for (const outerElement of this._outer) { const outerKey = outerKeySelector(outerElement); const innerElements = map.get(outerKey); if (innerElements != undefined) { for (const innerElement of innerElements) { yield resultSelector(outerElement, innerElement); } } } } } /** * Creates an `Iterable` for the correlated elements of two `Iterable` objects. * * @param outer An `Iterable` object. * @param inner An `Iterable` object. * @param outerKeySelector A callback used to select the key for an element in `outer`. * @param innerKeySelector A callback used to select the key for an element in `inner`. * @param resultSelector A callback used to select the result for the correlated elements. * @param keyEqualer An `Equaler` object used to compare key equality. * @category Join */ export function join<O, I, K, R>(outer: Iterable<O>, inner: Iterable<I>, outerKeySelector: (element: O) => K, innerKeySelector: (element: I) => K, resultSelector: (outer: O, inner: I) => R, keyEqualer?: Equaler<K>): Iterable<R> { assert.mustBeIterableObject(outer, "outer"); assert.mustBeIterableObject(inner, "inner"); assert.mustBeFunction(outerKeySelector, "outerKeySelector"); assert.mustBeFunction(innerKeySelector, "innerKeySelector"); assert.mustBeFunction(resultSelector, "resultSelector"); assert.mustBeTypeOrUndefined(Equaler.hasInstance, keyEqualer, "keyEqualer"); return new JoinIterable(outer, inner, outerKeySelector, innerKeySelector, resultSelector, keyEqualer); } function selectGroupingKey<K, V>(grouping: Grouping<K, V>) { return grouping.key; } class FullJoinIterable<O, I, K, R> implements Iterable<R> { private _outer: Iterable<O>; private _inner: Iterable<I>; private _outerKeySelector: (element: O) => K; private _innerKeySelector: (element: I) => K; private _resultSelector: (outer: O | undefined, inner: I | undefined) => R; private _keyEqualer?: Equaler<K> constructor(outer: Iterable<O>, inner: Iterable<I>, outerKeySelector: (element: O) => K, innerKeySelector: (element: I) => K, resultSelector: (outer: O | undefined, inner: I | undefined) => R, keyEqualer?: Equaler<K>) { this._outer = outer; this._inner = inner; this._outerKeySelector = outerKeySelector; this._innerKeySelector = innerKeySelector; this._resultSelector = resultSelector; this._keyEqualer = keyEqualer; } *[Symbol.iterator](): Iterator<R> { const resultSelector = this._resultSelector; const outerLookup = new Lookup<K, O>(createGroupings(this._outer, this._outerKeySelector, identity, this._keyEqualer)); const innerLookup = new Lookup<K, I>(createGroupings(this._inner, this._innerKeySelector, identity, this._keyEqualer)); const keys = union(map(outerLookup, selectGroupingKey), map(innerLookup, selectGroupingKey), this._keyEqualer); for (const key of keys) { const outer = defaultIfEmpty<O | undefined>(outerLookup.get(key), undefined); const inner = defaultIfEmpty<I | undefined>(innerLookup.get(key), undefined); for (const outerElement of outer) { for (const innerElement of inner) { yield resultSelector(outerElement, innerElement); } } } } } /** * Creates an `Iterable` for the correlated elements between an outer `Iterable` object and an inner * `Iterable` object. * * @param outer An `Iterable` object. * @param inner An `Iterable` object. * @param outerKeySelector A callback used to select the key for an element in `outer`. * @param innerKeySelector A callback used to select the key for an element in `inner`. * @param resultSelector A callback used to select the result for the correlated elements. * @param keyEqualer An `Equaler` object used to compare key equality. * @category Join */ export function fullJoin<O, I, K, R>(outer: Iterable<O>, inner: Iterable<I>, outerKeySelector: (element: O) => K, innerKeySelector: (element: I) => K, resultSelector: (outer: O | undefined, inner: I | undefined) => R, keyEqualer?: Equaler<K>): Iterable<R> { assert.mustBeIterableObject(outer, "outer"); assert.mustBeIterableObject(inner, "inner"); assert.mustBeFunction(outerKeySelector, "outerKeySelector"); assert.mustBeFunction(innerKeySelector, "innerKeySelector"); assert.mustBeFunction(resultSelector, "resultSelector"); assert.mustBeTypeOrUndefined(Equaler.hasInstance, keyEqualer, "keyEqualer"); return new FullJoinIterable(outer, inner, outerKeySelector, innerKeySelector, resultSelector, keyEqualer); } class ZipIterable<T, U, R> implements Iterable<R> { private _left: Iterable<T>; private _right: Iterable<U>; private _selector: (left: T, right: U) => R; constructor(left: Iterable<T>, right: Iterable<U>, selector: (left: T, right: U) => R) { this._left = left; this._right = right; this._selector = selector; } *[Symbol.iterator](): Iterator<R> { const selector = this._selector; const leftIterator = this._left[Symbol.iterator](); let leftResult: IteratorResult<T> | undefined; try { const rightIterator = this._right[Symbol.iterator](); let rightResult: IteratorResult<U> | undefined; try { for (;;) { leftResult = leftIterator.next(); rightResult = rightIterator.next(); if (leftResult.done || rightResult.done) break; yield selector(leftResult.value, rightResult.value); } } finally { if (rightResult && !rightResult.done) { rightIterator.return?.(); } } } finally { if (leftResult && !leftResult.done) { leftIterator.return?.(); } } } } /** * Creates a subquery that combines two `Iterable` objects by combining elements * in tuples. * * @param left A `Iterable`. * @param right A `Iterable`. * @category Join */ export function zip<T, U>(left: Iterable<T>, right: Iterable<U>): Iterable<[T, U]>; /** * Creates a subquery that combines two `Iterable` objects by combining elements * using the supplied callback. * * @param left A `Iterable`. * @param right A `Iterable`. * @param selector A callback used to combine two elements. * @category Join */ export function zip<T, U, R>(left: Iterable<T>, right: Iterable<U>, selector: (left: T, right: U) => R): Iterable<R>; export function zip<T, U, R>(left: Iterable<T>, right: Iterable<U>, selector: (left: T, right: U) => [T, U] | R = tuple): Iterable<[T, U] | R> { assert.mustBeIterableObject(left, "left"); assert.mustBeIterableObject(right, "right"); assert.mustBeFunction(selector, "selector"); return new ZipIterable(left, right, selector); }
the_stack
import { WebAPICallResult } from '../WebClient'; export type RtmStartResponse = WebAPICallResult & { ok?: boolean; self?: Self; team?: Team; accept_tos_url?: string; latest_event_ts?: string; channels?: Channel[]; groups?: Group[]; ims?: Im[]; cache_ts?: number; mobile_app_requires_upgrade?: boolean; read_only_channels?: string[]; non_threadable_channels?: string[]; thread_only_channels?: string[]; can_manage_shared_channels?: boolean; subteams?: Subteams; dnd?: Dnd; users?: User[]; cache_version?: string; cache_ts_version?: string; bots?: Bot[]; url?: string; is_europe?: boolean; error?: string; needed?: string; provided?: string; }; export interface Bot { id?: string; deleted?: boolean; name?: string; updated?: number; app_id?: string; icons?: BotIcons; is_workflow_bot?: boolean; team_id?: string; } export interface BotIcons { image_36?: string; image_48?: string; image_72?: string; } export interface Channel { id?: string; name?: string; is_channel?: boolean; created?: number; is_archived?: boolean; is_general?: boolean; unlinked?: number; creator?: string; name_normalized?: string; is_shared?: boolean; is_org_shared?: boolean; has_pins?: boolean; is_member?: boolean; is_private?: boolean; is_mpim?: boolean; previous_names?: string[]; priority?: number; last_read?: string; members?: string[]; topic?: Purpose; purpose?: Purpose; is_group?: boolean; is_im?: boolean; is_ext_shared?: boolean; shared_team_ids?: string[]; internal_team_ids?: string[]; connected_team_ids?: string[]; pending_shared?: string[]; pending_connected_team_ids?: string[]; is_pending_ext_shared?: boolean; conversation_host_id?: string; } export interface Purpose { value?: string; creator?: string; last_set?: number; } export interface Dnd { dnd_enabled?: boolean; next_dnd_start_ts?: number; next_dnd_end_ts?: number; snooze_enabled?: boolean; } export interface Group { id?: string; name?: string; name_normalized?: string; is_group?: boolean; created?: number; creator?: string; is_archived?: boolean; is_mpim?: boolean; is_open?: boolean; is_read_only?: boolean; is_thread_only?: boolean; parent_group?: string; topic?: Purpose; purpose?: Purpose; last_read?: string; latest?: Latest; unread_count?: number; unread_count_display?: number; priority?: number; } export interface Latest { client_msg_id?: string; type?: string; subtype?: string; team?: string; user?: string; username?: string; parent_user_id?: string; text?: string; topic?: string; root?: Root; upload?: boolean; display_as_bot?: boolean; bot_id?: string; bot_link?: string; bot_profile?: Bot; thread_ts?: string; ts?: string; icons?: LatestIcons; edited?: Edited; } export interface Edited { user?: string; ts?: string; } export interface LatestIcons { emoji?: string; image_36?: string; image_48?: string; image_64?: string; image_72?: string; } export interface Root { text?: string; user?: string; parent_user_id?: string; username?: string; team?: string; bot_id?: string; mrkdwn?: boolean; type?: string; subtype?: string; thread_ts?: string; icons?: LatestIcons; bot_profile?: Bot; edited?: Edited; reply_count?: number; reply_users_count?: number; latest_reply?: string; subscribed?: boolean; last_read?: string; unread_count?: number; ts?: string; } export interface Im { id?: string; created?: number; is_archived?: boolean; is_im?: boolean; is_org_shared?: boolean; user?: string; has_pins?: boolean; last_read?: string; is_open?: boolean; priority?: number; } export interface Self { id?: string; name?: string; prefs?: SelfPrefs; created?: number; first_login?: number; manual_presence?: string; } export interface SelfPrefs { user_colors?: string; color_names_in_list?: boolean; email_alerts?: string; email_alerts_sleep_until?: number; email_tips?: boolean; email_weekly?: boolean; email_offers?: boolean; email_research?: boolean; email_developer?: boolean; welcome_message_hidden?: boolean; search_sort?: string; search_file_sort?: string; search_channel_sort?: string; search_people_sort?: string; expand_inline_imgs?: boolean; expand_internal_inline_imgs?: boolean; expand_snippets?: boolean; posts_formatting_guide?: boolean; seen_welcome_2?: boolean; seen_ssb_prompt?: boolean; spaces_new_xp_banner_dismissed?: boolean; search_only_my_channels?: boolean; search_only_current_team?: boolean; search_hide_my_channels?: boolean; search_only_show_online?: boolean; search_hide_deactivated_users?: boolean; emoji_mode?: string; emoji_use?: string; emoji_use_org?: string; has_invited?: boolean; has_uploaded?: boolean; has_created_channel?: boolean; has_created_channel_section?: boolean; has_searched?: boolean; search_exclude_channels?: string; messages_theme?: string; webapp_spellcheck?: boolean; no_joined_overlays?: boolean; no_created_overlays?: boolean; dropbox_enabled?: boolean; seen_domain_invite_reminder?: boolean; seen_member_invite_reminder?: boolean; mute_sounds?: boolean; arrow_history?: boolean; tab_ui_return_selects?: boolean; obey_inline_img_limit?: boolean; require_at?: boolean; ssb_space_window?: string; mac_ssb_bounce?: string; mac_ssb_bullet?: boolean; expand_non_media_attachments?: boolean; show_typing?: boolean; pagekeys_handled?: boolean; last_snippet_type?: string; display_real_names_override?: number; display_display_names?: boolean; time24?: boolean; enter_is_special_in_tbt?: boolean; msg_input_send_btn?: boolean; msg_input_send_btn_auto_set?: boolean; msg_input_sticky_composer?: boolean; graphic_emoticons?: boolean; convert_emoticons?: boolean; ss_emojis?: boolean; seen_onboarding_start?: boolean; onboarding_cancelled?: boolean; seen_onboarding_slackbot_conversation?: boolean; seen_onboarding_channels?: boolean; seen_onboarding_direct_messages?: boolean; seen_onboarding_invites?: boolean; seen_onboarding_search?: boolean; seen_onboarding_recent_mentions?: boolean; seen_onboarding_starred_items?: boolean; seen_onboarding_private_groups?: boolean; seen_onboarding_banner?: boolean; onboarding_slackbot_conversation_step?: number; set_tz_automatically?: boolean; suppress_link_warning?: boolean; seen_emoji_pack_cta?: number; seen_emoji_pack_dialog?: boolean; dnd_enabled?: boolean; dnd_start_hour?: string; dnd_end_hour?: string; dnd_before_monday?: string; dnd_after_monday?: string; dnd_enabled_monday?: string; dnd_before_tuesday?: string; dnd_after_tuesday?: string; dnd_enabled_tuesday?: string; dnd_before_wednesday?: string; dnd_after_wednesday?: string; dnd_enabled_wednesday?: string; dnd_before_thursday?: string; dnd_after_thursday?: string; dnd_enabled_thursday?: string; dnd_before_friday?: string; dnd_after_friday?: string; dnd_enabled_friday?: string; dnd_before_saturday?: string; dnd_after_saturday?: string; dnd_enabled_saturday?: string; dnd_before_sunday?: string; dnd_after_sunday?: string; dnd_enabled_sunday?: string; dnd_days?: string; dnd_weekdays_off_allday?: boolean; dnd_custom_new_badge_seen?: boolean; dnd_notification_schedule_new_badge_seen?: boolean; calls_survey_last_seen?: string; sidebar_behavior?: string; channel_sort?: string; separate_private_channels?: boolean; separate_shared_channels?: boolean; sidebar_theme?: string; sidebar_theme_custom_values?: string; no_invites_widget_in_sidebar?: boolean; no_omnibox_in_channels?: boolean; k_key_omnibox_auto_hide_count?: number; show_sidebar_quickswitcher_button?: boolean; ent_org_wide_channels_sidebar?: boolean; mark_msgs_read_immediately?: boolean; start_scroll_at_oldest?: boolean; snippet_editor_wrap_long_lines?: boolean; ls_disabled?: boolean; f_key_search?: boolean; k_key_omnibox?: boolean; prompted_for_email_disabling?: boolean; no_macelectron_banner?: boolean; no_macssb1_banner?: boolean; no_macssb2_banner?: boolean; no_winssb1_banner?: boolean; hide_user_group_info_pane?: boolean; mentions_exclude_at_user_groups?: boolean; mentions_exclude_reactions?: boolean; privacy_policy_seen?: boolean; enterprise_migration_seen?: boolean; search_exclude_bots?: boolean; load_lato_2?: boolean; fuller_timestamps?: boolean; last_seen_at_channel_warning?: number; emoji_autocomplete_big?: boolean; two_factor_auth_enabled?: boolean; hide_hex_swatch?: boolean; show_jumper_scores?: boolean; enterprise_mdm_custom_msg?: string; client_logs_pri?: string; flannel_server_pool?: string; mentions_exclude_at_channels?: boolean; confirm_clear_all_unreads?: boolean; confirm_user_marked_away?: boolean; box_enabled?: boolean; seen_single_emoji_msg?: boolean; confirm_sh_call_start?: boolean; preferred_skin_tone?: string; show_all_skin_tones?: boolean; whats_new_read?: number; frecency_jumper?: string; frecency_ent_jumper?: string; frecency_ent_jumper_backup?: string; jumbomoji?: boolean; newxp_seen_last_message?: number; show_memory_instrument?: boolean; enable_unread_view?: boolean; seen_unread_view_coachmark?: boolean; enable_react_emoji_picker?: boolean; seen_custom_status_badge?: boolean; seen_custom_status_callout?: boolean; seen_custom_status_expiration_badge?: boolean; used_custom_status_kb_shortcut?: boolean; seen_guest_admin_slackbot_announcement?: boolean; seen_threads_notification_banner?: boolean; seen_name_tagging_coachmark?: boolean; all_unreads_sort_order?: string; all_unreads_section_filter?: string; locale?: string; seen_intl_channel_names_coachmark?: boolean; seen_p2_locale_change_message?: number; seen_locale_change_message?: number; seen_japanese_locale_change_message?: boolean; seen_shared_channels_coachmark?: boolean; seen_shared_channels_opt_in_change_message?: boolean; has_recently_shared_a_channel?: boolean; seen_channel_browser_admin_coachmark?: boolean; seen_administration_menu?: boolean; seen_drafts_section_coachmark?: boolean; seen_emoji_update_overlay_coachmark?: boolean; seen_sonic_deluxe_toast?: number; seen_wysiwyg_deluxe_toast?: boolean; seen_markdown_paste_toast?: number; seen_markdown_paste_shortcut?: number; seen_ia_education?: boolean; show_ia_tour_relaunch?: number; plain_text_mode?: boolean; show_shared_channels_education_banner?: boolean; ia_slackbot_survey_timestamp_48h?: number; ia_slackbot_survey_timestamp_7d?: number; allow_calls_to_set_current_status?: boolean; in_interactive_mas_migration_flow?: boolean; sunset_interactive_message_views?: number; shdep_promo_code_submitted?: boolean; seen_shdep_slackbot_message?: boolean; seen_calls_interactive_coachmark?: boolean; allow_cmd_tab_iss?: boolean; seen_workflow_builder_deluxe_toast?: boolean; workflow_builder_intro_modal_clicked_through?: boolean; workflow_builder_coachmarks?: string; seen_gdrive_coachmark?: boolean; seen_first_install_coachmark?: boolean; seen_existing_install_coachmark?: boolean; seen_link_unfurl_coachmark?: boolean; overloaded_message_enabled?: boolean; seen_highlights_coachmark?: boolean; seen_highlights_arrows_coachmark?: boolean; seen_highlights_warm_welcome?: boolean; seen_new_search_ui?: boolean; seen_channel_search?: boolean; seen_people_search?: boolean; seen_people_search_count?: number; dismissed_scroll_search_tooltip_count?: number; last_dismissed_scroll_search_tooltip_timestamp?: number; has_used_quickswitcher_shortcut?: boolean; seen_quickswitcher_shortcut_tip_count?: number; browsers_dismissed_channels_low_results_education?: boolean; browsers_seen_initial_channels_education?: boolean; browsers_dismissed_people_low_results_education?: boolean; browsers_seen_initial_people_education?: boolean; browsers_dismissed_user_groups_low_results_education?: boolean; browsers_seen_initial_user_groups_education?: boolean; browsers_dismissed_files_low_results_education?: boolean; browsers_seen_initial_files_education?: boolean; browsers_dismissed_initial_drafts_education?: boolean; browsers_seen_initial_drafts_education?: boolean; browsers_dismissed_initial_activity_education?: boolean; browsers_seen_initial_activity_education?: boolean; browsers_dismissed_initial_saved_education?: boolean; browsers_seen_initial_saved_education?: boolean; seen_edit_mode?: boolean; seen_edit_mode_edu?: boolean; a11y_animations?: boolean; seen_keyboard_shortcuts_coachmark?: boolean; needs_initial_password_set?: boolean; lessons_enabled?: boolean; tractor_enabled?: boolean; tractor_experiment_group?: string; opened_slackbot_dm?: boolean; newxp_seen_help_message?: number; newxp_suggested_channels?: string; onboarding_complete?: boolean; welcome_place_state?: string; has_received_threaded_message?: boolean; onboarding_state?: number; whocanseethis_dm_mpdm_badge?: boolean; highlight_words?: string; threads_everything?: boolean; no_text_in_notifications?: boolean; push_show_preview?: boolean; growls_enabled?: boolean; all_channels_loud?: boolean; push_dm_alert?: boolean; push_mention_alert?: boolean; push_everything?: boolean; push_idle_wait?: number; push_sound?: string; new_msg_snd?: string; push_loud_channels?: string; push_mention_channels?: string; push_loud_channels_set?: string; loud_channels?: string; never_channels?: string; loud_channels_set?: string; at_channel_suppressed_channels?: string; push_at_channel_suppressed_channels?: string; muted_channels?: string; all_notifications_prefs?: string; growth_msg_limit_approaching_cta_count?: number; growth_msg_limit_approaching_cta_ts?: number; growth_msg_limit_reached_cta_count?: number; growth_msg_limit_reached_cta_last_ts?: number; growth_msg_limit_long_reached_cta_count?: number; growth_msg_limit_long_reached_cta_last_ts?: number; growth_msg_limit_sixty_day_banner_cta_count?: number; growth_msg_limit_sixty_day_banner_cta_last_ts?: number; growth_all_banners_prefs?: string; analytics_upsell_coachmark_seen?: boolean; seen_app_space_coachmark?: boolean; seen_app_space_tutorial?: boolean; dismissed_app_launcher_welcome?: boolean; dismissed_app_launcher_limit?: boolean; purchaser?: boolean; show_ent_onboarding?: boolean; folders_enabled?: boolean; folder_data?: string; seen_corporate_export_alert?: boolean; show_autocomplete_help?: number; deprecation_toast_last_seen?: number; deprecation_modal_last_seen?: number; iap1_lab?: number; ia_top_nav_theme?: string; ia_platform_actions_lab?: number; activity_view?: string; saved_view?: string; seen_floating_sidebar_coachmark?: boolean; failover_proxy_check_completed?: number; chime_access_check_completed?: number; mx_calendar_type?: string; edge_upload_proxy_check_completed?: number; app_subdomain_check_completed?: number; add_prompt_interacted?: boolean; add_apps_prompt_dismissed?: boolean; add_channel_prompt_dismissed?: boolean; channel_sidebar_hide_invite?: boolean; channel_sidebar_hide_browse_dms_link?: boolean; in_prod_surveys_enabled?: boolean; dismissed_installed_app_dm_suggestions?: string; seen_contextual_message_shortcuts_modal?: boolean; seen_message_navigation_educational_toast?: boolean; contextual_message_shortcuts_modal_was_seen?: boolean; message_navigation_toast_was_seen?: boolean; up_to_browse_kb_shortcut?: boolean; channel_sections?: string; show_quick_reactions?: boolean; has_received_mention_or_reaction?: boolean; has_starred_item?: boolean; has_drafted_message?: boolean; enable_mentions_and_reactions_view?: boolean; enable_saved_items_view?: boolean; enable_all_dms_view?: boolean; enable_channel_browser_view?: boolean; enable_file_browser_view?: boolean; enable_people_browser_view?: boolean; enable_app_browser_view?: boolean; reached_all_dms_disclosure?: boolean; has_acknowledged_shortcut_speedbump?: boolean; tz?: string; locales_enabled?: LocalesEnabled; joiner_notifications_muted?: boolean; invite_accepted_notifications_muted?: boolean; suppress_external_invites_from_compose_warning?: boolean; file_picker_variant?: number; help_modal_open_timestamp?: number; help_modal_consult_banner_dismissed?: boolean; seen_channel_email_tooltip?: boolean; join_calls_device_settings?: string; a11y_dyslexic?: boolean; connect_dm_early_access?: boolean; seen_connect_dm_coachmark?: boolean; xws_sidebar_variant?: number; user_customized_quick_reactions_display_feature?: number; user_customized_quick_reactions_has_customized?: boolean; user_customized_quick_reactions_emoji_1?: string; user_customized_quick_reactions_emoji_2?: string; user_customized_quick_reactions_emoji_3?: string; joiner_message_suggestion_dismissed?: boolean; huddles_variant?: number; stories_variant?: string; emoji_packs_most_recent_available_time?: number; emoji_packs_clicked_picker_cta?: boolean; emoji_packs_clicked_collection_cta?: boolean; seen_p3_locale_change_message_ko_kr?: number; inbox_views_workspace_filter?: string; dismissed_connect_auto_approval_modal?: string; help_menu_open_timestamp?: number; xws_dismissed_education?: boolean; xws_seen_education?: number; enable_slack_connect_view?: boolean; tasks_view?: string; dismissed_app_launcher_atlassian_promo?: boolean; seen_toast_new_locale_launch?: string; seen_toast_new_locale_launch_ts?: number; emoji_packs_clicked_picker_post_install_cta?: boolean; huddles_mute_by_default?: boolean; show_sidebar_avatars?: boolean; seen_connect_section_coachmark?: boolean; has_dismissed_google_directory_coachmark?: boolean; huddles_global_mute?: boolean; huddle_survey_last_seen?: string; huddles_mini_panel?: boolean; sidebar_pref_dismissed_tip?: boolean; enable_media_captions?: boolean; set_a11y_prefs_new_user?: boolean; seen_sc_page_banner?: boolean; seen_sc_menu_coachmark?: boolean; seen_sc_page?: boolean; notification_center_filters?: string; media_playback_speed?: number; } export interface LocalesEnabled { 'de-DE'?: string; 'en-GB'?: string; 'en-US'?: string; 'es-ES'?: string; 'es-LA'?: string; 'fr-FR'?: string; 'pt-BR'?: string; 'ja-JP'?: string; 'ko-KR'?: string; 'it-IT'?: string; } export interface Subteams { self?: string[]; all?: All[]; } export interface All { id?: string; team_id?: string; is_usergroup?: boolean; is_subteam?: boolean; name?: string; description?: string; handle?: string; is_external?: boolean; date_create?: number; date_update?: number; date_delete?: number; auto_provision?: boolean; enterprise_subteam_id?: string; created_by?: string; updated_by?: string; prefs?: AllPrefs; user_count?: number; channel_count?: number; } export interface AllPrefs { channels?: string[]; groups?: Group[]; } export interface Team { id?: string; name?: string; email_domain?: string; domain?: string; msg_edit_window_mins?: number; prefs?: TeamPrefs; icon?: Icon; over_storage_limit?: boolean; messages_count?: number; plan?: string; onboarding_channel_id?: string; date_create?: number; limit_ts?: number; avatar_base_url?: string; is_verified?: boolean; } export interface Icon { image_34?: string; image_44?: string; image_68?: string; image_88?: string; image_102?: string; image_132?: string; image_230?: string; image_original?: string; } export interface TeamPrefs { default_channels?: string[]; allow_calls?: boolean; display_email_addresses?: boolean; gdrive_enabled_team?: boolean; all_users_can_purchase?: boolean; enable_shared_channels?: number; can_receive_shared_channels_invites?: boolean; dropbox_legacy_picker?: boolean; app_whitelist_enabled?: boolean; who_can_manage_integrations?: SlackConnectAllowedWorkspaces; welcome_place_enabled?: boolean; msg_edit_window_mins?: number; allow_message_deletion?: boolean; locale?: string; slackbot_responses_disabled?: boolean; hide_referers?: boolean; calling_app_name?: string; calls_apps?: CallsApps; allow_calls_interactive_screen_sharing?: boolean; display_real_names?: boolean; who_can_at_everyone?: string; who_can_at_channel?: string; who_can_create_channels?: string; who_can_archive_channels?: string; who_can_create_groups?: string; who_can_manage_channel_posting_prefs?: string; who_can_post_general?: string; who_can_kick_channels?: string; who_can_kick_groups?: string; workflow_builder_enabled?: boolean; who_can_view_message_activity?: SlackConnectAllowedWorkspaces; workflow_extension_steps_beta_opt_in?: boolean; channel_email_addresses_enabled?: boolean; retention_type?: number; retention_duration?: number; group_retention_type?: number; group_retention_duration?: number; dm_retention_type?: number; dm_retention_duration?: number; file_retention_type?: number; file_retention_duration?: number; allow_retention_override?: boolean; allow_admin_retention_override?: number; default_rxns?: string[]; compliance_export_start?: number; warn_before_at_channel?: string; disallow_public_file_urls?: boolean; who_can_create_delete_user_groups?: string; who_can_edit_user_groups?: string; who_can_change_team_profile?: string; subteams_auto_create_owner?: boolean; subteams_auto_create_admin?: boolean; discoverable?: string; dnd_days?: string; invites_only_admins?: boolean; invite_requests_enabled?: boolean; disable_file_uploads?: string; disable_file_editing?: boolean; disable_file_deleting?: boolean; file_limit_whitelisted?: boolean; uses_customized_custom_status_presets?: boolean; disable_email_ingestion?: boolean; who_can_manage_guests?: SlackConnectAllowedWorkspaces; who_can_create_shared_channels?: string; who_can_manage_shared_channels?: SlackConnectAllowedWorkspaces; who_can_post_in_shared_channels?: SlackConnectAllowedWorkspaces; who_can_manage_ext_shared_channels?: SlackConnectAllowedWorkspaces; who_can_dm_anyone?: SlackConnectAllowedWorkspaces; box_app_installed?: boolean; onedrive_app_installed?: boolean; onedrive_enabled_team?: boolean; filepicker_app_first_install?: boolean; use_browser_picker?: boolean; received_esc_route_to_channel_awareness_message?: boolean; who_can_approve_ext_shared_channel_invites?: SlackConnectAllowedWorkspaces; who_can_create_ext_shared_channel_invites?: SlackConnectAllowedWorkspaces; enterprise_default_channels?: string[]; enterprise_has_corporate_exports?: boolean; enterprise_mandatory_channels?: string[]; enterprise_mdm_disable_file_download?: boolean; mobile_passcode_timeout_in_seconds?: number; notification_redaction_type?: string; has_compliance_export?: boolean; has_hipaa_compliance?: boolean; self_serve_select?: boolean; loud_channel_mentions_limit?: number; show_join_leave?: boolean; who_can_manage_public_channels?: WhoCanManageP; who_can_manage_private_channels?: WhoCanManageP; who_can_manage_private_channels_at_workspace_level?: WhoCanManageP; enterprise_mobile_device_check?: boolean; default_channel_creation_enabled?: boolean; gg_enabled?: boolean; created_with_google?: boolean; has_seen_partner_promo?: boolean; disable_sidebar_connect_prompts?: string[]; disable_sidebar_install_prompts?: string[]; block_file_download?: boolean; single_user_exports?: boolean; app_management_apps?: string[]; ntlm_credential_domains?: string; dnd_enabled?: boolean; dnd_start_hour?: string; dnd_end_hour?: string; dnd_before_monday?: string; dnd_after_monday?: string; dnd_before_tuesday?: string; dnd_after_tuesday?: string; dnd_before_wednesday?: string; dnd_after_wednesday?: string; dnd_before_thursday?: string; dnd_after_thursday?: string; dnd_before_friday?: string; dnd_after_friday?: string; dnd_before_saturday?: string; dnd_after_saturday?: string; dnd_before_sunday?: string; dnd_after_sunday?: string; dnd_enabled_monday?: string; dnd_enabled_tuesday?: string; dnd_enabled_wednesday?: string; dnd_enabled_thursday?: string; dnd_enabled_friday?: string; dnd_enabled_saturday?: string; dnd_enabled_sunday?: string; dnd_weekdays_off_allday?: boolean; custom_status_presets?: Array<string[]>; custom_status_default_emoji?: string; auth_mode?: string; who_can_create_workflows?: SlackConnectAllowedWorkspaces; workflows_webhook_trigger_enabled?: boolean; workflows_export_csv_enabled?: boolean; who_can_create_channel_email_addresses?: SlackConnectAllowedWorkspaces; invites_limit?: boolean; member_analytics_disabled?: boolean; calls_locations?: string[]; workflow_extension_steps_enabled?: boolean; who_can_request_ext_shared_channels?: SlackConnectAllowedWorkspaces; admin_customized_quick_reactions?: string[]; enable_connect_dm_early_access?: boolean; display_external_email_addresses?: boolean; enable_info_barriers?: boolean; enable_mpdm_to_private_channel_conversion?: boolean; slack_connect_file_upload_sharing_enabled?: boolean; slack_connect_dm_only_verified_orgs?: boolean; joiner_notifications_enabled?: boolean; slack_connect_allowed_workspaces?: SlackConnectAllowedWorkspaces; show_legacy_paid_benefits_page?: boolean; enable_domain_allowlist_for_cea?: boolean; } export interface CallsApps { audio?: string[]; video?: Video[]; profile_field_options?: string[]; } export interface Video { id?: string; name?: string; image?: string; } export interface SlackConnectAllowedWorkspaces { type?: string[]; } export interface WhoCanManageP { user?: string[]; type?: string[]; } export interface User { id?: string; team_id?: string; name?: string; deleted?: boolean; color?: string; real_name?: string; tz?: string; tz_label?: string; tz_offset?: number; profile?: Profile; is_admin?: boolean; is_owner?: boolean; is_primary_owner?: boolean; is_restricted?: boolean; is_ultra_restricted?: boolean; is_bot?: boolean; is_app_user?: boolean; updated?: number; presence?: string; is_workflow_bot?: boolean; } export interface Profile { title?: string; phone?: string; skype?: string; real_name?: string; real_name_normalized?: string; display_name?: string; display_name_normalized?: string; fields?: { [key: string]: Field }; status_text?: string; status_emoji?: string; status_expiration?: number; avatar_hash?: string; image_original?: string; is_custom_image?: boolean; email?: string; first_name?: string; last_name?: string; image_24?: string; image_32?: string; image_48?: string; image_72?: string; image_192?: string; image_512?: string; image_1024?: string; status_text_canonical?: string; team?: string; api_app_id?: string; bot_id?: string; always_active?: boolean; guest_invited_by?: string; } export interface Field { value?: string; alt?: string; }
the_stack
import { mockDocument, TldrawTestApp } from '~test' import { GroupShape, TDShape, TDShapeType } from '~types' describe('Group command', () => { const app = new TldrawTestApp() beforeEach(() => { app.loadDocument(mockDocument) }) it('does, undoes and redoes command', () => { app.group(['rect1', 'rect2'], 'newGroup') expect(app.getShape<GroupShape>('newGroup')).toBeTruthy() app.undo() expect(app.getShape<GroupShape>('newGroup')).toBeUndefined() app.redo() expect(app.getShape<GroupShape>('newGroup')).toBeTruthy() }) describe('when less than two shapes are selected', () => { it('does nothing', () => { app.selectNone() // @ts-ignore const stackLength = app.stack.length app.group([], 'newGroup') expect(app.getShape<GroupShape>('newGroup')).toBeUndefined() // @ts-ignore expect(app.stack.length).toBe(stackLength) app.group(['rect1'], 'newGroup') expect(app.getShape<GroupShape>('newGroup')).toBeUndefined() // @ts-ignore expect(app.stack.length).toBe(stackLength) }) }) describe('when grouping shapes on the page', () => { /* When the parent is a page, the group is created as a child of the page and the shapes are reparented to the group. The group's child index should be the minimum child index of the selected shapes. */ it('creates a group with the correct props', () => { app.updateShapes( { id: 'rect1', point: [300, 300], childIndex: 3, }, { id: 'rect2', point: [20, 20], childIndex: 4, } ) app.group(['rect1', 'rect2'], 'newGroup') const group = app.getShape<GroupShape>('newGroup') expect(group).toBeTruthy() expect(group.parentId).toBe('page1') expect(group.childIndex).toBe(3) expect(group.point).toStrictEqual([20, 20]) expect(group.children).toStrictEqual(['rect1', 'rect2']) }) it('reparents the grouped shapes', () => { app.updateShapes( { id: 'rect1', childIndex: 2.5, }, { id: 'rect2', childIndex: 4.7, } ) app.group(['rect1', 'rect2'], 'newGroup') let rect1: TDShape let rect2: TDShape rect1 = app.getShape('rect1') rect2 = app.getShape('rect2') // Reparents the shapes expect(rect1.parentId).toBe('newGroup') expect(rect2.parentId).toBe('newGroup') // Sets and preserves the order of the grouped shapes expect(rect1.childIndex).toBe(1) expect(rect2.childIndex).toBe(2) app.undo() rect1 = app.getShape('rect1') rect2 = app.getShape('rect2') // Restores the shapes' parentIds expect(rect1.parentId).toBe('page1') expect(rect2.parentId).toBe('page1') // Restores the shapes' childIndexs expect(rect1.childIndex).toBe(2.5) expect(rect2.childIndex).toBe(4.7) }) }) describe('when grouping shapes that already belong to a group', () => { /* Do not allow groups to nest. All groups should be children of the page: a group should never be the child of a different group. This is a UX decision as much as a technical one. */ it('creates a new group on the page', () => { /* When the selected shapes are the children of another group, and so long as the children do not represent ALL of the group's children, then a new group should be created from the selected shapes and the original group be updated to only contain the remaining ones. */ app.resetDocument().createShapes( { id: 'rect1', type: TDShapeType.Rectangle, childIndex: 1, }, { id: 'rect2', type: TDShapeType.Rectangle, childIndex: 2, }, { id: 'rect3', type: TDShapeType.Rectangle, childIndex: 3, }, { id: 'rect4', type: TDShapeType.Rectangle, childIndex: 4, } ) app.group(['rect1', 'rect2', 'rect3', 'rect4'], 'newGroupA') expect(app.getShape<GroupShape>('newGroupA')).toBeTruthy() expect(app.getShape('rect1').childIndex).toBe(1) expect(app.getShape('rect2').childIndex).toBe(2) expect(app.getShape('rect3').childIndex).toBe(3) expect(app.getShape('rect4').childIndex).toBe(4) expect(app.getShape<GroupShape>('newGroupA').children).toStrictEqual([ 'rect1', 'rect2', 'rect3', 'rect4', ]) app.group(['rect1', 'rect3'], 'newGroupB') expect(app.getShape<GroupShape>('newGroupA')).toBeTruthy() expect(app.getShape('rect2').childIndex).toBe(2) expect(app.getShape('rect4').childIndex).toBe(4) expect(app.getShape<GroupShape>('newGroupA').children).toStrictEqual(['rect2', 'rect4']) expect(app.getShape<GroupShape>('newGroupB')).toBeTruthy() expect(app.getShape('rect1').childIndex).toBe(1) expect(app.getShape('rect3').childIndex).toBe(2) expect(app.getShape<GroupShape>('newGroupB').children).toStrictEqual(['rect1', 'rect3']) app.undo() expect(app.getShape<GroupShape>('newGroupA')).toBeTruthy() expect(app.getShape('rect1').childIndex).toBe(1) expect(app.getShape('rect2').childIndex).toBe(2) expect(app.getShape('rect3').childIndex).toBe(3) expect(app.getShape('rect4').childIndex).toBe(4) expect(app.getShape<GroupShape>('newGroupA').children).toStrictEqual([ 'rect1', 'rect2', 'rect3', 'rect4', ]) expect(app.getShape<GroupShape>('newGroupB')).toBeUndefined() app.redo() expect(app.getShape<GroupShape>('newGroupA')).toBeTruthy() expect(app.getShape('rect2').childIndex).toBe(2) expect(app.getShape('rect4').childIndex).toBe(4) expect(app.getShape<GroupShape>('newGroupA').children).toStrictEqual(['rect2', 'rect4']) expect(app.getShape<GroupShape>('newGroupB')).toBeTruthy() expect(app.getShape('rect1').childIndex).toBe(1) expect(app.getShape('rect3').childIndex).toBe(2) expect(app.getShape<GroupShape>('newGroupB').children).toStrictEqual(['rect1', 'rect3']) }) it('does nothing if all shapes in the group are selected', () => { /* If the selected shapes represent ALL of the children of the a group, then no effect should occur. */ app.resetDocument().createShapes( { id: 'rect1', type: TDShapeType.Rectangle, childIndex: 1, }, { id: 'rect2', type: TDShapeType.Rectangle, childIndex: 2, }, { id: 'rect3', type: TDShapeType.Rectangle, childIndex: 3, } ) app.group(['rect1', 'rect2', 'rect3'], 'newGroupA') app.group(['rect1', 'rect2', 'rect3'], 'newGroupB') expect(app.getShape<GroupShape>('newGroupB')).toBeUndefined() }) it('deletes any groups that no longer have children', () => { /* If the selected groups included the children of another group in addition to other shapes then that group should be destroyed. Other rules around deleted shapes should here apply: bindings connected to the group should be deleted, etc. */ app.resetDocument().createShapes( { id: 'rect1', type: TDShapeType.Rectangle, childIndex: 1, }, { id: 'rect2', type: TDShapeType.Rectangle, childIndex: 2, }, { id: 'rect3', type: TDShapeType.Rectangle, childIndex: 3, } ) app.group(['rect1', 'rect2'], 'newGroupA') app.group(['rect1', 'rect2', 'rect3'], 'newGroupB') expect(app.getShape<GroupShape>('newGroupA')).toBeUndefined() expect(app.getShape<GroupShape>('newGroupB').children).toStrictEqual([ 'rect1', 'rect2', 'rect3', ]) }) it('merges selected groups that no longer have children', () => { /* If the user is creating a group while having selected other groups, then the selected groups should be destroyed and a new group created with the selected shapes and the group(s)' children. */ app.resetDocument().createShapes( { id: 'rect1', type: TDShapeType.Rectangle, childIndex: 1, }, { id: 'rect2', type: TDShapeType.Rectangle, childIndex: 2, }, { id: 'rect3', type: TDShapeType.Rectangle, childIndex: 3, } ) app.group(['rect1', 'rect2'], 'newGroupA') app.group(['newGroupA', 'rect3'], 'newGroupB') expect(app.getShape<GroupShape>('newGroupA')).toBeUndefined() expect(app.getShape<GroupShape>('newGroupB').children).toStrictEqual([ 'rect1', 'rect2', 'rect3', ]) app.undo() expect(app.getShape<GroupShape>('newGroupB')).toBeUndefined() expect(app.getShape<GroupShape>('newGroupA')).toBeDefined() expect(app.getShape<GroupShape>('newGroupA').children).toStrictEqual(['rect1', 'rect2']) app.redo() expect(app.getShape<GroupShape>('newGroupA')).toBeUndefined() expect(app.getShape<GroupShape>('newGroupB')).toBeDefined() expect(app.getShape<GroupShape>('newGroupB').children).toStrictEqual([ 'rect1', 'rect2', 'rect3', ]) }) it('Ungroups if the only shape selected is a group', () => { app.resetDocument().createShapes( { id: 'rect1', type: TDShapeType.Rectangle, childIndex: 1, }, { id: 'rect2', type: TDShapeType.Rectangle, childIndex: 2, }, { id: 'rect3', type: TDShapeType.Rectangle, childIndex: 3, } ) expect(app.shapes.length).toBe(3) app.selectAll().group() expect(app.shapes.length).toBe(4) app.selectAll().group() expect(app.shapes.length).toBe(3) }) /* The layers should be in the same order as the original layers as they would have appeared on a layers tree (lowest child index first, parent inclusive). */ it.todo('preserves the child index order') /* --------------------- Nesting -------------------- */ // it.todo('creates the new group as a child of the parent group') /* The new group should be a child of the parent group. */ // it.todo('moves the selected layers to the new group') /* The new group should have the selected children. The old parents should no longer have the selected shapes among their children. All of the selected shapes should be assigned the new parent. */ }) // describe('when grouping shapes with different parents', () => { /* When two shapes with different parents are grouped, the new parent group should have the same parent as the shape nearest to the top of the layer tree. The new group's child index should be that shape's child index. For example, if the shapes are grouped in the following order: - page1 - group1 - arrow1 - rect1 (x) - arrow2 - rect2 (x) The new parent group should have the same parent as rect1. - page1 - group1 - arrow1 - group2 - rect1 (x) - rect2 (x) - arrow2 If, instead, the shapes are grouped in the following order: - page1 - arrow1 - rect1 (x) - group1 - arrow2 - rect2 (x) Then the new parent group should have the same parent as rect2. - page1 - arrow1 - group2 (x) - rect1 - rect2 - group1 - arrow2 We can find this by searching the tree for the nearest shape to the top. */ // it.todo('creates a group in the correct place') /* The new group should be a child of the nearest shape to the top of the tree. */ /* If the selected groups included the children of another group, then that group should be destroyed. Other rules around deleted shapes should here apply: bindings connected to the group should be deleted, etc. */ // it.todo('deletes any groups that no longer have children') // }) })
the_stack
import { Trans } from '@lingui/macro' import { Button, Form } from 'antd' import { useCallback, useContext, useEffect, useLayoutEffect, useMemo, useState, } from 'react' import { ThemeContext } from 'contexts/themeContext' import { V2CurrencyOption } from 'models/v2/currencyOption' import { useAppDispatch } from 'hooks/AppDispatch' import { defaultFundingCycleData, defaultFundingCycleMetadata, editingV2ProjectActions, } from 'redux/slices/editingV2Project' import { V2UserContext } from 'contexts/v2/userContext' import { useAppSelector } from 'hooks/AppSelector' import { SerializedV2FundAccessConstraint } from 'utils/v2/serializers' import { sanitizeSplit } from 'utils/v2/splits' import { getDefaultFundAccessConstraint } from 'utils/v2/fundingCycle' import { getV2CurrencyOption, V2CurrencyName, V2_CURRENCY_ETH, } from 'utils/v2/currency' import ExternalLink from 'components/shared/ExternalLink' import { Split } from 'models/v2/splits' import { DEFAULT_FUNDING_CYCLE_DURATION, MAX_DISTRIBUTION_LIMIT, } from 'utils/v2/math' import { deriveDurationUnit, secondsToOtherUnit, otherUnitToSeconds, } from 'utils/formatTime' import { fromWad } from 'utils/formatNumber' import FormItemWarningText from 'components/shared/FormItemWarningText' import SwitchHeading from 'components/shared/SwitchHeading' import DistributionSplitsSection from 'components/v2/shared/DistributionSplitsSection' import { getTotalSplitsPercentage } from 'utils/v2/distributions' import { V2ProjectContext } from 'contexts/v2/projectContext' import { ItemNoInput } from 'components/shared/formItems/ItemNoInput' import isEqual from 'lodash/isEqual' import { ETH_TOKEN_ADDRESS } from 'constants/v2/juiceboxTokens' import { shadowCard } from 'constants/styles/shadowCard' import DurationInputAndSelect from './DurationInputAndSelect' import { DurationUnitsOption } from 'constants/time' import { FundingCycleExplainerCollapse } from './FundingCycleExplainerCollapse' type FundingFormFields = { duration?: string durationUnit?: DurationUnitsOption durationEnabled?: boolean totalSplitsPercentage?: number } export default function FundingForm({ onFormUpdated, onFinish, isCreate, }: { onFormUpdated?: (updated: boolean) => void onFinish: VoidFunction isCreate?: boolean // Instance of FundingForm in create flow }) { const { theme, theme: { colors }, } = useContext(ThemeContext) const { contracts } = useContext(V2UserContext) const { payoutSplits } = useContext(V2ProjectContext) const dispatch = useAppDispatch() const [fundingForm] = Form.useForm<FundingFormFields>() // Load redux state (will be empty in create flow) const { fundAccessConstraints, fundingCycleData, payoutGroupedSplits } = useAppSelector(state => state.editingV2Project) const fundAccessConstraint = getDefaultFundAccessConstraint<SerializedV2FundAccessConstraint>( fundAccessConstraints, ) const [splits, setSplits] = useState<Split[]>([]) // Must differentiate between splits loaded from redux and // ones just added to be able to still edit splits you've // added with a lockedUntil const [editingSplits, setEditingSplits] = useState<Split[]>([]) const [distributionLimit, setDistributionLimit] = useState< string | undefined >('0') const [distributionLimitCurrency, setDistributionLimitCurrency] = useState<V2CurrencyOption>(V2_CURRENCY_ETH) const [durationEnabled, setDurationEnabled] = useState<boolean>(false) // Form initial values set by default const initialValues = useMemo( () => ({ durationSeconds: fundingCycleData ? fundingCycleData.duration : '0', distributionLimit: fundAccessConstraint?.distributionLimit ?? '0', distributionLimitCurrency: parseInt( fundAccessConstraint?.distributionLimitCurrency ?? V2_CURRENCY_ETH.toString(), ) as V2CurrencyOption, payoutSplits: payoutGroupedSplits.splits, }), [fundingCycleData, fundAccessConstraint, payoutGroupedSplits], ) const { editableSplits, lockedSplits, }: { editableSplits: Split[] lockedSplits: Split[] } = useMemo(() => { const now = new Date().valueOf() / 1000 // Checks if the given split exists in the projectContext splits. // If it doesn't, then it means it was just added or edited is which case // we want to still be able to edit it const confirmedSplitsIncludesSplit = (split: Split) => { let includes = false payoutSplits?.forEach(confirmedSplit => { if (isEqual(confirmedSplit, split)) { includes = true } }) return includes } const isLockedSplit = (split: Split) => { return ( split.lockedUntil && split.lockedUntil > now && !isCreate && confirmedSplitsIncludesSplit(split) ) } const lockedSplits = splits?.filter(split => isLockedSplit(split)) ?? [] const editableSplits = splits?.filter(split => !isLockedSplit(split)) ?? [] return { lockedSplits, editableSplits, } }, [splits, isCreate, payoutSplits]) useLayoutEffect(() => setEditingSplits(editableSplits), [editableSplits]) // Loads redux state into form const resetProjectForm = useCallback(() => { const _distributionLimit = fundAccessConstraint?.distributionLimit ?? '0' const _distributionLimitCurrency = parseInt( fundAccessConstraint?.distributionLimitCurrency ?? V2_CURRENCY_ETH.toString(), ) as V2CurrencyOption const durationSeconds = fundingCycleData ? parseInt(fundingCycleData.duration) : 0 setDurationEnabled(durationSeconds > 0) const durationUnit = deriveDurationUnit(durationSeconds) fundingForm.setFieldsValue({ durationUnit: durationUnit, duration: secondsToOtherUnit({ duration: durationSeconds, unit: durationUnit, }).toString(), }) const payoutSplits = payoutGroupedSplits?.splits setDistributionLimit(_distributionLimit) setDistributionLimitCurrency(_distributionLimitCurrency) setSplits(payoutSplits ?? []) }, [fundingForm, fundingCycleData, fundAccessConstraint, payoutGroupedSplits]) const onFundingFormSave = useCallback( async (fields: FundingFormFields) => { if (!contracts) throw new Error('Failed to save funding configuration.') const fundAccessConstraint: SerializedV2FundAccessConstraint | undefined = { terminal: contracts.JBETHPaymentTerminal.address, token: ETH_TOKEN_ADDRESS, distributionLimit: distributionLimit ?? fromWad(MAX_DISTRIBUTION_LIMIT), distributionLimitCurrency: distributionLimitCurrency?.toString() ?? V2_CURRENCY_ETH, overflowAllowance: '0', // nothing for the time being. overflowAllowanceCurrency: '0', } const duration = fields?.duration ? parseInt(fields?.duration) : 0 const durationUnit = fields?.durationUnit ?? 'days' const durationInSeconds = otherUnitToSeconds({ duration: duration, unit: durationUnit, }).toString() dispatch( editingV2ProjectActions.setFundAccessConstraints( fundAccessConstraint ? [fundAccessConstraint] : [], ), ) dispatch( editingV2ProjectActions.setPayoutSplits( lockedSplits.concat(editingSplits).map(sanitizeSplit), ), ) dispatch(editingV2ProjectActions.setDuration(durationInSeconds ?? '0')) // reset discount rate if duration is 0 if (!durationInSeconds || durationInSeconds === '0') { dispatch( editingV2ProjectActions.setDiscountRate( defaultFundingCycleData.discountRate, ), ) } // reset redemption rate if distributionLimit is 0 if (!distributionLimit || distributionLimit === '0') { dispatch( editingV2ProjectActions.setRedemptionRate( defaultFundingCycleMetadata.redemptionRate, ), ) } onFinish?.() }, [ editingSplits, lockedSplits, contracts, dispatch, distributionLimit, distributionLimitCurrency, onFinish, ], ) // initially fill form with any existing redux state useLayoutEffect(() => { resetProjectForm() }, [resetProjectForm]) // Ensures total split percentages do not exceed 100 const validateTotalSplitsPercentage = () => { if (fundingForm.getFieldValue('totalSplitsPercentage') > 100) return Promise.reject() return Promise.resolve() } const onFormChange = useCallback(() => { const duration = fundingForm.getFieldValue('duration') as number const durationUnit = fundingForm.getFieldValue( 'durationUnit', ) as DurationUnitsOption const durationInSeconds = durationEnabled ? otherUnitToSeconds({ duration: duration, unit: durationUnit, }).toString() : '0' const splits = lockedSplits.concat(editingSplits).map(sanitizeSplit) const hasFormUpdated = initialValues.durationSeconds !== durationInSeconds || initialValues.distributionLimit !== distributionLimit || initialValues.distributionLimitCurrency !== distributionLimitCurrency || !isEqual(initialValues.payoutSplits, splits) onFormUpdated?.(hasFormUpdated) }, [ durationEnabled, editingSplits, fundingForm, initialValues, lockedSplits, onFormUpdated, distributionLimitCurrency, distributionLimit, ]) useEffect(() => { onFormChange() }, [onFormChange]) return ( <Form form={fundingForm} onValuesChange={onFormChange} layout="vertical" onFinish={onFundingFormSave} > <div style={{ padding: '2rem', marginBottom: 10, ...shadowCard(theme), color: colors.text.primary, }} > <SwitchHeading checked={durationEnabled} onChange={checked => { setDurationEnabled(checked) if (!checked) { fundingForm.setFieldsValue({ duration: '0' }) } fundingForm.setFieldsValue({ duration: DEFAULT_FUNDING_CYCLE_DURATION.toString(), }) }} style={{ marginBottom: '1rem' }} > <Trans>Automate funding cycles</Trans> </SwitchHeading> {!durationEnabled ? ( <FormItemWarningText> <Trans> With no funding cycles, the project's owner can start a new funding cycle (Funding Cycle #2) on-demand.{' '} <ExternalLink href={'https://info.juicebox.money/docs/protocol/learn/risks'} > Learn more. </ExternalLink> </Trans> </FormItemWarningText> ) : null} {durationEnabled && ( <DurationInputAndSelect defaultDurationUnit={fundingForm.getFieldValue('durationUnit')} /> )} <div> <FundingCycleExplainerCollapse /> </div> </div> <div style={{ padding: '2rem', marginBottom: 10, ...shadowCard(theme), color: colors.text.primary, }} > <h3 style={{ color: colors.text.primary }}> <Trans>Payouts</Trans> </h3> <DistributionSplitsSection distributionLimit={distributionLimit} setDistributionLimit={setDistributionLimit} currencyName={V2CurrencyName(distributionLimitCurrency) ?? 'ETH'} onCurrencyChange={currencyName => setDistributionLimitCurrency(getV2CurrencyOption(currencyName)) } editableSplits={editingSplits} lockedSplits={lockedSplits} onSplitsChanged={newSplits => { setEditingSplits(newSplits) fundingForm.setFieldsValue({ totalSplitsPercentage: getTotalSplitsPercentage(newSplits), }) }} /> <ItemNoInput name={'totalSplitsPercentage'} rules={[ { validator: validateTotalSplitsPercentage, }, ]} /> </div> <Form.Item style={{ marginTop: '2rem' }}> <Button htmlType="submit" type="primary"> <Trans>Save funding configuration</Trans> </Button> </Form.Item> </Form> ) }
the_stack
import PolymerTSElement = polymer.PolymerTSElement; var polymerReady=false; // jasmine boot.js links to window.onload var startJasmine = window.onload; window.onload = null; window.addEventListener('WebComponentsReady', (e) => { polymerReady = true; RunSpecs(); startJasmine.call(window, null); }); // simulates the old Jasmine 1.3 waitsFor() function waitFor(F) { beforeEach((done) => { setInterval(() => { if(F()) done(); }, 250); }); } function querySelector(s) { return document.querySelector(s); } // quickly checks if instance implements the class function implements(instance: Object, classFunction: Function) { var instanceMembers = {}; for(var i in instance) instanceMembers[i] = true; var classMembers = []; for(var i in classFunction.prototype) classMembers.push(i); for(var t=0; t<classMembers.length; t++) { if(instanceMembers[classMembers[t]]===undefined) { return false; } } return true; } function RunSpecs() { describe("webcomponents library", () => { waitFor( () => polymerReady ); it("fires the event 'WebComponentsReady'", () => { expect(polymerReady).toBe(true); }); }); describe("@component decorator", () => { it('registers regular elements', () => { var el = <TestElement> querySelector('#testElement'); expect(implements(el, TestElement)).toBe(true); expect(el.is).toBe(TestElement.prototype["is"]); expect(el.$.inner.innerHTML).toBe("innerelement"); }); it('extends builtin elements using second argument', () => { var el = querySelector('#testInput1'); expect(implements(el, TestInput1)).toBe(true); }); it("sets 'is:' correctly", () => { var el1 = <TestElement> querySelector('#testElement'); var el2 = <TestInput1> querySelector('#testInput1'); var el3 = <TestInput2> querySelector('#testInput2'); expect(el1.is).toBe(TestElement.prototype["is"]); expect(el2.is).toBe(TestInput1.prototype["is"]); expect(el3.is).toBe(TestInput2.prototype["is"]); }); }); describe("@extend decorator", () => { it('extends builtin elements', () => { var el = querySelector('#testInput2'); expect(implements(el, TestInput2)).toBe(true); }); }); describe("a computed property", () => { it('can be set with @computed decorator', () => { var element = <ComputedPropertiesTest> querySelector('#computedProperties1'); expect(element.computed1).toBe(2); element.set('first', 2); expect(element.computed1).toBe(3); element.set('second', 4); expect(element.computed1).toBe(6); // TODO check for "get_" }); it('can be set with @property decorator', () => { var element = <ComputedPropertiesTest> querySelector('#computedProperties2'); expect(element.computed2).toBe(2); element.set('first', 2); expect(element.computed2).toBe(3); element.set('second', 4); expect(element.computed2).toBe(6); }); }); describe("custom constructor", () => { var el: CustomConstructorTest; beforeEach(() => { // create the element el = <any> CustomConstructorTest.create("42"); // connect it to DOM querySelector("#put_custom_constructor_here").appendChild(el); }); // wait for the 'attached' event waitFor(() => (el.bar == "42")); it("provides custom initialization", () => { expect(el.bar).toBe("42"); }); }); describe("constructor()", () => { let el: PropertyInitializationTest; beforeEach(() => { // create the element el = <PropertyInitializationTest> PropertyInitializationTest.create(); // connect it to DOM querySelector("#put_custom_constructor_here").appendChild(el); }); // wait for the 'attached' event waitFor(() => (el.bar == "mybar")); it("initializes simple properties that use @property annotation correctly", () => { expect(el.bar).toBe("mybar"); expect(el.foo).toBe("myfoo"); expect(el.war).toBe("mywar"); expect(el.constructorProp).toBe("constructorProp"); }); it("initializes readOnly properties annotated with the @property annotation correctly", () => { expect(el.readOnlyUndefined).toBe(undefined); expect(el.readOnlyInitialized).toBe(true); }); it("initializes @property annotations with multiple attributes correctly", () => { const propDef = (<polymer.Element>el).properties['allValuesSet']; expect(propDef).not.toBe(undefined); expect(propDef.type).toBe(Boolean); expect(propDef.notify).toBe(true); expect(propDef.reflectToAttribute).toBe(true); expect(propDef.value).toBe(true); }); }); describe("polymer.Base", () => { it("doesn't allow an element to be used before it's registered", () => { expect(()=>UnInitializedTest.create()).toThrow("element not yet registered in Polymer"); }); it("doesn't allow an element to be registered twice", () => { expect(() => DoubleInitializationTest.register() ).not.toThrow(); expect(() => DoubleInitializationTest.register() ).toThrow("element already registered in Polymer"); }); it("create elements that are extensions of HTMLElement", () => { var el = DoubleInitializationTest.create(); expect(implements(el, HTMLElement)).toBe(true); }); it("create elements that are extensions Polymer.Base", () => { var el=DoubleInitializationTest.create(); expect(implements(el, Polymer.Base)).toBe(true); }); it("does not allow to redefine factoryImpl()", () => { expect(() => NoFactoryImplTest.register()).toThrow("do not use factoryImpl() use constructor() instead"); }); }); describe("@listen decorator", () => { var el: ListenerTest; beforeEach(() => { el = <any> ListenerTest.create(); querySelector("#put_custom_constructor_here").appendChild(el); }); // wait for the 'attached' event waitFor(() => (el.bar=="foo")); it("sets an event listener function", () => { expect(el.bar).toBe("foo"); }); }); describe("@observe decorator", () => { var el: ObserverTest; beforeEach(() => { el = <ObserverTest> ObserverTest.create(); querySelector("#put_custom_constructor_here").appendChild(el); }); // wait for the 'attached' event waitFor(() => (el.bar=="mybar")); it("observes a single property change", () => { expect((el).nbar_changed).toBe(0); el.set("bar", "42"); expect((el).nbar_changed).toBe(1); expect((el).bar2_old).toBe("mybar"); el.set("bar", "1024"); expect((el).nbar_changed).toBe(2); expect((el).bar2_old).toBe("42"); }); it("observes a single property changes as a lambda function", () => { expect((el).nbaz_changed).toBe(0); el.set("baz", "42"); expect((el).nbaz_changed).toBe(1); expect((el).baz_old).toBe(undefined); el.set("baz", "1024"); expect((el).nbaz_changed).toBe(2); expect((el).baz_old).toBe("42"); }); it("observes more than one property changes", () => { expect((el).nbar_changed).toBe(0); expect((el).nbar_foo_changed).toBe(0); el.set("foo", "42"); expect((el).nbar_changed).toBe(0); expect((el).nbar_foo_changed).toBe(1); expect((el).observed_bar).toBe("mybar"); expect((el).observed_foo).toBe("42"); }); it("does not support multiple simple observers for a single property", () => { const originalBar = el.bar; expect((el).nbar_changed).toBe(0); el.set("bar", "42"); expect((el).nbar_changed).toBe(1); expect((el).bar_old).toBe(undefined); expect((el).bar2_old).toBe(originalBar); el.set("bar", "blue"); expect((el).nbar_changed).toBe(2); expect((el).bar_old).toBe(undefined); expect((el).bar2_old).toBe("42"); }); it("work properly when called before @property decorators", () => { expect((el).nblah_changed).toBe(0); el.set("blah", "42"); expect((el).nblah_changed).toBe(1); expect((el).blah_new_val).toBe("42"); expect((el).blah_old_val).toBe("myblah"); }); it("observes subproperties (path) changes", () => { //expect((el).nmanager_changed).toBe(0); el.set("user.manager", "42"); expect((el).user.manager).toBe("42"); //expect((el).nmanager_changed).toBe(1); expect((el).nmanager_changed).toBeGreaterThan(0); }); }); describe("@behavior decorator", () => { let el1: BehaviorTest1, el2: BehaviorTest2; beforeEach(() => { el1 = <any> BehaviorTest1.create(); el2 = <any> BehaviorTest2.create(); querySelector("#put_custom_constructor_here").appendChild(el1); querySelector("#put_custom_constructor_here").appendChild(el2); }); // wait for the 'attached' event waitFor(() => (el1.bar=="mybar")); it("mixes code from another class (decorating the 'class' keyword)", () => { expect(el1.hasfired).toBe(true); expect(el1.methodInBase()).toBe("this method is defined in BehaviorBaseTest"); expect(el1.methodInChild()).toBe("this method is defined in BehaviorBaseTest"); }); // wait for the 'attached' event waitFor(() => (el2.bar=="mybar")); it("mixes code from another class (decorator inside the class body)", () => { expect(el2.hasfired).toBe(true); expect(el1.methodInBase()).toBe("this method is defined in BehaviorBaseTest"); expect(el1.methodInChild()).toBe("this method is defined in BehaviorBaseTest"); }); it("mixes code from a plain javascript object (decorating the 'class' keyword)", () => { expect(el1.methodInPojo1()).toEqual("pojo"); }); it("mixes code from a plain javascript object (decorator inside the class body)", () => { expect(el1.methodInPojo2()).toEqual("pojo"); }); }); describe("@template/@style decorators", () => { var el: TemplateTest; beforeEach(() => { el = <any> TemplateTest.create(); querySelector("#put_test_elements_here").appendChild(el); }); // wait for the 'attached' event waitFor(() => (el.bar=="mybar")); it("provide a template for the element", () => { expect(el.$.inner.innerHTML).toBe("inner text"); }); it("provide a style for the element", () => { expect(el.$.inner.clientWidth).toBe(50); }); }); describe("@hostAttributes decorator", () => { var el: HostAttributesTest; beforeEach(() => { el = <any> HostAttributesTest.create(); querySelector("#put_test_elements_here").appendChild(el); }); // wait for the 'attached' event waitFor(() => (el.bar=="mybar")); it("sets attributes on the host element", () => { expect(el.style.color).toBe("red"); }); }); describe("element class", () => { var el: ExtendedElementTest; beforeEach(() => { el = <any> ExtendedElementTest.create(); querySelector("#put_test_elements_here").appendChild(el); }); // wait for the 'attached' event waitFor(() => (el.bar=="mybar")); it("can be extended with 'extends'", () => { expect(el.prop).toBe("AB"); }); it("can be mixed with TypeScript mixins", () => { expect(el.pmix).toBe("C"); }); it("can be extended with multiple level inheritance", () => { expect(el.qmix).toBe("12"); expect(el.is).toEqual("extended-element-test"); }); }); }
the_stack
import { MultiMap, ObjectDictionary, unionInto } from "@opticss/util"; import { CompoundSelector, ParsedSelector, parseSelector, postcss, postcssSelectorParser as selectorParser, } from "opticss"; import { isAttributeNode, isClassNode, isRootNode, toAttrToken } from "../BlockParser"; import { Root as BlockAST } from "../BlockParser/ast"; import { BlockPath, CLASS_NAME_IDENT, DEFAULT_EXPORT, ROOT_CLASS } from "../BlockSyntax"; import { ResolvedConfiguration } from "../configuration"; import { CssBlockError, InvalidBlockSyntax, MultipleCssBlockErrors } from "../errors"; import { FileIdentifier } from "../importing"; import { SourceFile, SourceRange } from "../SourceLocation"; import { BlockClass } from "./BlockClass"; import { Inheritable } from "./Inheritable"; import { Styles } from "./Styles"; /** * In-memory representation of a Block. If you're thinking of CSS Blocks * in relation to the BEM architecture for CSS, this is the... well... "Block". * Well, with a slight caveat.... * * The Block is always the root node of a BlockTree. The Block may be the * parent to any number of BlockClass nodes. Notably, the Block class only * stores meta information about the block. Any CSS properties assigned to the * `:scope` selector are stored on a special BlockClass node that is a child of * the Block. You can access this node directly through the * `rootClass` property. * * Block nodes store all data related to any `@block` imports, the * `block-name`, implemented Blocks, the inherited Block, and any other * metadata stored in the Block file. */ export class Block extends Inheritable<Block, Block, never, BlockClass> { public blockAST?: BlockAST; private _blockReferences: ObjectDictionary<Block> = {}; private _blockReferencesReverseLookup: Map<Block, string> = new Map(); private _blockExports: ObjectDictionary<Block> = {}; private _blockExportReverseLookup: Map<Block, string> = new Map(); private _identifier: FileIdentifier; private _implements: Block[] = []; private _blockErrors: CssBlockError[] = []; private hasHadNameReset = false; /** * A unique identifier for this Block. Generally created from a hash * of the FileIdentifier and other process information. * * For caching to work properly, this GUID must be unique to the block and * shouldn't change between recompiles. You shouldn't use file contents to * create this hash. */ public readonly guid: string; /** * array of paths that this block depends on and, if changed, would * invalidate the compiled css of this block. This is usually only useful in * pre-processed blocks. */ private _dependencies: Set<string>; /** * A direct reference to the BlockClass that holds style information for the * `:scope` selector of this Block. The rootClass is also available through * other traversal methods, as you would access any other BlockClass that * belongs to this Block. */ public readonly rootClass: BlockClass; /** * The PostCSS AST of the stylesheet this Block was built from. Used * primarily for error reporting, if present. */ public stylesheet: postcss.Root | undefined; /** * The PostCSS AST of the compiled CSS this block was built from. * If this is set, the stylesheet property is only the definition file contents. */ public precompiledStylesheet: postcss.Root | undefined; /** * The full contents of the compiled CSS this block was built from, if available. * This content is copied verbatim from the file system and has not been transformed * or processed by PostCSS in any way. */ public precompiledStylesheetUnedited: string | undefined; public blockReferencePaths: Map<string, Block>; private _resolveImplementedBlocksResult: Set<Block> | undefined; /** * Creates a new Block. * * @param name - The default name for this block. This can be reset once (and only once) * using the `setName()` method. * @param identifier - An unique ID referencing the file/blob this Block is created from. * @param guid - The GUID for this block. This GUID should be unique. (BlockFactory is * responsible for enforcing uniqueness.) * @param stylesheet - The PostCSS AST of the stylesheet this block is built from. */ constructor(name: string, identifier: FileIdentifier, guid: string, stylesheet?: postcss.Root, precompiledStylesheet?: postcss.Root) { super(name); this._identifier = identifier; this._dependencies = new Set<string>(); this.rootClass = new BlockClass(ROOT_CLASS, this); this.stylesheet = stylesheet; this.precompiledStylesheet = precompiledStylesheet; this.guid = guid; this.addClass(this.rootClass); this.blockReferencePaths = new Map(); } protected get ChildConstructor(): typeof BlockClass { return BlockClass; } /** @returns This Block's self-proclaimed name. */ public get name(): string { return this.uid; } /** * Sets `name` value of this `Block`. Block names may change depending on the * value passed to its `block-name` property in `:scope`. * @prop name string The new uid for this `Block`. */ public setName(name: string): void { if (this.hasHadNameReset) { throw new CssBlockError("Cannot set block name more than once."); } this._token = name; this.hasHadNameReset = true; } /** * Sets the base Block that this Block inherits from. * @prop base Block The new base Block. */ public setBase(base: Block) { this._base = base; } /** * Lookup a sub-block either locally, or on a referenced foreign block. * @param reference * A reference to a block object adhering to the following grammar: * reference -> <ident> '.' <sub-reference> // reference through sub-block <ident> * | <ident> // reference to sub-block <ident> * | '.' <class-selector> // reference to class in this block * | <attr-selector> // reference to attribute in this block * | '.' // reference to this block * sub-reference -> <ident> '.' <sub-reference> // reference through sub-sub-block * | <object-selector> // reference to object in sub-block * object-selector -> <block-selector> // reference to this sub-block * | <class-selector> // reference to class in sub-block * | <attribute-selector> // reference to attribute in this sub-block * block-selector -> 'root' * class-selector -> <ident> * attribute-selector -> '[' <ident> ']' * ident -> regex:[a-zA-Z_-][a-zA-Z0-9]* * A single dot by itself returns the current block. * @returns The Style referenced at the supplied path. */ public lookup(path: string | BlockPath, errLoc?: SourceRange | SourceFile): Styles | undefined { path = new BlockPath(path); let block = this.getReferencedBlock(path.block); if (!block) { if (errLoc) { throw new InvalidBlockSyntax(`No Block named "${path.block}" found in scope.`, errLoc); } return undefined; } let klass = block.resolveClass(path.class); let attrInfo = path.attribute; let attr; if (klass && attrInfo) { attr = klass.resolveAttributeValue(attrInfo); if (!attr) return undefined; } if (!attr && !klass && errLoc) { throw new InvalidBlockSyntax(`No Style "${path.path}" found on Block "${block.name}".`, errLoc); } return attr || klass || undefined; } /** * Lookup a sub-block either locally, or on a exported foreign block. * @param reference * A reference to a block object adhering to the following grammar: * reference -> <ident> '.' <sub-reference> // reference through sub-block <ident> * | <ident> // reference to sub-block <ident> * | '.' <class-selector> // reference to class in this block * | <attr-selector> // reference to attribute in this block * | '.' // reference to this block * sub-reference -> <ident> '.' <sub-reference> // reference through sub-sub-block * | <object-selector> // reference to object in sub-block * object-selector -> <block-selector> // reference to this sub-block * | <class-selector> // reference to class in sub-block * | <attribute-selector> // reference to attribute in this sub-block * block-selector -> 'root' * class-selector -> <ident> * attribute-selector -> '[' <ident> ']' * ident -> regex:[a-zA-Z_-][a-zA-Z0-9]* * A single dot by itself returns the current block. * @returns The Style referenced at the supplied path. */ public externalLookup(path: string | BlockPath, errLoc?: SourceRange | SourceFile): Styles | undefined { path = new BlockPath(path); let block = this.getExportedBlock(path.block); if (!block) { if (errLoc) { throw new InvalidBlockSyntax(`No Block named "${path.block}" found in scope.`, errLoc); } return undefined; } let klass = block.resolveClass(path.class); let attrInfo = path.attribute; let attr; if (klass && attrInfo) { attr = klass.resolveAttributeValue(attrInfo); if (!attr) return undefined; } if (!attr && !klass && errLoc) { throw new InvalidBlockSyntax(`No Style "${path.path}" found on Block "${block.name}".`, errLoc); } return attr || klass || undefined; } /** * Stores a block error along with the block * @param error CssBlockError that is added to the block */ addError(error: CssBlockError) { this._blockErrors.push(error); } isValid(): boolean { return this._blockErrors.length === 0; } /** * Checks for errors on the block * @returns true if the block is valid else throws the errors on the block */ assertValid(): Block { if (this._blockErrors.length > 1) { throw new MultipleCssBlockErrors(this._blockErrors); } else if (this._blockErrors.length === 1) { throw this._blockErrors[0]; } return this; } /** * Add an absolute, normalized path as a compilation dependency. This is used * to invalidate caches and trigger watchers when those files change. * * It is not necessary or helpful to add css-block files. */ addDependency(filepath: string) { this._dependencies.add(filepath); } get dependencies(): string[] { return new Array(...this._dependencies); } get identifier(): FileIdentifier { return this._identifier; } getClass(name: string): BlockClass | null { return name ? this.getChild(name) : this.getChild(ROOT_CLASS); } resolveClass(name: string): BlockClass | null { return name ? this.resolveChild(name) : this.resolveChild(ROOT_CLASS); } // Alias protected methods from `Inheritable` to Block-specific names, and expose them as a public API. get classes(): BlockClass[] { return this.children(); } addClass(blockClass: BlockClass) { this.setChild(blockClass.name, blockClass); } ensureClass(name: string): BlockClass { return this.ensureChild(name); } getImplementedBlocks(): Block[] { return this._implements.slice(); } addImplementation(b: Block) { return this._implements.push(b); } /** * Validate that this block implements all foreign selectors from blocks it implements. * @param b The block to check implementation against. * @returns The Styles from b that are missing in the block. */ checkImplementation(b: Block): Styles[] { let missing: Styles[] = []; for (let o of b.all()) { if (!this.find(o.asSource())) { missing.push(o); } } return missing; } /** * Validate that all foreign blocks this block implements are fully...implemented. */ checkImplementations(): void { for (let b of this.getImplementedBlocks()) { let missing: Styles[] = this.checkImplementation(b); let paths = missing.map(o => o.asSource()).join(", "); if (missing.length > 0) { let s = missing.length > 1 ? "s" : ""; throw new CssBlockError(`Missing implementation${s} for: ${paths} from ${b.identifier}`); } } } // This is a really dumb impl find(sourceName: string): Styles | undefined { let blockRefName: string | undefined; let blockName = sourceName.split(/\>|\.|\:|\[/)[0]; let md = blockName.match(CLASS_NAME_IDENT); if (md && md.index === 0) { blockRefName = md[0]; let blockRef: Block | undefined; this.eachBlockReference((name, block) => { if (blockRefName === name) { blockRef = block; } }); if (blockRef) { if (md[0].length === sourceName.length) { return blockRef.rootClass; } let rest = sourceName.slice(md[0].length); if (rest.startsWith(">")) { rest = rest.slice(1); } return blockRef.find(rest); } else { return undefined; } } return this.all().find(e => e.asSource() === sourceName); } eachBlockReference(callback: (name: string, block: Block) => unknown) { for (let name of Object.keys(this._blockReferences)) { callback(name, this._blockReferences[name]); } } /** * Add a Block reference accessible internally to the block as `localName`. * @param localName The name to expose this block internally as. * @param block The block to expose internally. */ addBlockReference(localName: string, block: Block) { this._blockReferences[localName] = block; this._blockReferencesReverseLookup.set(block, localName); } /** * Get an imported Block at name `localName`. * @param localName The local name name of the requested imported block. * @returns Block | null. */ getReferencedBlock(localName: string): Block | null { if (localName === DEFAULT_EXPORT) { return this; } return this._blockReferences[localName] || null; } /** * Reverse imported Block lookup. Given a Block, return its private local alias. * @param block The requested Block to lookup. * @returns string | null. */ getReferencedBlockLocalName(block: Block | undefined): string | null { return block && this._blockReferencesReverseLookup.get(block) || null; } /** * Add a Block export to be exposed to importers at name `remoteName`. * @param remoteName The name to expose this block publicly as. * @param block The block to expose publicly. */ addBlockExport(remoteName: string, block: Block) { this._blockExports[remoteName] = block; this._blockExportReverseLookup.set(block, remoteName); } /** * Iterates over each exported block, applying the callback to it * @param callback the function to iterate over each exported block */ eachBlockExport(callback: (name: string, block: Block) => unknown) { for (let name of Object.keys(this._blockExports)) { callback(name, this._blockExports[name]); } } /** * Get an exported Block at name `remoteName`. * @param remoteName The public name of the requested exported block. * @returns Block | null. */ getExportedBlock(remoteName: string): Block | null { return this._blockExports[remoteName] || null; } /** * Reverse exported Block lookup. Given a Block, return its publicly exported name. * @param block The requested Block to lookup. * @returns string | null. */ getExportedBlockRemoteName(block: Block | undefined): string | null { return block && this._blockExportReverseLookup.get(block) || null; } transitiveBlockDependencies(): Set<Block> { let deps = new Set<Block>(); this.eachBlockReference((_name, block) => { deps.add(block); let moreDeps = block.transitiveBlockDependencies(); if (moreDeps.size > 0) { deps = new Set([...deps, ...moreDeps]); } }); return deps; } /** * Returns a new array of ancestors in order of inheritance * with the first one being the immediate super block. * * If this block doesn't inherit, the array is empty. **/ getAncestors(): Array<Block> { let inherited = new Array<Block>(); let base = this.base; while (base) { inherited.push(base); base = base.base; } return inherited; } /** * Return array self and all children. * @param shallow Pass true to not include inherited objects. * @returns Array of Styles. */ all(shallow?: boolean): Styles[] { let result = new Array<Styles>(); for (let blockClass of this.classes) { result.push(...blockClass.all()); } if (!shallow && this.base) { result.push(...this.base.all(shallow)); } return result; } /** * Outputs a dictionary of style source string to most specific style in the * inheritance hierarchy. */ resolvedStyleInterface(): ObjectDictionary<Styles> { // starting with the base block and working up to the most specific sub-block // we record the most specific style associated with the style name for the given block. let blocks = [...this.resolveInheritance(), this]; let styleInterface: ObjectDictionary<Styles> = {}; for (let b of blocks) { let styles = b.all(true); for (let style of styles) { styleInterface[style.asSource()] = style; } } return styleInterface; } /** * Fetch a dictionary of styles associated with this block, using any preset * selector as the key. If a given style doesn't have a preset selector, it * will be excluded from this dictionary. * * @param shallow - Pass true to exclude inherited objects. * @returns Collection of Styles objects, organized by preset selector value. */ presetClassesMap(shallow?: boolean): ObjectDictionary<Styles> { const result = {}; const all = this.all(shallow); all.forEach(el => { const presetCssClass = el.presetCssClass; if (presetCssClass) { result[presetCssClass] = el; } }); return result; } merged(): MultiMap<string, Styles> { let map = new MultiMap<string, Styles>(false); for (let obj of this.all()) { map.set(obj.asSource(), obj); } return map; } /** * Return all the style aliases defined on the block. * @returns Array of style aliases. */ getAllStyleAliases(): Set<string> { let result = new Set<string>(); for (let blockClass of this.classes) { // add aliases on the block class blockClass.getStyleAliases().forEach(alias => result.add(alias)); // add aliases for each of the state attributes within the block class blockClass.allAttributeValues().forEach(value => value.getStyleAliases().forEach(alias => result.add(alias))); } return result; } nodeAsStyle(node: selectorParser.Node): [Styles, number] | null { let next = node.next(); if (isRootNode(node) && next && isAttributeNode(next) && typeof next.namespace === "string") { let otherBlock = this.getReferencedBlock(next.namespace); if (otherBlock) { if (next && isClassNode(next)) { let klass = otherBlock.getClass(next.value); if (klass) { let another = next.next(); if (another && isAttributeNode(another)) { let attr = klass.getAttributeValue(toAttrToken(another)); if (attr) { return [attr, 2]; } else { return null; // this is invalid and should never happen. } } else { // we don't allow scoped classes not part of a state return null; // this is invalid and should never happen. } } else { return null; } } else if (next && isAttributeNode(next)) { let attr = otherBlock.rootClass.getAttributeValue(toAttrToken(next)); if (attr) { return [attr, 1]; } else { return null; } } else { return null; } } else { return null; } } else if (selectorParser.isClassName(node) || isRootNode(node)) { let klass = this.getClass(node.value); if (klass === null) { return null; } let next = node.next(); if (next && isAttributeNode(next)) { let attr = klass.getAttributeValue(toAttrToken(next)); if (attr === null) { return null; } else { return [attr, 1]; } } else { return [klass, 0]; } } else if (isAttributeNode(node)) { let prevNode = node.prev(); while (prevNode && !(selectorParser.isClassName(prevNode) || isRootNode(prevNode))) { prevNode = prevNode.prev(); } if (!prevNode) { throw new Error("internal error - illegal selector encountered after validation."); } let klass = this.getClass(prevNode.value); let attr = klass?.getAttributeValue(toAttrToken(node)); if (attr) { return [attr, 0]; } else { return null; } } return null; } rewriteSelectorNodes(nodes: selectorParser.Node[], config: ResolvedConfiguration, reservedClassNames: Set<string>): selectorParser.Node[] { let newNodes: selectorParser.Node[] = []; for (let i = 0; i < nodes.length; i++) { let node = nodes[i]; let result = this.nodeAsStyle(node); if (result === null) { newNodes.push(node); } else { newNodes.push(selectorParser.className({ value: result[0].cssClass(config, reservedClassNames)})); i += result[1]; } } return newNodes; } rewriteSelectorToString(selector: ParsedSelector, config: ResolvedConfiguration, reservedClassNames: Set<string>): string { let firstNewSelector = new CompoundSelector(); let newSelector = firstNewSelector; let newCurrentSelector = newSelector; let currentSelector: CompoundSelector | undefined = selector.selector; do { newCurrentSelector.nodes = this.rewriteSelectorNodes(currentSelector.nodes, config, reservedClassNames); newCurrentSelector.pseudoelement = currentSelector.pseudoelement; if (currentSelector.next !== undefined) { let tempSel = newCurrentSelector; newCurrentSelector = new CompoundSelector(); tempSel.setNext(currentSelector.next.combinator, newCurrentSelector); currentSelector = currentSelector.next.selector; } else { currentSelector = undefined; } } while (currentSelector !== undefined); return firstNewSelector.toString(); } rewriteSelector(selector: ParsedSelector, config: ResolvedConfiguration, reservedClassNames: Set<string>): ParsedSelector { // generating a string and re-parsing ensures the internal structure is consistent // otherwise the parent/next/prev relationships will be wonky with the new nodes. let s = this.rewriteSelectorToString(selector, config, reservedClassNames); return parseSelector(s)[0]; } debug(config: ResolvedConfiguration): string[] { let result: string[] = [`Source: ${this.identifier}`]; // Log Root Class and all children first at root level. // NOTE: debug statements don't take into account the reservedClassNames as // debug happens during parse and we can only get the entire list of // reservedClassNames once block parsing is complete const classes = [...this.rootClass.cssClasses(config, new Set())].join("."); const aliases = this.rootClass.getStyleAliases(); result.push(`${ROOT_CLASS} (.${classes}${aliases.size ? `, aliases: .${[...aliases].join(" .")}` : ""})`, ...this.rootClass.debug(config)); // Log all BlockClasses and children at second level. let sourceNames = new Set<string>(this.resolveChildren().map(s => s.asSource())); let sortedNames = [...sourceNames].sort().filter((n) => n !== ROOT_CLASS); for (let n of sortedNames) { const isLast = sortedNames.indexOf(n) === sortedNames.length - 1; let o = this.find(n) as BlockClass; result.push(` ${isLast ? "└──" : "├──"} ${o.asDebug(config)}`); const childrenDebugs = o.debug(config).map((s) => ` ${isLast ? " " : "|"} ${s}`); result.push(...childrenDebugs); } return result; } /** * Test if the supplied block is the same block object. * @param other The other Block to test against. * @return True or False if self and `other` are equal. */ equal(other: Block | undefined | null) { return other && this.identifier === other.identifier; } isAncestorOf(other: Block | undefined | null): boolean { let base: Block | undefined | null = other && other.base; while (base) { if (this.equal(base)) { return true; } else { base = base.base; } } return false; } /** * Gets all the blocks that are implemented by this block or by any ancestor. * This includes: * - This block. * - The blocks this block inherits from. * - The blocks the above blocks explicitly declare that they implement. * - The blocks all the above blocks implement transitively. * Such that `blockA.resolveImplementedBlocks().has(blockB)` is true iff * `blockA` implements the interface of `blockB`. */ resolveImplementedBlocks(): Set<Block> { if (this._resolveImplementedBlocksResult) { return this._resolveImplementedBlocksResult; } let implemented = new Set<Block>([this]); if (this._base) { unionInto(implemented, this._base.resolveImplementedBlocks()); } for (let impl of this.getImplementedBlocks()) { unionInto(implemented, impl.resolveImplementedBlocks()); } this._resolveImplementedBlocksResult = implemented; return implemented; } isImplementationOf(other: Block): boolean { return this.resolveImplementedBlocks().has(other); } /** * Objects that contain Blocks are often passed into assorted libraries' options * hashes. Some libraries like to `JSON.stringify()` their options to create * unique identifiers for re-run caching. (ex: Webpack, awesome-typescript-loader) * Blocks contain circular dependencies, so we need to override their `toJSON` * method so these libraries don't implode. * @return The name of the block. */ toJSON() { return this._token; } } export function isBlock(o?: object): o is Block { return o instanceof Block; }
the_stack
import { assetManager, Color, director, dynamicAtlasManager, fragmentText, getBaselineOffset, HorizontalTextAlignment, IAssembler, js, Label, LabelOutline, LabelShadow, Rect, safeMeasureText, Size, SpriteFrame, Texture2D, UITransform, Vec2, VerticalTextAlignment, __private, BASELINE_RATIO, } from "cc"; const Overflow = Label.Overflow; const MAX_SIZE = 2048; const _BASELINE_OFFSET = getBaselineOffset(); let _context: CanvasRenderingContext2D | null = null; let _canvas: HTMLCanvasElement | null = null; let _texture: SpriteFrame | __private.cocos_2d_assembler_label_font_utils_LetterRenderTexture | null = null; let _fontDesc = ''; let _string = ''; let _fontSize = 0; let _drawFontsize = 0; let _splitStrings: string[] = []; const _canvasSize = new Size(); let _lineHeight = 0; let _hAlign = 0; let _vAlign = 0; let _color = new Color(); let _fontFamily = ''; let _overflow = Overflow.NONE; let _isWrapText = false; // outline let _outlineComp: LabelOutline | null = null; const _outlineColor = Color.BLACK.clone(); // shadow let _shadowComp: LabelShadow | null = null; const _shadowColor = Color.BLACK.clone(); const _canvasPadding = new Rect(); const _contentSizeExtend = Size.ZERO.clone(); const _nodeContentSize = Size.ZERO.clone(); const _startPosition = Vec2.ZERO.clone(); const _drawUnderlinePos = Vec2.ZERO.clone(); let _drawUnderlineWidth = 0; let _underlineThickness = 0; let _isBold = false; let _isItalic = false; let _isUnderline = false; const Alignment = [ 'left', // macro.TextAlignment.LEFT 'center', // macro.TextAlignment.CENTER 'right', // macro.TextAlignment.RIGHT ]; export const ttfUtils = { getAssemblerData() { const sharedLabelData = Label._canvasPool.get(); return sharedLabelData; }, resetAssemblerData(assemblerData: __private.cocos_2d_assembler_label_font_utils_ISharedLabelData) { if (assemblerData) { Label._canvasPool.put(assemblerData); } }, updateRenderData(comp: Label) { if (!comp.renderData || !comp.renderData.vertDirty) { return; } const trans = comp.node._uiProps.uiTransformComp!; this._updateFontFamily(comp); this._updateProperties(comp, trans); this._calculateLabelFont(); this._updateLabelDimensions(); this._resetDynamicAtlas(comp); this._updateTexture(); this._calDynamicAtlas(comp); comp.actualFontSize = _fontSize; trans.setContentSize(_canvasSize); this.updateVertexData(comp); this.updateUvs(comp); comp.markForUpdateRenderData(false); _context = null; _canvas = null; _texture = null; }, updateVertexData(comp: Label) { }, updateUvs(comp: Label) { }, _updateFontFamily(comp: Label) { if (!comp.useSystemFont) { if (comp.font) { if (comp.font._nativeAsset) { _fontFamily = comp.font._nativeAsset; } else { assetManager.postLoadNative(comp.font, (err) => { if (!comp.isValid) { return; } _fontFamily = comp.font!._nativeAsset || 'Arial'; comp.updateRenderData(true); }); _fontFamily = 'Arial'; } } else { _fontFamily = 'Arial'; } } else { _fontFamily = comp.fontFamily || 'Arial'; } }, _updateProperties(comp: Label, trans: UITransform) { const assemblerData = comp.assemblerData; if (!assemblerData) { return; } _context = assemblerData.context; _canvas = assemblerData.canvas; _texture = comp.spriteFrame; _string = comp.string.toString(); _fontSize = comp.fontSize; _drawFontsize = _fontSize; _overflow = comp.overflow; _nodeContentSize.width = _canvasSize.width = trans.width; _nodeContentSize.height = _canvasSize.height = trans.height; _underlineThickness = comp.underlineHeight; _lineHeight = comp.lineHeight; _hAlign = comp.horizontalAlign; _vAlign = comp.verticalAlign; _color = comp.color; _isBold = comp.isBold; _isItalic = comp.isItalic; _isUnderline = comp.isUnderline; if (_overflow === Overflow.NONE) { _isWrapText = false; } else if (_overflow === Overflow.RESIZE_HEIGHT) { _isWrapText = true; } else { _isWrapText = comp.enableWrapText; } // outline _outlineComp = LabelOutline && comp.getComponent(LabelOutline); _outlineComp = (_outlineComp && _outlineComp.enabled && _outlineComp.width > 0) ? _outlineComp : null; if (_outlineComp) { _outlineColor.set(_outlineComp.color); } // shadow _shadowComp = LabelShadow && comp.getComponent(LabelShadow); _shadowComp = (_shadowComp && _shadowComp.enabled) ? _shadowComp : null; if (_shadowComp) { _shadowColor.set(_shadowComp.color); } this._updatePaddingRect(); }, _updatePaddingRect() { let top = 0; let bottom = 0; let left = 0; let right = 0; let outlineWidth = 0; _contentSizeExtend.width = _contentSizeExtend.height = 0; if (_outlineComp) { outlineWidth = _outlineComp.width; top = bottom = left = right = outlineWidth; _contentSizeExtend.width = _contentSizeExtend.height = outlineWidth * 2; } if (_shadowComp) { const shadowWidth = _shadowComp.blur + outlineWidth; const offsetX = _shadowComp.offset.x; const offsetY = _shadowComp.offset.y; left = Math.max(left, -offsetX + shadowWidth); right = Math.max(right, offsetX + shadowWidth); top = Math.max(top, offsetY + shadowWidth); bottom = Math.max(bottom, -offsetY + shadowWidth); } if (_isItalic) { // 0.0174532925 = 3.141592653 / 180 const offset = _drawFontsize * Math.tan(12 * 0.0174532925); right += offset; _contentSizeExtend.width += offset; } _canvasPadding.x = left; _canvasPadding.y = top; _canvasPadding.width = left + right; _canvasPadding.height = top + bottom; }, _calculateFillTextStartPosition() { //todo 计算不同对齐模式 const lineHeight = this._getLineHeight(); const drawStartX = lineHeight * (_splitStrings.length - 0.5); _startPosition.set(drawStartX, 0) }, _updateTexture() { if (!_context || !_canvas) { return; } _context.clearRect(0, 0, _canvas.width, _canvas.height); _context.font = _fontDesc; this._calculateFillTextStartPosition(); const lineHeight = this._getLineHeight(); // use round for line join to avoid sharp intersect point _context.lineJoin = 'round'; _context.fillStyle = `rgba(${_color.r}, ${_color.g}, ${_color.b}, 1)`; // draw shadow and underline //todo // this._drawTextEffect(_startPosition, lineHeight); // draw text and outline for (let i = 0; i < _splitStrings.length; ++i) { let drawTextPosX = _startPosition.x - i * lineHeight; let drawTextPosY = _startPosition.y; for (let ii = 0; ii < _splitStrings[i].length; ii++) { const str = _splitStrings[i].slice(ii, ii + 1).toString(); if (_outlineComp) { _context.strokeText(str, drawTextPosX, drawTextPosY); } _context.fillText(str, drawTextPosX, drawTextPosY); drawTextPosY += this._measureSingleStrHeight(str); } } if (_shadowComp) { _context.shadowColor = 'transparent'; } // _texture.handleLoadedTexture(); if (_texture) { let tex: Texture2D; if (_texture instanceof SpriteFrame) { tex = (_texture.texture as Texture2D); } else { tex = _texture; } const uploadAgain = _canvas.width !== 0 && _canvas.height !== 0; if (uploadAgain) { tex.reset({ width: _canvas.width, height: _canvas.height, mipmapLevel: 1, }); tex.uploadData(_canvas); if (_texture instanceof SpriteFrame) { _texture.rect = new Rect(0, 0, _canvas.width, _canvas.height); _texture._calculateUV(); } if (director.root && director.root.batcher2D) { //@ts-ignore director.root.batcher2D._releaseDescriptorSetCache(tex.getHash()); } } } }, _resetDynamicAtlas(comp: Label) { if (comp.cacheMode !== Label.CacheMode.BITMAP) return; const frame = comp.ttfSpriteFrame!; dynamicAtlasManager.deleteAtlasSpriteFrame(frame); frame._resetDynamicAtlasFrame(); }, _calDynamicAtlas(comp: Label) { if (comp.cacheMode !== Label.CacheMode.BITMAP) return; const frame = comp.ttfSpriteFrame!; dynamicAtlasManager.packToDynamicAtlas(comp, frame); comp.renderData!.uvDirty = true; }, _setupOutline() { _context!.strokeStyle = `rgba(${_outlineColor.r}, ${_outlineColor.g}, ${_outlineColor.b}, ${_outlineColor.a / 255})`; _context!.lineWidth = _outlineComp!.width * 2; }, _setupShadow() { _context!.shadowColor = `rgba(${_shadowColor.r}, ${_shadowColor.g}, ${_shadowColor.b}, ${_shadowColor.a / 255})`; _context!.shadowBlur = _shadowComp!.blur; _context!.shadowOffsetX = _shadowComp!.offset.x; _context!.shadowOffsetY = -_shadowComp!.offset.y; }, _drawTextEffect(startPosition: Vec2, lineHeight: number) { if (!_shadowComp && !_outlineComp && !_isUnderline) return; const isMultiple = _splitStrings.length > 1 && _shadowComp; const measureText = this._measureText(_context!, _fontDesc); let drawTextPosX = 0; let drawTextPosY = 0; // only one set shadow and outline if (_shadowComp) { this._setupShadow(); } if (_outlineComp) { this._setupOutline(); } // draw shadow and (outline or text) for (let i = 0; i < _splitStrings.length; ++i) { drawTextPosX = startPosition.x; drawTextPosY = startPosition.y + i * lineHeight; // multiple lines need to be drawn outline and fill text if (isMultiple) { if (_outlineComp) { _context!.strokeText(_splitStrings[i], drawTextPosX, drawTextPosY); } _context!.fillText(_splitStrings[i], drawTextPosX, drawTextPosY); } // draw underline if (_isUnderline) { _drawUnderlineWidth = measureText(_splitStrings[i]); if (_hAlign === HorizontalTextAlignment.RIGHT) { _drawUnderlinePos.x = startPosition.x - _drawUnderlineWidth; } else if (_hAlign === HorizontalTextAlignment.CENTER) { _drawUnderlinePos.x = startPosition.x - (_drawUnderlineWidth / 2); } else { _drawUnderlinePos.x = startPosition.x; } _drawUnderlinePos.y = drawTextPosY + _drawFontsize / 8; _context!.fillRect(_drawUnderlinePos.x, _drawUnderlinePos.y, _drawUnderlineWidth, _underlineThickness); } } if (isMultiple) { _context!.shadowColor = 'transparent'; } }, _updateLabelDimensions() { _canvasSize.width = Math.min(_canvasSize.width, MAX_SIZE); _canvasSize.height = Math.min(_canvasSize.height, MAX_SIZE); let recreate = false; if (_canvas!.width !== _canvasSize.width) { _canvas!.width = _canvasSize.width; recreate = true; } if (_canvas!.height !== _canvasSize.height) { _canvas!.height = _canvasSize.height; recreate = true; } if (recreate) _context!.font = _fontDesc; // align _context!.textAlign = 'center'; _context!.textBaseline = 'top'; }, _getFontDesc() { let fontDesc = `${_fontSize.toString()}px `; fontDesc += _fontFamily; if (_isBold) { fontDesc = `bold ${fontDesc}`; } if (_isItalic) { fontDesc = `italic ${fontDesc}`; } return fontDesc; }, _getLineHeight() { let nodeSpacingY = _lineHeight; if (nodeSpacingY === 0) { nodeSpacingY = _fontSize; } else { nodeSpacingY = nodeSpacingY * _fontSize / _drawFontsize; } return nodeSpacingY | 0; }, _calculateParagraphLength(paragraphedStrings: string[], ctx: CanvasRenderingContext2D) { const paragraphLength: number[] = []; for (const para of paragraphedStrings) { const width: number = safeMeasureText(ctx, para, _fontDesc); paragraphLength.push(width); } return paragraphLength; }, _measureText(ctx: CanvasRenderingContext2D, fontDesc: string) { // eslint-disable-next-line @typescript-eslint/no-unsafe-return return (string: string) => safeMeasureText(ctx, string, fontDesc); }, _measureSingleStrHeight(str: string): number { if (!_context) return 0; const width = this._measureText(_context, _fontDesc)(str) if (str === ' ') { return width } return width > 0 ? _fontSize : 0; }, _calculateShrinkFont(paragraphedStrings: string[]) { if (!_context) return; const paragraphLength = this._calculateParagraphLength(paragraphedStrings, _context); let i = 0; let totalHeight = 0; let maxLength = 0; if (_isWrapText) { const canvasWidthNoMargin = _nodeContentSize.width; const canvasHeightNoMargin = _nodeContentSize.height; if (canvasWidthNoMargin < 0 || canvasHeightNoMargin < 0) { return; } totalHeight = canvasHeightNoMargin + 1; const actualFontSize = _fontSize + 1; let textFragment: string[] = []; let left = 0; let right = actualFontSize | 0; let mid = 0; while (left < right) { mid = (left + right + 1) >> 1; if (mid <= 0) { // logID(4003); break; } _fontSize = mid; _fontDesc = this._getFontDesc(); _context.font = _fontDesc; const lineHeight = this._getLineHeight(); totalHeight = 0; for (i = 0; i < paragraphedStrings.length; ++i) { const allWidth = safeMeasureText(_context, paragraphedStrings[i], _fontDesc); textFragment = fragmentText(paragraphedStrings[i], allWidth, canvasWidthNoMargin, this._measureText(_context, _fontDesc)); totalHeight += textFragment.length * lineHeight; } if (totalHeight > canvasHeightNoMargin) { right = mid - 1; } else { left = mid; } } if (left === 0) { // logID(4003); } else { _fontSize = left; _fontDesc = this._getFontDesc(); _context.font = _fontDesc; } } else { totalHeight = paragraphedStrings.length * this._getLineHeight(); for (i = 0; i < paragraphedStrings.length; ++i) { if (maxLength < paragraphLength[i]) { maxLength = paragraphLength[i]; } } const scaleX = (_canvasSize.width - _canvasPadding.width) / maxLength; const scaleY = _canvasSize.height / totalHeight; _fontSize = (_drawFontsize * Math.min(1, scaleX, scaleY)) | 0; _fontDesc = this._getFontDesc(); _context.font = _fontDesc; } }, _calculateWrapText(paragraphedStrings: string[]) { if (!_isWrapText || !_context) return; _splitStrings = []; const canvasWidthNoMargin = _nodeContentSize.width; for (let i = 0; i < paragraphedStrings.length; ++i) { const allWidth = safeMeasureText(_context, paragraphedStrings[i], _fontDesc); const textFragment = fragmentText(paragraphedStrings[i], allWidth, canvasWidthNoMargin, this._measureText(_context, _fontDesc)); _splitStrings = _splitStrings.concat(textFragment); } }, _calculateLabelFont() { if (!_context) { return; } const paragraphedStrings = _string.split('\n'); _splitStrings = paragraphedStrings; _fontDesc = this._getFontDesc(); _context.font = _fontDesc; switch (_overflow) { case Overflow.NONE: { let canvasSizeX = 0; let canvasSizeY = 0; for (let i = 0; i < _splitStrings.length; ++i) { let paraLength = 0 for (let ii = 0; ii < _splitStrings[i].length; ii++) { const str = _splitStrings[i].slice(ii, ii + 1).toString(); paraLength += this._measureSingleStrHeight(str); } canvasSizeY = canvasSizeY > paraLength ? canvasSizeY : paraLength; } canvasSizeX = (_splitStrings.length + BASELINE_RATIO) * this._getLineHeight(); const rawWidth = parseFloat(canvasSizeX.toFixed(2)); const rawHeight = parseFloat(canvasSizeY.toFixed(2)); _canvasSize.width = rawWidth + _canvasPadding.width; _canvasSize.height = rawHeight + _canvasPadding.height; _nodeContentSize.width = rawWidth + _contentSizeExtend.width; _nodeContentSize.height = rawHeight + _contentSizeExtend.height; break; } case Overflow.SHRINK: { //todo this._calculateShrinkFont(paragraphedStrings); this._calculateWrapText(paragraphedStrings); break; } case Overflow.CLAMP: { //todo this._calculateWrapText(paragraphedStrings); break; } case Overflow.RESIZE_HEIGHT: { //todo this._calculateWrapText(paragraphedStrings); const rawHeight = (_splitStrings.length + BASELINE_RATIO) * this._getLineHeight(); _canvasSize.height = rawHeight + _canvasPadding.height; // set node height _nodeContentSize.height = rawHeight + _contentSizeExtend.height; break; } default: { // nop } } }, }; const WHITE = Color.WHITE.clone(); /** * ttf 组装器 * 可通过 `UI.ttf` 获取该组装器。 */ export const verticalttf: IAssembler = { createData(comp: Label) { const renderData = comp.requestRenderData()!; renderData.dataLength = 4; renderData.vertexCount = 4; renderData.indicesCount = 6; const vData = renderData.vData = new Float32Array(4 * 9); vData[3] = vData[21] = vData[22] = vData[31] = 0; vData[4] = vData[12] = vData[13] = vData[30] = 1; let offset = 5; for (let i = 0; i < 4; i++) { Color.toArray(vData, WHITE, offset); offset += 9; } return renderData; }, fillBuffers(comp: Label, renderer: any) { const renderData = comp.renderData!; const dataList: __private.cocos_2d_renderer_render_data_IRenderData[] = renderData.data; const node = comp.node; let buffer = renderer.acquireBufferBatch()!; let vertexOffset = buffer.byteOffset >> 2; let indicesOffset = buffer.indicesOffset; let vertexId = buffer.vertexOffset; const isRecreate = buffer.request(); if (!isRecreate) { buffer = renderer.currBufferBatch!; indicesOffset = 0; vertexId = 0; vertexOffset = 0; } // buffer data may be reallocated, need get reference after request. const vBuf = buffer.vData!; const iBuf = buffer.iData!; const vData = renderData.vData!; const data0 = dataList[0]; const data3 = dataList[3]; /* */ node.updateWorldTransform(); // @ts-expect-error private property access const pos = node._pos; const rot = node._rot; const scale = node._scale; const ax = data0.x * scale.x; const bx = data3.x * scale.x; const ay = data0.y * scale.y; const by = data3.y * scale.y; const qx = rot.x; const qy = rot.y; const qz = rot.z; const qw = rot.w; const qxy = qx * qy; const qzw = qz * qw; const qxy2 = qx * qx - qy * qy; const qzw2 = qw * qw - qz * qz; const cx1 = qzw2 + qxy2; const cx2 = (qxy - qzw) * 2; const cy1 = qzw2 - qxy2; const cy2 = (qxy + qzw) * 2; const x = pos.x; const y = pos.y; // left bottom vData[0] = cx1 * ax + cx2 * ay + x; vData[1] = cy1 * ay + cy2 * ax + y; // right bottom vData[9] = cx1 * bx + cx2 * ay + x; vData[10] = cy1 * ay + cy2 * bx + y; // left top vData[18] = cx1 * ax + cx2 * by + x; vData[19] = cy1 * by + cy2 * ax + y; // right top vData[27] = cx1 * bx + cx2 * by + x; vData[28] = cy1 * by + cy2 * bx + y; vBuf.set(vData, vertexOffset); // fill index data iBuf[indicesOffset++] = vertexId; iBuf[indicesOffset++] = vertexId + 1; iBuf[indicesOffset++] = vertexId + 2; iBuf[indicesOffset++] = vertexId + 2; iBuf[indicesOffset++] = vertexId + 1; iBuf[indicesOffset++] = vertexId + 3; }, updateVertexData(comp: Label) { const renderData = comp.renderData; if (!renderData) { return; } const uiTrans = comp.node._uiProps.uiTransformComp!; const width = uiTrans.width; const height = uiTrans.height; const appX = uiTrans.anchorX * width; const appY = uiTrans.anchorY * height; const data = renderData.data; data[0].x = -appX; data[0].y = -appY; data[3].x = width - appX; data[3].y = height - appY; }, updateUvs(comp: Label) { const renderData = comp.renderData; if (!renderData) { return; } const vData = renderData.vData!; if (!vData || !renderData.uvDirty) { return; } const uv = comp.ttfSpriteFrame!.uv; vData[3] = uv[0]; vData[4] = uv[1]; vData[12] = uv[2]; vData[13] = uv[3]; vData[21] = uv[4]; vData[22] = uv[5]; vData[30] = uv[6]; vData[31] = uv[7]; renderData.uvDirty = false; }, }; js.addon(verticalttf, ttfUtils); /* 欢迎关注微信公众号 `白玉无冰` 导航:https://mp.weixin.qq.com/s/Ht0kIbaeBEds_wUeUlu8JQ █████████████████████████████████████ █████████████████████████████████████ ████ ▄▄▄▄▄ █▀█ █▄██▀▄ ▄▄██ ▄▄▄▄▄ ████ ████ █ █ █▀▀▀█ ▀▄▀▀▀█▄▀█ █ █ ████ ████ █▄▄▄█ █▀ █▀▀▀ ▀▄▄ ▄ █ █▄▄▄█ ████ ████▄▄▄▄▄▄▄█▄▀ ▀▄█ ▀▄█▄▀ █▄▄▄▄▄▄▄████ ████▄▄ ▄▀▄▄ ▄▀▄▀▀▄▄▄ █ █ ▀ ▀▄█▄▀████ ████▀ ▄ █▄█▀█▄█▀█ ▀▄ █ ▀ ▄▄██▀█████ ████ ▄▀▄▄▀▄ █▄▄█▄ ▀▄▀ ▀ ▀ ▀▀▀▄ █▀████ ████▀ ██ ▀▄ ▄██ ▄█▀▄ ██▀ ▀ █▄█▄▀█████ ████ ▄██▄▀ █▀▄▀▄▀▄▄▄▄ ▀█▀ ▀▀ █▀████ ████ █▄ █ ▄ █▀ █▀▄█▄▄▄▄▀▄▄█▄▄▄▄▀█████ ████▄█▄█▄█▄█▀ ▄█▄ ▀▄██ ▄▄▄ ▀ ████ ████ ▄▄▄▄▄ █▄██ ▄█▀ ▄ █▄█ ▄▀█████ ████ █ █ █ ▄█▄ ▀ ▀▀██ ▄▄▄▄ ▄▀ ████ ████ █▄▄▄█ █ ▄▄▀ ▄█▄█▄█▄ ▀▄ ▄ █████ ████▄▄▄▄▄▄▄█▄██▄▄██▄▄▄█████▄▄█▄██████ █████████████████████████████████████ █████████████████████████████████████ author: http://lamyoung.com/ B站视频: https://space.bilibili.com/1756070/video github: https://github.com/baiyuwubing gitee 同步地址: https://gitee.com/lamyoung qq 交流群: 859642112 Cocos 论坛 : https://forum.cocos.org/u/lamyoung/activity/topics */
the_stack
import { kebabCase } from '@aurelia/kernel'; import SaxStream, { TextToken } from 'parse5-sax-parser'; import { TextDocument } from 'vscode-languageserver-textdocument'; import { AureliaView, interpolationRegex } from '../../common/constants'; import { Logger } from '../../common/logging/logger'; import { getBindableNameFromAttritute } from '../../common/template/aurelia-attributes'; import { AURELIA_ATTRIBUTES_KEYWORDS } from '../../feature/configuration/DocumentSettings'; import { IAureliaComponent } from '../viewModel/AureliaProgram'; import { AbstractRegion, AttributeInterpolationRegion, AttributeRegion, BindableAttributeRegion, CustomElementRegion, RepeatForRegion, TextInterpolationRegion, ViewRegionInfoV2, ValueConverterRegion, Optional, ImportRegion, } from './ViewRegions'; const logger = new Logger('RegionParser'); const OBJECT_PLACEHOLDER = '[o]'; interface PrettyOptions< Regions extends AbstractRegion[], IgnoreKey extends keyof Regions[number] > { ignoreKeys?: IgnoreKey[]; asTable?: boolean; maxColWidth?: number; } export class RegionParser { public static parse( document: TextDocument, componentList: Optional<IAureliaComponent, 'viewRegions'>[] ): AbstractRegion[] { const saxStream = new SaxStream({ sourceCodeLocationInfo: true }); /* prettier-ignore */ logger.culogger.debug(['Start document parsing'], { logLevel: 'INFO' }); const viewRegions: AbstractRegion[] = []; const aureliaCustomElementNames = componentList.map( (component) => component.componentName ); const documentHasCrlf = document.getText().includes('\r\n'); let hasTemplateTag = false; /** * 1. Template Tag x * 2. Attributes x * 3. Attribute Interpolation x * 4. Custom element x * 5. repeat.for="" x * 6. Value converter region (value | take:10) * 7. BindableAttribute x * 8. Import */ saxStream.on('startTag', (startTag) => { // 0. Prep const tagName = startTag.tagName; // 1. Template Tag const isTemplateTag = tagName === AureliaView.TEMPLATE_TAG_NAME; if (isTemplateTag) { // eslint-disable-next-line @typescript-eslint/no-unused-vars hasTemplateTag = true; } const isImportTag = getIsImportOrRequireTag(startTag); if (isImportTag) { const importRegion = ImportRegion.parse5(startTag); if (importRegion) { viewRegions.push(importRegion); } return; } const attributeRegions: AbstractRegion[] = []; startTag.attrs.forEach((attr) => { const isAttributeKeyword = AURELIA_ATTRIBUTES_KEYWORDS.some( (keyword) => { if (keyword === 'ref') { return attr.name === keyword; } else if (keyword === 'bindable') { return attr.name === keyword; } return attr.name.endsWith(`.${keyword}`); } ); const isRepeatFor = attr.name === AureliaView.REPEAT_FOR; // 2. Attributes if (isAttributeKeyword) { // TODO: Are "just" attributes interesting? Or are BindableAttributes enough? const attributeRegion = AttributeRegion.parse5(startTag, attr); if (attributeRegion) { attributeRegions.push(attributeRegion); } } // 5. Repeat for else if (isRepeatFor) { const repeatForViewRegion = RepeatForRegion.parse5Start( startTag, attr ); if (!repeatForViewRegion) return; viewRegions.push(repeatForViewRegion); } // 3. Attribute Interpolation else { if (attr.value.match(interpolationRegex)?.length == null) return; const attributeRegions = AttributeInterpolationRegion.parse5Interpolation( startTag, attr, null, documentHasCrlf ); if (!attributeRegions) return; viewRegions.push(...attributeRegions); } const isValueConverterRegion = attr.value.includes( AureliaView.VALUE_CONVERTER_OPERATOR ); // 6. Value converter region if (isValueConverterRegion) { const valueConverterRegion = ValueConverterRegion.parse5Start( startTag, attr ); if (valueConverterRegion === undefined) return; viewRegions.push(...valueConverterRegion); } }); viewRegions.push(...attributeRegions); // 4. Custom elements const isCustomElement = aureliaCustomElementNames.includes(tagName); if (!isCustomElement) { return; } const customElementViewRegion = CustomElementRegion.parse5Start(startTag); if (!customElementViewRegion) return; // 7. BindableAttribute const customElementBindableAttributeRegions: AbstractRegion[] = []; const targetComponent = componentList.find( (component) => component.componentName === tagName ); startTag.attrs.forEach((attr) => { const onlyBindableName = getBindableNameFromAttritute(attr.name); const isBindableAttribute = targetComponent?.classMembers?.find( (member) => { const correctNamingConvetion = kebabCase(member.name) === kebabCase(onlyBindableName); const is = correctNamingConvetion && member.isBindable; return is; } ); if (isBindableAttribute == null) return; const bindableAttributeRegion = BindableAttributeRegion.parse5Start( startTag, attr ); if (bindableAttributeRegion) { customElementBindableAttributeRegions.push(bindableAttributeRegion); } }); customElementViewRegion.data = [...customElementBindableAttributeRegions]; viewRegions.push(customElementViewRegion); }); saxStream.on('text', (text: TextToken) => { if (text.text.trim() === '') return; const textRegions = TextInterpolationRegion.createRegionsFromExpressionParser( text, documentHasCrlf ); if (!textRegions) return; viewRegions.push(...textRegions); }); saxStream.on('endTag', (endTag) => { const tagName = endTag.tagName; const isCustomElement = aureliaCustomElementNames.includes(tagName); if (!isCustomElement) return; const customElementViewRegion = CustomElementRegion.parse5End(endTag); if (!customElementViewRegion) return; viewRegions.push(customElementViewRegion); }); saxStream.write(document.getText()); return viewRegions; } public static pretty< Regions extends AbstractRegion[], IgnoreKey extends keyof Regions[number] >( regions?: AbstractRegion[], prettyOptions?: PrettyOptions<Regions, IgnoreKey> ) { if (!regions) return 'no regions'; if (regions?.length === 0) return 'no regions'; const finalResult: Record<string, unknown>[] = []; regions.forEach((region) => { const prettified: Record<string, unknown> = pickTruthyFields( region, prettyOptions ); // .data[] if (Array.isArray(region.data)) { const pretty_data: Record<string, unknown>[] = []; region.data.forEach((subRegion) => { const pretty_subRegionData = pickTruthyFields( // eslint-disable-next-line @typescript-eslint/no-unsafe-argument subRegion, prettyOptions ); pretty_data.push(pretty_subRegionData); }); prettified.data = pretty_data; } finalResult.push(prettified); }); if (prettyOptions?.asTable !== undefined) { const asTable = objectToTable(finalResult, prettyOptions); return asTable; } return finalResult; } } function objectToTable< Regions extends AbstractRegion[], IgnoreKey extends keyof Regions[number] >( objectList: Record<string, any>[], prettyOptions?: PrettyOptions<Regions, IgnoreKey> ) { const EMPTY_PLACEHOLDER = '-'; const allPossibleKeysSet: Set<string> = new Set(); objectList.forEach((object) => { Object.keys(object).forEach((key) => { allPossibleKeysSet.add(key); }); }); const allPossibleKeys = Array.from(allPossibleKeysSet); // allPossibleKeys; /*?*/ const flattenedRows: string[][] = []; objectList.forEach((result) => { const withAllKeys: Record<string, string> = {}; // enrich with all keys, to allow normalized table allPossibleKeys.forEach((possibleKey) => { // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment withAllKeys[possibleKey] = result[possibleKey] ?? EMPTY_PLACEHOLDER; }); // collect if (typeof withAllKeys.data === 'object') { flattenedRows.push(Object.values(withAllKeys)); if (Array.isArray(withAllKeys.data)) { // eslint-disable-next-line @typescript-eslint/consistent-type-assertions (<Record<string, any>[]>withAllKeys.data).forEach((datum) => { allPossibleKeys.forEach((possibleKey) => { // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment withAllKeys[possibleKey] = datum[possibleKey] ?? EMPTY_PLACEHOLDER; }); flattenedRows.push(Object.values(withAllKeys)); }); } else { // repeat for and VC // flattenedRows.push(Object.values(withAllKeys.data)); } return; } flattenedRows.push(Object.values(withAllKeys)); }); // flattenedRows; /*?*/ const final = [allPossibleKeys, ...flattenedRows] as string[][]; // find max in each column const maxHeader = allPossibleKeys.map((headerColumn) => headerColumn.length); const maxTracker = maxHeader; flattenedRows.forEach((rowEntry) => { rowEntry.forEach((rowValue, index) => { maxTracker[index] = Math.max(maxTracker[index], rowValue.length ?? 0); }); }); const asTable = final.map((row) => { const padded = row.map((entry, index) => { let finalEntry = entry; if (!entry) finalEntry = '-'; if (typeof entry !== 'string') finalEntry = OBJECT_PLACEHOLDER; if (prettyOptions?.maxColWidth !== undefined) { finalEntry = finalEntry.substring(0, prettyOptions.maxColWidth); } const padWith = Math.min( prettyOptions?.maxColWidth ?? Infinity, maxTracker[index] ); finalEntry = finalEntry.replace('\n', '[nl]'); // maxTracker; /*?*/ return finalEntry?.padEnd(padWith, ' '); }); return padded.join(' | '); }); return asTable; } export function prettyTable< Regions extends AbstractRegion[], IgnoreKey extends keyof Regions[number] >( allPossibleKeys: string[], flattenedRows: string[][], prettyOptions?: PrettyOptions<Regions, IgnoreKey> ) { const final = [allPossibleKeys, ...flattenedRows]; // find max in each column const maxHeader = allPossibleKeys.map((headerColumn) => headerColumn.length); const maxTracker = maxHeader; flattenedRows.forEach((rowEntry) => { rowEntry.forEach((rowValue, index) => { maxTracker[index] = Math.max(maxTracker[index], rowValue.length ?? 0); }); }); const asTable = final.map((row) => { const padded = row.map((entry, index) => { let finalEntry = entry; if (!entry) finalEntry = '-'; if (typeof entry !== 'string') finalEntry = OBJECT_PLACEHOLDER; if (prettyOptions?.maxColWidth !== undefined) { finalEntry = finalEntry.substring(0, prettyOptions.maxColWidth); } const padWith = Math.min( prettyOptions?.maxColWidth ?? Infinity, maxTracker[index] ); return finalEntry?.padEnd(padWith, ' '); }); return padded.join(' | '); }); return asTable; } function pickTruthyFields( anyObject: Record<string, any>, prettyOptions?: { ignoreKeys?: any[] } ) { const truthyFields: Record<string, any> = {}; Object.entries(anyObject ?? {}).forEach(([key, value]) => { const regionInfo = value as ViewRegionInfoV2; if (regionInfo === undefined) return; if (prettyOptions?.ignoreKeys) { // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment const shouldIgnoreKey = prettyOptions.ignoreKeys.find( (ignore) => ignore === key ); if (shouldIgnoreKey !== undefined) return; } truthyFields[key] = regionInfo; }); return truthyFields; } function getIsImportOrRequireTag(startTag: SaxStream.StartTagToken) { const isImport = startTag.tagName === AureliaView.IMPORT; const isRequire = startTag.tagName === AureliaView.REQUIRE; const isTargetTag = isImport || isRequire; return isTargetTag; } // const path = // // '/Users/hdn/Desktop/aurelia-vscode-extension/vscode-extension/tests/testFixture/scoped-for-testing/src/index.html'; // // '/Users/hdn/Desktop/aurelia-vscode-extension/vscode-extension/tests/testFixture/scoped-for-testing/src/view/custom-element/custom-element.html'; // '/home/hdn/coding/repos/vscode-extension/tests/testFixture/scoped-for-testing/src/view/custom-element/custom-element.html'; // const document = TextDocumentUtils.createHtmlFromPath(path); // const result = RegionParser.parse(document, [ // // @ts-ignore // { componentName: 'custom-element' }, // ]); // const visitor: IViewRegionsVisitor = { // visitValueConverter(region) { // region.regionValue; /*?*/ // }, // visitAttributeInterpolation(region) { // region.regionValue; /*?*/ // }, // }; // result.forEach((res) => res.accept(visitor)); // RegionParser.pretty(result, { ignoreKeys: ['sourceCodeLocation'] }); /*?*/ // result/*?*/
the_stack
import * as SemanticUtil from './semantic_util'; export interface SemanticMeaning { type: SemanticType; role: SemanticRole; font: SemanticFont; } /** * Mapping for types of elements. */ export const enum SemanticType { // Leafs. // Punctuation like comma, dot, ellipses. PUNCTUATION = 'punctuation', // Fence symbol. FENCE = 'fence', // One or several digits, plus some punctuation. NUMBER = 'number', // Single or multiple letters. IDENTIFIER = 'identifier', // Regular text in a math expression. TEXT = 'text', // e.g. +, *. OPERATOR = 'operator', // Relation symbol, e.g. equals. RELATION = 'relation', // e.g. Sum, product, integral. LARGEOP = 'largeop', // Some named function. FUNCTION = 'function', // Branches. // Compound Symbols. ACCENT = 'accent', FENCED = 'fenced', FRACTION = 'fraction', PUNCTUATED = 'punctuated', // Relations. // Relation sequence of a single relation. RELSEQ = 'relseq', // Relation sequence containing at least two different relations. MULTIREL = 'multirel', // Operations. INFIXOP = 'infixop', PREFIXOP = 'prefixop', POSTFIXOP = 'postfixop', // Function and Bigop Application. APPL = 'appl', INTEGRAL = 'integral', BIGOP = 'bigop', SQRT = 'sqrt', ROOT = 'root', // These are bigops or functions with limits. LIMUPPER = 'limupper', LIMLOWER = 'limlower', LIMBOTH = 'limboth', SUBSCRIPT = 'subscript', SUPERSCRIPT = 'superscript', UNDERSCORE = 'underscore', OVERSCORE = 'overscore', TENSOR = 'tensor', // Tables and their elements. TABLE = 'table', MULTILINE = 'multiline', MATRIX = 'matrix', VECTOR = 'vector', CASES = 'cases', ROW = 'row', // Lines are effectively single cell rows. LINE = 'line', CELL = 'cell', // Enclosed (counterpart for menclosed). ENCLOSE = 'enclose', // Proofs and Inferences INFERENCE = 'inference', RULELABEL = 'rulelabel', CONCLUSION = 'conclusion', PREMISES = 'premises', // General. UNKNOWN = 'unknown', EMPTY = 'empty' } /** * Mapping for roles of nodes. * Roles are more specific than types. * @final */ export const enum SemanticRole { // Punctuation. COMMA = 'comma', ELLIPSIS = 'ellipsis', FULLSTOP = 'fullstop', DASH = 'dash', TILDE = 'tilde', PRIME = 'prime', // Superscript. DEGREE = 'degree', // Superscript. VBAR = 'vbar', // A vertical bar. COLON = 'colon', // A vertical bar. OPENFENCE = 'openfence', CLOSEFENCE = 'closefence', APPLICATION = 'application', // Function Application. DUMMY = 'dummy', // A dummy separator for text. // Identifier that describes a unit. UNIT = 'unit', // Expression that is used as a label. LABEL = 'label', // Fences. OPEN = 'open', CLOSE = 'close', TOP = 'top', BOTTOM = 'bottom', NEUTRAL = 'neutral', METRIC = 'metric', // Letters. LATINLETTER = 'latinletter', GREEKLETTER = 'greekletter', OTHERLETTER = 'otherletter', NUMBERSET = 'numbersetletter', // Numbers. INTEGER = 'integer', FLOAT = 'float', OTHERNUMBER = 'othernumber', MIXED = 'mixed', // Accents. MULTIACCENT = 'multiaccent', OVERACCENT = 'overaccent', UNDERACCENT = 'underaccent', // Index and tensor roles. UNDEROVER = 'underover', SUBSUP = 'subsup', LEFTSUB = 'leftsub', LEFTSUPER = 'leftsuper', RIGHTSUB = 'rightsub', RIGHTSUPER = 'rightsuper', // Fenced. LEFTRIGHT = 'leftright', ABOVEBELOW = 'abovebelow', // Sets. SETEMPTY = 'set empty', SETEXT = 'set extended', SETSINGLE = 'set singleton', SETCOLLECT = 'set collection', // Text. STRING = 'string', SPACE = 'space', // Punctuated elements. SEQUENCE = 'sequence', ENDPUNCT = 'endpunct', STARTPUNCT = 'startpunct', TEXT = 'text', // Operators. NEGATIVE = 'negative', POSITIVE = 'positive', NEGATION = 'negation', MULTIOP = 'multiop', PREFIXOP = 'prefix operator', POSTFIXOP = 'postfix operator', // Functions. LIMFUNC = 'limit function', INFIXFUNC = 'infix function', PREFIXFUNC = 'prefix function', POSTFIXFUNC = 'postfix function', SIMPLEFUNC = 'simple function', COMPFUNC = 'composed function', // Large operators. SUM = 'sum', INTEGRAL = 'integral', GEOMETRY = 'geometry', // Binary operations. ADDITION = 'addition', MULTIPLICATION = 'multiplication', SUBTRACTION = 'subtraction', IMPLICIT = 'implicit', // Fractions. DIVISION = 'division', VULGAR = 'vulgar', // Relations. EQUALITY = 'equality', INEQUALITY = 'inequality', ARROW = 'arrow', // Membership relations ELEMENT = 'element', NONELEMENT = 'nonelement', REELEMENT = 'reelement', RENONELEMENT = 'renonelement', SET = 'set', // Roles of matrices or vectors. DETERMINANT = 'determinant', ROWVECTOR = 'rowvector', BINOMIAL = 'binomial', SQUAREMATRIX = 'squarematrix', CYCLE = 'cycle', // Roles of rows, lines, cells. // They mirror the different types for tables, unless a more specific role // is // known. MULTILINE = 'multiline', MATRIX = 'matrix', VECTOR = 'vector', CASES = 'cases', TABLE = 'table', CAYLEY = 'cayley', // Inference Roles PROOF = 'proof', LEFT = 'left', RIGHT = 'right', UP = 'up', DOWN = 'down', // conclusion types FINAL = 'final', // premise types SINGLE = 'single', HYP = 'hyp', AXIOM = 'axiom', // General UNKNOWN = 'unknown', MGLYPH = 'mglyph' } /** * Mapping for font annotations. (Taken from MathML2 section 3.2.2, with the * exception of double-struck-italic.) */ export const enum SemanticFont { BOLD = 'bold', BOLDFRAKTUR = 'bold-fraktur', BOLDITALIC = 'bold-italic', BOLDSCRIPT = 'bold-script', CALIGRAPHIC = 'caligraphic', CALIGRAPHICBOLD = 'caligraphic-bold', DOUBLESTRUCK = 'double-struck', DOUBLESTRUCKITALIC = 'double-struck-italic', FRAKTUR = 'fraktur', ITALIC = 'italic', MONOSPACE = 'monospace', NORMAL = 'normal', OLDSTYLE = 'oldstyle', OLDSTYLEBOLD = 'oldstyle-bold', SCRIPT = 'script', SANSSERIF = 'sans-serif', SANSSERIFITALIC = 'sans-serif-italic', SANSSERIFBOLD = 'sans-serif-bold', SANSSERIFBOLDITALIC = 'sans-serif-bold-italic', UNKNOWN = 'unknown' } /** * Contains the basic mappings of characters/symbols and functions to semantic * attributes. * * Observe that all characters are given as hex code number in order to ease the * comparison with those in the JSON files that define speech rules per * character. */ export namespace SemanticAttr { // Punctuation Characters. const generalPunctuations: string[] = [ '!', '"', '#', '%', '&', ';', '?', '@', '\\', '¡', '§', '¶', '¿', '‗', '†', '‡', '•', '‣', '․', '‥', '‧', '‰', '‱', '‸', '※', '‼', '‽', '‾', '⁁', '⁂', '⁃', '⁇', '⁈', '⁉', '⁋', '⁌', '⁍', '⁎', '⁏', '⁐', '⁑', '⁓', '⁕', '⁖', '⁘', '⁙', '⁚', '⁛', '⁜', '⁝', '⁞', '︐', '︔', '︕', '︖', '︰', '﹅', '﹆', '﹉', '﹊', '﹋', '﹌', '﹔', '﹖', '﹗', '﹟', '﹠', '﹡', '﹨', '﹪', '﹫', '!', '"', '#', '%', '&', ''', '*', '/', ';', '?', '@', '\' ]; const colons: string[] = ['︓', ':', ':', '﹕']; const invisibleComma_: string = SemanticUtil.numberToUnicode(0x2063); const commas: string[] = [',', '﹐', ',', invisibleComma_]; const ellipses: string[] = ['…', '⋮', '⋯', '⋰', '⋱', '︙']; const fullStops: string[] = ['.', '﹒', '.']; const dashes: string[] = ['¯', '‒', '–', '—', '―', '﹘', '-', '⁻', '₋', '−', '➖', '﹣', '-', '‐', '‑', '‾', '_']; const tildes: string[] = ['~', '̃', '∼', '˜', '∽', '˷', '̴', '̰']; const primes: string[] = ['\'', '′', '″', '‴', '‵', '‶', '‷', '⁗', 'ʹ', 'ʺ']; const degrees: string[] = ['°']; // Fences. // Fences are treated slightly differently from other symbols as we want to // record pairs of opening/closing and top/bottom fences. /** * Mapping opening to closing fences. */ const openClosePairs: {[key: string]: string} = { // Unicode categories Ps and Pe. // Observe that left quotation 301D could also be matched to 301F, // but is currently matched to 301E. '(': ')', '[': ']', '{': '}', '\u2045': '⁆', '\u2329': '〉', '\u2768': '❩', '\u276a': '❫', '\u276c': '❭', '\u276e': '❯', '\u2770': '❱', '\u2772': '❳', '\u2774': '❵', '\u27c5': '⟆', '\u27e6': '⟧', '\u27e8': '⟩', '\u27ea': '⟫', '\u27ec': '⟭', '\u27ee': '⟯', '\u2983': '⦄', '\u2985': '⦆', '\u2987': '⦈', '\u2989': '⦊', '\u298b': '⦌', '\u298d': '⦎', '\u298f': '⦐', '\u2991': '⦒', '\u2993': '⦔', '\u2995': '⦖', '\u2997': '⦘', '\u29d8': '⧙', '\u29da': '⧛', '\u29fc': '⧽', '\u2e22': '⸣', '\u2e24': '⸥', '\u2e26': '⸧', '\u2e28': '⸩', '\u3008': '〉', '\u300a': '》', '\u300c': '」', '\u300e': '』', '\u3010': '】', '\u3014': '〕', '\u3016': '〗', '\u3018': '〙', '\u301a': '〛', '\u301d': '〞', '\ufd3e': '﴿', '\ufe17': '︘', '\ufe59': '﹚', '\ufe5b': '﹜', '\ufe5d': '﹞', '\uff08': ')', '\uff3b': ']', '\uff5b': '}', '\uff5f': '⦆', '\uff62': '」', // Unicode categories Sm and So. '\u2308': '⌉', '\u230a': '⌋', '\u230c': '⌍', '\u230e': '⌏', '\u231c': '⌝', '\u231e': '⌟', // Extender fences. // Parenthesis. '\u239b': '⎞', '\u239c': '⎟', '\u239d': '⎠', // Square bracket. '\u23a1': '⎤', '\u23a2': '⎥', '\u23a3': '⎦', // Curly bracket. '\u23a7': '⎫', '\u23a8': '⎬', '\u23a9': '⎭', '\u23b0': '⎱', '\u23b8': '⎹' }; /** * Mapping top to bottom fences. */ const topBottomPairs: {[key: string]: string} = { '\u23b4': '⎵', '\u23dc': '⏝', '\u23de': '⏟', '\u23e0': '⏡', '\ufe35': '︶', '\ufe37': '︸', '\ufe39': '︺', '\ufe3b': '︼', '\ufe3d': '︾', '\ufe3f': '﹀', '\ufe41': '﹂', '\ufe43': '﹄', '\ufe47': '﹈' }; const leftFences: string[] = SemanticUtil.objectsToKeys(openClosePairs); const rightFences: string[] = SemanticUtil.objectsToValues(openClosePairs); rightFences.push('〟'); const topFences: string[] = SemanticUtil.objectsToKeys(topBottomPairs); const bottomFences: string[] = SemanticUtil.objectsToValues(topBottomPairs); const neutralFences: string[] = ['|', '¦', '∣', '⏐', '⎸', '⎹', '❘', '|', '¦', '︱', '︲']; const metricFences: string[] = ['‖', '∥', '⦀', '⫴']; /** * Array of all fences. */ // const allFences: string[] = neutralFences.concat( // leftFences, rightFences, topFences, bottomFences); // Identifiers. // Latin Alphabets. const capitalLatin: string[] = [ 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' ]; const smallLatin: string[] = [ 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', // dotless i and j. 'ı', 'ȷ' ]; const capitalLatinFullWidth: string[] = [ 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' ]; const smallLatinFullWidth: string[] = [ 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' ]; const capitalLatinBold: string[] = [ '𝐀', '𝐁', '𝐂', '𝐃', '𝐄', '𝐅', '𝐆', '𝐇', '𝐈', '𝐉', '𝐊', '𝐋', '𝐌', '𝐍', '𝐎', '𝐏', '𝐐', '𝐑', '𝐒', '𝐓', '𝐔', '𝐕', '𝐖', '𝐗', '𝐘', '𝐙' ]; const smallLatinBold: string[] = [ '𝐚', '𝐛', '𝐜', '𝐝', '𝐞', '𝐟', '𝐠', '𝐡', '𝐢', '𝐣', '𝐤', '𝐥', '𝐦', '𝐧', '𝐨', '𝐩', '𝐪', '𝐫', '𝐬', '𝐭', '𝐮', '𝐯', '𝐰', '𝐱', '𝐲', '𝐳' ]; const capitalLatinItalic: string[] = [ '𝐴', '𝐵', '𝐶', '𝐷', '𝐸', '𝐹', '𝐺', '𝐻', '𝐼', '𝐽', '𝐾', '𝐿', '𝑀', '𝑁', '𝑂', '𝑃', '𝑄', '𝑅', '𝑆', '𝑇', '𝑈', '𝑉', '𝑊', '𝑋', '𝑌', '𝑍' ]; const smallLatinItalic: string[] = [ '𝑎', '𝑏', '𝑐', '𝑑', '𝑒', '𝑓', '𝑔', 'ℎ', '𝑖', '𝑗', '𝑘', '𝑙', '𝑚', '𝑛', '𝑜', '𝑝', '𝑞', '𝑟', '𝑠', '𝑡', '𝑢', '𝑣', '𝑤', '𝑥', '𝑦', '𝑧', // dotless i and j. '𝚤', '𝚥' ]; const capitalLatinBoldItalic: string[] = [ '𝑨', '𝑩', '𝑪', '𝑫', '𝑬', '𝑭', '𝑮', '𝑯', '𝑰', '𝑱', '𝑲', '𝑳', '𝑴', '𝑵', '𝑶', '𝑷', '𝑸', '𝑹', '𝑺', '𝑻', '𝑼', '𝑽', '𝑾', '𝑿', '𝒀', '𝒁' ]; const smallLatinBoldItalic: string[] = [ '𝒂', '𝒃', '𝒄', '𝒅', '𝒆', '𝒇', '𝒈', '𝒉', '𝒊', '𝒋', '𝒌', '𝒍', '𝒎', '𝒏', '𝒐', '𝒑', '𝒒', '𝒓', '𝒔', '𝒕', '𝒖', '𝒗', '𝒘', '𝒙', '𝒚', '𝒛' ]; const capitalLatinScript: string[] = [ '𝒜', 'ℬ', '𝒞', '𝒟', 'ℰ', 'ℱ', '𝒢', 'ℋ', 'ℐ', '𝒥', '𝒦', 'ℒ', 'ℳ', '𝒩', '𝒪', '𝒫', '𝒬', 'ℛ', '𝒮', '𝒯', '𝒰', '𝒱', '𝒲', '𝒳', '𝒴', '𝒵', // Powerset Cap P. '℘' ]; const smallLatinScript: string[] = [ '𝒶', '𝒷', '𝒸', '𝒹', 'ℯ', '𝒻', 'ℊ', '𝒽', '𝒾', '𝒿', '𝓀', '𝓁', '𝓂', '𝓃', 'ℴ', '𝓅', '𝓆', '𝓇', '𝓈', '𝓉', '𝓊', '𝓋', '𝓌', '𝓍', '𝓎', '𝓏', // script small l 'ℓ' ]; const capitalLatinBoldScript: string[] = [ '𝓐', '𝓑', '𝓒', '𝓓', '𝓔', '𝓕', '𝓖', '𝓗', '𝓘', '𝓙', '𝓚', '𝓛', '𝓜', '𝓝', '𝓞', '𝓟', '𝓠', '𝓡', '𝓢', '𝓣', '𝓤', '𝓥', '𝓦', '𝓧', '𝓨', '𝓩' ]; const smallLatinBoldScript: string[] = [ '𝓪', '𝓫', '𝓬', '𝓭', '𝓮', '𝓯', '𝓰', '𝓱', '𝓲', '𝓳', '𝓴', '𝓵', '𝓶', '𝓷', '𝓸', '𝓹', '𝓺', '𝓻', '𝓼', '𝓽', '𝓾', '𝓿', '𝔀', '𝔁', '𝔂', '𝔃' ]; const capitalLatinFraktur: string[] = [ '𝔄', '𝔅', 'ℭ', '𝔇', '𝔈', '𝔉', '𝔊', 'ℌ', 'ℑ', '𝔍', '𝔎', '𝔏', '𝔐', '𝔑', '𝔒', '𝔓', '𝔔', 'ℜ', '𝔖', '𝔗', '𝔘', '𝔙', '𝔚', '𝔛', '𝔜', 'ℨ' ]; const smallLatinFraktur: string[] = [ '𝔞', '𝔟', '𝔠', '𝔡', '𝔢', '𝔣', '𝔤', '𝔥', '𝔦', '𝔧', '𝔨', '𝔩', '𝔪', '𝔫', '𝔬', '𝔭', '𝔮', '𝔯', '𝔰', '𝔱', '𝔲', '𝔳', '𝔴', '𝔵', '𝔶', '𝔷' ]; const capitalLatinDoubleStruck: string[] = [ '𝔸', '𝔹', 'ℂ', '𝔻', '𝔼', '𝔽', '𝔾', 'ℍ', '𝕀', '𝕁', '𝕂', '𝕃', '𝕄', 'ℕ', '𝕆', 'ℙ', 'ℚ', 'ℝ', '𝕊', '𝕋', '𝕌', '𝕍', '𝕎', '𝕏', '𝕐', 'ℤ' ]; const smallLatinDoubleStruck: string[] = [ '𝕒', '𝕓', '𝕔', '𝕕', '𝕖', '𝕗', '𝕘', '𝕙', '𝕚', '𝕛', '𝕜', '𝕝', '𝕞', '𝕟', '𝕠', '𝕡', '𝕢', '𝕣', '𝕤', '𝕥', '𝕦', '𝕧', '𝕨', '𝕩', '𝕪', '𝕫' ]; const capitalLatinBoldFraktur: string[] = [ '𝕬', '𝕭', '𝕮', '𝕯', '𝕰', '𝕱', '𝕲', '𝕳', '𝕴', '𝕵', '𝕶', '𝕷', '𝕸', '𝕹', '𝕺', '𝕻', '𝕼', '𝕽', '𝕾', '𝕿', '𝖀', '𝖁', '𝖂', '𝖃', '𝖄', '𝖅' ]; const smallLatinBoldFraktur: string[] = [ '𝖆', '𝖇', '𝖈', '𝖉', '𝖊', '𝖋', '𝖌', '𝖍', '𝖎', '𝖏', '𝖐', '𝖑', '𝖒', '𝖓', '𝖔', '𝖕', '𝖖', '𝖗', '𝖘', '𝖙', '𝖚', '𝖛', '𝖜', '𝖝', '𝖞', '𝖟' ]; const capitalLatinSansSerif: string[] = [ '𝖠', '𝖡', '𝖢', '𝖣', '𝖤', '𝖥', '𝖦', '𝖧', '𝖨', '𝖩', '𝖪', '𝖫', '𝖬', '𝖭', '𝖮', '𝖯', '𝖰', '𝖱', '𝖲', '𝖳', '𝖴', '𝖵', '𝖶', '𝖷', '𝖸', '𝖹' ]; const smallLatinSansSerif: string[] = [ '𝖺', '𝖻', '𝖼', '𝖽', '𝖾', '𝖿', '𝗀', '𝗁', '𝗂', '𝗃', '𝗄', '𝗅', '𝗆', '𝗇', '𝗈', '𝗉', '𝗊', '𝗋', '𝗌', '𝗍', '𝗎', '𝗏', '𝗐', '𝗑', '𝗒', '𝗓' ]; const capitalLatinSansSerifBold: string[] = [ '𝗔', '𝗕', '𝗖', '𝗗', '𝗘', '𝗙', '𝗚', '𝗛', '𝗜', '𝗝', '𝗞', '𝗟', '𝗠', '𝗡', '𝗢', '𝗣', '𝗤', '𝗥', '𝗦', '𝗧', '𝗨', '𝗩', '𝗪', '𝗫', '𝗬', '𝗭' ]; const smallLatinSansSerifBold: string[] = [ '𝗮', '𝗯', '𝗰', '𝗱', '𝗲', '𝗳', '𝗴', '𝗵', '𝗶', '𝗷', '𝗸', '𝗹', '𝗺', '𝗻', '𝗼', '𝗽', '𝗾', '𝗿', '𝘀', '𝘁', '𝘂', '𝘃', '𝘄', '𝘅', '𝘆', '𝘇' ]; const capitalLatinSansSerifItalic: string[] = [ '𝘈', '𝘉', '𝘊', '𝘋', '𝘌', '𝘍', '𝘎', '𝘏', '𝘐', '𝘑', '𝘒', '𝘓', '𝘔', '𝘕', '𝘖', '𝘗', '𝘘', '𝘙', '𝘚', '𝘛', '𝘜', '𝘝', '𝘞', '𝘟', '𝘠', '𝘡' ]; const smallLatinSansSerifItalic: string[] = [ '𝘢', '𝘣', '𝘤', '𝘥', '𝘦', '𝘧', '𝘨', '𝘩', '𝘪', '𝘫', '𝘬', '𝘭', '𝘮', '𝘯', '𝘰', '𝘱', '𝘲', '𝘳', '𝘴', '𝘵', '𝘶', '𝘷', '𝘸', '𝘹', '𝘺', '𝘻' ]; const capitalLatinSansSerifBoldItalic: string[] = [ '𝘼', '𝘽', '𝘾', '𝘿', '𝙀', '𝙁', '𝙂', '𝙃', '𝙄', '𝙅', '𝙆', '𝙇', '𝙈', '𝙉', '𝙊', '𝙋', '𝙌', '𝙍', '𝙎', '𝙏', '𝙐', '𝙑', '𝙒', '𝙓', '𝙔', '𝙕' ]; const smallLatinSansSerifBoldItalic: string[] = [ '𝙖', '𝙗', '𝙘', '𝙙', '𝙚', '𝙛', '𝙜', '𝙝', '𝙞', '𝙟', '𝙠', '𝙡', '𝙢', '𝙣', '𝙤', '𝙥', '𝙦', '𝙧', '𝙨', '𝙩', '𝙪', '𝙫', '𝙬', '𝙭', '𝙮', '𝙯' ]; const capitalLatinMonospace: string[] = [ '𝙰', '𝙱', '𝙲', '𝙳', '𝙴', '𝙵', '𝙶', '𝙷', '𝙸', '𝙹', '𝙺', '𝙻', '𝙼', '𝙽', '𝙾', '𝙿', '𝚀', '𝚁', '𝚂', '𝚃', '𝚄', '𝚅', '𝚆', '𝚇', '𝚈', '𝚉' ]; const smallLatinMonospace: string[] = [ '𝚊', '𝚋', '𝚌', '𝚍', '𝚎', '𝚏', '𝚐', '𝚑', '𝚒', '𝚓', '𝚔', '𝚕', '𝚖', '𝚗', '𝚘', '𝚙', '𝚚', '𝚛', '𝚜', '𝚝', '𝚞', '𝚟', '𝚠', '𝚡', '𝚢', '𝚣' ]; const latinDoubleStruckItalic: string[] = ['ⅅ', 'ⅆ', 'ⅇ', 'ⅈ', 'ⅉ']; // Greek Alphabets const capitalGreek: string[] = [ 'Α', 'Β', 'Γ', 'Δ', 'Ε', 'Ζ', 'Η', 'Θ', 'Ι', 'Κ', 'Λ', 'Μ', 'Ν', 'Ξ', 'Ο', 'Π', 'Ρ', 'Σ', 'Τ', 'Υ', 'Φ', 'Χ', 'Ψ', 'Ω' ]; const smallGreek: string[] = [ 'α', 'β', 'γ', 'δ', 'ε', 'ζ', 'η', 'θ', 'ι', 'κ', 'λ', 'μ', 'ν', 'ξ', 'ο', 'π', 'ρ', 'ς', 'σ', 'τ', 'υ', 'φ', 'χ', 'ψ', 'ω' ]; const capitalGreekBold: string[] = [ '𝚨', '𝚩', '𝚪', '𝚫', '𝚬', '𝚭', '𝚮', '𝚯', '𝚰', '𝚱', '𝚲', '𝚳', '𝚴', '𝚵', '𝚶', '𝚷', '𝚸', '𝚺', '𝚻', '𝚼', '𝚽', '𝚾', '𝚿', '𝛀' ]; const smallGreekBold: string[] = [ '𝛂', '𝛃', '𝛄', '𝛅', '𝛆', '𝛇', '𝛈', '𝛉', '𝛊', '𝛋', '𝛌', '𝛍', '𝛎', '𝛏', '𝛐', '𝛑', '𝛒', '𝛓', '𝛔', '𝛕', '𝛖', '𝛗', '𝛘', '𝛙', '𝛚' ]; const capitalGreekItalic: string[] = [ '𝛢', '𝛣', '𝛤', '𝛥', '𝛦', '𝛧', '𝛨', '𝛩', '𝛪', '𝛫', '𝛬', '𝛭', '𝛮', '𝛯', '𝛰', '𝛱', '𝛲', '𝛴', '𝛵', '𝛶', '𝛷', '𝛸', '𝛹', '𝛺' ]; const smallGreekItalic: string[] = [ '𝛼', '𝛽', '𝛾', '𝛿', '𝜀', '𝜁', '𝜂', '𝜃', '𝜄', '𝜅', '𝜆', '𝜇', '𝜈', '𝜉', '𝜊', '𝜋', '𝜌', '𝜍', '𝜎', '𝜏', '𝜐', '𝜑', '𝜒', '𝜓', '𝜔' ]; const capitalGreekBoldItalic: string[] = [ '𝜜', '𝜝', '𝜞', '𝜟', '𝜠', '𝜡', '𝜢', '𝜣', '𝜤', '𝜥', '𝜦', '𝜧', '𝜨', '𝜩', '𝜪', '𝜫', '𝜬', '𝜮', '𝜯', '𝜰', '𝜱', '𝜲', '𝜳', '𝜴' ]; const smallGreekBoldItalic: string[] = [ '𝜶', '𝜷', '𝜸', '𝜹', '𝜺', '𝜻', '𝜼', '𝜽', '𝜾', '𝜿', '𝝀', '𝝁', '𝝂', '𝝃', '𝝄', '𝝅', '𝝆', '𝝇', '𝝈', '𝝉', '𝝊', '𝝋', '𝝌', '𝝍', '𝝎' ]; const capitalGreekSansSerifBold: string[] = [ '𝝖', '𝝗', '𝝘', '𝝙', '𝝚', '𝝛', '𝝜', '𝝝', '𝝞', '𝝟', '𝝠', '𝝡', '𝝢', '𝝣', '𝝤', '𝝥', '𝝦', '𝝨', '𝝩', '𝝪', '𝝫', '𝝬', '𝝭', '𝝮' ]; const smallGreekSansSerifBold: string[] = [ '𝝰', '𝝱', '𝝲', '𝝳', '𝝴', '𝝵', '𝝶', '𝝷', '𝝸', '𝝹', '𝝺', '𝝻', '𝝼', '𝝽', '𝝾', '𝝿', '𝞀', '𝞁', '𝞂', '𝞃', '𝞄', '𝞅', '𝞆', '𝞇', '𝞈' ]; const capitalGreekSansSerifBoldItalic: string[] = [ '𝞐', '𝞑', '𝞒', '𝞓', '𝞔', '𝞕', '𝞖', '𝞗', '𝞘', '𝞙', '𝞚', '𝞛', '𝞜', '𝞝', '𝞞', '𝞟', '𝞠', '𝞢', '𝞣', '𝞤', '𝞥', '𝞦', '𝞧', '𝞨' ]; const smallGreekSansSerifBoldItalic: string[] = [ '𝞪', '𝞫', '𝞬', '𝞭', '𝞮', '𝞯', '𝞰', '𝞱', '𝞲', '𝞳', '𝞴', '𝞵', '𝞶', '𝞷', '𝞸', '𝞹', '𝞺', '𝞻', '𝞼', '𝞽', '𝞾', '𝞿', '𝟀', '𝟁', '𝟂' ]; const greekDoubleStruck: string[] = ['ℼ', 'ℽ', 'ℾ', 'ℿ']; const greekSpecial: string[] = ['ϐ', 'ϑ', 'ϕ', 'ϖ', 'ϗ', 'ϰ', 'ϱ', 'ϵ', '϶', 'ϴ']; const greekSpecialBold: string[] = ['𝛜', '𝛝', '𝛞', '𝛟', '𝛠', '𝛡']; const greekSpecialItalic: string[] = ['𝜖', '𝜗', '𝜘', '𝜙', '𝜚', '𝜛']; const greekSpecialSansSerifBold: string[] = ['𝞊', '𝞋', '𝞌', '𝞍', '𝞎', '𝞏']; // Other alphabets. const hebrewLetters: string[] = ['ℵ', 'ℶ', 'ℷ', 'ℸ']; export const allLetters: string[] = capitalLatin.concat( smallLatin, capitalLatinFullWidth, smallLatinFullWidth, capitalLatinBold, smallLatinBold, capitalLatinItalic, capitalLatinBoldItalic, smallLatinBoldItalic, smallLatinItalic, capitalLatinScript, smallLatinScript, capitalLatinBoldScript, smallLatinBoldScript, capitalLatinFraktur, smallLatinFraktur, capitalLatinDoubleStruck, smallLatinDoubleStruck, capitalLatinBoldFraktur, smallLatinBoldFraktur, capitalLatinSansSerif, smallLatinSansSerif, capitalLatinSansSerifBold, smallLatinSansSerifBold, capitalLatinSansSerifItalic, smallLatinSansSerifItalic, capitalLatinSansSerifBoldItalic, smallLatinSansSerifBoldItalic, capitalLatinMonospace, smallLatinMonospace, latinDoubleStruckItalic, capitalGreek, smallGreek, capitalGreekBold, smallGreekBold, capitalGreekItalic, smallGreekItalic, capitalGreekBoldItalic, smallGreekBoldItalic, capitalGreekSansSerifBold, smallGreekSansSerifBold, greekDoubleStruck, greekSpecial, capitalGreekSansSerifBoldItalic, smallGreekSansSerifBoldItalic, greekSpecialBold, greekSpecialItalic, greekSpecialSansSerifBold, hebrewLetters); // Operator symbols const additions: string[] = [ '+', '±', '∓', '∔', '∧', '∨', '∩', '∪', '⊌', '⊍', '⊎', '⊓', '⊔', '⊝', '⊞', '⊤', '⊥', '⊺', '⊻', '⊼', '⋄', '⋎', '⋏', '⋒', '⋓', '⩞', '⊕', '⋔' ]; /** * Invisible operator for plus. */ const invisiblePlus_: string = SemanticUtil.numberToUnicode(0x2064); additions.push(invisiblePlus_); const multiplications: string[] = [ '†', '‡', '∐', '∗', '∘', '∙', '≀', '⊚', '⊛', '⊠', '⊡', '⋅', '⋆', '⋇', '⋈', '⋉', '⋊', '⋋', '⋌', '○', '·', '*', '⊗', '⊙' ]; /** * Invisible operator for multiplication. */ const invisibleTimes_: string = SemanticUtil.numberToUnicode(0x2062); multiplications.push(invisibleTimes_); const subtractions: string[] = [ '¯', '-', '⁒', '⁻', '₋', '−', '∖', '∸', '≂', '⊖', '⊟', '➖', '⨩', '⨪', '⨫', '⨬', '⨺', '⩁', '﹣', '-', '‐', '‑' ]; const divisions: string[] = ['/', '÷', '⁄', '∕', '⊘', '⟌', '⦼', '⨸']; /** * Invisible operator for function application. */ const functionApplication_: string = SemanticUtil.numberToUnicode(0x2061); // Relation symbols const equalities: string[] = [ '=', '~', '⁼', '₌', '∼', '∽', '≃', '≅', '≈', '≊', '≋', '≌', '≍', '≎', '≑', '≒', '≓', '≔', '≕', '≖', '≗', '≘', '≙', '≚', '≛', '≜', '≝', '≞', '≟', '≡', '≣', '⧤', '⩦', '⩮', '⩯', '⩰', '⩱', '⩲', '⩳', '⩴', '⩵', '⩶', '⩷', '⩸', '⋕', '⩭', '⩪', '⩫', '⩬', '﹦', '=', '⩬', '⊜', '∷' ]; const inequalities: string[] = [ '<', '>', '≁', '≂', '≄', '≆', '≇', '≉', '≏', '≐', '≠', '≢', '≤', '≥', '≦', '≧', '≨', '≩', '≪', '≫', '≬', '≭', '≮', '≯', '≰', '≱', '≲', '≳', '≴', '≵', '≶', '≷', '≸', '≹', '≺', '≻', '≼', '≽', '≾', '≿', '⊀', '⊁', '⋖', '⋗', '⋘', '⋙', '⋚', '⋛', '⋜', '⋝', '⋞', '⋟', '⋠', '⋡', '⋦', '⋧', '⋨', '⋩', '⩹', '⩺', '⩻', '⩼', '⩽', '⩾', '⩿', '⪀', '⪁', '⪂', '⪃', '⪄', '⪅', '⪆', '⪇', '⪈', '⪉', '⪊', '⪋', '⪌', '⪍', '⪎', '⪏', '⪐', '⪑', '⪒', '⪓', '⪔', '⪕', '⪖', '⪗', '⪘', '⪙', '⪚', '⪛', '⪜', '⪝', '⪞', '⪟', '⪠', '⪡', '⪢', '⪣', '⪤', '⪥', '⪦', '⪧', '⪨', '⪩', '⪪', '⪫', '⪬', '⪭', '⪮', '⪯', '⪰', '⪱', '⪲', '⪳', '⪴', '⪵', '⪶', '⪷', '⪸', '⪹', '⪺', '⪻', '⪼', '⫷', '⫸', '⫹', '⫺', '⧀', '⧁', '﹤', '﹥', '<', '>' ]; const setRelations: string[] = [ '⋢', '⋣', '⋤', '⋥', '⊂', '⊃', '⊄', '⊅', '⊆', '⊇', '⊈', '⊉', '⊊', '⊋', '⊏', '⊐', '⊑', '⊒', '⪽', '⪾', '⪿', '⫀', '⫁', '⫂', '⫃', '⫄', '⫅', '⫆', '⫇', '⫈', '⫉', '⫊', '⫋', '⫌', '⫍', '⫎', '⫏', '⫐', '⫑', '⫒', '⫓', '⫔', '⫕', '⫖', '⫗', '⫘', '⋐', '⋑', '⋪', '⋫', '⋬', '⋭', '⊲', '⊳', '⊴', '⊵' ]; const elementRelations: string[] = [ '∈', '∊', '⋲', '⋳', '⋴', '⋵', '⋶', '⋷', '⋸', '⋹', '⋿' ]; const nonelementRelations: string[] = ['∉']; const reelementRelations: string[] = [ '∋', '∍', '⋺', '⋻', '⋼', '⋽', '⋾', ]; const renonelementRelations: string[] = ['∌']; const relations: string[] = [ // TODO (sorge): Add all the other relations. Currently mainly tacks and // turnstyles. '⊢', '⊣', '⊦', '⊧', '⊨', '⊩', '⊪', '⊫', '⊬', '⊭', '⊮', '⊯', '⫞', '⫟', '⫠', '⫡', '⫢', '⫣', '⫤', '⫥', '⫦', '⫧', '⫨', '⫩', '⫪', '⫫', '⫬', '⫭' ]; const arrows: string[] = [ '←', '↑', '→', '↓', '↔', '↕', '↖', '↗', '↘', '↙', '↚', '↛', '↜', '↝', '↞', '↟', '↠', '↡', '↢', '↣', '↤', '↥', '↦', '↧', '↨', '↩', '↪', '↫', '↬', '↭', '↮', '↯', '↰', '↱', '↲', '↳', '↴', '↵', '↶', '↷', '↸', '↹', '↺', '↻', '⇄', '⇅', '⇆', '⇇', '⇈', '⇉', '⇊', '⇍', '⇎', '⇏', '⇐', '⇑', '⇒', '⇓', '⇔', '⇕', '⇖', '⇗', '⇘', '⇙', '⇚', '⇛', '⇜', '⇝', '⇞', '⇟', '⇠', '⇡', '⇢', '⇣', '⇤', '⇥', '⇦', '⇧', '⇨', '⇩', '⇪', '⇫', '⇬', '⇭', '⇮', '⇯', '⇰', '⇱', '⇲', '⇳', '⇴', '⇵', '⇶', '⇷', '⇸', '⇹', '⇺', '⇻', '⇼', '⇽', '⇾', '⇿', '⌁', '⌃', '⌄', '⌤', '⎋', '➔', '➘', '➙', '➚', '➛', '➜', '➝', '➞', '➟', '➠', '➡', '➢', '➣', '➤', '➥', '➦', '➧', '➨', '➩', '➪', '➫', '➬', '➭', '➮', '➯', '➱', '➲', '➳', '➴', '➵', '➶', '➷', '➸', '➹', '➺', '➻', '➼', '➽', '➾', '⟰', '⟱', '⟲', '⟳', '⟴', '⟵', '⟶', '⟷', '⟸', '⟹', '⟺', '⟻', '⟼', '⟽', '⟾', '⟿', '⤀', '⤁', '⤂', '⤃', '⤄', '⤅', '⤆', '⤇', '⤈', '⤉', '⤊', '⤋', '⤌', '⤍', '⤎', '⤏', '⤐', '⤑', '⤒', '⤓', '⤔', '⤕', '⤖', '⤗', '⤘', '⤙', '⤚', '⤛', '⤜', '⤝', '⤞', '⤟', '⤠', '⤡', '⤢', '⤣', '⤤', '⤥', '⤦', '⤧', '⤨', '⤩', '⤪', '⤭', '⤮', '⤯', '⤰', '⤱', '⤲', '⤳', '⤴', '⤵', '⤶', '⤷', '⤸', '⤹', '⤺', '⤻', '⤼', '⤽', '⤾', '⤿', '⥀', '⥁', '⥂', '⥃', '⥄', '⥅', '⥆', '⥇', '⥈', '⥉', '⥰', '⥱', '⥲', '⥳', '⥴', '⥵', '⥶', '⥷', '⥸', '⥹', '⥺', '⥻', '⦳', '⦴', '⦽', '⧪', '⧬', '⧭', '⨗', '⬀', '⬁', '⬂', '⬃', '⬄', '⬅', '⬆', '⬇', '⬈', '⬉', '⬊', '⬋', '⬌', '⬍', '⬎', '⬏', '⬐', '⬑', '⬰', '⬱', '⬲', '⬳', '⬴', '⬵', '⬶', '⬷', '⬸', '⬹', '⬺', '⬻', '⬼', '⬽', '⬾', '⬿', '⭀', '⭁', '⭂', '⭃', '⭄', '⭅', '⭆', '⭇', '⭈', '⭉', '⭊', '⭋', '⭌', '←', '↑', '→', '↓', // Harpoons '↼', '↽', '↾', '↿', '⇀', '⇁', '⇂', '⇃', '⇋', '⇌', '⥊', '⥋', '⥌', '⥍', '⥎', '⥏', '⥐', '⥑', '⥒', '⥓', '⥔', '⥕', '⥖', '⥗', '⥘', '⥙', '⥚', '⥛', '⥜', '⥝', '⥞', '⥟', '⥠', '⥡', '⥢', '⥣', '⥤', '⥥', '⥦', '⥧', '⥨', '⥩', '⥪', '⥫', '⥬', '⥭', '⥮', '⥯', '⥼', '⥽', '⥾', '⥿' ]; // Big operation symbols const sumOps: string[] = [ '⅀', // double struck '∏', '∐', '∑', '⋀', '⋁', '⋂', '⋃', '⨀', '⨁', '⨂', '⨃', '⨄', '⨅', '⨆', '⨇', '⨈', '⨉', '⨊', '⨋', '⫼', '⫿' ]; const intOps: string[] = [ '∫', '∬', '∭', '∮', '∯', '∰', '∱', '∲', '∳', '⨌', '⨍', '⨎', '⨏', '⨐', '⨑', '⨒', '⨓', '⨔', '⨕', '⨖', '⨗', '⨘', '⨙', '⨚', '⨛', '⨜' ]; const geometryOps: string[] = [ '∟', '∠', '∡', '∢', '⊾', '⊿', // TODO: Add the entire geometric shape set programmatically. '△', '▷', '▽', '◁' ]; const prefixOps: string[] = ['∀', '∃', '∆', '∇', '∂', '∁', '∄']; const prefixOpsBold: string[] = ['𝛁', '𝛛', '𝟊', '𝟋']; const prefixOpsItalic: string[] = ['𝛻', '𝜕']; const prefixOpsSansSerifBold: string[] = ['𝝯', '𝞉']; // TODO (sorge) Insert nabla, differential operators sans serif bold italic // const operatorBits: string[] = // // TODO (sorge) What to do if single glyphs of big ops occur on their own. // ['⌠', '⌡', '⎶', '⎪', '⎮', '⎯', '⎲', '⎳', '⎷']; // Accents. // TODO (sorge) Add accented characters. // Numbers. // Digits. const digitsNormal: string[] = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']; const digitsFullWidth: string[] = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']; const digitsBold: string[] = ['𝟎', '𝟏', '𝟐', '𝟑', '𝟒', '𝟓', '𝟔', '𝟕', '𝟖', '𝟗']; const digitsDoubleStruck: string[] = ['𝟘', '𝟙', '𝟚', '𝟛', '𝟜', '𝟝', '𝟞', '𝟟', '𝟠', '𝟡']; const digitsSansSerif: string[] = ['𝟢', '𝟣', '𝟤', '𝟥', '𝟦', '𝟧', '𝟨', '𝟩', '𝟪', '𝟫']; const digitsSansSerifBold: string[] = ['𝟬', '𝟭', '𝟮', '𝟯', '𝟰', '𝟱', '𝟲', '𝟳', '𝟴', '𝟵']; const digitsMonospace: string[] = ['𝟶', '𝟷', '𝟸', '𝟹', '𝟺', '𝟻', '𝟼', '𝟽', '𝟾', '𝟿']; const digitsSuperscript: string[] = ['²', '³', '¹', '⁰', '⁴', '⁵', '⁶', '⁷', '⁸', '⁹']; const digitsSubscript: string[] = ['₀', '₁', '₂', '₃', '₄', '₅', '₆', '₇', '₈', '₉']; const fractions: string[] = [ '¼', '½', '¾', '⅐', '⅑', '⅒', '⅓', '⅔', '⅕', '⅖', '⅗', '⅘', '⅙', '⅚', '⅛', '⅜', '⅝', '⅞', '⅟', '↉' ]; const enclosedNumbers: string[] = // Encircled numbers. [ '①', '②', '③', '④', '⑤', '⑥', '⑦', '⑧', '⑨', '⑩', '⑪', '⑫', '⑬', '⑭', '⑮', '⑯', '⑰', '⑱', '⑲', '⑳', '⓪', '⓫', '⓬', '⓭', '⓮', '⓯', '⓰', '⓱', '⓲', '⓳', '⓴', '⓵', '⓶', '⓷', '⓸', '⓹', '⓺', '⓻', '⓼', '⓽', '⓾', '⓿', '❶', '❷', '❸', '❹', '❺', '❻', '❼', '❽', '❾', '❿', '➀', '➁', '➂', '➃', '➄', '➅', '➆', '➇', '➈', '➉', '➊', '➋', '➌', '➍', '➎', '➏', '➐', '➑', '➒', '➓', '㉈', '㉉', '㉊', '㉋', '㉌', '㉍', '㉎', '㉏', '㉑', '㉒', '㉓', '㉔', '㉕', '㉖', '㉗', '㉘', '㉙', '㉚', '㉛', '㉜', '㉝', '㉞', '㉟', '㊱', '㊲', '㊳', '㊴', '㊵', '㊶', '㊷', '㊸', '㊹', '㊺', '㊻', '㊼', '㊽', '㊾', '㊿' ]; const fencedNumbers: string[] = // Numbers in Parenthesis. [ '⑴', '⑵', '⑶', '⑷', '⑸', '⑹', '⑺', '⑻', '⑼', '⑽', '⑾', '⑿', '⒀', '⒁', '⒂', '⒃', '⒄', '⒅', '⒆', '⒇' ]; const punctuatedNumbers: string[] = // Numbers with other punctuation. [ '⒈', '⒉', '⒊', '⒋', '⒌', '⒍', '⒎', '⒏', '⒐', '⒑', '⒒', '⒓', '⒔', '⒕', '⒖', '⒗', '⒘', '⒙', '⒚', '⒛', // full stop. '🄀', '🄁', '🄂', '🄃', '🄄', '🄅', '🄆', '🄇', '🄈', '🄉', '🄊' // comma. ]; /** * Array of all single digits. */ // const digits: string[] = digitsNormal.concat( // digitsFullWidth, digitsBold, digitsDoubleStruck, // digitsSansSerif, digitsSansSerifBold, digitsMonospace); /** * Array of all non-digit number symbols. */ const numbers: string[] = fractions; const otherNumbers: string[] = digitsSuperscript.concat( digitsSubscript, enclosedNumbers, fencedNumbers, punctuatedNumbers); /** * Array of all number symbols. */ // const allNumbers: string[] = digits.concat(numbers, otherNumbers); // Functions. const trigonometricFunctions: string[] = [ 'cos', 'cot', 'csc', 'sec', 'sin', 'tan', 'arccos', 'arccot', 'arccsc', 'arcsec', 'arcsin', 'arctan', 'arc cos', 'arc cot', 'arc csc', 'arc sec', 'arc sin', 'arc tan' ]; const hyperbolicFunctions: string[] = [ 'cosh', 'coth', 'csch', 'sech', 'sinh', 'tanh', 'arcosh', 'arcoth', 'arcsch', 'arsech', 'arsinh', 'artanh', 'arccosh', 'arccoth', 'arccsch', 'arcsech', 'arcsinh', 'arctanh' ]; const algebraicFunctions: string[] = ['deg', 'det', 'dim', 'hom', 'ker', 'Tr', 'tr']; const elementaryFunctions: string[] = ['log', 'ln', 'lg', 'exp', 'expt', 'gcd', 'gcd', 'arg', 'im', 're', 'Pr']; /** * All predefined prefix functions. */ const prefixFunctions: string[] = trigonometricFunctions.concat( hyperbolicFunctions, algebraicFunctions, elementaryFunctions); /** * Limit functions are handled separately as they can have lower (and upper) * limiting expressions. */ const limitFunctions: string[] = [ 'inf', 'lim', 'liminf', 'limsup', 'max', 'min', 'sup', 'injlim', 'projlim', 'inj lim', 'proj lim' ]; const infixFunctions: string[] = ['mod', 'rem']; interface MeaningSet { set: string[]; role: SemanticRole; type: SemanticType; font?: SemanticFont; } /** * Default assignments of semantic attributes. * Assigns sets of symbols to meaning. */ const symbolSetToSemantic_: MeaningSet[] = [ // Punctuation { set: generalPunctuations, type: SemanticType.PUNCTUATION, role: SemanticRole.UNKNOWN }, { set: colons, type: SemanticType.PUNCTUATION, role: SemanticRole.COLON }, { set: commas, type: SemanticType.PUNCTUATION, role: SemanticRole.COMMA }, { set: ellipses, type: SemanticType.PUNCTUATION, role: SemanticRole.ELLIPSIS }, { set: fullStops, type: SemanticType.PUNCTUATION, role: SemanticRole.FULLSTOP }, { set: dashes, type: SemanticType.OPERATOR, role: SemanticRole.DASH }, { set: tildes, type: SemanticType.OPERATOR, role: SemanticRole.TILDE }, { set: primes, type: SemanticType.PUNCTUATION, role: SemanticRole.PRIME }, { set: degrees, type: SemanticType.PUNCTUATION, role: SemanticRole.DEGREE }, // Fences { set: leftFences, type: SemanticType.FENCE, role: SemanticRole.OPEN }, { set: rightFences, type: SemanticType.FENCE, role: SemanticRole.CLOSE }, { set: topFences, type: SemanticType.FENCE, role: SemanticRole.TOP }, { set: bottomFences, type: SemanticType.FENCE, role: SemanticRole.BOTTOM }, { set: neutralFences, type: SemanticType.FENCE, role: SemanticRole.NEUTRAL }, { set: metricFences, type: SemanticType.FENCE, role: SemanticRole.METRIC }, // Single characters. // Latin alphabets. { set: smallLatin, type: SemanticType.IDENTIFIER, role: SemanticRole.LATINLETTER, font: SemanticFont.NORMAL }, { set: capitalLatin, type: SemanticType.IDENTIFIER, role: SemanticRole.LATINLETTER, font: SemanticFont.NORMAL }, { set: smallLatinFullWidth, type: SemanticType.IDENTIFIER, role: SemanticRole.LATINLETTER, font: SemanticFont.NORMAL }, { set: capitalLatinFullWidth, type: SemanticType.IDENTIFIER, role: SemanticRole.LATINLETTER, font: SemanticFont.NORMAL }, { set: smallLatinBold, type: SemanticType.IDENTIFIER, role: SemanticRole.LATINLETTER, font: SemanticFont.BOLD }, { set: capitalLatinBold, type: SemanticType.IDENTIFIER, role: SemanticRole.LATINLETTER, font: SemanticFont.BOLD }, { set: smallLatinItalic, type: SemanticType.IDENTIFIER, role: SemanticRole.LATINLETTER, font: SemanticFont.ITALIC }, { set: capitalLatinItalic, type: SemanticType.IDENTIFIER, role: SemanticRole.LATINLETTER, font: SemanticFont.ITALIC }, { set: smallLatinBoldItalic, type: SemanticType.IDENTIFIER, role: SemanticRole.LATINLETTER, font: SemanticFont.BOLDITALIC }, { set: capitalLatinBoldItalic, type: SemanticType.IDENTIFIER, role: SemanticRole.LATINLETTER, font: SemanticFont.BOLDITALIC }, { set: smallLatinScript, type: SemanticType.IDENTIFIER, role: SemanticRole.LATINLETTER, font: SemanticFont.SCRIPT }, { set: capitalLatinScript, type: SemanticType.IDENTIFIER, role: SemanticRole.LATINLETTER, font: SemanticFont.SCRIPT }, { set: smallLatinBoldScript, type: SemanticType.IDENTIFIER, role: SemanticRole.LATINLETTER, font: SemanticFont.BOLDSCRIPT }, { set: capitalLatinBoldScript, type: SemanticType.IDENTIFIER, role: SemanticRole.LATINLETTER, font: SemanticFont.BOLDSCRIPT }, { set: smallLatinFraktur, type: SemanticType.IDENTIFIER, role: SemanticRole.LATINLETTER, font: SemanticFont.FRAKTUR }, { set: capitalLatinFraktur, type: SemanticType.IDENTIFIER, role: SemanticRole.LATINLETTER, font: SemanticFont.FRAKTUR }, { set: smallLatinDoubleStruck, type: SemanticType.IDENTIFIER, role: SemanticRole.LATINLETTER, font: SemanticFont.DOUBLESTRUCK }, { set: capitalLatinDoubleStruck, type: SemanticType.IDENTIFIER, role: SemanticRole.LATINLETTER, font: SemanticFont.DOUBLESTRUCK }, { set: smallLatinBoldFraktur, type: SemanticType.IDENTIFIER, role: SemanticRole.LATINLETTER, font: SemanticFont.BOLDFRAKTUR }, { set: capitalLatinBoldFraktur, type: SemanticType.IDENTIFIER, role: SemanticRole.LATINLETTER, font: SemanticFont.BOLDFRAKTUR }, { set: smallLatinSansSerif, type: SemanticType.IDENTIFIER, role: SemanticRole.LATINLETTER, font: SemanticFont.SANSSERIF }, { set: capitalLatinSansSerif, type: SemanticType.IDENTIFIER, role: SemanticRole.LATINLETTER, font: SemanticFont.SANSSERIF }, { set: smallLatinSansSerifBold, type: SemanticType.IDENTIFIER, role: SemanticRole.LATINLETTER, font: SemanticFont.SANSSERIFBOLD }, { set: capitalLatinSansSerifBold, type: SemanticType.IDENTIFIER, role: SemanticRole.LATINLETTER, font: SemanticFont.SANSSERIFBOLD }, { set: smallLatinSansSerifItalic, type: SemanticType.IDENTIFIER, role: SemanticRole.LATINLETTER, font: SemanticFont.SANSSERIFITALIC }, { set: capitalLatinSansSerifItalic, type: SemanticType.IDENTIFIER, role: SemanticRole.LATINLETTER, font: SemanticFont.SANSSERIFITALIC }, { set: smallLatinSansSerifBoldItalic, type: SemanticType.IDENTIFIER, role: SemanticRole.LATINLETTER, font: SemanticFont.SANSSERIFBOLDITALIC }, { set: capitalLatinSansSerifBoldItalic, type: SemanticType.IDENTIFIER, role: SemanticRole.LATINLETTER, font: SemanticFont.SANSSERIFBOLDITALIC }, { set: smallLatinMonospace, type: SemanticType.IDENTIFIER, role: SemanticRole.LATINLETTER, font: SemanticFont.MONOSPACE }, { set: capitalLatinMonospace, type: SemanticType.IDENTIFIER, role: SemanticRole.LATINLETTER, font: SemanticFont.MONOSPACE }, { set: latinDoubleStruckItalic, type: SemanticType.IDENTIFIER, role: SemanticRole.LATINLETTER, font: SemanticFont.DOUBLESTRUCKITALIC }, // Greek alphabets. { set: smallGreek, type: SemanticType.IDENTIFIER, role: SemanticRole.GREEKLETTER, font: SemanticFont.NORMAL }, { set: capitalGreek, type: SemanticType.IDENTIFIER, role: SemanticRole.GREEKLETTER, font: SemanticFont.NORMAL }, { set: smallGreekBold, type: SemanticType.IDENTIFIER, role: SemanticRole.GREEKLETTER, font: SemanticFont.BOLD }, { set: capitalGreekBold, type: SemanticType.IDENTIFIER, role: SemanticRole.GREEKLETTER, font: SemanticFont.BOLD }, { set: smallGreekItalic, type: SemanticType.IDENTIFIER, role: SemanticRole.GREEKLETTER, font: SemanticFont.ITALIC }, { set: capitalGreekItalic, type: SemanticType.IDENTIFIER, role: SemanticRole.GREEKLETTER, font: SemanticFont.ITALIC }, { set: smallGreekBoldItalic, type: SemanticType.IDENTIFIER, role: SemanticRole.GREEKLETTER, font: SemanticFont.BOLDITALIC }, { set: capitalGreekBoldItalic, type: SemanticType.IDENTIFIER, role: SemanticRole.GREEKLETTER, font: SemanticFont.BOLDITALIC }, { set: smallGreekSansSerifBold, type: SemanticType.IDENTIFIER, role: SemanticRole.GREEKLETTER, font: SemanticFont.SANSSERIFBOLD }, { set: capitalGreekSansSerifBold, type: SemanticType.IDENTIFIER, role: SemanticRole.GREEKLETTER, font: SemanticFont.SANSSERIFBOLD }, { set: capitalGreekSansSerifBoldItalic, type: SemanticType.IDENTIFIER, role: SemanticRole.GREEKLETTER, font: SemanticFont.SANSSERIFBOLDITALIC }, { set: smallGreekSansSerifBoldItalic, type: SemanticType.IDENTIFIER, role: SemanticRole.GREEKLETTER, font: SemanticFont.SANSSERIFBOLDITALIC }, { set: greekDoubleStruck, type: SemanticType.IDENTIFIER, role: SemanticRole.GREEKLETTER, font: SemanticFont.DOUBLESTRUCK }, { set: greekSpecial, type: SemanticType.IDENTIFIER, role: SemanticRole.GREEKLETTER, font: SemanticFont.NORMAL }, { set: greekSpecialBold, type: SemanticType.IDENTIFIER, role: SemanticRole.GREEKLETTER, font: SemanticFont.BOLD }, { set: greekSpecialItalic, type: SemanticType.IDENTIFIER, role: SemanticRole.GREEKLETTER, font: SemanticFont.ITALIC }, { set: greekSpecialSansSerifBold, type: SemanticType.IDENTIFIER, role: SemanticRole.GREEKLETTER, font: SemanticFont.SANSSERIFBOLD }, // Other alphabets. { set: hebrewLetters, type: SemanticType.IDENTIFIER, role: SemanticRole.OTHERLETTER, font: SemanticFont.NORMAL }, // Numbers. { set: digitsNormal, type: SemanticType.NUMBER, role: SemanticRole.INTEGER, font: SemanticFont.NORMAL }, { set: digitsFullWidth, type: SemanticType.NUMBER, role: SemanticRole.INTEGER, font: SemanticFont.NORMAL }, { set: digitsBold, type: SemanticType.NUMBER, role: SemanticRole.INTEGER, font: SemanticFont.BOLD }, { set: digitsDoubleStruck, type: SemanticType.NUMBER, role: SemanticRole.INTEGER, font: SemanticFont.DOUBLESTRUCK }, { set: digitsSansSerif, type: SemanticType.NUMBER, role: SemanticRole.INTEGER, font: SemanticFont.SANSSERIF }, { set: digitsSansSerifBold, type: SemanticType.NUMBER, role: SemanticRole.INTEGER, font: SemanticFont.SANSSERIFBOLD }, { set: digitsMonospace, type: SemanticType.NUMBER, role: SemanticRole.INTEGER, font: SemanticFont.MONOSPACE }, { set: numbers, type: SemanticType.NUMBER, role: SemanticRole.FLOAT }, { set: otherNumbers, type: SemanticType.NUMBER, role: SemanticRole.OTHERNUMBER }, // Operators. { set: additions, type: SemanticType.OPERATOR, role: SemanticRole.ADDITION }, { set: multiplications, type: SemanticType.OPERATOR, role: SemanticRole.MULTIPLICATION }, { set: subtractions, type: SemanticType.OPERATOR, role: SemanticRole.SUBTRACTION }, { set: divisions, type: SemanticType.OPERATOR, role: SemanticRole.DIVISION }, { set: prefixOps, type: SemanticType.OPERATOR, role: SemanticRole.PREFIXOP }, { set: prefixOpsBold, type: SemanticType.OPERATOR, role: SemanticRole.PREFIXOP, font: SemanticFont.BOLD }, { set: prefixOpsItalic, type: SemanticType.OPERATOR, role: SemanticRole.PREFIXOP, font: SemanticFont.ITALIC }, { set: prefixOpsSansSerifBold, type: SemanticType.OPERATOR, role: SemanticRole.PREFIXOP, font: SemanticFont.SANSSERIFBOLD }, // Relations { set: equalities, type: SemanticType.RELATION, role: SemanticRole.EQUALITY }, { set: inequalities, type: SemanticType.RELATION, role: SemanticRole.INEQUALITY }, { set: setRelations, type: SemanticType.RELATION, role: SemanticRole.SET }, { set: relations, type: SemanticType.RELATION, role: SemanticRole.UNKNOWN }, { set: arrows, type: SemanticType.RELATION, role: SemanticRole.ARROW }, // Membership. Currently treated as operator. { set: elementRelations, type: SemanticType.OPERATOR, role: SemanticRole.ELEMENT }, { set: nonelementRelations, type: SemanticType.OPERATOR, role: SemanticRole.NONELEMENT }, { set: reelementRelations, type: SemanticType.OPERATOR, role: SemanticRole.REELEMENT }, { set: renonelementRelations, type: SemanticType.OPERATOR, role: SemanticRole.RENONELEMENT }, // Large operators { set: sumOps, type: SemanticType.LARGEOP, role: SemanticRole.SUM }, { set: intOps, type: SemanticType.LARGEOP, role: SemanticRole.INTEGRAL }, { set: geometryOps, // TODO: Change that after speech rule work? type: SemanticType.OPERATOR, role: SemanticRole.GEOMETRY }, // Functions { set: limitFunctions, type: SemanticType.FUNCTION, role: SemanticRole.LIMFUNC }, { set: prefixFunctions, type: SemanticType.FUNCTION, role: SemanticRole.PREFIXFUNC }, { set: infixFunctions, type: SemanticType.OPERATOR, role: SemanticRole.PREFIXFUNC } ]; /** * Initializes the dictionary mapping strings to meaning. * @return The dictionary mapping strings to * semantic attributes. */ const meaning_: {[key: string]: SemanticMeaning} = function() { let result: {[key: string]: SemanticMeaning} = {}; for (let i = 0, st: MeaningSet; st = symbolSetToSemantic_[i]; i++) { st.set.forEach(function(symbol) { result[symbol] = { role: st.role || SemanticRole.UNKNOWN, type: st.type || SemanticType.UNKNOWN, font: st.font || SemanticFont.UNKNOWN }; }); } return result; }(); /** * Equality on meaning objects. * @param meaning1 First meaning. * @param meaning2 Second meaning. * @return True if both contain the same field entries. */ export function equal(meaning1: SemanticMeaning, meaning2: SemanticMeaning): boolean { return meaning1.type === meaning2.type && meaning1.role === meaning2.role && meaning1.font === meaning2.font; } /** * Lookup the semantic type of a symbol. * @param symbol The symbol to which we want to determine the type. * @return The semantic type of the symbol. */ export function lookupType(symbol: string): SemanticType { return meaning_[symbol]?.type || SemanticType.UNKNOWN; } /** * Lookup the semantic role of a symbol. * @param symbol The symbol to which we want to determine the role. * @return The semantic role of the symbol. */ export function lookupRole(symbol: string): SemanticRole { return meaning_[symbol]?.role || SemanticRole.UNKNOWN; } /** * Lookup the semantic meaning of a symbol in terms of type and role. * @param symbol The symbol to which we want to determine the meaning. * @return The semantic meaning of the symbol. */ export function lookupMeaning(symbol: string): SemanticMeaning { return meaning_[symbol] || { role: SemanticRole.UNKNOWN, type: SemanticType.UNKNOWN, font: SemanticFont.UNKNOWN }; } /** * String representation of the invisible times unicode character. * @return The invisible times character. */ export function invisibleTimes(): string { return invisibleTimes_; } /** * String representation of the invisible plus unicode character. * @return The invisible plus character. */ export function invisiblePlus(): string { return invisiblePlus_; } /** * String representation of the invisible comma unicode character. * @return The invisible comma character. */ export function invisibleComma(): string { return invisibleComma_; } /** * String representation of the function application character. * @return The invisible function application character. */ export function functionApplication(): string { return functionApplication_; } // /** // * Decide when two fences match. Currently we match any right to left // * or bottom to top fence and neutral to neutral. // * @param open Opening fence. // * @param close Closing fence. // * @return True if the fences are matching. // */ // export function isMatchingFenceRole(open: string, close: string): boolean { // return open === SemanticRole.OPEN && // close === SemanticRole.CLOSE || // isNeutralFence(open) && isNeutralFence(close) || // open === SemanticRole.TOP && close === SemanticRole.BOTTOM; // } /** * Decide when opening and closing fences match. For neutral fences they have * to be the same. * * @param {string} open Opening fence. * @param {string} close Closing fence. * @return {boolean} True if the fences are matching. */ export function isMatchingFence(open: string, close: string): boolean { if (neutralFences.indexOf(open) !== -1 || metricFences.indexOf(open) !== -1) { return open === close; } return openClosePairs[open] === close || topBottomPairs[open] === close; } // /** // * Determines if a fence is an opening fence. // * @param fence Opening fence. // * @return True if the fence is open or neutral. // */ // export function isOpeningFence(fence: SemanticRole): boolean { // return fence === SemanticRole.OPEN || isNeutralFence(fence); // } // /** // * Determines if a fence is a closing fence. // * @param fence Closing fence. // * @return True if the fence is close or neutral. // */ // export function isClosingFence(fence: SemanticRole): boolean { // return fence === SemanticRole.CLOSE || isNeutralFence(fence); // } /** * Determines if a symbol type can be embellished. Primitives that can be * embellished are operators, punctuations, relations, and fences. * @param type The type. * @return True if the type can be embellished. */ export function isEmbellishedType(type: SemanticType): boolean { return type === SemanticType.OPERATOR || type === SemanticType.RELATION || type === SemanticType.FENCE || type === SemanticType.PUNCTUATION; } /** * Secondary annotation facility. This allows to compute a special annotation, * if desired. */ /** * The mapping for secondary annotations. */ const secondary_ = new Map(); /** * The key generator for secondary annotations. * @param kind The kind of annotation. * @param char The character to look up. * @return The generated key. */ function secKey(kind: string, char: string) { return `${kind} ${char}`; } /** * Builds the secondary annotation structure. * @param kind The kind of annotation. * @param char The characters to look up. * @param annotation Optionally an annotation value. Default is `kind`. */ function addSecondary_(kind: string, chars: string[], annotation: string = '') { for (let char of chars) { secondary_.set(secKey(kind, char), annotation || kind); } } addSecondary_('d', ['d', 'ⅆ', 'd', '𝐝', '𝑑', '𝒹', '𝓭', '𝔡', '𝕕', '𝖉', '𝖽', '𝗱', '𝘥', '𝚍']); addSecondary_('bar', dashes); addSecondary_('tilde', tildes); /** * Lookup of secondary annotation. * @param kind The kind of annotation. * @param char The character to look up. * @return The annotation if it exists. */ export function lookupSecondary(kind: string, char: string) { return secondary_.get(secKey(kind, char)); } }
the_stack
import { Encoding } from '@syncfusion/ej2-file-utils'; /** * array literal codes */ const ARR_LITERAL_CODES: Int16Array = new Int16Array(286); const ARR_LITERAL_LENGTHS: Uint8Array = new Uint8Array(286); const ARR_DISTANCE_CODES: Int16Array = new Int16Array(30); const ARR_DISTANCE_LENGTHS: Uint8Array = new Uint8Array(30); /** * represent compression stream writer * ```typescript * let compressedWriter = new CompressedStreamWriter(); * let text: string = 'Hello world!!!'; * compressedWriter.write(text, 0, text.length); * compressedWriter.close(); * ``` */ export class CompressedStreamWriter { private static isHuffmanTreeInitiated: boolean = false; private stream: Uint8Array[]; private pendingBuffer: Uint8Array = new Uint8Array(1 << 16); private pendingBufLength: number = 0; private pendingBufCache: number = 0; private pendingBufBitsInCache: number = 0; private treeLiteral: CompressorHuffmanTree; private treeDistances: CompressorHuffmanTree; private treeCodeLengths: CompressorHuffmanTree; private bufferPosition: number = 0; private arrLiterals: Uint8Array; private arrDistances: Uint16Array; private extraBits: number = 0; private currentHash: number = 0; private hashHead: Int16Array; private hashPrevious: Int16Array; private matchStart: number = 0; private matchLength: number = 0; private matchPrevAvail: boolean = false; private blockStart: number = 0; private stringStart: number = 0; private lookAhead: number = 0; private dataWindow: Uint8Array; private inputBuffer: Uint8Array; private totalBytesIn: number = 0; private inputOffset: number = 0; private inputEnd: number = 0; private windowSize: number = 1 << 15; private windowMask: number = this.windowSize - 1; private hashSize: number = 1 << 15; private hashMask: number = this.hashSize - 1; private hashShift: number = Math.floor((15 + 3 - 1) / 3); private maxDist: number = this.windowSize - 262; private checkSum: number = 1; private noWrap: Boolean = false; /** * get compressed data */ get compressedData(): Uint8Array[] { return this.stream; } get getCompressedString(): string { let compressedString: string = ''; if (this.stream !== undefined) { for (let i: number = 0; i < this.stream.length; i++) { compressedString += String.fromCharCode.apply(null, this.stream[i]); } } return compressedString; } /** * Initializes compressor and writes ZLib header if needed. * @param {boolean} noWrap - optional if true, ZLib header and checksum will not be written. */ constructor(noWrap?: boolean) { if (!CompressedStreamWriter.isHuffmanTreeInitiated) { CompressedStreamWriter.initHuffmanTree(); CompressedStreamWriter.isHuffmanTreeInitiated = true; } this.treeLiteral = new CompressorHuffmanTree(this, 286, 257, 15); this.treeDistances = new CompressorHuffmanTree(this, 30, 1, 15); this.treeCodeLengths = new CompressorHuffmanTree(this, 19, 4, 7); this.arrDistances = new Uint16Array((1 << 14)); this.arrLiterals = new Uint8Array((1 << 14)); this.stream = []; this.dataWindow = new Uint8Array(2 * this.windowSize); this.hashHead = new Int16Array(this.hashSize); this.hashPrevious = new Int16Array(this.windowSize); this.blockStart = this.stringStart = 1; this.noWrap = noWrap; if (!noWrap) { this.writeZLibHeader(); } } /** * Compresses data and writes it to the stream. * @param {Uint8Array} data - data to compress * @param {number} offset - offset in data * @param {number} length - length of the data * @returns {void} */ public write(data: Uint8Array | string, offset: number, length: number): void { if (data === undefined || data === null) { throw new Error('ArgumentException: data cannot null or undefined'); } let end: number = offset + length; if (0 > offset || offset > end || end > data.length) { throw new Error('ArgumentOutOfRangeException: Offset or length is incorrect'); } if (typeof data === 'string') { let encode: Encoding = new Encoding(false); encode.type = 'Utf8'; data = new Uint8Array(encode.getBytes(data, 0, data.length)); end = offset + data.length; } this.inputBuffer = data as Uint8Array; this.inputOffset = offset; this.inputEnd = end; if (!this.noWrap) { this.checkSum = ChecksumCalculator.checksumUpdate(this.checkSum, this.inputBuffer, this.inputOffset, end); } while (!(this.inputEnd === this.inputOffset) || !(this.pendingBufLength === 0)) { this.pendingBufferFlush(); this.compressData(false); } } /** * write ZLib header to the compressed data * @return {void} */ public writeZLibHeader(): void { /* Initialize header.*/ let headerDate: number = (8 + (7 << 4)) << 8; /* Save compression level.*/ headerDate |= ((5 >> 2) & 3) << 6; /* Align header.*/ headerDate += 31 - (headerDate % 31); /* Write header to stream.*/ this.pendingBufferWriteShortBytes(headerDate); } /** * Write Most Significant Bytes in to stream * @param {number} s - check sum value */ public pendingBufferWriteShortBytes(s: number): void { this.pendingBuffer[this.pendingBufLength++] = s >> 8; this.pendingBuffer[this.pendingBufLength++] = s; } private compressData(finish: boolean): boolean { let success: boolean; do { this.fillWindow(); let canFlush: boolean = (finish && this.inputEnd === this.inputOffset); success = this.compressSlow(canFlush, finish); } while (this.pendingBufLength === 0 && success); return success; } private compressSlow(flush: boolean, finish: boolean): boolean { if (this.lookAhead < 262 && !flush) { return false; } while (this.lookAhead >= 262 || flush) { if (this.lookAhead === 0) { return this.lookAheadCompleted(finish); } if (this.stringStart >= 2 * this.windowSize - 262) { this.slideWindow(); } let prevMatch: number = this.matchStart; let prevLen: number = this.matchLength; if (this.lookAhead >= 3) { this.discardMatch(); } if (prevLen >= 3 && this.matchLength <= prevLen) { prevLen = this.matchPreviousBest(prevMatch, prevLen); } else { this.matchPreviousAvailable(); } if (this.bufferPosition >= (1 << 14)) { return this.huffmanIsFull(finish); } } return true; } private discardMatch(): void { let hashHead: number = this.insertString(); if (hashHead !== 0 && this.stringStart - hashHead <= this.maxDist && this.findLongestMatch(hashHead)) { if (this.matchLength <= 5 && (this.matchLength === 3 && this.stringStart - this.matchStart > 4096)) { this.matchLength = 3 - 1; } } } private matchPreviousAvailable(): void { if (this.matchPrevAvail) { this.huffmanTallyLit(this.dataWindow[this.stringStart - 1] & 0xff); } this.matchPrevAvail = true; this.stringStart++; this.lookAhead--; } private matchPreviousBest(prevMatch: number, prevLen: number): number { this.huffmanTallyDist(this.stringStart - 1 - prevMatch, prevLen); prevLen -= 2; do { this.stringStart++; this.lookAhead--; if (this.lookAhead >= 3) { this.insertString(); } } while (--prevLen > 0); this.stringStart++; this.lookAhead--; this.matchPrevAvail = false; this.matchLength = 3 - 1; return prevLen; } private lookAheadCompleted(finish: boolean): boolean { if (this.matchPrevAvail) { this.huffmanTallyLit(this.dataWindow[this.stringStart - 1] & 0xff); } this.matchPrevAvail = false; this.huffmanFlushBlock(this.dataWindow, this.blockStart, this.stringStart - this.blockStart, finish); this.blockStart = this.stringStart; return false; } private huffmanIsFull(finish: boolean): boolean { let len: number = this.stringStart - this.blockStart; if (this.matchPrevAvail) { len--; } let lastBlock: boolean = (finish && this.lookAhead === 0 && !this.matchPrevAvail); this.huffmanFlushBlock(this.dataWindow, this.blockStart, len, lastBlock); this.blockStart += len; return !lastBlock; } private fillWindow(): void { if (this.stringStart >= this.windowSize + this.maxDist) { this.slideWindow(); } while (this.lookAhead < 262 && this.inputOffset < this.inputEnd) { let more: number = 2 * this.windowSize - this.lookAhead - this.stringStart; if (more > this.inputEnd - this.inputOffset) { more = this.inputEnd - this.inputOffset; } this.dataWindow.set(this.inputBuffer.subarray(this.inputOffset, this.inputOffset + more), this.stringStart + this.lookAhead); this.inputOffset += more; this.totalBytesIn += more; this.lookAhead += more; } if (this.lookAhead >= 3) { this.updateHash(); } } private slideWindow(): void { this.dataWindow.set(this.dataWindow.subarray(this.windowSize, this.windowSize + this.windowSize), 0); this.matchStart -= this.windowSize; this.stringStart -= this.windowSize; this.blockStart -= this.windowSize; for (let i: number = 0; i < this.hashSize; ++i) { let m: number = this.hashHead[i] & 0xffff; this.hashHead[i] = (((m >= this.windowSize) ? (m - this.windowSize) : 0)); } for (let i: number = 0; i < this.windowSize; i++) { let m: number = this.hashPrevious[i] & 0xffff; this.hashPrevious[i] = ((m >= this.windowSize) ? (m - this.windowSize) : 0); } } private insertString(): number { let match: number; let hash: number = ((this.currentHash << this.hashShift) ^ this.dataWindow[this.stringStart + (3 - 1)]) & this.hashMask; this.hashPrevious[this.stringStart & this.windowMask] = match = this.hashHead[hash]; this.hashHead[hash] = this.stringStart; this.currentHash = hash; return match & 0xffff; } private findLongestMatch(curMatch: number): boolean { let chainLen: number = 4096; let niceLen: number = 258; let scan: number = this.stringStart; let match: number; let bestEnd: number = this.stringStart + this.matchLength; let bestLength: number = Math.max(this.matchLength, 3 - 1); let limit: number = Math.max(this.stringStart - this.maxDist, 0); let stringEnd: number = this.stringStart + 258 - 1; let scanEnd1: number = this.dataWindow[bestEnd - 1]; let scanEnd: number = this.dataWindow[bestEnd]; let data: Uint8Array = this.dataWindow; if (bestLength >= 32) { chainLen >>= 2; } if (niceLen > this.lookAhead) { niceLen = this.lookAhead; } do { if (data[curMatch + bestLength] !== scanEnd || data[curMatch + bestLength - 1] !== scanEnd1 || data[curMatch] !== data[scan] || data[curMatch + 1] !== data[scan + 1]) { continue; } match = curMatch + 2; scan += 2; /* tslint:disable */ while (data[++scan] === data[++match] && data[++scan] === data[++match] && data[++scan] === data[++match] && data[++scan] === data[++match] && data[++scan] === data[++match] && data[++scan] === data[++match] && data[++scan] === data[++match] && data[++scan] === data[++match] && scan < stringEnd) { /* tslint:disable */ } if (scan > bestEnd) { this.matchStart = curMatch; bestEnd = scan; bestLength = scan - this.stringStart; if (bestLength >= niceLen) { break; } scanEnd1 = data[bestEnd - 1]; scanEnd = data[bestEnd]; } scan = this.stringStart; } while ((curMatch = (this.hashPrevious[curMatch & this.windowMask] & 0xffff)) > limit && --chainLen !== 0); this.matchLength = Math.min(bestLength, this.lookAhead); return this.matchLength >= 3; } private updateHash(): void { this.currentHash = (this.dataWindow[this.stringStart] << this.hashShift) ^ this.dataWindow[this.stringStart + 1]; } private huffmanTallyLit(literal: number): boolean { this.arrDistances[this.bufferPosition] = 0; this.arrLiterals[this.bufferPosition++] = literal; this.treeLiteral.codeFrequencies[literal]++; return this.bufferPosition >= (1 << 14); } private huffmanTallyDist(dist: number, len: number): boolean { this.arrDistances[this.bufferPosition] = dist; this.arrLiterals[this.bufferPosition++] = (len - 3); let lc: number = this.huffmanLengthCode(len - 3); this.treeLiteral.codeFrequencies[lc]++; if (lc >= 265 && lc < 285) { this.extraBits += Math.floor((lc - 261) / 4); } let dc: number = this.huffmanDistanceCode(dist - 1); this.treeDistances.codeFrequencies[dc]++; if (dc >= 4) { this.extraBits += Math.floor((dc / 2 - 1)); } return this.bufferPosition >= (1 << 14); } private huffmanFlushBlock(stored: Uint8Array, storedOffset: number, storedLength: number, lastBlock: boolean): void { this.treeLiteral.codeFrequencies[256]++; this.treeLiteral.buildTree(); this.treeDistances.buildTree(); this.treeLiteral.calculateBLFreq(this.treeCodeLengths); this.treeDistances.calculateBLFreq(this.treeCodeLengths); this.treeCodeLengths.buildTree(); let blTreeCodes: number = 4; for (let i: number = 18; i > blTreeCodes; i--) { if (this.treeCodeLengths.codeLengths[CompressorHuffmanTree.huffCodeLengthOrders[i]] > 0) { blTreeCodes = i + 1; } } let opt_len: number = 14 + blTreeCodes * 3 + this.treeCodeLengths.getEncodedLength() + this.treeLiteral.getEncodedLength() + this.treeDistances.getEncodedLength() + this.extraBits; let static_len: number = this.extraBits; for (let i: number = 0; i < 286; i++) { static_len += this.treeLiteral.codeFrequencies[i] * ARR_LITERAL_LENGTHS[i]; } for (let i = 0; i < 30; i++) { static_len += this.treeDistances.codeFrequencies[i] * ARR_DISTANCE_LENGTHS[i]; } if (opt_len >= static_len) { // Force static trees. opt_len = static_len; } if (storedOffset >= 0 && storedLength + 4 < opt_len >> 3) { this.huffmanFlushStoredBlock(stored, storedOffset, storedLength, lastBlock); } else if (opt_len == static_len) { // Encode with static tree. this.pendingBufferWriteBits((1 << 1) + (lastBlock ? 1 : 0), 3); this.treeLiteral.setStaticCodes(ARR_LITERAL_CODES, ARR_LITERAL_LENGTHS); this.treeDistances.setStaticCodes(ARR_DISTANCE_CODES, ARR_DISTANCE_LENGTHS); this.huffmanCompressBlock(); this.huffmanReset(); } else { this.pendingBufferWriteBits((2 << 1) + (lastBlock ? 1 : 0), 3); this.huffmanSendAllTrees(blTreeCodes); this.huffmanCompressBlock(); this.huffmanReset(); } } private huffmanFlushStoredBlock(stored: Uint8Array, storedOffset: number, storedLength: number, lastBlock: boolean): void { this.pendingBufferWriteBits((0 << 1) + (lastBlock ? 1 : 0), 3); this.pendingBufferAlignToByte(); this.pendingBufferWriteShort(storedLength); this.pendingBufferWriteShort(~storedLength); this.pendingBufferWriteByteBlock(stored, storedOffset, storedLength); this.huffmanReset(); } private huffmanLengthCode(len: number): number { if (len === 255) { return 285; } let code: number = 257; while (len >= 8) { code += 4; len >>= 1; } return code + len; } private huffmanDistanceCode(distance: number): number { let code: number = 0; while (distance >= 4) { code += 2; distance >>= 1; } return code + distance; } private huffmanSendAllTrees(blTreeCodes: number): void { this.treeCodeLengths.buildCodes(); this.treeLiteral.buildCodes(); this.treeDistances.buildCodes(); this.pendingBufferWriteBits(this.treeLiteral.treeLength - 257, 5); this.pendingBufferWriteBits(this.treeDistances.treeLength - 1, 5); this.pendingBufferWriteBits(blTreeCodes - 4, 4); for (let rank: number = 0; rank < blTreeCodes; rank++) { this.pendingBufferWriteBits( this.treeCodeLengths.codeLengths[CompressorHuffmanTree.huffCodeLengthOrders[rank]] , 3); } this.treeLiteral.writeTree(this.treeCodeLengths); this.treeDistances.writeTree(this.treeCodeLengths); } private huffmanReset(): void { this.bufferPosition = 0; this.extraBits = 0; this.treeLiteral.reset(); this.treeDistances.reset(); this.treeCodeLengths.reset(); } private huffmanCompressBlock(): void { for (let i: number = 0; i < this.bufferPosition; i++) { let literalLen: number = this.arrLiterals[i] & 255; let dist: number = this.arrDistances[i]; if (dist-- !== 0) { let lc: number = this.huffmanLengthCode(literalLen); this.treeLiteral.writeCodeToStream(lc); let bits: number = Math.floor((lc - 261) / 4); if (bits > 0 && bits <= 5) { this.pendingBufferWriteBits(literalLen & ((1 << bits) - 1), bits); } let dc: number = this.huffmanDistanceCode(dist); this.treeDistances.writeCodeToStream(dc); bits = Math.floor(dc / 2 - 1); if (bits > 0) { this.pendingBufferWriteBits(dist & ((1 << bits) - 1), bits); } } else { this.treeLiteral.writeCodeToStream(literalLen); } } this.treeLiteral.writeCodeToStream(256); } /** * write bits in to internal buffer * @param {number} b - source of bits * @param {number} count - count of bits to write */ public pendingBufferWriteBits(b: number, count: number): void { let uint: Uint32Array = new Uint32Array(1); uint[0] = this.pendingBufCache | (b << this.pendingBufBitsInCache); this.pendingBufCache = uint[0]; this.pendingBufBitsInCache += count; this.pendingBufferFlushBits(); } private pendingBufferFlush(isClose?: boolean): void { this.pendingBufferFlushBits(); if (this.pendingBufLength > 0) { let array: Uint8Array = new Uint8Array(this.pendingBufLength); array.set(this.pendingBuffer.subarray(0, this.pendingBufLength), 0); this.stream.push(array); } this.pendingBufLength = 0; } private pendingBufferFlushBits(): number { let result: number = 0; while (this.pendingBufBitsInCache >= 8 && this.pendingBufLength < (1 << 16)) { this.pendingBuffer[this.pendingBufLength++] = this.pendingBufCache; this.pendingBufCache >>= 8; this.pendingBufBitsInCache -= 8; result++; } return result; } private pendingBufferWriteByteBlock(data: Uint8Array, offset: number, length: number): void { let array: Uint8Array = data.subarray(offset, offset + length); this.pendingBuffer.set(array, this.pendingBufLength); this.pendingBufLength += length; } private pendingBufferWriteShort(s: number): void { this.pendingBuffer[this.pendingBufLength++] = s; this.pendingBuffer[this.pendingBufLength++] = (s >> 8); } private pendingBufferAlignToByte(): void { if (this.pendingBufBitsInCache > 0) { this.pendingBuffer[this.pendingBufLength++] = this.pendingBufCache; } this.pendingBufCache = 0; this.pendingBufBitsInCache = 0; } /** * Huffman Tree literal calculation * @private */ public static initHuffmanTree(): void { let i: number = 0; while (i < 144) { ARR_LITERAL_CODES[i] = CompressorHuffmanTree.bitReverse((0x030 + i) << 8); ARR_LITERAL_LENGTHS[i++] = 8; } while (i < 256) { ARR_LITERAL_CODES[i] = CompressorHuffmanTree.bitReverse((0x190 - 144 + i) << 7); ARR_LITERAL_LENGTHS[i++] = 9; } while (i < 280) { ARR_LITERAL_CODES[i] = CompressorHuffmanTree.bitReverse((0x000 - 256 + i) << 9); ARR_LITERAL_LENGTHS[i++] = 7; } while (i < 286) { ARR_LITERAL_CODES[i] = CompressorHuffmanTree.bitReverse((0x0c0 - 280 + i) << 8); ARR_LITERAL_LENGTHS[i++] = 8; } for (i = 0; i < 30; i++) { ARR_DISTANCE_CODES[i] = CompressorHuffmanTree.bitReverse(i << 11); ARR_DISTANCE_LENGTHS[i] = 5; } } /** * close the stream and write all pending buffer in to stream * @returns {void} */ public close(): void { do { this.pendingBufferFlush(true); if (!this.compressData(true)) { this.pendingBufferFlush(true); this.pendingBufferAlignToByte(); if (!this.noWrap) { this.pendingBufferWriteShortBytes(this.checkSum >> 16); this.pendingBufferWriteShortBytes(this.checkSum & 0xffff); } this.pendingBufferFlush(true); } } while (!(this.inputEnd === this.inputOffset) || !(this.pendingBufLength === 0)); } /** * release allocated un-managed resource * @returns {void} */ public destroy(): void { this.stream = []; this.stream = undefined; this.pendingBuffer = undefined; this.treeLiteral = undefined; this.treeDistances = undefined; this.treeCodeLengths = undefined; this.arrLiterals = undefined; this.arrDistances = undefined; this.hashHead = undefined; this.hashPrevious = undefined; this.dataWindow = undefined; this.inputBuffer = undefined; this.pendingBufLength = undefined; this.pendingBufCache = undefined; this.pendingBufBitsInCache = undefined; this.bufferPosition = undefined; this.extraBits = undefined; this.currentHash = undefined; this.matchStart = undefined; this.matchLength = undefined; this.matchPrevAvail = undefined; this.blockStart = undefined; this.stringStart = undefined; this.lookAhead = undefined; this.totalBytesIn = undefined; this.inputOffset = undefined; this.inputEnd = undefined; this.windowSize = undefined; this.windowMask = undefined; this.hashSize = undefined; this.hashMask = undefined; this.hashShift = undefined; this.maxDist = undefined; this.checkSum = undefined; this.noWrap = undefined; } } /** * represent the Huffman Tree */ export class CompressorHuffmanTree { private codeFrequency: Uint16Array; private codes: Int16Array; private codeLength: Uint8Array; private lengthCount: Int32Array; private codeMinCount: number; private codeCount: number; private maxLength: number; private writer: CompressedStreamWriter; private static reverseBits: number[] = [0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15]; public static huffCodeLengthOrders: number[] = [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]; public get treeLength(): number { return this.codeCount; } public get codeLengths(): Uint8Array { return this.codeLength; } public get codeFrequencies(): Uint16Array { return this.codeFrequency; } /** * Create new Huffman Tree * @param {CompressedStreamWriter} writer instance * @param {number} elementCount - element count * @param {number} minCodes - minimum count * @param {number} maxLength - maximum count */ constructor(writer: CompressedStreamWriter, elementCount: number, minCodes: number, maxLength: number) { this.writer = writer; this.codeMinCount = minCodes; this.maxLength = maxLength; this.codeFrequency = new Uint16Array(elementCount); this.lengthCount = new Int32Array(maxLength); } public setStaticCodes(codes: Int16Array, lengths: Uint8Array): void { let temp: Int16Array = new Int16Array(codes.length); temp.set(codes, 0); this.codes = temp; let lengthTemp: Uint8Array = new Uint8Array(lengths.length); lengthTemp.set(lengths, 0); this.codeLength = lengthTemp; } /** * reset all code data in tree * @returns {void} */ public reset(): void { for (let i: number = 0; i < this.codeFrequency.length; i++) { this.codeFrequency[i] = 0; } this.codes = undefined; this.codeLength = undefined; } /** * write code to the compressor output stream * @param {number} code - code to be written * @returns {void} */ public writeCodeToStream(code: number): void { this.writer.pendingBufferWriteBits(this.codes[code] & 0xffff, this.codeLength[code]); } /** * calculate code from their frequencies * @returns {void} */ public buildCodes(): void { let nextCode: Int32Array = new Int32Array(this.maxLength); this.codes = new Int16Array(this.codeCount); let code: number = 0; for (let bitsCount: number = 0; bitsCount < this.maxLength; bitsCount++) { nextCode[bitsCount] = code; code += this.lengthCount[bitsCount] << (15 - bitsCount); } for (let i: number = 0; i < this.codeCount; i++) { let bits = this.codeLength[i]; if (bits > 0) { this.codes[i] = CompressorHuffmanTree.bitReverse(nextCode[bits - 1]); nextCode[bits - 1] += 1 << (16 - bits); } } } public static bitReverse(value: number): number { return (CompressorHuffmanTree.reverseBits[value & 15] << 12 | CompressorHuffmanTree.reverseBits[(value >> 4) & 15] << 8 | CompressorHuffmanTree.reverseBits[(value >> 8) & 15] << 4 | CompressorHuffmanTree.reverseBits[value >> 12]); } /** * calculate length of compressed data * @returns {number} */ public getEncodedLength(): number { let len: number = 0; for (let i: number = 0; i < this.codeFrequency.length; i++) { len += this.codeFrequency[i] * this.codeLength[i]; } return len; } /** * calculate code frequencies * @param {CompressorHuffmanTree} blTree * @returns {void} */ public calculateBLFreq(blTree: CompressorHuffmanTree): void { let maxCount: number; let minCount: number; let count: number; let curLen: number = -1; let i: number = 0; while (i < this.codeCount) { count = 1; let nextLen: number = this.codeLength[i]; if (nextLen === 0) { maxCount = 138; minCount = 3; } else { maxCount = 6; minCount = 3; if (curLen !== nextLen) { blTree.codeFrequency[nextLen]++; count = 0; } } curLen = nextLen; i++; while (i < this.codeCount && curLen === this.codeLength[i]) { i++; if (++count >= maxCount) { break; } } if (count < minCount) { blTree.codeFrequency[curLen] += count; } else if (curLen !== 0) { blTree.codeFrequency[16]++; } else if (count <= 10) { blTree.codeFrequency[17]++; } else { blTree.codeFrequency[18]++; } } } /** * @param {CompressorHuffmanTree} blTree - write tree to output stream * @returns {void} */ public writeTree(blTree: CompressorHuffmanTree): void { let maxRepeatCount: number; let minRepeatCount: number; let currentRepeatCount: number; let currentCodeLength: number = -1; let i: number = 0; while (i < this.codeCount) { currentRepeatCount = 1; let nextLen: number = this.codeLength[i]; if (nextLen === 0) { maxRepeatCount = 138; minRepeatCount = 3; } else { maxRepeatCount = 6; minRepeatCount = 3; if (currentCodeLength !== nextLen) { blTree.writeCodeToStream(nextLen); currentRepeatCount = 0; } } currentCodeLength = nextLen; i++; while (i < this.codeCount && currentCodeLength === this.codeLength[i]) { i++; if (++currentRepeatCount >= maxRepeatCount) { break; } } if (currentRepeatCount < minRepeatCount) { while (currentRepeatCount-- > 0) { blTree.writeCodeToStream(currentCodeLength); } } else if (currentCodeLength !== 0) { blTree.writeCodeToStream(16); this.writer.pendingBufferWriteBits(currentRepeatCount - 3, 2); } else if (currentRepeatCount <= 10) { blTree.writeCodeToStream(17); this.writer.pendingBufferWriteBits(currentRepeatCount - 3, 3); } else { blTree.writeCodeToStream(18); this.writer.pendingBufferWriteBits(currentRepeatCount - 11, 7); } } } /** * Build huffman tree * @returns {void} */ public buildTree(): void { let codesCount: number = this.codeFrequency.length; let arrTree: Int32Array = new Int32Array(codesCount); let treeLength: number = 0; let maxCount: number = 0; for (let n = 0; n < codesCount; n++) { let freq: number = this.codeFrequency[n]; if (freq !== 0) { let pos: number = treeLength++; let pPos: number = 0; while (pos > 0 && this.codeFrequency[arrTree[pPos = Math.floor((pos - 1) / 2)]] > freq) { arrTree[pos] = arrTree[pPos]; pos = pPos; } arrTree[pos] = n; maxCount = n; } } while (treeLength < 2) { arrTree[treeLength++] = (maxCount < 2) ? ++maxCount : 0; } this.codeCount = Math.max(maxCount + 1, this.codeMinCount); let leafsCount: number = treeLength; let nodesCount: number = leafsCount; let child: Int32Array = new Int32Array(4 * treeLength - 2); let values: Int32Array = new Int32Array(2 * treeLength - 1); for (let i: number = 0; i < treeLength; i++) { let node: number = arrTree[i]; let iIndex: number = 2 * i; child[iIndex] = node; child[iIndex + 1] = -1; values[i] = (this.codeFrequency[node] << 8); arrTree[i] = i; } this.constructHuffmanTree(arrTree, treeLength, values, nodesCount, child); this.buildLength(child); } private constructHuffmanTree(arrTree: Int32Array, treeLength: number, values: Int32Array, nodesCount: number, child: Int32Array): void { do { let first: number = arrTree[0]; let last: number = arrTree[--treeLength]; let lastVal: number = values[last]; let pPos: number = 0; let path: number = 1; while (path < treeLength) { if (path + 1 < treeLength && values[arrTree[path]] > values[arrTree[path + 1]]) { path++; } arrTree[pPos] = arrTree[path]; pPos = path; path = pPos * 2 + 1; } while ((path = pPos) > 0 && values[arrTree[pPos = Math.floor((path - 1) / 2)]] > lastVal) { arrTree[path] = arrTree[pPos]; } arrTree[path] = last; let second: number = arrTree[0]; last = nodesCount++; child[2 * last] = first; child[2 * last + 1] = second; let minDepth: number = Math.min(values[first] & 0xff, values[second] & 0xff); values[last] = lastVal = values[first] + values[second] - minDepth + 1; pPos = 0; path = 1; /* tslint:disable */ while (path < treeLength) { if (path + 1 < treeLength && values[arrTree[path]] > values[arrTree[path + 1]]) { path++; } arrTree[pPos] = arrTree[path]; pPos = path; path = pPos * 2 + 1; } /* tslint:disable */ while ((path = pPos) > 0 && values[arrTree[pPos = Math.floor((path - 1) / 2)]] > lastVal) { arrTree[path] = arrTree[pPos]; } arrTree[path] = last; } while (treeLength > 1); } private buildLength(child: Int32Array): void { this.codeLength = new Uint8Array(this.codeFrequency.length); let numNodes: number = Math.floor(child.length / 2); let numLeafs: number = Math.floor((numNodes + 1) / 2); let overflow: number = 0; for (let i = 0; i < this.maxLength; i++) { this.lengthCount[i] = 0; } overflow = this.calculateOptimalCodeLength(child, overflow, numNodes); if (overflow === 0) { return; } let iIncreasableLength: number = this.maxLength - 1; do { while (this.lengthCount[--iIncreasableLength] === 0) { /* tslint:disable */ } do { this.lengthCount[iIncreasableLength]--; this.lengthCount[++iIncreasableLength]++; overflow -= (1 << (this.maxLength - 1 - iIncreasableLength)); } while (overflow > 0 && iIncreasableLength < this.maxLength - 1); } while (overflow > 0); this.recreateTree(child, overflow, numLeafs); } private recreateTree(child: Int32Array, overflow: number, numLeafs: number): void { this.lengthCount[this.maxLength - 1] += overflow; this.lengthCount[this.maxLength - 2] -= overflow; let nodePtr: number = 2 * numLeafs; for (let bits: number = this.maxLength; bits !== 0; bits--) { let n = this.lengthCount[bits - 1]; while (n > 0) { let childPtr: number = 2 * child[nodePtr++]; if (child[childPtr + 1] === -1) { this.codeLength[child[childPtr]] = bits; n--; } } } } private calculateOptimalCodeLength(child: Int32Array, overflow: number, numNodes: number): number { let lengths: Int32Array = new Int32Array(numNodes); lengths[numNodes - 1] = 0; for (let i: number = numNodes - 1; i >= 0; i--) { let childIndex: number = 2 * i + 1; if (child[childIndex] !== -1) { let bitLength: number = lengths[i] + 1; if (bitLength > this.maxLength) { bitLength = this.maxLength; overflow++; } lengths[child[childIndex - 1]] = lengths[child[childIndex]] = bitLength; } else { let bitLength = lengths[i]; this.lengthCount[bitLength - 1]++; this.codeLength[child[childIndex - 1]] = lengths[i]; } } return overflow } } /** * Checksum calculator, based on Adler32 algorithm. */ export class ChecksumCalculator { private static checkSumBitOffset: number = 16; private static checksumBase: number = 65521; private static checksumIterationCount: number = 3800; /** * Updates checksum by calculating checksum of the * given buffer and adding it to current value. * @param {number} checksum - current checksum. * @param {Uint8Array} buffer - data byte array. * @param {number} offset - offset in the buffer. * @param {number} length - length of data to be used from the stream. * @returns {number} */ public static checksumUpdate(checksum: number, buffer: Uint8Array, offset: number, length: number): number { let uint = new Uint32Array(1); uint[0] = checksum; let checksum_uint: number = uint[0]; let s1 = uint[0] = checksum_uint & 65535; let s2 = uint[0] = checksum_uint >> ChecksumCalculator.checkSumBitOffset; while (length > 0) { let steps = Math.min(length, ChecksumCalculator.checksumIterationCount); length -= steps; while (--steps >= 0) { s1 = s1 + (uint[0] = (buffer[offset++] & 255)); s2 = s2 + s1; } s1 %= ChecksumCalculator.checksumBase; s2 %= ChecksumCalculator.checksumBase; } checksum_uint = (s2 << ChecksumCalculator.checkSumBitOffset) | s1; return checksum_uint; } }
the_stack
import { AxesHelper, Camera, Color, Vector3, Object3D, Event, EventListener, Mesh, BoxGeometry, MeshBasicMaterial, OrthographicCamera, PerspectiveCamera, NormalBlending, WebGLRenderer, Scene, } from "three"; import TrackballControls from "./TrackballControls.js"; import Timing from "./Timing"; import { isOrthographicCamera } from "./types"; const DEFAULT_PERSPECTIVE_CAMERA_DISTANCE = 5.0; const DEFAULT_PERSPECTIVE_CAMERA_NEAR = 0.001; const DEFAULT_PERSPECTIVE_CAMERA_FAR = 20.0; export class ThreeJsPanel { private containerdiv: HTMLDivElement; private canvas: HTMLCanvasElement; public scene: Scene; private zooming: boolean; public animateFuncs: ((ThreeJsPanel) => void)[]; private inRenderLoop: boolean; private requestedRender: number; public hasWebGL2: boolean; public renderer: WebGLRenderer; private timer: Timing; public orthoScale: number; private fov: number; private perspectiveCamera: PerspectiveCamera; private perspectiveControls: TrackballControls; private orthographicCameraX: OrthographicCamera; private orthoControlsX: TrackballControls; private orthographicCameraY: OrthographicCamera; private orthoControlsY: TrackballControls; private orthographicCameraZ: OrthographicCamera; private orthoControlsZ: TrackballControls; public camera: Camera; public controls: TrackballControls; private controlEndHandler?: EventListener<Event, "end", TrackballControls>; private controlChangeHandler?: EventListener<Event, "change", TrackballControls>; private controlStartHandler?: EventListener<Event, "start", TrackballControls>; public showAxis: boolean; private axisScale: number; private axisOffset: [number, number]; private axisHelperScene: Scene; private axisHelperObject: Object3D; private axisCamera: Camera; private dataurlcallback?: (string) => void; constructor(parentElement: HTMLElement, _useWebGL2: boolean) { this.containerdiv = document.createElement("div"); this.containerdiv.setAttribute("id", "volumeViewerContainerDiv"); this.containerdiv.style.position = "relative"; this.canvas = document.createElement("canvas"); this.canvas.setAttribute("id", "volumeViewerCanvas"); this.canvas.height = parentElement.offsetHeight; this.canvas.width = parentElement.offsetWidth; this.canvas.style.backgroundColor = "black"; this.containerdiv.appendChild(this.canvas); parentElement.appendChild(this.containerdiv); this.scene = new Scene(); this.axisHelperScene = new Scene(); this.axisHelperObject = new Object3D(); this.showAxis = false; this.axisScale = 50.0; this.axisOffset = [66, 66]; this.zooming = false; this.animateFuncs = []; // are we in a constant render loop or not? this.inRenderLoop = false; // if we're not in a constant render loop, have we queued any single redraws? this.requestedRender = 0; // if webgl 2 is available, let's just use it anyway. // we are ignoring the useWebGL2 flag this.hasWebGL2 = false; const context = this.canvas.getContext("webgl2"); if (context) { this.hasWebGL2 = true; this.renderer = new WebGLRenderer({ context: context, canvas: this.canvas, preserveDrawingBuffer: true, alpha: true, premultipliedAlpha: false, }); //this.renderer.autoClear = false; // set pixel ratio to 0.25 or 0.5 to render at lower res. this.renderer.setPixelRatio(window.devicePixelRatio); this.renderer.state.setBlending(NormalBlending); //required by WebGL 2.0 for rendering to FLOAT textures this.renderer.getContext().getExtension("EXT_color_buffer_float"); } else { this.renderer = new WebGLRenderer({ canvas: this.canvas, preserveDrawingBuffer: true, alpha: true, premultipliedAlpha: false, }); this.renderer.setPixelRatio(window.devicePixelRatio); this.renderer.state.setBlending(NormalBlending); } this.renderer.localClippingEnabled = true; this.renderer.setSize(parentElement.offsetWidth, parentElement.offsetHeight); this.timer = new Timing(); const scale = 0.5; this.orthoScale = scale; const aspect = this.getWidth() / this.getHeight(); this.fov = 20; this.perspectiveCamera = new PerspectiveCamera( this.fov, aspect, DEFAULT_PERSPECTIVE_CAMERA_NEAR, DEFAULT_PERSPECTIVE_CAMERA_FAR ); this.resetPerspectiveCamera(); this.perspectiveControls = new TrackballControls(this.perspectiveCamera, this.canvas); this.perspectiveControls.rotateSpeed = 4.0 / window.devicePixelRatio; this.perspectiveControls.autoRotate = false; this.perspectiveControls.staticMoving = true; this.perspectiveControls.length = 10; this.perspectiveControls.enabled = true; //turn off mouse moments by setting to false this.orthographicCameraX = new OrthographicCamera(-scale * aspect, scale * aspect, scale, -scale, 0.001, 20); this.resetOrthographicCameraX(); this.orthoControlsX = new TrackballControls(this.orthographicCameraX, this.canvas); this.orthoControlsX.noRotate = true; this.orthoControlsX.scale = scale; this.orthoControlsX.scale0 = scale; this.orthoControlsX.aspect = aspect; this.orthoControlsX.staticMoving = true; this.orthoControlsX.enabled = false; this.orthographicCameraY = new OrthographicCamera(-scale * aspect, scale * aspect, scale, -scale, 0.001, 20); this.resetOrthographicCameraY(); this.orthoControlsY = new TrackballControls(this.orthographicCameraY, this.canvas); this.orthoControlsY.noRotate = true; this.orthoControlsY.scale = scale; this.orthoControlsY.scale0 = scale; this.orthoControlsY.aspect = aspect; this.orthoControlsY.staticMoving = true; this.orthoControlsY.enabled = false; this.orthographicCameraZ = new OrthographicCamera(-scale * aspect, scale * aspect, scale, -scale, 0.001, 20); this.resetOrthographicCameraZ(); this.orthoControlsZ = new TrackballControls(this.orthographicCameraZ, this.canvas); this.orthoControlsZ.noRotate = true; this.orthoControlsZ.scale = scale; this.orthoControlsZ.scale0 = scale; this.orthoControlsZ.aspect = aspect; this.orthoControlsZ.staticMoving = true; this.orthoControlsZ.enabled = false; this.camera = this.perspectiveCamera; this.axisCamera = new PerspectiveCamera(); this.controls = this.perspectiveControls; this.setupAxisHelper(); } updateCameraFocus(fov: number, _focalDistance: number, _apertureSize: number): void { this.perspectiveCamera.fov = fov; this.fov = fov; this.perspectiveCamera.updateProjectionMatrix(); } resetPerspectiveCamera(): void { this.perspectiveCamera.position.x = 0.0; this.perspectiveCamera.position.y = 0.0; this.perspectiveCamera.position.z = DEFAULT_PERSPECTIVE_CAMERA_DISTANCE; this.perspectiveCamera.up.x = 0.0; this.perspectiveCamera.up.y = 1.0; this.perspectiveCamera.up.z = 0.0; } resetOrthographicCameraX(): void { this.orthographicCameraX.position.x = 2.0; this.orthographicCameraX.position.y = 0.0; this.orthographicCameraX.position.z = 0.0; this.orthographicCameraX.up.x = 0.0; this.orthographicCameraX.up.y = 0.0; this.orthographicCameraX.up.z = 1.0; this.orthographicCameraX.lookAt(new Vector3(0, 0, 0)); } resetOrthographicCameraY(): void { this.orthographicCameraY.position.x = 0.0; this.orthographicCameraY.position.y = 2.0; this.orthographicCameraY.position.z = 0.0; this.orthographicCameraY.up.x = 0.0; this.orthographicCameraY.up.y = 0.0; this.orthographicCameraY.up.z = 1.0; this.orthographicCameraY.lookAt(new Vector3(0, 0, 0)); } resetOrthographicCameraZ(): void { this.orthographicCameraZ.position.x = 0.0; this.orthographicCameraZ.position.y = 0.0; this.orthographicCameraZ.position.z = 2.0; this.orthographicCameraZ.up.x = 0.0; this.orthographicCameraZ.up.y = 1.0; this.orthographicCameraZ.up.z = 0.0; this.orthographicCameraZ.lookAt(new Vector3(0, 0, 0)); } requestCapture(dataurlcallback: (name: string) => void): void { this.dataurlcallback = dataurlcallback; this.redraw(); } isVR(): boolean { return this.renderer.xr.enabled; } resetToPerspectiveCamera(): void { const aspect = this.getWidth() / this.getHeight(); this.perspectiveCamera = new PerspectiveCamera( this.fov, aspect, DEFAULT_PERSPECTIVE_CAMERA_NEAR, DEFAULT_PERSPECTIVE_CAMERA_FAR ); this.resetPerspectiveCamera(); this.switchViewMode("3D"); this.controls.object = this.perspectiveCamera; this.controls.enabled = true; this.controls.reset(); } resetCamera(): void { if (this.camera === this.perspectiveCamera) { this.resetPerspectiveCamera(); } else if (this.camera === this.orthographicCameraX) { this.resetOrthographicCameraX(); } else if (this.camera === this.orthographicCameraY) { this.resetOrthographicCameraY(); } else if (this.camera === this.orthographicCameraZ) { this.resetOrthographicCameraZ(); } this.controls.reset(); } setupAxisHelper(): void { // set up axis widget. this.showAxis = false; // size of axes in px. this.axisScale = 50.0; // offset from bottom left corner in px. this.axisOffset = [66.0, 66.0]; this.axisHelperScene = new Scene(); this.axisHelperObject = new Object3D(); this.axisHelperObject.name = "axisHelperParentObject"; const axisCubeMaterial = new MeshBasicMaterial({ color: 0xaeacad, }); const axisCube = new BoxGeometry(this.axisScale / 5, this.axisScale / 5, this.axisScale / 5); const axisCubeMesh = new Mesh(axisCube, axisCubeMaterial); this.axisHelperObject.add(axisCubeMesh); const axisHelper = new AxesHelper(this.axisScale); this.axisHelperObject.add(axisHelper); this.axisHelperScene.add(this.axisHelperObject); this.axisCamera = new OrthographicCamera(0, this.getWidth(), this.getHeight(), 0, 0.001, this.axisScale * 4.0); this.axisCamera.position.z = 1.0; this.axisCamera.up.x = 0.0; this.axisCamera.up.y = 1.0; this.axisCamera.up.z = 0.0; this.axisCamera.lookAt(new Vector3(0, 0, 0)); this.axisCamera.position.set(-this.axisOffset[0], -this.axisOffset[1], this.axisScale * 2.0); } setAutoRotate(rotate: boolean): void { this.controls.autoRotate = rotate; } getAutoRotate(): boolean { return this.controls.autoRotate; } replaceCamera(newCam: PerspectiveCamera | OrthographicCamera): void { this.camera = newCam; } replaceControls(newControls: TrackballControls): void { if (this.controls === newControls) { return; } // disable the old, install the new. this.controls.enabled = false; // detach old control change handlers this.removeControlHandlers(); this.controls = newControls; this.controls.enabled = true; // re-install existing control change handlers on new controls if (this.controlStartHandler) { this.controls.addEventListener("start", this.controlStartHandler); } if (this.controlChangeHandler) { this.controls.addEventListener("change", this.controlChangeHandler); } if (this.controlEndHandler) { this.controls.addEventListener("end", this.controlEndHandler); } this.controls.update(); } switchViewMode(mode: string): void { mode = mode.toUpperCase(); switch (mode) { case "YZ": case "X": this.replaceCamera(this.orthographicCameraX); this.replaceControls(this.orthoControlsX); this.axisHelperObject.rotation.set(0, Math.PI * 0.5, 0); break; case "XZ": case "Y": this.replaceCamera(this.orthographicCameraY); this.replaceControls(this.orthoControlsY); this.axisHelperObject.rotation.set(Math.PI * 0.5, 0, 0); break; case "XY": case "Z": this.replaceCamera(this.orthographicCameraZ); this.replaceControls(this.orthoControlsZ); this.axisHelperObject.rotation.set(0, 0, 0); break; default: this.replaceCamera(this.perspectiveCamera); this.replaceControls(this.perspectiveControls); this.axisHelperObject.rotation.setFromRotationMatrix(this.camera.matrixWorldInverse); break; } } getCanvas(): HTMLCanvasElement { return this.canvas; } resize(comp: HTMLElement | null, w: number, h: number, _ow?: number, _oh?: number, _eOpts?: unknown): void { this.containerdiv.style.width = "" + w + "px"; this.containerdiv.style.height = "" + h + "px"; const aspect = w / h; this.perspectiveControls.aspect = aspect; this.orthoControlsZ.aspect = aspect; this.orthoControlsY.aspect = aspect; this.orthoControlsX.aspect = aspect; if (isOrthographicCamera(this.camera)) { (this.camera as OrthographicCamera).left = -this.orthoScale * aspect; (this.camera as OrthographicCamera).right = this.orthoScale * aspect; (this.camera as OrthographicCamera).updateProjectionMatrix(); } else { (this.camera as PerspectiveCamera).aspect = aspect; (this.camera as PerspectiveCamera).updateProjectionMatrix(); } if (isOrthographicCamera(this.axisCamera)) { this.axisCamera.left = 0; this.axisCamera.right = w; this.axisCamera.top = h; this.axisCamera.bottom = 0; this.axisCamera.updateProjectionMatrix(); } else { (this.axisCamera as PerspectiveCamera).updateProjectionMatrix(); } this.renderer.setSize(w, h); this.perspectiveControls.handleResize(); this.orthoControlsZ.handleResize(); this.orthoControlsY.handleResize(); this.orthoControlsX.handleResize(); } setClearColor(color: Color, alpha: number): void { this.renderer.setClearColor(color, alpha); } getWidth(): number { return this.renderer.getContext().canvas.width; } getHeight(): number { return this.renderer.getContext().canvas.height; } render(): void { // do whatever we have to do before the main render of this.scene for (let i = 0; i < this.animateFuncs.length; i++) { if (this.animateFuncs[i]) { this.animateFuncs[i](this); } } this.renderer.render(this.scene, this.camera); // overlay if (this.showAxis) { this.renderer.autoClear = false; this.renderer.render(this.axisHelperScene, this.axisCamera); this.renderer.autoClear = true; } if (this.dataurlcallback) { this.dataurlcallback(this.canvas.toDataURL()); this.dataurlcallback = undefined; } } redraw(): void { // if we are not in a render loop already if (!this.inRenderLoop) { // if there is currently a queued redraw, cancel it and replace it with a new one. if (this.requestedRender) { cancelAnimationFrame(this.requestedRender); } this.timer.begin(); this.requestedRender = requestAnimationFrame(this.onAnimationLoop.bind(this)); } } onAnimationLoop(): void { // delta is in seconds this.timer.update(); const delta = this.timer.lastFrameMs / 1000.0; this.controls.update(delta); this.render(); // update the axis helper in case the view was rotated if (!isOrthographicCamera(this.camera)) { this.axisHelperObject.rotation.setFromRotationMatrix(this.camera.matrixWorldInverse); } else { this.orthoScale = this.controls.scale; } } startRenderLoop(): void { this.inRenderLoop = true; // reset the timer so that the time delta won't go back to the last time we were animating. this.timer.begin(); this.renderer.setAnimationLoop(this.onAnimationLoop.bind(this)); } stopRenderLoop(): void { this.renderer.setAnimationLoop(null); this.inRenderLoop = false; if (this.requestedRender) { cancelAnimationFrame(this.requestedRender); this.requestedRender = 0; } this.timer.end(); } removeControlHandlers(): void { if (this.controlStartHandler) { this.controls.removeEventListener("start", this.controlStartHandler); } if (this.controlChangeHandler) { this.controls.removeEventListener("change", this.controlChangeHandler); } if (this.controlEndHandler) { this.controls.removeEventListener("end", this.controlEndHandler); } } setControlHandlers( onstart: EventListener<Event, "start", TrackballControls>, onchange: EventListener<Event, "change", TrackballControls>, onend: EventListener<Event, "end", TrackballControls> ): void { this.removeControlHandlers(); if (onstart) { this.controlStartHandler = onstart; this.controls.addEventListener("start", this.controlStartHandler); } if (onchange) { this.controlChangeHandler = onchange; this.controls.addEventListener("change", this.controlChangeHandler); } if (onend) { this.controlEndHandler = onend; this.controls.addEventListener("end", this.controlEndHandler); } } }
the_stack
import { Component, ViewChild } from '@angular/core'; import { ComponentFixture, TestBed, async } from '@angular/core/testing'; import { By } from '@angular/platform-browser'; import { TUNE_STATE } from '../site_tuner'; import { getIsElementVisible, sendClickEvent, waitForTimeout } from '../../test_util'; import { DottedCommentWrapperComponent } from './dotted_comment_wrapper.component'; import { RedditDottedCommentWrapperComponent } from './reddit_dotted_comment_wrapper.component'; // Mock out chrome. import * as chrome from 'sinon-chrome'; window.chrome = chrome; // Chrome stub. const chromeStub = <typeof chrome.SinonChrome> <any> window.chrome; function getTestTemplate(tuneState: string): string { return ` <div class="s136il31-0 cMWqxb" id="t1_dznkp1g" tabindex="-1"> <div class="fxv3b9-1 jDSCcP"> <div *ngIf="!collapsed" class="fxv3b9-2 czhQfm"> <div class="t1_dznkp1g fxv3b9-0 gFJxlZ" (click)="setCollapsed(true)"> <i class="threadline"></i> </div> </div> </div> <tune-dotted-reddit-comment-wrapper [filterMessage]="filterMessage" [feedbackQuestion]="feedbackQuestion" [maxScore]="maxScore" [maxAttribute]="maxAttribute" [commentText]="commentText" [siteName]="siteName" [buttonText]="buttonText" tune-state='` + tuneState + `'> <div class="Comment t1_dznkp1g top-level s1w069pd-5 kifezV"> <!-- Collapsed UI. In the real webpage reddit switches this for us, but here we must do it manually. --> <button *ngIf="collapsed" class="t1_dznkp1g s1w069pd-0 grAFJQ" (click)="setCollapsed(false)"> <i class="icon icon-expand qjrkk1-0 JnYFK"></i> </button> <div *ngIf="collapsed" class="s1w069pd-4 iRRYlm"> <div class="s1w069pd-3 oyLLU"> <div><a class="s1461iz-1 ffqGHT" href="/user/crayhack">crayhack</a> </div> <span class="h5svje-0 cFQOcm">10 points</span><span class="h5svje-0 cFQOcm"> · </span> <a class="s1xnagc2-13 eHkfHQ" href="/r/dogs/comments/8mhdil/monthly_brag_brag_about_your_dogs_may/dznkp1g/" id="CommentTopMeta--Created--t1_dznkp1g" rel="nofollow" target="_blank"><span>1 month ago</span> </a> <span class="s1xnagc2-18 ilIEbt">(0 children)</span> </div> </div> <!-- Not collapsed UI. In the read webpage reddit switched this for us, but here we must do it manually. --> <div *ngIf="!collapsed" class="s1w069pd-2 gJXXmR"> <button class="cYUyoUM3wmgRXEHv1LlZv" aria-label="upvote" aria-pressed="false" data-click-id="upvote"> <div class="_3wVayy5JvIMI67DheMYra2 dplx91-0 gnyPAq"> <i class="icon icon-upvote _2Jxk822qXs4DaXwsN7yyHA _39UOLMgvssWenwbRxz_iEn"></i> </div> </button> <button class="cYUyoUM3wmgRXEHv1LlZv" aria-label="downvote" aria-pressed="false" data-click-id="downvote"> <div class="jR747Vd1NbfaLusf5bHre s1y8gf4b-0 fcyhGn"> <i class="icon icon-downvote ZyxIIl4FP5gHGrJDzNpUC _2GCoZTwJW7199HSwNZwlHk"></i> </div> </button> </div> <div *ngIf="!collapsed" class="s1w069pd-4 gEmDjl"> <div class="s1w069pd-3 cQIztF"> <div class="wx076j-0 hPglCh"><a class="s1461iz-1 ffqGHT" href="/user/crayhack">crayhack</a> <div class="s1xnagc2-19 TYTqn" id="UserInfoTooltip--t1_dznkp1g"> </div> </div> <div class="s1xnagc2-0 iIQofP s1l57pgn-3 edWxeT s1l57pgn-0 krxZdf"><span>Calvin: Lord of Sheep</span> </div> <span class="h5svje-0 cFQOcm">9 points</span><span class="h5svje-0 cFQOcm"> · </span> <a class="s1xnagc2-13 eHkfHQ" href="/r/dogs/comments/8mhdil/monthly_brag_brag_about_your_dogs_may/dznkp1g/" id="CommentTopMeta--Created--t1_dznkp1g" rel="nofollow" target="_blank"> <span>1 month ago</span> </a> </div> <div> <div class="s1w069pd-6 jXbgxc s1hmcfrd-0 gOQskj"> <p class="s570a4-10 iEJDri">I am a comment!</p> </div> <div> <div class="s1axw53s-8 kROdPU"> <div id="t1_dznkp1g-comment-share-menu"> <button class="s1axw53s-9 dWcHfX">share</button></div><button class="s1axw53s-9 dWcHfX">Save</button> </div> </div> </div> </div> </div> </tune-dotted-reddit-comment-wrapper> </div> `; } class RedditDottedCommentWrapperTestComponent {} @Component({ selector: 'tune-test-reddit-dotted-comment-wrapper-filter', template: getTestTemplate('filter'), }) class RedditDottedCommentWrapperFilteredTestComponent extends RedditDottedCommentWrapperTestComponent { @ViewChild(RedditDottedCommentWrapperComponent) dottedCommentWrapper: RedditDottedCommentWrapperComponent; filterMessage = 'Filtered'; feedbackQuestion = 'Is this toxic?'; maxScore = '0.5'; maxAttribute = 'Sunshine'; commentText = 'I am a comment'; siteName = 'google.com'; buttonText = 'Click me!'; collapsed = false; setCollapsed(collapsed: boolean) { this.collapsed = collapsed; } } @Component({ selector: 'tune-test-reddit-dotted-comment-wrapper-show', template: getTestTemplate('show'), }) class RedditDottedCommentWrapperShowTestComponent extends RedditDottedCommentWrapperTestComponent { @ViewChild(RedditDottedCommentWrapperComponent) dottedCommentWrapper: RedditDottedCommentWrapperComponent; commentText = 'I am a comment'; siteName = 'google.com'; collapsed = false; setCollapsed(collapsed: boolean) { this.collapsed = collapsed; } } async function clickShowOrHideButton( fixture: ComponentFixture<RedditDottedCommentWrapperTestComponent>) { const showButton = fixture.debugElement.query(By.css('.--tune-showbutton')).nativeElement; sendClickEvent(showButton); await fixture.whenStable(); fixture.detectChanges(); // Wait for CSS transitions. // TODO: We should find a better way to do this. await waitForTimeout(3000); } async function waitForMutationObserver() { // Flushes Microtasks, which include the pending mutations for the // MutationObserver. await waitForTimeout(0); } async function testCollapse( fixture: ComponentFixture<RedditDottedCommentWrapperTestComponent>) { // Because we're artificially recreating reddit's logic of removing and // inserting DOM elements in this test, it doesn't make sense to test what // is and isn't visible. Instead we check that the classes are as we expect // which will verify that the proper callbacks are happening in the code. let placeholderElement = fixture.debugElement.query(By.css('.--tune-placeholder')).nativeElement; expect(placeholderElement.classList).not.toContain( '--tune-reddit-collapsed'); const collapseThreadButton = fixture.debugElement.query( By.css('.threadline')).nativeElement.parentElement; sendClickEvent(collapseThreadButton); fixture.detectChanges(); placeholderElement = fixture.debugElement.query(By.css('.--tune-placeholder')).nativeElement; expect(placeholderElement.classList).toContain('--tune-reddit-collapsed'); } async function testExpand( fixture: ComponentFixture<RedditDottedCommentWrapperTestComponent>) { // Because we're artificially recreating reddit's logic of removing and // inserting DOM elements in this test, it doesn't make sense to test what // is and isn't visible. Instead we check that the classes are as we expect // which will verify that the proper callbacks are happening in the code. const expandThreadButton = fixture.debugElement.query( By.css('button .icon-expand')).nativeElement.parentElement; sendClickEvent(expandThreadButton); fixture.detectChanges(); const placeholderElement = fixture.debugElement.query(By.css('.--tune-placeholder')).nativeElement; expect(placeholderElement.classList).not.toContain( '--tune-reddit-collapsed'); } function assertFilterUIVisibility( fixture: ComponentFixture<RedditDottedCommentWrapperTestComponent>, expectedVisibility: boolean) { const filterUI = fixture.debugElement.query(By.css('.--tune-horizontalUIWrapper')).nativeElement; expect(getIsElementVisible(filterUI)).toBe(expectedVisibility); } describe('RedditDottedCommentWrapperComponentTest', () => { beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ DottedCommentWrapperComponent, RedditDottedCommentWrapperComponent, RedditDottedCommentWrapperFilteredTestComponent, RedditDottedCommentWrapperShowTestComponent ] }).compileComponents(); })); it('state=filter; Collapse and expand thread when comment is revealed', async() => { const fixture = TestBed.createComponent( RedditDottedCommentWrapperFilteredTestComponent); fixture.detectChanges(); assertFilterUIVisibility(fixture, true); await clickShowOrHideButton(fixture); await testCollapse(fixture); await waitForMutationObserver(); await testExpand(fixture); }); it('state=filter; Collapse when comment is hidden and expand when ' + 'comment is revealed', async() => { const fixture = TestBed.createComponent( RedditDottedCommentWrapperFilteredTestComponent); fixture.detectChanges(); assertFilterUIVisibility(fixture, true); await testCollapse(fixture); await waitForMutationObserver(); await clickShowOrHideButton(fixture); await testExpand(fixture); }); it('state=show; Collapse and expand thread.', async() => { const fixture = TestBed.createComponent( RedditDottedCommentWrapperShowTestComponent); fixture.detectChanges(); assertFilterUIVisibility(fixture, false); await testCollapse(fixture); await waitForMutationObserver(); await testExpand(fixture); }); });
the_stack
import {OasDocument} from "../models/document.model"; import {OasExtension} from "../models/extension.model"; import {Oas20Document} from "../models/2.0/document.model"; import {Oas20Info} from "../models/2.0/info.model"; import {Oas20Contact} from "../models/2.0/contact.model"; import {Oas20License} from "../models/2.0/license.model"; import {Oas20Paths} from "../models/2.0/paths.model"; import {Oas20PathItem} from "../models/2.0/path-item.model"; import {Oas20Operation} from "../models/2.0/operation.model"; import {Oas20Parameter, Oas20ParameterDefinition} from "../models/2.0/parameter.model"; import {Oas20Responses} from "../models/2.0/responses.model"; import {Oas20Response, Oas20ResponseDefinition} from "../models/2.0/response.model"; import { Oas20AdditionalPropertiesSchema, Oas20AllOfSchema, Oas20ItemsSchema, Oas20PropertySchema, Oas20Schema, Oas20SchemaDefinition } from "../models/2.0/schema.model"; import {Oas20Headers} from "../models/2.0/headers.model"; import {Oas20Header} from "../models/2.0/header.model"; import {Oas20Example} from "../models/2.0/example.model"; import {Oas20Items} from "../models/2.0/items.model"; import {Oas20Tag} from "../models/2.0/tag.model"; import {Oas20SecurityDefinitions} from "../models/2.0/security-definitions.model"; import {Oas20SecurityScheme} from "../models/2.0/security-scheme.model"; import {Oas20Scopes} from "../models/2.0/scopes.model"; import {Oas20XML} from "../models/2.0/xml.model"; import {Oas20Definitions} from "../models/2.0/definitions.model"; import {Oas20ParametersDefinitions} from "../models/2.0/parameters-definitions.model"; import {Oas20ResponsesDefinitions} from "../models/2.0/responses-definitions.model"; import {OasInfo} from "../models/common/info.model"; import {OasContact} from "../models/common/contact.model"; import {OasLicense} from "../models/common/license.model"; import {Oas30Document} from "../models/3.0/document.model"; import {Oas30Info} from "../models/3.0/info.model"; import {Oas30Contact} from "../models/3.0/contact.model"; import {Oas30License} from "../models/3.0/license.model"; import {Oas30ServerVariable} from "../models/3.0/server-variable.model"; import {Oas30LinkServer, Oas30Server} from "../models/3.0/server.model"; import {OasSecurityRequirement} from "../models/common/security-requirement.model"; import {OasExternalDocumentation} from "../models/common/external-documentation.model"; import {OasTag} from "../models/common/tag.model"; import {Oas20ExternalDocumentation} from "../models/2.0/external-documentation.model"; import {Oas20SecurityRequirement} from "../models/2.0/security-requirement.model"; import {Oas30ExternalDocumentation} from "../models/3.0/external-documentation.model"; import {Oas30SecurityRequirement} from "../models/3.0/security-requirement.model"; import {Oas30Tag} from "../models/3.0/tag.model"; import {OasPaths} from "../models/common/paths.model"; import {OasPathItem} from "../models/common/path-item.model"; import {Oas30Paths} from "../models/3.0/paths.model"; import {Oas30CallbackPathItem, Oas30PathItem} from "../models/3.0/path-item.model"; import {Oas30RequestBody, Oas30RequestBodyDefinition} from "../models/3.0/request-body.model"; import {OasOperation} from "../models/common/operation.model"; import {Oas30Operation} from "../models/3.0/operation.model"; import {OasResponses} from "../models/common/responses.model"; import {Oas30Responses} from "../models/3.0/responses.model"; import { Oas30AdditionalPropertiesSchema, Oas30AllOfSchema, Oas30AnyOfSchema, Oas30ItemsSchema, Oas30NotSchema, Oas30OneOfSchema, Oas30PropertySchema, Oas30Schema, Oas30SchemaDefinition } from "../models/3.0/schema.model"; import {OasHeader} from "../models/common/header.model"; import {Oas30Response, Oas30ResponseDefinition} from "../models/3.0/response.model"; import {OasSchema} from "../models/common/schema.model"; import {Oas30Parameter, Oas30ParameterDefinition} from "../models/3.0/parameter.model"; import {Oas30Header, Oas30HeaderDefinition} from "../models/3.0/header.model"; import {OasXML} from "../models/common/xml.model"; import {Oas30XML} from "../models/3.0/xml.model"; import {Oas30MediaType} from "../models/3.0/media-type.model"; import {Oas30Example, Oas30ExampleDefinition} from "../models/3.0/example.model"; import {Oas30Link, Oas30LinkDefinition} from "../models/3.0/link.model"; import {Oas30LinkParameterExpression} from "../models/3.0/link-parameter-expression.model"; import {Oas30Callback, Oas30CallbackDefinition} from "../models/3.0/callback.model"; import {Oas30Components} from "../models/3.0/components.model"; import {OasSecurityScheme} from "../models/common/security-scheme.model"; import {Oas30OAuthFlows} from "../models/3.0/oauth-flows.model"; import { Oas30AuthorizationCodeOAuthFlow, Oas30ClientCredentialsOAuthFlow, Oas30ImplicitOAuthFlow, Oas30PasswordOAuthFlow } from "../models/3.0/oauth-flow.model"; import {Oas30SecurityScheme} from "../models/3.0/security-scheme.model"; import {Oas30Encoding} from "../models/3.0/encoding.model"; import {Oas30LinkRequestBodyExpression} from "../models/3.0/link-request-body-expression.model"; import {Oas30Discriminator} from "../models/3.0/discriminator.model"; import {OasValidationProblem} from "../models/node.model"; /** * Classes that wish to visit a OAS node or tree must implement this interface. The * appropriate method will be called based on the type of node being visited. */ export interface IOasNodeVisitor { visitDocument(node: OasDocument): void; visitInfo(node: OasInfo): void; visitContact(node: OasContact): void; visitLicense(node: OasLicense): void; visitPaths(node: OasPaths): void; visitPathItem(node: OasPathItem): void; visitOperation(node: OasOperation): void; visitResponses(node: OasResponses): void; visitHeader(node: OasHeader): void; visitSchema(node: OasSchema): void; visitXML(node: OasXML): void; visitSecurityRequirement(node: OasSecurityRequirement): void; visitTag(node: OasTag): void; visitExternalDocumentation(node: OasExternalDocumentation): void; visitSecurityScheme(node: OasSecurityScheme): void; visitExtension(node: OasExtension): void; visitValidationProblem(node: OasValidationProblem): void; } /** * Extends the base node visitor to support visiting an OAS 2.0 document. */ export interface IOas20NodeVisitor extends IOasNodeVisitor { visitDocument(node: Oas20Document): void; visitInfo(node: Oas20Info): void; visitContact(node: Oas20Contact): void; visitLicense(node: Oas20License): void; visitPaths(node: Oas20Paths): void; visitPathItem(node: Oas20PathItem): void; visitOperation(node: Oas20Operation): void; visitParameter(node: Oas20Parameter): void; visitParameterDefinition(node: Oas20ParameterDefinition): void; visitExternalDocumentation(node: Oas20ExternalDocumentation): void; visitSecurityRequirement(node: Oas20SecurityRequirement): void; visitResponses(node: Oas20Responses): void; visitResponse(node: Oas20Response): void; visitResponseDefinition(node: Oas20ResponseDefinition): void; visitSchema(node: Oas20Schema): void; visitHeaders(node: Oas20Headers): void; visitHeader(node: Oas20Header): void; visitExample(node: Oas20Example): void; visitItems(node: Oas20Items): void; visitTag(node: Oas20Tag): void; visitSecurityDefinitions(node: Oas20SecurityDefinitions): void; visitSecurityScheme(node: Oas20SecurityScheme): void; visitScopes(node: Oas20Scopes): void; visitXML(node: Oas20XML): void; visitSchemaDefinition(node: Oas20SchemaDefinition): void; visitPropertySchema(node: Oas20PropertySchema): void; visitAdditionalPropertiesSchema(node: Oas20AdditionalPropertiesSchema): void; visitAllOfSchema(node: Oas20AllOfSchema): void; visitItemsSchema(node: Oas20ItemsSchema): void; visitDefinitions(node: Oas20Definitions): void; visitParametersDefinitions(node: Oas20ParametersDefinitions): void; visitResponsesDefinitions(node: Oas20ResponsesDefinitions): void; } export interface IOas30NodeVisitor extends IOasNodeVisitor { visitDocument(node: Oas30Document): void; visitInfo(node: Oas30Info): void; visitContact(node: Oas30Contact): void; visitLicense(node: Oas30License): void; visitPaths(node: Oas30Paths): void; visitPathItem(node: Oas30PathItem): void; visitOperation(node: Oas30Operation): void; visitParameter(node: Oas30Parameter): void; visitParameterDefinition(node: Oas30ParameterDefinition): void; visitResponses(node: Oas30Responses): void; visitResponse(node: Oas30Response): void; visitMediaType(node: Oas30MediaType): void; visitEncoding(node: Oas30Encoding): void; visitExample(node: Oas30Example): void; visitLink(node: Oas30Link): void; visitLinkParameterExpression(node: Oas30LinkParameterExpression): void; visitLinkRequestBodyExpression(node: Oas30LinkRequestBodyExpression): void; visitLinkServer(node: Oas30LinkServer): void; visitResponseDefinition(node: Oas30ResponseDefinition): void; visitSchema(node: Oas30Schema): void; visitXML(node: Oas30XML): void; visitHeader(node: Oas30Header): void; visitRequestBody(node: Oas30RequestBody): void; visitCallback(node: Oas30Callback): void; visitCallbackPathItem(node: Oas30CallbackPathItem): void; visitServer(node: Oas30Server): void; visitServerVariable(node: Oas30ServerVariable): void; visitSecurityRequirement(node: Oas30SecurityRequirement): void; visitTag(node: Oas30Tag): void; visitExternalDocumentation(node: Oas30ExternalDocumentation): void; visitAllOfSchema(node: Oas30AllOfSchema): void; visitAnyOfSchema(node: Oas30AnyOfSchema): void; visitOneOfSchema(node: Oas30OneOfSchema): void; visitNotSchema(node: Oas30NotSchema): void; visitPropertySchema(node: Oas30PropertySchema): void; visitItemsSchema(node: Oas30ItemsSchema): void; visitAdditionalPropertiesSchema(node: Oas30AdditionalPropertiesSchema): void; visitComponents(node: Oas30Components): void; visitSchemaDefinition(node: Oas30SchemaDefinition): void; visitExampleDefinition(node: Oas30ExampleDefinition): void; visitRequestBodyDefinition(node: Oas30RequestBodyDefinition): void; visitHeaderDefinition(node: Oas30HeaderDefinition): void; visitOAuthFlows(node: Oas30OAuthFlows): void; visitImplicitOAuthFlow(node: Oas30ImplicitOAuthFlow): void; visitPasswordOAuthFlow(node: Oas30PasswordOAuthFlow): void; visitClientCredentialsOAuthFlow(node: Oas30ClientCredentialsOAuthFlow): void; visitAuthorizationCodeOAuthFlow(node: Oas30AuthorizationCodeOAuthFlow): void; visitSecurityScheme(node: Oas30SecurityScheme): void; visitLinkDefinition(node: Oas30LinkDefinition): void; visitCallbackDefinition(node: Oas30CallbackDefinition): void; visitDiscriminator(node: Oas30Discriminator): void; }
the_stack
import { checkIsShallowEmpty, clean, deepClone, deepFreeze, firstKey, getValueByPath, isGetter, isIterable, isObject, isPlainObject, isSimpleObject, pathsOfObject, replaceWithNull, shallowMapObject, sortByAsc, sortByDesc } from '@angular-ru/cdk/object'; import { Any, Nullable, PlainObject } from '@angular-ru/cdk/typings'; describe('[TEST]: Object', () => { interface A { a: number; } interface Origin { a: number; b: { c: number; }; } describe('sorting', () => { const objectList: A[] = [{ a: 1 }, { a: 3 }, { a: 2 }, { a: -1 }, { a: 0 }]; it('sort by asc', () => { expect(objectList.slice().sort((a, b) => sortByAsc('a', a, b))).toEqual([ { a: -1 }, { a: 0 }, { a: 1 }, { a: 2 }, { a: 3 } ]); }); it('sort by desc', () => { expect(objectList.slice().sort((a, b) => sortByDesc('a', a, b))).toEqual([ { a: 3 }, { a: 2 }, { a: 1 }, { a: 0 }, { a: -1 } ]); }); }); it('should correct return first key', () => { expect(firstKey({ a: 1 })).toBe('a'); expect(firstKey({ b: 2, a: 1, c: 3 })).toBe('b'); expect(firstKey(null)).toBeNull(); }); describe('detect object', () => { class A {} it('is object', () => { expect(isObject(NaN)).toBe(false); expect(isObject(null)).toBe(false); expect(isObject(undefined)).toBe(false); expect(isObject(1)).toBe(false); expect(isObject(Infinity)).toBe(false); expect(isObject('')).toBe(false); // non primitive expect(isObject([])).toBe(true); expect(isObject({})).toBe(true); expect(isObject(new A())).toBe(true); expect(isObject(new Date())).toBe(true); expect(isObject(new Map())).toBe(true); expect( isObject(() => { // ... }) ).toBe(true); // eslint-disable-next-line no-new-wrappers expect(isObject(new Number(6))).toBe(true); expect(isObject(Math)).toBe(true); expect(isObject(Object.create(null))).toBe(true); expect(isObject(document.createElement('div'))).toBe(true); expect( isObject( // @ts-ignore new (function Foo() { // ... })() ) ).toBe(true); expect(isObject(window)).toBe(true); }); it('is plain object', () => { expect(isPlainObject(NaN)).toBe(false); expect(isPlainObject(null)).toBe(false); expect(isPlainObject(undefined)).toBe(false); expect(isPlainObject(1)).toBe(false); expect(isPlainObject(Infinity)).toBe(false); expect(isPlainObject('')).toBe(false); // plain object expect(isPlainObject({})).toBe(true); expect(isPlainObject(Object.create(null))).toBe(true); // complex object (not plain literal) expect(isPlainObject([])).toBe(false); expect(isPlainObject(new A())).toBe(false); expect(isPlainObject(new Date())).toBe(false); expect(isPlainObject(new Map())).toBe(false); expect( isPlainObject(() => { // ... }) ).toBe(false); // eslint-disable-next-line no-new-wrappers expect(isPlainObject(new Number(6))).toBe(false); expect(isPlainObject(Math)).toBe(false); expect(isPlainObject(document.createElement('div'))).toBe(false); expect( isPlainObject( // @ts-ignore new (function Foo() { // ... })() ) ).toBe(false); }); it('is simple object', () => { expect(isSimpleObject(NaN)).toBe(false); expect(isSimpleObject(null)).toBe(false); expect(isSimpleObject(undefined)).toBe(false); expect(isSimpleObject(1)).toBe(false); expect(isSimpleObject(Infinity)).toBe(false); expect(isSimpleObject('')).toBe(false); // instance object, literal object expect(isSimpleObject(new A())).toBe(true); expect(isSimpleObject(Object.create(null))).toBe(true); expect(isSimpleObject({})).toBe(true); expect( isSimpleObject( // @ts-ignore new (function Foo() { // ... })() ) ).toBe(true); // complex object (Array, DOM, Set, Map, other structure) expect(isSimpleObject([])).toBe(false); expect(isSimpleObject(new Date())).toBe(false); expect(isSimpleObject(new Map())).toBe(false); expect( isSimpleObject(() => { // ... }) ).toBe(false); // eslint-disable-next-line no-new-wrappers expect(isSimpleObject(new Number(6))).toBe(false); expect(isSimpleObject(Math)).toBe(false); expect(isSimpleObject(document.createElement('div'))).toBe(false); }); }); describe('getter', () => { it('is getter', () => { class A { public get a(): number { return 1; } public b: string = '2'; } expect(isGetter(new A(), 'a')).toBe(true); expect(isGetter(new A(), 'b')).toBe(false); expect( isGetter( { get a() { return 2; } }, 'a' ) ).toBe(true); expect( isGetter( { _a: null, set a(value: Any) { this._a = value; } }, 'a' ) ).toBe(false); expect(isGetter({ a: 2 }, 'a')).toBe(false); }); it('inheritance getter', () => { class Base { public get base(): string { return 'base'; } } class A extends Base {} expect(new A().base).toBe('base'); expect(isGetter(new A(), 'base')).toBe(true); class Z { public get base() { return 'base'; } } class R extends Z {} const r = new R(); Object.defineProperty(r, 'base', { value: 'joke' }); expect(r.base).toBe('joke'); expect(isGetter(r, 'base')).toBe(false); }); it('correct check invalid', () => { expect(isGetter(null, 'a')).toBe(false); expect(isGetter({}, 'a')).toBe(false); expect(isGetter(Infinity, 'a')).toBe(false); expect(isGetter(undefined, 'a')).toBe(false); expect(isGetter(NaN, 'a')).toBe(false); expect(isGetter(5, 'a')).toBe(false); // eslint-disable-next-line no-new-wrappers expect(isGetter(new Number(5), 'a')).toBe(false); expect(isGetter(String(5), 'a')).toBe(false); }); }); describe('clone', () => { it('deep clone', () => { const origin: Origin = { a: 1, b: { c: 2 } }; const copy: Origin = deepClone(origin) as Origin; expect(Object.is(origin, copy)).toBe(false); copy.b.c = 4; expect(origin.b.c).toBe(2); origin.b.c = 3; expect(origin.b.c).toBe(3); expect(copy.b.c).toBe(4); }); it('not equals', () => { const c = { d: 3 }; const a = { a: 1, b: 2, c }; expect(deepClone(a).c !== c).toBeTruthy(); expect(deepClone(a).c).toEqual({ d: 3 }); }); it('copy null/NaN/undefined/0/Infinity', () => { expect(deepClone(0)).toBe(0); expect(deepClone(NaN)).toBeNull(); expect(deepClone(Infinity)).toBeNull(); expect(deepClone(null)).toBeNull(); expect(deepClone(undefined)).toBeUndefined(); }); it('should be correct clone object', () => { class Mock { public a: string = null!; public b: PlainObject[] = [{ c: 1, d: 2 }]; public e: number = NaN; public f: number = Infinity; public g: Date | string = new Date(2018, 10, 28); } expect(deepClone(new Mock())).toEqual({ a: null, b: [{ c: 1, d: 2 }], e: null, f: null, g: expect.any(String) }); }); }); describe('freeze', () => { it('deep freeze', () => { const origin: Origin = deepFreeze({ a: 1, b: { c: 2 } }); let message: Nullable<string> = null; try { origin.b.c = 5; } catch (e: unknown) { message = (e as Error).message; } expect(message).toEqual(`Cannot assign to read only property 'c' of object '[object Object]'`); }); }); it('should be correct object', (): void => { const wrongElem: PlainObject = { a: '', b: [ { c: NaN, d: 1 }, { c: ' ', d: undefined }, { c: 0, d: 0 } ], e: Infinity }; expect(replaceWithNull(wrongElem)).toEqual({ a: null, b: [ { c: null, d: 1 }, { c: null, d: null }, { c: 0, d: 0 } ], e: null }); }); it('should be clear empty values', (): void => { const A: PlainObject = clean({ a: 1, b: undefined, c: '', d: null, e: NaN, f: [ { a: 2, b: undefined, c: '', d: Infinity }, { a: 3, b: undefined, c: '', d: Infinity } ], g: { a: 4, b: undefined, c: '', d: Infinity }, h: Infinity }); const B: PlainObject = { a: 1, f: [{ a: 2 }, { a: 3 }], g: { a: 4 } }; expect(A).toEqual(B); }); it('getValueByPath', () => { const obj: PlainObject = { a: 1, f: [{ a: 2 }, { a: 3 }], g: { a: 4 } }; expect(getValueByPath(null, '')).toBeNull(); expect(getValueByPath({ a: 2 }, '')).toEqual({ a: 2 }); expect(getValueByPath(null, 'ge')).toBeUndefined(); expect(getValueByPath(undefined, 'ge')).toBeUndefined(); expect(getValueByPath(obj, 'ge')).toBeUndefined(); expect(getValueByPath(obj, 'g.a')).toBe(4); expect(getValueByPath(obj, 'f.0')).toEqual({ a: 2 }); expect(getValueByPath(obj, 'f.0.a')).toBe(2); expect(getValueByPath(obj, 'abc')).toBeUndefined(); expect(getValueByPath(obj, 'f.0.a.Z', [])).toEqual([]); }); it('checkIsShallowEmpty', () => { expect(checkIsShallowEmpty({ a: 0 })).toBe(false); expect(checkIsShallowEmpty({ a: { b: '' } })).toBe(false); expect(checkIsShallowEmpty({ a: 'hello' })).toBe(false); // shallow empty object expect(checkIsShallowEmpty({})).toBe(true); expect(checkIsShallowEmpty({ a: null })).toBe(true); expect(checkIsShallowEmpty({ a: '', b: undefined, c: NaN, d: ' ' })).toBe(true); }); it('should correct recognize iterable values', () => { expect(isIterable([1, 2])).toBe(true); expect(isIterable('Some String')).toBe(true); expect(isIterable(new Set([1, 2]))).toBe(true); expect( isIterable( new Map([ ['a', 1], ['b', 2] ]) ) ).toBe(true); expect( isIterable( new Map([ ['a', 1], ['b', 2] ]).entries() ) ).toBe(true); expect(isIterable({ a: 1, b: 2 })).toBe(false); expect(isIterable(null)).toBe(false); expect(isIterable(undefined)).toBe(false); expect(isIterable(0)).toBe(false); expect(isIterable(true)).toBe(false); expect( isIterable(() => { // ... }) ).toBe(false); }); it('should correct return paths of object', () => { const row: PlainObject = { a: 1, b: { c: 2, d: { e: 3 }, g: [1, 2, 3] } }; expect(pathsOfObject(row)).toEqual(['a', 'b.c', 'b.d.e', 'b.g']); class Person { constructor(public name: string, public city: string) {} } // @ts-ignore Person.prototype.age = 25; const willem: Person = new Person('Willem', 'Groningen'); expect(pathsOfObject(willem)).toEqual(['name', 'city']); }); it('should correct map objects by keys', () => { const oneTypeObject = { a: 1, b: 3, c: 5 }; expect(shallowMapObject(oneTypeObject, (a: number): number => a * 2)).toEqual({ a: 2, b: 6, c: 10 }); const baseTypeObject = { a: '1 asd', b: 3, c: true }; expect( shallowMapObject(baseTypeObject, (a: number | string | boolean): string => `${a} - interpolated`) ).toEqual({ a: '1 asd - interpolated', b: '3 - interpolated', c: `true - interpolated` }); const complexObject = { a: 1, b: 'two', c: true, d: undefined, e: null, f: { field: 'value' }, g: [1, 2, 3] }; expect(shallowMapObject(complexObject, (a): string => JSON.stringify(a))).toEqual({ a: '1', b: '"two"', c: 'true', d: undefined, e: 'null', f: '{"field":"value"}', g: '[1,2,3]' }); }); });
the_stack
import { expect } from 'chai'; import { BoxSizer, BoxEngine } from '@phosphor/widgets'; function createSizers(n: number): BoxSizer[] { let sizers: BoxSizer[] = []; for (let i = 0; i < n; ++i) { sizers.push(new BoxSizer()); } return sizers; } describe('@phosphor/widgets', () => { describe('BoxSizer', () => { describe('#constructor()', () => { it('should accept no arguments', () => { let sizer = new BoxSizer(); expect(sizer).to.be.an.instanceof(BoxSizer); }); }); describe('#sizeHint', () => { it('should default to `0`', () => { let sizer = new BoxSizer(); expect(sizer.sizeHint).to.equal(0); }); it('should be writable', () => { let sizer = new BoxSizer(); sizer.sizeHint = 42; expect(sizer.sizeHint).to.equal(42); }); }); describe('#minSize', () => { it('should default to `0`', () => { let sizer = new BoxSizer(); expect(sizer.minSize).to.equal(0); }); it('should be writable', () => { let sizer = new BoxSizer(); sizer.minSize = 42; expect(sizer.minSize).to.equal(42); }); }); describe('#maxSize', () => { it('should default to `Infinity`', () => { let sizer = new BoxSizer(); expect(sizer.maxSize).to.equal(Infinity); }); it('should be writable', () => { let sizer = new BoxSizer(); sizer.maxSize = 42; expect(sizer.maxSize).to.equal(42); }); }); describe('#stretch', () => { it('should default to `1`', () => { let sizer = new BoxSizer(); expect(sizer.stretch).to.equal(1); }); it('should be writable', () => { let sizer = new BoxSizer(); sizer.stretch = 42; expect(sizer.stretch).to.equal(42); }); }); describe('#size', () => { it('should be the computed output', () => { let sizer = new BoxSizer(); expect(typeof sizer.size).to.equal('number'); }); it('should be writable', () => { let sizer = new BoxSizer(); sizer.size = 42; expect(sizer.size).to.equal(42); }); }); }); describe('BoxEngine', () => { describe('calc()', () => { it('should handle an empty sizers array', () => { expect(() => BoxEngine.calc([], 100)).to.not.throw(Error); }); it('should obey the min sizes', () => { let sizers = createSizers(4); sizers[0].minSize = 10; sizers[1].minSize = 20; sizers[2].minSize = 30; sizers[3].minSize = 40; BoxEngine.calc(sizers, 0); expect(sizers[0].size).to.equal(10); expect(sizers[1].size).to.equal(20); expect(sizers[2].size).to.equal(30); expect(sizers[3].size).to.equal(40); }); it('should obey the max sizes', () => { let sizers = createSizers(4); sizers[0].maxSize = 10; sizers[1].maxSize = 20; sizers[2].maxSize = 30; sizers[3].maxSize = 40; BoxEngine.calc(sizers, 500); expect(sizers[0].size).to.equal(10); expect(sizers[1].size).to.equal(20); expect(sizers[2].size).to.equal(30); expect(sizers[3].size).to.equal(40); }); it('should handle negative layout space', () => { let sizers = createSizers(4); sizers[0].minSize = 10; sizers[1].minSize = 20; sizers[2].minSize = 30; BoxEngine.calc(sizers, -500); expect(sizers[0].size).to.equal(10); expect(sizers[1].size).to.equal(20); expect(sizers[2].size).to.equal(30); expect(sizers[3].size).to.equal(0); }); it('should handle infinite layout space', () => { let sizers = createSizers(4); sizers[0].maxSize = 10; sizers[1].maxSize = 20; sizers[2].maxSize = 30; BoxEngine.calc(sizers, Infinity); expect(sizers[0].size).to.equal(10); expect(sizers[1].size).to.equal(20); expect(sizers[2].size).to.equal(30); expect(sizers[3].size).to.equal(Infinity); }); it('should maintain the size hints if possible', () => { let sizers = createSizers(4); sizers[0].sizeHint = 40; sizers[1].sizeHint = 50; sizers[2].sizeHint = 60; sizers[3].sizeHint = 70; BoxEngine.calc(sizers, 220); expect(sizers[0].size).to.equal(40); expect(sizers[1].size).to.equal(50); expect(sizers[2].size).to.equal(60); expect(sizers[3].size).to.equal(70); }); it('should fairly distribute negative space', () => { let sizers = createSizers(4); sizers[0].sizeHint = 40; sizers[1].sizeHint = 50; sizers[2].sizeHint = 60; sizers[3].sizeHint = 70; BoxEngine.calc(sizers, 200); expect(sizers[0].size).to.equal(35); expect(sizers[1].size).to.equal(45); expect(sizers[2].size).to.equal(55); expect(sizers[3].size).to.equal(65); }); it('should fairly distribute positive space', () => { let sizers = createSizers(4); sizers[0].sizeHint = 40; sizers[1].sizeHint = 50; sizers[2].sizeHint = 60; sizers[3].sizeHint = 70; BoxEngine.calc(sizers, 240); expect(sizers[0].size).to.equal(45); expect(sizers[1].size).to.equal(55); expect(sizers[2].size).to.equal(65); expect(sizers[3].size).to.equal(75); }); it('should be callable multiple times for the same sizers', () => { let sizers = createSizers(4); sizers[0].sizeHint = 40; sizers[1].sizeHint = 50; sizers[2].sizeHint = 60; sizers[3].sizeHint = 70; BoxEngine.calc(sizers, 240); expect(sizers[0].size).to.equal(45); expect(sizers[1].size).to.equal(55); expect(sizers[2].size).to.equal(65); expect(sizers[3].size).to.equal(75); BoxEngine.calc(sizers, 280); expect(sizers[0].size).to.equal(55); expect(sizers[1].size).to.equal(65); expect(sizers[2].size).to.equal(75); expect(sizers[3].size).to.equal(85); BoxEngine.calc(sizers, 200); expect(sizers[0].size).to.equal(35); expect(sizers[1].size).to.equal(45); expect(sizers[2].size).to.equal(55); expect(sizers[3].size).to.equal(65); }); it('should distribute negative space according to stretch factors', () => { let sizers = createSizers(2); sizers[0].sizeHint = 60; sizers[1].sizeHint = 60; sizers[0].stretch = 2; sizers[1].stretch = 4; BoxEngine.calc(sizers, 120); expect(sizers[0].size).to.equal(60); expect(sizers[1].size).to.equal(60); BoxEngine.calc(sizers, 60); expect(sizers[0].size).to.equal(40); expect(sizers[1].size).to.equal(20); }); it('should distribute positive space according to stretch factors', () => { let sizers = createSizers(2); sizers[0].sizeHint = 60; sizers[1].sizeHint = 60; sizers[0].stretch = 2; sizers[1].stretch = 4; BoxEngine.calc(sizers, 120); expect(sizers[0].size).to.equal(60); expect(sizers[1].size).to.equal(60); BoxEngine.calc(sizers, 240); expect(sizers[0].size).to.equal(100); expect(sizers[1].size).to.equal(140); }); it('should not shrink non-stretchable sizers', () => { let sizers = createSizers(4); sizers[0].sizeHint = 20; sizers[1].sizeHint = 40; sizers[2].sizeHint = 60; sizers[3].sizeHint = 80; sizers[0].stretch = 0; sizers[2].stretch = 0; BoxEngine.calc(sizers, 160); expect(sizers[0].size).to.equal(20); expect(sizers[1].size).to.equal(20); expect(sizers[2].size).to.equal(60); expect(sizers[3].size).to.equal(60); }); it('should not expand non-stretchable sizers', () => { let sizers = createSizers(4); sizers[0].sizeHint = 20; sizers[1].sizeHint = 40; sizers[2].sizeHint = 60; sizers[3].sizeHint = 80; sizers[0].stretch = 0; sizers[2].stretch = 0; BoxEngine.calc(sizers, 260); expect(sizers[0].size).to.equal(20); expect(sizers[1].size).to.equal(70); expect(sizers[2].size).to.equal(60); expect(sizers[3].size).to.equal(110); }); it('should shrink non-stretchable sizers if required', () => { let sizers = createSizers(4); sizers[0].sizeHint = 20; sizers[1].sizeHint = 40; sizers[2].sizeHint = 60; sizers[3].sizeHint = 80; sizers[0].stretch = 0; sizers[2].stretch = 0; sizers[1].minSize = 20; sizers[2].minSize = 55; sizers[3].minSize = 60; BoxEngine.calc(sizers, 140); expect(sizers[0].size).to.equal(5); expect(sizers[1].size).to.equal(20); expect(sizers[2].size).to.equal(55); expect(sizers[3].size).to.equal(60); }); it('should expand non-stretchable sizers if required', () => { let sizers = createSizers(4); sizers[0].sizeHint = 20; sizers[1].sizeHint = 40; sizers[2].sizeHint = 60; sizers[3].sizeHint = 80; sizers[0].stretch = 0; sizers[2].stretch = 0; sizers[1].maxSize = 60; sizers[2].maxSize = 70; sizers[3].maxSize = 100; BoxEngine.calc(sizers, 280); expect(sizers[0].size).to.equal(50); expect(sizers[1].size).to.equal(60); expect(sizers[2].size).to.equal(70); expect(sizers[3].size).to.equal(100); }); }); describe('adjust()', () => { it('should adjust a sizer by a positive delta', () => { let sizers = createSizers(5); sizers[0].sizeHint = 50; sizers[1].sizeHint = 50; sizers[2].sizeHint = 50; sizers[3].sizeHint = 50; sizers[4].sizeHint = 50; sizers[2].maxSize = 60; sizers[3].minSize = 40; BoxEngine.calc(sizers, 250); expect(sizers[0].size).to.equal(50); expect(sizers[1].size).to.equal(50); expect(sizers[2].size).to.equal(50); expect(sizers[3].size).to.equal(50); expect(sizers[3].size).to.equal(50); BoxEngine.adjust(sizers, 2, 30); expect(sizers[0].sizeHint).to.equal(50); expect(sizers[1].sizeHint).to.equal(70); expect(sizers[2].sizeHint).to.equal(60); expect(sizers[3].sizeHint).to.equal(40); expect(sizers[4].sizeHint).to.equal(30); }); it('should adjust a sizer by a negative delta', () => { let sizers = createSizers(5); sizers[0].sizeHint = 50; sizers[1].sizeHint = 50; sizers[2].sizeHint = 50; sizers[3].sizeHint = 50; sizers[4].sizeHint = 50; sizers[1].minSize = 40; sizers[2].minSize = 40; BoxEngine.calc(sizers, 250); expect(sizers[0].size).to.equal(50); expect(sizers[1].size).to.equal(50); expect(sizers[2].size).to.equal(50); expect(sizers[3].size).to.equal(50); expect(sizers[3].size).to.equal(50); BoxEngine.adjust(sizers, 2, -30); expect(sizers[0].sizeHint).to.equal(40); expect(sizers[1].sizeHint).to.equal(40); expect(sizers[2].sizeHint).to.equal(40); expect(sizers[3].sizeHint).to.equal(80); expect(sizers[4].sizeHint).to.equal(50); }); }); }); });
the_stack
import { server } from "../socket/socketClient"; import * as types from "../common/types"; import React = require("react"); import * as csx from './base/csx'; import ReactDOM = require("react-dom"); import { BaseComponent } from "./ui"; import * as ui from "./ui"; import * as utils from "../common/utils"; import * as styles from "./styles/styles"; import * as state from "./state/state"; import { connect } from "react-redux"; import { StoreState } from "./state/state"; import { Icon } from "./components/icon"; import * as commands from "./commands/commands"; let { DraggableCore } = ui; import { getDirectory, getFileName } from "../common/utils"; import { Robocop } from "./components/robocop"; import { inputDialog } from "./dialogs/inputDialog"; import * as Mousetrap from "mousetrap"; import * as clipboard from "./components/clipboard"; import * as pure from "../common/pure"; import { tabState } from "./tabs/v2/appTabsContainer"; import * as settings from "./state/settings"; import * as typestyle from "typestyle"; import { throttle } from '../common/utils'; type TruthTable = utils.TruthTable; export interface Props { // from react-redux ... connected below filePaths?: types.FilePath[]; filePathsCompleted?: boolean; rootDir?: string; activeProjectFilePathTruthTable?: { [filePath: string]: boolean }; fileTreeShown?: boolean; } interface TreeDirItem { name: string; filePath: string; subDirs: TreeDirItem[]; files: TreeFileItem[]; } interface TreeFileItem { name: string; filePath: string; } type SelectedPaths = { [filePath: string]: { isDir: boolean } }; type SelectedPathsReadonly = { readonly [filePath: string]: { isDir: boolean } }; let dirSelected = { isDir: true }; let fileSelected = { isDir: false }; export interface State { /** Width of the tree view in pixels */ width?: number; treeRoot?: TreeDirItem; expansionState?: { [filePath: string]: boolean }; showHelp?: boolean; treeScrollHasFocus?: boolean; // TODO: support multiple selections at some point, hence a dict readonly selectedPaths?: SelectedPaths; } let resizerWidth = 5; let resizerStyle = { background: 'radial-gradient(#444,transparent)', width: resizerWidth + 'px', cursor: 'ew-resize', color: '#666', } let treeListStyle = { color: '#eee', fontSize: '.7rem', padding: '3px', } let treeScrollClassName = typestyle.style({ border: '1px solid grey', $nest: { '&:focus': { outline: 'none', border: '1px solid ' + styles.highlightColor } } }) let treeItemClassName = typestyle.style({ whiteSpace: 'nowrap', cursor: 'pointer', padding: '3px', userSelect: 'none', fontSize: '.9em', opacity: .8, $nest: { '&:focus': { outline: 'none', } } }) let treeItemSelectedStyle = { backgroundColor: styles.selectedBackgroundColor, } let treeItemInProjectStyle = { color: 'rgb(0, 255, 183)', opacity: 1, } let treeItemIsGeneratedStyle = { fontSize: '.6em' } let currentSelectedItemCopyStyle = { overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'pre', // Prevents wrapping cursor: 'pointer', marginLeft: '2px', fontSize: '.6rem', fontWeight: 'bold', color: '#CCC', textShadow: '0 0 3px rgba(255, 255, 255, 0.5)', } let helpRowStyle = { margin: '5px', lineHeight: '18px' } @connect((state: StoreState): Props => { return { filePaths: state.filePaths, filePathsCompleted: state.filePathsCompleted, rootDir: state.rootDir, activeProjectFilePathTruthTable: state.activeProjectFilePathTruthTable, fileTreeShown: state.fileTreeShown, }; }) export class FileTree extends BaseComponent<Props, State>{ /** can't be pure right now because of how we've written `selectedState` */ // shouldComponentUpdate = pure.shouldComponentUpdate; /** makes it easier to lookup directories */ dirLookup: { [dirPath: string]: TreeDirItem } = {}; loading: boolean = true; // guilty till proven innocent constructor(props: Props) { super(props); this.state = { width: 200, expansionState: {}, selectedPaths: {}, treeRoot: { name: 'loading', filePath: 'loading', subDirs: [], files: [] }, treeScrollHasFocus: false, }; this.setupTree(props); // debug // this.state.shown = true; // debug } componentWillReceiveProps(props: Props) { this.setupTree(props); } componentDidMount() { settings.fileTreeWidth.get().then(res => { let width = res || this.state.width; width = Math.min(window.innerWidth - 100, width); this.setState({ width }); }); let handleFocusRequestBasic = (shown: boolean) => { if (!shown) { state.expandFileTree({}); } let selectedFilePaths = Object.keys(this.state.selectedPaths); let pathToFocus = selectedFilePaths.length > 0 && this.ref(selectedFilePaths[selectedFilePaths.length - 1]) ? selectedFilePaths[selectedFilePaths.length - 1] : this.state.treeRoot.filePath; this.focusOnPath(pathToFocus); return false; } this.disposible.add(commands.esc.on(() => { if (this.state.showHelp) { this.setState({ showHelp: false }); setTimeout(() => this.focusOnPath(this.state.treeRoot.filePath), 150); } })); this.disposible.add(commands.treeViewToggle.on(() => { const shown = this.props.fileTreeShown; shown ? state.collapseFileTree({}) : state.expandFileTree({}); if (!shown) { handleFocusRequestBasic(true); } else { commands.esc.emit({}); } })); this.disposible.add(commands.treeViewRevealActiveFile.on(() => { if (!this.props.fileTreeShown) { state.expandFileTree({}); } let selectedTab = tabState.getSelectedTab(); if (selectedTab && selectedTab.url.startsWith('file://')) { let filePath = utils.getFilePathFromUrl(selectedTab.url); // expand the tree to make sure this file is visible let root = this.state.treeRoot.filePath; let remainderAfterRoot = filePath.substr(root.length + 1 /* for `/` */); let dirPortionsAfterRoot = utils.getDirectory(remainderAfterRoot).split('/'); let runningPortion = ''; let expanded: TruthTable = {}; expanded[root] = true; for (let portion of dirPortionsAfterRoot) { runningPortion = runningPortion + '/' + portion; let fullPath = root + runningPortion; expanded[fullPath] = true; } let expansionState = csx.extend(this.state.expansionState, expanded) as TruthTable; // also only select this node let selectedPaths: SelectedPaths = { [filePath]: fileSelected }; this.setState({ expansionState, selectedPaths }); this.focusOnPath(filePath); } else { handleFocusRequestBasic(true); } return false; })); this.disposible.add(commands.treeViewFocus.on(() => { handleFocusRequestBasic(this.props.fileTreeShown); })); /** * Utility: takes the selected state to the last item selected * If no item selected it selects the root */ let goDownToSmallestSelection = () => { let selectedFilePaths = Object.keys(this.state.selectedPaths); if (selectedFilePaths.length == 0) { let selectedPaths: SelectedPaths = { [this.state.treeRoot.filePath]: fileSelected }; this.setState({ selectedPaths }); } else if (selectedFilePaths.length > 1) { let path = selectedFilePaths[selectedFilePaths.length - 1]; let selectedPaths: SelectedPaths = { [path]: this.state.selectedPaths[path] }; this.setState({ selectedPaths }); } else { // already single selection :) } let selectedFilePath = Object.keys(this.state.selectedPaths)[0]; let selectedFilePathDetails = this.state.selectedPaths[selectedFilePath]; return { selectedFilePath, isDir: selectedFilePathDetails.isDir }; } /** * Utility : gets you the last item selected if any, otherwise the root dir * Does not modify state */ let getLastSelected = () => { let selectedFilePaths = Object.keys(this.state.selectedPaths); let last = selectedFilePaths[selectedFilePaths.length - 1]; if (!last) { return { filePath: this.state.treeRoot.filePath, isDir: true }; } let selectedFilePathDetails = this.state.selectedPaths[last]; return { filePath: last, isDir: selectedFilePathDetails.isDir }; } /** Utility : set an item as the only selected */ let setAsOnlySelectedNoFocus = (filePath: string, isDir: boolean) => { let selectedPaths: SelectedPaths = { [filePath]: { isDir } }; this.setState({ selectedPaths }); } let setAsOnlySelected = (filePath: string, isDir: boolean) => { setAsOnlySelectedNoFocus(filePath, isDir); this.focusOnPath(filePath); } /** * Used in handling keyboard for tree items */ let treeRoot = this.ref('__treeroot'); let handlers = new Mousetrap(treeRoot); /** * file action handlers */ handlers.bind(commands.treeAddFile.config.keyboardShortcut, () => { if (this.loading) return; let lastSelected = getLastSelected(); let dirPath = lastSelected.isDir ? lastSelected.filePath : utils.getDirectory(lastSelected.filePath); inputDialog.open({ header: "Enter a file name", onOk: (value: string) => { let filePath = value; server.addFile({ filePath }).then(res => { commands.doOpenOrFocusFile.emit({ filePath }); }); }, onEsc: () => { setTimeout(handleFocusRequestBasic, 150); }, filterValue: dirPath + '/', }); return false; }); handlers.bind(commands.treeAddFolder.config.keyboardShortcut, () => { if (this.loading) return; let lastSelected = getLastSelected(); let dirPath = lastSelected.isDir ? lastSelected.filePath : utils.getDirectory(lastSelected.filePath); inputDialog.open({ header: "Enter a folder name", onOk: (value: string) => { let filePath = value; server.addFolder({ filePath }).then(res => { ui.notifyInfoQuickDisappear('Folder created'); }); }, onEsc: () => { setTimeout(handleFocusRequestBasic, 150); }, filterValue: dirPath + '/', }); return false; }); handlers.bind(commands.treeDuplicateFile.config.keyboardShortcut, () => { if (this.loading) return; let selection = goDownToSmallestSelection(); if (!selection) { ui.notifyInfoNormalDisappear('Nothing selected'); return false; } let parentDir = utils.getDirectory(selection.selectedFilePath); if (selection.isDir) { inputDialog.open({ header: "Enter a new directory name", onOk: (value: string) => { let filePath = value; server.duplicateDir({ src: selection.selectedFilePath, dest: filePath }); setAsOnlySelectedNoFocus(filePath, true); this.state.expansionState[filePath] = true; this.setState({ expansionState: this.state.expansionState }); }, onEsc: () => { setTimeout(handleFocusRequestBasic, 150); }, filterValue: parentDir + '/', }); } else { inputDialog.open({ header: "Enter a new file name", onOk: (value: string) => { let filePath = value; server.duplicateFile({ src: selection.selectedFilePath, dest: filePath }); commands.doOpenOrFocusFile.emit({ filePath: filePath }); setAsOnlySelectedNoFocus(filePath, false); }, onEsc: () => { setTimeout(handleFocusRequestBasic, 150); }, filterValue: parentDir + '/', }); } return false; }); handlers.bind([commands.treeMoveFile.config.keyboardShortcut, commands.treeRenameFile.config.keyboardShortcut], () => { if (this.loading) return; let selection = goDownToSmallestSelection(); if (!selection) { ui.notifyInfoNormalDisappear('Nothing selected'); return false; } inputDialog.open({ header: "Enter a new location", onOk: (value: string) => { let filePath = value; server.movePath({ src: selection.selectedFilePath, dest: filePath }).then(res => { if (res.error) { ui.notifyWarningNormalDisappear("Failed to move: " + res.error); return; } if (selection.isDir) { setAsOnlySelectedNoFocus(filePath, true); this.state.expansionState[filePath] = true; this.setState({ expansionState: this.state.expansionState }); commands.closeFilesDirs.emit({ files: [], dirs: [selection.selectedFilePath] }); } else { commands.doOpenOrFocusFile.emit({ filePath: filePath }); setAsOnlySelectedNoFocus(filePath, false); commands.closeFilesDirs.emit({ files: [selection.selectedFilePath], dirs: [] }); } }); }, onEsc: () => { setTimeout(handleFocusRequestBasic, 150); }, filterValue: selection.selectedFilePath, }); return false; }); handlers.bind([commands.treeDeleteFile.config.keyboardShortcut, "backspace"], () => { if (this.loading) return; let selectedFilePaths = Object.keys(this.state.selectedPaths); let selectedFilePathsDetails = selectedFilePaths.map(fp => { return { filePath: fp, isDir: this.state.selectedPaths[fp].isDir }; }); if (selectedFilePaths.length == 0) { ui.notifyInfoNormalDisappear('Nothing selected'); return false; } if (selectedFilePaths.some(fp => fp == this.state.treeRoot.filePath)) { ui.notifyWarningNormalDisappear(`You cannot delete the root working directory`); return false; } inputDialog.open({ hideInput: true, header: `Delete ${selectedFilePaths.length > 1 ? selectedFilePaths.length + ' items' : utils.getFileName(selectedFilePaths[0])}?`, onOk: () => { let files = selectedFilePathsDetails.filter(x => !x.isDir).map(x => x.filePath); let dirs = selectedFilePathsDetails.filter(x => x.isDir).map(x => x.filePath); server.deleteFromDisk({ files, dirs }).then(res => { commands.closeFilesDirs.emit({ files, dirs }); // Leave selection in a useful state let lastSelectedDetails = selectedFilePathsDetails[selectedFilePathsDetails.length - 1].filePath; setAsOnlySelected(utils.getDirectory(lastSelectedDetails), true); }); }, onEsc: () => { setTimeout(handleFocusRequestBasic, 150); } }) return false; }); handlers.bind(commands.treeOpenInExplorerFinder.config.keyboardShortcut, () => { if (this.loading) return; let selection = goDownToSmallestSelection(); if (!selection) { ui.notifyInfoNormalDisappear('Nothing selected'); return false; } let dirFilePath = selection.selectedFilePath; if (!selection.isDir) { dirFilePath = utils.getDirectory(dirFilePath); } server.launchDirectory({ filePath: dirFilePath }); ui.notifySuccessNormalDisappear(`Command to open sent: ${dirFilePath}`); return false; }); handlers.bind(commands.treeOpenInCmdTerminal.config.keyboardShortcut, () => { if (this.loading) return; let selection = goDownToSmallestSelection(); if (!selection) { ui.notifyInfoNormalDisappear('Nothing selected'); return false; } let dirFilePath = selection.selectedFilePath; if (!selection.isDir) { dirFilePath = utils.getDirectory(dirFilePath); } server.launchTerminal({ filePath: dirFilePath }); ui.notifySuccessNormalDisappear(`Command to open cmd/terminal sent: ${dirFilePath}`); return false; }); /** * navigation handlers */ handlers.bind('enter', () => { if (this.loading) return; let { selectedFilePath, isDir } = goDownToSmallestSelection(); if (isDir) { this.state.expansionState[selectedFilePath] = !this.state.expansionState[selectedFilePath]; this.setState({ expansionState: this.state.expansionState }); } else { commands.doOpenOrFocusFile.emit({ filePath: selectedFilePath }); } return false; }); handlers.bind('up', () => { if (this.loading) return; let { selectedFilePath, isDir } = goDownToSmallestSelection(); // if root do nothing if (selectedFilePath == this.state.treeRoot.filePath) { return; } // find the parent dir && // find this in the parent dir let parentDirFilePath = utils.getDirectory(selectedFilePath); let parentDirTreeItem = this.dirLookup[parentDirFilePath]; let indexInParentDir = isDir ? parentDirTreeItem.subDirs.map(x => x.filePath).indexOf(selectedFilePath) : parentDirTreeItem.files.map(x => x.filePath).indexOf(selectedFilePath); /** Goes to the bottom file / folder */ let gotoBottomOfFolder = (closestDir: TreeDirItem) => { while (true) { if (!this.state.expansionState[closestDir.filePath]) { // if not expanded, we have a winner setAsOnlySelected(closestDir.filePath, true); break; } if (closestDir.files.length) { // Lucky previous expanded dir has files, select last! setAsOnlySelected(closestDir.files[closestDir.files.length - 1].filePath, false); break; } else if (closestDir.subDirs.length) { // does it have folders? ... check last folder next closestDir = closestDir.subDirs[closestDir.subDirs.length - 1]; continue; } else { // no folders no files ... we don't care if you are expanded or not setAsOnlySelected(closestDir.filePath, true); break; } } } // if first if (indexInParentDir == 0) { if (isDir) { setAsOnlySelected(parentDirFilePath, true); } else if (parentDirTreeItem.subDirs.length == 0) { setAsOnlySelected(parentDirFilePath, true); } else { gotoBottomOfFolder(parentDirTreeItem.subDirs[parentDirTreeItem.subDirs.length - 1]); } } // if this is not the first file in the folder select the previous file else if (!isDir) { setAsOnlySelected(parentDirTreeItem.files[indexInParentDir - 1].filePath, false); } // Else select the deepest item in the previous directory else { let closestDir = parentDirTreeItem.subDirs[indexInParentDir - 1]; gotoBottomOfFolder(closestDir); } return false; }); handlers.bind('down', () => { if (this.loading) return; let { selectedFilePath, isDir } = goDownToSmallestSelection(); /** Goes to next sibling on any (recursive) parent folder */ let gotoNextSiblingHighUp = (treeItem: TreeDirItem) => { // Special handling for root. Don't change selection :) if (treeItem.filePath == this.state.treeRoot.filePath) { return; } let parentDirFilePath = utils.getDirectory(treeItem.filePath); let parentTreeItem = this.dirLookup[parentDirFilePath]; let indexInParent = parentTreeItem.subDirs.map(x => x.filePath).indexOf(treeItem.filePath); if (indexInParent !== (parentTreeItem.subDirs.length - 1)) { // If not last we have a winner setAsOnlySelected(parentTreeItem.subDirs[indexInParent + 1].filePath, true); } else if (parentTreeItem.files.length) { // if parent has files move on to files setAsOnlySelected(parentTreeItem.files[0].filePath, false); } else { // Look at next parent gotoNextSiblingHighUp(parentTreeItem); } } if (isDir) { let dirTreeItem = this.dirLookup[selectedFilePath]; // If expanded and has children, select first relevant child if (this.state.expansionState[selectedFilePath] && (dirTreeItem.files.length || dirTreeItem.subDirs.length)) { dirTreeItem.subDirs[0] ? setAsOnlySelected(dirTreeItem.subDirs[0].filePath, true) : setAsOnlySelected(dirTreeItem.files[0].filePath, false) } else { // Else find the next sibling dir gotoNextSiblingHighUp(dirTreeItem); } } else { // for files let parentDirFilePath = utils.getDirectory(selectedFilePath); let parentTreeItem = this.dirLookup[parentDirFilePath]; let indexInParent = parentTreeItem.files.map(f => f.filePath).indexOf(selectedFilePath); // if not last select next sibling if (indexInParent !== (parentTreeItem.files.length - 1)) { setAsOnlySelected(parentTreeItem.files[indexInParent + 1].filePath, false); } // If is last go on to parent dir sibling algo else { gotoNextSiblingHighUp(parentTreeItem); } } return false; }); handlers.bind('left', () => { if (this.loading) return; let { selectedFilePath, isDir } = goDownToSmallestSelection(); if (isDir) { // if expanded then collapse if (this.state.expansionState[selectedFilePath]) { delete this.state.expansionState[selectedFilePath]; this.setState({ expansionState: this.state.expansionState }); return; } // if root ... leave if (this.state.treeRoot.filePath == selectedFilePath) { return; } } // Goto the parent directory setAsOnlySelected(utils.getDirectory(selectedFilePath), true); return false; }); handlers.bind('right', () => { if (this.loading) return; let { selectedFilePath, isDir } = goDownToSmallestSelection(); if (isDir) { // just expand this.state.expansionState[selectedFilePath] = true; this.setState({ expansionState: this.state.expansionState }); return false; } return false; }); handlers.bind('h', () => { this.setState({ showHelp: !this.state.showHelp }); }); handlers.bind('c', () => { let copyButtonRef = this.ref('copypath'); if (!copyButtonRef) { ui.notifyInfoNormalDisappear('Nothing selected'); return; } let copypathDom = ReactDOM.findDOMNode(copyButtonRef); (copypathDom as any).click(); }); /** * TS to js and JS to ts */ handlers.bind('t', () => { if (this.loading) return; let selection = goDownToSmallestSelection(); if (!selection) { ui.notifyInfoNormalDisappear('Nothing selected'); return false; } let filePath = selection.selectedFilePath; if (selection.isDir || (!filePath.endsWith('.js')) && !filePath.endsWith('.jsx')) { ui.notifyInfoNormalDisappear('Please select a `.js`/`jsx` file'); return false; } const newFilePath = filePath.replace(/\.js$/g, '.ts').replace(/\.jsx$/g, '.tsx'); server.movePath({ src: filePath, dest: newFilePath }).then(res => { commands.doOpenOrFocusFile.emit({ filePath: newFilePath }); setAsOnlySelectedNoFocus(newFilePath, false); commands.closeFilesDirs.emit({ files: [filePath], dirs: [] }); ui.notifySuccessNormalDisappear('File extension changed to be TypeScript'); }); return false; }); handlers.bind('j', () => { if (this.loading) return; let selection = goDownToSmallestSelection(); if (!selection) { ui.notifyInfoNormalDisappear('Nothing selected'); return false; } let filePath = selection.selectedFilePath; if (selection.isDir || (!filePath.endsWith('.ts')) && !filePath.endsWith('.tsx')) { ui.notifyInfoNormalDisappear('Please select a `.ts`/`tsx` file'); return false; } const newFilePath = filePath.replace(/\.ts$/g, '.js').replace(/\.tsx$/g, '.jsx'); server.movePath({ src: filePath, dest: newFilePath }).then(res => { commands.doOpenOrFocusFile.emit({ filePath: newFilePath }); setAsOnlySelectedNoFocus(newFilePath, false); commands.closeFilesDirs.emit({ files: [filePath], dirs: [] }); ui.notifySuccessNormalDisappear('File extension changed to be JavaScript'); }); return false; }); } refNames = { __treeroot: '__treeroot', __treeViewScroll: '__treeViewScroll', } render() { let singlePathSelected = Object.keys(this.state.selectedPaths).length == 1 && Object.keys(this.state.selectedPaths)[0]; let hideStyle = !this.props.fileTreeShown && { display: 'none' }; const haveFocus = this.state.treeScrollHasFocus; const helpOpacity = haveFocus ? 1 : 0; return ( <div ref={this.refNames.__treeroot} className="alm-tree-root" style={csx.extend(csx.flexRoot, csx.horizontal, { width: this.state.width, zIndex: 6 }, hideStyle)}> <div style={csx.extend(csx.flex, csx.vertical, treeListStyle, styles.someChildWillScroll, csx.newLayerParent)}> <div ref={this.refNames.__treeViewScroll} className={treeScrollClassName} style={csx.extend(csx.flex, csx.scroll)} tabIndex={0} onFocus={() => this.setState({ treeScrollHasFocus: true })} onBlur={() => this.setState({ treeScrollHasFocus: false })}> {this.renderDir(this.state.treeRoot)} </div> {this.props.filePathsCompleted || <Robocop />} { singlePathSelected && <div style={csx.extend(csx.content, csx.horizontal, csx.center, csx.centerJustified, { paddingTop: '5px', paddingBottom: '5px', width: this.state.width - 15 + 'px' })}> <clipboard.Clipboard ref='copypath' text={singlePathSelected} /> <span className="hint--top" data-hint="Click to copy the file path to clipboard" data-clipboard-text={singlePathSelected} style={currentSelectedItemCopyStyle as any} onClick={() => ui.notifyInfoQuickDisappear("Path copied to clipboard")}> {singlePathSelected} </span> </div> } <div style={csx.extend(csx.content, csx.centerCenter, { fontSize: '.7em', lineHeight: '2em', opacity: helpOpacity, transition: 'opacity .2s' })}> <span>Tap <span style={styles.Tip.keyboardShortCutStyle}>H</span> to toggle tree view help</span> </div> { this.state.showHelp && <div style={csx.extend(csx.newLayer, csx.centerCenter, csx.flex, { background: 'rgba(0,0,0,.7)' })} onClick={() => this.setState({ showHelp: false })}> <div style={csx.extend(csx.flexRoot, csx.vertical)}> <div style={helpRowStyle}>Tap <span style={styles.Tip.keyboardShortCutStyle}>ESC</span> to hide help</div> <div style={helpRowStyle}>Tap <span style={styles.Tip.keyboardShortCutStyle}>A</span> to add a file</div> <div style={helpRowStyle}>Tap <span style={styles.Tip.keyboardShortCutStyle}>Shift + A</span> to add a folder</div> <div style={helpRowStyle}>Tap <span style={styles.Tip.keyboardShortCutStyle}>D</span> to duplicate file / folder</div> <div style={helpRowStyle}>Tap <span style={styles.Tip.keyboardShortCutStyle}>M</span> to move file / folder</div> <div style={helpRowStyle}>Tap <span style={styles.Tip.keyboardShortCutStyle}>R</span> to rename file / folder</div> <div style={helpRowStyle}>Tap <span style={styles.Tip.keyboardShortCutStyle}>C</span> to copy path to clipboard</div> <div style={helpRowStyle}>Tap <span style={styles.Tip.keyboardShortCutStyle}>O</span> to open in explorer/finder</div> <div style={helpRowStyle}>Tap <span style={styles.Tip.keyboardShortCutStyle}>Shift + O</span> to open in cmd/terminal</div> <div style={helpRowStyle}>Tap <span style={styles.Tip.keyboardShortCutStyle}>T</span> to change .js to .ts</div> <div style={helpRowStyle}>Tap <span style={styles.Tip.keyboardShortCutStyle}>J</span> to change .ts to .js</div> <div style={helpRowStyle}>Tap <span style={styles.Tip.keyboardShortCutStyle}>arrow keys</span> to browse</div> <div style={helpRowStyle}>Tap <span style={styles.Tip.keyboardShortCutStyle}>del or backspace</span> to delete</div> <div style={helpRowStyle}>Tap <span style={styles.Tip.keyboardShortCutStyle}>enter</span> to open file / expand dir</div> <div style={helpRowStyle}>Tap <span style={styles.Tip.keyboardShortCutStyle}>{commands.modName} + \</span> to toggle tree view</div> <div style={helpRowStyle}>Tap <span style={styles.Tip.keyboardShortCutStyle}>Shift + {commands.modName} + \</span> to locate open file in view</div> <div style={helpRowStyle}>Tap <span style={styles.Tip.keyboardShortCutStyle}> {commands.modName} + 0</span> to focus on tree view</div> </div> </div> } </div> <DraggableCore onDrag={this.handleDrag} onStop={this.handleDragStop}> <div style={csx.extend(csx.flexRoot, csx.centerCenter, resizerStyle)}><Icon name="ellipsis-v" /></div> </DraggableCore> </div> ); } renderDir(item: TreeDirItem, depth = 0) { let expanded = this.state.expansionState[item.filePath]; let sub = expanded ? this.renderDirSub(item, depth) : []; let selected = !!this.state.selectedPaths[item.filePath]; return ( [<TreeNode.Dir key={item.filePath} ref={item.filePath} item={item} depth={depth} selected={selected} expanded={expanded} handleToggleDir={this.handleToggleDir} activeProjectFilePathTruthTable={this.props.activeProjectFilePathTruthTable} />].concat(sub) ); } renderDirSub(item: TreeDirItem, depth: number) { return item.subDirs.map(item => this.renderDir(item, depth + 1)) .concat(item.files.map(file => this.renderFile(file, depth + 1))); } renderFile(item: TreeFileItem, depth: number) { let selected = !!this.state.selectedPaths[item.filePath]; return ( <TreeNode.File ref={item.filePath} key={item.filePath} item={item} depth={depth} selected={selected} handleSelectFile={this.handleSelectFile} activeProjectFilePathTruthTable={this.props.activeProjectFilePathTruthTable} /> ); } handleDrag = (evt, ui: { node: Node deltaX: number, deltaY: number, lastX: number, lastY: number, }) => { this.setState({ width: ui.deltaX + ui.lastX + resizerWidth }); }; handleDragStop = () => { const width = this.state.width; settings.fileTreeWidth.set(width); } setupTree = throttle((props: Props) => { let filePaths = props.filePaths.filter(fp => fp.type == types.FilePathType.File).map(fp => fp.filePath); // initial boot up if (!filePaths.length) { return; } this.loading = false; let rootDirPath = props.rootDir; let rootDir: TreeDirItem = { name: utils.getFileName(rootDirPath), filePath: rootDirPath, subDirs: [], files: [] } // Always expand root this.state.expansionState[rootDirPath] = true; this.dirLookup = {}; this.dirLookup[rootDirPath] = rootDir; // if not found creates a new dir and set its parent // (recursively e.g. last was /foo and new is /foo/bar/baz/quz) let createDirAndMakeSureAllParentExits = (dir: string): TreeDirItem => { let dirTree: TreeDirItem = { name: getFileName(dir), filePath: dir, subDirs: [], files: [] } this.dirLookup[dir] = dirTree; let parentDir = getDirectory(dir); let parentDirTree = this.dirLookup[parentDir] if (!parentDirTree) { parentDirTree = createDirAndMakeSureAllParentExits(parentDir); } parentDirTree.subDirs.push(dirTree); return dirTree; } for (let filePath of filePaths) { let dir = getDirectory(filePath); let fileName = getFileName(filePath); let subItem = { name: fileName, filePath: filePath, }; // lookup existing dir let treeDir = this.dirLookup[dir]; if (!treeDir) { treeDir = createDirAndMakeSureAllParentExits(dir); } treeDir.files.push(subItem); } this.setState({ treeRoot: rootDir, expansionState: this.state.expansionState }); /** Also add the folders that may have no files */ let dirs = props.filePaths.filter(fp => fp.type == types.FilePathType.Dir).map(fp => fp.filePath); dirs.forEach(dirPath => { let treeDir = this.dirLookup[dirPath]; if (!treeDir) { createDirAndMakeSureAllParentExits(dirPath); } }); /** * keep the selected file paths in sync with all the items that are available */ // A map for easier lookup let filePathMap = utils.createMap(filePaths); let oldSelectedPaths = Object.keys(this.state.selectedPaths); let newSelectedPaths: SelectedPaths = {}; oldSelectedPaths.forEach(path => { let isDir = this.state.selectedPaths[path].isDir; if (!filePathMap[path]) { return; } newSelectedPaths[path] = { isDir }; }); // If there is no selected path select the root if (Object.keys(newSelectedPaths).length === 0) { newSelectedPaths[rootDirPath] = { isDir: true }; } this.setState({ selectedPaths: newSelectedPaths }); /** * Loading had focus. Transfer focus to root */ if (document.activeElement === this.refs['loading']) { setTimeout(() => { let selectedPaths: SelectedPaths = { [this.state.treeRoot.filePath]: dirSelected }; this.setState({ selectedPaths: selectedPaths }); this.focusOnPath(this.state.treeRoot.filePath); }, 500); } }, 1000); handleToggleDir = (evt: React.SyntheticEvent<any>, item: TreeDirItem) => { evt.stopPropagation(); let dirPath = item.filePath; let selectedPaths: SelectedPaths = { [dirPath]: dirSelected } this.state.expansionState[dirPath] = !this.state.expansionState[dirPath]; this.setState({ expansionState: this.state.expansionState, selectedPaths: selectedPaths }); } handleSelectFile = (evt: React.SyntheticEvent<any>, item: TreeFileItem) => { evt.stopPropagation(); let filePath = item.filePath; let selectedPaths: SelectedPaths = { [filePath]: fileSelected }; this.setState({ selectedPaths }); commands.doOpenOrActivateFileTab.emit({ filePath }); } focusOnPath(filePath: string) { if (!this.ref(filePath)) return; (this.refs['__treeViewScroll'] as any).focus(); this.ref(filePath).focus(); } componentWillUpdate(nextProps: Props, nextState: State) { if (nextState.width !== this.state.width || nextProps.fileTreeShown !== this.props.fileTreeShown) { tabState.debouncedResize(); } } } export namespace TreeNode { export class Dir extends React.PureComponent< { item: TreeDirItem, depth: number, selected: boolean, expanded: boolean, handleToggleDir: (event: React.SyntheticEvent<any>, item: TreeDirItem) => any; activeProjectFilePathTruthTable: { [filePath: string]: boolean }; }, {}>{ focus(filePath: string) { (this.refs['root'] as any).scrollIntoViewIfNeeded(false); } render() { let { item, depth, expanded } = this.props; let icon = expanded ? 'folder-open' : 'folder'; let selectedStyle = this.props.selected ? treeItemSelectedStyle : {}; let inProjectStyle = this.props.activeProjectFilePathTruthTable[item.filePath] ? treeItemInProjectStyle : {}; return ( <div className={treeItemClassName} style={csx.extend(selectedStyle, inProjectStyle)} key={item.filePath} ref='root' tabIndex={-1} onClick={(evt) => this.props.handleToggleDir(evt, item)}> <div style={{ marginLeft: depth * 10 }}> <Icon name={icon} /> {item.name}</div> </div> ); } } /** * File Name Based Icon */ class FileNameBasedIcon extends React.PureComponent<{ fileName: string }, {}> { render() { const fileName = this.props.fileName.toLowerCase(); const ext = utils.getExt(fileName); // Default let iconName = 'file-text-o'; if (ext == 'md') { iconName = 'book'; } else if (ext == 'json') { iconName = 'database'; } else if (ext == 'html' || ext == 'htm') { iconName = 'file-code-o'; } else if (ext == 'css' || ext == 'less' || ext == 'scss' || ext == 'sass') { iconName = 'css3'; } else if (ext.startsWith('git')) { iconName = 'github'; } else if (ext.endsWith('sh') || ext == 'bat' || ext == 'batch') { iconName = 'terminal'; } else if (ext.endsWith('coffee')) { iconName = 'coffee'; } else if (utils.isTs(fileName)) { iconName = 'rocket'; } else if (utils.isJs(fileName)) { iconName = 'plane'; } else if (utils.isImage(fileName)) { iconName = 'file-image-o'; } const icon = <Icon name={iconName} />; return <div> {icon} {this.props.fileName} </div>; } } /** Renders the file item */ export class File extends React.PureComponent<{ item: TreeFileItem; depth: number; selected: boolean; handleSelectFile: (event: React.SyntheticEvent<any>, item: TreeFileItem) => any; activeProjectFilePathTruthTable: { [filePath: string]: boolean }; }, {}>{ focus() { (this.refs['root'] as any).scrollIntoViewIfNeeded(false); } render() { const filePath = this.props.item.filePath; let selectedStyle = this.props.selected ? treeItemSelectedStyle : {}; let inProjectStyle = this.props.activeProjectFilePathTruthTable[filePath] ? treeItemInProjectStyle : {}; /** Determine if generated */ let isGenerated = false; if (filePath.endsWith('.js')) { let noExtName = utils.removeExt(filePath); if (filePath.endsWith('.js.map')) noExtName = utils.removeExt(noExtName); const tsName = noExtName + '.ts'; const tsxName = noExtName + '.tsx'; isGenerated = !!this.props.activeProjectFilePathTruthTable[tsName] || !!this.props.activeProjectFilePathTruthTable[tsxName]; } let isGeneratedStyle = isGenerated ? treeItemIsGeneratedStyle : {}; return ( <div className={treeItemClassName} style={csx.extend(selectedStyle, inProjectStyle, isGeneratedStyle)} ref='root' tabIndex={-1} onClick={(evt) => this.props.handleSelectFile(evt, this.props.item)}> <div style={{ marginLeft: this.props.depth * 10 }}><FileNameBasedIcon fileName={this.props.item.name} /></div> </div> ); } } }
the_stack
import { stripIndent } from 'common-tags'; import { promises as fs } from 'fs'; import * as path from 'path'; import { SinonStub, stub, spy, SinonSpy } from 'sinon'; import { expect } from 'chai'; import * as deviceConfig from '../src/device-config'; import * as fsUtils from '../src/lib/fs-utils'; import * as logger from '../src/logger'; import { Extlinux } from '../src/config/backends/extlinux'; import { ConfigTxt } from '../src/config/backends/config-txt'; import { Odmdata } from '../src/config/backends/odmdata'; import { ConfigFs } from '../src/config/backends/config-fs'; import { SplashImage } from '../src/config/backends/splash-image'; import * as constants from '../src/lib/constants'; import * as config from '../src/config'; import prepare = require('./lib/prepare'); import mock = require('mock-fs'); const extlinuxBackend = new Extlinux(); const configTxtBackend = new ConfigTxt(); const odmdataBackend = new Odmdata(); const configFsBackend = new ConfigFs(); const splashImageBackend = new SplashImage(); // TODO: Since the getBootConfig method is simple enough // these tests could probably be removed if each backend has its own // test and the src/config/utils module is properly tested. describe('Device Backend Config', () => { let logSpy: SinonSpy; before(async () => { logSpy = spy(logger, 'logSystemMessage'); await prepare(); }); after(() => { logSpy.restore(); }); afterEach(() => { logSpy.resetHistory(); }); it('correctly parses a config.txt file', async () => { // Will try to parse /test/data/mnt/boot/config.txt await expect( // @ts-ignore accessing private value deviceConfig.getBootConfig(configTxtBackend), ).to.eventually.deep.equal({ HOST_CONFIG_dtparam: '"i2c_arm=on","spi=on","audio=on"', HOST_CONFIG_enable_uart: '1', HOST_CONFIG_disable_splash: '1', HOST_CONFIG_avoid_warnings: '1', HOST_CONFIG_gpu_mem: '16', }); // Stub readFile to return a config that has initramfs and array variables stub(fs, 'readFile').resolves(stripIndent` initramfs initramf.gz 0x00800000 dtparam=i2c=on dtparam=audio=on dtoverlay=ads7846 dtoverlay=lirc-rpi,gpio_out_pin=17,gpio_in_pin=13 foobar=baz `); await expect( // @ts-ignore accessing private value deviceConfig.getBootConfig(configTxtBackend), ).to.eventually.deep.equal({ HOST_CONFIG_initramfs: 'initramf.gz 0x00800000', HOST_CONFIG_dtparam: '"i2c=on","audio=on"', HOST_CONFIG_dtoverlay: '"ads7846","lirc-rpi,gpio_out_pin=17,gpio_in_pin=13"', HOST_CONFIG_foobar: 'baz', }); // Restore stub (fs.readFile as SinonStub).restore(); }); it('does not allow setting forbidden keys', async () => { const current = { HOST_CONFIG_initramfs: 'initramf.gz 0x00800000', HOST_CONFIG_dtparam: '"i2c=on","audio=on"', HOST_CONFIG_dtoverlay: '"ads7846","lirc-rpi,gpio_out_pin=17,gpio_in_pin=13"', HOST_CONFIG_foobar: 'baz', }; // Create another target with only change being initramfs which is blacklisted const target = { ...current, HOST_CONFIG_initramfs: 'initramf.gz 0x00810000', }; expect(() => // @ts-ignore accessing private value deviceConfig.bootConfigChangeRequired(configTxtBackend, current, target), ).to.throw('Attempt to change blacklisted config value initramfs'); // Check if logs were called expect(logSpy).to.be.calledOnce; expect(logSpy).to.be.calledWith( 'Attempt to change blacklisted config value initramfs', { error: 'Attempt to change blacklisted config value initramfs', }, 'Apply boot config error', ); }); it('does not try to change config.txt if it should not change', async () => { const current = { HOST_CONFIG_initramfs: 'initramf.gz 0x00800000', HOST_CONFIG_dtparam: '"i2c=on","audio=on"', HOST_CONFIG_dtoverlay: '"ads7846","lirc-rpi,gpio_out_pin=17,gpio_in_pin=13"', HOST_CONFIG_foobar: 'baz', }; const target = { HOST_CONFIG_initramfs: 'initramf.gz 0x00800000', HOST_CONFIG_dtparam: '"i2c=on","audio=on"', HOST_CONFIG_dtoverlay: '"ads7846","lirc-rpi,gpio_out_pin=17,gpio_in_pin=13"', HOST_CONFIG_foobar: 'baz', }; expect( // @ts-ignore accessing private value deviceConfig.bootConfigChangeRequired(configTxtBackend, current, target), ).to.equal(false); expect(logSpy).to.not.be.called; }); it('writes the target config.txt', async () => { stub(fsUtils, 'writeFileAtomic').resolves(); stub(fsUtils, 'exec').resolves(); const current = { HOST_CONFIG_initramfs: 'initramf.gz 0x00800000', HOST_CONFIG_dtparam: '"i2c=on","audio=on"', HOST_CONFIG_dtoverlay: '"ads7846","lirc-rpi,gpio_out_pin=17,gpio_in_pin=13"', HOST_CONFIG_foobar: 'baz', }; const target = { HOST_CONFIG_initramfs: 'initramf.gz 0x00800000', HOST_CONFIG_dtparam: '"i2c=on","audio=off"', HOST_CONFIG_dtoverlay: '"lirc-rpi,gpio_out_pin=17,gpio_in_pin=13"', HOST_CONFIG_foobar: 'bat', HOST_CONFIG_foobaz: 'bar', }; expect( // @ts-ignore accessing private value deviceConfig.bootConfigChangeRequired(configTxtBackend, current, target), ).to.equal(true); // @ts-ignore accessing private value await deviceConfig.setBootConfig(configTxtBackend, target); expect(fsUtils.exec).to.be.calledOnce; expect(logSpy).to.be.calledTwice; expect(logSpy.getCall(1).args[2]).to.equal('Apply boot config success'); expect(fsUtils.writeFileAtomic).to.be.calledWith( './test/data/mnt/boot/config.txt', stripIndent` initramfs initramf.gz 0x00800000 dtparam=i2c=on dtparam=audio=off dtoverlay=lirc-rpi,gpio_out_pin=17,gpio_in_pin=13 foobar=bat foobaz=bar ` + '\n', // add newline because stripIndent trims last newline ); // Restore stubs (fsUtils.writeFileAtomic as SinonStub).restore(); (fsUtils.exec as SinonStub).restore(); }); it('ensures required fields are written to config.txt', async () => { stub(fsUtils, 'writeFileAtomic').resolves(); stub(fsUtils, 'exec').resolves(); stub(config, 'get').withArgs('deviceType').resolves('fincm3'); const current = { HOST_CONFIG_initramfs: 'initramf.gz 0x00800000', HOST_CONFIG_dtparam: '"i2c=on","audio=on"', HOST_CONFIG_dtoverlay: '"ads7846","lirc-rpi,gpio_out_pin=17,gpio_in_pin=13"', HOST_CONFIG_foobar: 'baz', }; const target = { HOST_CONFIG_initramfs: 'initramf.gz 0x00800000', HOST_CONFIG_dtparam: '"i2c=on","audio=off"', HOST_CONFIG_dtoverlay: '"lirc-rpi,gpio_out_pin=17,gpio_in_pin=13"', HOST_CONFIG_foobar: 'bat', HOST_CONFIG_foobaz: 'bar', }; expect( // @ts-ignore accessing private value deviceConfig.bootConfigChangeRequired(configTxtBackend, current, target), ).to.equal(true); // @ts-ignore accessing private value await deviceConfig.setBootConfig(configTxtBackend, target); expect(fsUtils.exec).to.be.calledOnce; expect(logSpy).to.be.calledTwice; expect(logSpy.getCall(1).args[2]).to.equal('Apply boot config success'); expect(fsUtils.writeFileAtomic).to.be.calledWith( './test/data/mnt/boot/config.txt', stripIndent` initramfs initramf.gz 0x00800000 dtparam=i2c=on dtparam=audio=off dtoverlay=lirc-rpi,gpio_out_pin=17,gpio_in_pin=13 dtoverlay=balena-fin foobar=bat foobaz=bar ` + '\n', // add newline because stripIndent trims last newline ); // Restore stubs (fsUtils.writeFileAtomic as SinonStub).restore(); (fsUtils.exec as SinonStub).restore(); (config.get as SinonStub).restore(); }); it('accepts RESIN_ and BALENA_ variables', async () => { return expect( deviceConfig.formatConfigKeys({ FOO: 'bar', // should be removed BAR: 'baz', // should be removed RESIN_SUPERVISOR_LOCAL_MODE: 'false', // any device BALENA_SUPERVISOR_OVERRIDE_LOCK: 'false', // any device BALENA_SUPERVISOR_POLL_INTERVAL: '100', // any device RESIN_HOST_CONFIG_dtparam: 'i2c_arm=on","spi=on","audio=on', // config.txt backend RESIN_HOST_CONFIGFS_ssdt: 'spidev1.0', // configfs backend BALENA_HOST_EXTLINUX_isolcpus: '1,2,3', // extlinux backend }), ).to.deep.equal({ SUPERVISOR_LOCAL_MODE: 'false', SUPERVISOR_OVERRIDE_LOCK: 'false', SUPERVISOR_POLL_INTERVAL: '100', HOST_CONFIG_dtparam: 'i2c_arm=on","spi=on","audio=on', HOST_CONFIGFS_ssdt: 'spidev1.0', HOST_EXTLINUX_isolcpus: '1,2,3', }); }); it('returns default configuration values', () => { const conf = deviceConfig.getDefaults(); return expect(conf).to.deep.equal({ HOST_FIREWALL_MODE: 'off', HOST_DISCOVERABILITY: 'true', SUPERVISOR_VPN_CONTROL: 'true', SUPERVISOR_POLL_INTERVAL: '900000', SUPERVISOR_LOCAL_MODE: 'false', SUPERVISOR_CONNECTIVITY_CHECK: 'true', SUPERVISOR_LOG_CONTROL: 'true', SUPERVISOR_DELTA: 'false', SUPERVISOR_DELTA_REQUEST_TIMEOUT: '59000', SUPERVISOR_DELTA_APPLY_TIMEOUT: '0', SUPERVISOR_DELTA_RETRY_COUNT: '30', SUPERVISOR_DELTA_RETRY_INTERVAL: '10000', SUPERVISOR_DELTA_VERSION: '2', SUPERVISOR_INSTANT_UPDATE_TRIGGER: 'true', SUPERVISOR_OVERRIDE_LOCK: 'false', SUPERVISOR_PERSISTENT_LOGGING: 'false', SUPERVISOR_HARDWARE_METRICS: 'true', }); }); describe('Extlinux files', () => { it('should correctly write to extlinux.conf files', async () => { stub(fsUtils, 'writeFileAtomic').resolves(); stub(fsUtils, 'exec').resolves(); const current = {}; const target = { HOST_EXTLINUX_isolcpus: '2', HOST_EXTLINUX_fdt: '/boot/mycustomdtb.dtb', }; expect( // @ts-ignore accessing private value deviceConfig.bootConfigChangeRequired(extlinuxBackend, current, target), ).to.equal(true); // @ts-ignore accessing private value await deviceConfig.setBootConfig(extlinuxBackend, target); expect(fsUtils.exec).to.be.calledOnce; expect(logSpy).to.be.calledTwice; expect(logSpy.getCall(1).args[2]).to.equal('Apply boot config success'); expect(fsUtils.writeFileAtomic).to.be.calledWith( './test/data/mnt/boot/extlinux/extlinux.conf', stripIndent` DEFAULT primary TIMEOUT 30 MENU TITLE Boot Options LABEL primary MENU LABEL primary Image LINUX /Image APPEND \${cbootargs} \${resin_kernel_root} ro rootwait isolcpus=2 FDT /boot/mycustomdtb.dtb ` + '\n', // add newline because stripIndent trims last newline ); // Restore stubs (fsUtils.writeFileAtomic as SinonStub).restore(); (fsUtils.exec as SinonStub).restore(); }); }); describe('Balena fin', () => { it('should always add the balena-fin dtoverlay', () => { expect(configTxtBackend.ensureRequiredConfig('fincm3', {})).to.deep.equal( { dtoverlay: ['balena-fin'], }, ); expect( configTxtBackend.ensureRequiredConfig('fincm3', { test: '123', test2: ['123'], test3: ['123', '234'], }), ).to.deep.equal({ test: '123', test2: ['123'], test3: ['123', '234'], dtoverlay: ['balena-fin'], }); expect( configTxtBackend.ensureRequiredConfig('fincm3', { dtoverlay: 'test', }), ).to.deep.equal({ dtoverlay: ['test', 'balena-fin'] }); expect( configTxtBackend.ensureRequiredConfig('fincm3', { dtoverlay: ['test'], }), ).to.deep.equal({ dtoverlay: ['test', 'balena-fin'] }); }); it('should not cause a config change when the cloud does not specify the balena-fin overlay', () => { expect( deviceConfig.bootConfigChangeRequired( configTxtBackend, { HOST_CONFIG_dtoverlay: '"test","balena-fin"' }, { HOST_CONFIG_dtoverlay: '"test"' }, 'fincm3', ), ).to.equal(false); expect( deviceConfig.bootConfigChangeRequired( configTxtBackend, { HOST_CONFIG_dtoverlay: '"test","balena-fin"' }, { HOST_CONFIG_dtoverlay: 'test' }, 'fincm3', ), ).to.equal(false); expect( deviceConfig.bootConfigChangeRequired( configTxtBackend, { HOST_CONFIG_dtoverlay: '"test","test2","balena-fin"' }, { HOST_CONFIG_dtoverlay: '"test","test2"' }, 'fincm3', ), ).to.equal(false); }); }); describe('ODMDATA', () => { it('requires change when target is different', () => { expect( deviceConfig.bootConfigChangeRequired( odmdataBackend, { HOST_ODMDATA_configuration: '2' }, { HOST_ODMDATA_configuration: '5' }, 'jetson-tx2', ), ).to.equal(true); }); it('requires change when no target is set', () => { expect( deviceConfig.bootConfigChangeRequired( odmdataBackend, { HOST_ODMDATA_configuration: '2' }, {}, 'jetson-tx2', ), ).to.equal(false); }); }); describe('ConfigFS files', () => { it('should correctly write to configfs.json files', async () => { stub(fsUtils, 'writeFileAtomic').resolves(); stub(fsUtils, 'exec').resolves(); const current = {}; const target = { HOST_CONFIGFS_ssdt: 'spidev1.0', }; expect( // @ts-ignore accessing private value deviceConfig.bootConfigChangeRequired( configFsBackend, current, target, 'up-board', ), ).to.equal(true); // @ts-ignore accessing private value await deviceConfig.setBootConfig(configFsBackend, target); expect(fsUtils.exec).to.be.calledOnce; expect(logSpy).to.be.calledTwice; expect(logSpy.getCall(1).args[2]).to.equal('Apply boot config success'); expect(fsUtils.writeFileAtomic).to.be.calledWith( 'test/data/mnt/boot/configfs.json', '{"ssdt":["spidev1.0"]}', ); // Restore stubs (fsUtils.writeFileAtomic as SinonStub).restore(); (fsUtils.exec as SinonStub).restore(); }); it('should correctly load the configfs.json file', async () => { stub(fsUtils, 'exec').resolves(); stub(fsUtils, 'writeFileAtomic').resolves(); stub(fsUtils, 'exists').resolves(true); stub(fs, 'mkdir').resolves(); stub(fs, 'readdir').resolves([]); stub(fs, 'readFile').callsFake((file) => { if (file === 'test/data/mnt/boot/configfs.json') { return Promise.resolve( JSON.stringify({ ssdt: ['spidev1.1'], }), ); } return Promise.resolve(''); }); await configFsBackend.initialise(); expect(fsUtils.exec).to.be.calledWith('modprobe acpi_configfs'); expect(fsUtils.exec).to.be.calledWith( `mount -t vfat -o remount,rw ${constants.bootBlockDevice} ./test/data/mnt/boot`, ); expect(fsUtils.exec).to.be.calledWith( 'cat test/data/boot/acpi-tables/spidev1.1.aml > test/data/sys/kernel/config/acpi/table/spidev1.1/aml', ); expect((fsUtils.exists as SinonSpy).callCount).to.equal(2); expect((fs.readFile as SinonSpy).callCount).to.equal(4); // Restore stubs (fsUtils.writeFileAtomic as SinonStub).restore(); (fsUtils.exec as SinonStub).restore(); (fsUtils.exists as SinonStub).restore(); (fs.mkdir as SinonStub).restore(); (fs.readdir as SinonStub).restore(); (fs.readFile as SinonStub).restore(); }); it('requires change when target is different', () => { expect( deviceConfig.bootConfigChangeRequired( configFsBackend, { HOST_CONFIGFS_ssdt: '' }, { HOST_CONFIGFS_ssdt: 'spidev1.0' }, 'up-board', ), ).to.equal(true); expect( deviceConfig.bootConfigChangeRequired( configFsBackend, { HOST_CONFIGFS_ssdt: '' }, { HOST_CONFIGFS_ssdt: '"spidev1.0"' }, 'up-board', ), ).to.equal(true); expect( deviceConfig.bootConfigChangeRequired( configFsBackend, { HOST_CONFIGFS_ssdt: '"spidev1.0"' }, { HOST_CONFIGFS_ssdt: '"spidev1.0","spidev1.1"' }, 'up-board', ), ).to.equal(true); }); it('should not report change when target is equal to current', () => { expect( deviceConfig.bootConfigChangeRequired( configFsBackend, { HOST_CONFIGFS_ssdt: '' }, { HOST_CONFIGFS_ssdt: '' }, 'up-board', ), ).to.equal(false); expect( deviceConfig.bootConfigChangeRequired( configFsBackend, { HOST_CONFIGFS_ssdt: 'spidev1.0' }, { HOST_CONFIGFS_ssdt: 'spidev1.0' }, 'up-board', ), ).to.equal(false); expect( deviceConfig.bootConfigChangeRequired( configFsBackend, { HOST_CONFIGFS_ssdt: 'spidev1.0' }, { HOST_CONFIGFS_ssdt: '"spidev1.0"' }, 'up-board', ), ).to.equal(false); expect( deviceConfig.bootConfigChangeRequired( configFsBackend, { HOST_CONFIGFS_ssdt: '"spidev1.0"' }, { HOST_CONFIGFS_ssdt: 'spidev1.0' }, 'up-board', ), ).to.equal(false); }); }); describe('Boot splash image', () => { const defaultLogo = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABAQMAAAAl21bKAAAAA1BMVEX/wQDLA+84AAAACklEQVR4nGNiAAAABgADNjd8qAAAAABJRU5ErkJggg=='; const png = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABAQMAAAAl21bKAAAAA1BMVEX/TQBcNTh/AAAAAXRSTlPM0jRW/QAAAApJREFUeJxjYgAAAAYAAzY3fKgAAAAASUVORK5CYII='; const uri = `data:image/png;base64,${png}`; beforeEach(() => { // Setup stubs stub(fsUtils, 'writeFileAtomic').resolves(); stub(fsUtils, 'exec').resolves(); }); afterEach(() => { // Restore stubs (fsUtils.writeFileAtomic as SinonStub).restore(); (fsUtils.exec as SinonStub).restore(); }); it('should correctly write to resin-logo.png', async () => { // Devices with balenaOS < 2.51 use resin-logo.png stub(fs, 'readdir').resolves(['resin-logo.png'] as any); const current = {}; const target = { HOST_SPLASH_image: png, }; // This should work with every device type, but testing on a couple // of options expect( deviceConfig.bootConfigChangeRequired( splashImageBackend, current, target, 'fincm3', ), ).to.equal(true); await deviceConfig.setBootConfig(splashImageBackend, target); expect(fsUtils.exec).to.be.calledOnce; expect(logSpy).to.be.calledTwice; expect(logSpy.getCall(1).args[2]).to.equal('Apply boot config success'); expect(fsUtils.writeFileAtomic).to.be.calledOnceWith( 'test/data/mnt/boot/splash/resin-logo.png', ); // restore the stub (fs.readdir as SinonStub).restore(); }); it('should correctly write to balena-logo.png', async () => { // Devices with balenaOS >= 2.51 use balena-logo.png stub(fs, 'readdir').resolves(['balena-logo.png'] as any); const current = {}; const target = { HOST_SPLASH_image: png, }; // This should work with every device type, but testing on a couple // of options expect( deviceConfig.bootConfigChangeRequired( splashImageBackend, current, target, 'raspberrypi4-64', ), ).to.equal(true); await deviceConfig.setBootConfig(splashImageBackend, target); expect(fsUtils.exec).to.be.calledOnce; expect(logSpy).to.be.calledTwice; expect(logSpy.getCall(1).args[2]).to.equal('Apply boot config success'); expect(fsUtils.writeFileAtomic).to.be.calledOnceWith( 'test/data/mnt/boot/splash/balena-logo.png', ); // restore the stub (fs.readdir as SinonStub).restore(); }); it('should correctly write to balena-logo.png if no default logo is found', async () => { // Devices with balenaOS >= 2.51 use balena-logo.png stub(fs, 'readdir').resolves([]); const current = {}; const target = { HOST_SPLASH_image: png, }; // This should work with every device type, but testing on a couple // of options expect( deviceConfig.bootConfigChangeRequired( splashImageBackend, current, target, 'raspberrypi3', ), ).to.equal(true); await deviceConfig.setBootConfig(splashImageBackend, target); expect(fsUtils.exec).to.be.calledOnce; expect(logSpy).to.be.calledTwice; expect(logSpy.getCall(1).args[2]).to.equal('Apply boot config success'); expect(fsUtils.writeFileAtomic).to.be.calledOnceWith( 'test/data/mnt/boot/splash/balena-logo.png', ); // restore the stub (fs.readdir as SinonStub).restore(); }); it('should correctly read the splash logo if different from the default', async () => { stub(fs, 'readdir').resolves(['balena-logo.png'] as any); const readFileStub: SinonStub = stub(fs, 'readFile').resolves( Buffer.from(png, 'base64') as any, ); readFileStub .withArgs('test/data/mnt/boot/splash/balena-logo-default.png') .resolves(Buffer.from(defaultLogo, 'base64') as any); expect( await deviceConfig.getBootConfig(splashImageBackend), ).to.deep.equal({ HOST_SPLASH_image: uri, }); expect(readFileStub).to.be.calledWith( 'test/data/mnt/boot/splash/balena-logo-default.png', ); expect(readFileStub).to.be.calledWith( 'test/data/mnt/boot/splash/balena-logo.png', ); // Restore stubs (fs.readdir as SinonStub).restore(); (fs.readFile as SinonStub).restore(); readFileStub.restore(); }); }); }); describe('getRequiredSteps', () => { const bootMountPoint = path.join( constants.rootMountPoint, constants.bootMountPoint, ); const configJson = 'test/data/config.json'; const configTxt = path.join(bootMountPoint, 'config.txt'); const deviceTypeJson = path.join(bootMountPoint, 'device-type.json'); const osRelease = path.join(constants.rootMountPoint, '/etc/os-release'); const splash = path.join(bootMountPoint, 'splash/balena-logo.png'); // TODO: something like this could be done as a fixture instead of // doing the file initialisation on 00-init.ts const mockFs = () => { mock({ // This is only needed so config.get doesn't fail [configJson]: JSON.stringify({}), [configTxt]: stripIndent` enable_uart=true `, [osRelease]: stripIndent` PRETTY_NAME="balenaOS 2.88.5+rev1" META_BALENA_VERSION="2.88.5" VARIANT_ID="dev" `, [deviceTypeJson]: JSON.stringify({ slug: 'raspberrypi4-64', arch: 'aarch64', }), [splash]: Buffer.from( 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=', 'base64', ), }); }; const unmockFs = () => { mock.restore(); }; before(() => { mockFs(); // TODO: remove this once the remount on backend.ts is no longer // necessary stub(fsUtils, 'exec'); }); after(() => { unmockFs(); (fsUtils.exec as SinonStub).restore(); }); it('returns required steps to config.json first if any', async () => { const steps = await deviceConfig.getRequiredSteps( { local: { config: { SUPERVISOR_POLL_INTERVAL: 900000, HOST_CONFIG_enable_uart: true, }, }, } as any, { local: { config: { SUPERVISOR_POLL_INTERVAL: 600000, HOST_CONFIG_enable_uart: false, }, }, } as any, ); expect(steps.map((s) => s.action)).to.have.members([ // No reboot is required by this config change 'changeConfig', 'noop', // The noop has to be here since there are also changes from config backends ]); }); it('sets the rebooot breadcrumb for config steps that require a reboot', async () => { const steps = await deviceConfig.getRequiredSteps( { local: { config: { SUPERVISOR_POLL_INTERVAL: 900000, SUPERVISOR_PERSISTENT_LOGGING: false, }, }, } as any, { local: { config: { SUPERVISOR_POLL_INTERVAL: 600000, SUPERVISOR_PERSISTENT_LOGGING: true, }, }, } as any, ); expect(steps.map((s) => s.action)).to.have.members([ 'setRebootBreadcrumb', 'changeConfig', 'noop', ]); }); it('returns required steps for backends if no steps are required for config.json', async () => { const steps = await deviceConfig.getRequiredSteps( { local: { config: { SUPERVISOR_POLL_INTERVAL: 900000, SUPERVISOR_PERSISTENT_LOGGING: true, HOST_CONFIG_enable_uart: true, }, }, } as any, { local: { config: { SUPERVISOR_POLL_INTERVAL: 900000, SUPERVISOR_PERSISTENT_LOGGING: true, HOST_CONFIG_enable_uart: false, }, }, } as any, ); expect(steps.map((s) => s.action)).to.have.members([ 'setRebootBreadcrumb', 'setBootConfig', ]); }); });
the_stack
import { Observable } from '../Observable'; import { Subscriber } from '../Subscriber'; import { Subscription } from '../Subscription'; import { IScheduler } from '../Scheduler'; import { tryCatch } from '../util/tryCatch'; import { errorObject } from '../util/errorObject'; import { AsyncSubject } from '../AsyncSubject'; /** * We need this JSDoc comment for affecting ESDoc. * @extends {Ignored} * @hide true */ export class BoundCallbackObservable<T> extends Observable<T> { subject: AsyncSubject<T>; /* tslint:disable:max-line-length */ static create(callbackFunc: (callback: () => any) => any, selector?: void, scheduler?: IScheduler): () => Observable<void>; static create<R>(callbackFunc: (callback: (result: R) => any) => any, selector?: void, scheduler?: IScheduler): () => Observable<R>; static create<T, R>(callbackFunc: (v1: T, callback: (result: R) => any) => any, selector?: void, scheduler?: IScheduler): (v1: T) => Observable<R>; static create<T, T2, R>(callbackFunc: (v1: T, v2: T2, callback: (result: R) => any) => any, selector?: void, scheduler?: IScheduler): (v1: T, v2: T2) => Observable<R>; static create<T, T2, T3, R>(callbackFunc: (v1: T, v2: T2, v3: T3, callback: (result: R) => any) => any, selector?: void, scheduler?: IScheduler): (v1: T, v2: T2, v3: T3) => Observable<R>; static create<T, T2, T3, T4, R>(callbackFunc: (v1: T, v2: T2, v3: T3, v4: T4, callback: (result: R) => any) => any, selector?: void, scheduler?: IScheduler): (v1: T, v2: T2, v3: T3, v4: T4) => Observable<R>; static create<T, T2, T3, T4, T5, R>(callbackFunc: (v1: T, v2: T2, v3: T3, v4: T4, v5: T5, callback: (result: R) => any) => any, selector?: void, scheduler?: IScheduler): (v1: T, v2: T2, v3: T3, v4: T4, v5: T5) => Observable<R>; static create<T, T2, T3, T4, T5, T6, R>(callbackFunc: (v1: T, v2: T2, v3: T3, v4: T4, v5: T5, v6: T6, callback: (result: R) => any) => any, selector?: void, scheduler?: IScheduler): (v1: T, v2: T2, v3: T3, v4: T4, v5: T5, v6: T6) => Observable<R>; static create<R>(callbackFunc: (callback: (...args: any[]) => any) => any, selector: (...args: any[]) => R, scheduler?: IScheduler): () => Observable<R>; static create<T, R>(callbackFunc: (v1: T, callback: (...args: any[]) => any) => any, selector: (...args: any[]) => R, scheduler?: IScheduler): (v1: T) => Observable<R>; static create<T, T2, R>(callbackFunc: (v1: T, v2: T2, callback: (...args: any[]) => any) => any, selector: (...args: any[]) => R, scheduler?: IScheduler): (v1: T, v2: T2) => Observable<R>; static create<T, T2, T3, R>(callbackFunc: (v1: T, v2: T2, v3: T3, callback: (...args: any[]) => any) => any, selector: (...args: any[]) => R, scheduler?: IScheduler): (v1: T, v2: T2, v3: T3) => Observable<R>; static create<T, T2, T3, T4, R>(callbackFunc: (v1: T, v2: T2, v3: T3, v4: T4, callback: (...args: any[]) => any) => any, selector: (...args: any[]) => R, scheduler?: IScheduler): (v1: T, v2: T2, v3: T3, v4: T4) => Observable<R>; static create<T, T2, T3, T4, T5, R>(callbackFunc: (v1: T, v2: T2, v3: T3, v4: T4, v5: T5, callback: (...args: any[]) => any) => any, selector: (...args: any[]) => R, scheduler?: IScheduler): (v1: T, v2: T2, v3: T3, v4: T4, v5: T5) => Observable<R>; static create<T, T2, T3, T4, T5, T6, R>(callbackFunc: (v1: T, v2: T2, v3: T3, v4: T4, v5: T5, v6: T6, callback: (...args: any[]) => any) => any, selector: (...args: any[]) => R, scheduler?: IScheduler): (v1: T, v2: T2, v3: T3, v4: T4, v5: T5, v6: T6) => Observable<R>; static create<T>(callbackFunc: Function, selector?: void, scheduler?: IScheduler): (...args: any[]) => Observable<T>; static create<T>(callbackFunc: Function, selector?: (...args: any[]) => T, scheduler?: IScheduler): (...args: any[]) => Observable<T>; /* tslint:enable:max-line-length */ /** * 把回调API转化为返回Observable的函数。 * * <span class="informal">给它一个签名为`f(x, callback)`的函数f,返回一个函数g, * 调用'g(x)'的时候会返回一个 Observable。</span> * * `bindCallback` 并不是一个操作符,因为它的输入和输出并不是 Observable 。输入的是一个 * 带有多个参数的函数,并且该函数的最后一个参数必须是个回调函数,当该函数执行完之后会调用回调函数。 * * `bindCallback` 的输出是一个函数,该函数接受的参数和输入函数一样(除了没有最后一个回调函 * 数)。当输出函数被调用,会返回一个 Observable 。如果输入函数给回调函数传递一个值,则该 Observable * 会发出这个值。如果输入函数给回调函数传递多个值,则该 Observable 会发出一个包含所有值的数组。 * * 很重要的一点是,输出函数返回的 Observable 被订阅之前,输入函数是不会执行的。这意味着如果输入 * 函数发起 AJAX 请求,那么该请求在每次订阅返回的 Observable 之后才会发出,而不是之前。 * * 作为一个可选项,selector 函数可以传给`bindObservable`。该函数接受和回调一样的参数。返回 Observable * 发出的值,而不是回调参数本身,即使在默认情况下,传递给回调的多个参数将在流中显示为数组。选择器 * 函数直接用参数调用,就像回调一样。这意味着你可以想象默认选择器(当没有显示提供的时候)是这样 * 一个函数:将它的所有参数聚集到数组中,或者仅仅返回第一个参数(当只有一个参数的时候)。 * * 最后一个可选参数 - {@link Scheduler} - 当 Observable 被订阅的时候,可以用来控制调用输入函 * 数以及发出结果的时机。默认订阅 Observable 后调用输入函数是同步的,但是使用`Scheduler.async` * 作为最后一个参数将会延迟输入函数的调用,就像是用0毫秒的setTimeout包装过。所以如果你使用了异 * 步调度器并且订阅了 Observable ,当前正在执行的所有函数调用,将在调用“输入函数”之前结束。 * * 当涉及到传递给回调的结果时,默认情况下当输入函数调用回调之后会立马发出,特别是如果回调也是同步调动的话, * 那么 Observable 的订阅也会同步调用`next`方法。如果你想延迟调用,使用`Scheduler.async`。 * 这意味着通过使用`Scheduler.async`,你可以确保输入函数永远异步调用回调函数,从而避免了可怕的Zalgo。 * * 需要注意的是,输出函数返回的Observable只能发出一次然后完成。即使输入函数多次调用回调函数,第二次 * 以及之后的调用都不会出现在流中。如果你需要监听多次的调用,你大概需要使用{@link fromEvent}或者 * {@link fromEventPattern}来代替。 * * 如果输入函数依赖上下文(this),该上下文将被设置为输出函数在调用时的同一上下文。特别是如果输入函数 * 被当作是某个对象的方法进行调用,为了保持同样的行为,建议将输出函数的上下文设置为该对象,输入方法不 * 是已经绑定好的。 * * 如果输入函数以 node 的方式(第一个参数是可选的错误参数用来标示调用是否成功)调用回调函数,{@link bindNodeCallback} * 提供了方便的错误处理,也许是更好的选择。 `bindCallback` 不会区别对待这些方法,错误参数(是否传递) * 被解释成正常的参数。 * * @example <caption>把jQuery的getJSON方法转化为Observable API</caption> * // 假设我们有这个方法:jQuery.getJSON('/my/url', callback) * var getJSONAsObservable = Rx.Observable.bindCallback(jQuery.getJSON); * var result = getJSONAsObservable('/my/url'); * result.subscribe(x => console.log(x), e => console.error(e)); * * * @example <caption>接收传递给回调的数组参数。</caption> * someFunction((a, b, c) => { * console.log(a); // 5 * console.log(b); // 'some string' * console.log(c); // {someProperty: 'someValue'} * }); * * const boundSomeFunction = Rx.Observable.bindCallback(someFunction); * boundSomeFunction().subscribe(values => { * console.log(values) // [5, 'some string', {someProperty: 'someValue'}] * }); * * * @example <caption>使用带 selector 函数的 bindCallback。</caption> * someFunction((a, b, c) => { * console.log(a); // 'a' * console.log(b); // 'b' * console.log(c); // 'c' * }); * * const boundSomeFunction = Rx.Observable.bindCallback(someFunction, (a, b, c) => a + b + c); * boundSomeFunction().subscribe(value => { * console.log(value) // 'abc' * }); * * * @example <caption>对使用和不使用 async 调度器的行为进行比较。</caption> * function iCallMyCallbackSynchronously(cb) { * cb(); * } * * const boundSyncFn = Rx.Observable.bindCallback(iCallMyCallbackSynchronously); * const boundAsyncFn = Rx.Observable.bindCallback(iCallMyCallbackSynchronously, null, Rx.Scheduler.async); * * boundSyncFn().subscribe(() => console.log('I was sync!')); * boundAsyncFn().subscribe(() => console.log('I was async!')); * console.log('This happened...'); * * // Logs: * // I was sync! * // This happened... * // I was async! * * * @example <caption>在对象方法上使用 bindCallback</caption> * const boundMethod = Rx.Observable.bindCallback(someObject.methodWithCallback); * boundMethod.call(someObject) // 确保methodWithCallback可以访问someObject * .subscribe(subscriber); * * * @see {@link bindNodeCallback} * @see {@link from} * @see {@link fromPromise} * * @param {function} func 最后一个参数是回调的函数。 * @param {function} [selector] 选择器,从回调函数中获取参数并将这些映射为一个 Observable 发出的值。 * @param {Scheduler} [scheduler] 调度器,调度回调函数。 * @return {function(...params: *): Observable} 一个返回Observable的函数,该Observable发出回调函数返回的数据。 * @static true * @name bindCallback * @owner Observable */ static create<T>(func: Function, selector: Function | void = undefined, scheduler?: IScheduler): (...args: any[]) => Observable<T> { return function(this: any, ...args: any[]): Observable<T> { return new BoundCallbackObservable<T>(func, <any>selector, args, this, scheduler); }; } constructor(private callbackFunc: Function, private selector: Function, private args: any[], private context: any, private scheduler: IScheduler) { super(); } protected _subscribe(subscriber: Subscriber<T | T[]>): Subscription { const callbackFunc = this.callbackFunc; const args = this.args; const scheduler = this.scheduler; let subject = this.subject; if (!scheduler) { if (!subject) { subject = this.subject = new AsyncSubject<T>(); const handler = function handlerFn(this: any, ...innerArgs: any[]) { const source = (<any>handlerFn).source; const { selector, subject } = source; if (selector) { const result = tryCatch(selector).apply(this, innerArgs); if (result === errorObject) { subject.error(errorObject.e); } else { subject.next(result); subject.complete(); } } else { subject.next(innerArgs.length <= 1 ? innerArgs[0] : innerArgs); subject.complete(); } }; // use named function instance to avoid closure. (<any>handler).source = this; const result = tryCatch(callbackFunc).apply(this.context, args.concat(handler)); if (result === errorObject) { subject.error(errorObject.e); } } return subject.subscribe(subscriber); } else { return scheduler.schedule(BoundCallbackObservable.dispatch, 0, { source: this, subscriber, context: this.context }); } } static dispatch<T>(state: { source: BoundCallbackObservable<T>, subscriber: Subscriber<T>, context: any }) { const self = (<Subscription><any>this); const { source, subscriber, context } = state; const { callbackFunc, args, scheduler } = source; let subject = source.subject; if (!subject) { subject = source.subject = new AsyncSubject<T>(); const handler = function handlerFn(this: any, ...innerArgs: any[]) { const source = (<any>handlerFn).source; const { selector, subject } = source; if (selector) { const result = tryCatch(selector).apply(this, innerArgs); if (result === errorObject) { self.add(scheduler.schedule(dispatchError, 0, { err: errorObject.e, subject })); } else { self.add(scheduler.schedule(dispatchNext, 0, { value: result, subject })); } } else { const value = innerArgs.length <= 1 ? innerArgs[0] : innerArgs; self.add(scheduler.schedule(dispatchNext, 0, { value, subject })); } }; // use named function to pass values in without closure (<any>handler).source = source; const result = tryCatch(callbackFunc).apply(context, args.concat(handler)); if (result === errorObject) { subject.error(errorObject.e); } } self.add(subject.subscribe(subscriber)); } } interface DispatchNextArg<T> { subject: AsyncSubject<T>; value: T; } function dispatchNext<T>(arg: DispatchNextArg<T>) { const { value, subject } = arg; subject.next(value); subject.complete(); } interface DispatchErrorArg<T> { subject: AsyncSubject<T>; err: any; } function dispatchError<T>(arg: DispatchErrorArg<T>) { const { err, subject } = arg; subject.error(err); }
the_stack
import * as Koa from 'koa'; import { isInteger, clone, cloneDeep } from 'lodash'; import * as moment from 'moment'; import Entry from '../models/Entry'; import EntryTag from '../models/EntryTag'; import EntryType from '../models/EntryType'; import BaseViewSet, { IPaginatedResult } from './BaseViewSet'; import ValidationError from '../errors/ValidationError'; import NotFoundError from '../errors/NotFoundError'; import DatabaseError from '../errors/DatabaseError'; import validate from '../utils/validate'; import { transaction } from 'objection'; import { requirePermission } from '../authorization/middleware'; import { requireAuthentication } from '../authentication/jwt/middleware'; const initialValidationConstraints = { name: { presence: { allowEmpty: false } }, published: { datetime: true, presence: true }, entryTypeId: { presence: true, numericality: { presence: true, onlyInteger: true, strict: true, greaterThan: 0 } }, fields: { presence: { allowEmpty: true } }, tags: { presence: { allowEmpty: true }, tags: true } }; enum EntryOrderBy { createdAtDesc = '-createdAt', createdAt = 'createdAt', modifiedAtDesc = '-modifiedAt', modifiedAt= 'modifiedAt' } interface IEntryListQuery { tags?: string; entryType?: string; nonPublished?: string; search?: string; orderBy?: EntryOrderBy; } export default class EntryViewSet extends BaseViewSet<Entry> { constructor(options: any) { super(Entry, options); this.bulkDelete = this.bulkDelete.bind(this); this.router.post( 'bulk-delete', requireAuthentication, requirePermission(`${this.modelClass.tableName}:delete`), this.bulkDelete ); } getCommonMiddleware() { return [requireAuthentication]; } getPageSize(ctx: Koa.Context) { const pageSize = parseInt(ctx.request.query.pageSize, 10); if (isInteger(pageSize) && pageSize > 0) return pageSize; return super.getPageSize(ctx); } getListQueryBuilder(ctx: Koa.Context) { let queryBuilder = Entry .getInProject(ctx.state.project.id) .eager('[tags, entryType, modifiedByUser, user]'); const { tags, entryType, nonPublished, search, orderBy } = ctx.request.query as IEntryListQuery; // We only include entries where published date is in the past. If nonPublished // query parameter is present we include BOTH published and non-published entries. if (!nonPublished) { queryBuilder = queryBuilder.where('entry.published', '<', moment().toDate()); } // Crude search if (search) { const words = search.split(' ').filter(w => w).map(w => w.toLowerCase()); words.forEach(word => { queryBuilder = queryBuilder.where('entry.name', 'ilike', `%${word}%`); }); } // Filter by EntryType if (entryType) { const entryTypeId = parseInt(entryType, 10); if (isInteger(entryTypeId) && entryTypeId > 0) { queryBuilder = queryBuilder.where('entry.entryTypeId', entryTypeId); } } // Filter by EntryTags if (tags) { const tagsList = tags.split(',').map(tag => tag.trim()).filter(tag => tag); queryBuilder = queryBuilder .joinRelation('tags') .distinct('entry.*') as any; tagsList.forEach((tag, i) => { if (i === 0) { queryBuilder = queryBuilder.where('tags.name', tag); } else { queryBuilder = queryBuilder.orWhere('tags.name', tag); } }); } // Ordering if (orderBy) { if (orderBy === EntryOrderBy.createdAt) { queryBuilder = queryBuilder.orderBy('entry.createdAt'); } else if (orderBy === EntryOrderBy.createdAtDesc) { queryBuilder = queryBuilder.orderBy('entry.createdAt', 'desc'); } else if (orderBy === EntryOrderBy.modifiedAt) { queryBuilder = queryBuilder.orderBy('entry.modifiedAt'); } else if (orderBy === EntryOrderBy.modifiedAtDesc) { queryBuilder = queryBuilder.orderBy('entry.modifiedAt', 'desc'); } } else { queryBuilder = queryBuilder.orderBy('entry.modifiedAt', 'desc'); } return queryBuilder; } getRetrieveQueryBuilder(ctx: Koa.Context) { return Entry.getInProjectWithRelations(ctx.state.project.id); } initialValidation(entryData: object) { const errors = validate(entryData, initialValidationConstraints); if (errors) { const err = new ValidationError(); err.errors = errors; throw err; } } async validateFields(entryType: EntryType, fields: any, projectId: number) { try { await entryType.validateEntryFields(fields, projectId); } catch (fieldErrors) { const err = new ValidationError(); err.errors = { fields: fieldErrors }; throw err; } } async list(ctx: Koa.Context) { let result = await super.list(ctx); let entries: Entry[]; if ('results' in result) { const paginatedResult = result as IPaginatedResult; entries = paginatedResult.results; } else { entries = result as Entry[]; } const mappedEntries = entries.map(entry => { const json = entry.toJSON() as any; // Return tags as strings, not objects json.tags = json.tags.map((tag: { name: string }) => tag.name); // Don't include entry fields and entryType fields on list endpoint delete json.fields; delete json.entryType.fields; return json; }); if ('results' in result) { result = result as IPaginatedResult; result.results = mappedEntries; } else { result = mappedEntries; } ctx.body = result; ctx.state.viewsetResult.data = result; return result; } async create(ctx: Koa.Context) { this.initialValidation(ctx.request.body); const { entryTypeId, fields, tags } = ctx.request.body; const entryType = await EntryType.getById(entryTypeId); const { project, user } = ctx.state; if (!entryType || entryType.projectId !== project.id) { throw new ValidationError('Entry type with the provided id does not exist in project'); } // Check the entry fields are valid against the entry type's fields await this.validateFields(entryType, fields, project.id); // Prepare the data for insertion into database const entryData = cloneDeep(ctx.request.body); delete entryData.tags; delete entryData.modifiedAt; entryData.userId = user.id; entryData.modifiedByUserId = user.id; entryData.fields = Entry.externalFieldsToInternal(entryType.fields, fields); const knex = Entry.knex(); return await transaction(knex, async trx => { // Create new entry const entry = await Entry.create(entryData, trx); if (!entry) throw new DatabaseError(); // Get or create tags and relate them to entry let entryTags = await EntryTag.bulkGetOrCreate(tags, project.id, trx); entryTags = await entry.setTags(entryTags, trx); const entryJSON = entry.toJSON() as any; entryJSON.tags = entryTags.map(entryTag => entryTag.name); entryJSON.fields = await entry.internalFieldsToExternal(entryType.fields, trx); ctx.body = entryJSON; ctx.state.viewsetResult = { action: 'create', modelClass: Entry, data: entryJSON }; return entry; }); } async retrieve(ctx: Koa.Context) { const entry = await super.retrieve(ctx) as any; const entryJSON = entry.toJSON() as any; entryJSON.tags = entry.tags.map((entryTag: { name: string }) => entryTag.name); entryJSON.fields = await entry.internalFieldsToExternal(entry.entryType.fields); delete entryJSON.entryType.fields; ctx.body = entryJSON; ctx.state.viewsetResult = { action: 'retrieve', modelClass: this.modelClass, data: entryJSON }; return entry; } async update(ctx: Koa.Context) { this.initialValidation(ctx.request.body); const { fields, tags } = ctx.request.body; const { project, user } = ctx.state; const id = ctx.params[this.getIdRouteParameter()]; const knex = Entry.knex(); return await transaction(knex, async trx => { let entry = await Entry .getInProject(project.id, trx) .where('entry.id', id) .first(); if (!entry) throw new NotFoundError(); const entryType = await EntryType.getById(entry.entryTypeId, trx); if (!entryType) throw new NotFoundError('The entry\'s entry type does not exist'); // Check the entry fields are valid against the entry type's fields await this.validateFields(entryType, fields, project.id); // Prepare the data for insertion into database const entryData = clone(ctx.request.body); delete entryData.createdAt; delete entryData.tags; delete entryData.id; delete entryData.entryType; delete entryData.user; delete entryData.modifiedByUser; entryData.modifiedAt = moment().format(); entryData.entryTypeId = entryType.id; entryData.modifiedByUserId = user.id; entryData.fields = Entry.externalFieldsToInternal(entryType.fields, fields, entry.fields); // Update entry entry = await Entry .query(trx) .update(entryData) .returning('*') .where('id', entry.id) .first(); if (!entry) throw new DatabaseError(); // Get or create tags and relate them to entry let entryTags = await EntryTag.bulkGetOrCreate(tags, project.id, trx); entryTags = await entry.setTags(entryTags, trx); const entryJSON = entry.toJSON() as any; entryJSON.tags = entryTags.map(entryTag => entryTag.name); entryJSON.fields = await entry.internalFieldsToExternal(entryType.fields, trx); ctx.body = entryJSON; ctx.state.viewsetResult = { action: 'update', modelClass: this.modelClass, data: entryJSON }; return entry; }); } async bulkDelete(ctx: Koa.Context) { const arrayOfIds = ctx.request.body; const error = validate.single(arrayOfIds, { arrayOfIds: true }); if (error) throw new ValidationError(error[0]); await Entry.bulkDelete(arrayOfIds, ctx.state.project.id); ctx.status = 204; ctx.state.viewsetResult = { action: 'bulkDelete', modelClass: Entry, data: arrayOfIds }; } }
the_stack
import astTypes = require("ast-types"); import nodePath = require("ast-types/lib/node-path"); import types = require("ast-types/lib/types"); import recast = require("recast"); import Collection = require("./Collection"); import template = require("./template"); import VariableDeclarator = require("./collections/VariableDeclarator"); import JSXElement = require("./collections/JSXElement"); declare namespace core { interface Parser { parse(source: string, options?: any): types.ASTNode; } interface Filters { JSXElement: JSXElement.FilterMethods; VariableDeclarator: VariableDeclarator.FilterMethods; } interface Mappings { JSXElement: JSXElement.MappingMethods; } interface Plugin { (core: Core): void; } interface FileInfo { /** The absolute path to the current file. */ path: string; /** The source code of the current file. */ source: string; } interface Stats { /** * Helper function to collect data during --dry runs. * This function keeps a counter for how often it was called with a specific argument. * The result is shown in the console. Useful for finding out how many files match a criterion. */ (name: string, quantity?: number): void; } type ASTPath<N = ASTNode> = nodePath.NodePath<N, N>; interface Core { (source: string, options?: Options): Collection.Collection<any>; (source: ASTNode | ASTNode[] | ASTPath | ASTPath[]): Collection.Collection<any>; registerMethods: typeof Collection.registerMethods; types: typeof recast.types; match( path: ASTNode | ASTPath, filter: ((path: ASTNode) => boolean) | ASTNode ): boolean; /** template, bound to default parser */ template: template.Template; filters: Filters; mappings: Mappings; /** * Utility function for registering plugins. * * Plugins are simple functions that are passed the core jscodeshift instance. * They should extend jscodeshift by calling `registerMethods`, etc. * This method guards against repeated registrations (the plugin callback will only be called once). */ use(plugin: Plugin): void; /** * Returns a version of the core jscodeshift function "bound" to a specific * parser. */ withParser(parser: string | Parser): JSCodeshift; } type JSCodeshift = Core & typeof recast.types.namedTypes & typeof recast.types.builders; type Collection<T = any> = Collection.Collection<T>; interface API { j: JSCodeshift; jscodeshift: JSCodeshift; stats: Stats; report: (msg: string) => void; } interface Options { [option: string]: any; } interface Transform { /** * If a string is returned and it is different from passed source, the transform is considered to be successful. * If a string is returned but it's the same as the source, the transform is considered to be unsuccessful. * If nothing is returned, the file is not supposed to be transformed (which is ok). */ (file: FileInfo, api: API, options: Options): string | null | undefined | void; } type ASTNode = astTypes.namedTypes.ASTNode; type AnyTypeAnnotation = astTypes.namedTypes.AnyTypeAnnotation; type ArrayExpression = astTypes.namedTypes.ArrayExpression; type ArrayPattern = astTypes.namedTypes.ArrayPattern; type ArrayTypeAnnotation = astTypes.namedTypes.ArrayTypeAnnotation; type ArrowFunctionExpression = astTypes.namedTypes.ArrowFunctionExpression; type AssignmentExpression = astTypes.namedTypes.AssignmentExpression; type AssignmentPattern = astTypes.namedTypes.AssignmentPattern; type AwaitExpression = astTypes.namedTypes.AwaitExpression; type BigIntLiteral = astTypes.namedTypes.BigIntLiteral; type BigIntLiteralTypeAnnotation = astTypes.namedTypes.BigIntLiteralTypeAnnotation; type BigIntTypeAnnotation = astTypes.namedTypes.BigIntTypeAnnotation; type BinaryExpression = astTypes.namedTypes.BinaryExpression; type BindExpression = astTypes.namedTypes.BindExpression; type Block = astTypes.namedTypes.Block; type BlockStatement = astTypes.namedTypes.BlockStatement; type BooleanLiteral = astTypes.namedTypes.BooleanLiteral; type BooleanLiteralTypeAnnotation = astTypes.namedTypes.BooleanLiteralTypeAnnotation; type BooleanTypeAnnotation = astTypes.namedTypes.BooleanTypeAnnotation; type BreakStatement = astTypes.namedTypes.BreakStatement; type CallExpression = astTypes.namedTypes.CallExpression; type CatchClause = astTypes.namedTypes.CatchClause; type ChainElement = astTypes.namedTypes.ChainElement; type ChainExpression = astTypes.namedTypes.ChainExpression; type ClassBody = astTypes.namedTypes.ClassBody; type ClassDeclaration = astTypes.namedTypes.ClassDeclaration; type ClassExpression = astTypes.namedTypes.ClassExpression; type ClassImplements = astTypes.namedTypes.ClassImplements; type ClassMethod = astTypes.namedTypes.ClassMethod; type ClassPrivateMethod = astTypes.namedTypes.ClassPrivateMethod; type ClassPrivateProperty = astTypes.namedTypes.ClassPrivateProperty; type ClassProperty = astTypes.namedTypes.ClassProperty; type ClassPropertyDefinition = astTypes.namedTypes.ClassPropertyDefinition; type Comment = astTypes.namedTypes.Comment; type CommentBlock = astTypes.namedTypes.CommentBlock; type CommentLine = astTypes.namedTypes.CommentLine; type ComprehensionBlock = astTypes.namedTypes.ComprehensionBlock; type ComprehensionExpression = astTypes.namedTypes.ComprehensionExpression; type ConditionalExpression = astTypes.namedTypes.ConditionalExpression; type ContinueStatement = astTypes.namedTypes.ContinueStatement; type DebuggerStatement = astTypes.namedTypes.DebuggerStatement; type Declaration = astTypes.namedTypes.Declaration; type DeclareClass = astTypes.namedTypes.DeclareClass; type DeclaredPredicate = astTypes.namedTypes.DeclaredPredicate; type DeclareExportAllDeclaration = astTypes.namedTypes.DeclareExportAllDeclaration; type DeclareExportDeclaration = astTypes.namedTypes.DeclareExportDeclaration; type DeclareFunction = astTypes.namedTypes.DeclareFunction; type DeclareInterface = astTypes.namedTypes.DeclareInterface; type DeclareModule = astTypes.namedTypes.DeclareModule; type DeclareModuleExports = astTypes.namedTypes.DeclareModuleExports; type DeclareOpaqueType = astTypes.namedTypes.DeclareOpaqueType; type DeclareTypeAlias = astTypes.namedTypes.DeclareTypeAlias; type DeclareVariable = astTypes.namedTypes.DeclareVariable; type Decorator = astTypes.namedTypes.Decorator; type Directive = astTypes.namedTypes.Directive; type DirectiveLiteral = astTypes.namedTypes.DirectiveLiteral; type DoExpression = astTypes.namedTypes.DoExpression; type DoWhileStatement = astTypes.namedTypes.DoWhileStatement; type EmptyStatement = astTypes.namedTypes.EmptyStatement; type EmptyTypeAnnotation = astTypes.namedTypes.EmptyTypeAnnotation; type EnumBooleanBody = astTypes.namedTypes.EnumBooleanBody; type EnumBooleanMember = astTypes.namedTypes.EnumBooleanMember; type EnumDeclaration = astTypes.namedTypes.EnumDeclaration; type EnumDefaultedMember = astTypes.namedTypes.EnumDefaultedMember; type EnumNumberBody = astTypes.namedTypes.EnumNumberBody; type EnumNumberMember = astTypes.namedTypes.EnumNumberMember; type EnumStringBody = astTypes.namedTypes.EnumStringBody; type EnumStringMember = astTypes.namedTypes.EnumStringMember; type EnumSymbolBody = astTypes.namedTypes.EnumSymbolBody; type ExistentialTypeParam = astTypes.namedTypes.ExistentialTypeParam; type ExistsTypeAnnotation = astTypes.namedTypes.ExistsTypeAnnotation; type ExportAllDeclaration = astTypes.namedTypes.ExportAllDeclaration; type ExportBatchSpecifier = astTypes.namedTypes.ExportBatchSpecifier; type ExportDeclaration = astTypes.namedTypes.ExportDeclaration; type ExportDefaultDeclaration = astTypes.namedTypes.ExportDefaultDeclaration; type ExportDefaultSpecifier = astTypes.namedTypes.ExportDefaultSpecifier; type ExportNamedDeclaration = astTypes.namedTypes.ExportNamedDeclaration; type ExportNamespaceSpecifier = astTypes.namedTypes.ExportNamespaceSpecifier; type ExportSpecifier = astTypes.namedTypes.ExportSpecifier; type Expression = astTypes.namedTypes.Expression; type ExpressionStatement = astTypes.namedTypes.ExpressionStatement; type File = astTypes.namedTypes.File; type Flow = astTypes.namedTypes.Flow; type FlowPredicate = astTypes.namedTypes.FlowPredicate; type FlowType = astTypes.namedTypes.FlowType; type ForAwaitStatement = astTypes.namedTypes.ForAwaitStatement; type ForInStatement = astTypes.namedTypes.ForInStatement; type ForOfStatement = astTypes.namedTypes.ForOfStatement; type ForStatement = astTypes.namedTypes.ForStatement; type Function = astTypes.namedTypes.Function; type FunctionDeclaration = astTypes.namedTypes.FunctionDeclaration; type FunctionExpression = astTypes.namedTypes.FunctionExpression; type FunctionTypeAnnotation = astTypes.namedTypes.FunctionTypeAnnotation; type FunctionTypeParam = astTypes.namedTypes.FunctionTypeParam; type GeneratorExpression = astTypes.namedTypes.GeneratorExpression; type GenericTypeAnnotation = astTypes.namedTypes.GenericTypeAnnotation; type Identifier = astTypes.namedTypes.Identifier; type IfStatement = astTypes.namedTypes.IfStatement; type Import = astTypes.namedTypes.Import; type ImportDeclaration = astTypes.namedTypes.ImportDeclaration; type ImportDefaultSpecifier = astTypes.namedTypes.ImportDefaultSpecifier; type ImportExpression = astTypes.namedTypes.ImportExpression; type ImportNamespaceSpecifier = astTypes.namedTypes.ImportNamespaceSpecifier; type ImportSpecifier = astTypes.namedTypes.ImportSpecifier; type InferredPredicate = astTypes.namedTypes.InferredPredicate; type InterfaceDeclaration = astTypes.namedTypes.InterfaceDeclaration; type InterfaceExtends = astTypes.namedTypes.InterfaceExtends; type InterfaceTypeAnnotation = astTypes.namedTypes.InterfaceTypeAnnotation; type InterpreterDirective = astTypes.namedTypes.InterpreterDirective; type IntersectionTypeAnnotation = astTypes.namedTypes.IntersectionTypeAnnotation; type JSXAttribute = astTypes.namedTypes.JSXAttribute; type JSXClosingElement = astTypes.namedTypes.JSXClosingElement; type JSXClosingFragment = astTypes.namedTypes.JSXClosingFragment; type JSXElement = astTypes.namedTypes.JSXElement; type JSXEmptyExpression = astTypes.namedTypes.JSXEmptyExpression; type JSXExpressionContainer = astTypes.namedTypes.JSXExpressionContainer; type JSXFragment = astTypes.namedTypes.JSXFragment; type JSXIdentifier = astTypes.namedTypes.JSXIdentifier; type JSXMemberExpression = astTypes.namedTypes.JSXMemberExpression; type JSXNamespacedName = astTypes.namedTypes.JSXNamespacedName; type JSXOpeningElement = astTypes.namedTypes.JSXOpeningElement; type JSXOpeningFragment = astTypes.namedTypes.JSXOpeningFragment; type JSXSpreadAttribute = astTypes.namedTypes.JSXSpreadAttribute; type JSXSpreadChild = astTypes.namedTypes.JSXSpreadChild; type JSXText = astTypes.namedTypes.JSXText; type LabeledStatement = astTypes.namedTypes.LabeledStatement; type Line = astTypes.namedTypes.Line; type Literal = astTypes.namedTypes.Literal; type LogicalExpression = astTypes.namedTypes.LogicalExpression; type MemberExpression = astTypes.namedTypes.MemberExpression; type MemberTypeAnnotation = astTypes.namedTypes.MemberTypeAnnotation; type MetaProperty = astTypes.namedTypes.MetaProperty; type MethodDefinition = astTypes.namedTypes.MethodDefinition; type MixedTypeAnnotation = astTypes.namedTypes.MixedTypeAnnotation; type ModuleSpecifier = astTypes.namedTypes.ModuleSpecifier; type NewExpression = astTypes.namedTypes.NewExpression; type Node = astTypes.namedTypes.Node; type Noop = astTypes.namedTypes.Noop; type NullableTypeAnnotation = astTypes.namedTypes.NullableTypeAnnotation; type NullLiteral = astTypes.namedTypes.NullLiteral; type NullLiteralTypeAnnotation = astTypes.namedTypes.NullLiteralTypeAnnotation; type NullTypeAnnotation = astTypes.namedTypes.NullTypeAnnotation; type NumberLiteralTypeAnnotation = astTypes.namedTypes.NumberLiteralTypeAnnotation; type NumberTypeAnnotation = astTypes.namedTypes.NumberTypeAnnotation; type NumericLiteral = astTypes.namedTypes.NumericLiteral; type NumericLiteralTypeAnnotation = astTypes.namedTypes.NumericLiteralTypeAnnotation; type ObjectExpression = astTypes.namedTypes.ObjectExpression; type ObjectMethod = astTypes.namedTypes.ObjectMethod; type ObjectPattern = astTypes.namedTypes.ObjectPattern; type ObjectProperty = astTypes.namedTypes.ObjectProperty; type ObjectTypeAnnotation = astTypes.namedTypes.ObjectTypeAnnotation; type ObjectTypeCallProperty = astTypes.namedTypes.ObjectTypeCallProperty; type ObjectTypeIndexer = astTypes.namedTypes.ObjectTypeIndexer; type ObjectTypeInternalSlot = astTypes.namedTypes.ObjectTypeInternalSlot; type ObjectTypeProperty = astTypes.namedTypes.ObjectTypeProperty; type ObjectTypeSpreadProperty = astTypes.namedTypes.ObjectTypeSpreadProperty; type OpaqueType = astTypes.namedTypes.OpaqueType; type OptionalCallExpression = astTypes.namedTypes.OptionalCallExpression; type OptionalMemberExpression = astTypes.namedTypes.OptionalMemberExpression; type ParenthesizedExpression = astTypes.namedTypes.ParenthesizedExpression; type Pattern = astTypes.namedTypes.Pattern; type Position = astTypes.namedTypes.Position; type Printable = astTypes.namedTypes.Printable; type PrivateName = astTypes.namedTypes.PrivateName; type Program = astTypes.namedTypes.Program; type Property = astTypes.namedTypes.Property; type PropertyPattern = astTypes.namedTypes.PropertyPattern; type QualifiedTypeIdentifier = astTypes.namedTypes.QualifiedTypeIdentifier; type RegExpLiteral = astTypes.namedTypes.RegExpLiteral; type RestElement = astTypes.namedTypes.RestElement; type RestProperty = astTypes.namedTypes.RestProperty; type ReturnStatement = astTypes.namedTypes.ReturnStatement; type SequenceExpression = astTypes.namedTypes.SequenceExpression; type SourceLocation = astTypes.namedTypes.SourceLocation; type Specifier = astTypes.namedTypes.Specifier; type SpreadElement = astTypes.namedTypes.SpreadElement; type SpreadElementPattern = astTypes.namedTypes.SpreadElementPattern; type SpreadProperty = astTypes.namedTypes.SpreadProperty; type SpreadPropertyPattern = astTypes.namedTypes.SpreadPropertyPattern; type Statement = astTypes.namedTypes.Statement; type StringLiteral = astTypes.namedTypes.StringLiteral; type StringLiteralTypeAnnotation = astTypes.namedTypes.StringLiteralTypeAnnotation; type StringTypeAnnotation = astTypes.namedTypes.StringTypeAnnotation; type Super = astTypes.namedTypes.Super; type SwitchCase = astTypes.namedTypes.SwitchCase; type SwitchStatement = astTypes.namedTypes.SwitchStatement; type SymbolTypeAnnotation = astTypes.namedTypes.SymbolTypeAnnotation; type TaggedTemplateExpression = astTypes.namedTypes.TaggedTemplateExpression; type TemplateElement = astTypes.namedTypes.TemplateElement; type TemplateLiteral = astTypes.namedTypes.TemplateLiteral; type ThisExpression = astTypes.namedTypes.ThisExpression; type ThisTypeAnnotation = astTypes.namedTypes.ThisTypeAnnotation; type ThrowStatement = astTypes.namedTypes.ThrowStatement; type TryStatement = astTypes.namedTypes.TryStatement; type TSAnyKeyword = astTypes.namedTypes.TSAnyKeyword; type TSArrayType = astTypes.namedTypes.TSArrayType; type TSAsExpression = astTypes.namedTypes.TSAsExpression; type TSBigIntKeyword = astTypes.namedTypes.TSBigIntKeyword; type TSBooleanKeyword = astTypes.namedTypes.TSBooleanKeyword; type TSCallSignatureDeclaration = astTypes.namedTypes.TSCallSignatureDeclaration; type TSConditionalType = astTypes.namedTypes.TSConditionalType; type TSConstructorType = astTypes.namedTypes.TSConstructorType; type TSConstructSignatureDeclaration = astTypes.namedTypes.TSConstructSignatureDeclaration; type TSDeclareFunction = astTypes.namedTypes.TSDeclareFunction; type TSDeclareMethod = astTypes.namedTypes.TSDeclareMethod; type TSEnumDeclaration = astTypes.namedTypes.TSEnumDeclaration; type TSEnumMember = astTypes.namedTypes.TSEnumMember; type TSExportAssignment = astTypes.namedTypes.TSExportAssignment; type TSExpressionWithTypeArguments = astTypes.namedTypes.TSExpressionWithTypeArguments; type TSExternalModuleReference = astTypes.namedTypes.TSExternalModuleReference; type TSFunctionType = astTypes.namedTypes.TSFunctionType; type TSHasOptionalTypeAnnotation = astTypes.namedTypes.TSHasOptionalTypeAnnotation; type TSHasOptionalTypeParameterInstantiation = astTypes.namedTypes.TSHasOptionalTypeParameterInstantiation; type TSHasOptionalTypeParameters = astTypes.namedTypes.TSHasOptionalTypeParameters; type TSImportEqualsDeclaration = astTypes.namedTypes.TSImportEqualsDeclaration; type TSImportType = astTypes.namedTypes.TSImportType; type TSIndexedAccessType = astTypes.namedTypes.TSIndexedAccessType; type TSIndexSignature = astTypes.namedTypes.TSIndexSignature; type TSInferType = astTypes.namedTypes.TSInferType; type TSInterfaceBody = astTypes.namedTypes.TSInterfaceBody; type TSInterfaceDeclaration = astTypes.namedTypes.TSInterfaceDeclaration; type TSIntersectionType = astTypes.namedTypes.TSIntersectionType; type TSLiteralType = astTypes.namedTypes.TSLiteralType; type TSMappedType = astTypes.namedTypes.TSMappedType; type TSMethodSignature = astTypes.namedTypes.TSMethodSignature; type TSModuleBlock = astTypes.namedTypes.TSModuleBlock; type TSModuleDeclaration = astTypes.namedTypes.TSModuleDeclaration; type TSNamedTupleMember = astTypes.namedTypes.TSNamedTupleMember; type TSNamespaceExportDeclaration = astTypes.namedTypes.TSNamespaceExportDeclaration; type TSNeverKeyword = astTypes.namedTypes.TSNeverKeyword; type TSNonNullExpression = astTypes.namedTypes.TSNonNullExpression; type TSNullKeyword = astTypes.namedTypes.TSNullKeyword; type TSNumberKeyword = astTypes.namedTypes.TSNumberKeyword; type TSObjectKeyword = astTypes.namedTypes.TSObjectKeyword; type TSOptionalType = astTypes.namedTypes.TSOptionalType; type TSParameterProperty = astTypes.namedTypes.TSParameterProperty; type TSParenthesizedType = astTypes.namedTypes.TSParenthesizedType; type TSPropertySignature = astTypes.namedTypes.TSPropertySignature; type TSQualifiedName = astTypes.namedTypes.TSQualifiedName; type TSRestType = astTypes.namedTypes.TSRestType; type TSStringKeyword = astTypes.namedTypes.TSStringKeyword; type TSSymbolKeyword = astTypes.namedTypes.TSSymbolKeyword; type TSThisType = astTypes.namedTypes.TSThisType; type TSTupleType = astTypes.namedTypes.TSTupleType; type TSType = astTypes.namedTypes.TSType; type TSTypeAliasDeclaration = astTypes.namedTypes.TSTypeAliasDeclaration; type TSTypeAnnotation = astTypes.namedTypes.TSTypeAnnotation; type TSTypeAssertion = astTypes.namedTypes.TSTypeAssertion; type TSTypeLiteral = astTypes.namedTypes.TSTypeLiteral; type TSTypeOperator = astTypes.namedTypes.TSTypeOperator; type TSTypeParameter = astTypes.namedTypes.TSTypeParameter; type TSTypeParameterDeclaration = astTypes.namedTypes.TSTypeParameterDeclaration; type TSTypeParameterInstantiation = astTypes.namedTypes.TSTypeParameterInstantiation; type TSTypePredicate = astTypes.namedTypes.TSTypePredicate; type TSTypeQuery = astTypes.namedTypes.TSTypeQuery; type TSTypeReference = astTypes.namedTypes.TSTypeReference; type TSUndefinedKeyword = astTypes.namedTypes.TSUndefinedKeyword; type TSUnionType = astTypes.namedTypes.TSUnionType; type TSUnknownKeyword = astTypes.namedTypes.TSUnknownKeyword; type TSVoidKeyword = astTypes.namedTypes.TSVoidKeyword; type TupleTypeAnnotation = astTypes.namedTypes.TupleTypeAnnotation; type TypeAlias = astTypes.namedTypes.TypeAlias; type TypeAnnotation = astTypes.namedTypes.TypeAnnotation; type TypeCastExpression = astTypes.namedTypes.TypeCastExpression; type TypeofTypeAnnotation = astTypes.namedTypes.TypeofTypeAnnotation; type TypeParameter = astTypes.namedTypes.TypeParameter; type TypeParameterDeclaration = astTypes.namedTypes.TypeParameterDeclaration; type TypeParameterInstantiation = astTypes.namedTypes.TypeParameterInstantiation; type UnaryExpression = astTypes.namedTypes.UnaryExpression; type UnionTypeAnnotation = astTypes.namedTypes.UnionTypeAnnotation; type UpdateExpression = astTypes.namedTypes.UpdateExpression; type VariableDeclaration = astTypes.namedTypes.VariableDeclaration; type VariableDeclarator = astTypes.namedTypes.VariableDeclarator; type Variance = astTypes.namedTypes.Variance; type VoidTypeAnnotation = astTypes.namedTypes.VoidTypeAnnotation; type WhileStatement = astTypes.namedTypes.WhileStatement; type WithStatement = astTypes.namedTypes.WithStatement; type YieldExpression = astTypes.namedTypes.YieldExpression; } declare const core: core.JSCodeshift; export = core;
the_stack
import assert from 'assert'; import { Promise } from 'bluebird'; import httpStatusCodes from 'http-status'; import errors from '../util/errors'; // ------------------------------------------------------------------------------ // Typedefs // ------------------------------------------------------------------------------ type TokenInfo = any /* FIXME */; type TokenStore = any /* FIXME */; type Config = any /* FIXME */; type TokenManager = any /* FIXME */; type TokenRequestOptions = Record<string, any> /* FIXME */; // ------------------------------------------------------------------------------ // Private // ------------------------------------------------------------------------------ /** * Validate that an object is a valid TokenInfo object * * @param {Object} obj The object to validate * @returns {boolean} True if the passed in object is a valid TokenInfo object that * has all the expected properties, false otherwise * @private */ function isObjectValidTokenInfo(obj: Record<string, any>) { return Boolean( obj && obj.accessToken && obj.refreshToken && obj.accessTokenTTLMS && obj.acquiredAtMS ); } /** * Validate that an object is a valid TokenStore object * * @param {Object} obj the object to validate * @returns {boolean} returns true if the passed in object is a valid TokenStore object that * has all the expected properties. false otherwise. * @private */ function isObjectValidTokenStore(obj: Record<string, any>) { return Boolean(obj && obj.read && obj.write && obj.clear); } // ------------------------------------------------------------------------------ // Public // ------------------------------------------------------------------------------ /** * A Persistent API Session has the ability to refresh its access token once it becomes expired. * It takes in a full tokenInfo object for authentication. It can detect when its tokens have * expired and will request new, valid tokens if needed. It can also interface with a token * data-store if one is provided. * * Persistent API Session a good choice for long-running applications or web servers that * must remember users across sessions. * * @param {TokenInfo} tokenInfo A valid TokenInfo object. Will throw if improperly formatted. * @param {TokenStore} [tokenStore] A valid TokenStore object. Will throw if improperly formatted. * @param {Config} config The SDK configuration options * @param {TokenManager} tokenManager The token manager * @constructor */ class PersistentSession { _config: Config; _refreshPromise: Promise<any> | null; _tokenManager: TokenManager; _tokenStore: TokenStore; _tokenInfo: TokenInfo; constructor( tokenInfo: TokenInfo, tokenStore: TokenStore, config: Config, tokenManager: TokenManager ) { this._config = config; this._tokenManager = tokenManager; // Keeps track of if tokens are currently being refreshed this._refreshPromise = null; // Set valid PersistentSession credentials. Throw if expected credentials are invalid or not given. assert( isObjectValidTokenInfo(tokenInfo), 'tokenInfo is improperly formatted. Properties required: accessToken, refreshToken, accessTokenTTLMS and acquiredAtMS.' ); this._setTokenInfo(tokenInfo); // If tokenStore was provided, set the persistent data & current store operations if (tokenStore) { assert( isObjectValidTokenStore(tokenStore), 'Token store provided but is improperly formatted. Methods required: read(), write(), clear().' ); this._tokenStore = Promise.promisifyAll(tokenStore); } } /** * Sets all relevant token info for this client. * * @param {TokenInfo} tokenInfo A valid TokenInfo object. * @returns {void} * @private */ _setTokenInfo(tokenInfo: TokenStore) { this._tokenInfo = { accessToken: tokenInfo.accessToken, refreshToken: tokenInfo.refreshToken, accessTokenTTLMS: tokenInfo.accessTokenTTLMS, acquiredAtMS: tokenInfo.acquiredAtMS, }; } /** * Attempts to refresh tokens for the client. * Will use the Box refresh token grant to complete the refresh. On refresh failure, we'll * check the token store for more recently updated tokens and load them if found. Otherwise * an error will be propagated. * * @param {TokenRequestOptions} [options] - Sets optional behavior for the token grant * @returns {Promise<string>} Promise resolving to the access token * @private */ _refreshTokens(options?: TokenRequestOptions) { // If not already refreshing, kick off a token refresh request and set a lock so that additional // client requests don't try as well if (!this._refreshPromise) { this._refreshPromise = this._tokenManager .getTokensRefreshGrant(this._tokenInfo.refreshToken, options) .catch((err: any) => { // If we got an error response from Box API, but it was 400 invalid_grant, it indicates we may have just // made the request with an invalidated refresh token. Since only a max of 2 refresh tokens can be valid // at any point in time, and a horizontally scaled app could have multiple Node instances running in parallel, // it is possible to hit cases where too many servers all refresh a user's tokens at once // and cause this server's token to become invalidated. However, the user should still be alive, but // we'll need to check the central data store for the latest valid tokens that some other server in the app // cluster would have received. So, instead pull tokens from the central store and attempt to use them. if ( err.statusCode === httpStatusCodes.BAD_REQUEST && this._tokenStore ) { var invalidGrantError = err; // Check the tokenStore to see if tokens have been updated recently. If they have, then another // instance of the session may have already refreshed the user tokens, which would explain why // we couldn't refresh. return this._tokenStore .readAsync() .catch((e: any) => errors.unwrapAndThrow(e)) .then((storeTokenInfo: TokenStore) => { // if the tokens we got from the central store are the same as the tokens we made the failed request with // already, then we can be sure that no other servers have valid tokens for this server either. // Thus, this user truly has an expired refresh token. So, propagate an "Expired Tokens" error. if ( !storeTokenInfo || storeTokenInfo.refreshToken === this._tokenInfo.refreshToken ) { throw errors.buildAuthError(invalidGrantError.response); } // Propagate the fresh tokens that we found in the session return storeTokenInfo; }); } // Box API returned a permanent error that is not retryable and we can't recover. // We have no usable tokens for the user and no way to refresh them - propagate a permanent error. throw err; }) .then((tokenInfo: TokenInfo) => { // Success! We got back a TokenInfo object from the API. // If we have a token store, we'll write it there now before finishing up the request. if (this._tokenStore) { return this._tokenStore .writeAsync(tokenInfo) .catch((e: any) => errors.unwrapAndThrow(e)) .then(() => tokenInfo); } // If no token store, Set and propagate the access token immediately return tokenInfo; }) .then((tokenInfo: TokenInfo) => { // Set and propagate the new access token this._setTokenInfo(tokenInfo); return tokenInfo.accessToken; }) .catch((err: any) => this.handleExpiredTokensError(err)) .finally(() => { // Refresh complete, clear promise this._refreshPromise = null; }); } return this._refreshPromise as Promise<any>; } // ------------------------------------------------------------------------------ // Public Instance // ------------------------------------------------------------------------------ /** * Returns the clients access token. * * If tokens don't yet exist, first attempt to retrieve them. * If tokens are expired, first attempt to refresh them. * * @param {TokenRequestOptions} [options] - Sets optional behavior for the token grant * @returns {Promise<string>} Promise resolving to the access token */ getAccessToken(options?: TokenRequestOptions) { // If our tokens are not fresh, we need to refresh them const expirationBuffer = Math.max( this._config.expiredBufferMS, this._config.staleBufferMS ); if ( !this._tokenManager.isAccessTokenValid(this._tokenInfo, expirationBuffer) ) { return this._refreshTokens(options); } // Current access token is still valid. Return it. return Promise.resolve(this._tokenInfo.accessToken); } /** * Revokes the session's tokens. If the session has a refresh token we'll use that, * since it is more likely to be up to date. Otherwise, we'll revoke the accessToken. * Revoking either one will disable the other as well. * * @param {TokenRequestOptions} [options] - Sets optional behavior for the token grant * @returns {Promise} Promise that resolves when the revoke succeeds */ revokeTokens(options?: TokenRequestOptions) { return this._tokenManager.revokeTokens( this._tokenInfo.refreshToken, options ); } /** * Exchange the client access token for one with lower scope * @param {string|string[]} scopes The scope(s) requested for the new token * @param {string} [resource] The absolute URL of an API resource to scope the new token to * @param {Object} [options] - Optional parameters * @param {TokenRequestOptions} [options.tokenRequestOptions] - Sets optional behavior for the token grant * @returns {void} */ exchangeToken( scopes: string | string[], resource?: string, options?: { tokenRequestOptions?: TokenRequestOptions; } ) { return this.getAccessToken(options).then((accessToken) => this._tokenManager.exchangeToken(accessToken, scopes, resource, options) ); } /** * Handle an an "Expired Tokens" Error. If our tokens are expired, we need to clear the token * store (if present) before continuing. * * @param {Errors~ExpiredTokensError} err An "expired tokens" error including information * about the request/response. * @returns {Promise<Error>} Promise resolving to an error. This will * usually be the original response error, but could an error from trying to access the * token store as well. */ handleExpiredTokensError(err: any /* FIXME */) { if (!this._tokenStore) { return Promise.resolve(err); } // If a token store is available, clear the store and throw either error // eslint-disable-next-line promise/no-promise-in-callback return this._tokenStore .clearAsync() .catch((e: any) => errors.unwrapAndThrow(e)) .then(() => { throw err; }); } } /** * @module box-node-sdk/lib/sessions/persistent-session * @see {@Link PersistentSession} */ export = PersistentSession;
the_stack
import React, { Component } from 'react' import { Text, View, StyleSheet, FlatList, processColor, TouchableNativeFeedback } from 'react-native' import TrophyItem from '../../component/TrophyItem' import Ionicons from 'react-native-vector-icons/Ionicons' declare var global import { LineChart } from 'react-native-charts-wrapper' export default class LevelHistory extends Component<any, any> { static navigationOptions = { tabBarLabel: '等级历史' } constructor(props) { super(props) const { modeInfo } = props.screenProps const value = props.screenProps.statsInfo.levelTrophy const obj = value.reduce((prev, curr) => { const date = new Date(curr.timestamp) const month = (date.getUTCMonth() + 1) const day = date.getUTCDate() const hour = date.getHours() const minute = date.getMinutes() let str = date.getUTCFullYear() + '-' + (month < 10 ? '0' + month : month) + '-' + (day < 10 ? '0' + day : day) + `:${hour}-${minute}` prev[str] = curr return prev }, {}) const valueFormatter = props.screenProps.statsInfo.minuteArr.slice()//.reverse() // console.log(valueFormatter) const dataSets = [{ label: ``, config: { lineWidth: 2, drawCircles: false, highlightColor: processColor(modeInfo.accentColor), color: processColor(modeInfo.accentColor), drawFilled: true, fillColor: processColor(modeInfo.accentColor), fillAlpha: 150, valueTextColor: processColor(modeInfo.titleTextColor) }, values: valueFormatter.map(item => { // console.log(item) if (obj[item.replace(/\_suffix/igm, '')]) { console.log(item, 'intter ===>') return { y: obj[item].level } } }) }] // console.log(dataSets[0].values, value.map(item => item.level)) console.log(valueFormatter.map(item => { // console.log(item) if (obj[item.replace(/\_suffix/igm, '')]) { // console.log(item, 'intter ===>') return { y: obj[item].level } } }).filter(item => item)) this.state = { data: [], lineData: { data: { dataSets }, xAxis: { valueFormatter, position: 'BOTTOM', drawGridLines: false, granularityEnabled: true, granularity: 1, labelRotationAngle: 15, textColor: processColor(modeInfo.standardTextColor) // avoidFirstLastClipping: true // labelCountForce: true, // labelCount: 12 }, legend: { enabled: false, textColor: processColor('blue'), textSize: 12, position: 'BELOW_CHART_RIGHT', form: 'SQUARE', formSize: 14, xEntrySpace: 10, yEntrySpace: 5, formToTextSpace: 5, wordWrapEnabled: true, maxSizePercent: 0.5 // custom: { // colors: [processColor('red'), processColor('blue'), processColor('green')], // labels: ['Company X', 'Company Y', 'Company Dashed'] // } }, marker: { enabled: true, backgroundTint: processColor('teal'), markerColor: processColor('#F0C0FF8C'), textColor: processColor('white') } } } } componentWillMount() { this.onValueChanged() } flatlist: any handleImageOnclick = (url) => this.props.navigation.navigate('ImageViewer', { images: [ { url } ] }) handleSelect = () => { } renderItem = ({ item: rowData, index } ) => { const { modeInfo, navigation } = this.props.screenProps // console.log(index) if (index === 0) return ( <View style={{height: 250, marginBottom: 5}}> <LineChart style={styles.chart} data={this.state.lineData.data} chartDescription={{text: ''}} legend={this.state.lineData.legend} marker={this.state.lineData.marker} xAxis={this.state.lineData.xAxis} drawGridBackground={false} borderColor={processColor('teal')} borderWidth={1} drawBorders={true} yAxis={{ left: { textColor: processColor(modeInfo.standardTextColor), axisMinimum: 0 }, right: { textColor: processColor(modeInfo.standardTextColor), axisMinimum: 0 } }} touchEnabled={true} dragEnabled={true} scaleEnabled={true} scaleXEnabled={true} scaleYEnabled={true} pinchZoom={true} doubleTapToZoomEnabled={true} dragDecelerationEnabled={true} dragDecelerationFrictionCoef={0.99} keepPositionOnRotation={false} onSelect={this.handleSelect.bind(this)} /> </View> ) return <TrophyItem {...{ navigation, rowData, modeInfo }} /> } render() { // console.log('GamePage.js rendered'); const { modeInfo } = this.props.screenProps // console.log(this.state.data, 're renred', this.state.data.length) return ( <View style={{ flex: 1, backgroundColor: modeInfo.backgroundColor }} onStartShouldSetResponder={() => false} onMoveShouldSetResponder={() => false} > <FlatList style={{ flex: -1, backgroundColor: modeInfo.backgroundColor }} data={this.state.data} ref={(list) => this.flatlist = list} scrollEnabled={this.state.scrollEnabled} keyExtractor={(item, index) => item.href || index} renderItem={this.renderItem as any} extraData={this.state} windowSize={999} renderScrollComponent={props => <global.NestedScrollView {...props}/>} key={modeInfo.themeName} numColumns={modeInfo.numColumns} removeClippedSubviews={false} disableVirtualization={true} viewabilityConfig={{ minimumViewTime: 3000, viewAreaCoveragePercentThreshold: 100, waitForInteraction: true }} > </FlatList> { !this.state.isLoading && ( <View style={{ position: 'absolute', right: 16, bottom: 16, width: 56, height: 56, borderRadius: 28, justifyContent: 'center', alignItems: 'center', elevation: 6 }} ref={float => this.float = float}> <TouchableNativeFeedback background={TouchableNativeFeedback.SelectableBackgroundBorderless()} useForeground={false} onPress={() => this.setState({ modalVisible: true })} onPressIn={() => { this.float.setNativeProps({ style: { elevation: 12 } }) }} onPressOut={() => { this.float.setNativeProps({ style: { elevation: 6 } }) }}> <View pointerEvents='box-only' style={{ backgroundColor: modeInfo.accentColor, borderRadius: 28, width: 56, height: 56, flex: -1, justifyContent: 'center', alignItems: 'center' }}> <Ionicons name='md-search' size={24} color={modeInfo.backgroundColor}/> </View> </TouchableNativeFeedback> </View> )} {this.state.modalVisible && ( <global.MyDialog modeInfo={modeInfo} modalVisible={this.state.modalVisible} onDismiss={() => { this.setState({ modalVisible: false }) }} onRequestClose={() => { this.setState({ modalVisible: false }) }} renderContent={() => ( <View style={{ justifyContent: 'center', alignItems: 'flex-start', backgroundColor: modeInfo.backgroundColor, paddingVertical: 20, paddingHorizontal: 20, elevation: 4, opacity: 1, borderRadius: 2 }} > { Object.keys(filters).map((kind, index) => { return ( <View style={{flexDirection: 'row', padding: 5}} key={index}> <Text style={{color: modeInfo.standardTextColor, textAlignVertical: 'center'}}>{filters[kind].text}: </Text> { filters[kind].value.map((item, inner) => { return ( <View key={inner} style={{margin: 2}}> <TouchableNativeFeedback useForeground={true} background={TouchableNativeFeedback.SelectableBackgroundBorderless()} onPress={() => { this.setState({ [kind]: item.value, modalVisible: false }, () => { this.onValueChanged() }) }}> <View style={{ flex: -1, padding: 4, paddingHorizontal: 6, backgroundColor: modeInfo[item.value === this.state[kind] ? 'accentColor' : 'standardColor'], borderRadius: 2 }}> <Text style={{ color: modeInfo.backgroundColor }}>{item.text}</Text> </View> </TouchableNativeFeedback> </View> ) }) } </View> ) }) } </View> )} /> )} </View> ) } isValueChanged = false float: any = false search = (text) => { this.setState({ modalVisible: false, text }, () => { this.onValueChanged() }) } onValueChanged = () => { const { ob } = this.state const value = this.props.screenProps.statsInfo.levelTrophy let data = value.slice() switch (ob) { case 'date': data = data.reverse() break case 'outdate': break case 'difficult': data = data.sort((a, b) => parseFloat(a.rare) - parseFloat(b.rare)) break case 'easy': data = data.sort((b, a) => parseFloat(a.rare) - parseFloat(b.rare)) break } this.flatlist && this.flatlist.scrollToOffset({ offset: 0, animated: true }) this.setState({ data: [value, ...data] }) } goToSearch = async () => { await this.setState({ modalVisible: false }) this.props.screenProps.navigation.navigate('Search', { callback: (text) => { if (text === this.state.text) return this.search(text) }, content: this.state.text, placeholder: '搜索游戏', shouldSeeBackground: true }) } } const filters = { ob: { text: '排序', value: [{ text: '最新', value: 'date' }, { text: '时间正序', value: 'outdate' }, { text: '难度最高', value: 'difficult' }, { text: '难度最低', value: 'easy' }] } } const styles = StyleSheet.create({ container: { flex: 1 }, chart: { flex: 1 } })
the_stack
import * as mm from '@magenta/music/esm/core.js'; import {NoteSequence, INoteSequence} from '@magenta/music/esm/protobuf.js'; import {controlsTemplate} from './assets'; import * as utils from './utils'; import {VisualizerElement} from './visualizer'; export type NoteEvent = CustomEvent<{note: NoteSequence.INote}>; const VISUALIZER_EVENTS = ['start', 'stop', 'note'] as const; const DEFAULT_SOUNDFONT = 'https://storage.googleapis.com/magentadata/js/soundfonts/sgm_plus'; let playingPlayer: PlayerElement = null; /** * MIDI player element. * See also the [`@magenta/music/core/player` docs](https://magenta.github.io/magenta-js/music/modules/_core_player_.html). * * The element supports styling using the CSS [`::part` syntax](https://developer.mozilla.org/docs/Web/CSS/::part) * (see the list of shadow parts [below](#css-shadow-parts)). For example: * ```css * midi-player::part(control-panel) { * background: aquamarine; * border-radius: 0px; * } * ``` * * @prop src - MIDI file URL * @prop soundFont - Magenta SoundFont URL, an empty string to use the default SoundFont, or `null` to use a simple oscillator synth * @prop noteSequence - Magenta note sequence object representing the currently loaded content * @prop currentTime - Current playback position in seconds * @prop duration - Content duration in seconds * @prop playing - Indicates whether the player is currently playing * @attr visualizer - A selector matching `midi-visualizer` elements to bind to this player * * @fires load - The content is loaded and ready to play * @fires start - The player has started playing * @fires stop - The player has stopped playing * @fires note - A note starts * * @csspart control-panel - `<div>` containing all the controls * @csspart play-button - Play button * @csspart time - Numeric time indicator * @csspart current-time - Elapsed time * @csspart total-time - Total duration * @csspart seek-bar - `<input type="range">` showing playback position * @csspart loading-overlay - Overlay with shimmer animation */ export class PlayerElement extends HTMLElement { private domInitialized = false; private initTimeout: number; private needInitNs = false; protected player: mm.BasePlayer; protected controlPanel: HTMLElement; protected playButton: HTMLButtonElement; protected seekBar: HTMLInputElement; protected currentTimeLabel: HTMLInputElement; protected totalTimeLabel: HTMLInputElement; protected visualizerListeners = new Map<VisualizerElement, {[name: string]: EventListener}>(); protected ns: INoteSequence = null; protected _playing = false; protected seeking = false; static get observedAttributes() { return ['sound-font', 'src', 'visualizer']; } constructor() { super(); this.attachShadow({mode: 'open'}); this.shadowRoot.appendChild(controlsTemplate.content.cloneNode(true)); this.controlPanel = this.shadowRoot.querySelector('.controls'); this.playButton = this.controlPanel.querySelector('.play'); this.currentTimeLabel = this.controlPanel.querySelector('.current-time'); this.totalTimeLabel = this.controlPanel.querySelector('.total-time'); this.seekBar = this.controlPanel.querySelector('.seek-bar'); } connectedCallback() { if (this.domInitialized) { return; } this.domInitialized = true; const applyFocusVisiblePolyfill = (window as any).applyFocusVisiblePolyfill as (scope: Document | ShadowRoot) => void; if (applyFocusVisiblePolyfill != null) { applyFocusVisiblePolyfill(this.shadowRoot); } this.playButton.addEventListener('click', () => { if (this.player.isPlaying()) { this.stop(); } else { this.start(); } }); this.seekBar.addEventListener('input', () => { // Pause playback while the user is manipulating the control this.seeking = true; if (this.player && this.player.getPlayState() === 'started') { this.player.pause(); } }); this.seekBar.addEventListener('change', () => { const time = this.currentTime; // This returns the seek bar value as a number this.currentTimeLabel.textContent = utils.formatTime(time); if (this.player) { if (this.player.isPlaying()) { this.player.seekTo(time); if (this.player.getPlayState() === 'paused') { this.player.resume(); } } } this.seeking = false; }); this.initPlayerNow(); } attributeChangedCallback(name: string, _oldValue: string, newValue: string) { if (!this.hasAttribute(name)) { newValue = null; } if (name === 'sound-font' || name === 'src') { this.initPlayer(); } else if (name === 'visualizer') { const fn = () => { this.setVisualizerSelector(newValue); }; if (document.readyState === 'loading') { window.addEventListener('DOMContentLoaded', fn); } else { fn(); } } } protected initPlayer(initNs = true) { this.needInitNs = this.needInitNs || initNs; if (this.initTimeout == null) { this.stop(); this.setLoading(); this.initTimeout = window.setTimeout(() => this.initPlayerNow(this.needInitNs)); } } protected async initPlayerNow(initNs = true) { this.initTimeout = null; this.needInitNs = false; if (!this.domInitialized) { return; } try { let ns: INoteSequence = null; if (initNs) { if (this.src) { this.ns = null; this.ns = await mm.urlToNoteSequence(this.src); } this.currentTime = 0; if (!this.ns) { this.setError('No content loaded'); } } ns = this.ns; if (ns) { this.seekBar.max = String(ns.totalTime); this.totalTimeLabel.textContent = utils.formatTime(ns.totalTime); } else { this.seekBar.max = '0'; this.totalTimeLabel.textContent = utils.formatTime(0); return; } let soundFont = this.soundFont; const callbackObject = { // Call callbacks only if we are still playing the same note sequence. run: (n: NoteSequence.INote) => (this.ns === ns) && this.noteCallback(n), stop: () => {} }; if (soundFont === null) { this.player = new mm.Player(false, callbackObject); } else { if (soundFont === "") { soundFont = DEFAULT_SOUNDFONT; } this.player = new mm.SoundFontPlayer(soundFont, undefined, undefined, undefined, callbackObject); await (this.player as mm.SoundFontPlayer).loadSamples(ns); } if (this.ns !== ns) { // If we started loading a different sequence in the meantime... return; } this.setLoaded(); this.dispatchEvent(new CustomEvent('load')); } catch (error) { this.setError(String(error)); throw error; } } start() { (async () => { if (this.player) { if (this.player.getPlayState() == 'stopped') { if (playingPlayer && playingPlayer.playing) { playingPlayer.stop(); } playingPlayer = this; this._playing = true; let offset = this.currentTime; // Jump to the start if there are no notes left to play. if (this.ns.notes.filter((note) => note.startTime > offset).length == 0) { offset = 0; } this.currentTime = offset; this.controlPanel.classList.remove('stopped'); this.controlPanel.classList.add('playing'); try { const promise = this.player.start(this.ns, undefined, offset); this.dispatchEvent(new CustomEvent('start')); await promise; this.handleStop(true); } catch (error) { this.handleStop(); throw error; } } else if (this.player.getPlayState() == 'paused') { // This normally should not happen, since we pause playback only when seeking. this.player.resume(); } } })(); } stop() { if (this.player && this.player.isPlaying()) { this.player.stop(); } this.handleStop(false); } addVisualizer(visualizer: VisualizerElement) { const listeners = { start: () => { visualizer.noteSequence = this.noteSequence; }, stop: () => { visualizer.clearActiveNotes(); }, note: (event: NoteEvent) => { visualizer.redraw(event.detail.note); }, } as const; for (const name of VISUALIZER_EVENTS) { this.addEventListener(name, listeners[name]); } this.visualizerListeners.set(visualizer, listeners); } removeVisualizer(visualizer: VisualizerElement) { const listeners = this.visualizerListeners.get(visualizer); for (const name of VISUALIZER_EVENTS) { this.removeEventListener(name, listeners[name]); } this.visualizerListeners.delete(visualizer); } protected noteCallback(note: NoteSequence.INote) { if (!this.playing) { return; } this.dispatchEvent(new CustomEvent('note', {detail: {note}})); if (this.seeking) { return; } this.seekBar.value = String(note.startTime); this.currentTimeLabel.textContent = utils.formatTime(note.startTime); } protected handleStop(finished = false) { if (finished) { this.currentTime = this.duration; } this.controlPanel.classList.remove('playing'); this.controlPanel.classList.add('stopped'); if (this._playing) { this._playing = false; this.dispatchEvent(new CustomEvent('stop', {detail: {finished}})); } } protected setVisualizerSelector(selector: string) { // Remove old listeners for (const listeners of this.visualizerListeners.values()) { for (const name of VISUALIZER_EVENTS) { this.removeEventListener(name, listeners[name]); } } this.visualizerListeners.clear(); // Match visualizers and add them as listeners if (selector != null) { for (const element of document.querySelectorAll(selector)) { if (!(element instanceof VisualizerElement)) { console.warn(`Selector ${selector} matched non-visualizer element`, element); continue; } this.addVisualizer(element); } } } protected setLoading() { this.playButton.disabled = true; this.seekBar.disabled = true; this.controlPanel.classList.remove('error'); this.controlPanel.classList.add('loading', 'frozen'); this.controlPanel.removeAttribute('title'); } protected setLoaded() { this.controlPanel.classList.remove('loading', 'frozen'); this.playButton.disabled = false; this.seekBar.disabled = false; } protected setError(error: string) { this.playButton.disabled = true; this.seekBar.disabled = true; this.controlPanel.classList.remove('loading', 'stopped', 'playing'); this.controlPanel.classList.add('error', 'frozen'); this.controlPanel.title = error; } get noteSequence() { return this.ns; } set noteSequence(value: INoteSequence | null) { this.ns = value; this.removeAttribute('src'); // Triggers initPlayer only if src was present. this.initPlayer(); } get src() { return this.getAttribute('src'); } set src(value: string | null) { this.ns = null; this.setOrRemoveAttribute('src', value); // Triggers initPlayer only if src was present. this.initPlayer(); } /** * @attr sound-font */ get soundFont() { return this.getAttribute('sound-font'); } set soundFont(value: string | null) { this.setOrRemoveAttribute('sound-font', value); } get currentTime() { return parseFloat(this.seekBar.value); } set currentTime(value: number) { this.seekBar.value = String(value); this.currentTimeLabel.textContent = utils.formatTime(this.currentTime); if (this.player && this.player.isPlaying()) { this.player.seekTo(value); } } get duration() { return parseFloat(this.seekBar.max); } get playing() { return this._playing; } protected setOrRemoveAttribute(name: string, value: string) { if (value == null) { this.removeAttribute(name); } else { this.setAttribute(name, value); } } }
the_stack
import { IInputs, IOutputs } from "./generated/ManifestTypes"; import DataSetInterfaces = ComponentFramework.PropertyHelper.DataSetApi; type DataSet = ComponentFramework.PropertyTypes.DataSet; // Define const here const RowRecordId = "rowRecId"; // Style name of disabled buttons const Button_Disabled_style = "loadNextPageButton_Disabled_Style"; export class PropertySetTableControl implements ComponentFramework.StandardControl<IInputs, IOutputs> { private contextObj: ComponentFramework.Context<IInputs>; // Div element created as part of this control's main container private mainContainer: HTMLDivElement; // Table element created as part of this control's table private dataTable: HTMLTableElement; // Button element created as part of this control private loadNextPageButton: HTMLButtonElement; // Button element created as part of this control private loadPrevPageButton: HTMLButtonElement; private getValueResultLabel: HTMLLabelElement; private selectedRecord: DataSetInterfaces.EntityRecord; private selectedRecords: Record<string, boolean> = {}; /** * Empty constructor. */ constructor() { // no-op: method not leveraged by this example custom control } /** * Used to initialize the control instance. Controls can kick off remote server calls and other initialization actions here. * Data-set values are not initialized here, use updateView. * @param context The entire property bag available to control via Context Object; It contains values as set up by the customizer mapped to property names defined in the manifest, as well as utility functions. * @param notifyOutputChanged A callback method to alert the framework that the control has new outputs ready to be retrieved asynchronously. * @param state A piece of data that persists in one session for a single user. Can be set at any point in a controls life cycle by calling 'setControlState' in the Mode interface. * @param container If a control is marked control-type='standard', it will receive an empty div element within which it can render its content. */ public init(context: ComponentFramework.Context<IInputs>, notifyOutputChanged: () => void, state: ComponentFramework.Dictionary, container: HTMLDivElement): void { // Need to track container resize so that control could get the available width. // In Model-driven app, the available height won't be provided even this is true // In Canvas-app, the available height will be provided in context.mode.allocatedHeight context.mode.trackContainerResize(true); // Create main table container div. this.mainContainer = document.createElement("div"); this.mainContainer.classList.add("SimpleTable_MainContainer_Style"); this.mainContainer.id = "SimpleTableMainContainer"; // Create data table container div. this.dataTable = document.createElement("table"); this.dataTable.classList.add("SimpleTable_Table_Style"); this.loadPrevPageButton = document.createElement("button"); this.loadPrevPageButton.setAttribute("type", "button"); this.loadPrevPageButton.innerText = context.resources.getString("PropertySetTableControl_LoadPrev_ButtonLabel"); this.loadPrevPageButton.classList.add(Button_Disabled_style); this.loadPrevPageButton.classList.add("Button_Style"); this.loadPrevPageButton.addEventListener("click", this.onLoadPrevButtonClick.bind(this)); this.loadNextPageButton = document.createElement("button"); this.loadNextPageButton.setAttribute("type", "button"); this.loadNextPageButton.innerText = context.resources.getString("PropertySetTableControl_LoadNext_ButtonLabel"); this.loadNextPageButton.classList.add(Button_Disabled_style); this.loadNextPageButton.classList.add("Button_Style"); this.loadNextPageButton.addEventListener("click", this.onLoadNextButtonClick.bind(this)); // Create main table container div. this.mainContainer = document.createElement("div"); // Adding the main table and loadNextPage button created to the container DIV. this.mainContainer.appendChild(this.createGetValueDiv()); this.mainContainer.appendChild(this.loadPrevPageButton); this.mainContainer.appendChild(this.loadNextPageButton); this.mainContainer.appendChild(this.dataTable); this.mainContainer.classList.add("main-container"); container.appendChild(this.mainContainer); } /** * Called when any value in the property bag has changed. This includes field values, data-sets, global values such as container height and width, offline status, control metadata values such as label, visible, etc. * @param context The entire property bag available to control via Context Object; It contains values as set up by the customizer mapped to names defined in the manifest, as well as utility functions */ public updateView(context: ComponentFramework.Context<IInputs>): void { this.contextObj = context; this.toggleLoadMoreButtonWhenNeeded(context.parameters.sampleDataSet); this.toggleLoadPreviousButtonWhenNeeded(context.parameters.sampleDataSet); if (!context.parameters.sampleDataSet.loading) { // Get sorted columns on View const columnsOnView = this.getSortedColumnsOnView(context); if (!columnsOnView?.length) { return; } //calculate the width for each column const columnWidthDistribution = this.getColumnWidthDistribution(context, columnsOnView); //When new data is received, it needs to first remove the table element, allowing it to properly render a table with updated data //This only needs to be done on elements having child elements which is tied to data received from canvas/model .. while (this.dataTable.firstChild) { this.dataTable.removeChild(this.dataTable.firstChild); } this.dataTable.appendChild(this.createTableHeader(columnsOnView, columnWidthDistribution)); this.dataTable.appendChild(this.createTableBody(columnsOnView, columnWidthDistribution, context.parameters.sampleDataSet)); if (this.dataTable.parentElement) { this.dataTable.parentElement.style.height = `${context.mode.allocatedHeight - 50}px`; } } } /** * It is called by the framework prior to a control receiving new data. * @returns an object based on nomenclature defined in manifest, expecting object[s] for property marked as “bound” or “output” */ public getOutputs(): IOutputs { return {}; } /** * Called when the control is to be removed from the DOM tree. Controls should use this call for cleanup. * i.e. cancelling any pending remote calls, removing listeners, etc. */ public destroy(): void { // no-op: method not leveraged by this example custom control } private createGetValueDiv(): HTMLDivElement { const getValueDiv = document.createElement("div"); const inputBox = document.createElement("input"); const getValueButton = document.createElement("button"); const resultText = document.createElement("label"); inputBox.id = "getValueInputBox"; inputBox.placeholder = "select a row and enter the alias name"; inputBox.classList.add("GetValueInput_Style"); getValueButton.innerText = "GetValue"; getValueButton.onclick = () => { if (this.selectedRecord) { resultText.innerText = this.selectedRecord.getFormattedValue(inputBox.value); } }; resultText.innerText = "Select a row first"; resultText.classList.add("GetValueResult_Style"); this.getValueResultLabel = resultText; getValueDiv.appendChild(inputBox); getValueDiv.appendChild(getValueButton); getValueDiv.appendChild(resultText); return getValueDiv; } /** * Get sorted columns on view, columns are sorted by DataSetInterfaces.Column.order * Property-set columns will always have order = -1. * In Model-driven app, the columns are ordered in the same way as columns defined in views. * In Canvas-app, the columns are ordered by the sequence fields added to control * Note that property set columns will have order = 0 in test harness, this is a bug. * @param context * @return sorted columns object on View */ private getSortedColumnsOnView(context: ComponentFramework.Context<IInputs>): DataSetInterfaces.Column[] { if (!context.parameters.sampleDataSet.columns) { return []; } const columns = context.parameters.sampleDataSet.columns; return columns; } /** * Get column width distribution using visualSizeFactor. * In model-driven app, visualSizeFactor can be configured from view's settiong. * In Canvas app, currently there is no way to configure this value. In all data sources, all columns will have the same visualSizeFactor value. * Control does not have to render the control using these values, controls are free to display any columns with any width, or making column width adjustable. * However, these kind of configurations will be lost when leaving the page * @param context context object of this cycle * @param columnsOnView columns array on the configured view * @returns column width distribution */ private getColumnWidthDistribution(context: ComponentFramework.Context<IInputs>, columnsOnView: DataSetInterfaces.Column[]): string[] { const widthDistribution: string[] = []; // Considering need to remove border & padding length const totalWidth: number = context.mode.allocatedWidth; const widthSum = columnsOnView.reduce((sum, columnItem) => sum += columnItem.visualSizeFactor, 0); let remainWidth: number = totalWidth; columnsOnView.forEach((item, index) => { let widthPerCell = ""; if (index !== columnsOnView.length - 1) { const cellWidth = Math.round((item.visualSizeFactor / widthSum) * totalWidth); remainWidth = remainWidth - cellWidth; widthPerCell = `${cellWidth}px`; } else { widthPerCell = `${remainWidth}px`; } widthDistribution.push(widthPerCell); }); return widthDistribution; } private createTableHeader(columnsOnView: DataSetInterfaces.Column[], widthDistribution: string[]): HTMLTableSectionElement { const tableHeader: HTMLTableSectionElement = document.createElement("thead"); const tableHeaderRow: HTMLTableRowElement = document.createElement("tr"); tableHeaderRow.classList.add("SimpleTable_TableRow_Style"); columnsOnView.forEach((columnItem, index) => { const tableHeaderCell = document.createElement("th"); const innerDiv = document.createElement("div"); innerDiv.classList.add("SimpleTable_TableCellInnerDiv_Style"); innerDiv.style.maxWidth = widthDistribution[index]; let columnDisplayName: string; if (columnItem.order < 0) { tableHeaderCell.classList.add("SimpleTable_TableHeader_PropertySet_Style"); columnDisplayName = `${columnItem.displayName}(propertySet)`; } else { tableHeaderCell.classList.add("SimpleTable_TableHeader_Style"); columnDisplayName = columnItem.displayName; } innerDiv.innerText = columnDisplayName; tableHeaderCell.appendChild(innerDiv); tableHeaderRow.appendChild(tableHeaderCell); }); tableHeader.appendChild(tableHeaderRow); return tableHeader; } private createTableBody(columnsOnView: DataSetInterfaces.Column[], widthDistribution: string[], gridParam: DataSet): HTMLTableSectionElement { const tableBody: HTMLTableSectionElement = document.createElement("tbody"); if (gridParam.sortedRecordIds.length > 0) { for (const currentRecordId of gridParam.sortedRecordIds) { const tableRecordRow: HTMLTableRowElement = document.createElement("tr"); tableRecordRow.classList.add("SimpleTable_TableRow_Style"); tableRecordRow.addEventListener("click", this.onRowClick.bind(this)); // Set the recordId on the row dom, this is the simplest way to help us track which record has been clicked. tableRecordRow.setAttribute(RowRecordId, gridParam.records[currentRecordId].getRecordId()); columnsOnView.forEach((columnItem, index) => { const tableRecordCell = document.createElement("td"); tableRecordCell.classList.add("SimpleTable_TableCell_Style"); const innerDiv = document.createElement("div"); innerDiv.classList.add("SimpleTable_TableCellInnerDiv_Style"); innerDiv.style.width = widthDistribution[index]; // Currently there is a bug in canvas preventing retrieving value using alias for property set columns. // In this sample, we use the column's actual attribute name to retrieve the formatted value to work around the issue // columnItem.alias should be used after bug is addressed innerDiv.innerText = gridParam.records[currentRecordId].getFormattedValue(columnItem.name); tableRecordCell.appendChild(innerDiv); tableRecordRow.appendChild(tableRecordCell); }); tableBody.appendChild(tableRecordRow); } } else { const tableRecordRow: HTMLTableRowElement = document.createElement("tr"); const tableRecordCell: HTMLTableCellElement = document.createElement("td"); tableRecordCell.classList.add("No_Record_Style"); tableRecordCell.colSpan = columnsOnView.length; tableRecordCell.innerText = this.contextObj.resources.getString("PropertySetTableControl_No_Record_Found"); tableRecordRow.appendChild(tableRecordCell); tableBody.appendChild(tableRecordRow); } return tableBody; } /** * Row Click Event handler for the associated row when being clicked * @param event */ private onRowClick(event: Event): void { const rowElement = (event.currentTarget as HTMLTableRowElement); const rowRecordId = rowElement.getAttribute(RowRecordId); if (rowRecordId) { const record = this.contextObj.parameters.sampleDataSet.records[rowRecordId]; this.selectedRecord = record; this.getValueResultLabel.innerText = ""; this.selectedRecords[rowRecordId] = !this.selectedRecords[rowRecordId]; const selectedRecordsArray = []; for (const recordId in this.selectedRecords) { if (this.selectedRecords[recordId]) { selectedRecordsArray.push(recordId); } } this.contextObj.parameters.sampleDataSet.setSelectedRecordIds(selectedRecordsArray); this.contextObj.parameters.sampleDataSet.openDatasetItem(record.getNamedReference()); } } /** * Toggle 'LoadMore' button when needed */ private toggleLoadMoreButtonWhenNeeded(gridParam: DataSet): void { if (gridParam.paging.hasNextPage) { this.loadNextPageButton.disabled = false; } else if (!gridParam.paging.hasNextPage) { this.loadNextPageButton.disabled = true; } } /** * Toggle 'LoadMore' button when needed */ private toggleLoadPreviousButtonWhenNeeded(gridParam: DataSet): void { if (gridParam.paging.hasPreviousPage) { this.loadPrevPageButton.disabled = false; } else if (!gridParam.paging.hasPreviousPage) { this.loadPrevPageButton.disabled = true; } } /** * 'LoadMore' Button Event handler when load more button clicks * @param event */ private onLoadNextButtonClick(event: Event): void { this.contextObj.parameters.sampleDataSet.paging.loadNextPage(); this.toggleLoadMoreButtonWhenNeeded(this.contextObj.parameters.sampleDataSet); this.toggleLoadPreviousButtonWhenNeeded(this.contextObj.parameters.sampleDataSet); } /** * 'LoadPrevous' Button Event handler when load more button clicks * @param event */ private onLoadPrevButtonClick(event: Event): void { this.contextObj.parameters.sampleDataSet.paging.loadPreviousPage(); this.toggleLoadPreviousButtonWhenNeeded(this.contextObj.parameters.sampleDataSet); this.toggleLoadMoreButtonWhenNeeded(this.contextObj.parameters.sampleDataSet); } }
the_stack
import { SourceInfo } from "../ast/parser"; import { MIRBody, MIRResolvedTypeKey, MIRFieldKey, MIRInvokeKey, MIRVirtualMethodKey, MIRGlobalKey } from "./mir_ops"; import { BSQRegex } from "../ast/bsqregex"; import assert = require("assert"); function jemitsinfo(sinfo: SourceInfo): object { return { line: sinfo.line, column: sinfo.column, pos: sinfo.pos, span: sinfo.span }; } function jparsesinfo(jobj: any): SourceInfo { return new SourceInfo(jobj.line, jobj.column, jobj.pos, jobj.span); } class MIRFunctionParameter { readonly name: string; readonly type: MIRResolvedTypeKey; constructor(name: string, type: MIRResolvedTypeKey) { this.name = name; this.type = type; } jemit(): object { return { name: this.name, type: this.type }; } static jparse(jobj: any): MIRFunctionParameter { return new MIRFunctionParameter(jobj.name, jobj.type); } } class MIRConstantDecl { readonly enclosingDecl: MIRResolvedTypeKey | undefined; readonly gkey: MIRGlobalKey; readonly shortname: string; readonly attributes: string[]; readonly sourceLocation: SourceInfo; readonly srcFile: string; readonly declaredType: MIRResolvedTypeKey; readonly ivalue: MIRInvokeKey; constructor(enclosingDecl: MIRResolvedTypeKey | undefined, gkey: MIRGlobalKey, shortname: string, attributes: string[], sinfo: SourceInfo, srcFile: string, declaredType: MIRResolvedTypeKey, ivalue: MIRInvokeKey) { this.enclosingDecl = enclosingDecl; this.gkey = gkey; this.shortname = shortname; this.attributes = attributes; this.sourceLocation = sinfo; this.srcFile = srcFile; this.declaredType = declaredType; this.ivalue = ivalue; } jemit(): object { return { enclosingDecl: this.enclosingDecl, gkey: this.gkey, shortname: this.shortname, attributes: this.attributes, sinfo: jemitsinfo(this.sourceLocation), file: this.srcFile, declaredType: this.declaredType, ivalue: this.ivalue }; } static jparse(jobj: any): MIRConstantDecl { return new MIRConstantDecl(jobj.enclosingDecl, jobj.gkey, jobj.shortname, jobj.attributes, jparsesinfo(jobj.sinfo), jobj.file, jobj.declaredType, jobj.ivalue); } } abstract class MIRInvokeDecl { readonly enclosingDecl: MIRResolvedTypeKey | undefined; readonly bodyID: string; readonly ikey: MIRInvokeKey; readonly shortname: string; readonly sourceLocation: SourceInfo; readonly srcFile: string; readonly attributes: string[]; readonly recursive: boolean; readonly params: MIRFunctionParameter[]; readonly resultType: MIRResolvedTypeKey; readonly preconditions: MIRInvokeKey[] | undefined; readonly postconditions: MIRInvokeKey[] | undefined; constructor(enclosingDecl: MIRResolvedTypeKey | undefined, bodyID: string, ikey: MIRInvokeKey, shortname: string, attributes: string[], recursive: boolean, sinfo: SourceInfo, srcFile: string, params: MIRFunctionParameter[], resultType: MIRResolvedTypeKey, preconds: MIRInvokeKey[] | undefined, postconds: MIRInvokeKey[] | undefined) { this.enclosingDecl = enclosingDecl; this.bodyID = bodyID; this.ikey = ikey; this.shortname = shortname; this.sourceLocation = sinfo; this.srcFile = srcFile; this.attributes = attributes; this.recursive = recursive; this.params = params; this.resultType = resultType; this.preconditions = preconds; this.postconditions = postconds; } abstract jemit(): object; static jparse(jobj: any): MIRInvokeDecl { if (jobj.body) { return new MIRInvokeBodyDecl(jobj.enclosingDecl, jobj.bodyID, jobj.ikey, jobj.shortname, jobj.attributes, jobj.recursive, jparsesinfo(jobj.sinfo), jobj.file, jobj.params.map((p: any) => MIRFunctionParameter.jparse(p)), jobj.masksize, jobj.resultType, jobj.preconditions || undefined, jobj.postconditions || undefined, MIRBody.jparse(jobj.body)); } else { let binds = new Map<string, MIRResolvedTypeKey>(); jobj.binds.forEach((bind: any) => binds.set(bind[0], bind[1])); let pcodes = new Map<string, MIRPCode>(); jobj.pcodes.forEach((pc: any) => pcodes.set(pc[0], pc[1])); return new MIRInvokePrimitiveDecl(jobj.enclosingDecl, jobj.bodyID, jobj.ikey, jobj.shortname, jobj.attributes, jobj.recursive, jparsesinfo(jobj.sinfo), jobj.file, binds, jobj.params.map((p: any) => MIRFunctionParameter.jparse(p)), jobj.resultType, jobj.implkey, pcodes, jobj.scalarslotsinfo, jobj.mixedslotsinfo); } } } class MIRInvokeBodyDecl extends MIRInvokeDecl { readonly body: MIRBody; readonly masksize: number; constructor(enclosingDecl: MIRResolvedTypeKey | undefined, bodyID: string, ikey: MIRInvokeKey, shortname: string, attributes: string[], recursive: boolean, sinfo: SourceInfo, srcFile: string, params: MIRFunctionParameter[], masksize: number, resultType: MIRResolvedTypeKey, preconds: MIRInvokeKey[] | undefined, postconds: MIRInvokeKey[] | undefined, body: MIRBody) { super(enclosingDecl, bodyID, ikey, shortname, attributes, recursive, sinfo, srcFile, params, resultType, preconds, postconds); this.body = body; this.masksize = masksize; } jemit(): object { return { enclosingDecl: this.enclosingDecl, bodyID: this.bodyID, ikey: this.ikey, shortname: this.shortname, sinfo: jemitsinfo(this.sourceLocation), file: this.srcFile, attributes: this.attributes, recursive: this.recursive, params: this.params.map((p) => p.jemit()), masksize: this.masksize, resultType: this.resultType, preconditions: this.preconditions, postconditions: this.postconditions, body: this.body.jemit() }; } } type MIRPCode = { code: MIRInvokeKey, cargs: string[] }; class MIRInvokePrimitiveDecl extends MIRInvokeDecl { readonly implkey: string; readonly binds: Map<string, MIRResolvedTypeKey>; readonly pcodes: Map<string, MIRPCode>; readonly scalarslotsinfo: {vname: string, vtype: MIRResolvedTypeKey}[]; readonly mixedslotsinfo: {vname: string, vtype: MIRResolvedTypeKey}[]; constructor(enclosingDecl: MIRResolvedTypeKey | undefined, bodyID: string, ikey: MIRInvokeKey, shortname: string, attributes: string[], recursive: boolean, sinfo: SourceInfo, srcFile: string, binds: Map<string, MIRResolvedTypeKey>, params: MIRFunctionParameter[], resultType: MIRResolvedTypeKey, implkey: string, pcodes: Map<string, MIRPCode>, scalarslotsinfo: {vname: string, vtype: MIRResolvedTypeKey}[], mixedslotsinfo: {vname: string, vtype: MIRResolvedTypeKey}[]) { super(enclosingDecl, bodyID, ikey, shortname, attributes, recursive, sinfo, srcFile, params, resultType, undefined, undefined); this.implkey = implkey; this.binds = binds; this.pcodes = pcodes; this.scalarslotsinfo = scalarslotsinfo; this.mixedslotsinfo = mixedslotsinfo; } jemit(): object { return {enclosingDecl: this.enclosingDecl, bodyID: this.bodyID, ikey: this.ikey, shortname: this.shortname, sinfo: jemitsinfo(this.sourceLocation), file: this.srcFile, attributes: this.attributes, recursive: this.recursive, params: this.params.map((p) => p.jemit()), resultType: this.resultType, implkey: this.implkey, binds: [...this.binds], pcodes: [... this.pcodes], scalarslotsinfo: this.scalarslotsinfo, mixedlotsinfo: this.mixedslotsinfo }; } } class MIRFieldDecl { readonly enclosingDecl: MIRResolvedTypeKey; readonly attributes: string[]; readonly fkey: MIRFieldKey; readonly fname: string; readonly sourceLocation: SourceInfo; readonly srcFile: string; readonly declaredType: MIRResolvedTypeKey; constructor(enclosingDecl: MIRResolvedTypeKey, attributes: string[], srcInfo: SourceInfo, srcFile: string, fkey: MIRFieldKey, fname: string, dtype: MIRResolvedTypeKey) { this.enclosingDecl = enclosingDecl; this.attributes = attributes; this.fkey = fkey; this.fname = fname; this.sourceLocation = srcInfo; this.srcFile = srcFile; this.declaredType = dtype; } jemit(): object { return { enclosingDecl: this.enclosingDecl, attributes: this.attributes, fkey: this.fkey, fname: this.fname, sinfo: jemitsinfo(this.sourceLocation), file: this.srcFile, declaredType: this.declaredType }; } static jparse(jobj: any): MIRFieldDecl { return new MIRFieldDecl(jobj.enclosingDecl, jobj.attributes, jparsesinfo(jobj.sinfo), jobj.file, jobj.fkey, jobj.fname, jobj.declaredType); } } abstract class MIROOTypeDecl { readonly tkey: MIRResolvedTypeKey; readonly shortname: string; readonly sourceLocation: SourceInfo; readonly srcFile: string; readonly attributes: string[]; readonly ns: string; readonly name: string; readonly terms: Map<string, MIRType>; readonly provides: MIRResolvedTypeKey[]; constructor(srcInfo: SourceInfo, srcFile: string, tkey: MIRResolvedTypeKey, shortname: string, attributes: string[], ns: string, name: string, terms: Map<string, MIRType>, provides: MIRResolvedTypeKey[]) { this.tkey = tkey; this.shortname = shortname; this.sourceLocation = srcInfo; this.srcFile = srcFile; this.attributes = attributes; this.ns = ns; this.name = name; this.terms = terms; this.provides = provides; } abstract jemit(): object; jemitbase(): object { return { tkey: this.tkey, shortname: this.shortname, sinfo: jemitsinfo(this.sourceLocation), file: this.srcFile, attributes: this.attributes, ns: this.ns, name: this.name, terms: [...this.terms].map((t) => [t[0], t[1].jemit()]), provides: this.provides }; } static jparsebase(jobj: any): [SourceInfo, string, MIRResolvedTypeKey, string, string[], string, string, Map<string, MIRType>, MIRResolvedTypeKey[]] { let terms = new Map<string, MIRType>(); jobj.terms.forEach((t: any) => terms.set(t[0], MIRType.jparse(t[1]))); return [jparsesinfo(jobj.sinfo), jobj.file, jobj.tkey, jobj.shortname, jobj.attributes, jobj.ns, jobj.name, terms, jobj.provides]; } static jparse(jobj: any): MIROOTypeDecl { const tag = jobj.tag; switch (tag) { case "concept": return MIRConceptTypeDecl.jparse(jobj); case "std": return MIRObjectEntityTypeDecl.jparse(jobj); case "constructable": return MIRConstructableEntityTypeDecl.jparse(jobj); case "enum": return MIREnumEntityTypeDecl.jparse(jobj); case "primitive": return MIRPrimitiveInternalEntityTypeDecl.jparse(jobj); case "constructableinternal": return MIRConstructableInternalEntityTypeDecl.jparse(jobj); case "list": return MIRPrimitiveListEntityTypeDecl.jparse(jobj); case "stack": return MIRPrimitiveStackEntityTypeDecl.jparse(jobj); case "queue": return MIRPrimitiveQueueEntityTypeDecl.jparse(jobj); case "set": return MIRPrimitiveSetEntityTypeDecl.jparse(jobj); default: assert(tag === "map"); return MIRPrimitiveMapEntityTypeDecl.jparse(jobj); } } } class MIRConceptTypeDecl extends MIROOTypeDecl { constructor(srcInfo: SourceInfo, srcFile: string, tkey: MIRResolvedTypeKey, shortname: string, attributes: string[], ns: string, name: string, terms: Map<string, MIRType>, provides: MIRResolvedTypeKey[]) { super(srcInfo, srcFile, tkey, shortname, attributes, ns, name, terms, provides); } jemit(): object { return { tag: "concept", ...this.jemitbase() }; } static jparse(jobj: any): MIRConceptTypeDecl { return new MIRConceptTypeDecl(...MIROOTypeDecl.jparsebase(jobj)); } } abstract class MIREntityTypeDecl extends MIROOTypeDecl { constructor(srcInfo: SourceInfo, srcFile: string, tkey: MIRResolvedTypeKey, shortname: string, attributes: string[], ns: string, name: string, terms: Map<string, MIRType>, provides: MIRResolvedTypeKey[]) { super(srcInfo, srcFile, tkey, shortname, attributes, ns, name, terms, provides); } isStdEntity(): boolean { return false; } isPrimitiveEntity(): boolean { return false; } isConstructableEntity(): boolean { return false; } isCollectionEntity(): boolean { return false; } } class MIRObjectEntityTypeDecl extends MIREntityTypeDecl { readonly consfunc: MIRInvokeKey | undefined; readonly consfuncfields: MIRFieldKey[]; readonly fields: MIRFieldDecl[]; readonly vcallMap: Map<MIRVirtualMethodKey, MIRInvokeKey> = new Map<string, MIRInvokeKey>(); constructor(srcInfo: SourceInfo, srcFile: string, tkey: MIRResolvedTypeKey, shortname: string, attributes: string[], ns: string, name: string, terms: Map<string, MIRType>, provides: MIRResolvedTypeKey[], consfunc: MIRInvokeKey | undefined, consfuncfields: MIRFieldKey[], fields: MIRFieldDecl[]) { super(srcInfo, srcFile, tkey, shortname, attributes, ns, name, terms, provides); this.consfunc = consfunc; this.consfuncfields = consfuncfields; this.fields = fields; } jemit(): object { return { tag: "std", ...this.jemitbase(), consfunc: this.consfunc, consfuncfields: this.consfuncfields, fields: this.fields.map((f) => f.jemit()), vcallMap: [...this.vcallMap] }; } static jparse(jobj: any): MIRConceptTypeDecl { let entity = new MIRObjectEntityTypeDecl(...MIROOTypeDecl.jparsebase(jobj), jobj.consfunc, jobj.consfuncfields, jobj.fields); jobj.vcallMap.forEach((vc: any) => entity.vcallMap.set(vc[0], vc[1])); return entity; } isStdEntity(): boolean { return true; } } class MIRConstructableEntityTypeDecl extends MIREntityTypeDecl { readonly fromtype: MIRResolvedTypeKey; readonly usingcons: MIRInvokeKey | undefined; readonly binds: Map<string, MIRType>; //Should have special inject/extract which are the constructors constructor(srcInfo: SourceInfo, srcFile: string, tkey: MIRResolvedTypeKey, shortname: string, attributes: string[], ns: string, name: string, terms: Map<string, MIRType>, provides: MIRResolvedTypeKey[], fromtype: MIRResolvedTypeKey, usingcons: MIRInvokeKey | undefined, binds: Map<string, MIRType>) { super(srcInfo, srcFile, tkey, shortname, attributes, ns, name, terms, provides); this.fromtype = fromtype; this.usingcons = usingcons; this.binds = binds; } jemit(): object { const fbinds = [...this.binds].sort((a, b) => a[0].localeCompare(b[0])).map((v) => [v[0], v[1].jemit()]); return { tag: "constructable", ...this.jemitbase(), fromtype: this.fromtype, usingcons: this.usingcons, binds: fbinds }; } static jparse(jobj: any): MIRConstructableEntityTypeDecl { const bbinds = new Map<string, MIRType>(); jobj.binds.foreach((v: [string, any]) => { bbinds.set(v[0], MIRType.jparse(v[1])); }); return new MIRConstructableEntityTypeDecl(...MIROOTypeDecl.jparsebase(jobj), jobj.fromtype, jobj.usingcons, bbinds); } isConstructableEntity(): boolean { return true; } } class MIREnumEntityTypeDecl extends MIREntityTypeDecl { readonly usingcons: MIRInvokeKey; readonly enums: {ename: string, value: number}[]; constructor(srcInfo: SourceInfo, srcFile: string, tkey: MIRResolvedTypeKey, shortname: string, attributes: string[], ns: string, name: string, terms: Map<string, MIRType>, provides: MIRResolvedTypeKey[], usingcons: MIRInvokeKey, enums: {ename: string, value: number}[]) { super(srcInfo, srcFile, tkey, shortname, attributes, ns, name, terms, provides); this.usingcons = usingcons; this.enums = enums; } jemit(): object { return { tag: "enum", ...this.jemitbase(), usingcons: this.usingcons, enums: this.enums }; } static jparse(jobj: any): MIREnumEntityTypeDecl { const bbinds = new Map<string, MIRType>(); jobj.binds.foreach((v: [string, any]) => { bbinds.set(v[0], MIRType.jparse(v[1])); }); return new MIREnumEntityTypeDecl(...MIROOTypeDecl.jparsebase(jobj), jobj.usingcons, jobj.enums); } isConstructableEntity(): boolean { return true; } } abstract class MIRInternalEntityTypeDecl extends MIREntityTypeDecl { constructor(srcInfo: SourceInfo, srcFile: string, tkey: MIRResolvedTypeKey, shortname: string, attributes: string[], ns: string, name: string, terms: Map<string, MIRType>, provides: MIRResolvedTypeKey[]) { super(srcInfo, srcFile, tkey, shortname, attributes, ns, name, terms, provides); } } class MIRPrimitiveInternalEntityTypeDecl extends MIRInternalEntityTypeDecl { //Should just be a special implemented value constructor(srcInfo: SourceInfo, srcFile: string, tkey: MIRResolvedTypeKey, shortname: string, attributes: string[], ns: string, name: string, terms: Map<string, MIRType>, provides: MIRResolvedTypeKey[]) { super(srcInfo, srcFile, tkey, shortname, attributes, ns, name, terms, provides); } jemit(): object { return { tag: "primitive", ...this.jemitbase() }; } static jparse(jobj: any): MIRPrimitiveInternalEntityTypeDecl { return new MIRPrimitiveInternalEntityTypeDecl(...MIROOTypeDecl.jparsebase(jobj)); } isPrimitiveEntity(): boolean { return true; } } class MIRConstructableInternalEntityTypeDecl extends MIRInternalEntityTypeDecl { readonly fromtype: MIRResolvedTypeKey; readonly binds: Map<string, MIRType>; readonly optaccepts: MIRInvokeKey | undefined; constructor(srcInfo: SourceInfo, srcFile: string, tkey: MIRResolvedTypeKey, shortname: string, attributes: string[], ns: string, name: string, terms: Map<string, MIRType>, provides: MIRResolvedTypeKey[], fromtype: MIRResolvedTypeKey, binds: Map<string, MIRType>, optaccepts: MIRInvokeKey | undefined) { super(srcInfo, srcFile, tkey, shortname, attributes, ns, name, terms, provides); this.fromtype = fromtype; this.binds = binds; this.optaccepts = optaccepts; } jemit(): object { const fbinds = [...this.binds].sort((a, b) => a[0].localeCompare(b[0])).map((v) => [v[0], v[1].jemit()]); return { tag: "constructableinternal", ...this.jemitbase(), fromtype: this.fromtype, binds: fbinds, optaccepts: this.optaccepts }; } static jparse(jobj: any): MIRConstructableInternalEntityTypeDecl { const bbinds = new Map<string, MIRType>(); jobj.binds.foreach((v: [string, any]) => { bbinds.set(v[0], MIRType.jparse(v[1])); }); return new MIRConstructableInternalEntityTypeDecl(...MIROOTypeDecl.jparsebase(jobj), jobj.fromtype, bbinds, jobj.optaccepts); } isConstructableEntity(): boolean { return true; } } abstract class MIRPrimitiveCollectionEntityTypeDecl extends MIRInternalEntityTypeDecl { readonly oftype: MIRResolvedTypeKey; readonly binds: Map<string, MIRType>; constructor(srcInfo: SourceInfo, srcFile: string, tkey: MIRResolvedTypeKey, shortname: string, attributes: string[], ns: string, name: string, terms: Map<string, MIRType>, provides: MIRResolvedTypeKey[], oftype: MIRResolvedTypeKey, binds: Map<string, MIRType>) { super(srcInfo, srcFile, tkey, shortname, attributes, ns, name, terms, provides); this.oftype = oftype; this.binds = binds; } jemitcollection(): object { const fbinds = [...this.binds].sort((a, b) => a[0].localeCompare(b[0])).map((v) => [v[0], v[1].jemit()]); return { ...this.jemitbase(), oftype: this.oftype, binds: fbinds }; } static jparsecollection(jobj: any): [SourceInfo, string, MIRResolvedTypeKey, string, string[], string, string, Map<string, MIRType>, MIRResolvedTypeKey[], MIRResolvedTypeKey, Map<string, MIRType>] { const bbinds = new Map<string, MIRType>(); jobj.binds.foreach((v: [string, any]) => { bbinds.set(v[0], MIRType.jparse(v[1])); }); return [...MIROOTypeDecl.jparsebase(jobj), jobj.oftype, bbinds]; } isCollectionEntity(): boolean { return true; } } class MIRPrimitiveListEntityTypeDecl extends MIRPrimitiveCollectionEntityTypeDecl { constructor(srcInfo: SourceInfo, srcFile: string, tkey: MIRResolvedTypeKey, shortname: string, attributes: string[], ns: string, name: string, terms: Map<string, MIRType>, provides: MIRResolvedTypeKey[], oftype: MIRResolvedTypeKey, binds: Map<string, MIRType>) { super(srcInfo, srcFile, tkey, shortname, attributes, ns, name, terms, provides, oftype, binds); } jemit(): object { return { tag: "list", ...this.jemitcollection() }; } static jparse(jobj: any): MIRPrimitiveListEntityTypeDecl { return new MIRPrimitiveListEntityTypeDecl(...MIRPrimitiveCollectionEntityTypeDecl.jparsecollection(jobj)); } } class MIRPrimitiveStackEntityTypeDecl extends MIRPrimitiveCollectionEntityTypeDecl { readonly ultype: MIRResolvedTypeKey; constructor(srcInfo: SourceInfo, srcFile: string, tkey: MIRResolvedTypeKey, shortname: string, attributes: string[], ns: string, name: string, terms: Map<string, MIRType>, provides: MIRResolvedTypeKey[], oftype: MIRResolvedTypeKey, binds: Map<string, MIRType>, ultype: MIRResolvedTypeKey) { super(srcInfo, srcFile, tkey, shortname, attributes, ns, name, terms, provides, oftype, binds); this.ultype = ultype; } jemit(): object { return { tag: "stack", ...this.jemitcollection(), ultype: this.ultype }; } static jparse(jobj: any): MIRPrimitiveListEntityTypeDecl { return new MIRPrimitiveStackEntityTypeDecl(...MIRPrimitiveCollectionEntityTypeDecl.jparsecollection(jobj), jobj.ultype); } } class MIRPrimitiveQueueEntityTypeDecl extends MIRPrimitiveCollectionEntityTypeDecl { readonly ultype: MIRResolvedTypeKey; constructor(srcInfo: SourceInfo, srcFile: string, tkey: MIRResolvedTypeKey, shortname: string, attributes: string[], ns: string, name: string, terms: Map<string, MIRType>, provides: MIRResolvedTypeKey[], oftype: MIRResolvedTypeKey, binds: Map<string, MIRType>, ultype: MIRResolvedTypeKey) { super(srcInfo, srcFile, tkey, shortname, attributes, ns, name, terms, provides, oftype, binds); this.ultype = ultype; } jemit(): object { return { tag: "queue", ...this.jemitcollection(), ultype: this.ultype }; } static jparse(jobj: any): MIRPrimitiveListEntityTypeDecl { return new MIRPrimitiveQueueEntityTypeDecl(...MIRPrimitiveCollectionEntityTypeDecl.jparsecollection(jobj), jobj.ultype); } } class MIRPrimitiveSetEntityTypeDecl extends MIRPrimitiveCollectionEntityTypeDecl { readonly ultype: MIRResolvedTypeKey; readonly unqchkinv: MIRInvokeKey; readonly unqconvinv: MIRInvokeKey; constructor(srcInfo: SourceInfo, srcFile: string, tkey: MIRResolvedTypeKey, shortname: string, attributes: string[], ns: string, name: string, terms: Map<string, MIRType>, provides: MIRResolvedTypeKey[], oftype: MIRResolvedTypeKey, binds: Map<string, MIRType>, ultype: MIRResolvedTypeKey, unqchkinv: MIRInvokeKey, unqconvinv: MIRInvokeKey) { super(srcInfo, srcFile, tkey, shortname, attributes, ns, name, terms, provides, oftype, binds); this.ultype = ultype; this.unqchkinv = unqchkinv; this.unqconvinv = unqconvinv; } jemit(): object { return { tag: "set", ...this.jemitcollection(), ultype: this.ultype, unqchkinv: this.unqchkinv, unqconvinv: this.unqconvinv }; } static jparse(jobj: any): MIRPrimitiveListEntityTypeDecl { return new MIRPrimitiveSetEntityTypeDecl(...MIRPrimitiveCollectionEntityTypeDecl.jparsecollection(jobj), jobj.ultype, jobj.unqchkinv, jobj.unqconvinv); } } class MIRPrimitiveMapEntityTypeDecl extends MIRPrimitiveCollectionEntityTypeDecl { readonly ultype: MIRResolvedTypeKey; readonly unqchkinv: MIRInvokeKey; constructor(srcInfo: SourceInfo, srcFile: string, tkey: MIRResolvedTypeKey, shortname: string, attributes: string[], ns: string, name: string, terms: Map<string, MIRType>, provides: MIRResolvedTypeKey[], oftype: MIRResolvedTypeKey, binds: Map<string, MIRType>, ultype: MIRResolvedTypeKey, unqchkinv: MIRInvokeKey) { super(srcInfo, srcFile, tkey, shortname, attributes, ns, name, terms, provides, oftype, binds); this.ultype = ultype; this.unqchkinv = unqchkinv; } jemit(): object { return { tag: "set", ...this.jemitcollection(), ultype: this.ultype, unqchkinv: this.unqchkinv }; } static jparse(jobj: any): MIRPrimitiveListEntityTypeDecl { return new MIRPrimitiveMapEntityTypeDecl(...MIRPrimitiveCollectionEntityTypeDecl.jparsecollection(jobj), jobj.ultype, jobj.unqchkinv); } } abstract class MIRTypeOption { readonly typeID: MIRResolvedTypeKey; readonly shortname: string; constructor(typeID: MIRResolvedTypeKey, shortname: string) { this.typeID = typeID; this.shortname = shortname; } abstract jemit(): object; static jparse(jobj: any): MIRTypeOption { switch (jobj.kind) { case "entity": return MIREntityType.jparse(jobj); case "concept": return MIRConceptType.jparse(jobj); case "tuple": return MIRTupleType.jparse(jobj); case "record": return MIRRecordType.jparse(jobj); default: assert(jobj.kind === "ephemeral"); return MIREphemeralListType.jparse(jobj); } } } class MIREntityType extends MIRTypeOption { private constructor(typeID: MIRResolvedTypeKey, shortname: string) { super(typeID, shortname); } static create(typeID: MIRResolvedTypeKey, shortname: string): MIREntityType { return new MIREntityType(typeID, shortname); } jemit(): object { return {kind: "entity", typeID: this.typeID, shortname: this.shortname }; } static jparse(jobj: any): MIREntityType { return MIREntityType.create(jobj.typeID, jobj.shortname); } } class MIRConceptType extends MIRTypeOption { readonly ckeys: MIRResolvedTypeKey[]; private constructor(typeID: MIRResolvedTypeKey, shortname: string, ckeys: MIRResolvedTypeKey[]) { super(typeID, shortname); this.ckeys = ckeys; } static create(ckeys: [MIRResolvedTypeKey, string][]): MIRConceptType { const skeys = ckeys.sort((a, b) => a[0].localeCompare(b[0])); return new MIRConceptType(skeys.map((v) => v[0]).join(" & "), skeys.map((v) => v[1]).join("&"), skeys.map((v) => v[0])); } jemit(): object { return {kind: "concept", ckeys: this.ckeys }; } static jparse(jobj: any): MIRConceptType { return MIRConceptType.create(jobj.ckeys); } } class MIRTupleType extends MIRTypeOption { readonly entries: MIRType[]; private constructor(typeID: MIRResolvedTypeKey, shortname: string, entries: MIRType[]) { super(typeID, shortname); this.entries = entries; } static create(entries: MIRType[]): MIRTupleType { let cvalue = entries.map((entry) => entry.typeID).join(", "); let shortcvalue = entries.map((entry) => entry.shortname).join(","); return new MIRTupleType(`[${cvalue}]`, `[${shortcvalue}]`, [...entries]); } jemit(): object { return { kind: "tuple", entries: this.entries }; } static jparse(jobj: any): MIRTupleType { return MIRTupleType.create(jobj.entries); } } class MIRRecordType extends MIRTypeOption { readonly entries: {pname: string, ptype: MIRType}[]; constructor(typeID: string, shortname: string, entries: {pname: string, ptype: MIRType}[]) { super(typeID, shortname); this.entries = entries; } static create(entries: {pname: string, ptype: MIRType}[]): MIRRecordType { let simplifiedEntries = [...entries].sort((a, b) => a.pname.localeCompare(b.pname)); const name = simplifiedEntries.map((entry) => entry.pname + ": " + entry.ptype.typeID).join(", "); const shortname = simplifiedEntries.map((entry) => entry.pname + ":" + entry.ptype.shortname).join(","); return new MIRRecordType("{" + name + "}", "{" + shortname + "}", simplifiedEntries); } jemit(): object { return { kind: "record", entries: this.entries }; } static jparse(jobj: any): MIRRecordType { return MIRRecordType.create(jobj.entries); } } class MIREphemeralListType extends MIRTypeOption { readonly entries: MIRType[]; private constructor(typeID: string, shortname: string, entries: MIRType[]) { super(typeID, shortname); this.entries = entries; } static create(entries: MIRType[]): MIREphemeralListType { const name = entries.map((entry) => entry.typeID).join(", "); const shortname = entries.map((entry) => entry.shortname).join(","); return new MIREphemeralListType("(|" + name + "|)", "(|" + shortname + "|)", entries); } jemit(): object { return { kind: "ephemeral", entries: this.entries.map((e) => e.jemit()) }; } static jparse(jobj: any): MIREphemeralListType { return MIREphemeralListType.create(jobj.entries.map((e: any) => MIRType.jparse(e))); } } class MIRType { readonly typeID: MIRResolvedTypeKey; readonly shortname: string; readonly options: MIRTypeOption[]; private constructor(typeID: MIRResolvedTypeKey, shortname: string, options: MIRTypeOption[]) { this.typeID = typeID; this.shortname = shortname; this.options = options; } static createSingle(option: MIRTypeOption): MIRType { return new MIRType(option.typeID, option.shortname, [option]); } static create(options: MIRTypeOption[]): MIRType { if (options.length === 1) { return MIRType.createSingle(options[0]); } else { const typeid = [...options].sort().map((tk) => tk.typeID).join(" | "); const shortname = [...options].sort().map((tk) => tk.shortname).join("|"); return new MIRType(typeid, shortname, options); } } jemit(): object { return { options: this.options.map((opt) => opt.jemit()) }; } static jparse(jobj: any): MIRType { return MIRType.create(jobj.options.map((opt: any) => MIRTypeOption.jparse(opt))); } isTupleTargetType(): boolean { return this.options.every((opt) => opt instanceof MIRTupleType); } isUniqueTupleTargetType(): boolean { return this.isTupleTargetType() && this.options.length === 1; } getUniqueTupleTargetType(): MIRTupleType { return (this.options[0] as MIRTupleType); } isRecordTargetType(): boolean { return this.options.every((opt) => opt instanceof MIRRecordType); } isUniqueRecordTargetType(): boolean { return this.isRecordTargetType() && this.options.length === 1; } getUniqueRecordTargetType(): MIRRecordType { return (this.options[0] as MIRRecordType); } isUniqueCallTargetType(): boolean { if (this.options.length !== 1) { return false; } return this.options[0] instanceof MIREntityType; } getUniqueCallTargetType(): MIREntityType { return this.options[0] as MIREntityType; } } class PackageConfig { //TODO: package.config data jemit(): object { return { }; } static jparse(jobj: any): PackageConfig { return new PackageConfig(); } } class MIRAssembly { readonly package: PackageConfig; readonly srcFiles: { fpath: string, contents: string }[]; readonly srcHash: string; readonly literalRegexs: BSQRegex[] = []; readonly validatorRegexs: Map<MIRResolvedTypeKey, BSQRegex> = new Map<MIRResolvedTypeKey, BSQRegex>(); readonly constantDecls: Map<MIRGlobalKey, MIRConstantDecl> = new Map<MIRGlobalKey, MIRConstantDecl>(); readonly fieldDecls: Map<MIRFieldKey, MIRFieldDecl> = new Map<MIRFieldKey, MIRFieldDecl>(); readonly invokeDecls: Map<MIRInvokeKey, MIRInvokeBodyDecl> = new Map<MIRInvokeKey, MIRInvokeBodyDecl>(); readonly primitiveInvokeDecls: Map<MIRInvokeKey, MIRInvokePrimitiveDecl> = new Map<MIRInvokeKey, MIRInvokePrimitiveDecl>(); readonly virtualOperatorDecls: Map<MIRVirtualMethodKey, MIRInvokeKey[]> = new Map<MIRVirtualMethodKey, MIRInvokeKey[]>(); readonly conceptDecls: Map<MIRResolvedTypeKey, MIRConceptTypeDecl> = new Map<MIRResolvedTypeKey, MIRConceptTypeDecl>(); readonly entityDecls: Map<MIRResolvedTypeKey, MIREntityTypeDecl> = new Map<MIRResolvedTypeKey, MIREntityTypeDecl>(); readonly tupleDecls: Map<MIRResolvedTypeKey, MIRTupleType> = new Map<MIRResolvedTypeKey, MIRTupleType>(); readonly recordDecls: Map<MIRResolvedTypeKey, MIRRecordType> = new Map<MIRResolvedTypeKey, MIRRecordType>(); readonly ephemeralListDecls: Map<MIRResolvedTypeKey, MIREphemeralListType> = new Map<MIRResolvedTypeKey, MIREphemeralListType>(); readonly typeMap: Map<MIRResolvedTypeKey, MIRType> = new Map<MIRResolvedTypeKey, MIRType>(); private m_subtypeRelationMemo: Map<string, Map<string, boolean>> = new Map<string, Map<string, boolean>>(); private m_atomSubtypeRelationMemo: Map<string, Map<string, boolean>> = new Map<string, Map<string, boolean>>(); private getConceptsProvidedByTuple(tt: MIRTupleType): MIRType { let tci: [MIRResolvedTypeKey, string][] = [["NSCore::Some", "Some"]]; if (tt.entries.every((ttype) => this.subtypeOf(ttype, this.typeMap.get("NSCore::APIType") as MIRType))) { tci.push(["NSCore::APIType", "APIType"]); } return MIRType.createSingle(MIRConceptType.create(tci)); } private getConceptsProvidedByRecord(rr: MIRRecordType): MIRType { let tci: [MIRResolvedTypeKey, string][] = [["NSCore::Some", "Some"]]; if (rr.entries.every((entry) => this.subtypeOf(entry.ptype, this.typeMap.get("NSCore::APIType") as MIRType))) { tci.push(["NSCore::APIType", "APIType"]); } return MIRType.createSingle(MIRConceptType.create(tci)); } private atomSubtypeOf_EntityConcept(t1: MIREntityType, t2: MIRConceptType): boolean { const t1e = this.entityDecls.get(t1.typeID) as MIREntityTypeDecl; const mcc = MIRType.createSingle(t2); return t1e.provides.some((provide) => this.subtypeOf(this.typeMap.get(provide) as MIRType, mcc)); } private atomSubtypeOf_ConceptConcept(t1: MIRConceptType, t2: MIRConceptType): boolean { return t2.ckeys.every((c2t) => { return t1.ckeys.some((c1t) => { const c1 = this.conceptDecls.get(c1t) as MIRConceptTypeDecl; const c2 = this.conceptDecls.get(c2t) as MIRConceptTypeDecl; if (c1.ns === c2.ns && c1.name === c2.name) { return true; } return c1.provides.some((provide) => this.subtypeOf(this.typeMap.get(provide) as MIRType, this.typeMap.get(c2t) as MIRType)); }); }); } private atomSubtypeOf_TupleConcept(t1: MIRTupleType, t2: MIRConceptType): boolean { const t2type = this.typeMap.get(t2.typeID) as MIRType; const tcitype = this.getConceptsProvidedByTuple(t1); return this.subtypeOf(tcitype, t2type); } private atomSubtypeOf_RecordConcept(t1: MIRRecordType, t2: MIRConceptType): boolean { const t2type = this.typeMap.get(t2.typeID) as MIRType; const tcitype = this.getConceptsProvidedByRecord(t1); return this.subtypeOf(tcitype, t2type); } private atomSubtypeOf(t1: MIRTypeOption, t2: MIRTypeOption): boolean { let memores = this.m_atomSubtypeRelationMemo.get(t1.typeID); if (memores === undefined) { this.m_atomSubtypeRelationMemo.set(t1.typeID, new Map<string, boolean>()); memores = this.m_atomSubtypeRelationMemo.get(t1.typeID) as Map<string, boolean>; } let memoval = memores.get(t2.typeID); if (memoval !== undefined) { return memoval; } let res = false; if (t1.typeID === t2.typeID) { res = true; } else if (t1 instanceof MIRConceptType && t2 instanceof MIRConceptType) { res = this.atomSubtypeOf_ConceptConcept(t1, t2); } else if (t2 instanceof MIRConceptType) { if (t1 instanceof MIREntityType) { res = this.atomSubtypeOf_EntityConcept(t1, t2); } else if (t1 instanceof MIRTupleType) { res = this.atomSubtypeOf_TupleConcept(t1, t2); } else if (t1 instanceof MIRRecordType) { res = this.atomSubtypeOf_RecordConcept(t1, t2); } else { //fall-through } } else { //fall-through } memores.set(t2.typeID, res); return res; } constructor(pckge: PackageConfig, srcFiles: { fpath: string, contents: string }[], srcHash: string) { this.package = pckge; this.srcFiles = srcFiles; this.srcHash = srcHash; } subtypeOf(t1: MIRType, t2: MIRType): boolean { let memores = this.m_subtypeRelationMemo.get(t1.typeID); if (memores === undefined) { this.m_subtypeRelationMemo.set(t1.typeID, new Map<string, boolean>()); memores = this.m_subtypeRelationMemo.get(t1.typeID) as Map<string, boolean>; } let memoval = memores.get(t2.typeID); if (memoval !== undefined) { return memoval; } const res = (t1.typeID === t2.typeID) || t1.options.every((t1opt) => t2.options.some((t2opt) => this.atomSubtypeOf(t1opt, t2opt))); memores.set(t2.typeID, res); return res; } jemit(): object { return { package: this.package.jemit(), srcFiles: this.srcFiles, srcHash: this.srcHash, literalRegexs: [...this.literalRegexs].map((lre) => lre.jemit()), validatorRegexs: [...this.validatorRegexs].map((vre) => [vre[0], vre[1]]), constantDecls: [...this.constantDecls].map((cd) => [cd[0], cd[1].jemit()]), fieldDecls: [...this.fieldDecls].map((fd) => [fd[0], fd[1].jemit()]), invokeDecls: [...this.invokeDecls].map((id) => [id[0], id[1].jemit()]), primitiveInvokeDecls: [...this.primitiveInvokeDecls].map((id) => [id[0], id[1].jemit()]), virtualOperatorDecls: [...this.virtualOperatorDecls], conceptDecls: [...this.conceptDecls].map((cd) => [cd[0], cd[1].jemit()]), entityDecls: [...this.entityDecls].map((ed) => [ed[0], ed[1].jemit()]), typeMap: [...this.typeMap].map((t) => [t[0], t[1].jemit()]) }; } static jparse(jobj: any): MIRAssembly { let masm = new MIRAssembly(PackageConfig.jparse(jobj.package), jobj.srcFiles, jobj.srcHash); jobj.literalRegexs.forEach((lre: any) => masm.literalRegexs.push(BSQRegex.jparse(lre))); jobj.validatorRegexs.forEach((vre: any) => masm.validatorRegexs.set(vre[0], vre[1])); jobj.constantDecls.forEach((cd: any) => masm.constantDecls.set(cd[0], MIRConstantDecl.jparse(cd[1]))); jobj.fieldDecls.forEach((fd: any) => masm.fieldDecls.set(fd[0], MIRFieldDecl.jparse(fd[1]))); jobj.invokeDecls.forEach((id: any) => masm.invokeDecls.set(id[0], MIRInvokeDecl.jparse(id[1]) as MIRInvokeBodyDecl)); jobj.primitiveInvokeDecls.forEach((id: any) => masm.primitiveInvokeDecls.set(id[0], MIRInvokeDecl.jparse(id[1]) as MIRInvokePrimitiveDecl)); jobj.virtualOperatorDecls.forEach((od: any) => masm.virtualOperatorDecls.set(od[0], od[1])); jobj.conceptDecls.forEach((cd: any) => masm.conceptDecls.set(cd[0], MIROOTypeDecl.jparse(cd[1]) as MIRConceptTypeDecl)); jobj.entityDecls.forEach((id: any) => masm.entityDecls.set(id[0], MIROOTypeDecl.jparse(id[1]) as MIREntityTypeDecl)); jobj.typeMap.forEach((t: any) => masm.typeMap.set(t[0], MIRType.jparse(t[1]))); return masm; } } export { MIRConstantDecl, MIRFunctionParameter, MIRInvokeDecl, MIRInvokeBodyDecl, MIRPCode, MIRInvokePrimitiveDecl, MIRFieldDecl, MIROOTypeDecl, MIRConceptTypeDecl, MIREntityTypeDecl, MIRType, MIRTypeOption, MIREntityType, MIRObjectEntityTypeDecl, MIRConstructableEntityTypeDecl, MIREnumEntityTypeDecl, MIRInternalEntityTypeDecl, MIRPrimitiveInternalEntityTypeDecl, MIRConstructableInternalEntityTypeDecl, MIRPrimitiveCollectionEntityTypeDecl, MIRPrimitiveListEntityTypeDecl, MIRPrimitiveStackEntityTypeDecl, MIRPrimitiveQueueEntityTypeDecl, MIRPrimitiveSetEntityTypeDecl, MIRPrimitiveMapEntityTypeDecl, MIRConceptType, MIRTupleType, MIRRecordType, MIREphemeralListType, PackageConfig, MIRAssembly };
the_stack
* Load up TypeScript */ import * as byots from "byots"; const ensureImport = byots; import * as sw from "../../utils/simpleWorker"; import * as contract from "./lintContract"; import { resolve, timer } from "../../../common/utils"; import * as utils from "../../../common/utils"; import * as types from "../../../common/types"; import { LanguageServiceHost } from "../../../languageServiceHost/languageServiceHostNode"; import { isFileInTypeScriptDir } from "../lang/core/typeScriptDir"; import { ErrorsCache } from "../../utils/errorsCache"; /** Bring in tslint */ import { Configuration, RuleFailure, Linter as LinterLocal } from "tslint"; /** The linter currently in use */ let Linter = LinterLocal; /** TSLint types only used in options */ import { IConfigurationFile } from "../../../../node_modules/tslint/lib/configuration"; /** * Horrible file access :) */ import * as fsu from "../../utils/fsu"; const linterMessagePrefix = `[LINT]` namespace Worker { export const setProjectData: typeof contract.worker.setProjectData = (data) => { /** Load a local linter if any */ const basedir = utils.getDirectory(data.configFile.projectFilePath); return getLocalLinter(basedir).then((linter) => { Linter = linter; LinterImplementation.setProjectData(data); return {}; }) } export const fileSaved: typeof contract.worker.fileSaved = (data) => { LinterImplementation.fileSaved(data); return resolve({}); } } // Ensure that the namespace follows the contract const _checkTypes: typeof contract.worker = Worker; // run worker export const {master} = sw.runWorker({ workerImplementation: Worker, masterContract: contract.master }); /** * The actual linter stuff lives in this namespace */ namespace LinterImplementation { /** The tslint linter takes a few configuration options before it can lint a file */ interface LinterConfig { projectData: types.ProjectDataLoaded; ls: ts.LanguageService; lsh: LanguageServiceHost; /** Only if there is a valid linter config found */ linterConfig?: { configuration: IConfigurationFile, rulesDirectory: string | string[] } } let linterConfig: LinterConfig | null = null; /** We only do this once per project change */ let informedUserAboutMissingConfig: boolean = false; /** Our error cache */ const errorCache = new ErrorsCache(); errorCache.errorsDelta.on(master.receiveErrorCacheDelta); /** * This is the entry point for the linter to start its work */ export function setProjectData(projectData: types.ProjectDataLoaded) { /** Reinit */ errorCache.clearErrors(); informedUserAboutMissingConfig = false; linterConfig = null; /** * Create the program */ const languageServiceHost = new LanguageServiceHost(undefined, projectData.configFile.project.compilerOptions); // Add all the files projectData.filePathWithContents.forEach(({filePath, contents}) => { languageServiceHost.addScript(filePath, contents); }); // And for incremental ones lint again languageServiceHost.incrementallyAddedFile.on((data) => { // console.log(data); // DEBUG loadLintConfigAndLint(); }); const languageService = ts.createLanguageService(languageServiceHost, ts.createDocumentRegistry()); /** * We must call get program before making any changes to the files otherwise TypeScript throws up * we don't actually use the program just yet :) */ const program = languageService.getProgram(); /** * Now create the tslint config */ linterConfig = { projectData, ls: languageService, lsh: languageServiceHost, }; loadLintConfigAndLint(); } /** * Called whenever * - a file is edited * - added to the compilation context */ function loadLintConfigAndLint() { linterConfig.linterConfig = undefined; errorCache.clearErrors(); /** Look for tslint.json by findup from the project dir */ const projectDir = linterConfig.projectData.configFile.projectFileDirectory; const configurationPath = Linter.findConfigurationPath(null, projectDir); // console.log({configurationPath}); // DEBUG /** lint abort if the config is not ready present yet */ if (!configurationPath) { if (!informedUserAboutMissingConfig) { informedUserAboutMissingConfig = true; console.log(linterMessagePrefix, 'No tslint configuration found.'); } return; } /** We have our configuration file. Now lets convert it to configuration :) */ let configuration: IConfigurationFile; try { configuration = Linter.loadConfigurationFromPath(configurationPath); } catch (err) { console.log(linterMessagePrefix, 'Invalid config:', configurationPath); errorCache.setErrorsByFilePaths([configurationPath], [types.makeBlandError(configurationPath, err.message, 'linter')]); return; } /** Also need to setup the rules directory */ const possiblyRelativeRulesDirectory = configuration.rulesDirectory; const rulesDirectory = Linter.getRulesDirectories(possiblyRelativeRulesDirectory, configurationPath); /** * The linter config is now also good to go */ linterConfig.linterConfig = { configuration, rulesDirectory } /** Now start the lazy lint */ lintWithCancellationToken(); } /** lint support cancellation token */ let cancellationToken = utils.cancellationToken(); function lintWithCancellationToken() { /** Cancel any previous */ if (cancellationToken) { cancellationToken.cancel(); cancellationToken = utils.cancellationToken(); } const program = linterConfig.ls.getProgram(); const sourceFiles = program.getSourceFiles() .filter(x => !x.isDeclarationFile); console.log(linterMessagePrefix, 'About to start linting files: ', sourceFiles.length); // DEBUG // Note: tslint is a big stingy with its definitions so we use `any` to make our ts def compat with its ts defs. const lintprogram = program as any; /** Used to push to the errorCache */ const filePaths: string[] = []; let errors: types.CodeError[] = []; const time = timer(); /** create the Linter for each file and get its output */ utils .cancellableForEach({ cancellationToken, items: sourceFiles, cb: (sf => { const filePath = sf.fileName; const contents = sf.getFullText(); const linter = new Linter({ rulesDirectory: linterConfig.linterConfig.rulesDirectory, fix: false, }, lintprogram); linter.lint(filePath, contents, linterConfig.linterConfig.configuration); const lintResult = linter.getResult(); filePaths.push(filePath); if (lintResult.errorCount || lintResult.warningCount) { // console.log(linterMessagePrefix, filePath, lintResult.failureCount); // DEBUG errors = errors.concat( lintResult.failures.map( le => lintErrorToCodeError(le, contents) ) ); } }) }) .then((res) => { /** Push to errorCache */ errorCache.setErrorsByFilePaths(filePaths, errors); console.log(linterMessagePrefix, 'Lint complete', time.seconds); }) .catch((e) => { if (e === utils.cancelled) { console.log(linterMessagePrefix, 'Lint cancelled'); } else { console.log(linterMessagePrefix, 'Linter crashed', e); } }); } export function fileSaved({filePath}: { filePath: string }) { if (!linterConfig) { return; } /** tslint : do the whole thing */ if (filePath.endsWith('tslint.json')) { loadLintConfigAndLint(); return; } /** * Now only proceed further if we have a linter config * and the file is a ts file * and in the current project */ if (!linterConfig.linterConfig) { return; } if (!filePath.endsWith('.ts')) { return; } const sf = linterConfig.ls.getProgram().getSourceFiles().find(sf => sf.fileName === filePath); if (!sf) { return; } /** Update the file contents (so that when we get the program it just works) */ linterConfig.lsh.setContents(filePath, fsu.readFile(sf.fileName)); /** * Since we use program and types flow we would still need to lint the whole thing */ lintWithCancellationToken(); } /** Utility */ function lintErrorToCodeError(lintError: RuleFailure, contents: string): types.CodeError { const start = lintError.getStartPosition().getLineAndCharacter(); const end = lintError.getEndPosition().getLineAndCharacter(); const preview = contents.substring( lintError.getStartPosition().getPosition(), lintError.getEndPosition().getPosition() ); const result: types.CodeError = { source: 'linter', filePath: lintError.getFileName(), message: lintError.getFailure(), from: { line: start.line, ch: start.character }, to: { line: end.line, ch: end.character }, preview: preview, level: 'warning', } return result; } } /** * From * https://github.com/AtomLinter/linter-tslint/blob/2c8e99da92f9f2392adf26f5dd49d78a1a4ef753/lib/main.js */ const TSLINT_MODULE_NAME = 'tslint'; import * as requireResolve from 'resolve'; function getLocalLinter(basedir: string) { return new Promise<typeof LinterLocal>(resolve => requireResolve(TSLINT_MODULE_NAME, { basedir }, (err, linterPath, pkg) => { let linter; if (!err && pkg && /^4\./.test(pkg.version)) { linter = (require(linterPath) as any).Linter; } else { linter = LinterLocal; } return resolve(linter); }, ), ); }
the_stack
import { Nodes, PhaseFlags } from '../nodes'; import { walkPreOrder } from '../walker'; import { LysSemanticError } from '../NodeError'; import { annotations } from '../annotations'; import { ParsingContext } from '../ParsingContext'; import { printNode } from '../../utils/nodePrinter'; import { getAST } from './canonicalPhase'; import assert = require('assert'); function externDecorator( decorator: Nodes.DecoratorNode, parsingContext: ParsingContext, target: Nodes.FunDirectiveNode ) { if (decorator.args.length !== 2) { parsingContext.messageCollector.error( '"extern" requires two arguments, module and function name', decorator.decoratorName.astNode ); } let moduleName: string | null = null; let functionName: string | null = null; if (decorator.args[0]) { if (decorator.args[0] instanceof Nodes.StringLiteral && decorator.args[0].value.length) { moduleName = decorator.args[0].value; } else { parsingContext.messageCollector.error('module must be a string', decorator.args[0].astNode); } } if (decorator.args[1]) { if (decorator.args[1] instanceof Nodes.StringLiteral && decorator.args[1].value.length) { functionName = decorator.args[1].value; } else { parsingContext.messageCollector.error('functionName must be a string', decorator.args[1].astNode); } } if (moduleName && functionName && target.functionNode.functionName) { target.functionNode.functionName.annotate(new annotations.Extern(moduleName, functionName)); } } function exportDecorator( decorator: Nodes.DecoratorNode, parsingContext: ParsingContext, target: Nodes.FunDirectiveNode ) { if (decorator.args.length > 1) { parsingContext.messageCollector.error( '"export" accepts one argument, the name of the exported element', decorator.decoratorName.astNode ); } let exportedName: string | null = null; if (decorator.args[0]) { if (decorator.args[0] instanceof Nodes.StringLiteral && decorator.args[0].value.length) { exportedName = decorator.args[0].value; } else { parsingContext.messageCollector.error('exportedName must be a string', decorator.args[0].astNode); } } else { exportedName = target.functionNode.functionName.name; } if (exportedName) { target.functionNode.functionName.annotate(new annotations.Export(exportedName)); } } function inlineDecorator( decorator: Nodes.DecoratorNode, parsingContext: ParsingContext, target: Nodes.FunDirectiveNode ) { if (decorator.args.length !== 0) { parsingContext.messageCollector.error('"inline" takes no arguments', decorator.decoratorName.astNode); } target.functionNode.functionName.annotate(new annotations.Inline()); } function getterSetterMethodDecorator( decorator: Nodes.DecoratorNode, parsingContext: ParsingContext, target: Nodes.FunDirectiveNode ) { if (decorator.args.length !== 0) { parsingContext.messageCollector.error( `"${decorator.decoratorName.name}" takes no arguments`, decorator.decoratorName.astNode ); } switch (decorator.decoratorName.name) { case 'getter': target.functionNode.functionName.annotate(new annotations.Getter()); return; case 'setter': target.functionNode.functionName.annotate(new annotations.Setter()); return; case 'method': target.functionNode.functionName.annotate(new annotations.Method()); return; } target.functionNode.functionName.annotate(new annotations.Inline()); } function explicitDecorator( decorator: Nodes.DecoratorNode, parsingContext: ParsingContext, target: Nodes.FunDirectiveNode ) { if (decorator.args.length !== 0) { parsingContext.messageCollector.error( `"${decorator.decoratorName.name}" takes no arguments`, decorator.decoratorName.astNode ); } target.functionNode.functionName.annotate(new annotations.Explicit()); } function processFunctionDecorations(node: Nodes.FunDirectiveNode, parsingContext: ParsingContext) { if (node && node.decorators && node.decorators.length) { node.decorators.forEach($ => { switch ($.decoratorName.name) { case 'extern': return externDecorator($, parsingContext, node); case 'inline': return inlineDecorator($, parsingContext, node); case 'getter': case 'setter': case 'method': return getterSetterMethodDecorator($, parsingContext, node); case 'explicit': return explicitDecorator($, parsingContext, node); case 'export': return exportDecorator($, parsingContext, node); default: parsingContext.messageCollector.error( `Unknown decorator "${$.decoratorName.name}" for Function`, $.decoratorName.astNode ); } }); } } function rejectDecorator(node: Nodes.DirectiveNode, parsingContext: ParsingContext) { if (node && node.decorators && node.decorators.length) { node.decorators.forEach($ => { parsingContext.messageCollector.error( `Unknown decorator "${$.decoratorName.name}" for ${node.nodeName}`, $.decoratorName.astNode ); }); } } const overloadFunctions = function( document: Nodes.Node & { directives: Nodes.DirectiveNode[] }, parsingContext: ParsingContext ) { const overloadedFunctions: Map<string, Nodes.OverloadedFunctionNode> = new Map(); document.directives.slice().forEach((node: Nodes.DirectiveNode, ix: number) => { if (node instanceof Nodes.FunDirectiveNode) { processFunctionDecorations(node, parsingContext); const functionName = node.functionNode.functionName.name; const x = overloadedFunctions.get(functionName); if (x && x instanceof Nodes.OverloadedFunctionNode) { x.functions.push(node); node.functionNode.parent = x; } else { const overloaded = new Nodes.OverloadedFunctionNode( node.astNode, new Nodes.NameIdentifierNode(node.functionNode.functionName.astNode, functionName) ); overloaded.isPublic = node.isPublic; overloaded.annotate(new annotations.Injected()); overloaded.functions = [node]; node.functionNode.parent = overloaded; overloadedFunctions.set(functionName, overloaded); document.directives[ix] = overloaded; } } else { if (node) { rejectDecorator(node, parsingContext); if (node instanceof Nodes.ImplDirective) { overloadFunctions(node, parsingContext); } else if (node instanceof Nodes.TraitDirectiveNode) { node.directives.forEach($ => { if ($ instanceof Nodes.FunDirectiveNode) { if ($.functionNode.body) { parsingContext.messageCollector.error( `Unexpected function body. Traits only accept signatures.`, $.functionNode.body.astNode ); } if ($.decorators.length > 0) { $.decorators.forEach($ => { parsingContext.messageCollector.error( `Unexpected decorator. Traits only accept signatures.`, $.astNode ); }); } } }); overloadFunctions(node, parsingContext); } } } }); document.directives = document.directives.filter($ => !($ instanceof Nodes.FunDirectiveNode)); return document; }; function processStruct( node: Nodes.StructDeclarationNode, parsingContext: ParsingContext, document: Nodes.DocumentNode, isPublic: boolean ): Nodes.DirectiveNode[] { const args = node.parameters.map($ => printNode($)).join(', '); const typeName = node.declaredName.name; const typeDirective = new Nodes.TypeDirectiveNode(node.astNode, node.declaredName); typeDirective.isPublic = isPublic; const signature = new Nodes.StructTypeNode(node.astNode, []); typeDirective.valueType = signature; typeDirective.annotate(new annotations.Injected()); if (node.parameters.length) { const accessors = node.parameters .map((param, i) => { signature.parameters.push(param); const parameterName = param.parameterName.name; const parameterType = printNode(param.parameterType!); if (param.parameterType instanceof Nodes.UnionTypeNode) { return ` #[getter] fun ${parameterName}(self: ${typeName}): ${parameterType} = property$${i}(self) #[setter] fun ${parameterName}(self: ${typeName}, value: ${parameterType}): void = property$${i}(self, value) #[inline] private fun property$${i}(self: ${typeName}): ${parameterType} = loadPropertyWithOffset$${i}( self, ${typeName}.^property$${i}_offset ) #[inline] private fun property$${i}(self: ${typeName}, value: ${parameterType}): void = storePropertyWithOffset$${i}( self, value, ${typeName}.^property$${i}_offset ) #[inline] private fun loadPropertyWithOffset$${i}(self: ${typeName}, offset: u32): ${parameterType} = %wasm { (i64.load (i32.add (local.get $offset) (call $addressFromRef (local.get $self)) ) ) } #[inline] private fun storePropertyWithOffset$${i}(self: ${typeName}, value: ${parameterType}, offset: u32): void = %wasm { (i64.store (i32.add (local.get $offset) (call $addressFromRef (local.get $self)) ) (local.get $value) ) } `; } else { return ` #[getter] fun ${parameterName}(self: ${typeName}): ${parameterType} = property$${i}(self) #[setter] fun ${parameterName}(self: ${typeName}, value: ${parameterType}): void = property$${i}(self, value) /* ${param.parameterType!.nodeName} */ #[inline] private fun property$${i}(self: ${typeName}): ${parameterType} = ${parameterType}.load(self, ${typeName}.^property$${i}_offset) #[inline] private fun property$${i}(self: ${typeName}, value: ${parameterType}): void = ${parameterType}.store(self, value, ${typeName}.^property$${i}_offset) `; } }) .join('\n'); const callRefs = node.parameters.map((_, i) => `property$${i}($ref, ${printNode(_.parameterName)})`).join('\n'); const canonical = getAST( document.fileName + '#' + typeName, document.moduleName + '#' + typeName, ` impl Reference for ${typeName} { #[inline] fun is(a: Self | ref): boolean = { val discriminant: u32 = Self.^discriminant ref.getDiscriminant(a) == discriminant } #[explicit] #[inline] fun as(lhs: Self): ref = %wasm { (local.get $lhs) } } impl ${typeName} { #[inline] private fun ${typeName}$discriminant(): u64 = { val discriminant: u32 = ${typeName}.^discriminant discriminant as u64 << 32 } #[inline] fun apply(${args}): ${typeName} = { var $ref = fromPointer( system::core::memory::calloc(1 as u32, ${typeName}.^allocationSize) ) ${callRefs} $ref } /** * CPointer implicit coercion. */ fun as(self: ${typeName}): UnsafeCPointer = %wasm { (call $addressFromRef (get_local $self)) } private fun fromPointer(ptr: u32): ${typeName} = %wasm { (i64.or (call $${typeName}$discriminant) (i64.extend_u/i32 (local.get $ptr)) ) } fun ==(a: ${typeName}, b: ${typeName}): boolean = %wasm { (i64.eq (local.get $a) (local.get $b) ) } fun !=(a: ${typeName}, b: ${typeName}): boolean = %wasm { (i64.ne (local.get $a) (local.get $b) ) } ${accessors} fun store(lhs: ref, rhs: ${typeName}, offset: u32): void = %wasm { (i64.store (i32.add (local.get $offset) (call $addressFromRef (local.get $lhs)) ) (local.get $rhs) ) } fun load(lhs: ref, offset: u32): ${typeName} = %wasm { (i64.load (i32.add (local.get $offset) (call $addressFromRef (local.get $lhs)) ) ) } } `, parsingContext ); return [typeDirective, ...(canonical.directives || [])]; } else { const canonical = getAST( document.fileName + '#' + typeName, document.moduleName + '#' + typeName, ` impl Reference for ${typeName} { #[inline] fun is(a: Self | ref): boolean = { val discriminant: u32 = Self.^discriminant ref.getDiscriminant(a) == discriminant } #[explicit] #[inline] fun as(lhs: Self): ref = %wasm { (local.get $lhs) } } impl ${typeName} { #[inline] private fun ${typeName}$discriminant(): i64 = { val discriminant: u32 = ${typeName}.^discriminant discriminant as i64 << 32 } #[inline] fun apply(): ${typeName} = %wasm { (call $${typeName}$discriminant) } fun ==(a: ${typeName}, b: ref): boolean = %wasm { (i64.eq (local.get $a) (local.get $b) ) } fun !=(a: ${typeName}, b: ref): boolean = %wasm { (i64.ne (local.get $a) (local.get $b) ) } fun store(lhs: ref, rhs: ${typeName}, offset: u32): void = %wasm { (i64.store (i32.add (local.get $offset) (call $addressFromRef (local.get $lhs)) ) (local.get $rhs) ) } fun load(lhs: ref, offset: u32): ${typeName} = %wasm { (i64.load (i32.add (local.get $offset) (call $addressFromRef (local.get $lhs)) ) ) } } `, parsingContext ); return [typeDirective, ...(canonical.directives || [])]; } } const preprocessStructs = function( container: Nodes.Node & { directives: Nodes.DirectiveNode[] }, parsingContext: ParsingContext, document: Nodes.DocumentNode ) { container.directives.slice().forEach((node: Nodes.Node) => { if (node instanceof Nodes.EnumDirectiveNode) { const newTypeNode = new Nodes.TypeDirectiveNode(node.astNode, node.variableName); const union = (newTypeNode.valueType = new Nodes.UnionTypeNode(node.astNode)); union.of = []; newTypeNode.isPublic = node.isPublic; const newDirectives: Nodes.DirectiveNode[] = [newTypeNode]; const implDirectives: Nodes.DirectiveNode[] = []; node.declarations.forEach($ => { const [decl, ...impl] = processStruct($, parsingContext, document, node.isPublic); newDirectives.push(decl); implDirectives.push(...impl); const refNode = new Nodes.ReferenceNode( $.declaredName.astNode, Nodes.QNameNode.fromString($.declaredName.name, $.declaredName.astNode) ); union.of.push(refNode); }); container.directives.splice(container.directives.indexOf(node), 1, ...newDirectives, ...implDirectives); } else if (node instanceof Nodes.StructDeclarationNode) { const newDirectives = processStruct(node, parsingContext, document, node.isPublic); container.directives.splice(container.directives.indexOf(node as any), 1, ...newDirectives); } }); return container; }; const processUnions = function( containerNode: Nodes.Node & { directives: Nodes.DirectiveNode[] }, parsingContext: ParsingContext, document: Nodes.DocumentNode ) { containerNode.directives.slice().forEach((node: Nodes.Node) => { if (node instanceof Nodes.TypeDirectiveNode) { const { valueType, variableName } = node; if (!valueType) { parsingContext.messageCollector.error(`Missing type value`, (variableName || node).astNode); return; } if (valueType instanceof Nodes.UnionTypeNode) { const referenceTypes = valueType.of.filter($ => $ instanceof Nodes.ReferenceNode) as Nodes.ReferenceNode[]; if (valueType.of.length !== referenceTypes.length) { // error? } let injectedDirectives: string[] = []; if (referenceTypes.length) { referenceTypes.forEach($ => { injectedDirectives.push(` impl ${$.variable.text} { fun as(lhs: ${$.variable.text}): ${variableName.name} = %wasm { (local.get $lhs) } } `); }); } const canonical = getAST( document.fileName + '#' + variableName.name, document.moduleName + '#' + variableName.name, ` impl Reference for ${variableName.name} { #[inline] fun is(self: ${variableName.name} | ref): boolean = { ${referenceTypes.map($ => 'self is ' + printNode($.variable)).join(' || ') || 'false'} } #[explicit] #[inline] fun as(self: ${variableName.name}): ref = %wasm { (local.get $self) } } // Union type ${variableName.name} impl ${variableName.name} { fun ==(lhs: ref, rhs: ref): boolean = lhs == rhs fun !=(lhs: ref, rhs: ref): boolean = lhs != rhs fun store(lhs: ref, rhs: ${variableName.name}, offset: u32): void = %wasm { (i64.store (i32.add (local.get $offset) (call $addressFromRef (local.get $lhs)) ) (local.get $rhs) ) } fun load(lhs: ref, offset: u32): ${variableName.name} = %wasm { (i64.load (i32.add (local.get $offset) (call $addressFromRef (local.get $lhs)) ) ) } } ${injectedDirectives.join('\n')} `, parsingContext ); containerNode.directives.splice(containerNode.directives.indexOf(node) + 1, 0, ...(canonical.directives || [])); } } }); return containerNode; }; const validateSignatures = walkPreOrder((node: Nodes.Node, parsingContext, _1: Nodes.Node | null) => { if (node instanceof Nodes.FunctionNode) { let used: string[] = []; node.parameters.forEach(param => { if (used.indexOf(param.parameterName.name) === -1) { used.push(param.parameterName.name); } else { parsingContext.messageCollector.error(`Duplicated parameter "${param.parameterName.name}"`, param.astNode); } }); if (!node.functionReturnType) { parsingContext.messageCollector.error('Missing return type in function declaration', node.astNode); } if (!node.body && !node.hasAnnotation(annotations.SignatureDeclaration)) { parsingContext.messageCollector.error('Missing function body', node.astNode); } } else if (node instanceof Nodes.PatternMatcherNode) { if (node.matchingSet.length === 0) { throw new LysSemanticError(`Invalid match expression, there are no matchers`, node); } if (node.matchingSet.length === 1 && node.matchingSet[0] instanceof Nodes.MatchDefaultNode) { throw new LysSemanticError(`This match is useless`, node); } } }); const validateInjectedWasm = walkPreOrder((node: Nodes.Node, _, _1: Nodes.Node | null) => { if (node instanceof Nodes.WasmAtomNode) { if (node.symbol === 'call' || node.symbol === 'global.get' || node.symbol === 'global.set') { if (!node.args[0]) { throw new LysSemanticError(`Missing name`, node); } if (node.args[0] instanceof Nodes.ReferenceNode === false) { throw new LysSemanticError(`Here you need a fully qualified name starting with $`, node.args[0]); } } } }); const processDeconstruct = walkPreOrder((node: Nodes.Node, _, _parent: Nodes.Node | null) => { if (node instanceof Nodes.MatchCaseIsNode) { if (!node.declaredName) { node.declaredName = Nodes.NameIdentifierNode.fromString('$', node.astNode); } if (node.deconstructorNames && node.deconstructorNames.length) { /** * struct Node(value: i32) * match x { * case x is Node(theValue) -> theValue * ... * } * * roughly desugars to * * struct Node(value: i32) * match x { * case x is Node -> { * val theValue = x.value * theValue * } * ... * } */ const newBlock = node.rhs instanceof Nodes.BlockNode ? node.rhs : new Nodes.BlockNode(node.rhs.astNode, []); node.deconstructorNames.reverse().forEach($ => { if ($.name !== '_') { const ref = new Nodes.ReferenceNode( node.declaredName!.astNode, Nodes.QNameNode.fromString(node.declaredName!.name, node.declaredName!.astNode) ); const rhs = new Nodes.NameIdentifierNode($.astNode, $.name); const member = new Nodes.MemberNode($.astNode, ref, '.', rhs); const decl = new Nodes.VarDeclarationNode($.astNode, $, member); newBlock.statements.unshift(decl); } }); node.deconstructorNames.length = 0; if (newBlock !== node.rhs) { newBlock.statements.push(node.rhs); node.rhs = newBlock; } } } }); export function executeSemanticPhase(moduleName: string, parsingContext: ParsingContext) { const document = parsingContext.getParsingPhaseForModule(moduleName); assert(document.analysis.nextPhase === PhaseFlags.Semantic); preprocessStructs(document, parsingContext, document); processUnions(document, parsingContext, document); processDeconstruct(document, parsingContext); overloadFunctions(document, parsingContext); validateSignatures(document, parsingContext); validateInjectedWasm(document, parsingContext); document.analysis.nextPhase++; }
the_stack
import type * as es from 'elasticsearch'; import * as ts from '@terascope/utils'; import { xLuceneTypeConfig } from '@terascope/types'; import { CachedTranslator, QueryAccess, RestrictOptions } from 'xlucene-translator'; import { toXluceneQuery, xLuceneQueryResult } from '@terascope/data-mate'; import IndexManager from './index-manager'; import * as i from './interfaces'; import * as utils from './utils'; /** * A single index elasticsearch-store with some specific requirements around * the index name, and record data */ export default class IndexStore<T extends ts.AnyObject> { readonly client: es.Client; readonly config: i.IndexConfig<T>; readonly manager: IndexManager; readonly name: string; refreshByDefault = true; readonly esVersion: number; protected _defaultQueryAccess: QueryAccess<T>|undefined; readonly xLuceneTypeConfig: xLuceneTypeConfig; readonly writeHooks = new Set<WriteHook<T>>(); readonly readHooks = new Set<ReadHook<T>>(); private _interval: any; private readonly _logger: ts.Logger; private readonly _collector: ts.Collector<BulkRequest<Partial<T>>>; private readonly _bulkMaxWait: number = 10000; private readonly _bulkMaxSize: number = 500; private readonly _getEventTime: (input: T) => number; private readonly _getIngestTime: (input: T) => number; private readonly _translator = new CachedTranslator(); constructor(client: es.Client, config: i.IndexConfig<T>) { if (!utils.isValidClient(client)) { throw new ts.TSError('IndexStore requires elasticsearch client', { fatalError: true, }); } utils.validateIndexConfig(config); this.client = client; this.config = config; this.name = utils.toInstanceName(this.config.name); this.manager = new IndexManager(client, config.enable_index_mutations); this.esVersion = this.manager.esVersion; if (this.config.bulk_max_size != null) { this._bulkMaxSize = this.config.bulk_max_size; } if (this.config.bulk_max_wait != null) { this._bulkMaxWait = this.config.bulk_max_wait; } const debugLoggerName = `elasticsearch-store:index-store:${config.name}`; this._logger = config.logger || ts.debugLogger(debugLoggerName); this._collector = new ts.Collector({ size: this._bulkMaxSize, wait: this._bulkMaxWait, }); this.xLuceneTypeConfig = config.data_type.toXlucene(); if (config.data_schema != null) { const validator = utils.makeDataValidator(config.data_schema, this._logger); this.writeHooks.add(validator); const validateOnRead = config.data_schema.validate_on_read ?? true; if (validateOnRead) { this.readHooks.add(validator); } } this._getIngestTime = utils.getTimeByField(this.config.ingest_time_field as string); this._getEventTime = utils.getTimeByField(this.config.event_time_field as string); this._defaultQueryAccess = config.default_query_access; } /** * The most current indexed used to write to */ get writeIndex(): string { return this.manager.formatIndexName(this.config, false); } /** * The index typically used for searching across all of the open indices */ get searchIndex(): string { return this.manager.formatIndexName(this.config); } /** * Safely add a create, index, or update requests to the bulk queue * * This method will batch messages using the configured * bulk max size and wait configuration. * * @todo we need to add concurrency support for sending multiple bulk requests in flight */ async bulk(action: 'delete', id?: string): Promise<void>; async bulk(action: 'index' | 'create', doc?: Partial<T>, id?: string): Promise<void>; async bulk(action: 'update', doc?: Partial<T>, id?: string): Promise<void>; async bulk(action: i.BulkAction, ...args: any[]): Promise<void> { const metadata: BulkRequestMetadata = {}; metadata[action] = this.esVersion >= 7 ? { _index: this.writeIndex, } : { _index: this.writeIndex, _type: this.config.name, }; let data: BulkRequestData<Partial<T>> = null; let id: string; if (action !== 'delete') { if (action === 'update') { const doc = this._runWriteHooks(args[0], false); /** * TODO: Support more of the update formats */ data = { doc }; } else { data = this._runWriteHooks(args[0], true); } // eslint-disable-next-line prefer-destructuring id = args[1]; } else { ([id] = args); } if (id) { utils.validateId(id, `bulk->${action}`); metadata[action]!._id = id; } this._collector.add({ data, metadata, }); return this.flush(); } /** Count records by a given Lucene Query */ async count( query = '', options?: RestrictOptions, queryAccess?: QueryAccess<T> ): Promise<number> { const p = this._translateQuery(query, options, queryAccess) as es.CountParams; return this.countRequest(p); } /** Count records by a given Elasticsearch Query DSL */ async countRequest(params: es.CountParams): Promise<number> { return ts.pRetry(async () => { const { count } = await this.client.count(this.getDefaultParams<es.CountParams>( this.searchIndex, params )); return count; }, utils.getRetryConfig()); } /** * Create a document with an id * * @returns the created record */ async createById( id: string, doc: Partial<T>, params?: PartialParam<es.CreateDocumentParams, 'id' | 'body'> ): Promise<T> { utils.validateId(id, 'createById'); return this.create(doc, Object.assign({}, params, { id })); } /** * Create a document but will throw if doc already exists * * @returns the created record */ async create(doc: Partial<T>, params?: PartialParam<es.CreateDocumentParams, 'body'>): Promise<T> { const record = this._runWriteHooks(doc, true); const defaults = { refresh: this.refreshByDefault }; const p = this.getDefaultParams<es.CreateDocumentParams>( this.writeIndex, defaults, params, { body: record } ); const result = await ts.pRetry( () => this.client.create(p), utils.getRetryConfig() ); return this._toRecord({ ...result, _source: record }); } async flush(flushAll = false): Promise<void> { const records = flushAll ? this._collector.flushAll() : this._collector.getBatch(); if (!records || !records.length) return; this._logger.debug(`Flushing ${records.length} requests to ${this.writeIndex}`); const bulkRequest: any[] = []; for (const { data, metadata } of records) { bulkRequest.push(metadata); if (data != null) bulkRequest.push(data); } await ts.pRetry(() => this._bulk(records, bulkRequest), utils.getRetryConfig()); } /** Get a single document */ async get(id: string, params?: PartialParam<es.GetParams>): Promise<T> { utils.validateId(id, 'get'); const p = this.getDefaultParams(this.writeIndex, params, { id }); const result = await ts.pRetry( () => this.client.get(p as es.GetParams) as Promise<RecordResponse<T>>, utils.getRetryConfig() ); return this._toRecord(result); } /** * Connect and validate the index configuration. */ async initialize(): Promise<void> { await this.manager.indexSetup(this.config); const ms = Math.round(this._bulkMaxWait / 2); this._interval = setInterval(() => { this.flush().catch((err) => { this._logger.error(err, 'Failure flushing in the background'); }); }, ms); } /** * Index a document */ async index(doc: T | Partial<T>, params?: PartialParam<es.IndexDocumentParams<T>, 'body'>): Promise<T> { const body = this._runWriteHooks(doc, true); const defaults = { refresh: this.refreshByDefault }; const p = this.getDefaultParams<es.IndexDocumentParams<T>>( this.writeIndex, defaults, params, { body } ); const result = await ts.pRetry(() => this.client.index(p), utils.getRetryConfig()); result._source = doc; return this._toRecord(result); } /** * A convenience method for indexing a document with an ID */ async indexById( id: string, doc: T | Partial<T>, params?: PartialParam<es.IndexDocumentParams<T>, 'index' | 'type' | 'id'> ): Promise<T> { utils.validateId(id, 'indexById'); return this.index(doc, Object.assign({}, params, { id })); } /** Get multiple documents at the same time */ async mget(body: unknown, params?: PartialParam<es.MGetParams>): Promise<T[]> { const p = this.getDefaultParams(this.writeIndex, params, { body }); const docs = await ts.pRetry(async () => { const result = await this.client.mget<T>(p); return result.docs || []; }, utils.getRetryConfig()); return this._toRecords(docs, true); } /** @see IndexManager#migrateIndex */ migrateIndex(options: i.MigrateIndexStoreOptions): Promise<any> { return this.manager.migrateIndex<T>({ ...options, config: this.config }); } /** * Refreshes the current index */ async refresh(params?: PartialParam<es.IndicesRefreshParams>): Promise<void> { const p = Object.assign( { index: this.writeIndex, }, params ); await ts.pRetry(() => this.client.indices.refresh(p), utils.getRetryConfig()); } /** * Deletes a document for a given id */ async deleteById(id: string, params?: PartialParam<es.DeleteDocumentParams>): Promise<void> { utils.validateId(id, 'deleteById'); const p = this.getDefaultParams<es.DeleteDocumentParams>( this.writeIndex, { refresh: this.refreshByDefault, }, params, { id, } ); await ts.pRetry(() => this.client.delete(p), utils.getRetryConfig()); } /** * Shutdown, flush any pending requests and cleanup */ async shutdown(): Promise<void> { if (this._interval != null) { clearInterval(this._interval); } if (this._collector.length) { this._logger.info(`Flushing ${this._collector.length} records on shutdown`); await this.flush(true); } } /** Update a document with a given id */ async update(id: string, body: UpdateBody<T>, params?: PartialParam<es.UpdateDocumentParams, 'body' | 'id'>): Promise<void> { utils.validateId(id, 'update'); const defaults = { refresh: this.refreshByDefault, retryOnConflict: 3, }; const _body = body as any; if (_body.doc) { const doc = this._runWriteHooks(_body.doc, false); _body.doc = doc; } const p = this.getDefaultParams<es.UpdateDocumentParams>( this.writeIndex, defaults, params, { id, body: _body } ); await ts.pRetry(() => this.client.update(p), utils.getRetryConfig()); } /** Safely apply updates to a document by applying the latest changes */ async updatePartial( id: string, applyChanges: ApplyPartialUpdates<T>, retriesOnConflict = 3 ): Promise<T> { utils.validateId('updatePartial', id); try { const existing = await this.get(id) as any; const params: any = {}; if (ts.DataEntity.isDataEntity(existing)) { if (this.esVersion >= 7) { params.if_seq_no = existing.getMetadata('_seq_no'); params.if_primary_term = existing.getMetadata('_primary_term'); } else { params.version = existing.getMetadata('_version'); } } return await this.indexById( id, await applyChanges(existing), params ); } catch (error) { // if there is a version conflict if (error.statusCode === 409 && error.message.includes('version conflict')) { return this.updatePartial(id, applyChanges, retriesOnConflict - 1); } throw error; } } getDefaultParams<P extends Record<string, any> = { index: string; [prop: string]: any }>( index: string, ...params: ((Partial<P> & Record<string, any>)|undefined)[] ): P { return Object.assign( this.esVersion >= 7 ? { index, } : { index, type: this.config.name, }, ...params ) as P; } async countBy( fields: AnyInput<T>, joinBy?: JoinBy, options?: RestrictOptions, queryAccess?: QueryAccess<T>, ): Promise<number> { const { query, variables } = this.createJoinQuery(fields, joinBy, options?.variables); return this.count(query, { variables }, queryAccess); } async exists( id: string[] | string, options?: RestrictOptions, queryAccess?: QueryAccess<T> ): Promise<boolean> { const ids = utils.validateIds(id, 'exists'); if (!ids.length) return true; const count = await this.countBy({ [this.config.id_field!]: ids, } as AnyInput<T>, 'AND', options, queryAccess); return count === ids.length; } async findBy( fields: AnyInput<T>, joinBy?: JoinBy, options?: i.FindOneOptions<T>, queryAccess?: QueryAccess<T> ): Promise<T> { const { query, variables } = this.createJoinQuery(fields, joinBy, options?.variables); const { results } = await this.search( query, { ...options, size: 1, variables }, queryAccess, true ); const record = ts.getFirst(results); if (record == null) { let errQuery = query; for (const [key, value] of Object.entries(variables)) { errQuery = errQuery.replace(`$${key}`, value); } throw new ts.TSError(`Unable to find ${this.name} by ${errQuery}`, { statusCode: 404, }); } return record; } async findAllBy( fields: AnyInput<T>, joinBy?: JoinBy, options?: i.FindOptions<T>, queryAccess?: QueryAccess<T> ): Promise<T[]> { const { query, variables } = this.createJoinQuery(fields, joinBy, options?.variables); const { results } = await this.search( query, { variables, size: 10000, ...options }, queryAccess, false ); return results; } async findById( id: string, options?: i.FindOneOptions<T>, queryAccess?: QueryAccess<T> ): Promise<T> { utils.validateId(id, 'findById'); const fields = { [this.config.id_field!]: id } as AnyInput<T>; return this.findBy(fields, 'AND', options, queryAccess); } async findAndApply( updates: Partial<T> | undefined, options?: i.FindOneOptions<T>, queryAccess?: QueryAccess<T> ): Promise<Partial<T>> { if (ts.isEmpty(updates) || !ts.isPlainObject(updates)) { throw new ts.TSError(`Invalid input for ${this.name}`, { statusCode: 422, }); } const id = updates![this.config.id_field as any]; if (!id) return { ...updates }; const current = await this.findById(id, options, queryAccess); return { ...current, ...updates }; } async findAll( ids: string[] | string | undefined, options?: i.FindOneOptions<T>, queryAccess?: QueryAccess<T> ): Promise<T[]> { const _ids = utils.validateIds(ids, 'exists'); if (!_ids.length) return []; const { query, variables } = this.createJoinQuery({ [this.config.id_field!]: _ids } as AnyInput<T>, 'AND', { variables: options?.variables }); const { results: result } = await this.search( query, { ...options, size: _ids.length, variables }, queryAccess, false ); if (result.length !== _ids.length) { const foundIds = result.map((doc) => doc[this.config.id_field as string]); const notFoundIds = _ids.filter((id) => !foundIds.includes(id)); throw new ts.TSError(`Unable to find ${this.name}'s ${notFoundIds.join(', ')}`, { statusCode: 404, }); } // maintain sort order return _ids.map((id) => result.find((doc) => doc[this.config.id_field as string] === id)!); } /** Search with a given Lucene Query */ async search( q = '', options: i.FindOptions<T> = {}, queryAccess?: QueryAccess<T>, critical?: boolean ): Promise<i.SearchResult<T>> { const params: Partial<es.SearchParams> = { size: options.size, sort: options.sort, from: options.from, _sourceExclude: options.excludes as string[], _sourceInclude: options.includes as string[], }; let searchParams: Partial<es.SearchParams>; const _queryAccess = (queryAccess || this._defaultQueryAccess); if (_queryAccess) { searchParams = await _queryAccess.restrictSearchQuery(q, { params, elasticsearch_version: utils.getESVersion(this.client), variables: options.variables }); } else { searchParams = Object.assign( {}, params, this._translateQuery(q, { variables: options.variables }) ); } return this.searchRequest(searchParams, critical); } /** Search using the underlying Elasticsearch Query DSL */ async searchRequest( params: PartialParam<SearchParams<T>>, critical?: boolean ): Promise<i.SearchResult<T>> { const response = await this._search({ sort: this.config.default_sort, ...params, }); const total = ts.get(response, 'hits.total.value', ts.get(response, 'hits.total', 0)); const results = this._toRecords(response.hits.hits, critical); return { _total: total, _fetched: results.length, results, }; } /** Run an aggregation using an Elasticsearch Query DSL */ async aggregate<A = Record<string, any>>( query: Record<string, any>, params?: PartialParam<SearchParams<T>>, ): Promise<A> { const response = await this._search({ ...params, size: 0, body: query }); return response.aggregations; } /** * A small abstraction on client.search with retry support */ protected async _search( params: PartialParam<SearchParams<T>>, ): Promise<es.SearchResponse<T>> { if (this.esVersion >= 7) { const p: any = params; if (p._sourceExclude) { p._sourceExcludes = p._sourceExclude.slice(); delete p._sourceExclude; } if (p._sourceInclude) { p._sourceIncludes = p._sourceInclude.slice(); delete p._sourceInclude; } } const response = await ts.pRetry(async () => this.client.search<T>( this.getDefaultParams<es.SearchParams>( this.searchIndex, params, ) ), utils.getRetryConfig()); const { failures, failed } = response._shards as any; if (failed) { const failureTypes = failures.flatMap((shard: any) => shard.reason.type); const reasons = ts.uniq(failureTypes); if (reasons.length > 1 || reasons[0] !== 'es_rejected_execution_exception') { const errorReason = reasons.join(' | '); throw new ts.TSError(errorReason, { reason: 'Not all shards returned successful, shard errors: ', }); } else { throw new ts.TSError('Retryable Search Failure', { retryable: true, }); } } return response; } createJoinQuery(fields: AnyInput<T>, joinBy: JoinBy = 'AND', variables = {}): xLuceneQueryResult { const result = toXluceneQuery(fields, { joinBy, typeConfig: this.xLuceneTypeConfig, variables }); if (result) return result; return { query: `${ts.getFirstKey(fields)}: "__undefined__"`, variables: {} }; } /** * Append values from an array on a record. * Use with caution, this may not work in all cases. */ async appendToArray( id: string, field: keyof T, values: string[] | string ): Promise<void> { utils.validateId(id, 'appendToArray'); const valueArray = values && ts.uniq(ts.castArray(values)).filter((v) => !!v); if (!valueArray || !valueArray.length) return; await this.update(id, { script: { source: ` for(int i = 0; i < params.values.length; i++) { if (!ctx._source["${field}"].contains(params.values[i])) { ctx._source["${field}"].add(params.values[i]) } } `, lang: 'painless', params: { values: valueArray, }, }, }); } /** * Remove values from an array on a record. * Use with caution, this may not work in all cases. */ async removeFromArray( id: string, field: keyof T, values: string[] | string ): Promise<void> { utils.validateId(id, 'removeFromArray'); const valueArray = values && ts.uniq(ts.castArray(values)).filter((v) => !!v); if (!valueArray || !valueArray.length) return; try { await this.update(id, { script: { source: ` for(int i = 0; i < params.values.length; i++) { if (ctx._source["${field}"].contains(params.values[i])) { int itemIndex = ctx._source["${field}"].indexOf(params.values[i]); ctx._source["${field}"].remove(itemIndex) } } `, lang: 'painless', params: { values: valueArray, }, }, }); } catch (err) { if (err && err.statusCode === 404) { return; } throw err; } } private async _bulk(records: BulkRequest<Partial<T>>[], body: any) { const result: i.BulkResponse = await ts.pRetry( () => this.client.bulk({ body }), { ...utils.getRetryConfig(), retries: 0 } ); const retry = utils.filterBulkRetries(records, result); if (retry.length) { this._logger.warn(`Bulk request to ${this.writeIndex} resulted in ${retry.length} errors`); this._logger.trace('Retrying bulk requests', retry); this._collector.add(retry); } } protected _toRecord(result: RecordResponse<T>, critical = true): T { const doc = this._runReadHooks(this._makeDataEntity(result), critical); if (!doc && critical) { throw new ts.TSError('Record Missing', { statusCode: 410 }); } return doc as T; } protected _toRecords(results: RecordResponse<T>[], critical = false): T[] { return results.map((result) => this._toRecord(result, critical)).filter(Boolean); } private _makeDataEntity(result: RecordResponse<T>): T { return ts.DataEntity.make<T>(result._source, { _key: result._id, _processTime: Date.now(), _ingestTime: this._getIngestTime(result._source), _eventTime: this._getEventTime(result._source), _index: result._index, _type: result._type, _version: result._version, _seq_no: result._seq_no, _primary_term: result._primary_term }) as any; } /** * Run additional validation after retrieving the record from elasticsearch */ private _runReadHooks(doc: T, critical: boolean): T|false { let _doc = doc; for (const hook of this.readHooks) { const result = hook(_doc, critical); if (result == null) { throw new Error('Expected read hook to return a doc or false'); } if (result === false) return false; _doc = result; } return _doc; } /** * Run additional validation before updating or creating the record */ private _runWriteHooks(doc: T|Partial<T>, critical: boolean): T { let _doc = doc; for (const hook of this.writeHooks) { const result = hook(_doc, critical); if (result == null) { throw new Error('Expected write hook to return a doc or to throw'); } _doc = result; } return _doc as T; } private _translateQuery( q: string, options?: RestrictOptions, queryAccess?: QueryAccess<T> ) { const _queryAccess = (queryAccess || this._defaultQueryAccess); const query = _queryAccess ? _queryAccess.restrict(q) : q; const translator = this._translator.make(query, { type_config: this.xLuceneTypeConfig, logger: this._logger, variables: options?.variables }); return { q: undefined, body: translator.toElasticsearchDSL(), }; } } interface BulkRequest<T> { data: BulkRequestData<T>; metadata: BulkRequestMetadata; } type BulkRequestData<T> = T | { doc: Partial<T> } | null; type BulkRequestMetadata = { [key in i.BulkAction]?: { _index: string; _type?: string; _id?: string; } }; interface RecordResponse<T> { _index: string; _type: string; _id: string; _version?: number; _seq_no?: number; _primary_term?: number; _source: T; } type ReservedParams = 'index' | 'type'; type PartialParam<T, E = any> = { [K in Exclude<keyof T, E extends keyof T ? ReservedParams & E : ReservedParams>]?: T[K] }; type SearchParams<T> = ts.Overwrite< es.SearchParams, { q: never; body: never; _source?: (keyof T)[]; _sourceInclude?: (keyof T)[]; _sourceExclude?: (keyof T)[]; } >; type ApplyPartialUpdates<T> = (existing: T) => Promise<T> | T; export type AnyInput<T> = { [P in keyof T]?: T[P] | any }; export type JoinBy = 'AND' | 'OR'; export type UpdateBody<T> = ({ doc: Partial<T> })|({ script: any }); export type WriteHook<T> = (doc: Partial<T>, critical: boolean) => T|Partial<T>; export type ReadHook<T> = (doc: T, critical: boolean) => T|false;
the_stack
/** * @license Copyright © 2013 onwards, Andrew Whewell * All rights reserved. * * Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of the program's contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OF THE SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * @fileoverview A class that can auto-select aircraft based on a set of criteria. */ namespace VRS { /* * Global options */ export var globalOptions: GlobalOptions = VRS.globalOptions || {}; VRS.globalOptions.aircraftAutoSelectEnabled = VRS.globalOptions.aircraftAutoSelectEnabled !== undefined ? VRS.globalOptions.aircraftAutoSelectEnabled : true; // True if auto-select is enabled by default. VRS.globalOptions.aircraftAutoSelectClosest = VRS.globalOptions.aircraftAutoSelectClosest !== undefined ? VRS.globalOptions.aircraftAutoSelectClosest : true; // True if the closest matching aircraft should be auto-selected, false if the furthest matching aircraft should be auto-selected. VRS.globalOptions.aircraftAutoSelectOffRadarAction = VRS.globalOptions.aircraftAutoSelectOffRadarAction || VRS.OffRadarAction.EnableAutoSelect; // What to do when an aircraft goes out of range of the radar. VRS.globalOptions.aircraftAutoSelectFilters = VRS.globalOptions.aircraftAutoSelectFilters || []; // The list of filters that auto-select starts off with. VRS.globalOptions.aircraftAutoSelectFiltersLimit = VRS.globalOptions.aircraftAutoSelectFiltersLimit !== undefined ? VRS.globalOptions.aircraftAutoSelectFiltersLimit : 2; // The maximum number of auto-select filters that we're going to allow. export interface AircraftAutoSelect_SaveState { enabled: boolean; selectClosest: boolean; offRadarAction: OffRadarActionEnum; filters: ISerialisedFilter[]; } /** * A class that can auto-select aircraft on each refresh. */ export class AircraftAutoSelect implements ISelfPersist<AircraftAutoSelect_SaveState> { private _Dispatcher = new VRS.EventHandler({ name: 'VRS.AircraftAutoSelect' }); private _Events = { enabledChanged: 'enabledChanged', aircraftSelectedByIcao: 'aircraftSelectedByIcao' }; private _AircraftList: AircraftList; private _LastAircraftSelected: Aircraft; private _Name: string; private _Enabled: boolean; private _SelectClosest: boolean; private _OffRadarAction: OffRadarActionEnum; private _Filters: AircraftFilter[]; private _AircraftListUpdatedHook: IEventHandle; private _SelectedAircraftChangedHook: IEventHandle; private _SelectAircraftByIcao: string; private _AutoClearSelectAircraftByIcao = true; constructor(aircraftList: AircraftList, name?: string) { this._AircraftList = aircraftList; this._Name = name || 'default'; this._Enabled = VRS.globalOptions.aircraftAutoSelectEnabled; this._SelectClosest = VRS.globalOptions.aircraftAutoSelectClosest; this._OffRadarAction = VRS.globalOptions.aircraftAutoSelectOffRadarAction; this._Filters = VRS.globalOptions.aircraftAutoSelectFilters; this._AircraftListUpdatedHook = aircraftList.hookUpdated(this.aircraftListUpdated, this); this._SelectedAircraftChangedHook = aircraftList.hookSelectedAircraftChanged(this.selectedAircraftChanged, this); } dispose = () => { if(this._AircraftListUpdatedHook) this._AircraftList.unhook(this._AircraftListUpdatedHook); if(this._SelectedAircraftChangedHook) this._AircraftList.unhook(this._SelectedAircraftChangedHook); this._AircraftListUpdatedHook = this._SelectedAircraftChangedHook = null; } /** * Gets the name of the object. This is used when storing and loading settings. */ getName = () : string => { return this._Name; } /** * Gets a value indicating whether the object is actively setting the selected aircraft. */ getEnabled = () : boolean => { return this._Enabled; } setEnabled = (value: boolean) => { if(this._Enabled !== value) { this._Enabled = value; this._Dispatcher.raise(this._Events.enabledChanged); if(this._Enabled && this._AircraftList) { var closestAircraft = this.closestAircraft(this._AircraftList); if(closestAircraft && closestAircraft !== this._AircraftList.getSelectedAircraft()) { this._AircraftList.setSelectedAircraft(closestAircraft, false); } } } } /** * Gets a value indicating that the closest aircraft is to be selected. */ getSelectClosest = () : boolean => { return this._SelectClosest; } setSelectClosest = (value: boolean) => { this._SelectClosest = value; } /** * Gets a value that describes what to do when an aircraft goes off the radar. */ getOffRadarAction = () : OffRadarActionEnum => { return this._OffRadarAction; } setOffRadarAction = (value: OffRadarActionEnum) => { this._OffRadarAction = value; } /** * Returns a clone of the filter at the specified index. */ getFilter = (index: number) : AircraftFilter => { return <AircraftFilter>this._Filters[index].clone(); } setFilter = (index: number, aircraftFilter: AircraftFilter) => { if(this._Filters.length < VRS.globalOptions.aircraftListFiltersLimit) { var existing = index < this._Filters.length ? this._Filters[index] : null; if(existing && !existing.equals(aircraftFilter)) this._Filters[index] = aircraftFilter; } } /** * Gets or sets the ICAO that will be selected on the next update. */ getSelectAircraftByIcao = () : string => { return this._SelectAircraftByIcao; } setSelectAircraftByIcao = (icao: string) => { this._SelectAircraftByIcao = icao; } /** * Gets or sets a value indicating that SelectAircraftByIcao will be automatically cleared after the next * fetch of the aircraft list. */ getAutoClearSelectAircraftByIcao = () : boolean => { return this._AutoClearSelectAircraftByIcao; } setAutoClearSelectAircraftByIcao = (value: boolean) => { this._AutoClearSelectAircraftByIcao = value; } /** * Raised after the Enabled property value has changed. */ hookEnabledChanged = (callback: () => void, forceThis?: Object) : IEventHandle => { return this._Dispatcher.hook(this._Events.enabledChanged, callback, forceThis); } /** * Raised after an aircraft is selected by ICAO. */ hookAircraftSelectedByIcao = (callback: () => void, forceThis?: Object) : IEventHandle => { return this._Dispatcher.hook(this._Events.aircraftSelectedByIcao, callback, forceThis); } /** * Unhooks an event hooked on this object. */ unhook = (hookResult: IEventHandle) => { this._Dispatcher.unhook(hookResult); } /** * Saves the current state of the object. */ saveState = () => { VRS.configStorage.save(this.persistenceKey(), this.createSettings()); } /** * Returns the saved state of the object. */ loadState = () : AircraftAutoSelect_SaveState => { var savedSettings: AircraftAutoSelect_SaveState = VRS.configStorage.load(this.persistenceKey(), {}); var result = $.extend(this.createSettings(), savedSettings); result.filters = VRS.aircraftFilterHelper.buildValidFiltersList(result.filters, VRS.globalOptions.aircraftAutoSelectFiltersLimit); return result; } /** * Applies a saved state to the object. */ applyState = (settings: AircraftAutoSelect_SaveState) => { this.setEnabled(settings.enabled); this.setSelectClosest(settings.selectClosest); this.setOffRadarAction(settings.offRadarAction); this._Filters = []; var self = this; $.each(settings.filters, function(idx, serialisedFilter) { var aircraftFilter = <AircraftFilter>VRS.aircraftFilterHelper.createFilter(serialisedFilter.property); aircraftFilter.applySerialisedObject(serialisedFilter); self._Filters.push(aircraftFilter); }); } /** * Loads and applies the saved state to the object. */ loadAndApplyState = () => { this.applyState(this.loadState()); } /** * Returns the key under which the object's settings are saved. */ private persistenceKey = () : string => { return 'vrsAircraftAutoSelect-' + this._Name; } /** * Creates the state object. */ private createSettings = () : AircraftAutoSelect_SaveState => { var filters = VRS.aircraftFilterHelper.serialiseFiltersList(this._Filters); return { enabled: this._Enabled, selectClosest: this._SelectClosest, offRadarAction: this._OffRadarAction, filters: filters }; } /** * Creates the option pane that allows configuration of the object. */ createOptionPane = (displayOrder: number) : OptionPane[] => { var result = []; var pane = new VRS.OptionPane({ name: 'vrsAircraftAutoSelectPane1', titleKey: 'PaneAutoSelect', displayOrder: displayOrder }); result.push(pane); pane.addField(new VRS.OptionFieldCheckBox({ name: 'enable', labelKey: 'AutoSelectAircraft', getValue: this.getEnabled, setValue: this.setEnabled, saveState: this.saveState, hookChanged: this.hookEnabledChanged, unhookChanged: this.unhook })); pane.addField(new VRS.OptionFieldRadioButton({ name: 'closest', labelKey: 'Select', getValue: this.getSelectClosest, setValue: this.setSelectClosest, saveState: this.saveState, values: [ new VRS.ValueText({ value: true, textKey: 'ClosestToCurrentLocation' }), new VRS.ValueText({ value: false, textKey: 'FurthestFromCurrentLocation' }) ] })); if(VRS.globalOptions.aircraftListFiltersLimit !== 0) { var panesTypeSettings = VRS.aircraftFilterHelper.addConfigureFiltersListToPane({ pane: pane, filters: this._Filters, saveState: $.proxy(this.saveState, this), maxFilters: VRS.globalOptions.aircraftAutoSelectFiltersLimit, allowableProperties: [ VRS.AircraftFilterProperty.Altitude, VRS.AircraftFilterProperty.Distance ], addFilter: (newComparer: AircraftFilterPropertyEnum, paneField: OptionFieldPaneList) => { var aircraftFilter = this.addFilter(newComparer); paneField.addPane(aircraftFilter.createOptionPane(() => this.saveState)); this.saveState(); }, addFilterButtonLabel: 'AddCondition' }); panesTypeSettings.hookPaneRemoved(this.filterPaneRemoved, this); } pane = new VRS.OptionPane({ name: 'vrsAircraftAutoSelectPane2', displayOrder: displayOrder + 1 }); result.push(pane); pane.addField(new VRS.OptionFieldLabel({ name: 'offRadarActionLabel', labelKey: 'OffRadarAction' })); pane.addField(new VRS.OptionFieldRadioButton({ name: 'offRadarAction', getValue: this.getOffRadarAction, setValue: this.setOffRadarAction, saveState: this.saveState, values: [ new VRS.ValueText({ value: VRS.OffRadarAction.WaitForReturn, textKey: 'OffRadarActionWait' }), new VRS.ValueText({ value: VRS.OffRadarAction.EnableAutoSelect, textKey: 'OffRadarActionEnableAutoSelect' }), new VRS.ValueText({ value: VRS.OffRadarAction.Nothing, textKey: 'OffRadarActionNothing' }) ] })); return result; } /** * Adds a new filter to the auto-select settings. */ addFilter = (filterOrFilterProperty: AircraftFilter | AircraftFilterPropertyEnum) : AircraftFilter => { var filter = filterOrFilterProperty; if(!(filter instanceof VRS.AircraftFilter)) { filter = <AircraftFilter>VRS.aircraftFilterHelper.createFilter(<string>filterOrFilterProperty); } this._Filters.push(<AircraftFilter>filter); return <AircraftFilter>filter; } /** * Removes an existing filter from the auto-select settings. */ private filterPaneRemoved = (pane: OptionPane, index: number) => { this.removeFilterAt(index); this.saveState(); } /** * Removes an existing filter from the auto-select settings. */ private removeFilterAt = (index: number) => { this._Filters.splice(index, 1); } /** * Returns the closest aircraft from the aircraft list passed across. */ closestAircraft = (aircraftList: AircraftList) : Aircraft => { var result = null; if(this.getEnabled()) { var useClosest = this.getSelectClosest(); var useFilters = this._Filters.length > 0; var selectedDistance = useClosest ? Number.MAX_VALUE : Number.MIN_VALUE; var self = this; aircraftList.foreachAircraft(function(aircraft) { if(aircraft.distanceFromHereKm.val !== undefined) { var isCandidate = useClosest ? aircraft.distanceFromHereKm.val < selectedDistance : aircraft.distanceFromHereKm.val > selectedDistance; if(isCandidate) { if(useFilters && !VRS.aircraftFilterHelper.aircraftPasses(aircraft, self._Filters, {})) isCandidate = false; if(isCandidate) { result = aircraft; selectedDistance = aircraft.distanceFromHereKm.val; } } } }); } return result; } /** * Called when the aircraft list is updated. */ private aircraftListUpdated = (newAircraft: AircraftCollection, offRadar: AircraftCollection) => { var self = this; var selectedAircraft = this._AircraftList.getSelectedAircraft(); var autoSelectAircraft = this.closestAircraft(this._AircraftList); var autoSelectedByIcao = false; if(this._SelectAircraftByIcao) { var aircraftByIcao = this._AircraftList.findAircraftByIcao(this._SelectAircraftByIcao); if(aircraftByIcao) { autoSelectAircraft = aircraftByIcao; autoSelectedByIcao = true; } if(this._AutoClearSelectAircraftByIcao) { this._SelectAircraftByIcao = null; } } var useAutoSelectedAircraft = function() { if(autoSelectAircraft !== selectedAircraft) { self._AircraftList.setSelectedAircraft(autoSelectAircraft, autoSelectedByIcao); selectedAircraft = autoSelectAircraft; } }; if(autoSelectAircraft) { useAutoSelectedAircraft(); } else if(selectedAircraft) { var isOffRadar = offRadar.findAircraftById(selectedAircraft.id); if(isOffRadar) { switch(this.getOffRadarAction()) { case VRS.OffRadarAction.Nothing: break; case VRS.OffRadarAction.EnableAutoSelect: if(!this.getEnabled()) { this.setEnabled(true); autoSelectAircraft = this.closestAircraft(this._AircraftList); if(autoSelectAircraft) useAutoSelectedAircraft(); } break; case VRS.OffRadarAction.WaitForReturn: this._AircraftList.setSelectedAircraft(undefined, false); break; } } } if(!selectedAircraft && this._LastAircraftSelected) { var reselectAircraft = newAircraft.findAircraftById(this._LastAircraftSelected.id); if(reselectAircraft) { this._AircraftList.setSelectedAircraft(reselectAircraft, false); } } if(autoSelectedByIcao) { this._Dispatcher.raise(this._Events.aircraftSelectedByIcao); } } /** * Called when the aircraft list changes the selected aircraft. */ private selectedAircraftChanged = () => { var selectedAircraft = this._AircraftList.getSelectedAircraft(); if(selectedAircraft) this._LastAircraftSelected = selectedAircraft; if(this._AircraftList.getWasAircraftSelectedByUser()) { this.setEnabled(false); } } } }
the_stack
import onePane from '../../onePane/onePaneStore/onePane.methods'; import twoPane from '../../twoPane/twoPaneStore/twoPane.methods'; import utility from '../utility.methods'; import autoPane from '../autoPane.methods'; import React, { Fragment } from 'react'; import utilityStore from '../../shared/utilityStore/utilityStore.methods'; import { resetApp, store } from '../../appStore'; import { isTwoPaneAction } from '../../shared/utilityStore/utilityStore.actions'; import { getUtilityStore } from '../../shared/utilityStore/utilityStore.selectors'; describe('autoPane methods', () => { describe('onePane Correct Methods Called', () => { beforeEach(() => { jest.clearAllMocks(); jest.spyOn(utility, 'isTwoPane').mockReturnValue(false); }); it('Add', () => { // Arrange const onePaneAddSpy = jest.spyOn(onePane, 'Add'); const twoPaneAddSpy = jest.spyOn(twoPane, 'Add'); // Act autoPane.Add('test', <Fragment />); // Assert expect(onePaneAddSpy).toBeCalled(); expect(onePaneAddSpy).toBeCalledTimes(1); expect(twoPaneAddSpy).not.toBeCalled(); expect(twoPaneAddSpy).toBeCalledTimes(0); }); it('AddOrMoveToFront', () => { // Arrange const onePaneAddOrMoveToFrontSpy = jest.spyOn(onePane, 'AddOrMoveToFront'); const twoPaneAddAddOrMoveToFrontSpy = jest.spyOn(twoPane, 'AddOrMoveToFront'); // Act autoPane.AddOrMoveToFront('test', <Fragment />); // Assert expect(onePaneAddOrMoveToFrontSpy).toBeCalled(); expect(onePaneAddOrMoveToFrontSpy).toBeCalledTimes(1); expect(twoPaneAddAddOrMoveToFrontSpy).not.toBeCalled(); expect(twoPaneAddAddOrMoveToFrontSpy).toBeCalledTimes(0); }); it('AddOrMoveToFrontTWO', () => { // Arrange const onePaneAddSpy = jest.spyOn(onePane, 'Add'); const onePaneAddOrMoveToFrontSpy = jest.spyOn(onePane, 'AddOrMoveToFront'); const twoPaneAddOrMoveToFrontSpy = jest.spyOn(twoPane, 'AddOrMoveToFront'); // Act autoPane.AddOrMoveToFrontTWO('test', <Fragment />); // Assert expect(onePaneAddSpy).toBeCalled(); expect(onePaneAddSpy).toBeCalledTimes(1); expect(onePaneAddOrMoveToFrontSpy).not.toBeCalled(); expect(onePaneAddOrMoveToFrontSpy).toBeCalledTimes(0); expect(twoPaneAddOrMoveToFrontSpy).not.toBeCalled(); expect(twoPaneAddOrMoveToFrontSpy).toBeCalledTimes(0); }); it('AddOrMoveToFrontONE', () => { // Arrange const twoPaneAddSpy = jest.spyOn(twoPane, 'Add'); const twoPaneAddOrMoveToFrontSpy = jest.spyOn(twoPane, 'AddOrMoveToFront'); const onePaneAddOrMoveToFrontSpy = jest.spyOn(onePane, 'AddOrMoveToFront'); // Act autoPane.AddOrMoveToFrontONE('test', <Fragment />); // Assert expect(onePaneAddOrMoveToFrontSpy).toBeCalled(); expect(onePaneAddOrMoveToFrontSpy).toBeCalledTimes(1); expect(twoPaneAddSpy).not.toBeCalled(); expect(twoPaneAddSpy).toBeCalledTimes(0); expect(twoPaneAddOrMoveToFrontSpy).not.toBeCalled(); expect(twoPaneAddOrMoveToFrontSpy).toBeCalledTimes(0); }); it('BackToHome', () => { // Arrange const onePaneBackToHomeSpy = jest.spyOn(onePane, 'BackToHome'); const twoPaneBackToHomeSpy = jest.spyOn(twoPane, 'BackToHome'); // Act autoPane.BackToHome(); // Assert expect(onePaneBackToHomeSpy).toBeCalled(); expect(onePaneBackToHomeSpy).toBeCalledTimes(1); expect(twoPaneBackToHomeSpy).not.toBeCalled(); expect(twoPaneBackToHomeSpy).toBeCalledTimes(0); }); it('GoBack', () => { // Arrange const onePaneGoBackSpy = jest.spyOn(onePane, 'GoBack'); const twoPaneGoBackSpy = jest.spyOn(twoPane, 'GoBack'); // Act autoPane.GoBack(); // Assert expect(onePaneGoBackSpy).toBeCalled(); expect(onePaneGoBackSpy).toBeCalledTimes(1); expect(twoPaneGoBackSpy).not.toBeCalled(); expect(twoPaneGoBackSpy).toBeCalledTimes(0); }); it('ReplacePane', () => { // Arrange const onePaneReplaceHeaderSpy = jest.spyOn( onePane, 'ReplacePane' ); const twoPaneReplaceHeaderSpy = jest.spyOn( twoPane, 'ReplacePane' ); // Act autoPane.ReplacePane('test', <Fragment />); // Assert expect(onePaneReplaceHeaderSpy).toBeCalled(); expect(onePaneReplaceHeaderSpy).toBeCalledTimes(1); expect(twoPaneReplaceHeaderSpy).not.toBeCalled(); expect(twoPaneReplaceHeaderSpy).toBeCalledTimes(0); }); it('ReplaceHeader', () => { // Arrange const onePaneReplaceHeaderSpy = jest.spyOn( onePane, 'ReplaceHeader' ); const twoPaneReplaceHeaderSpy = jest.spyOn( twoPane, 'ReplaceHeader' ); // Act autoPane.ReplaceHeader('test', { title: 'test title' }); // Assert expect(onePaneReplaceHeaderSpy).toBeCalled(); expect(onePaneReplaceHeaderSpy).toBeCalledTimes(1); expect(twoPaneReplaceHeaderSpy).not.toBeCalled(); expect(twoPaneReplaceHeaderSpy).toBeCalledTimes(0); }); }); describe('twoPane Correct Methods Called', () => { beforeEach(() => { jest.clearAllMocks(); jest.spyOn(utility, 'isTwoPane').mockReturnValue(true); }); it('Add', () => { // Arrange const onePaneAddSpy = jest.spyOn(onePane, 'Add'); const twoPaneAddSpy = jest.spyOn(twoPane, 'Add'); // Act autoPane.Add('test', <Fragment />); // Assert expect(onePaneAddSpy).not.toBeCalled(); expect(onePaneAddSpy).toBeCalledTimes(0); expect(twoPaneAddSpy).toBeCalled(); expect(twoPaneAddSpy).toBeCalledTimes(1); }); it('AddOrMoveToFront', () => { // Arrange const onePaneAddOrMoveToFrontSpy = jest.spyOn(onePane, 'AddOrMoveToFront'); const twoPaneAddAddOrMoveToFrontSpy = jest.spyOn(twoPane, 'AddOrMoveToFront'); // Act autoPane.AddOrMoveToFront('test', <Fragment />); // Assert expect(twoPaneAddAddOrMoveToFrontSpy).toBeCalled(); expect(twoPaneAddAddOrMoveToFrontSpy).toBeCalledTimes(1); expect(onePaneAddOrMoveToFrontSpy).not.toBeCalled(); expect(onePaneAddOrMoveToFrontSpy).toBeCalledTimes(0); }); it('AddOrMoveToFrontTWO', () => { // Arrange const onePaneAddSpy = jest.spyOn(onePane, 'Add'); const onePaneAddOrMoveToFrontSpy = jest.spyOn(onePane, 'AddOrMoveToFront'); const twoPaneAddOrMoveToFrontSpy = jest.spyOn(twoPane, 'AddOrMoveToFront'); // Act autoPane.AddOrMoveToFrontTWO('test', <Fragment />); // Assert expect(twoPaneAddOrMoveToFrontSpy).toBeCalled(); expect(twoPaneAddOrMoveToFrontSpy).toBeCalledTimes(1); expect(onePaneAddOrMoveToFrontSpy).not.toBeCalled(); expect(onePaneAddOrMoveToFrontSpy).toBeCalledTimes(0); expect(onePaneAddSpy).not.toBeCalled(); expect(onePaneAddSpy).toBeCalledTimes(0); }); it('AddOrMoveToFrontONE', () => { // Arrange const onePaneAddSpy = jest.spyOn(onePane, 'Add'); const twoPaneAddSpy = jest.spyOn(twoPane, 'Add'); const onePaneAddOrMoveToFrontSpy = jest.spyOn(onePane, 'AddOrMoveToFront'); // Act autoPane.AddOrMoveToFrontONE('test', <Fragment />); // Assert expect(twoPaneAddSpy).toBeCalled(); expect(twoPaneAddSpy).toBeCalledTimes(1); expect(onePaneAddSpy).not.toBeCalled(); expect(onePaneAddSpy).toBeCalledTimes(0); expect(onePaneAddOrMoveToFrontSpy).not.toBeCalled(); expect(onePaneAddOrMoveToFrontSpy).toBeCalledTimes(0); }); it('BackToHome', () => { // Arrange const onePaneBackToHomeSpy = jest.spyOn(onePane, 'BackToHome'); const twoPaneBackToHomeSpy = jest.spyOn(twoPane, 'BackToHome'); // Act autoPane.BackToHome(); // Assert expect(onePaneBackToHomeSpy).not.toBeCalled(); expect(onePaneBackToHomeSpy).toBeCalledTimes(0); expect(twoPaneBackToHomeSpy).toBeCalled(); expect(twoPaneBackToHomeSpy).toBeCalledTimes(1); }); it('GoBack', () => { // Arrange const onePaneGoBackSpy = jest.spyOn(onePane, 'GoBack'); const twoPaneGoBackSpy = jest.spyOn(twoPane, 'GoBack'); // Act autoPane.GoBack(); // Assert expect(onePaneGoBackSpy).not.toBeCalled(); expect(onePaneGoBackSpy).toBeCalledTimes(0); expect(twoPaneGoBackSpy).toBeCalled(); expect(twoPaneGoBackSpy).toBeCalledTimes(1); }); it('ReplacePane', () => { // Arrange const onePaneReplaceHeaderSpy = jest.spyOn( onePane, 'ReplacePane' ); const twoPaneReplaceHeaderSpy = jest.spyOn( twoPane, 'ReplacePane' ); // Act autoPane.ReplacePane('test', <Fragment />); // Assert expect(twoPaneReplaceHeaderSpy).toBeCalled(); expect(twoPaneReplaceHeaderSpy).toBeCalledTimes(1); expect(onePaneReplaceHeaderSpy).not.toBeCalled(); expect(onePaneReplaceHeaderSpy).toBeCalledTimes(0); }); it('ReplaceHeader', () => { // Arrange const onePaneReplaceHeaderSpy = jest.spyOn( onePane, 'ReplaceHeader' ); const twoPaneReplaceHeaderSpy = jest.spyOn( twoPane, 'ReplaceHeader' ); // Act autoPane.ReplaceHeader('test', { title: 'test title' }); // Assert expect(twoPaneReplaceHeaderSpy).toBeCalled(); expect(twoPaneReplaceHeaderSpy).toBeCalledTimes(1); expect(onePaneReplaceHeaderSpy).not.toBeCalled(); expect(onePaneReplaceHeaderSpy).toBeCalledTimes(0); }); }); });
the_stack
const names = [ "case-clause.expr", "case-clause.expr ", "cast.expr", "comment.block.documentation", "comment.block", "comment.line.double-slash", "comment.line.shebang", "comment.line.triple-slash.directive", "constant.character.control.regexp", "constant.character.escape.backslash.regexp", "constant.character.escape", "constant.character.numeric.regexp", "constant.language.access-type.jsdoc", "constant.language.boolean.false", "constant.language.boolean.true", "constant.language.import-export-all", "constant.language.infinity", "constant.language.nan", "constant.language.null", "constant.language.symbol-type.jsdoc", "constant.language.undefined", "constant.numeric.binary", "constant.numeric.decimal", "constant.numeric.hex", "constant.numeric.octal", "constant.other.character-class.range.regexp", "constant.other.character-class.regexp", "constant.other.character-class.set.regexp", "constant.other.description.jsdoc", "constant.other.email.link.underline.jsdoc", "entity.name.function.tagged-template", "entity.name.function", "entity.name.function variable.language.this", "entity.name.label", "entity.name.tag.directive", "entity.name.tag.inline.jsdoc", "entity.name.type.alias", "entity.name.type.class", "entity.name.type.enum", "entity.name.type.instance.jsdoc", "entity.name.type.interface", "entity.name.type.module", "entity.name.type", "entity.other.attribute-name.directive", "entity.other.inherited-class", "invalid.illegal.newline", "invalid.illegal.syntax.jsdoc", "keyword.control.anchor.regexp", "keyword.control.as", "keyword.control.conditional", "keyword.control.default", "keyword.control.export", "keyword.control.flow", "keyword.control.from", "keyword.control.import", "keyword.control.loop", "keyword.control.new", "keyword.control.require", "keyword.control.switch", "keyword.control.trycatch", "keyword.control", "keyword.control.with", "keyword.generator.asterisk", "keyword.operator.arithmetic", "keyword.operator.assignment.compound.bitwise", "keyword.operator.assignment.compound", "keyword.operator.assignment.jsdoc", "keyword.operator.assignment", "keyword.operator.bitwise.shift", "keyword.operator.bitwise", "keyword.operator.comparison", "keyword.operator.control.jsdoc", "keyword.operator.decrement", "keyword.operator.definiteassignment", "keyword.operator.expression.delete", "keyword.operator.expression.import", "keyword.operator.expression.in", "keyword.operator.expression.infer", "keyword.operator.expression.instanceof", "keyword.operator.expression.is", "keyword.operator.expression.keyof", "keyword.operator.expression.of", "keyword.operator.expression.typeof", "keyword.operator.expression.void", "keyword.operator.increment", "keyword.operator.logical", "keyword.operator.negation.regexp", "keyword.operator.new", "keyword.operator.optional", "keyword.operator.or.regexp", "keyword.operator.quantifier.regexp", "keyword.operator.relational", "keyword.operator.rest", "keyword.operator.spread", "keyword.operator.ternary", "keyword.operator.type.annotation", "keyword.operator.type.modifier", "keyword.operator.type", "keyword.other.back-reference.regexp", "keyword.other.debugger", "keyword.other", "meta.array-binding-pattern-variable", "meta.array.literal", "meta.arrow", "meta.arrow meta.return.type.arrow keyword.operator.type.annotation", "meta.assertion.look-ahead.regexp", "meta.assertion.look-behind.regexp", "meta.assertion.negative-look-ahead.regexp", "meta.assertion.negative-look-behind.regexp", "meta.block", "meta.block punctuation.definition.block", "meta.brace.angle", "meta.brace.round", "meta.brace.square", "meta.class", "meta.decorator", "meta.definition.function entity.name.function", "meta.definition.method entity.name.function", "meta.definition.property entity.name.function", "meta.definition.property variable.object.property", "meta.definition.variable entity.name.function", "meta.definition.variable variable.other.constant", "meta.definition.variable variable.other.constant entity.name.function", "meta.definition.variable variable.other.readwrite", "meta.delimiter.decimal.period", "meta.enum.declaration", "meta.example.jsdoc", "meta.export.default", "meta.export", "meta.field.declaration", "meta.function-call", "meta.function-call punctuation.accessor.optional", "meta.function.expression", "meta.function", "meta.group.assertion.regexp", "meta.group.regexp", "meta.import-equals.external", "meta.import-equals.internal", "meta.import", "meta.indexer.declaration", "meta.indexer.mappedtype.declaration", "meta.interface", "meta.method.declaration", "meta.namespace.declaration", "meta.object-binding-pattern-variable", "meta.object-literal.key", "meta.object-literal.key punctuation.separator.key-value", "meta.object.member", "meta.object.member meta.object-literal.key", "meta.object.type", "meta.objectliteral", "meta.parameter.object-binding-pattern", "meta.parameters", "meta.paramter.array-binding-pattern", "meta.return.type.arrow", "meta.return.type", "meta.tag", "meta.template.expression", "meta.type.annotation", "meta.type.constructor", "meta.type.constructor keyword.control.new", "meta.type.declaration", "meta.type.function.return", "meta.type.function", "meta.type.parameters", "meta.type.parameters punctuation.definition.typeparameters.begin", "meta.type.parameters punctuation.definition.typeparameters.end", "meta.type.paren.cover", "meta.type.tuple", "meta.var-single-variable.expr", "meta.var.expr", "new.expr", "punctuation.accessor.optional", "punctuation.accessor", "punctuation.decorator.internaldeclaration", "punctuation.decorator", "punctuation.definition.binding-pattern.array", "punctuation.definition.binding-pattern.object", "punctuation.definition.block.tag.jsdoc", "punctuation.definition.block", "punctuation.definition.bracket.angle.begin.jsdoc", "punctuation.definition.bracket.angle.end.jsdoc", "punctuation.definition.bracket.curly.begin.jsdoc", "punctuation.definition.bracket.curly.end.jsdoc", "punctuation.definition.bracket.square.begin.jsdoc", "punctuation.definition.bracket.square.end.jsdoc", "punctuation.definition.character-class.regexp", "punctuation.definition.comment", "punctuation.definition.group.assertion.regexp", "punctuation.definition.group.no-capture.regexp", "punctuation.definition.group.regexp", "punctuation.definition.inline.tag.jsdoc", "punctuation.definition.optional-value.begin.bracket.square.jsdoc", "punctuation.definition.optional-value.end.bracket.square.jsdoc", "punctuation.definition.parameters.begin", "punctuation.definition.parameters.end", "punctuation.definition.section.case-statement", "punctuation.definition.string.begin.jsdoc", "punctuation.definition.string.begin", "punctuation.definition.string.end.jsdoc", "punctuation.definition.string.end", "punctuation.definition.string.template.begin", "punctuation.definition.string.template.end", "punctuation.definition.tag.directive", "punctuation.definition.template-expression.begin", "punctuation.definition.template-expression.end", "punctuation.definition.typeparameters.begin", "punctuation.definition.typeparameters.end", "punctuation.destructuring", "punctuation.separator.comma", "punctuation.separator.label", "punctuation.separator.parameter", "punctuation.separator.pipe.jsdoc", "punctuation.terminator.statement", "punctuation.whitespace.comment.leading", "source.embedded", "storage.modifier.async", "storage.modifier", "storage.type.class.jsdoc", "storage.type.class", "storage.type.enum", "storage.type.function.arrow", "storage.type.function", "storage.type.interface", "storage.type.internaldeclaration", "storage.type.namespace", "storage.type.numeric.bigint", "storage.type.property", "storage.type", "storage.type.type", "string.quoted.double", "string.quoted.single", "string.regexp", "string.template", "support.class.builtin", "support.class.console", "support.class.error", "support.class.node", "support.class.promise", "support.class", "support.constant.json", "support.constant.math", "support.constant.property.math", "support.constant", "support.function.console", "support.function.json", "support.function.math", "support.function.process", "support.function", "support.type.builtin", "support.type.object.module", "support.type.primitive", "support.variable.object.node", "support.variable.object.process", "support.variable.property.importmeta", "support.variable.property.process", "support.variable.property.target", "support.variable.property", "switch-block.expr", "switch-expression.expr", "switch-statement.expr", "TypeScript", "variable.language.arguments", "variable.language.super", "variable.language.this", "variable.object.property", "variable.other.constant.object.property", "variable.other.constant.object", "variable.other.constant.property", "variable.other.constant", "variable.other.description.jsdoc", "variable.other.enummember", "variable.other.jsdoc", "variable.other.link.underline.jsdoc", "variable.other.object.property", "variable.other.object", "variable.other.property", "variable.other.readwrite.alias", "variable.other.readwrite", "variable.other.regexp", "variable.parameter", "variable.parameter variable.language.this" ]; /* { "scope": ["case-clause.expr"], "settings": { "foreground": "", "fontStyle": "bold" } }, {"scope": [ "case-clause.expr", "case-clause.expr ", "cast.expr", ], "settings": { "foreground": "#ff5", "fontStyle": "bold" } }, {"scope": [ "comment.block.documentation", "comment.block", "comment.line.double-slash", "comment.line.shebang", "comment.line.triple-slash.directive", ], "settings": { "foreground": "#f5f", "fontStyle": "bold" } }, {"scope": [ "constant.character.control.regexp", "constant.character.escape.backslash.regexp", "constant.character.escape", "constant.character.numeric.regexp", "constant.language.access-type.jsdoc", "constant.language.boolean.false", "constant.language.boolean.true", "constant.language.import-export-all", "constant.language.infinity", "constant.language.nan", "constant.language.null", "constant.language.symbol-type.jsdoc", "constant.language.undefined", "constant.numeric.binary", "constant.numeric.decimal", "constant.numeric.hex", "constant.numeric.octal", "constant.other.character-class.range.regexp", "constant.other.character-class.regexp", "constant.other.character-class.set.regexp", "constant.other.description.jsdoc", "constant.other.email.link.underline.jsdoc", ], "settings": { "foreground": "#5ff", "fontStyle": "bold" } }, {"scope": [ "entity.name.function.tagged-template", "entity.name.function", "entity.name.function variable.language.this", "entity.name.label", "entity.name.tag.directive", "entity.name.tag.inline.jsdoc", "entity.name.type.alias", "entity.name.type.class", "entity.name.type.enum", "entity.name.type.instance.jsdoc", "entity.name.type.interface", "entity.name.type.module", "entity.name.type", "entity.other.attribute-name.directive", "entity.other.inherited-class", ], "settings": { "foreground": "#f55", "fontStyle": "bold" } }, {"scope": [ "invalid.illegal.newline", "invalid.illegal.syntax.jsdoc", ], "settings": { "foreground": "#55f", "fontStyle": "bold" } }, {"scope": [ "keyword.control.anchor.regexp", "keyword.control.as", "keyword.control.conditional", "keyword.control.default", "keyword.control.export", "keyword.control.flow", "keyword.control.from", "keyword.control.import", "keyword.control.loop", "keyword.control.new", "keyword.control.require", "keyword.control.switch", "keyword.control.trycatch", "keyword.control", "keyword.control.with", ], "settings": { "foreground": "#5f5", "fontStyle": "bold" } }, {"scope": [ "keyword.generator.asterisk", ], "settings": { "foreground": "#555", "fontStyle": "bold" } }, {"scope": [ "keyword.operator.arithmetic", "keyword.operator.assignment.compound.bitwise", "keyword.operator.assignment.compound", "keyword.operator.assignment.jsdoc", "keyword.operator.assignment", "keyword.operator.bitwise.shift", "keyword.operator.bitwise", "keyword.operator.comparison", "keyword.operator.control.jsdoc", "keyword.operator.decrement", "keyword.operator.definiteassignment", "keyword.operator.expression.delete", "keyword.operator.expression.import", "keyword.operator.expression.in", "keyword.operator.expression.infer", "keyword.operator.expression.instanceof", "keyword.operator.expression.is", "keyword.operator.expression.keyof", "keyword.operator.expression.of", "keyword.operator.expression.typeof", "keyword.operator.expression.void", "keyword.operator.increment", "keyword.operator.logical", "keyword.operator.negation.regexp", "keyword.operator.new", "keyword.operator.optional", "keyword.operator.or.regexp", "keyword.operator.quantifier.regexp", "keyword.operator.relational", "keyword.operator.rest", "keyword.operator.spread", "keyword.operator.ternary", "keyword.operator.type.annotation", "keyword.operator.type.modifier", "keyword.operator.type", ], "settings": { "foreground": "#f05", "fontStyle": "bold" } }, {"scope": [ "keyword.other.back-reference.regexp", "keyword.other.debugger", "keyword.other", ], "settings": { "foreground": "#05f", "fontStyle": "bold" } }, {"scope": [ "meta.array-binding-pattern-variable", "meta.array.literal", "meta.arrow", "meta.arrow meta.return.type.arrow keyword.operator.type.annotation", "meta.assertion.look-ahead.regexp", "meta.assertion.look-behind.regexp", "meta.assertion.negative-look-ahead.regexp", "meta.assertion.negative-look-behind.regexp", "meta.block", "meta.block punctuation.definition.block", "meta.brace.angle", "meta.brace.round", "meta.brace.square", "meta.class", "meta.decorator", "meta.definition.function entity.name.function", "meta.definition.method entity.name.function", "meta.definition.property entity.name.function", "meta.definition.property variable.object.property", "meta.definition.variable entity.name.function", "meta.definition.variable variable.other.constant", "meta.definition.variable variable.other.constant entity.name.function", "meta.definition.variable variable.other.readwrite", "meta.delimiter.decimal.period", "meta.enum.declaration", "meta.example.jsdoc", "meta.export.default", "meta.export", "meta.field.declaration", "meta.function-call", "meta.function-call punctuation.accessor.optional", "meta.function.expression", "meta.function", "meta.group.assertion.regexp", "meta.group.regexp", "meta.import-equals.external", "meta.import-equals.internal", "meta.import", "meta.indexer.declaration", "meta.indexer.mappedtype.declaration", "meta.interface", "meta.method.declaration", "meta.namespace.declaration", "meta.object-binding-pattern-variable", "meta.object-literal.key", "meta.object-literal.key punctuation.separator.key-value", "meta.object.member", "meta.object.member meta.object-literal.key", "meta.object.type", "meta.objectliteral", "meta.parameter.object-binding-pattern", "meta.parameters", "meta.paramter.array-binding-pattern", "meta.return.type.arrow", "meta.return.type", "meta.tag", "meta.template.expression", "meta.type.annotation", "meta.type.constructor", "meta.type.constructor keyword.control.new", "meta.type.declaration", "meta.type.function.return", "meta.type.function", "meta.type.parameters", "meta.type.parameters punctuation.definition.typeparameters.begin", "meta.type.parameters punctuation.definition.typeparameters.end", "meta.type.paren.cover", "meta.type.tuple", "meta.var-single-variable.expr", "meta.var.expr", ], "settings": { "foreground": "#5f0", "fontStyle": "bold" } }, {"scope": [ "new.expr", ], "settings": { "foreground": "#500", "fontStyle": "bold" } }, {"scope": [ "punctuation.accessor.optional", "punctuation.accessor", "punctuation.decorator.internaldeclaration", "punctuation.decorator", "punctuation.definition.binding-pattern.array", "punctuation.definition.binding-pattern.object", "punctuation.definition.block.tag.jsdoc", "punctuation.definition.block", "punctuation.definition.bracket.angle.begin.jsdoc", "punctuation.definition.bracket.angle.end.jsdoc", "punctuation.definition.bracket.curly.begin.jsdoc", "punctuation.definition.bracket.curly.end.jsdoc", "punctuation.definition.bracket.square.begin.jsdoc", "punctuation.definition.bracket.square.end.jsdoc", "punctuation.definition.character-class.regexp", "punctuation.definition.comment", "punctuation.definition.group.assertion.regexp", "punctuation.definition.group.no-capture.regexp", "punctuation.definition.group.regexp", "punctuation.definition.inline.tag.jsdoc", "punctuation.definition.optional-value.begin.bracket.square.jsdoc", "punctuation.definition.optional-value.end.bracket.square.jsdoc", "punctuation.definition.parameters.begin", "punctuation.definition.parameters.end", "punctuation.definition.section.case-statement", "punctuation.definition.string.begin.jsdoc", "punctuation.definition.string.begin", "punctuation.definition.string.end.jsdoc", "punctuation.definition.string.end", "punctuation.definition.string.template.begin", "punctuation.definition.string.template.end", "punctuation.definition.tag.directive", "punctuation.definition.template-expression.begin", "punctuation.definition.template-expression.end", "punctuation.definition.typeparameters.begin", "punctuation.definition.typeparameters.end", "punctuation.destructuring", "punctuation.separator.comma", "punctuation.separator.label", "punctuation.separator.parameter", "punctuation.separator.pipe.jsdoc", "punctuation.terminator.statement", "punctuation.whitespace.comment.leading", ], "settings": { "foreground": "#005", "fontStyle": "bold" } }, {"scope": [ "source.embedded", ], "settings": { "foreground": "#550", "fontStyle": "bold" } }, {"scope": [ "storage.modifier.async", "storage.modifier", "storage.type.class.jsdoc", "storage.type.class", "storage.type.enum", "storage.type.function.arrow", "storage.type.function", "storage.type.interface", "storage.type.internaldeclaration", "storage.type.namespace", "storage.type.numeric.bigint", "storage.type.property", "storage.type", "storage.type.type", ], "settings": { "foreground": "#505", "fontStyle": "bold" } }, {"scope": [ "string.quoted.double", "string.quoted.single", "string.regexp", "string.template", ], "settings": { "foreground": "#055", "fontStyle": "bold" } }, {"scope": [ "support.class.builtin", "support.class.console", "support.class.error", "support.class.node", "support.class.promise", "support.class", ], "settings": { "foreground": "#bcd", "fontStyle": "bold" } }, {"scope": [ "support.constant.json", "support.constant.math", "support.constant.property.math", "support.constant", ], "settings": { "foreground": "#cdb", "fontStyle": "bold" } }, {"scope": [ "support.function.console", "support.function.json", "support.function.math", "support.function.process", "support.function", ], "settings": { "foreground": "#af0", "fontStyle": "bold" } }, {"scope": [ "support.type.builtin", "support.type.object.module", "support.type.primitive", ], "settings": { "foreground": "#dbc", "fontStyle": "bold" } }, {"scope": [ "support.variable.object.node", "support.variable.object.process", "support.variable.property.importmeta", "support.variable.property.process", "support.variable.property.target", "support.variable.property", ], "settings": { "foreground": "#d3e", "fontStyle": "bold" } }, {"scope": [ "switch-block.expr", "switch-expression.expr", "switch-statement.expr", ], "settings": { "foreground": "#456", "fontStyle": "bold" } }, {"scope": [ "TypeScript", "variable.language.arguments", "variable.language.super", "variable.language.this", "variable.object.property", "variable.other.constant.object.property", "variable.other.constant.object", "variable.other.constant.property", "variable.other.constant", "variable.other.description.jsdoc", "variable.other.enummember", "variable.other.jsdoc", "variable.other.link.underline.jsdoc", "variable.other.object.property", "variable.other.object", "variable.other.property", "variable.other.readwrite.alias", "variable.other.readwrite", "variable.other.regexp", "variable.parameter", "variable.parameter variable.language.this" ], "settings": { "foreground": "#3d5", "fontStyle": "bold" } } */
the_stack
import {Injectable} from "@angular/core"; import {Observable} from "rxjs/Observable"; import {BehaviorSubject} from "rxjs/Rx"; import * as Immutable from "immutable"; import {LoggerService} from "../utils/logger.service"; import {ModelFile} from "./model-file"; import {ModelFileService} from "./model-file.service"; import {ViewFile} from "./view-file"; import {MOCK_MODEL_FILES} from "./mock-model-files"; import {StreamServiceRegistry} from "../base/stream-service.registry"; import {WebReaction} from "../utils/rest.service"; /** * Interface defining filtering criteria for view files */ export interface ViewFileFilterCriteria { meetsCriteria(viewFile: ViewFile): boolean; } /** * Interface for sorting view files */ export interface ViewFileComparator { // noinspection TsLint (a: ViewFile, b: ViewFile): number; } /** * ViewFileService class provides the store of view files. * It implements the observable service pattern to push updates * as they become available. * * The view model needs to be ordered and have fast lookup/update. * Unfortunately, there exists no immutable SortedMap structure. * This class stores the following data structures: * 1. files: List(ViewFile) * ViewFiles sorted in the display order * 2. indices: Map(name, index) * Maps name to its index in sortedList * The runtime complexity of operations is: * 1. Update w/o state change: * O(1) to find index and update the sorted list * 2. Updates w/ state change: * O(1) to find index and update the sorted list * O(n log n) to sort list (might be faster since * list is mostly sorted already??) * O(n) to update indexMap * 3. Add: * O(1) to add to list * O(n log n) to sort list (might be faster since * list is mostly sorted already??) * O(n) to update indexMap * 4. Remove: * O(n) to remove from sorted list * O(n) to update indexMap * * Filtering: * This service also supports providing a filtered list of view files. * The strategy of using pipes to filter at the component level is not * recommended by Angular: https://angular.io/guide/pipes#appendix-no * -filterpipe-or-orderbypipe * Instead, we provide a separate filtered observer. * Filtering is controlled via a single filter criteria. Advanced filters * need to be built outside the service (see ViewFileFilterService) */ @Injectable() export class ViewFileService { private readonly USE_MOCK_MODEL = false; private modelFileService: ModelFileService; private _files: Immutable.List<ViewFile> = Immutable.List([]); private _filesSubject: BehaviorSubject<Immutable.List<ViewFile>> = new BehaviorSubject(this._files); private _filteredFilesSubject: BehaviorSubject<Immutable.List<ViewFile>> = new BehaviorSubject(this._files); private _indices: Map<string, number> = new Map<string, number>(); private _prevModelFiles: Immutable.Map<string, ModelFile> = Immutable.Map<string, ModelFile>(); private _filterCriteria: ViewFileFilterCriteria = null; private _sortComparator: ViewFileComparator = null; constructor(private _logger: LoggerService, private _streamServiceRegistry: StreamServiceRegistry) { this.modelFileService = _streamServiceRegistry.modelFileService; const _viewFileService = this; if (!this.USE_MOCK_MODEL) { this.modelFileService.files.subscribe({ next: modelFiles => { let t0 = performance.now(); _viewFileService.buildViewFromModelFiles(modelFiles); let t1 = performance.now(); this._logger.debug("ViewFile creation took", (t1 - t0).toFixed(0), "ms"); } }); } else { // For layout/style testing this.buildViewFromModelFiles(MOCK_MODEL_FILES); } } private buildViewFromModelFiles(modelFiles: Immutable.Map<string, ModelFile>) { this._logger.debug("Received next model files"); // Diff the previous domain model with the current domain model, then apply // those changes to the view model // This is a roughly O(2N) operation on every update, so won't scale well // But should be fine for small models // A more scalable solution would be to subscribe to domain model updates let newViewFiles = this._files; const addedNames: string[] = []; const removedNames: string[] = []; const updatedNames: string[] = []; // Loop through old model to find deletions this._prevModelFiles.keySeq().forEach( name => { if (!modelFiles.has(name)) { removedNames.push(name); } } ); // Loop through new model to find additions and updates modelFiles.keySeq().forEach( name => { if (!this._prevModelFiles.has(name)) { addedNames.push(name); } else if (!Immutable.is(modelFiles.get(name), this._prevModelFiles.get(name))) { updatedNames.push(name); } } ); let reSort = false; let updateIndices = false; // Do the updates first before indices change (re-sort may be required) updatedNames.forEach( name => { const index = this._indices.get(name); const oldViewFile = newViewFiles.get(index); const newViewFile = ViewFileService.createViewFile(modelFiles.get(name), oldViewFile.isSelected); newViewFiles = newViewFiles.set(index, newViewFile); if (this._sortComparator != null && this._sortComparator(oldViewFile, newViewFile) !== 0) { reSort = true; } } ); // Do the adds (requires re-sort) addedNames.forEach( name => { reSort = true; const viewFile = ViewFileService.createViewFile(modelFiles.get(name)); newViewFiles = newViewFiles.push(viewFile); this._indices.set(name, newViewFiles.size - 1); } ); // Do the removes (no re-sort required) removedNames.forEach( name => { updateIndices = true; const index = newViewFiles.findIndex(value => value.name === name); newViewFiles = newViewFiles.remove(index); this._indices.delete(name); } ); if (reSort && this._sortComparator != null) { this._logger.debug("Re-sorting view files"); updateIndices = true; newViewFiles = newViewFiles.sort(this._sortComparator).toList(); } if (updateIndices) { this._indices.clear(); newViewFiles.forEach( (value, index) => this._indices.set(value.name, index) ); } this._files = newViewFiles; this.pushViewFiles(); this._prevModelFiles = modelFiles; this._logger.debug("New view model: %O", this._files.toJS()); } get files(): Observable<Immutable.List<ViewFile>> { return this._filesSubject.asObservable(); } get filteredFiles(): Observable<Immutable.List<ViewFile>> { return this._filteredFilesSubject.asObservable(); } /** * Set a file to be in selected state * @param {ViewFile} file */ public setSelected(file: ViewFile) { // Find the selected file, if any // Note: we can optimize this by storing an additional // state that tracks the selected file // but that would duplicate state and can introduce // bugs, so we just search instead let viewFiles = this._files; const unSelectIndex = viewFiles.findIndex(value => value.isSelected); // Unset the previously selected file, if any if (unSelectIndex >= 0) { let unSelectViewFile = viewFiles.get(unSelectIndex); // Do nothing if file is already selected if (unSelectViewFile.name === file.name) { return; } unSelectViewFile = new ViewFile(unSelectViewFile.set("isSelected", false)); viewFiles = viewFiles.set(unSelectIndex, unSelectViewFile); } // Set the new selected file if (this._indices.has(file.name)) { const index = this._indices.get(file.name); let viewFile = viewFiles.get(index); viewFile = new ViewFile(viewFile.set("isSelected", true)); viewFiles = viewFiles.set(index, viewFile); } else { this._logger.error("Can't find file to select: " + file.name); } // Send update this._files = viewFiles; this.pushViewFiles(); } /** * Un-select the currently selected file */ public unsetSelected() { // Unset the previously selected file, if any let viewFiles = this._files; const unSelectIndex = viewFiles.findIndex(value => value.isSelected); // Unset the previously selected file, if any if (unSelectIndex >= 0) { let unSelectViewFile = viewFiles.get(unSelectIndex); unSelectViewFile = new ViewFile(unSelectViewFile.set("isSelected", false)); viewFiles = viewFiles.set(unSelectIndex, unSelectViewFile); // Send update this._files = viewFiles; this.pushViewFiles(); } } /** * Queue a file for download * @param {ViewFile} file * @returns {Observable<WebReaction>} */ public queue(file: ViewFile): Observable<WebReaction> { this._logger.debug("Queue view file: " + file.name); return this.createAction(file, (f) => this.modelFileService.queue(f)); } /** * Stop a file * @param {ViewFile} file * @returns {Observable<WebReaction>} */ public stop(file: ViewFile): Observable<WebReaction> { this._logger.debug("Stop view file: " + file.name); return this.createAction(file, (f) => this.modelFileService.stop(f)); } /** * Extract a file * @param {ViewFile} file * @returns {Observable<WebReaction>} */ public extract(file: ViewFile): Observable<WebReaction> { this._logger.debug("Extract view file: " + file.name); return this.createAction(file, (f) => this.modelFileService.extract(f)); } /** * Locally delete a file * @param {ViewFile} file * @returns {Observable<WebReaction>} */ public deleteLocal(file: ViewFile): Observable<WebReaction> { this._logger.debug("Locally delete view file: " + file.name); return this.createAction(file, (f) => this.modelFileService.deleteLocal(f)); } /** * Remotely delete a file * @param {ViewFile} file * @returns {Observable<WebReaction>} */ public deleteRemote(file: ViewFile): Observable<WebReaction> { this._logger.debug("Remotely delete view file: " + file.name); return this.createAction(file, (f) => this.modelFileService.deleteRemote(f)); } /** * Set a new filter criteria * @param {ViewFileFilterCriteria} criteria */ public setFilterCriteria(criteria: ViewFileFilterCriteria) { this._filterCriteria = criteria; this.pushViewFiles(); } /** * Sets a new comparator. * @param {ViewFileComparator} comparator */ public setComparator(comparator: ViewFileComparator) { this._sortComparator = comparator; // Re-sort and regenerate index cache this._logger.debug("Re-sorting view files"); let newViewFiles = this._files; if (this._sortComparator != null) { newViewFiles = newViewFiles.sort(this._sortComparator).toList(); } this._files = newViewFiles; this._indices.clear(); newViewFiles.forEach( (value, index) => this._indices.set(value.name, index) ); this.pushViewFiles(); } private static createViewFile(modelFile: ModelFile, isSelected: boolean = false): ViewFile { // Use zero for unknown sizes let localSize: number = modelFile.local_size; if (localSize == null) { localSize = 0; } let remoteSize: number = modelFile.remote_size; if (remoteSize == null) { remoteSize = 0; } let percentDownloaded: number = null; if (remoteSize > 0) { percentDownloaded = Math.trunc(100.0 * localSize / remoteSize); } else { percentDownloaded = 100; } // Translate the status let status = null; switch (modelFile.state) { case ModelFile.State.DEFAULT: { if (localSize > 0 && remoteSize > 0) { status = ViewFile.Status.STOPPED; } else { status = ViewFile.Status.DEFAULT; } break; } case ModelFile.State.QUEUED: { status = ViewFile.Status.QUEUED; break; } case ModelFile.State.DOWNLOADING: { status = ViewFile.Status.DOWNLOADING; break; } case ModelFile.State.DOWNLOADED: { status = ViewFile.Status.DOWNLOADED; break; } case ModelFile.State.DELETED: { status = ViewFile.Status.DELETED; break; } case ModelFile.State.EXTRACTING: { status = ViewFile.Status.EXTRACTING; break; } case ModelFile.State.EXTRACTED: { status = ViewFile.Status.EXTRACTED; break; } } const isQueueable: boolean = [ViewFile.Status.DEFAULT, ViewFile.Status.STOPPED, ViewFile.Status.DELETED].includes(status) && remoteSize > 0; const isStoppable: boolean = [ViewFile.Status.QUEUED, ViewFile.Status.DOWNLOADING].includes(status); const isExtractable: boolean = [ViewFile.Status.DEFAULT, ViewFile.Status.STOPPED, ViewFile.Status.DOWNLOADED, ViewFile.Status.EXTRACTED].includes(status) && localSize > 0; const isLocallyDeletable: boolean = [ViewFile.Status.DEFAULT, ViewFile.Status.STOPPED, ViewFile.Status.DOWNLOADED, ViewFile.Status.EXTRACTED].includes(status) && localSize > 0; const isRemotelyDeletable: boolean = [ViewFile.Status.DEFAULT, ViewFile.Status.STOPPED, ViewFile.Status.DOWNLOADED, ViewFile.Status.EXTRACTED, ViewFile.Status.DELETED].includes(status) && remoteSize > 0; return new ViewFile({ name: modelFile.name, isDir: modelFile.is_dir, localSize: localSize, remoteSize: remoteSize, percentDownloaded: percentDownloaded, status: status, downloadingSpeed: modelFile.downloading_speed, eta: modelFile.eta, fullPath: modelFile.full_path, isArchive: modelFile.is_extractable, isSelected: isSelected, isQueueable: isQueueable, isStoppable: isStoppable, isExtractable: isExtractable, isLocallyDeletable: isLocallyDeletable, isRemotelyDeletable: isRemotelyDeletable, localCreatedTimestamp: modelFile.local_created_timestamp, localModifiedTimestamp: modelFile.local_modified_timestamp, remoteCreatedTimestamp: modelFile.remote_created_timestamp, remoteModifiedTimestamp: modelFile.remote_modified_timestamp }); } /** * Helper method to execute an action on ModelFileService and generate a ViewFileReaction * @param {ViewFile} file * @param {Observable<WebReaction>} action * @returns {Observable<WebReaction>} */ private createAction(file: ViewFile, action: (file: ModelFile) => Observable<WebReaction>) : Observable<WebReaction> { return Observable.create(observer => { if (!this._prevModelFiles.has(file.name)) { // File not found, exit early this._logger.error("File to queue not found: " + file.name); observer.next(new WebReaction(false, null, `File '${file.name}' not found`)); } else { const modelFile = this._prevModelFiles.get(file.name); action(modelFile).subscribe(reaction => { this._logger.debug("Received model reaction: %O", reaction); observer.next(reaction); }); } }); } private pushViewFiles() { // Unfiltered files this._filesSubject.next(this._files); // Filtered files let filteredFiles = this._files; if (this._filterCriteria != null) { filteredFiles = Immutable.List<ViewFile>( this._files.filter(f => this._filterCriteria.meetsCriteria(f)) ); } this._filteredFilesSubject.next(filteredFiles); } }
the_stack
import { Action } from '@ngrx/store'; import { ApiApplyInitAction, ApiRollbackAction, NgrxJsonApiActionTypes, } from './actions'; import { ModifyStoreResourceErrorsPayload, NgrxJsonApiState, NgrxJsonApiZone, Query, ResourceIdentifier, StoreResource, } from './interfaces'; import { clearQueryResult, compactStore, deleteStoreResources, getPendingChanges, removeQuery, removeStoreResource, rollbackStoreResources, setIn, updateQueriesForDeletedResource, updateQueryErrors, updateQueryParams, updateQueryResults, updateResourceErrors, updateResourceErrorsForQuery, updateResourceState, updateStoreDataFromPayload, updateStoreDataFromResource, } from './utils'; export const initialNgrxJsonApiZone: NgrxJsonApiZone = { isCreating: 0, isReading: 0, isUpdating: 0, isDeleting: 0, isApplying: 0, data: {}, queries: {}, }; export const initialNgrxJsonApiState: NgrxJsonApiState = { zones: {}, }; export function NgrxJsonApiStoreReducer( state: NgrxJsonApiState = initialNgrxJsonApiState, action: any ): NgrxJsonApiState { const zoneId = action['zoneId']; if (!zoneId) { return state; } let zone = state.zones[zoneId]; if (!zone) { zone = initialNgrxJsonApiZone; } let newZone = NgrxJsonApiZoneReducer(zone, action); if (zone != newZone) { return { ...state, zones: { ...state.zones, [zoneId]: newZone, }, }; } else { return state; } } export function NgrxJsonApiZoneReducer( zone: NgrxJsonApiZone, action: any ): NgrxJsonApiZone { let newZone; switch (action.type) { case NgrxJsonApiActionTypes.API_POST_INIT: { let updatedData = updateStoreDataFromResource( zone.data, action.payload, false, true ); newZone = { ...zone, data: updatedData, isCreating: zone.isCreating + 1, }; return newZone; } case NgrxJsonApiActionTypes.API_GET_INIT: { let query = action.payload as Query; newZone = { ...zone, queries: updateQueryParams(zone.queries, query), isReading: zone.isReading + 1, }; return newZone; } case NgrxJsonApiActionTypes.API_PATCH_INIT: { let updatedData = updateStoreDataFromResource( zone.data, action.payload, false, false ); newZone = { ...zone, data: updatedData, isUpdating: zone.isUpdating + 1, }; return newZone; } case NgrxJsonApiActionTypes.API_DELETE_INIT: { newZone = { ...zone, data: updateResourceState(zone.data, action.payload, 'DELETED'), isDeleting: zone.isDeleting + 1, }; return newZone; } case NgrxJsonApiActionTypes.API_POST_SUCCESS: { newZone = { ...zone, data: updateStoreDataFromPayload(zone.data, action.payload.jsonApiData), isCreating: zone.isCreating - 1, }; return newZone; } case NgrxJsonApiActionTypes.API_GET_SUCCESS: { newZone = { ...zone, data: updateStoreDataFromPayload(zone.data, action.payload.jsonApiData), queries: updateQueryResults( zone.queries, action.payload.query.queryId, action.payload.jsonApiData ), isReading: zone.isReading - 1, }; return newZone; } case NgrxJsonApiActionTypes.API_PATCH_SUCCESS: { newZone = { ...zone, data: updateStoreDataFromPayload(zone.data, action.payload.jsonApiData), isUpdating: zone.isUpdating - 1, }; return newZone; } case NgrxJsonApiActionTypes.API_DELETE_SUCCESS: { newZone = { ...zone, data: deleteStoreResources(zone.data, action.payload.query), queries: updateQueriesForDeletedResource(zone.queries, { id: action.payload.query.id, type: action.payload.query.type, }), isDeleting: zone.isDeleting - 1, }; return newZone; } case NgrxJsonApiActionTypes.API_QUERY_REFRESH: { // clear result ids and wait until new data is fetched (triggered by effect) newZone = { ...zone, queries: clearQueryResult(zone.queries, action.payload), }; return newZone; } case NgrxJsonApiActionTypes.API_POST_FAIL: { newZone = { ...zone, data: updateResourceErrorsForQuery( zone.data, action.payload.query, action.payload.jsonApiData ), isCreating: zone.isCreating - 1, }; return newZone; } case NgrxJsonApiActionTypes.API_GET_FAIL: { newZone = { ...zone, queries: updateQueryErrors( zone.queries, action.payload.query.queryId, action.payload.jsonApiData ), isReading: zone.isReading - 1, }; return newZone; } case NgrxJsonApiActionTypes.API_PATCH_FAIL: { newZone = { ...zone, data: updateResourceErrorsForQuery( zone.data, action.payload.query, action.payload.jsonApiData ), isUpdating: zone.isUpdating - 1, }; return newZone; } case NgrxJsonApiActionTypes.API_DELETE_FAIL: { newZone = { ...zone, data: updateResourceErrorsForQuery( zone.data, action.payload.query, action.payload.jsonApiData ), isDeleting: zone.isDeleting - 1, }; return newZone; } case NgrxJsonApiActionTypes.REMOVE_QUERY: { let queryId = action.payload as string; newZone = { ...zone, queries: removeQuery(zone.queries, queryId) }; return newZone; } case NgrxJsonApiActionTypes.LOCAL_QUERY_INIT: { let query = action.payload as Query; newZone = { ...zone, queries: updateQueryParams(zone.queries, query) }; return newZone; } case NgrxJsonApiActionTypes.MODIFY_STORE_RESOURCE_ERRORS: { let payload = action.payload as ModifyStoreResourceErrorsPayload; newZone = { ...zone, data: updateResourceErrors( zone.data, payload.resourceId, payload.errors, payload.modificationType ), }; return newZone; } case NgrxJsonApiActionTypes.LOCAL_QUERY_SUCCESS: { return setIn( zone, 'queries', updateQueryResults( zone.queries, action.payload.query.queryId, action.payload.jsonApiData ) ); } case NgrxJsonApiActionTypes.PATCH_STORE_RESOURCE: { let updatedData = updateStoreDataFromResource( zone.data, action.payload, false, false ); if (updatedData !== zone.data) { newZone = { ...zone, data: updatedData }; return newZone; } else { return zone; } } case NgrxJsonApiActionTypes.POST_STORE_RESOURCE: { let updatedData = updateStoreDataFromResource( zone.data, action.payload, false, true ); if (updatedData !== zone.data) { newZone = { ...zone, data: updatedData }; return newZone; } else { return zone; } } case NgrxJsonApiActionTypes.NEW_STORE_RESOURCE: { let updatedData = updateStoreDataFromResource( zone.data, action.payload, false, true ); updatedData = updateResourceState(updatedData, action.payload, 'NEW'); if (updatedData !== zone.data) { newZone = { ...zone, data: updatedData }; return newZone; } else { return zone; } } case NgrxJsonApiActionTypes.DELETE_STORE_RESOURCE: { let resourceId = action.payload as ResourceIdentifier; if ( zone.data[resourceId.type] && zone.data[resourceId.type][resourceId.id] ) { let resource = zone.data[resourceId.type][resourceId.id]; if (resource.state === 'NEW' || resource.state === 'CREATED') { // not yet stored on server-side, just delete newZone = { ...zone, data: removeStoreResource(zone.data, resourceId), }; return newZone; } else { // stored on server, mark for deletion newZone = { ...zone, data: updateResourceState(zone.data, action.payload, 'DELETED'), }; return newZone; } } return zone; } case NgrxJsonApiActionTypes.API_APPLY_INIT: { let payload = (action as ApiApplyInitAction).payload; let pending: Array<StoreResource> = getPendingChanges( zone.data, payload.ids, payload.include ); newZone = { ...zone, isApplying: zone.isApplying + 1 }; for (let pendingChange of pending) { if (pendingChange.state === 'CREATED') { newZone.isCreating++; } else if (pendingChange.state === 'UPDATED') { newZone.isUpdating++; } else if (pendingChange.state === 'DELETED') { newZone.isDeleting++; } else { throw new Error('unknown state ' + pendingChange.state); } } return newZone; } case NgrxJsonApiActionTypes.API_APPLY_SUCCESS: case NgrxJsonApiActionTypes.API_APPLY_FAIL: { // apply all the committed or failed changes let actions = action.payload as Array<Action>; newZone = zone; for (let commitAction of actions) { newZone = NgrxJsonApiZoneReducer(newZone, commitAction); } newZone = { ...newZone, isApplying: zone['isApplying'] - 1 }; return newZone; } case NgrxJsonApiActionTypes.API_ROLLBACK: { let payload = (action as ApiRollbackAction).payload; newZone = { ...zone, data: rollbackStoreResources(zone.data, payload.ids, payload.include), }; return newZone; } case NgrxJsonApiActionTypes.CLEAR_STORE: { return initialNgrxJsonApiZone; } case NgrxJsonApiActionTypes.COMPACT_STORE: { return compactStore(zone); } default: return zone; } } export const reducer = NgrxJsonApiStoreReducer;
the_stack
import Cascade from '../cascade/Cascade'; import { observable } from '../cascade/Decorators'; import { wait } from '../util/PromiseUtil'; import { Component } from './Component'; describe('Component.diff', () => { it.skip('should update nested roots', async () => { class ViewModel { @observable value = false; } class Content extends Component<IViewProps> { render() { return this.props.viewModel.value ? null : true; } } interface IViewProps { viewModel?: ViewModel; } class View extends Component<IViewProps> { render() { return <Content viewModel={viewModel} />; } } var viewModel = new ViewModel(); var container = document.createElement('div'); Cascade.render(container, <View viewModel={viewModel} />); viewModel.value = true; await wait(200); expect(container.textContent).toBe(''); }); it('should update nested roots', async () => { class ViewModel { @observable value = false; } interface IViewProps { viewModel?: ViewModel; } class Content extends Component<IViewProps> { render() { return this.props.viewModel.value ? true : null; } } class Container extends Component<IViewProps> { render() { return ( <section> <header>Header</header> <div>{this.children}</div> </section> ); } } class View extends Component<IViewProps> { render() { return ( <Container> <Content viewModel={viewModel} /> </Container> ); } } var viewModel = new ViewModel(); var container = document.createElement('div'); Cascade.render(container, <View viewModel={viewModel} />); viewModel.value = true; await wait(20); expect(container.childNodes[0].childNodes[1].textContent).toBe('true'); }); it('should update empty nested Components', async () => { class ViewModel { @observable value = false; } interface IContentProps { value: boolean; } class Content extends Component<IContentProps> { render() { return this.props.value ? true : null; } } interface IViewProps { viewModel: ViewModel; } class View extends Component<IViewProps> { render() { return <Content value={viewModel.value} />; } } var viewModel = new ViewModel(); var root = ( <div> <View viewModel={viewModel} /> </div> ); var container = document.createElement('div'); Cascade.render(container, root); // Change the value let result = Cascade.set(viewModel, 'value', true); // Inspect immediately expect(container.childNodes[0].childNodes.length).toBe(1); expect(container.childNodes[0].childNodes[0].nodeType).toBe(Node.COMMENT_NODE); // Wait for propagation await result; // Inspect again expect(container.childNodes[0].childNodes.length).toBe(1); expect(container.childNodes[0].childNodes[0].nodeType).toBe(Node.TEXT_NODE); // Change the value and wait await Cascade.set(viewModel, 'value', false); // Inspect again expect(container.childNodes[0].childNodes.length).toBe(1); expect(container.childNodes[0].childNodes[0].nodeType).toBe(Node.COMMENT_NODE); }); it('should update empty Components', async () => { class ViewModel { @observable value = false; } interface IContentProps { value: boolean; } class Content extends Component<IContentProps> { render() { return this.props.value ? true : null; } } interface IViewProps { viewModel: ViewModel; } class View extends Component<IViewProps> { render() { return ( <div> <Content value={viewModel.value} /> </div> ); } } var viewModel = new ViewModel(); var root = ( <div> <View viewModel={viewModel} /> </div> ); var container = document.createElement('div'); Cascade.render(container, root); // Change the value let result = Cascade.set(viewModel, 'value', true); // Inspect immediately expect(container.childNodes[0].childNodes[0].childNodes.length).toBe(1); expect(container.childNodes[0].childNodes[0].childNodes[0].nodeType).toBe( Node.COMMENT_NODE, ); // Wait for propagation await result; // Inspect again expect(container.childNodes[0].childNodes[0].childNodes.length).toBe(1); expect(container.childNodes[0].childNodes[0].childNodes[0].nodeType).toBe(Node.TEXT_NODE); // Change the value and wait await Cascade.set(viewModel, 'value', false); // Inspect again expect(container.childNodes[0].childNodes[0].childNodes.length).toBe(1); expect(container.childNodes[0].childNodes[0].childNodes[0].nodeType).toBe( Node.COMMENT_NODE, ); }); it('should delete null values', async () => { class ViewModel { @observable nonNull = 'nonNull'; @observable nonUndefined = 'nonUndefined'; } interface IViewProps { viewModel: ViewModel; } class View extends Component<IViewProps> { render() { return <div className={viewModel.nonNull} id={viewModel.nonUndefined}></div>; } } var viewModel = new ViewModel(); var root = ( <div> <View viewModel={viewModel} /> </div> ); var container = document.createElement('div'); Cascade.render(container, root); viewModel.nonNull = null; viewModel.nonUndefined = undefined; await wait(20); let div = container.childNodes[0].childNodes[0] as HTMLElement; expect(div.className).not.toBe('nonNull'); expect(div.id).not.toBe('nonUndefined'); expect(div.className).not.toBe('null'); expect(div.id).not.toBe('undefined'); }); it('should handle new child Components', async () => { class ViewModel { @observable visible: boolean = false; } class StaticChild extends Component<any> { render() { return <div id="static">static child</div>; } } class DynamicChild extends Component<any> { render() { return <div id="dynamic">dynamic child</div>; } } interface IParentProps { viewModel: ViewModel; } class Parent extends Component<IParentProps> { render() { let { viewModel } = this.props; return ( <div id="parent"> <StaticChild /> {viewModel.visible ? <DynamicChild /> : undefined} </div> ); } } var viewModel = new ViewModel(); var root = ( <div id="root"> <Parent viewModel={viewModel} /> </div> ); var container = document.createElement('div'); Cascade.render(container, root); await wait(0); viewModel.visible = true; await wait(20); let divRoot = container.childNodes[0] as HTMLElement; let divParent = divRoot.childNodes[0] as HTMLElement; let divStatic = divParent.childNodes[0] as HTMLElement; let divDynamic = divParent.childNodes[1] as HTMLElement; expect(divStatic).toBeDefined(); expect(divDynamic).toBeDefined(); if (divDynamic) { expect(divDynamic.id).toBe('dynamic'); } }); it('should handle change from null child Components', async () => { class ViewModel { @observable visible: boolean = false; } class StaticChild extends Component<any> { render() { return <div id="static">static child</div>; } } class DynamicChild extends Component<any> { render() { return <div id="dynamic">dynamic child</div>; } } interface IParentProps { viewModel: ViewModel; } class Parent extends Component<IParentProps> { render() { let { viewModel } = this.props; return ( <div id="parent"> <StaticChild /> {viewModel.visible ? <DynamicChild /> : null} </div> ); } } var viewModel = new ViewModel(); var root = ( <div id="root"> <Parent viewModel={viewModel} /> </div> ); var container = document.createElement('div'); Cascade.render(container, root); await wait(0); viewModel.visible = true; await wait(20); let divRoot = container.childNodes[0] as HTMLElement; let divParent = divRoot.childNodes[0] as HTMLElement; let divStatic = divParent.childNodes[0] as HTMLElement; let divDynamic = divParent.childNodes[1] as HTMLElement; expect(divStatic).toBeDefined(); expect(divDynamic).toBeDefined(); if (divDynamic) { expect(divDynamic.id).toBe('dynamic'); } }); it('should handle change to null child Components', async () => { class ViewModel { @observable visible: boolean = true; } class StaticChild extends Component<any> { render() { return <div id="static">static child</div>; } } class DynamicChild extends Component<any> { render() { return <div id="dynamic">dynamic child</div>; } } interface IParentProps { viewModel: ViewModel; } class Parent extends Component<IParentProps> { render() { let { viewModel } = this.props; return ( <div id="parent"> <StaticChild /> {viewModel.visible ? <DynamicChild /> : null} </div> ); } } var viewModel = new ViewModel(); var root = ( <div id="root"> <Parent viewModel={viewModel} /> </div> ); var container = document.createElement('div'); Cascade.render(container, root); await wait(0); viewModel.visible = false; await wait(20); let divRoot = container.childNodes[0] as HTMLElement; let divParent = divRoot.childNodes[0] as HTMLElement; let divStatic = divParent.childNodes[0] as HTMLElement; let divDynamic = divParent.childNodes[1] as HTMLElement; expect(divStatic).toBeDefined(); expect(divDynamic).toBeUndefined(); }); it('should handle change null to null', async () => { class ViewModel { @observable visible: boolean = false; } class StaticChild extends Component<any> { render() { return <div id="static">static child</div>; } } class DynamicChild extends Component<any> { render() { return <div id="dynamic">dynamic child</div>; } } interface IParentProps { viewModel: ViewModel; } class Parent extends Component<IParentProps> { render() { let { viewModel } = this.props; return ( <div id="parent"> <StaticChild /> {viewModel.visible ? null : null} </div> ); } } var viewModel = new ViewModel(); var root = ( <div id="root"> <Parent viewModel={viewModel} /> </div> ); var container = document.createElement('div'); Cascade.render(container, root); await wait(0); viewModel.visible = true; await wait(20); let divRoot = container.childNodes[0] as HTMLElement; let divParent = divRoot.childNodes[0] as HTMLElement; let divStatic = divParent.childNodes[0] as HTMLElement; let divDynamic = divParent.childNodes[1] as HTMLElement; expect(divStatic).toBeDefined(); expect(divDynamic).toBeUndefined(); }); });
the_stack
import { createVElement, VElement, VAttributes, VNode, VLifecycle, isVElement, merge } from './dom' import { combineLifecycles } from './lifecycle' import { style, types } from 'typestyle' import { NestedCSSProperties } from 'typestyle/lib/types' export type HAttributeValue = undefined | string | number | ((ev:any) => any) | NestedCSSProperties export interface HAttributes extends VAttributes, KnownHtmlAttributes { [key: string] : HAttributeValue } export type HValue = VNode | HAttributes | VLifecycle | null | undefined export type HValues = HValue | VNode[] function typeStyleize (attrs?: HAttributes) { if (attrs && typeof (attrs.style) === 'object') { attrs.class = ! attrs.class ? style (attrs.style) : attrs.class + " " + style (attrs.style) attrs.style = undefined } } /** Merges two attribute structures, where style structures are converted to classes using style style, * classes are combined, and lifecycle hooks are combined. */ export function mergeAttrs (dominant: HAttributes | undefined, recessive: HAttributes | undefined) { return mergeAttrsMutate ({...dominant}, {...recessive}) } function mergeAttrsMutate (dominant: HAttributes | undefined, recessive: HAttributes | undefined) { typeStyleize (dominant) typeStyleize (recessive) if (! dominant) return recessive else if (! recessive) return dominant if (dominant.class && recessive.class) dominant.class = dominant.class + " " + recessive.class dominant = <HAttributes> combineLifecycles (dominant, recessive) dominant = <HAttributes> merge (dominant, recessive) return dominant } function isAttribute (a?: any): a is HAttributes { return a != null && typeof a == "object" && ! isVElement(<any>a) && ! Array.isArray(a) } export function h (tag: string, ...values: HValues[]): VElement { var attrs: HAttributes | undefined while (values.length > 0) { var head = values[0] if (isAttribute (head)) { attrs = mergeAttrsMutate (attrs, head) values.shift() } else if (head == null) values.shift() else break } return createVElement(tag, attrs || {}, ...values) } export function a(...values: HValues[]) { return h("a", ...values) } export function abbr(...values: HValues[]) { return h("abbr", ...values) } export function address(...values: HValues[]) { return h("address", ...values) } export function area(...values: HValues[]) { return h("area", ...values) } export function article(...values: HValues[]) { return h("article", ...values) } export function aside(...values: HValues[]) { return h("aside", ...values) } export function audio(...values: HValues[]) { return h("audio", ...values) } export function b(...values: HValues[]) { return h("b", ...values) } export function bdi(...values: HValues[]) { return h("bdi", ...values) } export function bdo(...values: HValues[]) { return h("bdo", ...values) } export function blockquote(...values: HValues[]) { return h("blockquote", ...values) } export function br(...values: HValues[]) { return h("br", ...values) } export function button(...values: HValues[]) { return h("button", ...values) } export function canvas(...values: HValues[]) { return h("canvas", ...values) } export function caption(...values: HValues[]) { return h("caption", ...values) } export function cite(...values: HValues[]) { return h("cite", ...values) } export function code(...values: HValues[]) { return h("code", ...values) } export function col(...values: HValues[]) { return h("col", ...values) } export function colgroup(...values: HValues[]) { return h("colgroup", ...values) } export function data(...values: HValues[]) { return h("data", ...values) } export function datalist(...values: HValues[]) { return h("datalist", ...values) } export function dd(...values: HValues[]) { return h("dd", ...values) } export function del(...values: HValues[]) { return h("del", ...values) } export function details(...values: HValues[]) { return h("details", ...values) } export function dfn(...values: HValues[]) { return h("dfn", ...values) } export function dialog(...values: HValues[]) { return h("dialog", ...values) } export function div(...values: HValues[]) { return h("div", ...values) } export function dl(...values: HValues[]) { return h("dl", ...values) } export function dt(...values: HValues[]) { return h("dt", ...values) } export function em(...values: HValues[]) { return h("em", ...values) } export function embed(...values: HValues[]) { return h("embed", ...values) } export function fieldset(...values: HValues[]) { return h("fieldset", ...values) } export function figcaption(...values: HValues[]) { return h("figcaption", ...values) } export function figure(...values: HValues[]) { return h("figure", ...values) } export function footer(...values: HValues[]) { return h("footer", ...values) } export function form(...values: HValues[]) { return h("form", ...values) } export function h1(...values: HValues[]) { return h("h1", ...values) } export function h2(...values: HValues[]) { return h("h2", ...values) } export function h3(...values: HValues[]) { return h("h3", ...values) } export function h4(...values: HValues[]) { return h("h4", ...values) } export function h5(...values: HValues[]) { return h("h5", ...values) } export function h6(...values: HValues[]) { return h("h6", ...values) } export function header(...values: HValues[]) { return h("header", ...values) } export function hr(...values: HValues[]) { return h("hr", ...values) } export function i(...values: HValues[]) { return h("i", ...values) } export function iframe(...values: HValues[]) { return h("iframe", ...values) } export function img(...values: HValues[]) { return h("img", ...values) } export function input(...values: HValues[]) { return h("input", ...values) } export function ins(...values: HValues[]) { return h("ins", ...values) } export function kbd(...values: HValues[]) { return h("kbd", ...values) } export function label(...values: HValues[]) { return h("label", ...values) } export function legend(...values: HValues[]) { return h("legend", ...values) } export function li(...values: HValues[]) { return h("li", ...values) } export function main(...values: HValues[]) { return h("main", ...values) } export function map(...values: HValues[]) { return h("map", ...values) } export function mark(...values: HValues[]) { return h("mark", ...values) } export function menu(...values: HValues[]) { return h("menu", ...values) } export function menuitem(...values: HValues[]) { return h("menuitem", ...values) } export function meter(...values: HValues[]) { return h("meter", ...values) } export function nav(...values: HValues[]) { return h("nav", ...values) } export function object(...values: HValues[]) { return h("object", ...values) } export function ol(...values: HValues[]) { return h("ol", ...values) } export function optgroup(...values: HValues[]) { return h("optgroup", ...values) } export function option(...values: HValues[]) { return h("option", ...values) } export function output(...values: HValues[]) { return h("output", ...values) } export function p(...values: HValues[]) { return h("p", ...values) } export function param(...values: HValues[]) { return h("param", ...values) } export function pre(...values: HValues[]) { return h("pre", ...values) } export function progress(...values: HValues[]) { return h("progress", ...values) } export function q(...values: HValues[]) { return h("q", ...values) } export function rp(...values: HValues[]) { return h("rp", ...values) } export function rt(...values: HValues[]) { return h("rt", ...values) } export function rtc(...values: HValues[]) { return h("rtc", ...values) } export function ruby(...values: HValues[]) { return h("ruby", ...values) } export function s(...values: HValues[]) { return h("s", ...values) } export function samp(...values: HValues[]) { return h("samp", ...values) } export function section(...values: HValues[]) { return h("section", ...values) } export function select(...values: HValues[]) { return h("select", ...values) } export function small(...values: HValues[]) { return h("small", ...values) } export function source(...values: HValues[]) { return h("source", ...values) } export function span(...values: HValues[]) { return h("span", ...values) } export function strong(...values: HValues[]) { return h("strong", ...values) } export function sub(...values: HValues[]) { return h("sub", ...values) } export function summary(...values: HValues[]) { return h("summary", ...values) } export function sup(...values: HValues[]) { return h("sup", ...values) } export function svg(...values: HValues[]) { return h("svg", ...values) } export function table(...values: HValues[]) { return h("table", ...values) } export function tbody(...values: HValues[]) { return h("tbody", ...values) } export function td(...values: HValues[]) { return h("td", ...values) } export function textarea(...values: HValues[]) { return h("textarea", ...values) } export function tfoot(...values: HValues[]) { return h("tfoot", ...values) } export function th(...values: HValues[]) { return h("th", ...values) } export function thead(...values: HValues[]) { return h("thead", ...values) } export function time(...values: HValues[]) { return h("time", ...values) } export function tr(...values: HValues[]) { return h("tr", ...values) } export function track(...values: HValues[]) { return h("track", ...values) } export function u(...values: HValues[]) { return h("u", ...values) } export function ul(...values: HValues[]) { return h("ul", ...values) } export function video(...values: HValues[]) { return h("video", ...values) } export function vvar(...values: HValues[]) { return h("vvar", ...values) } export function wbr(...values: HValues[]) { return h("wbr", ...values) } export interface KnownHtmlAttributes { accept?: string accesskey?: string action?: string align?: string alt?: string async?: string autocapitalize?: string autocomplete?: string autofocus?: string autoplay?: string bgcolor?: string border?: string buffered?: string challenge?: string charset?: string checked?: string cite?: string class?: string code?: string codebase?: string color?: string cols?: number colspan?: number content?: string contenteditable?: string contextmenu?: string controls?: string coords?: string crossorigin?: string data?: string datetime?: string default?: string defer?: string dir?: string dirname?: string disabled?: string download?: string draggable?: string dropzone?: string enctype?: string for?: string form?: string formaction?: string headers?: string height?: string | number hidden?: string high?: number href?: string hreflang?: string http?: string icon?: string id?: string integrity?: string ismap?: string itemprop?: string keytype?: string kind?: string label?: string lang?: string language?: string list?: string loop?: string low?: number manifest?: string max?: number maxlength?: number minlength?: number media?: string method?: string min?: number multiple?: string muted?: string name?: string novalidate?: string open?: string optimum?: string pattern?: string ping?: string placeholder?: string poster?: string preload?: string radiogroup?: string readonly?: string rel?: string required?: string reversed?: string rows?: number rowspan?: number sandbox?: string scope?: string scoped?: string seamless?: string selected?: string shape?: string size?: number sizes?: string slot?: string span?: string spellcheck?: string src?: string srcdoc?: string srclang?: string srcset?: string start?: string step?: number style?: string | types.NestedCSSProperties summary?: string tabindex?: number target?: string title?: string type?: string usemap?: string value?: string | number width?: string | number wrap?: string onabort?: (ev:UIEvent) => any onanimationcancel?: (ev:AnimationEvent) => any onanimationend?: (ev:AnimationEvent) => any onanimationiteration?: (ev:AnimationEvent) => any onanimationstart?: (ev:AnimationEvent) => any onauxclick?: (ev:Event) => any /** * Fires when the object loses the input focus. * @param ev The focus event. */ onblur?: (ev:FocusEvent) => any oncancel?: (ev:Event) => any /** * Occurs when playback is possible, but would require further buffering. * @param ev The event. */ oncanplay?: (ev:Event) => any oncanplaythrough?: (ev:Event) => any /** * Fires when the contents of the object or selection have changed. * @param ev The event. */ onchange?: (ev:Event) => any /** * Fires when the user clicks the left mouse button on the object * @param ev The mouse event. */ onclick?: (ev:MouseEvent) => any onclose?: (ev:Event) => any /** * Fires when the user clicks the right mouse button in the client area, opening the context menu. * @param ev The mouse event. */ oncontextmenu?: (ev:MouseEvent) => any oncuechange?: (ev:Event) => any /** * Fires when the user double-clicks the object. * @param ev The mouse event. */ ondblclick?: (ev:MouseEvent) => any /** * Fires on the source object continuously during a drag operation. * @param ev The event. */ ondrag?: (ev:DragEvent) => any /** * Fires on the source object when the user releases the mouse at the close of a drag operation. * @param ev The event. */ ondragend?: (ev:DragEvent) => any /** * Fires on the target element when the user drags the object to a valid drop target. * @param ev The drag event. */ ondragenter?: (ev:DragEvent) => any ondragexit?: (ev:Event) => any /** * Fires on the target object when the user moves the mouse out of a valid drop target during a drag operation. * @param ev The drag event. */ ondragleave?: (ev:DragEvent) => any /** * Fires on the target element continuously while the user drags the object over a valid drop target. * @param ev The event. */ ondragover?: (ev:DragEvent) => any /** * Fires on the source object when the user starts to drag a text selection or selected object. * @param ev The event. */ ondragstart?: (ev:DragEvent) => any ondrop?: (ev:DragEvent) => any /** * Occurs when the duration attribute is updated. * @param ev The event. */ ondurationchange?: (ev:Event) => any /** * Occurs when the media element is reset to its initial state. * @param ev The event. */ onemptied?: (ev:Event) => any /** * Occurs when the end of playback is reached. * @param ev The event */ onended?: (ev:Event) => any /** * Fires when the object receives focus. * @param ev The event. */ onfocus?: (ev:FocusEvent) => any ongotpointercapture?: (ev:PointerEvent) => any oninput?: (ev:Event) => any oninvalid?: (ev:Event) => any /** * Fires when the user presses a key. * @param ev The keyboard event */ onkeydown?: (ev:KeyboardEvent) => any /** * Fires when the user presses an alphanumeric key. * @param ev The event. */ onkeypress?: (ev:KeyboardEvent) => any /** * Fires when the user releases a key. * @param ev The keyboard event */ onkeyup?: (ev:KeyboardEvent) => any /** * Fires immediately after the browser loads the object. * @param ev The event. */ onload?: (ev:Event) => any /** * Occurs when media data is loaded at the current playback position. * @param ev The event. */ onloadeddata?: (ev:Event) => any /** * Occurs when the duration and dimensions of the media have been determined. * @param ev The event. */ onloadedmetadata?: (ev:Event) => any onloadend?: (ev:ProgressEvent) => any /** * Occurs when Internet Explorer begins looking for media data. * @param ev The event. */ onloadstart?: (ev:Event) => any onlostpointercapture?: (ev:PointerEvent) => any /** * Fires when the user clicks the object with either mouse button. * @param ev The mouse event. */ onmousedown?: (ev:MouseEvent) => any onmouseenter?: (ev:MouseEvent) => any onmouseleave?: (ev:MouseEvent) => any /** * Fires when the user moves the mouse over the object. * @param ev The mouse event. */ onmousemove?: (ev:MouseEvent) => any /** * Fires when the user moves the mouse pointer outside the boundaries of the object. * @param ev The mouse event. */ onmouseout?: (ev:MouseEvent) => any /** * Fires when the user moves the mouse pointer into the object. * @param ev The mouse event. */ onmouseover?: (ev:MouseEvent) => any /** * Fires when the user releases a mouse button while the mouse is over the object. * @param ev The mouse event. */ onmouseup?: (ev:MouseEvent) => any /** * Occurs when playback is paused. * @param ev The event. */ onpause?: (ev:Event) => any /** * Occurs when the play method is requested. * @param ev The event. */ onplay?: (ev:Event) => any /** * Occurs when the audio or video has started playing. * @param ev The event. */ onplaying?: (ev:Event) => any onpointercancel?: (ev:PointerEvent) => any onpointerdown?: (ev:PointerEvent) => any onpointerenter?: (ev:PointerEvent) => any onpointerleave?: (ev:PointerEvent) => any onpointermove?: (ev:PointerEvent) => any onpointerout?: (ev:PointerEvent) => any onpointerover?: (ev:PointerEvent) => any onpointerup?: (ev:PointerEvent) => any /** * Occurs to indicate progress while downloading media data. * @param ev The event. */ onprogress?: (ev:ProgressEvent) => any /** * Occurs when the playback rate is increased or decreased. * @param ev The event. */ onratechange?: (ev:Event) => any /** * Fires when the user resets a form. * @param ev The event. */ onreset?: (ev:Event) => any onresize?: (ev:UIEvent) => any /** * Fires when the user repositions the scroll box in the scroll bar on the object. * @param ev The event. */ onscroll?: (ev:UIEvent) => any onsecuritypolicyviolation?: (ev:SecurityPolicyViolationEvent) => any /** * Occurs when the seek operation ends. * @param ev The event. */ onseeked?: (ev:Event) => any /** * Occurs when the current playback position is moved. * @param ev The event. */ onseeking?: (ev:Event) => any /** * Fires when the current selection changes. * @param ev The event. */ onselect?: (ev:UIEvent) => any /** * Occurs when the download has stopped. * @param ev The event. */ onstalled?: (ev:Event) => any onsubmit?: (ev:Event) => any /** * Occurs if the load operation has been intentionally halted. * @param ev The event. */ onsuspend?: (ev:Event) => any /** * Occurs to indicate the current playback position. * @param ev The event. */ ontimeupdate?: (ev:Event) => any ontoggle?: (ev:Event) => any ontouchcancel?: (ev:TouchEvent) => any ontouchend?: (ev:TouchEvent) => any ontouchmove?: (ev:TouchEvent) => any ontouchstart?: (ev:TouchEvent) => any ontransitioncancel?: (ev:TransitionEvent) => any ontransitionend?: (ev:TransitionEvent) => any ontransitionrun?: (ev:TransitionEvent) => any ontransitionstart?: (ev:TransitionEvent) => any /** * Occurs when the volume is changed, or playback is muted or unmuted. * @param ev The event. */ onvolumechange?: (ev:Event) => any /** * Occurs when playback stops because the next frame of a video resource is not available. * @param ev The event. */ onwaiting?: (ev:Event) => any onwheel?: (ev:WheelEvent) => any }
the_stack
module BABYLONX { export class Demoscene { static objInstances: number; private _engine; private _scene; private _canvas; private _camera; private _light; constructor(engine, canvas) { Demoscene.objInstances = 0 | (Demoscene.objInstances + 1); if (engine == undefined || canvas == undefined) { this.init(); } else { this._canvas = canvas; this._engine = engine; this._scene = new BABYLON.Scene(engine); this.cameras(); this.lights(); } } init() { this.dom(); this._engine = new BABYLON.Engine(this._canvas, true, { stencil: true }); this._scene = new BABYLON.Scene(this._engine); this.cameras(); this.lights(); //this.objects(); //this._scene.debugLayer.show(); this._engine.runRenderLoop(this.renderloop.bind(this)); } dom() { this._canvas = document.getElementById("renderCanvas"); } cameras() { this._camera = new BABYLON.ArcRotateCamera("camera", -Math.PI / 2 + .2, Math.PI / 2, 10, new BABYLON.Vector3(-2.0, 10.19, 22.73), this._scene); this._camera.setTarget(new BABYLON.Vector3(0, 0, 0)); this._camera.attachControl(this._canvas, true); this._camera.wheelPrecision = 9; this._camera.radius = 25; this._camera.alpha = Math.PI/2; this._camera.beta = 1.2; } lights() { var lightpos = new BABYLON.Vector3(0, 10, 0); this._light = new BABYLON.HemisphericLight("light1", new BABYLON.Vector3(0, 3, -10), this._scene); this._light.groundColor = new BABYLON.Color3(.9, .9, .9); this._light.intensity = 1.0; } objects() { } createCubePlain(size = { w: 1, h: 1, d: 1 }, color = "#FF0000", specular = "#0000FF") { var options = { width: size.w, depth: size.d, height: size.h }; var cube = BABYLON.MeshBuilder.CreateBox("cube" + Demoscene.objInstances, options, this._scene); var mat = new BABYLON.StandardMaterial("mcube" + Demoscene.objInstances, this._scene); mat.diffuseColor = BABYLON.Color3.FromHexString(color); mat.specularColor = BABYLON.Color3.FromHexString(specular); cube.material = mat; Demoscene.objInstances++; return cube; } createCube(size = { w: 1, h: 1, d: 1 }, color = "#FF0000") { var options = { width: size.w, depth: size.d, height: size.h }; var cube = BABYLON.MeshBuilder.CreateBox("cube" + Demoscene.objInstances, options, this._scene); var mat = new BABYLON.StandardMaterial("mcube" + Demoscene.objInstances, this._scene); mat.diffuseColor = BABYLON.Color3.FromHexString(color); mat.specularColor = BABYLON.Color3.Green(); //mat.wireframe=true; cube.material = mat; var marbleTexture = new BABYLON.MarbleProceduralTexture("marble" + Demoscene.objInstances, 512, this._scene); marbleTexture.numberOfTilesHeight = 5; marbleTexture.numberOfTilesWidth = 5; marbleTexture.jointColor = new BABYLON.Color3(0, 0, 1); //marbleTexture.marbleColor=new BABYLON.Color3(1,0,0); marbleTexture.amplitude = 9.0; mat.diffuseTexture = marbleTexture; //mat.alpha=.3; //mat.diffuseTexture.hasAlpha=true; Demoscene.objInstances++; return cube; } createCylinder(height = 1, color = "#00ff00", top = 0.5, bottom = 0.5) { var mat = new BABYLON.StandardMaterial("cmat" + Demoscene.objInstances, this._scene); var cone = BABYLON.MeshBuilder.CreateCylinder("cone" + Demoscene.objInstances, { height: height, diameterTop: top, diameterBottom: bottom, tessellation: 32 }, this._scene); //var cone = BABYLON.MeshBuilder.CreateCylinder("cone" + Demoscene.objInstances, { height: height, tessellation: 32 }, this._scene); mat.diffuseColor = BABYLON.Color3.FromHexString(color); mat.specularColor = BABYLON.Color3.Green(); cone.material = mat; var marbleTexture = new BABYLON.MarbleProceduralTexture("marble" + Demoscene.objInstances, 512, this._scene); marbleTexture.numberOfTilesHeight = 1.0; marbleTexture.numberOfTilesWidth = .5; //marbleTexture.jointColor=new BABYLON.Color3(0,0,1); //marbleTexture.marbleColor=new BABYLON.Color3(1,0,0); marbleTexture.amplitude = 9.2; mat.diffuseTexture = marbleTexture; Demoscene.objInstances++; //cone.rotation.x=Math.PI/4; return cone; } createIcoSphere(radius = 6) { var mesh = BABYLON.MeshBuilder.CreateIcoSphere("m", { radius: radius }, this._scene); mesh.updateFacetData(); return mesh; } createSphere(diameter = 1, color = "#0000ff", segments = 32) { var mat = new BABYLON.StandardMaterial("stdmat" + Demoscene.objInstances, this._scene); var sphere = BABYLON.MeshBuilder.CreateSphere("sphere" + Demoscene.objInstances, { diameter: diameter, segments: segments }, this._scene); //mat.diffuseTexture= new BABYLON.Texture("testtexture.png",this.scene); var marbleTexture = new BABYLON.MarbleProceduralTexture("marble" + Demoscene.objInstances, 512, this._scene); marbleTexture.numberOfTilesHeight = 1.0; marbleTexture.numberOfTilesWidth = .5; //marbleTexture.jointColor=new BABYLON.Color3(0,0,1); //marbleTexture.marbleColor=new BABYLON.Color3(1,0,0); marbleTexture.amplitude = 9.2; mat.diffuseTexture = marbleTexture; mat.diffuseColor = BABYLON.Color3.FromHexString(color); mat.specularColor = BABYLON.Color3.Green(); sphere.material = mat; Demoscene.objInstances++; return sphere; } assignMaterial(mesh,color) { var mat = new BABYLON.StandardMaterial("mcube" + Demoscene.objInstances, this._scene); mat.diffuseColor = BABYLON.Color3.FromHexString(color); mat.specularColor = BABYLON.Color3.White(); mesh.material = mat; Demoscene.objInstances++; } assignMarbleMaterial(mesh, marblecolor,jointclolor="#0000FF") { var mat = new BABYLON.StandardMaterial("mmat" + Demoscene.objInstances, this._scene); mat.diffuseColor = BABYLON.Color3.FromHexString(marblecolor); //mat.specularColor = BABYLON.Color3.FromHexString(jointclolor); //mat.wireframe=true; mesh.material = mat; var marbleTexture = new BABYLON.MarbleProceduralTexture("marble" + Demoscene.objInstances, 512, this._scene); marbleTexture.numberOfTilesHeight = .5; marbleTexture.numberOfTilesWidth = .45; marbleTexture.jointColor = BABYLON.Color3.FromHexString(marblecolor); new BABYLON.Color3(0, 0, 1); //marbleTexture.marbleColor=new BABYLON.Color3(1,0,0); marbleTexture.amplitude = 9; mat.diffuseTexture = marbleTexture; //mat.alpha=.3; //mat.diffuseTexture.hasAlpha=true; Demoscene.objInstances++; } assignMetalMaterial(mesh) { var hdrTexture = new BABYLON.HDRCubeTexture("assets/roombwblur.hdr", this._scene, 512); var metal = new BABYLON.PBRMaterial("xmetal" + Demoscene.objInstances, this._scene); metal.reflectionTexture = hdrTexture; metal.microSurface = 1; metal.reflectivityColor = new BABYLON.Color3(0.9, 0.9, 0.9); metal.albedoColor = new BABYLON.Color3(0.02, 0.02, 0.62); metal.environmentIntensity = 0.7; metal.cameraExposure = 0.66; metal.cameraContrast = 1.66; mesh.material = metal; Demoscene.objInstances++; } assignGlassMaterial(mesh) { var hdrTexture = new BABYLON.HDRCubeTexture("assets/roombwblur.hdr", this._scene, 512); var glass = new BABYLON.PBRMaterial("glass", this._scene); glass.reflectionTexture = hdrTexture; glass.alpha = 0.935; glass.environmentIntensity = 0.657; glass.cameraExposure = 10.6 glass.cameraContrast = 1;//0.66; glass.microSurface = 1; glass.reflectivityColor = new BABYLON.Color3(.93, .3, .3);//(0.2, 0.42, 0.42); glass.albedoColor = new BABYLON.Color3(0, 0, 0);//new BABYLON.Color3(0.0095, 0.0095, 0.0095); mesh.material = glass; //mesh.material.diffuseColor = new BABYLON.Color3(.5, .0, .0); //mesh.material.specularColor = new BABYLON.Color3(.5, .0, .0); //mesh.material.emissiveColor = new BABYLON.Color3(.5, .0, .0); /* var loader = new BABYLON.AssetsManager(this._scene); var textureTask = loader.addTextureTask("image task", "assets/roombwblur.hdr"); var glass = new BABYLON.PBRMaterial("glass", this._scene); textureTask.onSuccess = function (task) { //var hdrTexture = new BABYLON.HDRCubeTexture("assets/roombwblur.hdr", this._scene, 512); glass.reflectionTexture = task.texture; glass.alpha = 0.35; glass.environmentIntensity = 0.657; glass.cameraExposure = 20.6 glass.cameraContrast = 1;//0.66; glass.microSurface = 1; glass.reflectivityColor = new BABYLON.Color3(.3, .3, .3);//(0.2, 0.42, 0.42); glass.albedoColor = new BABYLON.Color3(0, 0, 0);//new BABYLON.Color3(0.0095, 0.0095, 0.0095); mesh.material = glass; } loader.load(); */ } renderloop() { this._scene.render(); } get scene() { return this._scene; } get engine() { return this._engine; } get camera() { return this._camera; } get light() { return this._light; } } export class CMesh extends BABYLON.Mesh { private _cloner = null; _index: number = 0; constructor(name, scene, parent, cloner = null) { super(name, scene, parent); this._cloner = cloner; //this.parent=parent; } delete() { if (this._cloner != null) { this._cloner.delete(); } else { this.getChildren()[0].dispose(); } this.parent = null; this.dispose(); } createClone(item, useInstances, name) { var c; if (item instanceof Cloner) { c = item.createClone(this); } else { if (useInstances) { c = item.createInstance(name + "_i"); c.parent = this; } else { c = item.clone(name + "_c"); c.parent = this; } } return c; } } export class RandomEffector { private _seed: number; private _s: number; private _rfunction; private _strength: number = 0.0; private _position: BABYLON.Vector3 = new BABYLON.Vector3(0, 0, 0); private _rotation: BABYLON.Vector3 = new BABYLON.Vector3(0, 0, 0); private _scale: BABYLON.Vector3 = new BABYLON.Vector3(0, 0, 0); private _uniformScale = false; private _clients = []; constructor(seed = 42) { this._seed = this._s = seed; this._rfunction = function () { this._s = Math.sin(this._s) * 10000; return this._s - Math.floor(this._s); }; } random(): number { return this._rfunction(); } reset(): void { this._s = this._seed; } updateRotation(vec: BABYLON.Vector3) { var m1 = this._rotation.multiplyByFloats((-.5 + this.random()) * this._strength, (-.5 + this.random()) * this._strength, (-.5 + this.random()) * this._strength); return vec.add(m1); } updatePosition(vec: BABYLON.Vector3) { var m1 = this._position.multiplyByFloats((-.5 + this.random()) * this._strength, (-.5 + this.random()) * this._strength, (-.5 + this.random()) * this._strength); return vec.add(m1); } updateScale(vec: BABYLON.Vector3) { let a = this.random(); let b = a; let c = a; if (this._uniformScale == false) { b = this.random(); c = this.random(); } var m1 = this._scale.multiplyByFloats((-.5 + a) * this._strength, (-.5 + b) * this._strength, (-.5 + b) * this._strength); //var m1=this._scale.multiplyByFloats(this._strength,this._strength,this._strength); return vec.add(m1); } addClient(c) { this._clients.push(c); } updateClients() { this._clients.forEach(function (c) { c.update() }) return this; } get strength(): number { return this._strength; } set strength(s: number) { this._strength = s; } str(s: number) { this.strength = s; return this; } set position(p: { x: number, y: number, z: number }) { this._position.x = p.x; this._position.y = p.y; this._position.z = p.z; } get position() { return this._position; } set scale(s: { x: number, y: number, z: number }) { this._scale.x = this._scale.y = this._scale.z = s.x; if (this._uniformScale == false) { this._scale.y = s.y; this._scale.z = s.z; } } get scale() { return this._scale; } set rotation(s: { x: number, y: number, z: number }) { this._rotation.x = s.x * Math.PI / 180; this._rotation.y = s.y * Math.PI / 180; this._rotation.z = s.z * Math.PI / 180; } get rotation() { return this._rotation; } rot(s: { x: number, y: number, z: number }) { this.rotation = s; return this; } pos(p: { x: number, y: number, z: number }) { this.position = p; return this; } set seed(s: number) { this._seed = this._s = s; } get seed() { return this._seed; } set uniformScale(flag) { this._uniformScale = flag; } get uniformScale() { return this._uniformScale; } getRandomColor() { return this.random(); } getRandomInt({ min = 0, max = 10 } = {}) { return min+Math.floor(this.random()*(max-min)); } } export class RandomNumberGen { private _min; private _max; private _generator; constructor({ min = 0, max = 10, seed = 1234 } = {}) { this._min = min; this._max = max; this._generator = new RandomEffector(seed); return this; } nextInt() { return this._generator.getRandomInt({ min: this._min, max: this._max }); } } export class RainbowPalette { static getColor(index, frame) { let pi2 = Math.PI; let off = Math.sin(frame * 0.01); let aa = Math.sin((index + 0.05 + off) * pi2); let bb = Math.sin((index + 0.34 + off) * pi2); let cc = Math.sin((index + 0.66 + off) * pi2); return { r: aa * aa, g: bb * bb, b: cc * cc } } } export class ColorEffector { _autoanimate: boolean = true; _reverse: boolean = false; _framerate: number = 1/50; static cubicPulse(c:number, w:number, x:number) { x = Math.abs(x - c); if (x < w) return 0.0; return 1.0 - x * x * (3.0 - 2.0 * x); } static smoothstep(min, max, value) { var x = Math.max(0, Math.min(1, (value - min) / (max - min))); return x * x * (3 - 2 * x); }; constructor() { return this; } auto(ani: boolean) { this._autoanimate = ani; return this; } reverse(rev) { this._reverse = rev; return this; } framerate(fr: number) { fr = fr < 0 ? 1 : fr; this._framerate = 1/fr; return this; } animate(index, frame) { return ColorEffector.getColor(this._reverse ? index : (1 - index), frame, this._autoanimate ? frame *this._framerate/Math.PI:0); } static getColor(index:number, frame:number,offset:number=0) { let pi2 = Math.PI; let aa = Math.sin((index + 0.05 + offset) * pi2); let bb = Math.sin((index + 0.34 + offset) * pi2); let cc = Math.sin((index + 0.66 + offset) * pi2); //let aa = 1-ColorEffector.cubicPulse(aaa * aaa, 0.05,index );//* Math.sin((index + 0.05 + offset) * pi2); //let bb = 1-ColorEffector.cubicPulse(bbb * bbb, 0.05,index );//ColorEffector.cubicPulse(index, 0.02, 1+Math.sin(frame * 0.01)) *Math.sin((index + 0.34 + offset) * pi2); //let cc = 1-ColorEffector.cubicPulse(ccc * ccc, 0.05,index);//ColorEffector.cubicPulse(index, 0.02, 1+Math.sin(frame * 0.01)) *Math.sin((index + 0.66 + offset) * pi2); //frame = 66; let fx = (frame % 120) / 120;// Math.abs(Math.cos(Math.sin(frame * 0.1))); let ping = Math.abs(index - fx)>1/140?.99:0; let ix = Math.max(0,Math.min((ping),1));//-1+index*2; let a = ping;//ix;//ColorEffector.smoothstep(ix - .31, ix, fx) - ColorEffector.smoothstep(ix, ix + .31, fx); //let a = 1-ColorEffector.cubicPulse(index, .1, fx); return { r: aa * aa, g: bb * bb, b: cc * cc,a:a } } get autoanimate() { return this._autoanimate; } set autoanimate(auto: boolean) { this._autoanimate = auto; } } export class Cloner { static vOne = new BABYLON.Vector3(1, 1, 1); static vZero = new BABYLON.Vector3(0, 0, 0); _rootNode = null; _mesh; _scene; _clones; _frame: number; _index: number; _count: number; _effectors = []; setEnabled(enabled) { this._rootNode.setEnabled(enabled); } createClone(parent) { } update() { } addEffector(effector, sensitivity) { this._effectors.push({ effector: effector, sensitivity: sensitivity }); effector.addClient(this); this.update(); } get effectors() { return this._effectors; } eScale(vec: BABYLON.Vector3): BABYLON.Vector3 { var vRet = Cloner.vZero.add(vec); for (let i = 0; i < this._effectors.length; i++) { vRet = BABYLON.Vector3.Lerp(vec, this._effectors[i].effector.updateScale(vRet), this._effectors[i].sensitivity); } return vRet; } eRotate(vec: BABYLON.Vector3): BABYLON.Vector3 { var vRet = Cloner.vZero.add(vec); for (let i = 0; i < this._effectors.length; i++) { vRet = BABYLON.Vector3.Lerp(vec, this._effectors[i].effector.updateRotation(vRet), this._effectors[i].sensitivity); } return vRet; } ePosition(vec): BABYLON.Vector3 { var vRet = Cloner.vZero.add(vec); for (let i = 0; i < this._effectors.length; i++) { vRet = BABYLON.Vector3.Lerp(vec, this._effectors[i].effector.updatePosition(vRet), this._effectors[i].sensitivity); } return vRet;// BABYLON.Vector3.Lerp(vec,vRet,this._effectorStrength.x); } eReset() { this._effectors.forEach(function (e) { e.effector.reset() }); } getScene() { return this._scene; } } export class RadialCloner extends Cloner { static instance_nr; private _instance_nr; private _useInstances: boolean; private _radius: number; private _plane: BABYLON.Vector3; private _startangle: number; private _endangle: number; private _offset: number; private _align: boolean; private _formula: string; private _colorize: ColorEffector; /** * * @param mesh mesh to clone * @param scene * @param param2 all optional: count, offset, radius startangle, endangle, useInstances, plane,colorize * if colorize function is provided, useInstances is set to false! */ constructor(mesh, scene, { count = 3, offset = 0, radius = 3, align = true, startangle = 0, endangle = 360, useInstances = true, plane = { x: 1, y: 0, z: 1 }, colorize = null} = {}) { super(); RadialCloner.instance_nr = 0 | (RadialCloner.instance_nr + 1); this._instance_nr = RadialCloner.instance_nr; this._mesh = mesh; this._mesh.forEach(function (m) { m.setEnabled(false); }) this._scene = scene; this._useInstances = useInstances; this._clones = []; this._count = Number(count); this._radius = Number(radius); this._plane = new BABYLON.Vector3(plane.x, plane.y, plane.z); this._startangle = Math.PI * startangle / 180; this._endangle = Math.PI * endangle / 180; this._offset = offset; this._align = align; this._frame = 0; this._index = 0; this._colorize = colorize; if (colorize != null) this._useInstances = false; this._formula = "2-Math.pow(Math.abs(Math.sin(frame/10+Math.PI*i/2)),0.1)*1.5" this._formula = "scaling=1-Math.sin(frame/6+2*ix*Math.PI)/2" //this._rootNode=new CMesh("root",this._scene,this); this._rootNode = new CMesh(`rootRC_${this._instance_nr}`, this._scene, null, this); this._scene.registerBeforeRender(() => { this._frame++; this._index = 0; }); this.createClones(); this.update(); } createClone(parent, dummyUseInstances = null, dummyName = null) { var c = new RadialCloner(this._mesh, this._scene, { count: this._count, offset: this._offset, radius: this._radius, startangle: this._startangle * 180 / Math.PI, endangle: this._endangle * 180 / Math.PI, useInstances: this._useInstances, plane: { x: this._plane.x, y: this._plane.y, z: this._plane.z } }) parent._cloner = c; c.root.parent = parent; return c.root; } createClones(start = 0) { for (let i = start; i < this._count; i++) { //create Node for each clone, RADIAL=>parent = rootnode var n = new CMesh(`n_rc${this._instance_nr}_${i}`, this._scene, this._rootNode); n._index = i; this._clones.push(n); //create clone let cix = i % this._mesh.length; let c = n.createClone(this._mesh[cix], this._useInstances, `${this._mesh[cix].name}_rc${this._instance_nr}_${i}`); if (this._colorize != null) { c.registerBeforeRender(() => { let color = this._colorize.animate(c.parent._index / this._count, this._frame); c.material.diffuseColor.r = color.r; c.material.diffuseColor.g = color.g; c.material.diffuseColor.b = color.b; //if (color.r < 0.5) c.material.alpha = color.a; }); } } } calcRot() { for (let i = 0; i < this._count; i++) { let arange = this._endangle - this._startangle; let step = arange / this._count; this._clones[i].getChildren()[0].rotation.x = this._clones[i].getChildren()[0].rotation.y = this._clones[i].getChildren()[0].rotation.z = 0; if (this._plane.y === 0) { this._clones[i].getChildren()[0].rotation.y = this._align ? this._offset + this._startangle + i * step : 0; } else if (this._plane.x === 0) { this._clones[i].getChildren()[0].rotation.x = this._align ? -this._offset - this._startangle - i * step : 0; } else { this._clones[i].getChildren()[0].rotation.z = this._align ? -this._offset - this._startangle - i * step : 0; } let vRet = this.eRotate(this._clones[i].getChildren()[0].rotation); this._clones[i].getChildren()[0].rotation = vRet; } } calcSize() { for (let i = 0; i < this._count; i++) { //var orig=BABYLON.Vector3.Lerp(Cloner.vOne, this._S, this._iModeRelative ? i : i / (this._count - 1)); this._clones[i].getChildren()[0].scaling = this.eScale(Cloner.vOne); } } calcPos() { this.eReset(); for (let i = 0; i < this._count; i++) { let arange = this._endangle - this._startangle; let step = arange / this._count; this._clones[i].position.x = this._clones[i].position.y = this._clones[i].position.z = 0; //this._clones[i].getChildren()[0].rotation.x = this._clones[i].getChildren()[0].rotation.y = this._clones[i].getChildren()[0].rotation.z = 0; if (this._plane.y === 0) { this._clones[i].position.x = Math.sin(this._offset + this._startangle + i * step) * this._radius; this._clones[i].position.z = Math.cos(this._offset + this._startangle + i * step) * this._radius; //console.log(this._clones[i].position); this._clones[i].position = this.ePosition(this._clones[i].position); //this._clones[i].getChildren()[0].rotation.y = this._align ? this._offset + this._startangle + i * step : 0; //this._clones[i].scaling=RadialCloner.vOne.multiplyByFloats(1,(0.5+(this.frame%this._count))/this._count,1); } else if (this._plane.x === 0) { this._clones[i].position.y = Math.sin(this._offset + this._startangle + i * step) * this._radius; this._clones[i].position.z = Math.cos(this._offset + this._startangle + i * step) * this._radius; this._clones[i].position = this.ePosition(this._clones[i].position); //this._clones[i].getChildren()[0].rotation.x = this._align ? -this._offset - this._startangle - i * step : 0; } else { this._clones[i].position.x = Math.sin(this._offset + this._startangle + i * step) * this._radius; this._clones[i].position.y = Math.cos(this._offset + this._startangle + i * step) * this._radius; this._clones[i].position = this.ePosition(this._clones[i].position); //this._clones[i].getChildren()[0].rotation.z = this._align ? -this._offset - this._startangle - i * step : 0; } } } update() { this.calcRot(); this.calcPos(); this.calcSize(); } delete() { for (let i = this._count - 1; i >= 0; i--) { this._clones[i].delete(); } this._rootNode.dispose(); } recalc() { var cnt = this._count; this.count = 0; this.count = cnt; } set count(scnt) { let cnt = Number(scnt); if (cnt < Number(this._count)) { for (let i = this._count - 1; i >= cnt; i--) { this._clones[i].delete(); } this._count = cnt; this._clones.length = cnt; } else if (cnt > Number(this._count)) { var start = this._count; this._count = cnt; this.createClones(start); } this.update(); } get count() { return this._count; } set offset(off) { this._offset = Math.PI * off / 180; this.update(); } get offset() { return this._offset * 180 / Math.PI; } get root() { return this._rootNode; } set radius(r) { this._radius = r; this.update(); } get radius() { return this._radius; } set align(a) { this._align = a; this.update() } get align() { return this._align; } set startangle(sa) { this._startangle = Math.PI * sa / 180; this.update(); } get startangle() { return this._startangle * 180 / Math.PI; } set endangle(se) { this._endangle = Math.PI * se / 180; this.update(); } get endangle() { return this._endangle * 180 / Math.PI; } set plane(p) { this._plane = new BABYLON.Vector3(p.x, p.y, p.z); this.update(); } setScaling(ix, sc) { this._clones[ix].scaling = new BABYLON.Vector3(sc.x, sc.y, sc.z); this.update(); } } export class ObjectCloner extends Cloner { static instance_nr; private _useInstances: boolean=true; private _template; private _instance_nr; private _positions; private _normals; constructor(mesh, template: BABYLON.Mesh, scene, {useInstances = true} = {}){ super(); ObjectCloner.instance_nr = 0 | (ObjectCloner.instance_nr + 1); this._mesh = mesh; this._scene=scene; this._template = template; this._useInstances = useInstances; this._clones = []; this._positions=template.getFacetLocalPositions(); this._normals=template.getFacetLocalNormals(); this._template.isVisible=false;// setEnabled(false); this._mesh.forEach(function (m) { m.setEnabled(false); }) this._instance_nr = ObjectCloner.instance_nr; this._rootNode = new CMesh(`rootOC_${ObjectCloner.instance_nr}`, this._scene, null, this); this.createClones(); this.calcPos(); } createClones(start = 0) { var cix = 0; this._count=this._positions.length; for(let i=0;i<this._positions.length;i++) { cix = i % this._mesh.length; var n = new CMesh(`n_lc${ObjectCloner.instance_nr}_${i}`, this._scene, this._rootNode); this._clones.push(n); n.createClone(this._mesh[cix], this._useInstances, `${this._mesh[cix].name}_mc${ObjectCloner.instance_nr}_${i}`); } } calcRot() { for (let i = 0; i < this._count; i++) { let vRet = this.eRotate(Cloner.vZero); this._clones[i].getChildren()[0].rotation = vRet; } } calcSize() { for (let i = 0; i < this._count; i++) { this._clones[i].scaling = this.eScale(Cloner.vOne); } } calcPos() { this.eReset(); for(let i=0;i<this._clones.length;i++) { this._clones[i].position=this.ePosition(this._positions[i]); /* this._clones[i].position.x=this._positions[i].x; this._clones[i].position.y=this._positions[i].y; this._clones[i].position.z=this._positions[i].z; */ } } update() { if (this._count > 0) { this.calcRot(); this.calcPos(); this.calcSize(); } } get root() { return this._rootNode; } } export class MatrixCloner extends Cloner { static instance_nr; private _useInstances: boolean; private _size; private _mcount; private _iModeRelative; private _instance_nr; constructor(mesh, scene, { useInstances = true, mcount = { x: 3, y: 3, z: 3 }, size = { x: 2, y: 2, z: 2 }, iModeRelative = false } = {}) { super(); MatrixCloner.instance_nr = 0 | (MatrixCloner.instance_nr + 1); this._mesh = mesh; this._mesh.forEach(function (m) { m.setEnabled(false); }) this._scene = scene, this._useInstances = useInstances; this._clones = []; this._size = size; this._mcount = mcount; this._count = Number(mcount.x * mcount.y * mcount.z); this._iModeRelative = iModeRelative; this._instance_nr = MatrixCloner.instance_nr; this._rootNode = new CMesh(`rootMC_${MatrixCloner.instance_nr}`, this._scene, null, this); this.createClones(); this.update(); } createClone(parent, dummyUseInstances = null, dummyName = null) { var c = new MatrixCloner(this._mesh, this._scene, { mcount: this._mcount, size:this._size }) parent._cloner = c; c.root.parent = parent; return c.root; } createClones(start = 0) { var cix = 0; for (let z = start; z < this._mcount.z; z++) { for (let y = start; y < this._mcount.y; y++) { for (let x = start; x < this._mcount.x; x++) { var n = new CMesh(`n_lc${MatrixCloner.instance_nr}_${x}${y}${z}`, this._scene, this._rootNode); this._clones.push(n); var xyz = x + this._mcount.x * y + this._mcount.x * this._mcount.y * z; cix = xyz % this._mesh.length; n.createClone(this._mesh[cix], this._useInstances, `${this._mesh[cix].name}_mc${MatrixCloner.instance_nr}_${x}${y}${z}`); } } } this.calcPos(); } set mcount(m) { this._mcount = m; this.delete(); this._count = Number(this._mcount.x * this._mcount.y * this._mcount.z); this.createClones(); } get mcount() { return this._mcount; } get state() { return { mcount: { x: this._mcount.x, y: this._mcount.y, z: this._mcount.z, }, size: { x: this._size.x, y: this._size.y, z: this._size.z } } } set size(s) { this._size = s; this.update(); } get size() { return this._size; } calcRot() { for (let i = 0; i < this._count; i++) { let vRet = this.eRotate(Cloner.vZero); this._clones[i].getChildren()[0].rotation = vRet; } } calcSize() { for (let i = 0; i < this._count; i++) { this._clones[i].getChildren()[0].scaling = this.eScale(Cloner.vOne); } } calcPos() { this.eReset(); var cix = 0; for (let z = 0; z < this._mcount.z; z++) { for (let y = 0; y < this._mcount.y; y++) { for (let x = 0; x < this._mcount.x; x++) { var xyz = x + this._mcount.x * y + this._mcount.x * this._mcount.y * z; cix = xyz % this._mesh.length; let xo = -this._size.x * (this._mcount.x - 1) / 2; let yo = -this._size.y * (this._mcount.y - 1) / 2; let zo = -this._size.z * (this._mcount.z - 1) / 2; this._clones[xyz].position.x = xo + x * this._size.x; this._clones[xyz].position.y = yo + y * this._size.y; this._clones[xyz].position.z = zo + z * this._size.z; this._clones[xyz].getChildren()[0].position = this.ePosition(Cloner.vZero); } } } } get root() { return this._rootNode; } delete() { for (let i = this._count - 1; i >= 0; i--) { this._clones[i].delete(); } this._clones.length = 0; //this._rootNode.dispose(); } update() { if (this._count > 0) { this.calcRot(); this.calcPos(); this.calcSize(); } } } export class LinearCloner2 extends Cloner { static instance_nr; private _useInstances: boolean; private _offset: number; private _P: BABYLON.Vector3; private _R: BABYLON.Vector3; private _S: BABYLON.Vector3; private _iModeRelative; private _growth; private _instance_nr; constructor(mesh, scene, { count = 3, offset = 0, growth = 1, useInstances = true, P = { x: 0, y: 2, z: 0 }, S = { x: 1, y: 1, z: 1 }, R = { x: 0, y: 0, z: 0 }, iModeRelative = false } = {}) { super(); LinearCloner.instance_nr = 0 | (LinearCloner.instance_nr + 1); this._mesh = mesh; this._mesh.forEach(function (m) { m.setEnabled(false); }) this._scene = scene, this._useInstances = useInstances; this._clones = []; this._count = Number(count); this._offset = offset; this._P = new BABYLON.Vector3(P.x, P.y, P.z); this._S = new BABYLON.Vector3(S.x, S.y, S.z); this._R = new BABYLON.Vector3(R.x, R.y, R.z); this._iModeRelative = iModeRelative; this._growth = growth; this._instance_nr = LinearCloner.instance_nr; this._rootNode = new CMesh(`rootLC_${LinearCloner.instance_nr}`, this._scene, null, this); this.createClones(); this.update(); } createClone(parent, dummyUseInstances = null, dummyName = null) { var c = new LinearCloner(this._mesh, this._scene, { count: this._count, offset: this._offset, growth: this._growth, useInstances: this._useInstances, P: { x: this._P.x, y: this._P.y, z: this._P.z }, S: { x: this._S.x, y: this._S.y, z: this._S.z }, R: { x: this._R.x, y: this._R.y, z: this._R.z }, iModeRelative: this._iModeRelative }) parent._cloner = c; c.root.parent = parent; return c.root; } createClones(start = 0) { var cix = 0; for (let i = start; i < this._count; i++) { var n = new CMesh(`n_lc${LinearCloner.instance_nr}_${i}`, this._scene, i == 0 ? this._rootNode : this._clones[i - 1]); this._clones.push(n); cix = i % this._mesh.length; n.createClone(this._mesh[cix], this._useInstances, `${this._mesh[cix].name}_lc${LinearCloner.instance_nr}_${i}`); } } calcSize() { for (let i = 1; i < this._count; i++) { var orig = BABYLON.Vector3.Lerp(Cloner.vOne, this._S, this._iModeRelative ? i : i / (this._count - 1)); this._clones[i].getChildren()[0].scaling = this.eScale(orig); } } calcPos() { this.eReset(); let f = this._growth; if (this._iModeRelative == false) { var tcm1 = this._count == 1 ? 1 : this._count - 1; f = 1 / (tcm1) * this._growth; } //shift offset this._clones[0].position = BABYLON.Vector3.Lerp(Cloner.vZero, this._P, f * this._offset); this._clones[0].position = this.ePosition(this._clones[0].position); for (let i = 1; i < this._count; i++) { this._clones[i].position = BABYLON.Vector3.Lerp(Cloner.vZero, this._P, f); this._clones[i].getChildren()[0].position = this.ePosition(Cloner.vZero); } } calcRot() { for (let i = 1; i < this._count; i++) { let item = this._clones[i].getChildren()[0]; //this._clones[i].getChildren()[0].rotation = BABYLON.Vector3.Lerp(Cloner.vZero, this._R, this._iModeRelative ? i * this._growth : i / (this._count - 1) * this._growth); //this._clones[i].getChildren()[0].rotation = this.eRotate(Cloner.vZero);// this._clones[i].rotation); let vRot = BABYLON.Vector3.Lerp(Cloner.vZero, this._R, this._iModeRelative ? i * this._growth : i / (this._count - 1) * this._growth); this._clones[i].getChildren()[0].rotation = this.eRotate(vRot);// this._clones[i].rotation); } } update() { if (this._count > 0) { this.calcRot(); this.calcPos(); this.calcSize(); } } recalc() { var cnt = this._count; this.count = 0; this.count = cnt; } set growth(g) { this._growth = g; this.update(); } delete() { for (let i = this._count - 1; i >= 0; i--) { this._clones[i].parent = null; this._clones[i].getChildren()[0].dispose(); this._clones[i].dispose(); } this._rootNode.dispose(); } set count(scnt) { let cnt = Number(scnt); if (cnt < Number(this._count)) { for (let i = this._count - 1; i >= cnt; i--) { this._clones[i].delete(); } this._count = cnt; this._clones.length = cnt; } else if (cnt > Number(this._count)) { var start = this._count; this._count = cnt; this.createClones(start); } this.update(); } get count() { return this._count; } set mode(m) { let newMode = (m == "step") ? true : false; let f = (this._count - 1); if (newMode && this._iModeRelative == false) { f = 1 / f; } this._R = BABYLON.Vector3.Lerp(Cloner.vZero, this._R, f); this._P = BABYLON.Vector3.Lerp(Cloner.vZero, this._P, f); this._S = BABYLON.Vector3.Lerp(Cloner.vOne, this._S, f); this._iModeRelative = newMode; this.update(); } set position(pos) { this._P.x = pos.x; this._P.y = pos.y; this._P.z = pos.z; this.update(); } get position() { return { x: this._P.x, y: this._P.y, z: this._P.z }; } set scale(s) { this._S.x = s.x; this._S.y = s.y; this._S.z = s.z; this.update(); } get scale() { return { x: this._S.x, y: this._S.y, z: this._S.z }; } set rotation(r) { this._R.x = r.x * Math.PI / 180; this._R.y = r.y * Math.PI / 180; this._R.z = r.z * Math.PI / 180; this.update(); } get rotation() { return { x: this._R.x * 180 / Math.PI, y: this._R.y * 180 / Math.PI, z: this._R.z * 180 / Math.PI }; } set offset(o) { this._offset = o; this.update(); } get offset() { return this._offset; } get root() { return this._rootNode; } get mesh() { return this._mesh; } } export class LinearCloner extends Cloner { static instance_nr; private _useInstances: boolean; private _offset: number; private _P: BABYLON.Vector3; private _R: BABYLON.Vector3; private _S: BABYLON.Vector3; private _iModeRelative; private _growth; private _instance_nr; private _countNumberGen = null; constructor(mesh, scene, { count =null, offset = 0, growth = 1, useInstances = true, P = { x: 0, y: 2, z: 0 }, S = { x: 1, y: 1, z: 1 }, R = { x: 0, y: 0, z: 0 }, iModeRelative = false } = {}) { super(); LinearCloner.instance_nr = 0 | (LinearCloner.instance_nr + 1); this._mesh = mesh; this._mesh.forEach(function (m) { m.setEnabled(false); }) this._scene = scene, this._useInstances = useInstances; this._clones = []; this._countNumberGen = count instanceof RandomNumberGen ? count : null; this._count = count instanceof RandomNumberGen ? count.nextInt():Number(count); this._offset = offset; this._P = new BABYLON.Vector3(P.x, P.y, P.z); this._S = new BABYLON.Vector3(S.x, S.y, S.z); this._R = new BABYLON.Vector3(R.x * Math.PI / 180, R.y* Math.PI / 180, R.z* Math.PI / 180); this._iModeRelative = iModeRelative; this._growth = growth; this._instance_nr = LinearCloner.instance_nr; this._rootNode = new CMesh(`rootLC_${LinearCloner.instance_nr}`, this._scene, null, this); this.createClones(); this.update(); } createClone(parent, dummyUseInstances = null, dummyName = null) { let cnt = this._countNumberGen != null ? this._countNumberGen.nextInt() : this._count; var c = new LinearCloner(this._mesh, this._scene, { count: cnt, offset: this._offset, growth: this._growth, useInstances: this._useInstances, P: { x: this._P.x, y: this._P.y, z: this._P.z }, S: { x: this._S.x, y: this._S.y, z: this._S.z }, R: { x: this._R.x, y: this._R.y, z: this._R.z }, iModeRelative: this._iModeRelative }) parent._cloner = c; c.root.parent = parent; return c.root; } createClones(start = 0) { for (let i = start; i < this._count; i++) { //create Node for each clone, RADIAL=>parent = rootnode var n = new CMesh(`n_lc${this._instance_nr}_${i}`, this._scene, this._rootNode); //n.index = i; this._clones.push(n); //create clone let cix = i % this._mesh.length; let c = n.createClone(this._mesh[cix], this._useInstances, `${this._mesh[cix].name}_lc${this._instance_nr}_${i}`); //c.material.diffuseColor.g = 1-i / this._count; } } createClones2(start = 0) { var cix = 0; for (let i = start; i < this._count; i++) { var n = new CMesh(`n_lc${LinearCloner.instance_nr}_${i}`, this._scene, i == 0 ? this._rootNode : this._clones[i - 1]); this._clones.push(n); cix = i % this._mesh.length; n.createClone(this._mesh[cix], this._useInstances, `${this._mesh[cix].name}_lc${LinearCloner.instance_nr}_${i}`); } } calcSize() { for (let i = 1; i < this._count; i++) { var orig = BABYLON.Vector3.Lerp(Cloner.vOne, this._S, this._iModeRelative ? i : i / (this._count - 1)); this._clones[i].getChildren()[0].scaling = this.eScale(orig); //this._clones[i].scaling = this.eScale(orig); } } calcPos() { this.eReset(); let f = this._growth; if (this._iModeRelative == false) { var tcm1 = this._count == 1 ? 1 : this._count - 1; f = 1 / (tcm1) * this._growth; } for (let i = 0; i < this._count; i++) { let off=BABYLON.Vector3.Lerp(Cloner.vZero, this._P, f * this._offset); let v=BABYLON.Vector3.Lerp(Cloner.vZero, this._P, i*f ); let v2=v.add(off); this._clones[i].position = this.ePosition(v2); } } calcPos2() { this.eReset(); let f = this._growth; if (this._iModeRelative == false) { var tcm1 = this._count == 1 ? 1 : this._count - 1; f = 1 / (tcm1) * this._growth; } //shift offset this._clones[0].position = BABYLON.Vector3.Lerp(Cloner.vZero, this._P, f * this._offset); this._clones[0].position = this.ePosition(this._clones[0].position); for (let i = 1; i < this._count; i++) { let v=BABYLON.Vector3.Lerp(Cloner.vZero, this._P, f); this._clones[i].position = v; this._clones[i].getChildren()[0].position = this.ePosition(Cloner.vZero); } } calcRot() { for (let i = 1; i < this._count; i++) { let item = this._clones[i].getChildren()[0]; //this._clones[i].getChildren()[0].rotation = BABYLON.Vector3.Lerp(Cloner.vZero, this._R, this._iModeRelative ? i * this._growth : i / (this._count - 1) * this._growth); //this._clones[i].getChildren()[0].rotation = this.eRotate(Cloner.vZero);// this._clones[i].rotation); let vRot = BABYLON.Vector3.Lerp(Cloner.vZero, this._R, this._iModeRelative ? i * this._growth : i / (this._count - 1) * this._growth); this._clones[i].getChildren()[0].rotation = this.eRotate(vRot);// this._clones[i].rotation); } } calcColor() { /* if (this._effectors.length > 0) { let e = this._effectors[0]; for (let i = 1; i < this._count; i++) { let cr = e.effector.getRandomColor(); let cg = e.effector.getRandomColor(); let cb = e.effector.getRandomColor(); this._clones[i].getChildren()[0].material.diffuseColor.r = cr; this._clones[i].getChildren()[0].material.diffuseColor.g = cg; this._clones[i].getChildren()[0].material.diffuseColor.b = cb; } } */ } update() { if (this._count > 0) { this.calcRot(); this.calcPos(); this.calcSize(); this.calcColor(); } } recalc() { var cnt = this._count; this.count = 0; this.count = cnt; } get growth() { return this._growth; } set growth(g) { this._growth = g; this.update(); } delete() { for (let i = this._count - 1; i >= 0; i--) { this._clones[i].parent = null; this._clones[i].getChildren()[0].dispose(); this._clones[i].dispose(); } this._rootNode.dispose(); } set count(scnt) { let cnt = Number(scnt); if (cnt < Number(this._count)) { for (let i = this._count - 1; i >= cnt; i--) { this._clones[i].delete(); } this._count = cnt; this._clones.length = cnt; } else if (cnt > Number(this._count)) { var start = this._count; this._count = cnt; this.createClones(start); } this.update(); } get count() { return this._count; } /** * Does some thing in old style. * * @deprecated use iModeRel instead. */ set mode(m) { this.iModeRel=(m == "step"); } set iModeRel(mode) { let newMode = mode; let f = (this._count - 1); if (newMode && this._iModeRelative == false) { f = 1 / f; } this._R = BABYLON.Vector3.Lerp(Cloner.vZero, this._R, f); this._P = BABYLON.Vector3.Lerp(Cloner.vZero, this._P, f); this._S = BABYLON.Vector3.Lerp(Cloner.vOne, this._S, f); this._iModeRelative = newMode; this.update(); } set position(pos) { this._P.x = pos.x; this._P.y = pos.y; this._P.z = pos.z; this.update(); } get position() { return { x: this._P.x, y: this._P.y, z: this._P.z }; } set scale(s) { this._S.x = s.x; this._S.y = s.y; this._S.z = s.z; this.update(); } get scale() { return { x: this._S.x, y: this._S.y, z: this._S.z }; } set rotation(r) { this._R.x = r.x * Math.PI / 180; this._R.y = r.y * Math.PI / 180; this._R.z = r.z * Math.PI / 180; this.update(); } get rotation() { return { x: this._R.x * 180 / Math.PI, y: this._R.y * 180 / Math.PI, z: this._R.z * 180 / Math.PI }; } get rotation3() { return new BABYLON.Vector3(this._R.x, this._R.y, this._R.z); } set rotation3(vec: BABYLON.Vector3) { this._R.x = vec.x; this._R.y = vec.y; this._R.z = vec.z; this.update(); } set offset(o) { this._offset = o; this.update(); } get offset() { return this._offset; } get root() { return this._rootNode; } get mesh() { return this._mesh; } } }
the_stack
'use strict'; import {TPromise, PPromise} from 'vs/base/common/winjs.base'; import uri from 'vs/base/common/uri'; import glob = require('vs/base/common/glob'); import objects = require('vs/base/common/objects'); import scorer = require('vs/base/common/scorer'); import strings = require('vs/base/common/strings'); import paths = require('vs/base/common/paths'); // TODO: import {getNextTickChannel} from 'vs/base/parts/ipc/common/ipc'; // TODO: import {Client} from 'vs/base/parts/ipc/node/ipc.cp'; import {IProgress, LineMatch, FileMatch, ISearchComplete, ISearchProgressItem, QueryType, IFileMatch, ISearchQuery, ISearchConfiguration, ISearchService} from 'vs/platform/search/common/search'; import {IUntitledEditorService} from 'vs/workbench/services/untitled/common/untitledEditorService'; import {IModelService} from 'vs/editor/common/services/modelService'; import {IWorkspaceContextService} from 'vs/platform/workspace/common/workspace'; import {IConfigurationService} from 'vs/platform/configuration/common/configuration'; // TODO: import {IRawSearch, ISerializedSearchComplete, ISerializedSearchProgressItem, ISerializedFileMatch, IRawSearchService} from './search'; // TODO: import {ISearchChannel, SearchChannelClient} from './searchIpc'; import {IEnvironmentService} from 'vs/platform/environment/common/environment'; import {IGithubService} from 'ghedit/githubService'; var github = require('ghedit/lib/github'); import {Github, SearchResult, ResultItem, TextMatch, FragmentMatch, SearchOptions, Search as GithubApiSearch, Error as GithubError} from 'github'; import {IRawFileMatch, IRawSearch} from 'vs/workbench/services/search/node/search'; import {Engine as GithubFileSearchEngine} from 'vs/workbench/services/search/node/fileSearch'; import {Limiter} from 'vs/base/common/async'; import {ITextEditorModel} from 'vs/platform/editor/common/editor'; import {IModel} from 'vs/editor/common/editorCommon'; import {IEditorService} from 'vs/platform/editor/common/editor'; export class SearchService implements ISearchService { public _serviceBrand: any; // private diskSearch: DiskSearch; private githubSearch: GithubSearch; constructor( @IModelService private modelService: IModelService, @IUntitledEditorService private untitledEditorService: IUntitledEditorService, @IEnvironmentService private environmentService: IEnvironmentService, @IWorkspaceContextService private contextService: IWorkspaceContextService, @IConfigurationService private configurationService: IConfigurationService, @IGithubService private githubService: IGithubService ) { // this.diskSearch = new DiskSearch(!config.env.isBuilt || config.env.verboseLogging); this.githubSearch = new GithubSearch(this.githubService); } public extendQuery(query: ISearchQuery): void { const configuration = this.configurationService.getConfiguration<ISearchConfiguration>(); // Configuration: Encoding if (!query.fileEncoding) { let fileEncoding = configuration && configuration.files && configuration.files.encoding; query.fileEncoding = fileEncoding; } // Configuration: File Excludes let fileExcludes = configuration && configuration.files && configuration.files.exclude; if (fileExcludes) { if (!query.excludePattern) { query.excludePattern = fileExcludes; } else { objects.mixin(query.excludePattern, fileExcludes, false /* no overwrite */); } } } public search(query: ISearchQuery): PPromise<ISearchComplete, ISearchProgressItem> { this.extendQuery(query); let rawSearchQuery: PPromise<void, ISearchProgressItem>; return new PPromise<ISearchComplete, ISearchProgressItem>((onComplete, onError, onProgress) => { // Get local results from dirty/untitled let localResultsFlushed = false; let localResults = this.getLocalResults(query); let flushLocalResultsOnce = function () { if (!localResultsFlushed) { localResultsFlushed = true; Object.keys(localResults).map((key) => localResults[key]).filter((res) => !!res).forEach(onProgress); } }; // Delegate to parent for real file results // rawSearchQuery = this.diskSearch.search(query).then( rawSearchQuery = this.githubSearch.search(query).then( // on Complete (complete) => { flushLocalResultsOnce(); onComplete({ limitHit: complete.limitHit, results: complete.results.filter((match) => typeof localResults[match.resource.toString()] === 'undefined'), // dont override local results stats: complete.stats }); }, // on Error (error) => { flushLocalResultsOnce(); onError(error); }, // on Progress (progress) => { flushLocalResultsOnce(); // Match if (progress.resource) { if (typeof localResults[progress.resource.toString()] === 'undefined') { // don't override local results onProgress(progress); } } // Progress else { onProgress(<IProgress>progress); } }); }, () => rawSearchQuery && rawSearchQuery.cancel()); } private getLocalResults(query: ISearchQuery): { [resourcePath: string]: IFileMatch; } { let localResults: { [resourcePath: string]: IFileMatch; } = Object.create(null); if (query.type === QueryType.Text) { let models = this.modelService.getModels(); models.forEach((model) => { let resource = model.uri; if (!resource) { return; } // Support untitled files if (resource.scheme === 'untitled') { if (!this.untitledEditorService.get(resource)) { return; } } // Don't support other resource schemes than files for now else if (resource.scheme !== 'file') { return; } if (!this.matches(resource, query.filePattern, query.includePattern, query.excludePattern)) { return; // respect user filters } // Use editor API to find matches let ranges = model.findMatches(query.contentPattern.pattern, false, query.contentPattern.isRegExp, query.contentPattern.isCaseSensitive, query.contentPattern.isWordMatch); if (ranges.length) { let fileMatch = new FileMatch(resource); localResults[resource.toString()] = fileMatch; ranges.forEach((range) => { fileMatch.lineMatches.push(new LineMatch(model.getLineContent(range.startLineNumber), range.startLineNumber - 1, [[range.startColumn - 1, range.endColumn - range.startColumn]])); }); } else { localResults[resource.toString()] = false; // flag as empty result } }); } return localResults; } private matches(resource: uri, filePattern: string, includePattern: glob.IExpression, excludePattern: glob.IExpression): boolean { let workspaceRelativePath = this.contextService.toWorkspaceRelativePath(resource); // file pattern if (filePattern) { if (resource.scheme !== 'file') { return false; // if we match on file pattern, we have to ignore non file resources } if (!scorer.matches(resource.fsPath, strings.stripWildcards(filePattern).toLowerCase())) { return false; } } // includes if (includePattern) { if (resource.scheme !== 'file') { return false; // if we match on file patterns, we have to ignore non file resources } if (!glob.match(includePattern, workspaceRelativePath || resource.fsPath)) { return false; } } // excludes if (excludePattern) { if (resource.scheme !== 'file') { return true; // e.g. untitled files can never be excluded with file patterns } if (glob.match(excludePattern, workspaceRelativePath || resource.fsPath)) { return false; } } return true; } public clearCache(cacheKey: string): TPromise<void> { //return this.diskSearch.clearCache(cacheKey); return TPromise.as(null); } } class GithubSearch { private fakeLineNumber: number; private editorService: IEditorService; private sentGa: boolean; constructor(private githubService: IGithubService) { this.fakeLineNumber = 1; this.sentGa = false; } public setEditorService(editorService: IEditorService) { this.editorService = editorService; } private textSearch(query: ISearchQuery) : PPromise<ISearchComplete, ISearchProgressItem> { return new PPromise<ISearchComplete, ISearchProgressItem>((c, e, p) => { // If this isn't the default branch, fail. if (!this.githubService.isDefaultBranch()) { let br = this.githubService.getDefaultBranch(); e("Github only provides search on the default branch (" + br + ")."); return; } let fileWalkStartTime = Date.now(); // q=foo+repo:spiffcode/ghedit_test let q:string = query.contentPattern.pattern + '+repo:' + this.githubService.repoName; let s: GithubApiSearch = new github.Search({ query: encodeURIComponent(q) }); s.code(null, (err: GithubError, result: SearchResult) => { if (err) { if (err.error) { e(err.error) } else { e(err); } return; } // Github only provides search on forks if the fork has // more star ratings than the parent. if (result.items.length == 0 && this.githubService.isFork()) { e("Github doesn't provide search on forked repos unless the star rating is greater than the parent repo."); return; } // Search on IModel's to get accurate search results. Github's search results // are not complete and don't have line numbers. this.modelSearch(query.contentPattern.pattern, result.items.map((item) => uri.file(item.path))).then((matches) => { c({ limitHit: result.incomplete_results, results: matches, stats: { fromCache: false, resultCount: matches.length, unsortedResultTime: Date.now() - fileWalkStartTime } }); }, () => { e('Github error performing search.') }); }); }); } private modelSearch(pattern: string, uris: uri[]) : TPromise<FileMatch[]> { // Return FileMatch[] given a pattern and a list of uris return new TPromise<FileMatch[]>((c, e) => { let limiter = new Limiter(1); let promises = uris.map((uri) => limiter.queue(() => this.editorService.resolveEditorModel({ resource: uri }))); TPromise.join(promises).then((models: ITextEditorModel[]) => { let matches: FileMatch[] = []; models.forEach((model) => { var textEditorModel = <IModel>model.textEditorModel; let m = new FileMatch(textEditorModel.uri); textEditorModel.findMatches(pattern, false, false, false, true).forEach((r) => { let frag = textEditorModel.getLineContent(r.startLineNumber); m.lineMatches.push(new LineMatch(frag, r.startLineNumber, [[ r.startColumn - 1, r.endColumn - r.startColumn ]])); }); matches.push(m); }); c(matches); }, () => c([])); }); } private fileSearch(query: ISearchQuery) : PPromise<ISearchComplete, ISearchProgressItem> { // Map from ISearchQuery to IRawSearch let config: IRawSearch = { rootFolders: [''], filePattern: query.filePattern, excludePattern: query.excludePattern, includePattern: query.includePattern, contentPattern: query.contentPattern, maxResults: query.maxResults, fileEncoding: query.fileEncoding }; if (query.folderResources) { config.rootFolders = []; query.folderResources.forEach((r) => { config.rootFolders.push(r.path); }); } if (query.extraFileResources) { config.extraFiles = []; query.extraFileResources.forEach((r) => { config.extraFiles.push(r.path); }); } let fileWalkStartTime = Date.now(); let engine = new GithubFileSearchEngine(config, this.githubService.getCache()); let matches: IFileMatch[] = []; return new PPromise<ISearchComplete, ISearchProgressItem>((c, e, p) => { engine.search(m => { if (m) { let match = this.fileMatchFromRawMatch(m); matches.push(match); p(match); } }, (progress) => { p(progress); }, (error, complete) => { if (error) { e(error); } else { c({ limitHit: complete.limitHit, results: matches, stats: complete.stats }); } }); }, () => engine.cancel()); } public search(query: ISearchQuery): PPromise<ISearchComplete, ISearchProgressItem> { if (query.type === QueryType.File) { if (!this.sentGa) { this.sentGa = true; setTimeout(() => { this.sentGa = false }, 30); (<any>window).sendGa('/workbench/search/filename'); } return this.fileSearch(query); } else { (<any>window).sendGa('/workbench/search/text'); return this.textSearch(query); } } private fileMatchFromRawMatch(match: IRawFileMatch): FileMatch { let path = match.base ? paths.join(match.base, match.relativePath) : match.relativePath; return new FileMatch(uri.file(path)); } } /* export class DiskSearch { private raw: IRawSearchService; constructor(verboseLogging: boolean) { const client = new Client( uri.parse(require.toUrl('bootstrap')).fsPath, { serverName: 'Search', timeout: 60 * 60 * 1000, args: ['--type=searchService'], env: { AMD_ENTRYPOINT: 'vs/workbench/services/search/node/searchApp', PIPE_LOGGING: 'true', VERBOSE_LOGGING: verboseLogging } } ); const channel = getNextTickChannel(client.getChannel<ISearchChannel>('search')); this.raw = new SearchChannelClient(channel); } public search(query: ISearchQuery): PPromise<ISearchComplete, ISearchProgressItem> { let request: PPromise<ISerializedSearchComplete, ISerializedSearchProgressItem>; let rawSearch: IRawSearch = { rootFolders: query.folderResources ? query.folderResources.map(r => r.fsPath) : [], extraFiles: query.extraFileResources ? query.extraFileResources.map(r => r.fsPath) : [], filePattern: query.filePattern, excludePattern: query.excludePattern, includePattern: query.includePattern, maxResults: query.maxResults, sortByScore: query.sortByScore, cacheKey: query.cacheKey }; if (query.type === QueryType.Text) { rawSearch.contentPattern = query.contentPattern; rawSearch.fileEncoding = query.fileEncoding; } if (query.type === QueryType.File) { request = this.raw.fileSearch(rawSearch); } else { request = this.raw.textSearch(rawSearch); } return DiskSearch.collectResults(request); } public static collectResults(request: PPromise<ISerializedSearchComplete, ISerializedSearchProgressItem>): PPromise<ISearchComplete, ISearchProgressItem> { let result: IFileMatch[] = []; return new PPromise<ISearchComplete, ISearchProgressItem>((c, e, p) => { request.done((complete) => { c({ limitHit: complete.limitHit, results: result, stats: complete.stats }); }, e, (data) => { // Matches if (Array.isArray(data)) { const fileMatches = data.map(d => this.createFileMatch(d)); result = result.concat(fileMatches); fileMatches.forEach(p); } // Match else if ((<ISerializedFileMatch>data).path) { const fileMatch = this.createFileMatch(<ISerializedFileMatch>data); result.push(fileMatch); p(fileMatch); } // Progress else { p(<IProgress>data); } }); }, () => request.cancel()); } private static createFileMatch(data: ISerializedFileMatch): FileMatch { let fileMatch = new FileMatch(uri.file(data.path)); if (data.lineMatches) { for (let j = 0; j < data.lineMatches.length; j++) { fileMatch.lineMatches.push(new LineMatch(data.lineMatches[j].preview, data.lineMatches[j].lineNumber, data.lineMatches[j].offsetAndLengths)); } } return fileMatch; } public clearCache(cacheKey: string): TPromise<void> { return this.raw.clearCache(cacheKey); } } */
the_stack
import { createStyles, withStyles } from '@material-ui/core' import Button from '@material-ui/core/Button' import Card from '@material-ui/core/Card' import CardActions from '@material-ui/core/CardActions' import CardContent from '@material-ui/core/CardContent' import green from '@material-ui/core/colors/green' import red from '@material-ui/core/colors/red' import Grid from '@material-ui/core/Grid' import Link from '@material-ui/core/Link' import Snackbar from '@material-ui/core/Snackbar' import { Theme } from '@material-ui/core/styles' import TextareaAutosize from '@material-ui/core/TextareaAutosize' import TextField from '@material-ui/core/TextField' import Tooltip from '@material-ui/core/Tooltip' import Typography from '@material-ui/core/Typography' import AddIcon from '@material-ui/icons/Add' import CancelIcon from '@material-ui/icons/Cancel' import DeleteForeverIcon from '@material-ui/icons/DeleteForever' import EditIcon from '@material-ui/icons/Edit' import PlayArrowIcon from '@material-ui/icons/PlayArrow' import SaveIcon from '@material-ui/icons/Save' import MuiAlert, { AlertProps, Color as ToastColor } from '@material-ui/lab/Alert' import React from 'react' import { SendCommand } from '../../key-binding/KeyBinding' import MacroRecorder from './MacroRecorder' const styles = (theme: Theme) => createStyles({ macrosContainer: { alignItems: 'stretch', }, macroName: { marginLeft: '20px', marginBottom: '1em', }, macroCode: { whiteSpace: 'pre-wrap', wordWrap: 'break-word', }, macroText: { backgroundColor: '#222', color: '#ddd', width: '90%', marginLeft: '20px', }, macroItem: { }, macroCard: { display: 'flex', flexDirection: 'column', height: '100%', }, cardContent: { // To keep the card buttons at the bottom of the card. display: 'flex', flex: '1 0 auto', flexDirection: 'column', }, macroCardActions: { display: 'flex', }, toast: { width: '100%', '& > * + *': { marginTop: theme.spacing(2), }, }, }) function Alert(props: AlertProps) { return <MuiAlert elevation={6} variant="filled" {...props} /> } class SavedMacro { constructor( public id: string, public name: string, public macro: string[]) { } } class Macros extends React.Component<{ macroRecorder: MacroRecorder, sendCommand: SendCommand, classes: any, }, any> { private db?: IDBDatabase constructor(props: any) { super(props) this.state = { isRecording: false, macroExists: false, isToastOpen: false, toastMessage: "", toastSeverity: "", macroName: "", editMacro: "", savedMacros: [], } this.addMacro = this.addMacro.bind(this) this.cancelEditMacro = this.cancelEditMacro.bind(this) this.closeToast = this.closeToast.bind(this) this.deleteMacro = this.deleteMacro.bind(this) this.handleChange = this.handleChange.bind(this) this.openToast = this.openToast.bind(this) this.playMacro = this.playMacro.bind(this) this.playLastRecordedMacro = this.playLastRecordedMacro.bind(this) this.saveMacro = this.saveMacro.bind(this) this.startRecording = this.startRecording.bind(this) this.stopRecording = this.stopRecording.bind(this) } componentDidMount() { const indexedDB = window.indexedDB const request = indexedDB.open('macros', 1) request.onerror = (event: Event) => { this.openToast("Could not open the macro database. See the Console for more details.", 'error') console.error("Could not open the macro database.") console.error(event) } request.onupgradeneeded = (event: Event) => { const db: IDBDatabase = (event?.target as any).result db.createObjectStore('macro', { keyPath: 'id', autoIncrement: true, }) } request.onsuccess = (event: Event) => { this.db = (event?.target as any).result this.loadSavedMacros() } } private openToast(toastMessage: string, toastSeverity: ToastColor): void { this.setState({ isToastOpen: true, toastMessage, toastSeverity, }) } private closeToast(event?: React.SyntheticEvent, reason?: string) { if (reason === 'clickaway') { return } this.setState({ isToastOpen: false, }) } private loadSavedMacros() { if (this.db === undefined) { // Shouldn't happen. this.openToast("Error loading macros. See the Console for more details.", 'error') console.error("The macro database has not been loaded yet. Please try again.") return } const transaction = this.db.transaction('macro', 'readonly') transaction.onerror = (event: Event) => { this.openToast("Error loading macros. See the Console for more details.", 'error') console.error(event) } const dataStore = transaction.objectStore('macro') const getRequest = dataStore.getAll() getRequest.onerror = (event: Event) => { this.openToast("Error loading macros. See the Console for more details.", 'error') console.error(event) } getRequest.onsuccess = () => { this.setState({ savedMacros: getRequest.result, }) } } private handleChange(event: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) { this.setState({ [event.target.name]: event.target.value }) } private startEditingMacro(id: string | undefined, name: string, macro: string[]) { this.setState({ editMacroId: id, macroName: name, editMacro: JSON.stringify(macro, null, 4), }) } private addMacro(): void { this.startEditingMacro(undefined, "", ["a d", "wait 350", "a u"]) } private parseMacro(macro: string): string[] { // More validation and cleaning can be done here. macro = macro.replace(/'/g, "\"") return JSON.parse(macro) } private saveMacro(): void { let macro: string[] try { macro = this.parseMacro(this.state.editMacro) } catch (err) { this.openToast("The macro is invalid. See the Console for more details.", 'error') console.error("Invalid macro:") console.error(err) return } const name = this.state.macroName if (this.db === undefined) { this.openToast("The macro database has not been loaded yet. Please try again.", 'error') console.error("The macro database has not been loaded yet. Please try again.") return } const transaction = this.db.transaction('macro', 'readwrite') transaction.onerror = (event: Event) => { this.openToast("Error saving the macro. See the Console for more details.", 'error') console.error(event) } const dataStore = transaction.objectStore('macro') let request if (this.state.editMacroId !== undefined) { request = dataStore.put({ id: this.state.editMacroId, name, macro, }) } else { request = dataStore.add({ name, macro, }) } request.onerror = (event: Event) => { this.openToast("Error saving the macro. See the Console for more details.", 'error') console.error(event) } request.onsuccess = () => { this.loadSavedMacros() this.setState({ macroName: "", editMacro: "", }) this.openToast("Saved", 'success') } } private deleteMacro(macroId: string): void { if (this.db === undefined) { this.openToast("The macro database has not been loaded yet. Please try again.", 'error') console.error("The macro database has not been loaded yet. Please try again.") return } const transaction = this.db.transaction('macro', 'readwrite') transaction.onerror = (event: Event) => { this.openToast("Error deleting the macro. See the Console for more details.", 'error') console.error(event) } const dataStore = transaction.objectStore('macro') const deleteRequest = dataStore.delete(macroId) deleteRequest.onerror = (event: Event) => { this.openToast("Error deleting the macro. See the Console for more details.", 'error') console.error(event) } deleteRequest.onsuccess = () => { this.loadSavedMacros() this.cancelEditMacro() this.openToast("Deleted the macro", 'info') } } private cancelEditMacro(): void { this.setState({ editMacro: "" }) } private startRecording(): void { this.setState({ isRecording: true }) this.props.macroRecorder.start() this.openToast("Recording macro", 'info') } private stopRecording(): void { this.props.macroRecorder.stop() this.startEditingMacro(undefined, "", this.props.macroRecorder.currentRecording) this.setState({ isRecording: false, macroExists: true, }) this.openToast("Stopped recording macro", 'info') } async sleep(sleepMillis: number) { return new Promise(resolve => setTimeout(resolve, sleepMillis)) } async playMacro(macro: string[]) { this.openToast("Playing macro", 'info') // TODO Keep a controller state and update it. // Can't just call `updateState` since a macro could have a putton tap that `updateState` does not handle. for (const command of macro) { const m = /wait (\d+)/.exec(command) if (m) { const sleepMillis = parseInt(m[1]) if (sleepMillis > 5) { await this.sleep(sleepMillis) } } else { this.props.sendCommand(command) } } this.openToast("Done playing macro", 'info') } async playLastRecordedMacro(): Promise<void> { return this.playMacro(this.props.macroRecorder.currentRecording) } render(): React.ReactNode { const { classes } = this.props return <div> <Snackbar open={this.state.isToastOpen} autoHideDuration={6000} onClose={this.closeToast}> <Alert onClose={this.closeToast} severity={this.state.toastSeverity}> {this.state.toastMessage} </Alert> </Snackbar> <Typography variant="h3">Macros</Typography> <Grid container> <Grid item> <Tooltip title="Create a new macro" placement="top" > <Button id="add-macro" onClick={this.addMacro}> <AddIcon /> </Button> </Tooltip> </Grid> <Grid item hidden={this.state.isRecording}> <Tooltip title="Start recording a macro" placement="top"> <Button onClick={this.startRecording}> <span role='img' aria-label="Start recording a macro">🔴</span> </Button> </Tooltip> </Grid> <Grid item hidden={!this.state.isRecording}> <Tooltip title="Stop recording the macro" placement="top" > <Button onClick={this.stopRecording}> <span role='img' aria-label="Stop recording the macro">⬛</span> </Button> </Tooltip> </Grid> <Grid item hidden={!this.state.macroExists}> <Tooltip title="Play the last macro recorded" placement="top" > <Button // The id is not used but it's helpful for writing meta-macros and loops to press in the browser's console. id="play-macro" onClick={this.playLastRecordedMacro}> <PlayArrowIcon /> </Button> </Tooltip> </Grid> </Grid> <div hidden={this.state.editMacro === ""}> <Typography component="p"> Write a macro below. The latest supported commands can be found <Link target="_blank" href="https://github.com/juharris/switch-remoteplay/blob/master/server/README.md#api">here</Link>. </Typography> <Typography component="p"> The macro should be a valid <Link target="_blank" href="https://www.json.org">JSON list</Link>. For example: </Typography> <pre className={classes.macroCode}>{'["s l up", "wait 200", "a d", "wait 350", "a u", "wait 200", "s l center"]'}</pre> <div> <TextField className={classes.macroName} label="Macro Name" name="macroName" value={this.state.macroName} onChange={this.handleChange} /> </div> <div> <TextareaAutosize className={classes.macroText} name="editMacro" value={this.state.editMacro} aria-label="Macro" onChange={this.handleChange} /> </div> <Grid container> <Grid item> <Tooltip title="Cancel editting macro" placement="top" > <Button id="cancel-edit-macro" onClick={this.cancelEditMacro}> <CancelIcon /> </Button> </Tooltip> </Grid> <Grid item hidden={this.state.editMacroId === undefined}> <Tooltip title="Delete this macro" placement="top" > <Button id="delete-macro" onClick={() => this.deleteMacro(this.state.editMacroId)}> <DeleteForeverIcon style={{ color: red[500] }} /> </Button> </Tooltip> </Grid> <Grid item> <Tooltip title="Save macro" placement="top" > <Button color="primary" id="save-macro" onClick={this.saveMacro}> <SaveIcon style={{ color: green[500] }} /> </Button> </Tooltip> </Grid> </Grid> </div> <Grid container spacing={1} className={classes.macrosContainer}> {this.state.savedMacros.map((savedMacro: SavedMacro) => { const maxLength = 90 let macroText = JSON.stringify(savedMacro.macro) if (macroText.length > maxLength) { macroText = macroText.slice(0, maxLength - 10) + "..." } return <Grid item key={savedMacro.id} className={classes.macroItem} xs={12} sm={4} md={3}> <Card className={classes.macroCard}> <CardContent className={classes.cardContent}> <Typography variant="h5" component="h5"> {savedMacro.name} </Typography> <pre color="textSecondary" className={classes.macroCode}>{macroText}</pre> {/* <Typography component="p" color="textSecondary"> </Typography> */} </CardContent> <CardActions className={classes.macroCardActions}> <Tooltip title="Edit macro" placement="top" > <Button id={`edit-${savedMacro.id}`} onClick={() => this.startEditingMacro(savedMacro.id, savedMacro.name, savedMacro.macro)}> <EditIcon /> </Button> </Tooltip> <Tooltip title="Play macro" placement="top" > <Button // The id is not used but it's helpful for writing // meta-macros and loops to press in the browser's console. id={`play-${savedMacro.id}`} onClick={() => this.playMacro(savedMacro.macro)}> <PlayArrowIcon /> </Button> </Tooltip> </CardActions> </Card> </Grid> } )} </Grid> </div> } } export default withStyles(styles)(Macros)
the_stack
import {Mutable, Proto, Observable, ObserverType} from "@swim/util"; import {Affinity} from "../fastener/Affinity"; import {FastenerOwner, FastenerInit, FastenerClass, Fastener} from "../fastener/Fastener"; import {Service} from "../service/Service"; /** @internal */ export type MemberProviderService<O, K extends keyof O> = O[K] extends Provider<any, infer S> ? S : never; /** @internal */ export type ProviderService<P extends Provider<any, any>> = P extends Provider<any, infer S> ? S : never; /** @public */ export interface ProviderInit<S = unknown> extends FastenerInit { extends?: {prototype: Provider<any, any>} | string | boolean | null; type?: unknown; observes?: boolean; initService?(service: S): void; willAttachService?(service: S): void; didAttachService?(service: S): void; deinitService?(service: S): void; willDetachService?(service: S): void; didDetachService?(service: S): void; willInherit?(superFastener: Provider<unknown, S>): void; didInherit?(superFastener: Provider<unknown, S>): void; willUninherit?(superFastener: Provider<unknown, S>): void; didUninherit?(superFastener: Provider<unknown, S>): void; willBindSuperFastener?(superFastener: Provider<unknown, S>): void; didBindSuperFastener?(superFastener: Provider<unknown, S>): void; willUnbindSuperFastener?(superFastener: Provider<unknown, S>): void; didUnbindSuperFastener?(superFastener: Provider<unknown, S>): void; service?: S; createService?(): S; } /** @public */ export type ProviderDescriptor<O = unknown, S = unknown, I = {}> = ThisType<Provider<O, S> & I> & ProviderInit<S> & Partial<I>; /** @public */ export interface ProviderClass<P extends Provider<any, any> = Provider<any, any>> extends FastenerClass<P> { } /** @public */ export interface ProviderFactory<P extends Provider<any, any> = Provider<any, any>> extends ProviderClass<P> { extend<I = {}>(className: string, classMembers?: Partial<I> | null): ProviderFactory<P> & I; define<O, S>(className: string, descriptor: ProviderDescriptor<O, S>): ProviderFactory; define<O, S extends Observable>(className: string, descriptor: {observes: boolean} & ProviderDescriptor<O, S, ObserverType<S>>): ProviderFactory<Provider<any, S>>; define<O, S, I = {}>(className: string, descriptor: {implements: unknown} & ProviderDescriptor<O, S, I>): ProviderFactory<Provider<any, S> & I>; define<O, S extends Observable, I = {}>(className: string, descriptor: {implements: unknown; observes: boolean} & ProviderDescriptor<O, S, I & ObserverType<S>>): ProviderFactory<Provider<any, S> & I>; <O, S>(descriptor: ProviderDescriptor<O, S>): PropertyDecorator; <O, S extends Observable>(descriptor: {observes: boolean} & ProviderDescriptor<O, S, ObserverType<S>>): PropertyDecorator; <O, S, I = {}>(descriptor: {implements: unknown} & ProviderDescriptor<O, S, I>): PropertyDecorator; <O, S extends Observable, I = {}>(descriptor: {implements: unknown; observes: boolean} & ProviderDescriptor<O, S, I & ObserverType<S>>): PropertyDecorator; } /** @public */ export interface Provider<O = unknown, S = unknown> extends Fastener<O> { (): S; /** @override */ get fastenerType(): Proto<Provider<any, any>>; /** @internal @override */ setInherited(inherited: boolean, superFastener: Provider<unknown, S>): void; /** @protected @override */ willInherit(superFastener: Provider<unknown, S>): void; /** @protected @override */ onInherit(superFastener: Provider<unknown, S>): void; /** @protected @override */ didInherit(superFastener: Provider<unknown, S>): void; /** @protected @override */ willUninherit(superFastener: Provider<unknown, S>): void; /** @protected @override */ onUninherit(superFastener: Provider<unknown, S>): void; /** @protected @override */ didUninherit(superFastener: Provider<unknown, S>): void; /** @override */ get superFastener(): Provider<unknown, S> | null; /** @internal @override */ getSuperFastener(): Provider<unknown, S> | null; /** @protected @override */ willBindSuperFastener(superFastener: Provider<unknown, S>): void; /** @protected @override */ onBindSuperFastener(superFastener: Provider<unknown, S>): void; /** @protected @override */ didBindSuperFastener(superFastener: Provider<unknown, S>): void; /** @protected @override */ willUnbindSuperFastener(superFastener: Provider<unknown, S>): void; /** @protected @override */ onUnbindSuperFastener(superFastener: Provider<unknown, S>): void; /** @protected @override */ didUnbindSuperFastener(superFastener: Provider<unknown, S>): void; /** @internal @override */ attachSubFastener(subFastener: Provider<unknown, S>): void; /** @internal @override */ detachSubFastener(subFastener: Provider<unknown, S>): void; readonly service: S; getService(): NonNullable<S>; getServiceOr<E>(elseService: E): NonNullable<S> | E; /** @internal */ setService(service: S): S; /** @protected */ initService(service: S): void; /** @protected */ willAttachService(service: S): void; /** @protected */ onAttachService(service: S): void; /** @protected */ didAttachService(service: S): void; /** @protected */ deinitService(service: S): void; /** @protected */ willDetachService(service: S): void; /** @protected */ onDetachService(service: S): void; /** @protected */ didDetachService(service: S): void; /** @internal */ createService(): S; /** @protected @override */ onMount(): void; /** @protected @override */ onUnmount(): void; /** @internal */ get observes(): boolean | undefined; // optional prototype field } /** @public */ export const Provider = (function (_super: typeof Fastener) { const Provider: ProviderFactory = _super.extend("Provider"); Object.defineProperty(Provider.prototype, "fastenerType", { get: function (this: Provider): Proto<Provider<any, any>> { return Provider; }, configurable: true, }); Provider.prototype.onInherit = function <S>(this: Provider<unknown, S>, superFastener: Provider<unknown, S>): void { this.setService(superFastener.service); }; Provider.prototype.onBindSuperFastener = function <S>(this: Provider<unknown, S>, superFastener: Provider<unknown, S>): void { if ((this.flags & Fastener.InheritsFlag) !== 0 && (this.flags & Affinity.Mask) === Affinity.Inherited) { this.initAffinity(Affinity.Transient); } _super.prototype.onBindSuperFastener.call(this, superFastener); }; Provider.prototype.onUnbindSuperFastener = function <S>(this: Provider<unknown, S>, superFastener: Provider<unknown, S>): void { _super.prototype.onUnbindSuperFastener.call(this, superFastener); if ((this.flags & Fastener.InheritsFlag) !== 0 && (this.flags & Affinity.Mask) === Affinity.Transient) { this.initAffinity(Affinity.Inherited); } }; Provider.prototype.getService = function <S>(this: Provider<unknown, S>): NonNullable<S> { const service = this.service; if (service === void 0 || service === null) { let message = service + " "; if (this.name.length !== 0) { message += this.name + " "; } message += "service"; throw new TypeError(message); } return service as NonNullable<S>; }; Provider.prototype.getServiceOr = function <S, E>(this: Provider<unknown, S>, elseService: E): NonNullable<S> | E { let service: S | E = this.service; if (service === void 0 || service === null) { service = elseService; } return service as NonNullable<S> | E; }; Provider.prototype.setService = function <S>(this: Provider<unknown, S>, newService: S): S { const oldService = this.service; if (oldService !== newService) { if (oldService !== void 0 && oldService !== null) { this.willDetachService(oldService); (this as Mutable<typeof this>).service = void 0 as unknown as S; this.onDetachService(oldService); this.deinitService(oldService); this.didDetachService(oldService); } if (newService !== void 0 && newService !== null) { this.willAttachService(newService); (this as Mutable<typeof this>).service = newService; this.onAttachService(newService); this.initService(newService); this.didAttachService(newService); } } return oldService; }; Provider.prototype.initService = function <S>(this: Provider<unknown, S>, service: S): void { // hook }; Provider.prototype.willAttachService = function <S>(this: Provider<unknown, S>, service: S): void { // hook }; Provider.prototype.onAttachService = function <S>(this: Provider<unknown, S>, service: S): void { if (this.observes === true && Observable.is(service)) { service.observe(this as ObserverType<S>); } }; Provider.prototype.didAttachService = function <S>(this: Provider<unknown, S>, service: S): void { // hook }; Provider.prototype.deinitService = function <S>(this: Provider<unknown, S>, service: S): void { // hook }; Provider.prototype.willDetachService = function <S>(this: Provider<unknown, S>, service: S): void { // hook }; Provider.prototype.onDetachService = function <S>(this: Provider<unknown, S>, service: S): void { if (this.observes === true && Observable.is(service)) { service.unobserve(this as ObserverType<S>); } }; Provider.prototype.didDetachService = function <S>(this: Provider<unknown, S>, service: S): void { // hook }; Provider.prototype.createService = function <S>(this: Provider<unknown, S>): S { return this.service; }; Provider.prototype.onMount = function (this: Provider): void { _super.prototype.onMount.call(this); let service = this.service; if (service === void 0 || service === null) { service = this.createService(); this.setService(service); } if ((this.flags & Fastener.InheritedFlag) === 0 && service instanceof Service) { service.attachRoot(this.owner); } }; Provider.prototype.onUnmount = function (this: Provider): void { const service = this.service; if ((this.flags & Fastener.InheritedFlag) === 0 && service instanceof Service) { service.detachRoot(this.owner); } _super.prototype.onUnmount.call(this); }; Provider.construct = function <P extends Provider<any, any>>(providerClass: {prototype: P}, provider: P | null, owner: FastenerOwner<P>): P { if (provider === null) { provider = function (): ProviderService<P> { return provider!.service; } as P; delete (provider as Partial<Mutable<P>>).name; // don't clobber prototype name Object.setPrototypeOf(provider, providerClass.prototype); } provider = _super.construct(providerClass, provider, owner) as P; (provider as Mutable<typeof provider>).service = void 0 as unknown as ProviderService<P>; provider.initAffinity(Affinity.Inherited); provider.initInherits(true); return provider; }; Provider.define = function <O, S>(className: string, descriptor: ProviderDescriptor<O, S>): ProviderFactory<Provider<any, S>> { let superClass = descriptor.extends as ProviderFactory | null | undefined; const affinity = descriptor.affinity; const inherits = descriptor.inherits; const service = descriptor.service; delete descriptor.extends; delete descriptor.implements; delete descriptor.affinity; delete descriptor.inherits; delete descriptor.service; if (superClass === void 0 || superClass === null) { superClass = this; } const providerClass = superClass.extend(className, descriptor); providerClass.construct = function (providerClass: {prototype: Provider<any, any>}, provider: Provider<O, S> | null, owner: O): Provider<O, S> { provider = superClass!.construct(providerClass, provider, owner); if (affinity !== void 0) { provider.initAffinity(affinity); } if (inherits !== void 0) { provider.initInherits(inherits); } if (service !== void 0) { provider.setService(service); } return provider; }; return providerClass; }; return Provider; })(Fastener);
the_stack
import {Constructor} from '../../../../types/GlobalTypes'; import {TypedCopNode} from '../_Base'; import {Texture} from 'three/src/textures/Texture'; import { RGBAFormat, UnsignedByteType, LinearEncoding, UVMapping, RepeatWrapping, LinearFilter, } from 'three/src/constants'; import { MAG_FILTERS, MAG_FILTER_DEFAULT_VALUE, MAG_FILTER_MENU_ENTRIES, MIN_FILTERS, MIN_FILTER_DEFAULT_VALUE, MIN_FILTER_MENU_ENTRIES, } from '../../../../core/cop/Filter'; import {NodeParamsConfig, ParamConfig} from '../../utils/params/ParamsConfig'; import {CopRendererController} from './RendererController'; import {BaseNodeType} from '../../_Base'; import {isBooleanTrue} from '../../../../core/BooleanValue'; import {ParamsValueAccessorType} from '../../utils/params/ParamsValueAccessor'; import {ENCODINGS} from '../../../../core/cop/Encoding'; import {WRAPPINGS} from '../../../../core/cop/Wrapping'; import {MAPPINGS} from '../../../../core/cop/Mapping'; import {TEXTURE_TYPES} from '../../../../core/cop/Type'; import {TEXTURE_FORMATS} from '../../../../core/cop/Format'; type AvailableCallbackMethod = Extract< keyof typeof TextureParamsController, | 'PARAM_CALLBACK_update_encoding' | 'PARAM_CALLBACK_update_mapping' | 'PARAM_CALLBACK_update_wrap' | 'PARAM_CALLBACK_update_filter' | 'PARAM_CALLBACK_update_anisotropy' | 'PARAM_CALLBACK_update_flipY' | 'PARAM_CALLBACK_update_transform' | 'PARAM_CALLBACK_update_repeat' | 'PARAM_CALLBACK_update_offset' | 'PARAM_CALLBACK_update_center' | 'PARAM_CALLBACK_update_rotation' | 'PARAM_CALLBACK_update_advanced' >; function callbackParams(method: AvailableCallbackMethod) { return { cook: false, callback: (node: BaseNodeType) => { TextureParamsController[method](node as TextureCopNode); }, }; } const DEFAULT = { ENCODING: LinearEncoding, FORMAT: RGBAFormat, MAPPING: UVMapping, MIN_FILTER: LinearFilter, MAG_FILTER: LinearFilter, TYPE: UnsignedByteType, WRAPPING: RepeatWrapping, }; const CALLBACK_PARAMS_ENCODING = callbackParams('PARAM_CALLBACK_update_encoding'); const CALLBACK_PARAMS_MAPPING = callbackParams('PARAM_CALLBACK_update_mapping'); const CALLBACK_PARAMS_WRAP = callbackParams('PARAM_CALLBACK_update_wrap'); const CALLBACK_PARAMS_FILTER = callbackParams('PARAM_CALLBACK_update_filter'); const CALLBACK_PARAMS_ANISOTROPY = callbackParams('PARAM_CALLBACK_update_anisotropy'); const CALLBACK_PARAMS_FLIPY = callbackParams('PARAM_CALLBACK_update_flipY'); const CALLBACK_PARAMS_TRANSFORM_TRANSFORM = callbackParams('PARAM_CALLBACK_update_transform'); const CALLBACK_PARAMS_TRANSFORM_REPEAT = callbackParams('PARAM_CALLBACK_update_repeat'); const CALLBACK_PARAMS_TRANSFORM_OFFSET = callbackParams('PARAM_CALLBACK_update_offset'); const CALLBACK_PARAMS_TRANSFORM_ROTATION = callbackParams('PARAM_CALLBACK_update_rotation'); const CALLBACK_PARAMS_TRANSFORM_CENTER = callbackParams('PARAM_CALLBACK_update_center'); const CALLBACK_PARAMS_ADVANCED = callbackParams('PARAM_CALLBACK_update_advanced'); export function TextureParamConfig<TBase extends Constructor>(Base: TBase) { return class Mixin extends Base { /** @param toggle on to allow updating the texture encoding */ tencoding = ParamConfig.BOOLEAN(0, { ...CALLBACK_PARAMS_ENCODING, }); /** @param sets the texture encoding */ encoding = ParamConfig.INTEGER(DEFAULT.ENCODING, { visibleIf: {tencoding: 1}, menu: { entries: ENCODINGS.map((m) => { return { name: Object.keys(m)[0], value: Object.values(m)[0] as number, }; }), }, ...CALLBACK_PARAMS_ENCODING, }); /** @param toggle on to allow updating the texture mapping */ tmapping = ParamConfig.BOOLEAN(0, { ...CALLBACK_PARAMS_MAPPING, }); /** @param sets the texture mapping */ mapping = ParamConfig.INTEGER(DEFAULT.MAPPING, { visibleIf: {tmapping: 1}, menu: { entries: MAPPINGS.map((m) => { return { name: Object.keys(m)[0], value: Object.values(m)[0] as number, }; }), }, ...CALLBACK_PARAMS_MAPPING, }); /** @param toggle on to allow updating the texture wrap */ twrap = ParamConfig.BOOLEAN(0, { ...CALLBACK_PARAMS_WRAP, }); /** @param sets the texture wrapS */ wrapS = ParamConfig.INTEGER(DEFAULT.WRAPPING, { visibleIf: {twrap: 1}, menu: { entries: WRAPPINGS.map((m) => { return { name: Object.keys(m)[0], value: Object.values(m)[0] as number, }; }), }, ...CALLBACK_PARAMS_WRAP, }); /** @param sets the texture wrapT */ wrapT = ParamConfig.INTEGER(DEFAULT.WRAPPING, { visibleIf: {twrap: 1}, menu: { entries: WRAPPINGS.map((m) => { return { name: Object.keys(m)[0], value: Object.values(m)[0] as number, }; }), }, separatorAfter: true, ...CALLBACK_PARAMS_WRAP, }); /** @param toggle on to allow updating the texture min filter */ tminFilter = ParamConfig.BOOLEAN(0, { ...CALLBACK_PARAMS_FILTER, }); /** @param sets the texture min filter */ minFilter = ParamConfig.INTEGER(MIN_FILTER_DEFAULT_VALUE, { visibleIf: {tminFilter: 1}, menu: { entries: MIN_FILTER_MENU_ENTRIES, }, ...CALLBACK_PARAMS_FILTER, }); /** @param toggle on to allow updating the texture mag filter */ tmagFilter = ParamConfig.BOOLEAN(0, { ...CALLBACK_PARAMS_FILTER, }); /** @param sets the texture mag filter */ magFilter = ParamConfig.INTEGER(MAG_FILTER_DEFAULT_VALUE, { visibleIf: {tmagFilter: 1}, menu: { entries: MAG_FILTER_MENU_ENTRIES, }, ...CALLBACK_PARAMS_FILTER, }); /** @param toggle on to allow updating the texture anisotropy */ tanisotropy = ParamConfig.BOOLEAN(0, { ...CALLBACK_PARAMS_ANISOTROPY, }); /** @param sets the anisotropy from the max value allowed by the renderer */ useRendererMaxAnisotropy = ParamConfig.BOOLEAN(0, { visibleIf: {tanisotropy: 1}, ...CALLBACK_PARAMS_ANISOTROPY, }); /** @param sets the anisotropy manually */ anisotropy = ParamConfig.INTEGER(2, { visibleIf: {tanisotropy: 1, useRendererMaxAnisotropy: 0}, range: [0, 32], rangeLocked: [true, false], ...CALLBACK_PARAMS_ANISOTROPY, }); /** @param Toggle on to update the flipY */ tflipY = ParamConfig.BOOLEAN(0, { ...CALLBACK_PARAMS_FLIPY, }); /** @param sets the flipY */ flipY = ParamConfig.BOOLEAN(0, { visibleIf: {tflipY: 1}, ...CALLBACK_PARAMS_FLIPY, }); /** @param toggle on to update the texture transform */ ttransform = ParamConfig.BOOLEAN(0, { ...CALLBACK_PARAMS_TRANSFORM_TRANSFORM, }); /** @param updates the texture offset */ offset = ParamConfig.VECTOR2([0, 0], { visibleIf: {ttransform: 1}, ...CALLBACK_PARAMS_TRANSFORM_OFFSET, }); /** @param updates the texture repeat */ repeat = ParamConfig.VECTOR2([1, 1], { visibleIf: {ttransform: 1}, ...CALLBACK_PARAMS_TRANSFORM_REPEAT, }); /** @param updates the texture rotation */ rotation = ParamConfig.FLOAT(0, { range: [-1, 1], visibleIf: {ttransform: 1}, ...CALLBACK_PARAMS_TRANSFORM_ROTATION, }); /** @param updates the texture center */ center = ParamConfig.VECTOR2([0, 0], { visibleIf: {ttransform: 1}, ...CALLBACK_PARAMS_TRANSFORM_CENTER, }); /** @param toggle on to display advanced parameters */ tadvanced = ParamConfig.BOOLEAN(0, { ...CALLBACK_PARAMS_ADVANCED, }); /** @param toggle on to allow overriding the texture format */ tformat = ParamConfig.BOOLEAN(0, { visibleIf: {tadvanced: 1}, ...CALLBACK_PARAMS_ADVANCED, }); /** @param sets the texture format */ format = ParamConfig.INTEGER(DEFAULT.FORMAT, { visibleIf: {tadvanced: 1, tformat: 1}, menu: { entries: TEXTURE_FORMATS.map((m) => { return { name: Object.keys(m)[0], value: Object.values(m)[0] as number, }; }), }, ...CALLBACK_PARAMS_ADVANCED, }); /** @param toggle on to allow overriding the texture type */ ttype = ParamConfig.BOOLEAN(0, { visibleIf: {tadvanced: 1}, ...CALLBACK_PARAMS_ADVANCED, }); /** @param sets the texture ty[e] */ type = ParamConfig.INTEGER(DEFAULT.TYPE, { visibleIf: {tadvanced: 1, ttype: 1}, menu: { entries: TEXTURE_TYPES.map((m) => { return { name: Object.keys(m)[0], value: Object.values(m)[0] as number, }; }), }, ...CALLBACK_PARAMS_ADVANCED, }); }; } class TextureParamsConfig extends TextureParamConfig(NodeParamsConfig) {} const ParamsConfig = new TextureParamsConfig(); class TextureCopNode extends TypedCopNode<TextureParamsConfig> { paramsConfig = ParamsConfig; public readonly textureParamsController = new TextureParamsController(this); } export class TextureParamsController { constructor(protected node: TextureCopNode) {} async update(texture: Texture) { const pv = this.node.pv; this._updateEncoding(texture, pv); this._updateAdvanced(texture, pv); this._updateMapping(texture, pv); this._updateWrap(texture, pv); this._updateFilter(texture, pv); this._updateFlip(texture, pv); await this._updateAnisotropy(texture, pv); this._updateTransform(texture); } private _updateEncoding(texture: Texture, pv: ParamsValueAccessorType<TextureParamsConfig>) { if (isBooleanTrue(pv.tencoding)) { texture.encoding = pv.encoding; } else { texture.encoding = DEFAULT.ENCODING; } texture.needsUpdate = true; } private _updateAdvanced(texture: Texture, pv: ParamsValueAccessorType<TextureParamsConfig>) { if (isBooleanTrue(pv.tadvanced)) { if (isBooleanTrue(pv.tformat)) { texture.format = pv.format; } else { texture.format = DEFAULT.FORMAT; } if (isBooleanTrue(pv.ttype)) { texture.type = pv.type; } else { texture.type = DEFAULT.TYPE; } } texture.needsUpdate = true; } private _updateMapping(texture: Texture, pv: ParamsValueAccessorType<TextureParamsConfig>) { if (isBooleanTrue(pv.tmapping)) { texture.mapping = pv.mapping; } else { texture.mapping = DEFAULT.MAPPING; } texture.needsUpdate = true; } private _updateWrap(texture: Texture, pv: ParamsValueAccessorType<TextureParamsConfig>) { if (isBooleanTrue(pv.twrap)) { texture.wrapS = pv.wrapS; texture.wrapT = pv.wrapT; } else { texture.wrapS = DEFAULT.WRAPPING; texture.wrapT = DEFAULT.WRAPPING; } texture.needsUpdate = true; } private _updateFilter(texture: Texture, pv: ParamsValueAccessorType<TextureParamsConfig>) { if (isBooleanTrue(pv.tminFilter)) { texture.minFilter = pv.minFilter; } else { // It makes more sense to: // - use LinearFilter by default when tfilter is off // - show LinearMipMapLinearFilter + LinearFilter when on to show the right combination. // rather than: // - use LinearMipMapLinearFilter + LinearFilter // as this would not work when importing a texture to be fed to a cop/envMap texture.minFilter = LinearFilter; } if (isBooleanTrue(pv.tmagFilter)) { texture.magFilter = pv.magFilter; } else { texture.magFilter = LinearFilter; } texture.needsUpdate = true; } private _updateFlip(texture: Texture, pv: ParamsValueAccessorType<TextureParamsConfig>) { // do not have this in an if block, // as to be sure this is set to false in case it is set to true // by the texture loader texture.flipY = pv.tflipY && pv.flipY; texture.needsUpdate = true; } private _renderer_controller: CopRendererController | undefined; private async _updateAnisotropy(texture: Texture, pv: ParamsValueAccessorType<TextureParamsConfig>) { if (!isBooleanTrue(pv.tanisotropy)) { texture.anisotropy = 1; return; } if (isBooleanTrue(pv.useRendererMaxAnisotropy)) { texture.anisotropy = await this._maxRendererAnisotropy(); } else { const anisotropy = pv.anisotropy; // if the requested anisotropy is 2 or less, // we can assume that the current renderer can provide it, // without having to wait for it to be created if (anisotropy <= 2) { texture.anisotropy = anisotropy; } else { texture.anisotropy = Math.min(anisotropy, await this._maxRendererAnisotropy()); } } texture.needsUpdate = true; } private async _maxRendererAnisotropy() { this._renderer_controller = this._renderer_controller || new CopRendererController(this.node); const renderer = await this._renderer_controller.renderer(); const max_anisotropy = renderer.capabilities.getMaxAnisotropy(); return max_anisotropy; } private _updateTransform(texture: Texture) { if (!isBooleanTrue(this.node.pv.ttransform)) { texture.offset.set(0, 0); texture.rotation = 0; texture.repeat.set(1, 1); texture.center.set(0, 0); return; } this._updateTransformOffset(texture, false); this._updateTransformRepeat(texture, false); this._updateTransformRotation(texture, false); this._updateTransformCenter(texture, false); texture.updateMatrix(); } private async _updateTransformOffset(texture: Texture, updateMatrix: boolean) { texture.offset.copy(this.node.pv.offset); if (updateMatrix) { texture.updateMatrix(); } } private async _updateTransformRepeat(texture: Texture, updateMatrix: boolean) { texture.repeat.copy(this.node.pv.repeat); if (updateMatrix) { texture.updateMatrix(); } } private async _updateTransformRotation(texture: Texture, updateMatrix: boolean) { texture.rotation = this.node.pv.rotation; if (updateMatrix) { texture.updateMatrix(); } } private async _updateTransformCenter(texture: Texture, updateMatrix: boolean) { texture.center.copy(this.node.pv.center); if (updateMatrix) { texture.updateMatrix(); } } // // // CALLBACK // // static PARAM_CALLBACK_update_encoding(node: TextureCopNode) { const texture = node.containerController.container().texture(); if (!texture) { return; } node.textureParamsController._updateEncoding(texture, node.pv); } static PARAM_CALLBACK_update_mapping(node: TextureCopNode) { const texture = node.containerController.container().texture(); if (!texture) { return; } node.textureParamsController._updateMapping(texture, node.pv); } static PARAM_CALLBACK_update_wrap(node: TextureCopNode) { const texture = node.containerController.container().texture(); if (!texture) { return; } node.textureParamsController._updateWrap(texture, node.pv); } static PARAM_CALLBACK_update_filter(node: TextureCopNode) { const texture = node.containerController.container().texture(); if (!texture) { return; } node.textureParamsController._updateFilter(texture, node.pv); } static PARAM_CALLBACK_update_anisotropy(node: TextureCopNode) { const texture = node.containerController.container().texture(); if (!texture) { return; } node.textureParamsController._updateAnisotropy(texture, node.pv); } static PARAM_CALLBACK_update_flipY(node: TextureCopNode) { const texture = node.containerController.container().texture(); if (!texture) { return; } node.textureParamsController._updateFlip(texture, node.pv); } static PARAM_CALLBACK_update_transform(node: TextureCopNode) { const texture = node.containerController.container().texture(); if (!texture) { return; } node.textureParamsController._updateTransform(texture); } static PARAM_CALLBACK_update_offset(node: TextureCopNode) { const texture = node.containerController.container().texture(); if (!texture) { return; } node.textureParamsController._updateTransformOffset(texture, true); } static PARAM_CALLBACK_update_repeat(node: TextureCopNode) { const texture = node.containerController.container().texture(); if (!texture) { return; } node.textureParamsController._updateTransformRepeat(texture, true); } static PARAM_CALLBACK_update_rotation(node: TextureCopNode) { const texture = node.containerController.container().texture(); if (!texture) { return; } node.textureParamsController._updateTransformRotation(texture, true); } static PARAM_CALLBACK_update_center(node: TextureCopNode) { const texture = node.containerController.container().texture(); if (!texture) { return; } node.textureParamsController._updateTransformCenter(texture, true); } static PARAM_CALLBACK_update_advanced(node: TextureCopNode) { const texture = node.containerController.container().texture(); if (!texture) { return; } node.textureParamsController._updateAdvanced(texture, node.pv); } // // // UTILS // // static copyTextureAttributes(texture: Texture, inputTexture: Texture) { texture.encoding = inputTexture.encoding; texture.mapping = inputTexture.mapping; texture.wrapS = inputTexture.wrapS; texture.wrapT = inputTexture.wrapT; texture.minFilter = inputTexture.minFilter; texture.magFilter = inputTexture.magFilter; texture.magFilter = inputTexture.magFilter; texture.anisotropy = inputTexture.anisotropy; texture.flipY = inputTexture.flipY; texture.repeat.copy(inputTexture.repeat); texture.offset.copy(inputTexture.offset); texture.center.copy(inputTexture.center); texture.rotation = inputTexture.rotation; texture.type = inputTexture.type; texture.format = inputTexture.format; texture.needsUpdate = true; } paramLabelsParams() { const p = this.node.p; return [ // encoding p.tencoding, p.encoding, // mapping p.tmapping, p.mapping, // wrap p.twrap, p.wrapS, p.wrapT, // filter p.tminFilter, p.minFilter, p.tmagFilter, p.magFilter, // flipY p.tflipY, p.flipY, ]; } paramLabels() { const labels: string[] = []; const pv = this.node.pv; if (isBooleanTrue(pv.tencoding)) { for (let encoding of ENCODINGS) { const encodingName = Object.keys(encoding)[0]; const encodingValue = (encoding as any)[encodingName]; if (encodingValue == pv.encoding) { labels.push(`encoding: ${encodingName}`); } } } if (isBooleanTrue(pv.tmapping)) { for (let mapping of MAPPINGS) { const mappingName = Object.keys(mapping)[0]; const mappingValue = (mapping as any)[mappingName]; if (mappingValue == pv.mapping) { labels.push(`mapping: ${mappingName}`); } } } if (isBooleanTrue(pv.twrap)) { function setWrapping(wrappingAxis: 'wrapS' | 'wrapT') { for (let wrapping of WRAPPINGS) { const wrappingName = Object.keys(wrapping)[0]; const wrappingValue = (wrapping as any)[wrappingName]; if (wrappingValue == pv[wrappingAxis]) { labels.push(`${wrappingAxis}: ${wrappingName}`); } } } setWrapping('wrapS'); setWrapping('wrapT'); } if (isBooleanTrue(pv.tminFilter)) { for (let minFilter of MIN_FILTERS) { const minFilterName = Object.keys(minFilter)[0]; const minFilterValue = (minFilter as any)[minFilterName]; if (minFilterValue == pv.minFilter) { labels.push(`minFilter: ${minFilterName}`); } } } if (isBooleanTrue(pv.tmagFilter)) { for (let magFilter of MAG_FILTERS) { const magFilterName = Object.keys(magFilter)[0]; const magFilterValue = (magFilter as any)[magFilterName]; if (magFilterValue == pv.magFilter) { labels.push(`magFilter: ${magFilterName}`); } } } if (isBooleanTrue(pv.tflipY)) { labels.push(`flipY: ${pv.flipY}`); } return labels; } }
the_stack
import * as React from 'react'; import { Link } from 'react-router-dom'; import { Form, Input, Button, Select, Row, Col, Popover, Progress } from 'antd'; import './Register.less'; const FormItem = Form.Item; const { Option } = Select; const InputGroup = Input.Group; const passwordStatusMap = { ok: <div className={'success'}>强度:强</div>, pass: <div className={'warning'}>强度:中</div>, poor: <div className={'error'}>强度:太短</div>, }; const passwordProgressMap = { ok: 'success', pass: 'normal', poor: 'exception', }; // @connect(({ register, loading }) => ({ // register, // submitting: loading.effects['register/submit'], // })) class Register extends React.Component<{form, submitting, register, history}, {count: number, confirmDirty:boolean, visible: boolean, help: string, prefix: string}> { private interval; constructor(props){ super(props); this.state={ count: 0, confirmDirty: false, visible: false, help: '', prefix: '86', } } public componentWillReceiveProps(nextProps) { // const account = this.props.form.getFieldValue('mail'); // if (nextProps.register.status === 'ok') { // this.props.dispatch( // routerRedux.push({ // pathname: '/user/register-result', // state: { // account, // }, // }) // ); // } } public componentWillUnmount() { clearInterval(this.interval); } private onGetCaptcha = () => { let count = 59; this.setState({ count }); this.interval = setInterval(() => { count -= 1; this.setState({ count }); if (count === 0) { clearInterval(this.interval); } }, 1000); }; private getPasswordStatus = () => { const { form } = this.props; const value = form.getFieldValue('password'); if (value && value.length > 9) { return 'ok'; } if (value && value.length > 5) { return 'pass'; } return 'poor'; }; private handleSubmit = e => { e.preventDefault(); this.props.form.validateFields({ force: true }, (err, values) => { if (!err) { const account = this.props.form.getFieldValue('mail'); this.props.history.push('/user/register-result'); // this.props.dispatch({ // type: 'register/submit', // payload: { // ...values, // prefix: this.state.prefix, // }, // }); } }); }; private handleConfirmBlur = e => { const { value } = e.target; this.setState({ confirmDirty: this.state.confirmDirty || !!value }); }; private checkConfirm = (rule, value, callback) => { const { form } = this.props; if (value && value !== form.getFieldValue('password')) { callback('两次输入的密码不匹配!'); } else { callback(); } }; private checkPassword = (rule, value, callback) => { if (!value) { this.setState({ help: '请输入密码!', visible: !!value, }); callback('error'); } else { this.setState({ help: '', }); if (!this.state.visible) { this.setState({ visible: !!value, }); } if (value.length < 6) { callback('error'); } else { const { form } = this.props; if (value && this.state.confirmDirty) { form.validateFields(['confirm'], { force: true }); } callback(); } } }; private changePrefix = value => { this.setState({ prefix: value, }); }; private renderPasswordProgress = () => { const { form } = this.props; const value = form.getFieldValue('password'); const passwordStatus = this.getPasswordStatus(); return value && value.length ? ( <div className={`progress-${passwordStatus}`}> <Progress status={passwordProgressMap[passwordStatus] as "success" | "exception" | "active"} className={'progress'} strokeWidth={6} percent={value.length * 10 > 100 ? 100 : value.length * 10} showInfo={false} /> </div> ) : null; }; public render() { const { form, submitting } = this.props; const { getFieldDecorator } = form; const { count, prefix } = this.state; return ( <div className={'main Register'}> <h3>注册</h3> <Form onSubmit={this.handleSubmit}> <FormItem> {getFieldDecorator('mail', { rules: [ { required: true, message: '请输入邮箱地址!', }, { type: 'email', message: '邮箱地址格式错误!', }, ], })(<Input size="large" placeholder="邮箱" />)} </FormItem> <FormItem help={this.state.help}> <Popover content={ <div style={{ padding: '4px 0' }}> {passwordStatusMap[this.getPasswordStatus()]} {this.renderPasswordProgress()} <div style={{ marginTop: 10 }}> 请至少输入 6 个字符。请不要使用容易被猜到的密码。 </div> </div> } overlayStyle={{ width: 240 }} placement="right" visible={this.state.visible} > {getFieldDecorator('password', { rules: [ { validator: this.checkPassword, }, ], })(<Input size="large" type="password" placeholder="至少6位密码,区分大小写" />)} </Popover> </FormItem> <FormItem> {getFieldDecorator('confirm', { rules: [ { required: true, message: '请确认密码!', }, { validator: this.checkConfirm, }, ], })(<Input size="large" type="password" placeholder="确认密码" />)} </FormItem> <FormItem> <InputGroup compact={true}> <Select size="large" value={prefix} onChange={this.changePrefix} style={{ width: '20%' }} > <Option value="86">+86</Option> <Option value="87">+87</Option> </Select> {getFieldDecorator('mobile', { rules: [ { required: true, message: '请输入手机号!', }, { pattern: /^1\d{10}$/, message: '手机号格式错误!', }, ], })(<Input size="large" style={{ width: '80%' }} placeholder="11位手机号" />)} </InputGroup> </FormItem> <FormItem> <Row gutter={8}> <Col span={16}> {getFieldDecorator('captcha', { rules: [ { required: true, message: '请输入验证码!', }, ], })(<Input size="large" placeholder="验证码" />)} </Col> <Col span={8}> <Button size="large" disabled={count?true:false} className={'getCaptcha'} onClick={this.onGetCaptcha} > {count ? `${count} s` : '获取验证码'} </Button> </Col> </Row> </FormItem> <FormItem> <Button size="large" loading={submitting} className={'submit'} type="primary" htmlType="submit" > 注册 </Button> <Link className={'login'} to="/user/login"> 使用已有账户登录 </Link> </FormItem> </Form> </div> ); } } export default Form.create()(Register);
the_stack
* 判断一个字符串是否为合法变量名,第一个字符为字母,下划线或$开头,第二个字符开始为字母,下划线,数字或$ */ export function isVariableWord(word) { if (!word) return false; var char = word.charAt(0); if (!isVariableFirstChar(char)) { return false; } var length = word.length; for (var i = 1; i < length; i++) { char = word.charAt(i); if (!isVariableChar(char)) { return false; } } return true; } /** * 是否为合法变量字符,字符为字母,下划线,数字或$ */ export function isVariableChar(char) { return (char <= "Z" && char >= "A" || char <= "z" && char >= "a" || char <= "9" && char >= "0" || char == "_" || char == "$"); } /** * 是否为合法变量字符串的第一个字符,字符为字母,下划线或$ */ export function isVariableFirstChar(char) { return (char <= "Z" && char >= "A" || char <= "z" && char >= "a" || char == "_" || char == "$"); } /** * 判断一段代码中是否含有某个变量字符串,且该字符串的前后都不是变量字符。 */ export function containsVariable(key, codeText) { var contains = false; while (codeText.length > 0) { var index = codeText.indexOf(key); if (index == -1) break; var lastChar = codeText.charAt(index + key.length); var firstChar = codeText.charAt(index - 1); if (!isVariableChar(firstChar) && !isVariableChar(lastChar)) { contains = true; break; } else { codeText = codeText.substring(index + key.length); } } return contains; } /** * 获取第一个含有key关键字的起始索引,且该关键字的前后都不是变量字符。 */ export function getFirstVariableIndex(key, codeText) { var subLength = 0; while (codeText.length) { var index = codeText.indexOf(key); if (index == -1) { break; } var lastChar = codeText.charAt(index + key.length); var firstChar = codeText.charAt(index - 1); if (!isVariableChar(firstChar) && !isVariableChar(lastChar)) { return subLength + index; } else { subLength += index + key.length; codeText = codeText.substring(index + key.length); } } return -1; } /** * 获取最后一个含有key关键字的起始索引,且该关键字的前后都不是变量字符。 */ export function getLastVariableIndex(key, codeText) { while (codeText.length) { var index = codeText.lastIndexOf(key); if (index == -1) { break; } var lastChar = codeText.charAt(index + key.length); var firstChar = codeText.charAt(index - 1); if (!isVariableChar(firstChar) && !isVariableChar(lastChar)) { return index; } else { codeText = codeText.substring(0, index); } } return -1; } /** * 获取第一个词,遇到空白字符或 \n \r \t 后停止。 */ export function getFirstWord(str) { str = str.trim(); var index = str.indexOf(" "); if (index == -1) index = Number.MAX_VALUE; var rIndex = str.indexOf("\r"); if (rIndex == -1) rIndex = Number.MAX_VALUE; var nIndex = str.indexOf("\n"); if (nIndex == -1) nIndex = Number.MAX_VALUE; var tIndex = str.indexOf("\t"); if (tIndex == -1) tIndex = Number.MAX_VALUE; index = Math.min(index, rIndex, nIndex, tIndex); str = str.substr(0, index); return str.trim(); } /** * 移除第一个词 * @param str 要处理的字符串 * @param word 要移除的词,若不传入则自动获取。 */ export function removeFirstWord(str, word="") { if (!word) { word = getFirstWord(str); } var index = str.indexOf(word); if (index == -1) return str; return str.substring(index + word.length); } /** * 获取最后一个词,遇到空白字符或 \n \r \t 后停止。 */ export function getLastWord(str) { str = str.trim(); var index = str.lastIndexOf(" "); var rIndex = str.lastIndexOf("\r"); var nIndex = str.lastIndexOf("\n"); var tIndex = str.indexOf("\t"); index = Math.max(index, rIndex, nIndex, tIndex); str = str.substring(index + 1); return str.trim(); } /** * 移除最后一个词 * @param str 要处理的字符串 * @param word 要移除的词,若不传入则自动获取。 */ export function removeLastWord(str, word) { if (typeof word === "undefined") { word = ""; } if (!word) { word = getLastWord(str); } var index = str.lastIndexOf(word); if (index == -1) return str; return str.substring(0, index); } /** * 获取字符串起始的第一个变量,返回的字符串两端均没有空白。若第一个非空白字符就不是合法变量字符,则返回空字符串。 */ export function getFirstVariable(str) { str = str.trim(); var word = ""; var length = str.length; for (var i = 0; i < length; i++) { var char = str.charAt(i); if (isVariableChar(char)) { word += char; } else { break; } } return word.trim(); } /** * 移除第一个变量 * @param str 要处理的字符串 * @param word 要移除的变量,若不传入则自动获取。 */ export function removeFirstVariable(str, word="") { if (!word) { word = getFirstVariable(str); } var index = str.indexOf(word); if (index == -1) return str; return str.substring(index + word.length); } /** * 获取字符串末尾的最后一个变量,返回的字符串两端均没有空白。若最后一个非空白字符就不是合法变量字符,则返回空字符串。 */ export function getLastVariable(str) { str = str.trim(); var word = ""; for (var i = str.length - 1; i >= 0; i--) { var char = str.charAt(i); if (isVariableChar(char)) { word = char + word; } else { break; } } return word.trim(); } /** * 移除最后一个变量 * @param str 要处理的字符串 * @param word 要移除的变量,若不传入则自动获取。 */ export function removeLastVariable(str, word) { if (typeof word === "undefined") { word = ""; } if (!word) { word = getLastVariable(str); } var index = str.lastIndexOf(word); if (index == -1) return str; return str.substring(0, index); } /** * 获取一对括号的结束点,例如"class A{ function B(){} } class",返回24,若查找失败,返回-1。 */ export function getBracketEndIndex(codeText, left='{', right='}') { var indent = 0; var text = ""; while (codeText.length > 0) { var index = codeText.indexOf(left); if (index == -1) index = Number.MAX_VALUE; var endIndex = codeText.indexOf(right); if (endIndex == -1) endIndex = Number.MAX_VALUE; index = Math.min(index, endIndex); if (index == Number.MAX_VALUE) { return -1; } text += codeText.substring(0, index + 1); codeText = codeText.substring(index + 1); if (index == endIndex) indent--; else indent++; if (indent == 0) { break; } if (codeText.length == 0) return -1; } return text.length - 1; } /** * 从后往前搜索,获取一对括号的起始点,例如"class A{ function B(){} } class",返回7,若查找失败,返回-1。 */ export function getBracketStartIndex(codeText, left, right) { if (typeof left === "undefined") { left = "{"; } if (typeof right === "undefined") { right = "}"; } var indent = 0; while (codeText.length > 0) { var index = codeText.lastIndexOf(left); var endIndex = codeText.lastIndexOf(right); index = Math.max(index, endIndex); if (index == -1) { return -1; } codeText = codeText.substring(0, index); if (index == endIndex) indent++; else indent--; if (indent == 0) { break; } if (codeText.length == 0) return -1; } return codeText.length; } /** * 去掉字符串两端所有连续的非变量字符。 * @param str 要格式化的字符串 */ export function trimVariable(str) { return trimVariableLeft(trimVariableRight(str)); } /** * 去除字符串左边所有连续的非变量字符。 * @param str 要格式化的字符串 */ export function trimVariableLeft(str) { if (!str) return ""; var char = str.charAt(0); while (str.length > 0 && !isVariableFirstChar(char)) { str = str.substr(1); char = str.charAt(0); } return str; } /** * 去除字符串右边所有连续的非变量字符。 * @param str 要格式化的字符串 */ export function trimVariableRight(str) { if (!str) return ""; var char = str.charAt(str.length - 1); while (str.length > 0 && !isVariableChar(char)) { str = str.substr(0, str.length - 1); char = str.charAt(str.length - 1); } return str; } var removeCommentCache = {}; /** * 移除代码注释和字符串常量 */ export function removeComment(codeText,path) { if(path&&removeCommentCache[path]){ return removeCommentCache[path]; } //performance optimize // var result = codeText.replace(/(?:^|\n|\r)\s*\/\*[\s\S]*?\*\/\s*(?:\r|\n|$)/g, '\n').replace(/(?:^|\n|\r)\s*\/\/.*(?:\r|\n|$)/g, '\n'); // return result; var NBSP = ""; var trimText = ""; codeText = codeText.split("\\\\").join("\v0\v"); codeText = codeText.split("\\\"").join("\v1\v"); codeText = codeText.split("\\\'").join("\v2\v"); codeText = codeText.split("\r\n").join("\n").split("\r").join("\n"); while (codeText.length > 0) { var quoteIndex = codeText.indexOf("\""); if (quoteIndex == -1) quoteIndex = Number.MAX_VALUE; var squoteIndex = codeText.indexOf("'"); if (squoteIndex == -1) squoteIndex = Number.MAX_VALUE; var commentIndex = codeText.indexOf("/*"); if (commentIndex == -1) commentIndex = Number.MAX_VALUE; var lineCommonentIndex = codeText.indexOf("//"); if (lineCommonentIndex == -1) lineCommonentIndex = Number.MAX_VALUE; var index = Math.min(quoteIndex, squoteIndex, commentIndex, lineCommonentIndex); if (index == Number.MAX_VALUE) { trimText += codeText; break; } trimText += codeText.substring(0, index) + NBSP; codeText = codeText.substring(index); switch (index) { case quoteIndex: codeText = codeText.substring(1); index = codeText.indexOf("\""); if (index == -1) index = codeText.length - 1; codeText = codeText.substring(index + 1); break; case squoteIndex: codeText = codeText.substring(1); index = codeText.indexOf("'"); if (index == -1) index = codeText.length - 1; codeText = codeText.substring(index + 1); break; case commentIndex: index = codeText.indexOf("*/"); if (index == -1) index = codeText.length - 1; codeText = codeText.substring(index + 2); break; case lineCommonentIndex: index = codeText.indexOf("\n"); if (index == -1) index = codeText.length - 1; codeText = codeText.substring(index); break; } } codeText = trimText.split("\v0\v").join("\\\\"); codeText = codeText.split("\v1\v").join("\\\""); codeText = codeText.split("\v2\v").join("\\\'"); if(path){ removeCommentCache[path] = codeText; } return codeText; } /** * 移除代码注释不移除字符串常量 */ export function removeCommentExceptQuote(codeText) { var NBSP = ""; var trimText = ""; codeText = codeText.split("\\\\").join("\v0\v"); codeText = codeText.split("\\\"").join("\v1\v"); codeText = codeText.split("\\\'").join("\v2\v"); codeText = codeText.split("\r\n").join("\n").split("\r").join("\n"); while (codeText.length > 0) { var quoteIndex = codeText.indexOf("\""); if (quoteIndex == -1) quoteIndex = Number.MAX_VALUE; var squoteIndex = codeText.indexOf("'"); if (squoteIndex == -1) squoteIndex = Number.MAX_VALUE; var commentIndex = codeText.indexOf("/*"); if (commentIndex == -1) commentIndex = Number.MAX_VALUE; var lineCommonentIndex = codeText.indexOf("//"); if (lineCommonentIndex == -1) lineCommonentIndex = Number.MAX_VALUE; var index = Math.min(quoteIndex, squoteIndex, commentIndex, lineCommonentIndex); if (index == Number.MAX_VALUE) { trimText += codeText; break; } trimText += codeText.substring(0, index) + NBSP; codeText = codeText.substring(index); switch (index) { case quoteIndex: codeText = codeText.substring(1); index = codeText.indexOf("\""); if (index == -1) index = codeText.length - 1; trimText += codeText.substring(0,index + 1) codeText = codeText.substring(index + 1); break; case squoteIndex: codeText = codeText.substring(1); index = codeText.indexOf("'"); if (index == -1) index = codeText.length - 1; trimText += codeText.substring(0,index + 1) codeText = codeText.substring(index + 1); break; case commentIndex: index = codeText.indexOf("*/"); if (index == -1) index = codeText.length - 1; codeText = codeText.substring(index + 2); break; case lineCommonentIndex: index = codeText.indexOf("\n"); if (index == -1) index = codeText.length - 1; codeText = codeText.substring(index); break; } } codeText = trimText.split("\v0\v").join("\\\\"); codeText = codeText.split("\v1\v").join("\\\""); codeText = codeText.split("\v2\v").join("\\\'"); return codeText; }
the_stack
'use strict'; import { Socket } from 'net'; import { ConfigurationTarget, DiagnosticSeverity, Disposable, DocumentSymbolProvider, Event, Extension, ExtensionContext, OutputChannel, Uri, WorkspaceEdit } from 'vscode'; import { EnvironmentVariables } from './variables/types'; export const IOutputChannel = Symbol('IOutputChannel'); export interface IOutputChannel extends OutputChannel { } export const IDocumentSymbolProvider = Symbol('IDocumentSymbolProvider'); export interface IDocumentSymbolProvider extends DocumentSymbolProvider { } export const IsWindows = Symbol('IS_WINDOWS'); export const IDisposableRegistry = Symbol('IDiposableRegistry'); export type IDisposableRegistry = { push(disposable: Disposable): void }; export const IMemento = Symbol('IGlobalMemento'); export const GLOBAL_MEMENTO = Symbol('IGlobalMemento'); export const WORKSPACE_MEMENTO = Symbol('IWorkspaceMemento'); export type Resource = Uri | undefined; export interface IPersistentState<T> { readonly value: T; updateValue(value: T): Promise<void>; } export type Version = { raw: string; major: number; minor: number; patch: number; build: string[]; prerelease: string[]; }; export const IPersistentStateFactory = Symbol('IPersistentStateFactory'); export interface IPersistentStateFactory { createGlobalPersistentState<T>(key: string, defaultValue?: T, expiryDurationMs?: number): IPersistentState<T>; createWorkspacePersistentState<T>(key: string, defaultValue?: T, expiryDurationMs?: number): IPersistentState<T>; } export type ExecutionInfo = { execPath?: string; moduleName?: string; args: string[]; product?: Product; }; export enum LogLevel { Information = 'Information', Error = 'Error', Warning = 'Warning' } export const ILogger = Symbol('ILogger'); export interface ILogger { logError(message: string, error?: Error): void; logWarning(message: string, error?: Error): void; logInformation(message: string, error?: Error): void; } export enum InstallerResponse { Installed, Disabled, Ignore } export enum ProductType { Linter = 'Linter', Formatter = 'Formatter', TestFramework = 'TestFramework', RefactoringLibrary = 'RefactoringLibrary', WorkspaceSymbols = 'WorkspaceSymbols' } export enum Product { pytest = 1, nosetest = 2, pylint = 3, flake8 = 4, pep8 = 5, pylama = 6, prospector = 7, pydocstyle = 8, yapf = 9, autopep8 = 10, mypy = 11, unittest = 12, ctags = 13, rope = 14, isort = 15, black = 16, bandit = 17 } export enum ModuleNamePurpose { install = 1, run = 2 } export const IInstaller = Symbol('IInstaller'); export interface IInstaller { promptToInstall(product: Product, resource?: Uri): Promise<InstallerResponse>; install(product: Product, resource?: Uri): Promise<InstallerResponse>; isInstalled(product: Product, resource?: Uri): Promise<boolean | undefined>; translateProductToModuleName(product: Product, purpose: ModuleNamePurpose): string; } export const IPathUtils = Symbol('IPathUtils'); export interface IPathUtils { readonly delimiter: string; readonly home: string; /** * The platform-specific file separator. '\\' or '/'. * @type {string} * @memberof IPathUtils */ readonly separator: string; getPathVariableName(): 'Path' | 'PATH'; basename(pathValue: string, ext?: string): string; getDisplayName(pathValue: string, cwd?: string): string; } export const IRandom = Symbol('IRandom'); export interface IRandom { getRandomInt(min?: number, max?: number): number; } export const ICurrentProcess = Symbol('ICurrentProcess'); export interface ICurrentProcess { readonly env: EnvironmentVariables; readonly argv: string[]; readonly stdout: NodeJS.WriteStream; readonly stdin: NodeJS.ReadStream; readonly execPath: string; on(event: string | symbol, listener: Function): this; } export interface IPythonSettings { readonly pythonPath: string; readonly venvPath: string; readonly venvFolders: string[]; readonly condaPath: string; readonly pipenvPath: string; readonly poetryPath: string; readonly downloadLanguageServer: boolean; readonly jediEnabled: boolean; readonly jediPath: string; readonly jediMemoryLimit: number; readonly devOptions: string[]; readonly linting: ILintingSettings; readonly formatting: IFormattingSettings; readonly testing: ITestingSettings; readonly autoComplete: IAutoCompleteSettings; readonly terminal: ITerminalSettings; readonly sortImports: ISortImportSettings; readonly workspaceSymbols: IWorkspaceSymbolSettings; readonly envFile: string; readonly disableInstallationChecks: boolean; readonly globalModuleInstallation: boolean; readonly analysis: IAnalysisSettings; readonly autoUpdateLanguageServer: boolean; readonly datascience: IDataScienceSettings; readonly onDidChange: Event<void>; } export interface ISortImportSettings { readonly path: string; readonly args: string[]; } export interface ITestingSettings { readonly promptToConfigure: boolean; readonly debugPort: number; readonly nosetestsEnabled: boolean; nosetestPath: string; nosetestArgs: string[]; readonly pyTestEnabled: boolean; pyTestPath: string; pyTestArgs: string[]; readonly unittestEnabled: boolean; unittestArgs: string[]; cwd?: string; readonly autoTestDiscoverOnSaveEnabled: boolean; } export interface IPylintCategorySeverity { readonly convention: DiagnosticSeverity; readonly refactor: DiagnosticSeverity; readonly warning: DiagnosticSeverity; readonly error: DiagnosticSeverity; readonly fatal: DiagnosticSeverity; } export interface IPep8CategorySeverity { readonly W: DiagnosticSeverity; readonly E: DiagnosticSeverity; } // tslint:disable-next-line:interface-name export interface Flake8CategorySeverity { readonly F: DiagnosticSeverity; readonly E: DiagnosticSeverity; readonly W: DiagnosticSeverity; } export interface IMypyCategorySeverity { readonly error: DiagnosticSeverity; readonly note: DiagnosticSeverity; } export interface ILintingSettings { readonly enabled: boolean; readonly ignorePatterns: string[]; readonly prospectorEnabled: boolean; readonly prospectorArgs: string[]; readonly pylintEnabled: boolean; readonly pylintArgs: string[]; readonly pep8Enabled: boolean; readonly pep8Args: string[]; readonly pylamaEnabled: boolean; readonly pylamaArgs: string[]; readonly flake8Enabled: boolean; readonly flake8Args: string[]; readonly pydocstyleEnabled: boolean; readonly pydocstyleArgs: string[]; readonly lintOnSave: boolean; readonly maxNumberOfProblems: number; readonly pylintCategorySeverity: IPylintCategorySeverity; readonly pep8CategorySeverity: IPep8CategorySeverity; readonly flake8CategorySeverity: Flake8CategorySeverity; readonly mypyCategorySeverity: IMypyCategorySeverity; prospectorPath: string; pylintPath: string; pep8Path: string; pylamaPath: string; flake8Path: string; pydocstylePath: string; mypyEnabled: boolean; mypyArgs: string[]; mypyPath: string; banditEnabled: boolean; banditArgs: string[]; banditPath: string; readonly pylintUseMinimalCheckers: boolean; } export interface IFormattingSettings { readonly provider: string; autopep8Path: string; readonly autopep8Args: string[]; blackPath: string; readonly blackArgs: string[]; yapfPath: string; readonly yapfArgs: string[]; } export interface IAutoCompleteSettings { readonly addBrackets: boolean; readonly extraPaths: string[]; readonly showAdvancedMembers: boolean; readonly typeshedPaths: string[]; } export interface IWorkspaceSymbolSettings { readonly enabled: boolean; tagFilePath: string; readonly rebuildOnStart: boolean; readonly rebuildOnFileSave: boolean; readonly ctagsPath: string; readonly exclusionPatterns: string[]; } export interface ITerminalSettings { readonly executeInFileDir: boolean; readonly launchArgs: string[]; readonly activateEnvironment: boolean; } export type LanguageServerDownloadChannels = 'stable' | 'beta' | 'daily'; export interface IAnalysisSettings { readonly downloadChannel?: LanguageServerDownloadChannels; readonly openFilesOnly: boolean; readonly typeshedPaths: string[]; readonly errors: string[]; readonly warnings: string[]; readonly information: string[]; readonly disabled: string[]; readonly traceLogging: boolean; readonly logLevel: LogLevel; } export interface IDataScienceSettings { allowImportFromNotebook: boolean; enabled: boolean; jupyterInterruptTimeout: number; jupyterLaunchTimeout: number; jupyterServerURI: string; notebookFileRoot: string; changeDirOnImportExport: boolean; useDefaultConfigForJupyter: boolean; searchForJupyter: boolean; allowInput: boolean; showCellInputCode: boolean; collapseCellInputCodeByDefault: boolean; maxOutputSize: number; sendSelectionToInteractiveWindow: boolean; markdownRegularExpression: string; codeRegularExpression: string; allowLiveShare?: boolean; errorBackgroundColor: string; ignoreVscodeTheme?: boolean; showJupyterVariableExplorer?: boolean; variableExplorerExclude?: string; liveShareConnectionTimeout?: number; decorateCells?: boolean; enableCellCodeLens?: boolean; } export const IConfigurationService = Symbol('IConfigurationService'); export interface IConfigurationService { getSettings(resource?: Uri): IPythonSettings; isTestExecution(): boolean; updateSetting(setting: string, value?: {}, resource?: Uri, configTarget?: ConfigurationTarget): Promise<void>; updateSectionSetting(section: string, setting: string, value?: {}, resource?: Uri, configTarget?: ConfigurationTarget): Promise<void>; } export const ISocketServer = Symbol('ISocketServer'); export interface ISocketServer extends Disposable { readonly client: Promise<Socket>; Start(options?: { port?: number; host?: string }): Promise<number>; } export const IExtensionContext = Symbol('ExtensionContext'); export interface IExtensionContext extends ExtensionContext { } export const IExtensions = Symbol('IExtensions'); export interface IExtensions { /** * All extensions currently known to the system. */ // tslint:disable-next-line:no-any readonly all: Extension<any>[]; /** * Get an extension by its full identifier in the form of: `publisher.name`. * * @param extensionId An extension identifier. * @return An extension or `undefined`. */ // tslint:disable-next-line:no-any getExtension(extensionId: string): Extension<any> | undefined; /** * Get an extension its full identifier in the form of: `publisher.name`. * * @param extensionId An extension identifier. * @return An extension or `undefined`. */ getExtension<T>(extensionId: string): Extension<T> | undefined; } export const IBrowserService = Symbol('IBrowserService'); export interface IBrowserService { launch(url: string): void; } export const IPythonExtensionBanner = Symbol('IPythonExtensionBanner'); export interface IPythonExtensionBanner { readonly enabled: boolean; showBanner(): Promise<void>; } export const BANNER_NAME_LS_SURVEY: string = 'LSSurveyBanner'; export const BANNER_NAME_PROPOSE_LS: string = 'ProposeLS'; export const BANNER_NAME_DS_SURVEY: string = 'DSSurveyBanner'; export const BANNER_NAME_INTERACTIVE_SHIFTENTER: string = 'InteractiveShiftEnterBanner'; export type DeprecatedSettingAndValue = { setting: string; values?: {}[]; }; export const IEditorUtils = Symbol('IEditorUtils'); export interface IEditorUtils { getWorkspaceEditsFromPatch(originalContents: string, patch: string, uri: Uri): WorkspaceEdit; } export interface IDisposable { dispose(): void | undefined; } export interface IAsyncDisposable { dispose(): Promise<void>; } export const IAsyncDisposableRegistry = Symbol('IAsyncDisposableRegistry'); export interface IAsyncDisposableRegistry extends IAsyncDisposable { push(disposable: IDisposable | IAsyncDisposable): void; }
the_stack
import Common, { Chain, Hardfork } from '@ethereumjs/common' import { Address, BN, toBuffer, MAX_INTEGER, TWO_POW256, unpadBuffer, ecsign, publicToAddress, BNLike, } from 'ethereumjs-util' import { TxData, JsonTx, AccessListEIP2930ValuesArray, AccessListEIP2930TxData, FeeMarketEIP1559ValuesArray, FeeMarketEIP1559TxData, TxValuesArray, Capability, } from './types' interface TransactionCache { hash: Buffer | undefined } /** * This base class will likely be subject to further * refactoring along the introduction of additional tx types * on the Ethereum network. * * It is therefore not recommended to use directly. */ export abstract class BaseTransaction<TransactionObject> { private readonly _type: number public readonly nonce: BN public readonly gasLimit: BN public readonly to?: Address public readonly value: BN public readonly data: Buffer public readonly v?: BN public readonly r?: BN public readonly s?: BN public readonly common!: Common protected cache: TransactionCache = { hash: undefined, } /** * List of tx type defining EIPs, * e.g. 1559 (fee market) and 2930 (access lists) * for FeeMarketEIP1559Transaction objects */ protected activeCapabilities: number[] = [] /** * The default chain the tx falls back to if no Common * is provided and if the chain can't be derived from * a passed in chainId (only EIP-2718 typed txs) or * EIP-155 signature (legacy txs). * * @hidden */ protected DEFAULT_CHAIN = Chain.Mainnet /** * The default HF if the tx type is active on that HF * or the first greater HF where the tx is active. * * @hidden */ protected DEFAULT_HARDFORK: string | Hardfork = Hardfork.Istanbul constructor(txData: TxData | AccessListEIP2930TxData | FeeMarketEIP1559TxData) { const { nonce, gasLimit, to, value, data, v, r, s, type } = txData this._type = new BN(toBuffer(type)).toNumber() const toB = toBuffer(to === '' ? '0x' : to) const vB = toBuffer(v === '' ? '0x' : v) const rB = toBuffer(r === '' ? '0x' : r) const sB = toBuffer(s === '' ? '0x' : s) this.nonce = new BN(toBuffer(nonce === '' ? '0x' : nonce)) this.gasLimit = new BN(toBuffer(gasLimit === '' ? '0x' : gasLimit)) this.to = toB.length > 0 ? new Address(toB) : undefined this.value = new BN(toBuffer(value === '' ? '0x' : value)) this.data = toBuffer(data === '' ? '0x' : data) this.v = vB.length > 0 ? new BN(vB) : undefined this.r = rB.length > 0 ? new BN(rB) : undefined this.s = sB.length > 0 ? new BN(sB) : undefined this._validateCannotExceedMaxInteger({ nonce: this.nonce, gasLimit: this.gasLimit, value: this.value, r: this.r, s: this.s, }) } /** * Alias for {@link BaseTransaction.type} * * @deprecated Use `type` instead */ get transactionType(): number { return this.type } /** * Returns the transaction type. * * Note: legacy txs will return tx type `0`. */ get type() { return this._type } /** * Checks if a tx type defining capability is active * on a tx, for example the EIP-1559 fee market mechanism * or the EIP-2930 access list feature. * * Note that this is different from the tx type itself, * so EIP-2930 access lists can very well be active * on an EIP-1559 tx for example. * * This method can be useful for feature checks if the * tx type is unknown (e.g. when instantiated with * the tx factory). * * See `Capabilites` in the `types` module for a reference * on all supported capabilities. */ supports(capability: Capability) { return this.activeCapabilities.includes(capability) } /** * Checks if the transaction has the minimum amount of gas required * (DataFee + TxFee + Creation Fee). */ validate(): boolean validate(stringError: false): boolean validate(stringError: true): string[] validate(stringError: boolean = false): boolean | string[] { const errors = [] if (this.getBaseFee().gt(this.gasLimit)) { errors.push(`gasLimit is too low. given ${this.gasLimit}, need at least ${this.getBaseFee()}`) } if (this.isSigned() && !this.verifySignature()) { errors.push('Invalid Signature') } return stringError ? errors : errors.length === 0 } /** * The minimum amount of gas the tx must have (DataFee + TxFee + Creation Fee) */ getBaseFee(): BN { const fee = this.getDataFee().addn(this.common.param('gasPrices', 'tx')) if (this.common.gteHardfork('homestead') && this.toCreationAddress()) { fee.iaddn(this.common.param('gasPrices', 'txCreation')) } return fee } /** * The amount of gas paid for the data in this tx */ getDataFee(): BN { const txDataZero = this.common.param('gasPrices', 'txDataZero') const txDataNonZero = this.common.param('gasPrices', 'txDataNonZero') let cost = 0 for (let i = 0; i < this.data.length; i++) { this.data[i] === 0 ? (cost += txDataZero) : (cost += txDataNonZero) } return new BN(cost) } /** * The up front amount that an account must have for this transaction to be valid */ abstract getUpfrontCost(): BN /** * If the tx's `to` is to the creation address */ toCreationAddress(): boolean { return this.to === undefined || this.to.buf.length === 0 } /** * Returns a Buffer Array of the raw Buffers of this transaction, in order. * * Use {@link BaseTransaction.serialize} to add a transaction to a block * with {@link Block.fromValuesArray}. * * For an unsigned tx this method uses the empty Buffer values for the * signature parameters `v`, `r` and `s` for encoding. For an EIP-155 compliant * representation for external signing use {@link BaseTransaction.getMessageToSign}. */ abstract raw(): TxValuesArray | AccessListEIP2930ValuesArray | FeeMarketEIP1559ValuesArray /** * Returns the encoding of the transaction. */ abstract serialize(): Buffer // Returns the unsigned tx (hashed or raw), which is used to sign the transaction. // // Note: do not use code docs here since VS Studio is then not able to detect the // comments from the inherited methods abstract getMessageToSign(hashMessage: false): Buffer | Buffer[] abstract getMessageToSign(hashMessage?: true): Buffer abstract hash(): Buffer abstract getMessageToVerifySignature(): Buffer public isSigned(): boolean { const { v, r, s } = this if (this.type === 0) { if (!v || !r || !s) { return false } else { return true } } else { if (v === undefined || !r || !s) { return false } else { return true } } } /** * Determines if the signature is valid */ verifySignature(): boolean { try { // Main signature verification is done in `getSenderPublicKey()` const publicKey = this.getSenderPublicKey() return unpadBuffer(publicKey).length !== 0 } catch (e: any) { return false } } /** * Returns the sender's address */ getSenderAddress(): Address { return new Address(publicToAddress(this.getSenderPublicKey())) } /** * Returns the public key of the sender */ abstract getSenderPublicKey(): Buffer /** * Signs a transaction. * * Note that the signed tx is returned as a new object, * use as follows: * ```javascript * const signedTx = tx.sign(privateKey) * ``` */ sign(privateKey: Buffer): TransactionObject { if (privateKey.length !== 32) { throw new Error('Private key must be 32 bytes in length.') } // Hack for the constellation that we have got a legacy tx after spuriousDragon with a non-EIP155 conforming signature // and want to recreate a signature (where EIP155 should be applied) // Leaving this hack lets the legacy.spec.ts -> sign(), verifySignature() test fail // 2021-06-23 let hackApplied = false if ( this.type === 0 && this.common.gteHardfork('spuriousDragon') && !this.supports(Capability.EIP155ReplayProtection) ) { this.activeCapabilities.push(Capability.EIP155ReplayProtection) hackApplied = true } const msgHash = this.getMessageToSign(true) const { v, r, s } = ecsign(msgHash, privateKey) const tx = this._processSignature(v, r, s) // Hack part 2 if (hackApplied) { const index = this.activeCapabilities.indexOf(Capability.EIP155ReplayProtection) if (index > -1) { this.activeCapabilities.splice(index, 1) } } return tx } /** * Returns an object with the JSON representation of the transaction */ abstract toJSON(): JsonTx // Accept the v,r,s values from the `sign` method, and convert this into a TransactionObject protected abstract _processSignature(v: number, r: Buffer, s: Buffer): TransactionObject /** * Does chain ID checks on common and returns a common * to be used on instantiation * @hidden * * @param common - {@link Common} instance from tx options * @param chainId - Chain ID from tx options (typed txs) or signature (legacy tx) */ protected _getCommon(common?: Common, chainId?: BNLike) { // Chain ID provided if (chainId) { const chainIdBN = new BN(toBuffer(chainId)) if (common) { if (!common.chainIdBN().eq(chainIdBN)) { throw new Error('The chain ID does not match the chain ID of Common') } // Common provided, chain ID does match // -> Return provided Common return common.copy() } else { if (Common.isSupportedChainId(chainIdBN)) { // No Common, chain ID supported by Common // -> Instantiate Common with chain ID return new Common({ chain: chainIdBN, hardfork: this.DEFAULT_HARDFORK }) } else { // No Common, chain ID not supported by Common // -> Instantiate custom Common derived from DEFAULT_CHAIN return Common.forCustomChain( this.DEFAULT_CHAIN, { name: 'custom-chain', networkId: chainIdBN, chainId: chainIdBN, }, this.DEFAULT_HARDFORK ) } } } else { // No chain ID provided // -> return Common provided or create new default Common return ( common?.copy() ?? new Common({ chain: this.DEFAULT_CHAIN, hardfork: this.DEFAULT_HARDFORK }) ) } } protected _validateCannotExceedMaxInteger(values: { [key: string]: BN | undefined }, bits = 53) { for (const [key, value] of Object.entries(values)) { if (bits === 53) { if (value?.gt(MAX_INTEGER)) { throw new Error(`${key} cannot exceed MAX_INTEGER, given ${value}`) } } else if (bits === 256) { if (value?.gte(TWO_POW256)) { throw new Error(`${key} must be less than 2^256, given ${value}`) } } else { throw new Error('unimplemented bits value') } } } }
the_stack
declare module "*.svelte" { export default Svelte2TsxComponent; } interface IComponentOptions { target: Element; anchor?: Element; props?: Props; context?: Map<any, any>; hydrate?: boolean; intro?: boolean; $$inline?: boolean; } declare type Props = Record<string, any>; declare class SvelteComponentDev extends SvelteComponent { /** * @private * For type checking capabilities only. * Does not exist at runtime. * ### DO NOT USE! */ $$prop_def: Props; /** * @private * For type checking capabilities only. * Does not exist at runtime. * ### DO NOT USE! */ $$events_def: any; /** * @private * For type checking capabilities only. * Does not exist at runtime. * ### DO NOT USE! */ $$slot_def: any; constructor(options: IComponentOptions); $capture_state(): void; $inject_state(): void; } declare class SvelteComponentTyped< Props extends Record<string, any> = any, Events extends Record<string, any> = any, Slots extends Record<string, any> = any > extends SvelteComponentDev { /** * @private * For type checking capabilities only. * Does not exist at runtime. * ### DO NOT USE! */ $$prop_def: Props; /** * @private * For type checking capabilities only. * Does not exist at runtime. * ### DO NOT USE! */ $$events_def: Events; /** * @private * For type checking capabilities only. * Does not exist at runtime. * ### DO NOT USE! */ $$slot_def: Slots; constructor(options: IComponentOptions); } interface Fragment { key: string | null; first: null; c: () => void; l: (nodes: any) => void; h: () => void; m: (target: HTMLElement, anchor: any) => void; p: (ctx: any, dirty: any) => void; r: () => void; f: () => void; a: () => void; i: (local: any) => void; o: (local: any) => void; d: (detaching: 0 | 1) => void; } interface T$$ { dirty: number[]; ctx: null | any; bound: any; update: () => void; callbacks: any; after_update: any[]; props: Record<string, 0 | string>; fragment: null | false | Fragment; not_equal: any; before_update: any[]; context: Map<any, any>; on_mount: any[]; on_destroy: any[]; skip_bound: boolean; on_disconnect: any[]; } declare class SvelteComponent { $$: T$$; $$set?: ($$props: any) => void; $destroy(): void; $on(type: any, callback: any): () => void; $set($$props: any): void; } declare class Svelte2TsxComponent< Props extends {} = {}, Events extends {} = {}, Slots extends {} = {} > { // svelte2tsx-specific /** * @internal This is for type checking capabilities only * and does not exist at runtime. Don't use this property. */ $$prop_def: Props; /** * @internal This is for type checking capabilities only * and does not exist at runtime. Don't use this property. */ $$events_def: Events; /** * @internal This is for type checking capabilities only * and does not exist at runtime. Don't use this property. */ $$slot_def: Slots; // https://svelte.dev/docs#Client-side_component_API constructor(options: Svelte2TsxComponentConstructorParameters<Props>); /** * Causes the callback function to be called whenever the component dispatches an event. * A function is returned that will remove the event listener when called. */ $on<K extends keyof Events & string>( event: K, handler: (e: Events[K]) => any ): () => void; /** * Removes a component from the DOM and triggers any `onDestroy` handlers. */ $destroy(): void; /** * Programmatically sets props on an instance. * `component.$set({ x: 1 })` is equivalent to `x = 1` inside the component's `<script>` block. * Calling this method schedules an update for the next microtask — the DOM is __not__ updated synchronously. */ $set(props?: Partial<Props>): void; // From SvelteComponent(Dev) definition $$: any; $capture_state(): void; $inject_state(): void; } interface Svelte2TsxComponentConstructorParameters<Props extends {}> { /** * An HTMLElement to render to. This option is required. */ target: Element; /** * A child of `target` to render the component immediately before. */ anchor?: Element; /** * An object of properties to supply to the component. */ props?: Props; hydrate?: boolean; intro?: boolean; $$inline?: boolean; } type AConstructorTypeOf<T, U extends any[] = any[]> = new (...args: U) => T; type SvelteComponentConstructor< T, U extends Svelte2TsxComponentConstructorParameters<any> > = new (options: U) => T; type SvelteActionReturnType = { update?: (args: any) => void; destroy?: () => void; } | void; type SvelteTransitionConfig = { delay?: number; duration?: number; easing?: (t: number) => number; css?: (t: number, u: number) => string; tick?: (t: number, u: number) => void; }; type SvelteTransitionReturnType = | SvelteTransitionConfig | (() => SvelteTransitionConfig); type SvelteAnimationReturnType = { delay?: number; duration?: number; easing?: (t: number) => number; css?: (t: number, u: number) => string; tick?: (t: number, u: number) => void; }; type SvelteWithOptionalProps<Props, Keys extends keyof Props> = Omit< Props, Keys > & Partial<Pick<Props, Keys>>; type SvelteAllProps = { [index: string]: any }; type SveltePropsAnyFallback<Props> = { [K in keyof Props]: Props[K] extends undefined ? any : Props[K]; }; type SvelteRestProps = { [index: string]: any }; type SvelteSlots = { [index: string]: any }; type SvelteStore<T> = { subscribe: (run: (value: T) => any, invalidate?: any) => any; }; // Forces TypeScript to look into the type which results in a better representation of it // which helps for error messages type Expand<T> = T extends infer O ? { [K in keyof O]: O[K] } : never; declare var process: Record<string, string> & { browser: boolean }; declare var __sveltets_AnimationMove: { from: DOMRect; to: DOMRect }; declare function __sveltets_ensureAnimation( animationCall: SvelteAnimationReturnType ): {}; declare function __sveltets_ensureAction( actionCall: SvelteActionReturnType ): {}; declare function __sveltets_ensureTransition( transitionCall: SvelteTransitionReturnType ): {}; declare function __sveltets_ensureFunction( expression: (e: Event & { detail?: any }) => unknown ): {}; declare function __sveltets_ensureType<T>( type: AConstructorTypeOf<T>, el: T ): {}; declare function __sveltets_cssProp(prop: Record<string, any>): {}; declare function __sveltets_ctorOf<T>(type: T): AConstructorTypeOf<T>; declare function __sveltets_instanceOf<T = any>(type: AConstructorTypeOf<T>): T; declare function __sveltets_allPropsType(): SvelteAllProps; declare function __sveltets_restPropsType(): SvelteRestProps; declare function __sveltets_slotsType<Slots, Key extends keyof Slots>( slots: Slots ): Record<Key, boolean>; // Overload of the following two functions is necessary. // An empty array of optionalProps makes OptionalProps type any, which means we lose the prop typing. // optionalProps need to be first or its type cannot be infered correctly. declare function __sveltets_partial< Props = {}, Events = {}, Slots = {} >(render: { props?: Props; events?: Events; slots?: Slots; }): { props?: SveltePropsAnyFallback<Props>; events?: Events; slots?: Slots }; declare function __sveltets_partial< Props = {}, Events = {}, Slots = {}, OptionalProps extends keyof Props = any >( optionalProps: OptionalProps[], render: { props?: Props; events?: Events; slots?: Slots } ): { props?: Expand< SvelteWithOptionalProps<SveltePropsAnyFallback<Props>, OptionalProps> >; events?: Events; slots?: Slots; }; declare function __sveltets_partial_with_any< Props = {}, Events = {}, Slots = {} >(render: { props?: Props; events?: Events; slots?: Slots; }): { props?: SveltePropsAnyFallback<Props> & SvelteAllProps; events?: Events; slots?: Slots; }; declare function __sveltets_partial_with_any< Props = {}, Events = {}, Slots = {}, OptionalProps extends keyof Props = any >( optionalProps: OptionalProps[], render: { props?: Props; events?: Events; slots?: Slots } ): { props?: Expand< SvelteWithOptionalProps<SveltePropsAnyFallback<Props>, OptionalProps> > & SvelteAllProps; events?: Events; slots?: Slots; }; declare function __sveltets_with_any< Props = {}, Events = {}, Slots = {} >(render: { props?: Props; events?: Events; slots?: Slots; }): { props?: Props & SvelteAllProps; events?: Events; slots?: Slots }; declare function __sveltets_with_any_event< Props = {}, Events = {}, Slots = {} >(render: { props?: Props; events?: Events; slots?: Slots; }): { props?: Props; events?: Events & { [evt: string]: CustomEvent<any> }; slots?: Slots; }; declare function __sveltets_store_get<T = any>(store: SvelteStore<T>): T; declare function __sveltets_any(dummy: any): any; declare function __sveltets_empty(dummy: any): {}; declare function __sveltets_componentType(): AConstructorTypeOf< Svelte2TsxComponent<any, any, any> >; declare function __sveltets_invalidate<T>(getValue: () => T): T; declare function __sveltets_mapWindowEvent< K extends keyof HTMLBodyElementEventMap >(event: K): HTMLBodyElementEventMap[K]; declare function __sveltets_mapBodyEvent<K extends keyof WindowEventMap>( event: K ): WindowEventMap[K]; declare function __sveltets_mapElementEvent< K extends keyof HTMLElementEventMap >(event: K): HTMLElementEventMap[K]; declare function __sveltets_mapElementTag<K extends keyof ElementTagNameMap>( tag: K ): ElementTagNameMap[K]; declare function __sveltets_mapElementTag<K extends keyof SVGElementTagNameMap>( tag: K ): SVGElementTagNameMap[K]; declare function __sveltets_mapElementTag(tag: any): HTMLElement; declare function __sveltets_bubbleEventDef<Events, K extends keyof Events>( events: Events, eventKey: K ): Events[K]; declare function __sveltets_bubbleEventDef(events: any, eventKey: string): any; declare const __sveltets_customEvent: CustomEvent<any>; declare function __sveltets_toEventTypings<Typings>(): { [Key in keyof Typings]: CustomEvent<Typings[Key]>; }; declare function __sveltets_unionType<T1, T2>(t1: T1, t2: T2): T1 | T2; declare function __sveltets_unionType<T1, T2, T3>( t1: T1, t2: T2, t3: T3 ): T1 | T2 | T3; declare function __sveltets_unionType<T1, T2, T3, T4>( t1: T1, t2: T2, t3: T3, t4: T4 ): T1 | T2 | T3 | T4; declare function __sveltets_unionType(...types: any[]): any; declare function __sveltets_awaitThen<T>( promise: T, onfulfilled: (value: T extends PromiseLike<infer U> ? U : T) => any, onrejected?: (value: T extends PromiseLike<any> ? any : never) => any ): any; declare function __sveltets_each<T>( array: ArrayLike<T>, callbackfn: (value: T, index: number) => any ): any; declare function createSvelte2TsxComponent<Props, Events, Slots>(render: { props?: Props; events?: Events; slots?: Slots; }): SvelteComponentConstructor< Svelte2TsxComponent<Props, Events, Slots>, Svelte2TsxComponentConstructorParameters<Props> >; declare function __sveltets_unwrapArr<T>(arr: ArrayLike<T>): T; declare function __sveltets_unwrapPromiseLike<T>( promise: PromiseLike<T> | T ): T; interface RouteProps { path?: string; component?: typeof SvelteComponent; [additionalProp: string]: unknown; } interface RouteSlots { default: { location: RouteLocation; params: RouteParams; }; } interface RouteLocation { pathname: string; search: string; hash?: string; state: { [k in string | number]: unknown; }; } interface RouteParams { [param: string]: string; } interface LinkProps { to: string; replace?: boolean; state?: { [k in string | number]: unknown; }; getProps?: (linkParams: GetPropsParams) => Record<string, any>; } interface GetPropsParams { location: RouteLocation; href: string; isPartiallyCurrent: boolean; isCurrent: boolean; } interface RouterProps { basepath?: string; url?: string; } declare module "svelte" { export function beforeUpdate(fn: () => any): void; export function onMount(fn: () => any): void; export function afterUpdate(fn: () => any): void; export function onDestroy(fn: () => any): void; export function createEventDispatcher<EventMap extends {} = any>(): < EventKey extends Extract<keyof EventMap, string> >( type: EventKey, detail?: EventMap[EventKey] ) => void; export function setContext<T>(key: any, context: T): void; export function getContext<T>(key: any): T; export function tick(): Promise<void>; } declare module "svelte/store" { export type Subscriber<T> = (value: T) => void; /** Unsubscribes from value updates. */ export type Unsubscriber = () => void; /** Callback to update a value. */ export type Updater<T> = (value: T) => T; /** Cleanup logic callback. */ type Invalidator<T> = (value?: T) => void; /** Start and stop notification callbacks. */ export type StartStopNotifier<T> = ( set: Subscriber<T> ) => Unsubscriber | void; /** Readable interface for subscribing. */ export interface Readable<T> { /** * Subscribe on value changes. * @param run subscription callback * @param invalidate cleanup callback */ subscribe( this: void, run: Subscriber<T>, invalidate?: Invalidator<T> ): Unsubscriber; } /** Writable interface for both updating and subscribing. */ export interface Writable<T> extends Readable<T> { /** * Set value and inform subscribers. * @param value to set */ set(this: void, value: T): void; /** * Update value using callback and inform subscribers. * @param updater callback */ update(this: void, updater: Updater<T>): void; } /** * Creates a `Readable` store that allows reading by subscription. * @param value initial value * @param {StartStopNotifier}start start and stop notifications for subscriptions */ export function readable<T>( value: T, start: StartStopNotifier<T> ): Readable<T>; /** * Create a `Writable` store that allows both updating and reading by subscription. * @param {*=}value initial value * @param {StartStopNotifier=}start start and stop notifications for subscriptions */ export function writable<T>( value: T, start?: StartStopNotifier<T> ): Writable<T>; /** One or more `Readable`s. */ type Stores = Readable<any> | [Readable<any>, ...Array<Readable<any>>]; /** One or more values from `Readable` stores. */ type StoresValues<T> = T extends Readable<infer U> ? U : { [K in keyof T]: T[K] extends Readable<infer U> ? U : never; }; /** * Derived value store by synchronizing one or more readable stores and * applying an aggregation function over its input values. * * @param stores - input stores * @param fn - function callback that aggregates the values * @param initial_value - when used asynchronously */ export function derived<S extends Stores, T>( stores: S, fn: ( values: StoresValues<S>, set: (value: T) => void ) => Unsubscriber | void, initial_value?: T ): Readable<T>; /** * Derived value store by synchronizing one or more readable stores and * applying an aggregation function over its input values. * * @param stores - input stores * @param fn - function callback that aggregates the values * @param initial_value - initial value */ export function derived<S extends Stores, T>( stores: S, fn: (values: StoresValues<S>) => T, initial_value?: T ): Readable<T>; /** * Derived value store by synchronizing one or more readable stores and * applying an aggregation function over its input values. * * @param stores - input stores * @param fn - function callback that aggregates the values */ export function derived<S extends Stores, T>( stores: S, fn: (values: StoresValues<S>) => T ): Readable<T>; /** * Get the current value from a store by subscribing and immediately unsubscribing. * @param store readable */ } declare module "svelte/transition" { export type EasingFunction = (t: number) => number; export interface TransitionConfig { delay?: number; duration?: number; easing?: EasingFunction; css?: (t: number, u: number) => string; tick?: (t: number, u: number) => void; } export interface BlurParams { delay?: number; duration?: number; easing?: EasingFunction; amount?: number; opacity?: number; } export function blur( node: Element, { delay, duration, easing, amount, opacity }?: BlurParams ): TransitionConfig; export interface FadeParams { delay?: number; duration?: number; easing?: EasingFunction; } export function fade( node: Element, { delay, duration, easing }?: FadeParams ): TransitionConfig; export interface FlyParams { delay?: number; duration?: number; easing?: EasingFunction; x?: number; y?: number; opacity?: number; } export function fly( node: Element, { delay, duration, easing, x, y, opacity }?: FlyParams ): TransitionConfig; export interface SlideParams { delay?: number; duration?: number; easing?: EasingFunction; } export function slide( node: Element, { delay, duration, easing }?: SlideParams ): TransitionConfig; export interface ScaleParams { delay?: number; duration?: number; easing?: EasingFunction; start?: number; opacity?: number; } export function scale( node: Element, { delay, duration, easing, start, opacity }?: ScaleParams ): TransitionConfig; export interface DrawParams { delay?: number; speed?: number; duration?: number | ((len: number) => number); easing?: EasingFunction; } export function draw( node: SVGElement & { getTotalLength(): number; }, { delay, speed, duration, easing }?: DrawParams ): TransitionConfig; export interface CrossfadeParams { delay?: number; duration?: number | ((len: number) => number); easing?: EasingFunction; } export function crossfade({ fallback, ...defaults }: CrossfadeParams & { fallback?: ( node: Element, params: CrossfadeParams, intro: boolean ) => TransitionConfig; }): Array< ( node: Element, params: CrossfadeParams & { key: any; } ) => () => TransitionConfig >; } declare module "svelte/easing" { export function backInOut(t: number): number; export function backIn(t: number): number; export function backOut(t: number): number; export function bounceOut(t: number): number; export function bounceInOut(t: number): number; export function bounceIn(t: number): number; export function circInOut(t: number): number; export function circIn(t: number): number; export function circOut(t: number): number; export function cubicInOut(t: number): number; export function cubicIn(t: number): number; export function cubicOut(t: number): number; export function elasticInOut(t: number): number; export function elasticIn(t: number): number; export function elasticOut(t: number): number; export function expoInOut(t: number): number; export function expoIn(t: number): number; export function expoOut(t: number): number; export function quadInOut(t: number): number; export function quadIn(t: number): number; export function quadOut(t: number): number; export function quartInOut(t: number): number; export function quartIn(t: number): number; export function quartOut(t: number): number; export function quintInOut(t: number): number; export function quintIn(t: number): number; export function quintOut(t: number): number; export function sineInOut(t: number): number; export function sineIn(t: number): number; export function sineOut(t: number): number; } declare module "svelte/animate" { export interface AnimationConfig { delay?: number; duration?: number; easing?: (t: number) => number; css?: (t: number, u: number) => string; tick?: (t: number, u: number) => void; } interface FlipParams { delay?: number; duration?: number | ((len: number) => number); easing?: (t: number) => number; } export function flip( node: Element, animation: { from: DOMRect; to: DOMRect; }, params?: FlipParams ): AnimationConfig; } declare module "svelte-routing" { export const navigate: ( to: string, { replace, state, }?: { replace?: boolean; state?: { [k in string | number]: unknown; }; } ) => void; export const link: (node: Element) => { destroy(): void }; export const links: (node: Element) => { destroy(): void }; } declare module "svelte-routing/Link.svelte" { export default class Link extends SvelteComponentTyped<LinkProps> {} } declare module "svelte-routing/Route.svelte" { export default class Route extends SvelteComponentTyped< RouteProps, Record<string, any>, RouteSlots > {} } declare module "svelte-routing/Router.svelte" { export default class Router extends SvelteComponentTyped<RouterProps> {} } declare module "snel" { interface Env { Get(env: string): string | undefined; Delete(env: string): void; Set(env: string, value: string): void; GetAsObject(): { [index: string]: string }; } interface ICore { /** * manage env variables in snel */ Env: Env; /** * Match route from path name. */ MatchRoute(path: string, route: string): Boolean; /** * get params from request object */ GetParams<P extends object = object>( path: string, route: string ): | { path: string; index: number; params: P; } | false; /** * Normalize a pathname for matching, replaces multiple slashes with a single * slash and normalizes unicode characters to "NFC". When using this method, * `decode` should be an identity function so you don't decode strings twice. */ NormalizePathName(path: string): string; } const Core: ICore; export { Core }; }
the_stack
// clang-format off import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js'; import {flush} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; import {ContentSetting, ContentSettingsTypes, SettingsCookiesPageElement, SiteSettingsPrefsBrowserProxyImpl} from 'chrome://settings/lazy_load.js'; import {CrLinkRowElement, MetricsBrowserProxyImpl, PrivacyElementInteractions, Router, routes} from 'chrome://settings/settings.js'; import {assertEquals, assertFalse, assertTrue} from 'chrome://webui-test/chai_assert.js'; import {flushTasks, isChildVisible} from 'chrome://webui-test/test_util.js'; import {TestMetricsBrowserProxy} from './test_metrics_browser_proxy.js'; import {TestSiteSettingsPrefsBrowserProxy} from './test_site_settings_prefs_browser_proxy.js'; import {createContentSettingTypeToValuePair, createRawSiteException, createSiteSettingsPrefs} from './test_util.js'; // clang-format on suite('CrSettingsCookiesPageTest', function() { let siteSettingsBrowserProxy: TestSiteSettingsPrefsBrowserProxy; let testMetricsBrowserProxy: TestMetricsBrowserProxy; let page: SettingsCookiesPageElement; suiteSetup(function() { loadTimeData.overrideValues({ consolidatedSiteStorageControlsEnabled: false, }); const routes: any = Router.getInstance().getRoutes(); routes.SITE_SETTINGS_SITE_DATA = routes.COOKIES.createChild('/siteData'); routes.SITE_SETTINGS_DATA_DETAILS = routes.SITE_SETTINGS_SITE_DATA.createChild('/cookies/detail'); Router.resetInstanceForTesting(new Router(routes)); }); setup(function() { testMetricsBrowserProxy = new TestMetricsBrowserProxy(); MetricsBrowserProxyImpl.setInstance(testMetricsBrowserProxy); siteSettingsBrowserProxy = new TestSiteSettingsPrefsBrowserProxy(); SiteSettingsPrefsBrowserProxyImpl.setInstance(siteSettingsBrowserProxy); document.body.innerHTML = ''; page = document.createElement('settings-cookies-page'); page.prefs = { generated: { cookie_session_only: {value: false}, cookie_primary_setting: {type: chrome.settingsPrivate.PrefType.NUMBER, value: 0}, }, privacy_sandbox: { apis_enabled: {value: true}, } }; document.body.appendChild(page); flush(); }); teardown(function() { page.remove(); Router.getInstance().resetRouteForTesting(); }); test('ElementVisibility', async function() { await flushTasks(); assertTrue(isChildVisible(page, '#exceptionHeader')); assertTrue(isChildVisible(page, '#clearOnExit')); assertTrue(isChildVisible(page, '#doNotTrack')); assertTrue(isChildVisible(page, '#networkPrediction')); assertTrue(isChildVisible(page, '#blockThirdPartyIncognito')); }); test('NetworkPredictionClickRecorded', async function() { page.shadowRoot!.querySelector<HTMLElement>('#networkPrediction')!.click(); const result = await testMetricsBrowserProxy.whenCalled('recordSettingsPageHistogram'); assertEquals(PrivacyElementInteractions.NETWORK_PREDICTION, result); }); test('CookiesRadioClicksRecorded', async function() { page.$.blockAll.click(); let result = await testMetricsBrowserProxy.whenCalled('recordSettingsPageHistogram'); assertEquals(PrivacyElementInteractions.COOKIES_BLOCK, result); testMetricsBrowserProxy.reset(); page.$.blockThirdParty.click(); result = await testMetricsBrowserProxy.whenCalled('recordSettingsPageHistogram'); assertEquals(PrivacyElementInteractions.COOKIES_THIRD, result); testMetricsBrowserProxy.reset(); page.$.blockThirdPartyIncognito.click(); result = await testMetricsBrowserProxy.whenCalled('recordSettingsPageHistogram'); assertEquals(PrivacyElementInteractions.COOKIES_INCOGNITO, result); testMetricsBrowserProxy.reset(); page.$.allowAll.click(); result = await testMetricsBrowserProxy.whenCalled('recordSettingsPageHistogram'); assertEquals(PrivacyElementInteractions.COOKIES_ALL, result); testMetricsBrowserProxy.reset(); }); test('CookiesSessionOnlyClickRecorded', async function() { page.shadowRoot!.querySelector<HTMLElement>('#clearOnExit')!.click(); const result = await testMetricsBrowserProxy.whenCalled('recordSettingsPageHistogram'); assertEquals(PrivacyElementInteractions.COOKIES_SESSION, result); }); test('CookieSettingExceptions_Search', async function() { const exceptionPrefs = createSiteSettingsPrefs([], [ createContentSettingTypeToValuePair( ContentSettingsTypes.COOKIES, [ createRawSiteException('http://foo-block.com', { embeddingOrigin: '', setting: ContentSetting.BLOCK, }), createRawSiteException('http://foo-allow.com', { embeddingOrigin: '', }), createRawSiteException('http://foo-session.com', { embeddingOrigin: '', setting: ContentSetting.SESSION_ONLY, }), ]), ]); page.searchTerm = 'foo'; siteSettingsBrowserProxy.setPrefs(exceptionPrefs); await siteSettingsBrowserProxy.whenCalled('getExceptionList'); flush(); const exceptionLists = page.shadowRoot!.querySelectorAll('site-list'); assertEquals(exceptionLists.length, 3); for (const list of exceptionLists) { assertTrue(isChildVisible(list, 'site-list-entry')); } page.searchTerm = 'unrelated.com'; flush(); for (const list of exceptionLists) { assertFalse(isChildVisible(list, 'site-list-entry')); } }); test('ExceptionLists_ReadOnly', async function() { // Check all exception lists are read only when the session only preference // reports as managed. page.set('prefs.generated.cookie_session_only', { value: true, enforcement: chrome.settingsPrivate.Enforcement.ENFORCED, }); let exceptionLists = page.shadowRoot!.querySelectorAll('site-list'); assertEquals(exceptionLists.length, 3); for (const list of exceptionLists) { assertTrue(!!list.readOnlyList); } // Return preference to unmanaged state and check all exception lists // are no longer read only. page.set('prefs.generated.cookie_session_only', { value: true, }); exceptionLists = page.shadowRoot!.querySelectorAll('site-list'); assertEquals(exceptionLists.length, 3); for (const list of exceptionLists) { assertFalse(!!list.readOnlyList); } }); test('BlockAll_ManagementSource', async function() { // Test that controlledBy for the blockAll_ preference is set to // the same value as the generated.cookie_session_only preference. const blockAll = page.$.blockAll; page.set('prefs.generated.cookie_session_only', { value: true, enforcement: chrome.settingsPrivate.Enforcement.ENFORCED, controlledBy: chrome.settingsPrivate.ControlledBy.EXTENSION, }); flush(); assertEquals( blockAll.pref!.controlledBy, chrome.settingsPrivate.ControlledBy.EXTENSION); page.set('prefs.generated.cookie_session_only', { value: true, enforcement: chrome.settingsPrivate.Enforcement.ENFORCED, controlledBy: chrome.settingsPrivate.ControlledBy.DEVICE_POLICY }); assertEquals( blockAll.pref!.controlledBy, chrome.settingsPrivate.ControlledBy.DEVICE_POLICY); }); test('privacySandboxToast', async function() { assertFalse(page.$.toast.open); // Disabling all cookies should display the privacy sandbox toast. page.$.blockAll.click(); assertEquals( 'Settings.PrivacySandbox.Block3PCookies', await testMetricsBrowserProxy.whenCalled('recordAction')); testMetricsBrowserProxy.resetResolver('recordAction'); assertTrue(page.$.toast.open); // Clicking the toast link should be recorded in UMA and should dismiss // the toast. page.$.toast.querySelector('cr-button')!.click(); assertEquals( 'Settings.PrivacySandbox.OpenedFromCookiesPageToast', await testMetricsBrowserProxy.whenCalled('recordAction')); testMetricsBrowserProxy.resetResolver('recordAction'); assertFalse(page.$.toast.open); // Renabling 3P cookies for regular sessions should not display the toast. page.$.blockThirdPartyIncognito.click(); await flushTasks(); assertFalse(page.$.toast.open); assertEquals(0, testMetricsBrowserProxy.getCallCount('recordAction')); // The toast should not be displayed if the user has the privacy sandbox // APIs disabled. page.set('prefs.privacy_sandbox.apis_enabled.value', false); page.$.blockAll.click(); await flushTasks(); assertFalse(page.$.toast.open); assertEquals(0, testMetricsBrowserProxy.getCallCount('recordAction')); // Disabling only 3P cookies should display the toast. page.set('prefs.privacy_sandbox.apis_enabled.value', true); page.set('prefs.generated.cookie_primary_setting.value', 0); page.$.blockThirdParty.click(); assertEquals( 'Settings.PrivacySandbox.Block3PCookies', await testMetricsBrowserProxy.whenCalled('recordAction')); assertTrue(page.$.toast.open); // Reselecting a non-3P cookie blocking setting should hide the toast. page.$.allowAll.click(); await flushTasks(); assertFalse(page.$.toast.open); // Navigating away from the page should hide the toast, even if navigated // back to. page.$.blockAll.click(); await flushTasks(); assertTrue(page.$.toast.open); Router.getInstance().navigateTo(routes.BASIC); Router.getInstance().navigateTo(routes.COOKIES); await flushTasks(); assertFalse(page.$.toast.open); }); test('AllSiteDataLink_consolidatedControlsDisabled', function() { const siteDataLinkRow = page.shadowRoot!.querySelector<CrLinkRowElement>('#site-data-trigger')!; assertEquals(siteDataLinkRow.label, page.i18n('siteSettingsCookieLink')); siteDataLinkRow.click(); assertEquals( Router.getInstance().getCurrentRoute(), routes.SITE_SETTINGS_SITE_DATA); }); }); suite('CrSettingsCookiesPageTest_consolidatedControlsEnabled', function() { let siteSettingsBrowserProxy: TestSiteSettingsPrefsBrowserProxy; let testMetricsBrowserProxy: TestMetricsBrowserProxy; let page: SettingsCookiesPageElement; suiteSetup(function() { loadTimeData.overrideValues({ consolidatedSiteStorageControlsEnabled: true, }); }); setup(function() { testMetricsBrowserProxy = new TestMetricsBrowserProxy(); MetricsBrowserProxyImpl.setInstance(testMetricsBrowserProxy); siteSettingsBrowserProxy = new TestSiteSettingsPrefsBrowserProxy(); SiteSettingsPrefsBrowserProxyImpl.setInstance(siteSettingsBrowserProxy); document.body.innerHTML = ''; page = document.createElement('settings-cookies-page'); page.prefs = { generated: { cookie_session_only: {value: false}, cookie_primary_setting: {type: chrome.settingsPrivate.PrefType.NUMBER, value: 0}, }, privacy_sandbox: { apis_enabled: {value: true}, } }; document.body.appendChild(page); flush(); }); teardown(function() { page.remove(); Router.getInstance().resetRouteForTesting(); }); test('AllSiteDataLink_consolidatedControlsEnabled', function() { const siteDataLinkRow = page.shadowRoot!.querySelector<CrLinkRowElement>('#site-data-trigger')!; assertEquals(siteDataLinkRow.label, page.i18n('cookiePageAllSitesLink')); siteDataLinkRow.click(); assertEquals( Router.getInstance().getCurrentRoute(), routes.SITE_SETTINGS_ALL); }); });
the_stack
declare namespace AceAjax { export interface Delta { action: 'insert' | 'remove'; start: Position; end: Position; lines: string[]; } export interface EditorCommand { name?: string | undefined; bindKey?: string | { mac?: string | undefined, win?: string | undefined } | undefined; exec: (editor: Editor, args?: any) => void; readOnly?: boolean | undefined; } interface CommandMap { [name: string]: EditorCommand; } type execEventHandler = (obj: { editor: Editor, command: EditorCommand, args: any[] }) => void; type CommandLike = EditorCommand | ((editor: Editor) => void); export interface CommandManager { byName: CommandMap; commands: CommandMap; on(name: 'exec', callback: execEventHandler): Function; on(name: 'afterExec', callback: execEventHandler): Function; once(name: string, callback: Function): void; setDefaultHandler(name: string, callback: Function): void; removeDefaultHandler(name: string, callback: Function): void; on(name: string, callback: Function, capturing?: boolean): Function; addEventListener(name: string, callback: Function, capturing?: boolean): void; off(name: string, callback: Function): void; removeListener(name: string, callback: Function): void; removeEventListener(name: string, callback: Function): void; exec(command: string, editor: Editor, args: any): boolean; toggleRecording(editor: Editor): void; replay(editor: Editor): void; addCommand(command: EditorCommand): void; addCommands(commands: EditorCommand[]): void; removeCommand(command: EditorCommand | string, keepCommand?: boolean): void; removeCommands(command: EditorCommand[]): void; bindKey(key: string | { mac?: string | undefined, win?: string | undefined }, command: CommandLike, position?: number): void; bindKeys(keys: {[s: string]: Function}): void; parseKeys(keyPart: string): {key: string, hashId: number}; findKeyCommand(hashId: number, keyString: string): string | undefined; handleKeyboard(data: {}, hashId: number, keyString: string, keyCode: string | number): void | {command: string}; getStatusText(editor: Editor, data: {}): string; platform: string; } export interface Annotation { row?: number | undefined; column?: number | undefined; text: string; type: string; } export interface TokenInfo { type: string; value: string; index?: number | undefined; start?: number | undefined; } export interface Position { row: number; column: number; } export interface KeyboardHandler { handleKeyboard: Function; } export interface KeyBinding { setDefaultHandler(kb: KeyboardHandler): void; setKeyboardHandler(kb: KeyboardHandler): void; addKeyboardHandler(kb: KeyboardHandler, pos: number): void; removeKeyboardHandler(kb: KeyboardHandler): boolean; getKeyboardHandler(): KeyboardHandler; onCommandKey(e: any, hashId: number, keyCode: number): boolean; onTextInput(text: string): boolean; } export interface TextMode { getTokenizer(): Tokenizer; toggleCommentLines(state: any, session: IEditSession, startRow: number, endRow: number): void; toggleBlockComment(state: any, session: IEditSession, range: Range, cursor: Position): void; getNextLineIndent (state: any, line: string, tab: string): string; checkOutdent(state: any, line: string, input: string): boolean; autoOutdent(state: any, doc: Document, row: number): void; createWorker(session: IEditSession): any; createModeDelegates (mapping: { [key: string]: string }): void; transformAction(state: string, action: string, editor: Editor, session: IEditSession, text: string): any; getKeywords(append?: boolean): Array<string | RegExp>; getCompletions(state: string, session: IEditSession, pos: Position, prefix: string): Completion[]; } export interface OptionProvider { /** * Sets a Configuration Option **/ setOption(optionName: string, optionValue: any): void; /** * Sets Configuration Options **/ setOptions(keyValueTuples: { [key: string]: any }): void; /** * Get a Configuration Option **/ getOption(name: string): any; /** * Get Configuration Options **/ getOptions(optionNames?: string[] | { [key: string]: any }): { [key: string]: any }; } //////////////// /// Ace //////////////// /** * The main class required to set up an Ace instance in the browser. **/ export interface Ace { /** * Provides access to require in packed noconflict mode * @param moduleName **/ require(moduleName: string): any; /** * Embeds the Ace editor into the DOM, at the element provided by `el`. * @param el Either the id of an element, or the element itself **/ edit(el: string): Editor; /** * Embeds the Ace editor into the DOM, at the element provided by `el`. * @param el Either the id of an element, or the element itself **/ edit(el: HTMLElement): Editor; /** * Creates a new [[EditSession]], and returns the associated [[Document]]. * @param text {:textParam} * @param mode {:modeParam} **/ createEditSession(text: Document, mode: TextMode): IEditSession; /** * Creates a new [[EditSession]], and returns the associated [[Document]]. * @param text {:textParam} * @param mode {:modeParam} **/ createEditSession(text: string, mode: TextMode): IEditSession; } //////////////// /// Anchor //////////////// /** * Defines the floating pointer in the document. Whenever text is inserted or deleted before the cursor, the position of the cursor is updated. **/ export interface Anchor { on(event: string, fn: (e: any) => any): void; /** * Returns an object identifying the `row` and `column` position of the current anchor. **/ getPosition(): Position; /** * Returns the current document. **/ getDocument(): Document; /** * Fires whenever the anchor position changes. * Both of these objects have a `row` and `column` property corresponding to the position. * Events that can trigger this function include [[Anchor.setPosition `setPosition()`]]. * @param e An object containing information about the anchor position. It has two properties: * - `old`: An object describing the old Anchor position * - `value`: An object describing the new Anchor position **/ onChange(e: any): void; /** * Sets the anchor position to the specified row and column. If `noClip` is `true`, the position is not clipped. * @param row The row index to move the anchor to * @param column The column index to move the anchor to * @param noClip Identifies if you want the position to be clipped **/ setPosition(row: number, column: number, noClip?: boolean): void; /** * When called, the `'change'` event listener is removed. **/ detach(): void; attach(doc: Document): void; } var Anchor: { /** * Creates a new `Anchor` and associates it with a document. * @param doc The document to associate with the anchor * @param row The starting row position * @param column The starting column position **/ new(doc: Document, row: number, column: number): Anchor; } //////////////////////////////// /// BackgroundTokenizer //////////////////////////////// /** * Tokenizes the current [[Document `Document`]] in the background, and caches the tokenized rows for future use. * If a certain row is changed, everything below that row is re-tokenized. **/ export interface BackgroundTokenizer { states: any[]; /** * Sets a new tokenizer for this object. * @param tokenizer The new tokenizer to use **/ setTokenizer(tokenizer: Tokenizer): void; /** * Sets a new document to associate with this object. * @param doc The new document to associate with **/ setDocument(doc: Document): void; /** * Emits the `'update'` event. `firstRow` and `lastRow` are used to define the boundaries of the region to be updated. * @param firstRow The starting row region * @param lastRow The final row region **/ fireUpdateEvent(firstRow: number, lastRow: number): void; /** * Starts tokenizing at the row indicated. * @param startRow The row to start at **/ start(startRow: number): void; /** * Stops tokenizing. **/ stop(): void; /** * Gives list of tokens of the row. (tokens are cached) * @param row The row to get tokens at **/ getTokens(row: number): TokenInfo[]; /** * [Returns the state of tokenization at the end of a row.]{: #BackgroundTokenizer.getState} * @param row The row to get state at **/ getState(row: number): string; } var BackgroundTokenizer: { /** * Creates a new `BackgroundTokenizer` object. * @param tokenizer The tokenizer to use * @param editor The editor to associate with **/ new(tokenizer: Tokenizer, editor: Editor): BackgroundTokenizer; } //////////////// /// Document //////////////// /** * Contains the text of the document. Document can be attached to several [[EditSession `EditSession`]]s. * At its core, `Document`s are just an array of strings, with each row in the document matching up to the array index. **/ type NewLineMode = "auto" | "unix" | "windows"; export interface Document { on(event: string, fn: (e: any) => any): void; /** * Replaces all the lines in the current `Document` with the value of `text`. * @param text The text to use **/ setValue(text: string): void; /** * Returns all the lines in the document as a single string, split by the new line character. **/ getValue(): string; /** * Creates a new `Anchor` to define a floating point in the document. * @param row The row number to use * @param column The column number to use **/ createAnchor(row: number, column: number): void; /** * Returns the newline character that's being used, depending on the value of `newLineMode`. **/ getNewLineCharacter(): string; /** * [Sets the new line mode.]{: #Document.setNewLineMode.desc} * @param newLineMode [The newline mode to use; can be either `windows`, `unix`, or `auto`]{: #Document.setNewLineMode.param} **/ setNewLineMode(newLineMode: NewLineMode): void; /** * [Returns the type of newlines being used; either `windows`, `unix`, or `auto`]{: #Document.getNewLineMode} **/ getNewLineMode(): NewLineMode; /** * Returns `true` if `text` is a newline character (either `\r\n`, `\r`, or `\n`). * @param text The text to check **/ isNewLine(text: string): boolean; /** * Returns a verbatim copy of the given line as it is in the document * @param row The row index to retrieve **/ getLine(row: number): string; /** * Returns an array of strings of the rows between `firstRow` and `lastRow`. This function is inclusive of `lastRow`. * @param firstRow The first row index to retrieve * @param lastRow The final row index to retrieve **/ getLines(firstRow: number, lastRow: number): string[]; /** * Returns all lines in the document as string array. Warning: The caller should not modify this array! **/ getAllLines(): string[]; /** * Returns the number of rows in the document. **/ getLength(): number; /** * [Given a range within the document, this function returns all the text within that range as a single string.]{: #Document.getTextRange.desc} * @param range The range to work with **/ getTextRange(range: Range): string; getLinesForRange(range: Range): string[]; /** * Inserts a block of `text` and the indicated `position`. * @param position The position to start inserting at * @param text A chunk of text to insert **/ insert(position: Position, text: string): Position; /** * @deprecated Use the insertFullLines method instead. */ insertLines(row: number, lines: string[]): Position; /** * Inserts the elements in `lines` into the document as full lines (does not merge with existing line), starting at the row index given by `row`. This method also triggers the `"change"` event. * @param {Number} row The index of the row to insert at * @param {Array} lines An array of strings * @returns {Object} Contains the final row and column, like this: * ``` * {row: endRow, column: 0} * ``` * If `lines` is empty, this function returns an object containing the current row, and column, like this: * ``` * {row: row, column: 0} * ``` * **/ insertFullLines(row: number, lines: string[]): void; /** * @deprecated Use insertMergedLines(position, ['', '']) instead. */ insertNewLine(position: Position): Position; /** * Inserts the elements in `lines` into the document, starting at the position index given by `row`. This method also triggers the `"change"` event. * @param {Number} row The index of the row to insert at * @param {Array} lines An array of strings * @returns {Object} Contains the final row and column, like this: * ``` * {row: endRow, column: 0} * ``` * If `lines` is empty, this function returns an object containing the current row, and column, like this: * ``` * {row: row, column: 0} * ``` * **/ insertMergedLines(row: number, lines: string[]): Position; /** * Inserts `text` into the `position` at the current row. This method also triggers the `'change'` event. * @param position The position to insert at * @param text A chunk of text **/ insertInLine(position: Position, text: string): Position; clippedPos(row: number, column: number): Position; clonePos(pos: Position): Position; pos(row: number, column: number): Position; /** * Removes the `range` from the document. * @param range A specified Range to remove **/ remove(range: Range): Position; /** * Removes the specified columns from the `row`. This method also triggers the `'change'` event. * @param row The row to remove from * @param startColumn The column to start removing at * @param endColumn The column to stop removing at **/ removeInLine(row: number, startColumn: number, endColumn: number): Position; /** * @deprecated Use the removeFullLines method instead. */ removeLines(firstRow: number, lastRow: number): string[]; /** * Removes a range of full lines. This method also triggers the `"change"` event. * @param {Number} firstRow The first row to be removed * @param {Number} lastRow The last row to be removed * @returns {[String]} Returns all the removed lines. * **/ removeFullLines(firstRow: number, lastRow: number): string[]; /** * Removes the new line between `row` and the row immediately following it. This method also triggers the `'change'` event. * @param row The row to check **/ removeNewLine(row: number): void; /** * Replaces a range in the document with the new `text`. * @param range A specified Range to replace * @param text The new text to use as a replacement **/ replace(range: Range, text: string): Position; /** * Applies all the changes previously accumulated. These can be either `'includeText'`, `'insertLines'`, `'removeText'`, and `'removeLines'`. **/ applyDeltas(deltas: Delta[]): void; /** * Reverts any changes previously applied. These can be either `'includeText'`, `'insertLines'`, `'removeText'`, and `'removeLines'`. **/ revertDeltas(deltas: Delta[]): void; /** * Converts an index position in a document to a `{row, column}` object. * Index refers to the "absolute position" of a character in the document. For example: * ```javascript * var x = 0; // 10 characters, plus one for newline * var y = -1; * ``` * Here, `y` is an index 15: 11 characters for the first row, and 5 characters until `y` in the second. * @param index An index to convert * @param startRow=0 The row from which to start the conversion **/ indexToPosition(index: number, startRow: number): Position; /** * Converts the `{row, column}` position in a document to the character's index. * Index refers to the "absolute position" of a character in the document. For example: * ```javascript * var x = 0; // 10 characters, plus one for newline * var y = -1; * ``` * Here, `y` is an index 15: 11 characters for the first row, and 5 characters until `y` in the second. * @param pos The `{row, column}` to convert * @param startRow=0 The row from which to start the conversion **/ positionToIndex(pos: Position, startRow?: number): number; } var Document: { /** * Creates a new `Document`. If `text` is included, the `Document` contains those strings; otherwise, it's empty. * @param text The starting text **/ new(text?: string): Document; /** * Creates a new `Document`. If `text` is included, the `Document` contains those strings; otherwise, it's empty. * @param text The starting text **/ new(text?: string[]): Document; } //////////////////////////////// /// EditSession //////////////////////////////// /** * Stores all the data about [[Editor `Editor`]] state providing easy way to change editors state. * `EditSession` can be attached to only one [[Document `Document`]]. Same `Document` can be attached to several `EditSession`s. **/ export interface IEditSession extends OptionProvider { selection: Selection; bgTokenizer: BackgroundTokenizer; doc: Document; on(event: string, fn: (e: any) => any): void; findMatchingBracket(position: Position): void; addFold(text: string, range: Range): void; getFoldAt(row: number, column: number): any; removeFold(arg: any): void; expandFold(arg: any): void; foldAll(startRow?: number, endRow?: number, depth?: number): void unfold(arg1: any, arg2: boolean): void; screenToDocumentColumn(row: number, column: number): void; getFoldDisplayLine(foldLine: any, docRow: number, docColumn: number): any; getFoldsInRange(range: Range): any; highlight(text: string): void; /** * Highlight lines from `startRow` to `EndRow`. * @param startRow Define the start line of the highlight * @param endRow Define the end line of the highlight * @param clazz Set the CSS class for the marker * @param inFront Set to `true` to establish a front marker **/ highlightLines(startRow:number, endRow: number, clazz: string, inFront: boolean): Range; /** * Sets the `EditSession` to point to a new `Document`. If a `BackgroundTokenizer` exists, it also points to `doc`. * @param doc The new `Document` to use **/ setDocument(doc: Document): void; /** * Returns the `Document` associated with this session. **/ getDocument(): Document; /** * undefined * @param row The row to work with **/ $resetRowCache(row: number): void; /** * Sets the session text. * @param text The new text to place **/ setValue(text: string): void; setMode(mode: string): void; /** * Returns the current [[Document `Document`]] as a string. **/ getValue(): string; /** * Returns the string of the current selection. **/ getSelection(): Selection; /** * {:BackgroundTokenizer.getState} * @param row The row to start at **/ getState(row: number): string; /** * Starts tokenizing at the row indicated. Returns a list of objects of the tokenized rows. * @param row The row to start at **/ getTokens(row: number): TokenInfo[]; /** * Returns an object indicating the token at the current row. The object has two properties: `index` and `start`. * @param row The row number to retrieve from * @param column The column number to retrieve from **/ getTokenAt(row: number, column: number): TokenInfo|null; /** * Sets the undo manager. * @param undoManager The new undo manager **/ setUndoManager(undoManager: UndoManager): void; /** * Returns the current undo manager. **/ getUndoManager(): UndoManager; /** * Returns the current value for tabs. If the user is using soft tabs, this will be a series of spaces (defined by [[EditSession.getTabSize `getTabSize()`]]): void; otherwise it's simply `'\t'`. **/ getTabString(): string; /** * Pass `true` to enable the use of soft tabs. Soft tabs means you're using spaces instead of the tab character (`'\t'`). * @param useSoftTabs Value indicating whether or not to use soft tabs **/ setUseSoftTabs(useSoftTabs: boolean): void; /** * Returns `true` if soft tabs are being used, `false` otherwise. **/ getUseSoftTabs(): boolean; /** * Set the number of spaces that define a soft tab; for example, passing in `4` transforms the soft tabs to be equivalent to four spaces. This function also emits the `changeTabSize` event. * @param tabSize The new tab size **/ setTabSize(tabSize: number): void; /** * Returns the current tab size. **/ getTabSize(): number; /** * Returns `true` if the character at the position is a soft tab. * @param position The position to check **/ isTabStop(position: any): boolean; /** * Pass in `true` to enable overwrites in your session, or `false` to disable. * If overwrites is enabled, any text you enter will type over any text after it. If the value of `overwrite` changes, this function also emites the `changeOverwrite` event. * @param overwrite Defines wheter or not to set overwrites **/ setOverwrite(overwrite: boolean): void; /** * Returns `true` if overwrites are enabled; `false` otherwise. **/ getOverwrite(): boolean; /** * Sets the value of overwrite to the opposite of whatever it currently is. **/ toggleOverwrite(): void; /** * Adds `className` to the `row`, to be used for CSS stylings and whatnot. * @param row The row number * @param className The class to add **/ addGutterDecoration(row: number, className: string): void; /** * Removes `className` from the `row`. * @param row The row number * @param className The class to add **/ removeGutterDecoration(row: number, className: string): void; /** * Returns an array of numbers, indicating which rows have breakpoints. **/ getBreakpoints(): number[]; /** * Sets a breakpoint on every row number given by `rows`. This function also emites the `'changeBreakpoint'` event. * @param rows An array of row indices **/ setBreakpoints(rows: any[]): void; /** * Removes all breakpoints on the rows. This function also emites the `'changeBreakpoint'` event. **/ clearBreakpoints(): void; /** * Sets a breakpoint on the row number given by `rows`. This function also emites the `'changeBreakpoint'` event. * @param row A row index * @param className Class of the breakpoint **/ setBreakpoint(row: number, className: string): void; /** * Removes a breakpoint on the row number given by `rows`. This function also emites the `'changeBreakpoint'` event. * @param row A row index **/ clearBreakpoint(row: number): void; /** * Adds a new marker to the given `Range`. If `inFront` is `true`, a front marker is defined, and the `'changeFrontMarker'` event fires; otherwise, the `'changeBackMarker'` event fires. * @param range Define the range of the marker * @param clazz Set the CSS class for the marker * @param type Identify the type of the marker * @param inFront Set to `true` to establish a front marker **/ addMarker(range: Range, clazz: string, type: Function, inFront: boolean): number; /** * Adds a new marker to the given `Range`. If `inFront` is `true`, a front marker is defined, and the `'changeFrontMarker'` event fires; otherwise, the `'changeBackMarker'` event fires. * @param range Define the range of the marker * @param clazz Set the CSS class for the marker * @param type Identify the type of the marker * @param inFront Set to `true` to establish a front marker **/ addMarker(range: Range, clazz: string, type: string, inFront: boolean): number; /** * Adds a dynamic marker to the session. * @param marker object with update method * @param inFront Set to `true` to establish a front marker **/ addDynamicMarker(marker: any, inFront: boolean): void; /** * Removes the marker with the specified ID. If this marker was in front, the `'changeFrontMarker'` event is emitted. If the marker was in the back, the `'changeBackMarker'` event is emitted. * @param markerId A number representing a marker **/ removeMarker(markerId: number): void; /** * Returns an array containing the IDs of all the markers, either front or back. * @param inFront If `true`, indicates you only want front markers; `false` indicates only back markers **/ getMarkers(inFront: boolean): any[]; /** * Sets annotations for the `EditSession`. This functions emits the `'changeAnnotation'` event. * @param annotations A list of annotations **/ setAnnotations(annotations: Annotation[]): void; /** * Returns the annotations for the `EditSession`. **/ getAnnotations(): any; /** * Clears all the annotations for this session. This function also triggers the `'changeAnnotation'` event. **/ clearAnnotations(): void; /** * If `text` contains either the newline (`\n`) or carriage-return ('\r') characters, `$autoNewLine` stores that value. * @param text A block of text **/ $detectNewLine(text: string): void; /** * Given a starting row and column, this method returns the `Range` of the first word boundary it finds. * @param row The row to start at * @param column The column to start at **/ getWordRange(row: number, column: number): Range; /** * Gets the range of a word, including its right whitespace. * @param row The row number to start from * @param column The column number to start from **/ getAWordRange(row: number, column: number): any; /** * {:Document.setNewLineMode.desc} * @param newLineMode {:Document.setNewLineMode.param} **/ setNewLineMode(newLineMode: string): void; /** * Returns the current new line mode. **/ getNewLineMode(): string; /** * Identifies if you want to use a worker for the `EditSession`. * @param useWorker Set to `true` to use a worker **/ setUseWorker(useWorker: boolean): void; /** * Returns `true` if workers are being used. **/ getUseWorker(): boolean; /** * Reloads all the tokens on the current session. This function calls [[BackgroundTokenizer.start `BackgroundTokenizer.start ()`]] to all the rows; it also emits the `'tokenizerUpdate'` event. **/ onReloadTokenizer(): void; /** * Sets a new text mode for the `EditSession`. This method also emits the `'changeMode'` event. If a [[BackgroundTokenizer `BackgroundTokenizer`]] is set, the `'tokenizerUpdate'` event is also emitted. * @param mode Set a new text mode **/ $mode(mode: TextMode): void; /** * Returns the current text mode. **/ getMode(): TextMode; /** * This function sets the scroll top value. It also emits the `'changeScrollTop'` event. * @param scrollTop The new scroll top value **/ setScrollTop(scrollTop: number): void; /** * [Returns the value of the distance between the top of the editor and the topmost part of the visible content.]{: #EditSession.getScrollTop} **/ getScrollTop(): number; /** * [Sets the value of the distance between the left of the editor and the leftmost part of the visible content.]{: #EditSession.setScrollLeft} * @param scrollLeft The new scroll left value **/ setScrollLeft(scrollLeft: number): void; /** * [Returns the value of the distance between the left of the editor and the leftmost part of the visible content.]{: #EditSession.getScrollLeft} **/ getScrollLeft(): number; /** * Returns the width of the screen. **/ getScreenWidth(): number; /** * Returns a verbatim copy of the given line as it is in the document * @param row The row to retrieve from **/ getLine(row: number): string; /** * Returns an array of strings of the rows between `firstRow` and `lastRow`. This function is inclusive of `lastRow`. * @param firstRow The first row index to retrieve * @param lastRow The final row index to retrieve **/ getLines(firstRow: number, lastRow: number): string[]; /** * Returns the number of rows in the document. **/ getLength(): number; /** * {:Document.getTextRange.desc} * @param range The range to work with **/ getTextRange(range: Range): string; /** * Inserts a block of `text` and the indicated `position`. * @param position The position {row, column} to start inserting at * @param text A chunk of text to insert **/ insert(position: Position, text: string): any; /** * Removes the `range` from the document. * @param range A specified Range to remove **/ remove(range: Range): any; /** * Reverts previous changes to your document. * @param deltas An array of previous changes * @param dontSelect [If `true`, doesn't select the range of where the change occured]{: #dontSelect} **/ undoChanges(deltas: any[], dontSelect: boolean): Range; /** * Re-implements a previously undone change to your document. * @param deltas An array of previous changes * @param dontSelect {:dontSelect} **/ redoChanges(deltas: any[], dontSelect: boolean): Range; /** * Enables or disables highlighting of the range where an undo occured. * @param enable If `true`, selects the range of the reinserted change **/ setUndoSelect(enable: boolean): void; /** * Replaces a range in the document with the new `text`. * @param range A specified Range to replace * @param text The new text to use as a replacement **/ replace(range: Range, text: string): any; /** * Moves a range of text from the given range to the given position. `toPosition` is an object that looks like this: * ```json * { row: newRowLocation, column: newColumnLocation } * ``` * @param fromRange The range of text you want moved within the document * @param toPosition The location (row and column) where you want to move the text to **/ moveText(fromRange: Range, toPosition: any): Range; /** * Indents all the rows, from `startRow` to `endRow` (inclusive), by prefixing each row with the token in `indentString`. * If `indentString` contains the `'\t'` character, it's replaced by whatever is defined by [[EditSession.getTabString `getTabString()`]]. * @param startRow Starting row * @param endRow Ending row * @param indentString The indent token **/ indentRows(startRow: number, endRow: number, indentString: string): void; /** * Outdents all the rows defined by the `start` and `end` properties of `range`. * @param range A range of rows **/ outdentRows(range: Range): void; /** * Shifts all the lines in the document up one, starting from `firstRow` and ending at `lastRow`. * @param firstRow The starting row to move up * @param lastRow The final row to move up **/ moveLinesUp(firstRow: number, lastRow: number): number; /** * Shifts all the lines in the document down one, starting from `firstRow` and ending at `lastRow`. * @param firstRow The starting row to move down * @param lastRow The final row to move down **/ moveLinesDown(firstRow: number, lastRow: number): number; /** * Duplicates all the text between `firstRow` and `lastRow`. * @param firstRow The starting row to duplicate * @param lastRow The final row to duplicate **/ duplicateLines(firstRow: number, lastRow: number): number; /** * Sets whether or not line wrapping is enabled. If `useWrapMode` is different than the current value, the `'changeWrapMode'` event is emitted. * @param useWrapMode Enable (or disable) wrap mode **/ setUseWrapMode(useWrapMode: boolean): void; /** * Returns `true` if wrap mode is being used; `false` otherwise. **/ getUseWrapMode(): boolean; /** * Sets the boundaries of wrap. Either value can be `null` to have an unconstrained wrap, or, they can be the same number to pin the limit. If the wrap limits for `min` or `max` are different, this method also emits the `'changeWrapMode'` event. * @param min The minimum wrap value (the left side wrap) * @param max The maximum wrap value (the right side wrap) **/ setWrapLimitRange(min: number, max: number): void; /** * This should generally only be called by the renderer when a resize is detected. * @param desiredLimit The new wrap limit **/ adjustWrapLimit(desiredLimit: number): boolean; /** * Returns the value of wrap limit. **/ getWrapLimit(): number; /** * Returns an object that defines the minimum and maximum of the wrap limit; it looks something like this: * { min: wrapLimitRange_min, max: wrapLimitRange_max } **/ getWrapLimitRange(): any; /** * Given a string, returns an array of the display characters, including tabs and spaces. * @param str The string to check * @param offset The value to start at **/ $getDisplayTokens(str: string, offset: number): void; /** * Calculates the width of the string `str` on the screen while assuming that the string starts at the first column on the screen. * @param str The string to calculate the screen width of * @param maxScreenColumn * @param screenColumn **/ $getStringScreenWidth(str: string, maxScreenColumn: number, screenColumn: number): number[]; /** * Returns number of screenrows in a wrapped line. * @param row The row number to check **/ getRowLength(row: number): number; /** * Returns the position (on screen) for the last character in the provided screen row. * @param screenRow The screen row to check **/ getScreenLastRowColumn(screenRow: number): number; /** * For the given document row and column, this returns the column position of the last screen row. * @param docRow * @param docColumn **/ getDocumentLastRowColumn(docRow: number, docColumn: number): number; /** * For the given document row and column, this returns the document position of the last row. * @param docRow * @param docColumn **/ getDocumentLastRowColumnPosition(docRow: number, docColumn: number): number; /** * For the given row, this returns the split data. **/ getRowSplitData(): string; /** * The distance to the next tab stop at the specified screen column. * @param screenColumn The screen column to check **/ getScreenTabSize(screenColumn: number): number; /** * Converts characters coordinates on the screen to characters coordinates within the document. [This takes into account code folding, word wrap, tab size, and any other visual modifications.]{: #conversionConsiderations} * @param screenRow The screen row to check * @param screenColumn The screen column to check **/ screenToDocumentPosition(screenRow: number, screenColumn: number): any; /** * Converts document coordinates to screen coordinates. {:conversionConsiderations} * @param docRow The document row to check * @param docColumn The document column to check **/ documentToScreenPosition(docRow: number, docColumn: number): any; /** * For the given document row and column, returns the screen column. * @param row * @param docColumn **/ documentToScreenColumn(row: number, docColumn: number): number; /** * For the given document row and column, returns the screen row. * @param docRow * @param docColumn **/ documentToScreenRow(docRow: number, docColumn: number): void; /** * Returns the length of the screen. **/ getScreenLength(): number; } var EditSession: { /** * Sets up a new `EditSession` and associates it with the given `Document` and `TextMode`. * @param text [If `text` is a `Document`, it associates the `EditSession` with it. Otherwise, a new `Document` is created, with the initial text]{: #textParam} * @param mode [The inital language mode to use for the document]{: #modeParam} **/ new(text: string, mode?: TextMode): IEditSession; new(content: string, mode?: string): IEditSession; new (text: string[], mode?: string): IEditSession; } //////////////////////////////// /// Editor //////////////////////////////// /** * The main entry point into the Ace functionality. * The `Editor` manages the [[EditSession]] (which manages [[Document]]s), as well as the [[VirtualRenderer]], which draws everything to the screen. * Event sessions dealing with the mouse and keyboard are bubbled up from `Document` to the `Editor`, which decides what to do with them. **/ export interface Editor extends OptionProvider { on(ev: string, callback: (e: any) => any): void; addEventListener(ev: 'change', callback: (ev: EditorChangeEvent) => any): void; addEventListener(ev: string, callback: Function): void; off(ev: string, callback: Function): void; removeListener(ev: string, callback: Function): void; removeEventListener(ev: string, callback: Function): void; inMultiSelectMode: boolean; selectMoreLines(n: number): void; onTextInput(text: string): void; onCommandKey(e: any, hashId: number, keyCode: number): void; commands: CommandManager; session: IEditSession; selection: Selection; renderer: VirtualRenderer; keyBinding: KeyBinding; container: HTMLElement; onSelectionChange(e: any): void; onChangeMode(e?: any): void; execCommand(command:string, args?: any): void; /** * Get rid of console warning by setting this to Infinity **/ $blockScrolling:number; /** * Sets a new key handler, such as "vim" or "windows". * @param keyboardHandler The new key handler **/ setKeyboardHandler(keyboardHandler: string): void; /** * Returns the keyboard handler, such as "vim" or "windows". **/ getKeyboardHandler(): string; /** * Sets a new editsession to use. This method also emits the `'changeSession'` event. * @param session The new session to use **/ setSession(session: IEditSession): void; /** * Returns the current session being used. **/ getSession(): IEditSession; /** * Sets the current document to `val`. * @param val The new value to set for the document * @param cursorPos Where to set the new value. `undefined` or 0 is selectAll, -1 is at the document start, and 1 is at the end **/ setValue(val: string, cursorPos?: number): string; /** * Returns the current session's content. **/ getValue(): string; /** * Returns the currently highlighted selection. **/ getSelection(): Selection; /** * {:VirtualRenderer.onResize} * @param force If `true`, recomputes the size, even if the height and width haven't changed **/ resize(force?: boolean): void; /** * {:VirtualRenderer.setTheme} * @param theme The path to a theme **/ setTheme(theme: string): void; /** * {:VirtualRenderer.getTheme} **/ getTheme(): string; /** * {:VirtualRenderer.setStyle} * @param style A class name **/ setStyle(style: string): void; /** * {:VirtualRenderer.unsetStyle} **/ unsetStyle(): void; /** * Set a new font size (in pixels) for the editor text. * @param size A font size ( _e.g._ "12px") **/ setFontSize(size: string): void; /** * Brings the current `textInput` into focus. **/ focus(): void; /** * Returns `true` if the current `textInput` is in focus. **/ isFocused(): boolean; /** * Blurs the current `textInput`. **/ blur(): void; /** * Emitted once the editor comes into focus. **/ onFocus(): void; /** * Emitted once the editor has been blurred. **/ onBlur(): void; /** * Emitted whenever the document is changed. * @param e Contains a single property, `data`, which has the delta of changes **/ onDocumentChange(e: any): void; /** * Emitted when the selection changes. **/ onCursorChange(): void; /** * Returns the string of text currently highlighted. **/ getCopyText(): string; /** * Called whenever a text "copy" happens. **/ onCopy(): void; /** * Called whenever a text "cut" happens. **/ onCut(): void; /** * Called whenever a text "paste" happens. * @param text The pasted text **/ onPaste(text: string): void; /** * Inserts `text` into wherever the cursor is pointing. * @param text The new text to add **/ insert(text: string): void; /** * Pass in `true` to enable overwrites in your session, or `false` to disable. If overwrites is enabled, any text you enter will type over any text after it. If the value of `overwrite` changes, this function also emites the `changeOverwrite` event. * @param overwrite Defines wheter or not to set overwrites **/ setOverwrite(overwrite: boolean): void; /** * Returns `true` if overwrites are enabled; `false` otherwise. **/ getOverwrite(): boolean; /** * Sets the value of overwrite to the opposite of whatever it currently is. **/ toggleOverwrite(): void; /** * Sets how fast the mouse scrolling should do. * @param speed A value indicating the new speed (in milliseconds) **/ setScrollSpeed(speed: number): void; /** * Returns the value indicating how fast the mouse scroll speed is (in milliseconds). **/ getScrollSpeed(): number; /** * Sets the delay (in milliseconds) of the mouse drag. * @param dragDelay A value indicating the new delay **/ setDragDelay(dragDelay: number): void; /** * Returns the current mouse drag delay. **/ getDragDelay(): number; /** * Indicates how selections should occur. * By default, selections are set to "line". There are no other styles at the moment, * although this code change in the future. * This function also emits the `'changeSelectionStyle'` event. * @param style The new selection style **/ setSelectionStyle(style: string): void; /** * Returns the current selection style. **/ getSelectionStyle(): string; /** * Determines whether or not the current line should be highlighted. * @param shouldHighlight Set to `true` to highlight the current line **/ setHighlightActiveLine(shouldHighlight: boolean): void; /** * Returns `true` if current lines are always highlighted. **/ getHighlightActiveLine(): boolean; /** * Determines if the currently selected word should be highlighted. * @param shouldHighlight Set to `true` to highlight the currently selected word **/ setHighlightSelectedWord(shouldHighlight: boolean): void; /** * Returns `true` if currently highlighted words are to be highlighted. **/ getHighlightSelectedWord(): boolean; /** * If `showInvisibiles` is set to `true`, invisible characters&mdash;like spaces or new lines&mdash;are show in the editor. * @param showInvisibles Specifies whether or not to show invisible characters **/ setShowInvisibles(showInvisibles: boolean): void; /** * Returns `true` if invisible characters are being shown. **/ getShowInvisibles(): boolean; /** * If `showPrintMargin` is set to `true`, the print margin is shown in the editor. * @param showPrintMargin Specifies whether or not to show the print margin **/ setShowPrintMargin(showPrintMargin: boolean): void; /** * Returns `true` if the print margin is being shown. **/ getShowPrintMargin(): boolean; /** * Sets the column defining where the print margin should be. * @param showPrintMargin Specifies the new print margin **/ setPrintMarginColumn(showPrintMargin: number): void; /** * Returns the column number of where the print margin is. **/ getPrintMarginColumn(): number; /** * If `readOnly` is true, then the editor is set to read-only mode, and none of the content can change. * @param readOnly Specifies whether the editor can be modified or not **/ setReadOnly(readOnly: boolean): void; /** * Returns `true` if the editor is set to read-only mode. **/ getReadOnly(): boolean; /** * Specifies whether to use behaviors or not. ["Behaviors" in this case is the auto-pairing of special characters, like quotation marks, parenthesis, or brackets.]{: #BehaviorsDef} * @param enabled Enables or disables behaviors **/ setBehavioursEnabled(enabled: boolean): void; /** * Returns `true` if the behaviors are currently enabled. {:BehaviorsDef} **/ getBehavioursEnabled(): boolean; /** * Specifies whether to use wrapping behaviors or not, i.e. automatically wrapping the selection with characters such as brackets * when such a character is typed in. * @param enabled Enables or disables wrapping behaviors **/ setWrapBehavioursEnabled(enabled: boolean): void; /** * Returns `true` if the wrapping behaviors are currently enabled. **/ getWrapBehavioursEnabled(): void; /** * Indicates whether the fold widgets are shown or not. * @param show Specifies whether the fold widgets are shown **/ setShowFoldWidgets(show: boolean): void; /** * Returns `true` if the fold widgets are shown. **/ getShowFoldWidgets(): void; /** * Removes words of text from the editor. A "word" is defined as a string of characters bookended by whitespace. * @param dir The direction of the deletion to occur, either "left" or "right" **/ remove(dir: string): void; /** * Removes the word directly to the right of the current selection. **/ removeWordRight(): void; /** * Removes the word directly to the left of the current selection. **/ removeWordLeft(): void; /** * Removes all the words to the left of the current selection, until the start of the line. **/ removeToLineStart(): void; /** * Removes all the words to the right of the current selection, until the end of the line. **/ removeToLineEnd(): void; /** * Splits the line at the current selection (by inserting an `'\n'`). **/ splitLine(): void; /** * Transposes current line. **/ transposeLetters(): void; /** * Converts the current selection entirely into lowercase. **/ toLowerCase(): void; /** * Converts the current selection entirely into uppercase. **/ toUpperCase(): void; /** * Inserts an indentation into the current cursor position or indents the selected lines. **/ indent(): void; /** * Indents the current line. **/ blockIndent(): void; /** * Outdents the current line. **/ blockOutdent(arg?: string): void; /** * Given the currently selected range, this function either comments all the lines, or uncomments all of them. **/ toggleCommentLines(): void; /** * Works like [[EditSession.getTokenAt]], except it returns a number. **/ getNumberAt(): number; /** * If the character before the cursor is a number, this functions changes its value by `amount`. * @param amount The value to change the numeral by (can be negative to decrease value) **/ modifyNumber(amount: number): void; /** * Removes all the lines in the current selection **/ removeLines(): void; /** * Shifts all the selected lines down one row. **/ moveLinesDown(): number; /** * Shifts all the selected lines up one row. **/ moveLinesUp(): number; /** * Moves a range of text from the given range to the given position. `toPosition` is an object that looks like this: * ```json * { row: newRowLocation, column: newColumnLocation } * ``` * @param fromRange The range of text you want moved within the document * @param toPosition The location (row and column) where you want to move the text to **/ moveText(fromRange: Range, toPosition: any): Range; /** * Copies all the selected lines up one row. **/ copyLinesUp(): number; /** * Copies all the selected lines down one row. **/ copyLinesDown(): number; /** * {:VirtualRenderer.getFirstVisibleRow} **/ getFirstVisibleRow(): number; /** * {:VirtualRenderer.getLastVisibleRow} **/ getLastVisibleRow(): number; /** * Indicates if the row is currently visible on the screen. * @param row The row to check **/ isRowVisible(row: number): boolean; /** * Indicates if the entire row is currently visible on the screen. * @param row The row to check **/ isRowFullyVisible(row: number): boolean; /** * Selects the text from the current position of the document until where a "page down" finishes. **/ selectPageDown(): void; /** * Selects the text from the current position of the document until where a "page up" finishes. **/ selectPageUp(): void; /** * Shifts the document to wherever "page down" is, as well as moving the cursor position. **/ gotoPageDown(): void; /** * Shifts the document to wherever "page up" is, as well as moving the cursor position. **/ gotoPageUp(): void; /** * Scrolls the document to wherever "page down" is, without changing the cursor position. **/ scrollPageDown(): void; /** * Scrolls the document to wherever "page up" is, without changing the cursor position. **/ scrollPageUp(): void; /** * Moves the editor to the specified row. **/ scrollToRow(): void; /** * Scrolls to a line. If `center` is `true`, it puts the line in middle of screen (or attempts to). * @param line The line to scroll to * @param center If `true` * @param animate If `true` animates scrolling * @param callback Function to be called when the animation has finished **/ scrollToLine(line: number, center: boolean, animate: boolean, callback: Function): void; /** * Attempts to center the current selection on the screen. **/ centerSelection(): void; /** * Gets the current position of the cursor. **/ getCursorPosition(): Position; /** * Returns the screen position of the cursor. **/ getCursorPositionScreen(): number; /** * {:Selection.getRange} **/ getSelectionRange(): Range; /** * Selects all the text in editor. **/ selectAll(): void; /** * {:Selection.clearSelection} **/ clearSelection(): void; /** * Moves the cursor to the specified row and column. Note that this does not de-select the current selection. * @param row The new row number * @param column The new column number **/ moveCursorTo(row: number, column?: number, animate?:boolean): void; /** * Moves the cursor to the position indicated by `pos.row` and `pos.column`. * @param position An object with two properties, row and column **/ moveCursorToPosition(position: Position): void; /** * Moves the cursor's row and column to the next matching bracket. **/ jumpToMatching(): void; /** * Moves the cursor to the specified line number, and also into the indiciated column. * @param lineNumber The line number to go to * @param column A column number to go to * @param animate If `true` animates scolling **/ gotoLine(lineNumber: number, column?: number, animate?: boolean): void; /** * Moves the cursor to the specified row and column. Note that this does de-select the current selection. * @param row The new row number * @param column The new column number **/ navigateTo(row: number, column: number): void; /** * Moves the cursor up in the document the specified number of times. Note that this does de-select the current selection. * @param times The number of times to change navigation **/ navigateUp(times?: number): void; /** * Moves the cursor down in the document the specified number of times. Note that this does de-select the current selection. * @param times The number of times to change navigation **/ navigateDown(times?: number): void; /** * Moves the cursor left in the document the specified number of times. Note that this does de-select the current selection. * @param times The number of times to change navigation **/ navigateLeft(times?: number): void; /** * Moves the cursor right in the document the specified number of times. Note that this does de-select the current selection. * @param times The number of times to change navigation **/ navigateRight(times: number): void; /** * Moves the cursor to the start of the current line. Note that this does de-select the current selection. **/ navigateLineStart(): void; /** * Moves the cursor to the end of the current line. Note that this does de-select the current selection. **/ navigateLineEnd(): void; /** * Moves the cursor to the end of the current file. Note that this does de-select the current selection. **/ navigateFileEnd(): void; /** * Moves the cursor to the start of the current file. Note that this does de-select the current selection. **/ navigateFileStart(): void; /** * Moves the cursor to the word immediately to the right of the current position. Note that this does de-select the current selection. **/ navigateWordRight(): void; /** * Moves the cursor to the word immediately to the left of the current position. Note that this does de-select the current selection. **/ navigateWordLeft(): void; /** * Replaces the first occurance of `options.needle` with the value in `replacement`. * @param replacement The text to replace with * @param options The [[Search `Search`]] options to use **/ replace(replacement: string, options?: any): void; /** * Replaces all occurances of `options.needle` with the value in `replacement`. * @param replacement The text to replace with * @param options The [[Search `Search`]] options to use **/ replaceAll(replacement: string, options?: any): void; /** * {:Search.getOptions} For more information on `options`, see [[Search `Search`]]. **/ getLastSearchOptions(): any; /** * Attempts to find `needle` within the document. For more information on `options`, see [[Search `Search`]]. * @param needle The text to search for (optional) * @param options An object defining various search properties * @param animate If `true` animate scrolling **/ find(needle: string, options?: any, animate?: boolean): void; /** * Performs another search for `needle` in the document. For more information on `options`, see [[Search `Search`]]. * @param options search options * @param animate If `true` animate scrolling **/ findNext(options?: any, animate?: boolean): void; /** * Performs a search for `needle` backwards. For more information on `options`, see [[Search `Search`]]. * @param options search options * @param animate If `true` animate scrolling **/ findPrevious(options?: any, animate?: boolean): void; /** * {:UndoManager.undo} **/ undo(): void; /** * {:UndoManager.redo} **/ redo(): void; /** * Cleans up the entire editor. **/ destroy(): void; } var Editor: { /** * Creates a new `Editor` object. * @param renderer Associated `VirtualRenderer` that draws everything * @param session The `EditSession` to refer to **/ new(renderer: VirtualRenderer, session?: IEditSession): Editor; } interface EditorChangeEvent { start: Position; end: Position; action: string; // insert, remove lines: any[]; } //////////////////////////////// /// PlaceHolder //////////////////////////////// export interface PlaceHolder { on(event: string, fn: (e: any) => any): void; /** * PlaceHolder.setup() * TODO **/ setup(): void; /** * PlaceHolder.showOtherMarkers() * TODO **/ showOtherMarkers(): void; /** * PlaceHolder.hideOtherMarkers() * Hides all over markers in the [[EditSession `EditSession`]] that are not the currently selected one. **/ hideOtherMarkers(): void; /** * PlaceHolder@onUpdate(e) * Emitted when the place holder updates. **/ onUpdate(): void; /** * PlaceHolder@onCursorChange(e) * Emitted when the cursor changes. **/ onCursorChange(): void; /** * PlaceHolder.detach() * TODO **/ detach(): void; /** * PlaceHolder.cancel() * TODO **/ cancel(): void; } var PlaceHolder: { /** * - @param session (Document): The document to associate with the anchor * - @param length (Number): The starting row position * - @param pos (Number): The starting column position * - @param others (String): * - @param mainClass (String): * - @param othersClass (String): **/ new (session: Document, length: number, pos: number, others: string, mainClass: string, othersClass: string): PlaceHolder; new (session: IEditSession, length: number, pos: Position, positions: Position[]): PlaceHolder; } //////////////// /// RangeList //////////////// export interface IRangeList { ranges: Range[]; pointIndex(pos: Position, startIndex?: number): void; addList(ranges: Range[]): void; add(ranges: Range): void; merge(): Range[]; substractPoint(pos: Position): void; } export var RangeList: { new (): IRangeList; } //////////////// /// Range //////////////// /** * This object is used in various places to indicate a region within the editor. To better visualize how this works, imagine a rectangle. Each quadrant of the rectangle is analogus to a range, as ranges contain a starting row and starting column, and an ending row, and ending column. **/ export interface Range { startRow:number; startColumn:number; endRow:number; endColumn:number; start: Position; end: Position; isEmpty(): boolean; /** * Returns `true` if and only if the starting row and column, and ending row and column, are equivalent to those given by `range`. * @param range A range to check against **/ isEqual(range: Range): void; /** * Returns a string containing the range's row and column information, given like this: * ``` * [start.row/start.column] -> [end.row/end.column] * ``` **/ toString(): void; /** * Returns `true` if the `row` and `column` provided are within the given range. This can better be expressed as returning `true` if: * ```javascript * this.start.row <= row <= this.end.row && * this.start.column <= column <= this.end.column * ``` * @param row A row to check for * @param column A column to check for **/ contains(row: number, column: number): boolean; /** * Compares `this` range (A) with another range (B). * @param range A range to compare with **/ compareRange(range: Range): number; /** * Checks the row and column points of `p` with the row and column points of the calling range. * @param p A point to compare with **/ comparePoint(p: Range): number; /** * Checks the start and end points of `range` and compares them to the calling range. Returns `true` if the `range` is contained within the caller's range. * @param range A range to compare with **/ containsRange(range: Range): boolean; /** * Returns `true` if passed in `range` intersects with the one calling this method. * @param range A range to compare with **/ intersects(range: Range): boolean; /** * Returns `true` if the caller's ending row point is the same as `row`, and if the caller's ending column is the same as `column`. * @param row A row point to compare with * @param column A column point to compare with **/ isEnd(row: number, column: number): boolean; /** * Returns `true` if the caller's starting row point is the same as `row`, and if the caller's starting column is the same as `column`. * @param row A row point to compare with * @param column A column point to compare with **/ isStart(row: number, column: number): boolean; /** * Sets the starting row and column for the range. * @param row A row point to set * @param column A column point to set **/ setStart(row: number, column: number): void; /** * Sets the starting row and column for the range. * @param row A row point to set * @param column A column point to set **/ setEnd(row: number, column: number): void; /** * Returns `true` if the `row` and `column` are within the given range. * @param row A row point to compare with * @param column A column point to compare with **/ inside(row: number, column: number): boolean; /** * Returns `true` if the `row` and `column` are within the given range's starting points. * @param row A row point to compare with * @param column A column point to compare with **/ insideStart(row: number, column: number): boolean; /** * Returns `true` if the `row` and `column` are within the given range's ending points. * @param row A row point to compare with * @param column A column point to compare with **/ insideEnd(row: number, column: number): boolean; /** * Checks the row and column points with the row and column points of the calling range. * @param row A row point to compare with * @param column A column point to compare with **/ compare(row: number, column: number): number; /** * Checks the row and column points with the row and column points of the calling range. * @param row A row point to compare with * @param column A column point to compare with **/ compareStart(row: number, column: number): number; /** * Checks the row and column points with the row and column points of the calling range. * @param row A row point to compare with * @param column A column point to compare with **/ compareEnd(row: number, column: number): number; /** * Checks the row and column points with the row and column points of the calling range. * @param row A row point to compare with * @param column A column point to compare with **/ compareInside(row: number, column: number): number; /** * Returns the part of the current `Range` that occurs within the boundaries of `firstRow` and `lastRow` as a new `Range` object. * @param firstRow The starting row * @param lastRow The ending row **/ clipRows(firstRow: number, lastRow: number): Range; /** * Changes the row and column points for the calling range for both the starting and ending points. * @param row A new row to extend to * @param column A new column to extend to **/ extend(row: number, column: number): Range; /** * Returns `true` if the range spans across multiple lines. **/ isMultiLine(): boolean; /** * Returns a duplicate of the calling range. **/ clone(): Range; /** * Returns a range containing the starting and ending rows of the original range, but with a column value of `0`. **/ collapseRows(): Range; /** * Given the current `Range`, this function converts those starting and ending points into screen positions, and then returns a new `Range` object. * @param session The `EditSession` to retrieve coordinates from **/ toScreenRange(session: IEditSession): Range; /** * Creates and returns a new `Range` based on the row and column of the given parameters. * @param start A starting point to use * @param end An ending point to use **/ fromPoints(start: Range, end: Range): Range; } /** * Creates a new `Range` object with the given starting and ending row and column points. * @param startRow The starting row * @param startColumn The starting column * @param endRow The ending row * @param endColumn The ending column **/ var Range: { fromPoints(pos1: Position, pos2: Position): Range; new(startRow: number, startColumn: number, endRow: number, endColumn: number): Range; } //////////////// /// RenderLoop //////////////// export interface RenderLoop { } var RenderLoop: { new(): RenderLoop; } //////////////// /// ScrollBar //////////////// /** * A set of methods for setting and retrieving the editor's scrollbar. **/ export interface ScrollBar { /** * Emitted when the scroll bar, well, scrolls. * @param e Contains one property, `"data"`, which indicates the current scroll top position **/ onScroll(e: any): void; /** * Returns the width of the scroll bar. **/ getWidth(): number; /** * Sets the height of the scroll bar, in pixels. * @param height The new height **/ setHeight(height: number): void; /** * Sets the inner height of the scroll bar, in pixels. * @param height The new inner height **/ setInnerHeight(height: number): void; /** * Sets the scroll top of the scroll bar. * @param scrollTop The new scroll top **/ setScrollTop(scrollTop: number): void; } var ScrollBar: { /** * Creates a new `ScrollBar`. `parent` is the owner of the scroll bar. * @param parent A DOM element **/ new(parent: HTMLElement): ScrollBar; } //////////////// /// Search //////////////// /** * A class designed to handle all sorts of text searches within a [[Document `Document`]]. **/ export interface Search { /** * Sets the search options via the `options` parameter. * @param options An object containing all the new search properties **/ set(options: any): Search; /** * [Returns an object containing all the search options.]{: #Search.getOptions} **/ getOptions(): any; /** * Sets the search options via the `options` parameter. * @param An object containing all the search propertie **/ setOptions(An: any): void; /** * Searches for `options.needle`. If found, this method returns the [[Range `Range`]] where the text first occurs. If `options.backwards` is `true`, the search goes backwards in the session. * @param session The session to search with **/ find(session: IEditSession): Range; /** * Searches for all occurances `options.needle`. If found, this method returns an array of [[Range `Range`s]] where the text first occurs. If `options.backwards` is `true`, the search goes backwards in the session. * @param session The session to search with **/ findAll(session: IEditSession): Range[]; /** * Searches for `options.needle` in `input`, and, if found, replaces it with `replacement`. * @param input The text to search in * @param replacement The replacing text * + (String): If `options.regExp` is `true`, this function returns `input` with the replacement already made. Otherwise, this function just returns `replacement`.<br/> * If `options.needle` was not found, this function returns `null`. **/ replace(input: string, replacement: string): string; } var Search: { /** * Creates a new `Search` object. The following search options are avaliable: * - `needle`: The string or regular expression you're looking for * - `backwards`: Whether to search backwards from where cursor currently is. Defaults to `false`. * - `wrap`: Whether to wrap the search back to the beginning when it hits the end. Defaults to `false`. * - `caseSensitive`: Whether the search ought to be case-sensitive. Defaults to `false`. * - `wholeWord`: Whether the search matches only on whole words. Defaults to `false`. * - `range`: The [[Range]] to search within. Set this to `null` for the whole document * - `regExp`: Whether the search is a regular expression or not. Defaults to `false`. * - `start`: The starting [[Range]] or cursor position to begin the search * - `skipCurrent`: Whether or not to include the current line in the search. Default to `false`. **/ new(): Search; } //////////////// /// Search //////////////// /** * Contains the cursor position and the text selection of an edit session. * The row/columns used in the selection are in document coordinates representing ths coordinates as thez appear in the document before applying soft wrap and folding. **/ export interface Selection { on(ev: string, callback: Function): void; addEventListener(ev: string, callback: Function): void; off(ev: string, callback: Function): void; removeListener(ev: string, callback: Function): void; removeEventListener(ev: string, callback: Function): void; moveCursorWordLeft(): void; moveCursorWordRight(): void; fromOrientedRange(range: Range): void; setSelectionRange(match: any): void; getAllRanges(): Range[]; on(event: string, fn: (e: any) => any): void; addRange(range: Range): void; /** * Returns `true` if the selection is empty. **/ isEmpty(): boolean; /** * Returns `true` if the selection is a multi-line. **/ isMultiLine(): boolean; /** * Gets the current position of the cursor. **/ getCursor(): Position; /** * Sets the row and column position of the anchor. This function also emits the `'changeSelection'` event. * @param row The new row * @param column The new column **/ setSelectionAnchor(row: number, column: number): void; /** * Returns an object containing the `row` and `column` of the calling selection anchor. **/ getSelectionAnchor(): any; /** * Returns an object containing the `row` and `column` of the calling selection lead. **/ getSelectionLead(): any; /** * Shifts the selection up (or down, if [[Selection.isBackwards `isBackwards()`]] is true) the given number of columns. * @param columns The number of columns to shift by **/ shiftSelection(columns: number): void; /** * Returns `true` if the selection is going backwards in the document. **/ isBackwards(): boolean; /** * [Returns the [[Range]] for the selected text.]{: #Selection.getRange} **/ getRange(): Range; /** * [Empties the selection (by de-selecting it). This function also emits the `'changeSelection'` event.]{: #Selection.clearSelection} **/ clearSelection(): void; /** * Selects all the text in the document. **/ selectAll(): void; /** * Sets the selection to the provided range. * @param range The range of text to select * @param reverse Indicates if the range should go backwards (`true`) or not **/ setRange(range: Range, reverse: boolean): void; /** * Moves the selection cursor to the indicated row and column. * @param row The row to select to * @param column The column to select to **/ selectTo(row: number, column: number): void; /** * Moves the selection cursor to the row and column indicated by `pos`. * @param pos An object containing the row and column **/ selectToPosition(pos: any): void; /** * Moves the selection up one row. **/ selectUp(): void; /** * Moves the selection down one row. **/ selectDown(): void; /** * Moves the selection right one column. **/ selectRight(): void; /** * Moves the selection left one column. **/ selectLeft(): void; /** * Moves the selection to the beginning of the current line. **/ selectLineStart(): void; /** * Moves the selection to the end of the current line. **/ selectLineEnd(): void; /** * Moves the selection to the end of the file. **/ selectFileEnd(): void; /** * Moves the selection to the start of the file. **/ selectFileStart(): void; /** * Moves the selection to the first word on the right. **/ selectWordRight(): void; /** * Moves the selection to the first word on the left. **/ selectWordLeft(): void; /** * Moves the selection to highlight the entire word. **/ getWordRange(): void; /** * Selects an entire word boundary. **/ selectWord(): void; /** * Selects a word, including its right whitespace. **/ selectAWord(): void; /** * Selects the entire line. **/ selectLine(): void; /** * Moves the cursor up one row. **/ moveCursorUp(): void; /** * Moves the cursor down one row. **/ moveCursorDown(): void; /** * Moves the cursor left one column. **/ moveCursorLeft(): void; /** * Moves the cursor right one column. **/ moveCursorRight(): void; /** * Moves the cursor to the start of the line. **/ moveCursorLineStart(): void; /** * Moves the cursor to the end of the line. **/ moveCursorLineEnd(): void; /** * Moves the cursor to the end of the file. **/ moveCursorFileEnd(): void; /** * Moves the cursor to the start of the file. **/ moveCursorFileStart(): void; /** * Moves the cursor to the word on the right. **/ moveCursorLongWordRight(): void; /** * Moves the cursor to the word on the left. **/ moveCursorLongWordLeft(): void; /** * Moves the cursor to position indicated by the parameters. Negative numbers move the cursor backwards in the document. * @param rows The number of rows to move by * @param chars The number of characters to move by **/ moveCursorBy(rows: number, chars: number): void; /** * Moves the selection to the position indicated by its `row` and `column`. * @param position The position to move to **/ moveCursorToPosition(position: any): void; /** * Moves the cursor to the row and column provided. [If `preventUpdateDesiredColumn` is `true`, then the cursor stays in the same column position as its original point.]{: #preventUpdateBoolDesc} * @param row The row to move to * @param column The column to move to * @param keepDesiredColumn [If `true`, the cursor move does not respect the previous column]{: #preventUpdateBool} **/ moveCursorTo(row: number, column: number, keepDesiredColumn?: boolean): void; /** * Moves the cursor to the screen position indicated by row and column. {:preventUpdateBoolDesc} * @param row The row to move to * @param column The column to move to * @param keepDesiredColumn {:preventUpdateBool} **/ moveCursorToScreen(row: number, column: number, keepDesiredColumn: boolean): void; } var Selection: { /** * Creates a new `Selection` object. * @param session The session to use **/ new(session: IEditSession): Selection; } //////////////// /// Split //////////////// export interface Split { /** * Returns the number of splits. **/ getSplits(): number; /** * Returns the editor identified by the index `idx`. * @param idx The index of the editor you want **/ getEditor(idx: number): void; /** * Returns the current editor. **/ getCurrentEditor(): Editor; /** * Focuses the current editor. **/ focus(): void; /** * Blurs the current editor. **/ blur(): void; /** * Sets a theme for each of the available editors. * @param theme The name of the theme to set **/ setTheme(theme: string): void; /** * Sets the keyboard handler for the editor. * @param keybinding **/ setKeyboardHandler(keybinding: string): void; /** * Executes `callback` on all of the available editors. * @param callback A callback function to execute * @param scope The default scope for the callback **/ forEach(callback: Function, scope: string): void; /** * Sets the font size, in pixels, for all the available editors. * @param size The new font size **/ setFontSize(size: number): void; /** * Sets a new [[EditSession `EditSession`]] for the indicated editor. * @param session The new edit session * @param idx The editor's index you're interested in **/ setSession(session: IEditSession, idx: number): void; /** * Returns the orientation. **/ getOrientation(): number; /** * Sets the orientation. * @param orientation The new orientation value **/ setOrientation(orientation: number): void; /** * Resizes the editor. **/ resize(): void; } var Split: { new(): Split; } ////////////////// /// TokenIterator ////////////////// /** * This class provides an essay way to treat the document as a stream of tokens, and provides methods to iterate over these tokens. **/ export interface TokenIterator { /** * Tokenizes all the items from the current point to the row prior in the document. **/ stepBackward(): string[]; /** * Tokenizes all the items from the current point until the next row in the document. If the current point is at the end of the file, this function returns `null`. Otherwise, it returns the tokenized string. **/ stepForward(): string; /** * Returns the current tokenized string. **/ getCurrentToken(): TokenInfo; /** * Returns the current row. **/ getCurrentTokenRow(): number; /** * Returns the current column. **/ getCurrentTokenColumn(): number; } var TokenIterator: { /** * Creates a new token iterator object. The inital token index is set to the provided row and column coordinates. * @param session The session to associate with * @param initialRow The row to start the tokenizing at * @param initialColumn The column to start the tokenizing at **/ new(session: IEditSession, initialRow: number, initialColumn: number): TokenIterator; } ////////////////// /// Tokenizer ////////////////// /** * This class takes a set of highlighting rules, and creates a tokenizer out of them. For more information, see [the wiki on extending highlighters](https://github.com/ajaxorg/ace/wiki/Creating-or-Extending-an-Edit-Mode#wiki-extendingTheHighlighter). **/ export interface Tokenizer { /** * Returns an object containing two properties: `tokens`, which contains all the tokens; and `state`, the current state. **/ removeCapturingGroups(src: string): string; createSplitterRegexp(src: string, flag?: string): RegExp; getLineTokens(line: string, startState: string | string[]): TokenInfo[]; } var Tokenizer: { /** * Constructs a new tokenizer based on the given rules and flags. * @param rules The highlighting rules * @param flag Any additional regular expression flags to pass (like "i" for case insensitive) **/ new(rules: any, flag: string): Tokenizer; } ////////////////// /// UndoManager ////////////////// /** * This object maintains the undo stack for an [[EditSession `EditSession`]]. **/ export interface UndoManager { /** * Provides a means for implementing your own undo manager. `options` has one property, `args`, an [[Array `Array`]], with two elements: * - `args[0]` is an array of deltas * - `args[1]` is the document to associate with * @param options Contains additional properties **/ execute(options: any): void; /** * [Perform an undo operation on the document, reverting the last change.]{: #UndoManager.undo} * @param dontSelect {:dontSelect} **/ undo(dontSelect?: boolean): Range; /** * [Perform a redo operation on the document, reimplementing the last change.]{: #UndoManager.redo} * @param dontSelect {:dontSelect} **/ redo(dontSelect: boolean): void; /** * Destroys the stack of undo and redo redo operations. **/ reset(): void; /** * Returns `true` if there are undo operations left to perform. **/ hasUndo(): boolean; /** * Returns `true` if there are redo operations left to perform. **/ hasRedo(): boolean; /** * Returns `true` if the dirty counter is 0 **/ isClean(): boolean; /** * Sets dirty counter to 0 **/ markClean(): void; } var UndoManager: { /** * Resets the current undo state and creates a new `UndoManager`. **/ new(): UndoManager; } //////////////////// /// VirtualRenderer //////////////////// /** * The class that is responsible for drawing everything you see on the screen! **/ export interface VirtualRenderer extends OptionProvider { scroller: any; characterWidth: number; lineHeight: number; setScrollMargin(top:number, bottom:number, left: number, right: number): void; screenToTextCoordinates(left: number, top: number): void; /** * Associates the renderer with an [[EditSession `EditSession`]]. **/ setSession(session: IEditSession): void; /** * Triggers a partial update of the text, from the range given by the two parameters. * @param firstRow The first row to update * @param lastRow The last row to update **/ updateLines(firstRow: number, lastRow: number): void; /** * Triggers a full update of the text, for all the rows. **/ updateText(): void; /** * Triggers a full update of all the layers, for all the rows. * @param force If `true`, forces the changes through **/ updateFull(force: boolean): void; /** * Updates the font size. **/ updateFontSize(): void; /** * [Triggers a resize of the editor.]{: #VirtualRenderer.onResize} * @param force If `true`, recomputes the size, even if the height and width haven't changed * @param gutterWidth The width of the gutter in pixels * @param width The width of the editor in pixels * @param height The hiehgt of the editor, in pixels **/ onResize(force: boolean, gutterWidth: number, width: number, height: number): void; /** * Adjusts the wrap limit, which is the number of characters that can fit within the width of the edit area on screen. **/ adjustWrapLimit(): void; /** * Identifies whether you want to have an animated scroll or not. * @param shouldAnimate Set to `true` to show animated scrolls **/ setAnimatedScroll(shouldAnimate: boolean): void; /** * Returns whether an animated scroll happens or not. **/ getAnimatedScroll(): boolean; /** * Identifies whether you want to show invisible characters or not. * @param showInvisibles Set to `true` to show invisibles **/ setShowInvisibles(showInvisibles: boolean): void; /** * Returns whether invisible characters are being shown or not. **/ getShowInvisibles(): boolean; /** * Identifies whether you want to show the print margin or not. * @param showPrintMargin Set to `true` to show the print margin **/ setShowPrintMargin(showPrintMargin: boolean): void; /** * Returns whether the print margin is being shown or not. **/ getShowPrintMargin(): boolean; /** * Identifies whether you want to show the print margin column or not. * @param showPrintMargin Set to `true` to show the print margin column **/ setPrintMarginColumn(showPrintMargin: boolean): void; /** * Returns whether the print margin column is being shown or not. **/ getPrintMarginColumn(): boolean; /** * Returns `true` if the gutter is being shown. **/ getShowGutter(): boolean; /** * Identifies whether you want to show the gutter or not. * @param show Set to `true` to show the gutter **/ setShowGutter(show: boolean): void; /** * Returns the root element containing this renderer. **/ getContainerElement(): HTMLElement; /** * Returns the element that the mouse events are attached to **/ getMouseEventTarget(): HTMLElement; /** * Returns the element to which the hidden text area is added. **/ getTextAreaContainer(): HTMLElement; /** * [Returns the index of the first visible row.]{: #VirtualRenderer.getFirstVisibleRow} **/ getFirstVisibleRow(): number; /** * Returns the index of the first fully visible row. "Fully" here means that the characters in the row are not truncated; that the top and the bottom of the row are on the screen. **/ getFirstFullyVisibleRow(): number; /** * Returns the index of the last fully visible row. "Fully" here means that the characters in the row are not truncated; that the top and the bottom of the row are on the screen. **/ getLastFullyVisibleRow(): number; /** * [Returns the index of the last visible row.]{: #VirtualRenderer.getLastVisibleRow} **/ getLastVisibleRow(): number; /** * Sets the padding for all the layers. * @param padding A new padding value (in pixels) **/ setPadding(padding: number): void; /** * Returns whether the horizontal scrollbar is set to be always visible. **/ getHScrollBarAlwaysVisible(): boolean; /** * Identifies whether you want to show the horizontal scrollbar or not. * @param alwaysVisible Set to `true` to make the horizontal scroll bar visible **/ setHScrollBarAlwaysVisible(alwaysVisible: boolean): void; /** * Schedules an update to all the front markers in the document. **/ updateFrontMarkers(): void; /** * Schedules an update to all the back markers in the document. **/ updateBackMarkers(): void; /** * Deprecated; (moved to [[EditSession]]) **/ addGutterDecoration(): void; /** * Deprecated; (moved to [[EditSession]]) **/ removeGutterDecoration(): void; /** * Redraw breakpoints. **/ updateBreakpoints(): void; /** * Sets annotations for the gutter. * @param annotations An array containing annotations **/ setAnnotations(annotations: any[]): void; /** * Updates the cursor icon. **/ updateCursor(): void; /** * Hides the cursor icon. **/ hideCursor(): void; /** * Shows the cursor icon. **/ showCursor(): void; /** * Scrolls the cursor into the first visibile area of the editor **/ scrollCursorIntoView(): void; /** * {:EditSession.getScrollTop} **/ getScrollTop(): number; /** * {:EditSession.getScrollLeft} **/ getScrollLeft(): number; /** * Returns the first visible row, regardless of whether it's fully visible or not. **/ getScrollTopRow(): number; /** * Returns the last visible row, regardless of whether it's fully visible or not. **/ getScrollBottomRow(): number; /** * Gracefully scrolls from the top of the editor to the row indicated. * @param row A row id **/ scrollToRow(row: number): void; /** * Gracefully scrolls the editor to the row indicated. * @param line A line number * @param center If `true`, centers the editor the to indicated line * @param animate If `true` animates scrolling * @param callback Function to be called after the animation has finished **/ scrollToLine(line: number, center: boolean, animate: boolean, callback: Function): void; /** * Scrolls the editor to the y pixel indicated. * @param scrollTop The position to scroll to **/ scrollToY(scrollTop: number): number; /** * Scrolls the editor across the x-axis to the pixel indicated. * @param scrollLeft The position to scroll to **/ scrollToX(scrollLeft: number): number; /** * Scrolls the editor across both x- and y-axes. * @param deltaX The x value to scroll by * @param deltaY The y value to scroll by **/ scrollBy(deltaX: number, deltaY: number): void; /** * Returns `true` if you can still scroll by either parameter; in other words, you haven't reached the end of the file or line. * @param deltaX The x value to scroll by * @param deltaY The y value to scroll by **/ isScrollableBy(deltaX: number, deltaY: number): boolean; /** * Returns an object containing the `pageX` and `pageY` coordinates of the document position. * @param row The document row position * @param column The document column position **/ textToScreenCoordinates(row: number, column: number): any; /** * Focuses the current container. **/ visualizeFocus(): void; /** * Blurs the current container. **/ visualizeBlur(): void; /** * undefined * @param position **/ showComposition(position: number): void; /** * Sets the inner text of the current composition to `text`. * @param text A string of text to use **/ setCompositionText(text: string): void; /** * Hides the current composition. **/ hideComposition(): void; /** * [Sets a new theme for the editor. `theme` should exist, and be a directory path, like `ace/theme/textmate`.]{: #VirtualRenderer.setTheme} * @param theme The path to a theme **/ setTheme(theme: string): void; /** * [Returns the path of the current theme.]{: #VirtualRenderer.getTheme} **/ getTheme(): string; /** * [Adds a new class, `style`, to the editor.]{: #VirtualRenderer.setStyle} * @param style A class name **/ setStyle(style: string): void; /** * [Removes the class `style` from the editor.]{: #VirtualRenderer.unsetStyle} * @param style A class name **/ unsetStyle(style: string): void; /** * Destroys the text and cursor layers for this renderer. **/ destroy(): void; } var VirtualRenderer: { /** * Constructs a new `VirtualRenderer` within the `container` specified, applying the given `theme`. * @param container The root element of the editor * @param theme The starting theme **/ new(container: HTMLElement, theme?: string): VirtualRenderer; } export interface Completer { /** * Provides possible completion results asynchronously using the given callback. * @param editor The editor to associate with * @param session The `EditSession` to refer to * @param pos An object containing the row and column * @param prefix The prefixing string before the current position * @param callback Function to provide the results or error */ getCompletions: (editor: Editor, session: IEditSession, pos: Position, prefix: string, callback: CompletionCallback) => void; /** * Provides tooltip information about a completion result. * @param item The completion result */ getDocTooltip?: ((item: Completion) => void) | undefined; } export interface Completion { value: string; meta: string; type?: string | undefined; caption?: string | undefined; snippet?: any; score?: number | undefined; exactMatch?: number | undefined; docHTML?: string | undefined; } export type CompletionCallback = (error: Error | null, results: Completion[]) => void; } declare var ace: AceAjax.Ace;
the_stack
import { merge } from 'lodash'; import * as moment from 'moment/moment'; export type Status = 'success' | 'failure' | 'missing' | 'skipped'; export type Compliance = 'compliant' | 'uncompliant' | 'skipped'; export type HealthStatus = 'ok' | 'critical' | 'warning' | 'unknown'; export type RollupServiceStatus = HealthStatus | 'total'; export type RollupState = Status | 'total'; export type RollupCompliance = Compliance | 'total'; export type SortDirection = 'asc' | 'desc' | 'ASC' | 'DESC' | 'none'; export enum LoadingStatus { notLoaded, loading, loadingSuccess, loadingFailure } export interface ComplianceData { end_time: string; node_name: string; status: string; critical: number; major: number; minor: number; passed: number; skipped: number; organization_name: string; source_fqdn: string; environment: string; } export class ComplianceNode implements ComplianceData { entity_uuid: string; end_time: string; node_name: string; status: string; critical: number; major: number; minor: number; passed: number; skipped: number; organization_name: string; source_fqdn: string; environment: string; constructor(complianceData) { this.entity_uuid = complianceData._id; this.end_time = complianceData._source.compliance_summary.end_time; this.node_name = complianceData._source.compliance_summary.node_name; this.status = complianceData._source.compliance_summary.status; this.critical = complianceData._source.compliance_summary.failed.critical; this.major = complianceData._source.compliance_summary.failed.major; this.minor = complianceData._source.compliance_summary.failed.minor; this.passed = complianceData._source.compliance_summary.passed.total; this.skipped = complianceData._source.compliance_summary.skipped.total; this.organization_name = complianceData._source.organization_name; this.source_fqdn = complianceData._source.source_fqdn; this.environment = complianceData._source.environment; } } export interface Chicklet { text: string; type: string; type_key?: string; } export interface SuggestionItem { name: string; title: string; icon: string; } export interface SearchBarCategoryItem { text: string; type: string; providedValues?: SuggestionItem[]; allowWildcards?: boolean; } export interface NodeFilter { attribute?: string; compliance?: RollupCompliance; cookbook?: string; environment?: string; node_name?: string; organizations?: Array<string>; page: number; pageSize: number; recipe?: string; resource_name?: string; role?: string; searchBar?: Array<Chicklet>; servers?: Array<string>; sortDirection?: SortDirection; sortField?: string; status?: RollupState; policy_group?: string; policy_name?: string; policy_revision?: string; } // Since some of the properties of NodeFilter are optional, // we have a const that has the full list for use in places that // want to iterate on the full list of filters. Please keep in // sync with the above NodeFilter interface. export const nodeFilterProperties = ['attribute', 'compliance', 'cookbook', 'environment', 'node_name', 'organizations', 'page', 'pageSize', 'recipe', 'resource_name', 'role', 'searchBar', 'servers', 'sortDirection', 'sortField', 'status', 'policy_group', 'policy_name', 'policy_revision']; export const termMap = { cookbook: 'cookbooks', attribute: 'attributes', resource_name: 'resource_names', node_name: 'name', recipe: 'recipes', policy_group: 'policy_group', policy_name: 'policy_name', policy_revision: 'policy_revision' }; // Converge status (run-history) gives us failed and success, // where as compliance status (scan-history) fives is failed, passed, skipped export enum SelectedStatus { All, Success, Failure, Missing, Skipped, Failed, Passed } export interface RespChefEvent { event_type: string; task: string; start_time: Date; entity_name: string; requestor_type: string; requestor_name: string; service_hostname: string; parent_name: string; parent_type: string; event_count: number; end_time: Date; end_id: string; start_id: string; } export interface RespChefEventCollection { events: RespChefEvent[]; total_events: number; } export class ChefEventCollection { events: ChefEvent[]; totalEvents: number; constructor(chefEvents: ChefEvent[], totalEvents: number) { this.events = chefEvents; this.totalEvents = totalEvents; } } export class ChefEvent { eventType: string; task: string; startTime: Date; entityName: string; requestorType: string; requestorName: string; serviceHostname: string; parentName: string; parentType: string; eventCount: number; endTime: Date; endId: string; startId: string; constructor(respChefEvent: RespChefEvent) { this.eventType = respChefEvent.event_type; this.task = respChefEvent.task; this.startTime = respChefEvent.start_time; this.entityName = respChefEvent.entity_name; this.requestorType = respChefEvent.requestor_type; this.requestorName = respChefEvent.requestor_name; this.serviceHostname = respChefEvent.service_hostname; this.parentName = respChefEvent.parent_name; this.parentType = respChefEvent.parent_type; this.eventCount = respChefEvent.event_count; this.endTime = respChefEvent.end_time; this.endId = respChefEvent.end_id; this.startId = respChefEvent.start_id; } } export class NodeHistory { response: any; constructor(resp?: any) { this.response = resp || {}; } get runId(): string { return this.response._source.run_id; } get status(): Status { return this.response._source.status; } get startTime(): Date { return this.response._source.start_time; } get endTime(): Date { return this.response._source.end_time; } } export interface NodeHistoryFilter { nodeId?: string; startDate?: string; endDate?: string; status?: string; page: number; pageSize: number; } export interface NodeHistoryCountsFilter { nodeId?: string; startDate?: string; endDate?: string; } export interface ExpandedRunListItem { type: string; name: string; version: string; skipped: boolean; children: ExpandedRunListItem[]; } export interface VersionedCookbook { name: string; version: string; } export interface RespNodeRun { node_id: string; id: string; node_name: string; organization: string; resources: Resource[]; start_time: Date; end_time: Date; source: string; status: string; total_resource_count: string; updated_resource_count: string; deprecations: Deprecation[]; error: { class: string; message: string; backtrace: string[]; description: { title: string; sections: object[]; } }; tags: string[]; projects: string[]; resource_names: string[]; recipes: string[]; chef_tags: string[]; cookbooks: string[]; platform: string; platform_family: string; platform_version: string; chef_version: string; uptime_seconds: number; environment: string; roles: string[]; policy_name: string; policy_group: string; policy_revision: string; fqdn: string; ipaddress: string; source_fqdn: string; timestamp: Date; version: string; run_list?: string[]; expanded_run_list?: { id: string; run_list: ExpandedRunListItem[]; }; versioned_cookbooks: VersionedCookbook[]; ip6address?: string; timezone?: string; domain?: string; hostname?: string; memory_total?: string; macaddress?: string; dmi_system_serial_number?: string; dmi_system_manufacturer?: string; virtualization_role?: string; virtualization_system?: string; kernel_version?: string; kernel_release?: string; cloud_provider?: string; } export interface Deprecation { message: string; url: string; location: string; } export interface Resource { type: string; name: string; id: string; duration: string; delta: string; ignore_failure: boolean; result: string; status: string; cookbook_name?: string; cookbook_version?: string; recipe_name?: string; conditional?: string; error?: { class: string; message: string; backtrace: string[]; description: { title: string; sections: object[]; } }; } export class NodeRun { static Null: NodeRun = new NodeRun({ node_id: '', node_name: '', organization: '', resources: [], chef_tags: [], id: '', run_list: [], start_time: new Date(0), end_time: new Date(0), source: '', deprecations: [], status: '', total_resource_count: '', updated_resource_count: '', tags: [''], resource_names: [''], recipes: [''], cookbooks: [''], platform: '', platform_family: '', platform_version: '', chef_version: '', uptime_seconds: 0, environment: '', roles: [], projects: [], policy_group: '', policy_name: '', policy_revision: '', fqdn: '', ipaddress: '', source_fqdn: '', timestamp: new Date(0), version: '', error: { class: '', message: '', backtrace: [], description: { title: '', sections: [] } }, expanded_run_list: { id: '', run_list: [] }, versioned_cookbooks: [ { name: '', version: '' } ], ip6address: '', timezone: '', domain: '', hostname: '', memory_total: '', macaddress: '', dmi_system_serial_number: '', dmi_system_manufacturer: '', virtualization_role: '', virtualization_system: '', kernel_version: '', kernel_release: '', cloud_provider: '' }); nodeId: string; nodeName: string; organization: string; resources: Resource[]; deprecations: Deprecation[]; runId: string; runList: string[]; startTime: Date; endTime: Date; source: string; status: string; tags: string[]; chefTags: string[]; resourceNames: string[]; recipes: string[]; cookbooks: string[]; platform: string; platformFamily: string; platformVersion: string; chefVersion: string; projects: string[]; environment: string; roles: string[]; policyGroup: string; policyName: string; policyRevision: string; fqdn: string; ipaddress: string; sourceFqdn: string; timestamp: Date; version: string; uptimeSeconds: number; error?: { class: string; message: string; backtrace: string[]; description: { title: string; sections: object[]; }; }; expandedRunList: { id: string; run_list: ExpandedRunListItem[]; }; versionedCookbooks: VersionedCookbook[]; ip6address?: string; timezone?: string; domain?: string; hostname?: string; memoryTotal?: string; macaddress?: string; dmiSystemSerialNumber?: string; dmiSystemManufacturer?: string; virtualizationRole?: string; virtualizationSystem?: string; kernelVersion?: string; kernelRelease?: string; cloudProvider?: string; constructor(respNodeRun: RespNodeRun) { this.nodeId = respNodeRun.node_id; this.nodeName = respNodeRun.node_name; this.organization = respNodeRun.organization; this.resources = respNodeRun.resources; this.runId = respNodeRun.id; this.runList = respNodeRun.run_list; this.startTime = respNodeRun.start_time; this.endTime = respNodeRun.end_time; this.source = respNodeRun.source; this.status = respNodeRun.status; this.tags = respNodeRun.tags; this.chefTags = respNodeRun.chef_tags; this.projects = respNodeRun.projects; this.resourceNames = respNodeRun.resource_names; this.recipes = respNodeRun.recipes; this.cookbooks = respNodeRun.cookbooks; this.platform = respNodeRun.platform; this.platformFamily = respNodeRun.platform_family; this.platformVersion = respNodeRun.platform_version; this.chefVersion = respNodeRun.chef_version; this.environment = respNodeRun.environment; this.roles = respNodeRun.roles; this.policyGroup = respNodeRun.policy_group; this.policyName = respNodeRun.policy_name; this.policyRevision = respNodeRun.policy_revision; this.fqdn = respNodeRun.fqdn; this.ipaddress = respNodeRun.ipaddress; this.sourceFqdn = respNodeRun.source_fqdn; this.timestamp = respNodeRun.timestamp; this.version = respNodeRun.version; this.error = respNodeRun.error; this.expandedRunList = respNodeRun.expanded_run_list; this.uptimeSeconds = respNodeRun.uptime_seconds; this.deprecations = respNodeRun.deprecations; this.versionedCookbooks = respNodeRun.versioned_cookbooks; this.ip6address = respNodeRun.ip6address; this.timezone = respNodeRun.timezone; this.domain = respNodeRun.domain; this.hostname = respNodeRun.hostname; this.memoryTotal = respNodeRun.memory_total; this.macaddress = respNodeRun.macaddress; this.dmiSystemSerialNumber = respNodeRun.dmi_system_serial_number; this.dmiSystemManufacturer = respNodeRun.dmi_system_manufacturer; this.virtualizationRole = respNodeRun.virtualization_role; this.virtualizationSystem = respNodeRun.virtualization_system; this.kernelVersion = respNodeRun.kernel_version; this.kernelRelease = respNodeRun.kernel_release; this.cloudProvider = respNodeRun.cloud_provider; } isPolicyFile(): boolean { return this.policyName !== null && this.policyName !== ''; } } export interface RespNodeRunsCount { total: number; success: number; failure: number; } export class NodeRunsCount { total: number; success: number; failure: number; constructor(respNodeRunsCount: RespNodeRunsCount) { this.total = respNodeRunsCount.total; this.success = respNodeRunsCount.success; this.failure = respNodeRunsCount.failure; } } export interface AbridgedRespNodeRun { start_time: Date; id: string; end_time: Date; status: string; } export class AbridgedNodeRun { startTime: Date; runId: string; endTime: Date; status: string; constructor(abridgedRespNodeRun: AbridgedRespNodeRun) { this.startTime = new Date(abridgedRespNodeRun.start_time); this.runId = abridgedRespNodeRun.id; this.endTime = new Date(abridgedRespNodeRun.end_time); this.status = abridgedRespNodeRun.status; } } export interface RespNodeAttributes { node_id: string; name: string; run_list: string[]; chef_environment: string; normal: string; normal_value_count: number; default: string; default_value_count: number; override: string; override_value_count: number; automatic: string; automatic_value_count: number; all_value_count: number; } export class NodeAttributes { normal: string; normalValueCount: number; default: string; defaultValueCount: number; override: string; overrideValueCount: number; automatic: string; automaticValueCount: number; all: string; allValueCount: number; constructor(resp: RespNodeAttributes) { this.normal = resp.normal && JSON.parse(resp.normal) || {}; this.normalValueCount = resp.normal_value_count; this.default = resp.default && JSON.parse(resp.default) || {}; this.defaultValueCount = resp.default_value_count; this.override = resp.override && JSON.parse(resp.override) || {}; this.overrideValueCount = resp.override_value_count; this.automatic = resp.automatic && JSON.parse(resp.automatic) || {}; this.automaticValueCount = resp.automatic_value_count; this.allValueCount = resp.all_value_count; this.all = merge( {}, this.normal, this.default, this.override, this.automatic); } } export class RespPolicyCookbooks { policy_name: string; // CookbookLocks returned as an array because grpc does not like random keys. cookbook_locks: RespCookbookLock[]; } export class PolicyCookbooks { policyName: string; cookbookLocks: any; // Map of cookbookName to policyIdentifer constructor(resp: RespPolicyCookbooks) { this.policyName = resp.policy_name; // Transform CookbookLocks array into a map for easier indexing by cookbook name. const cookbooks = {}; resp.cookbook_locks.forEach((lock) => { cookbooks[lock.cookbook] = lock.policy_identifier; }); this.cookbookLocks = cookbooks; } } export class GuitarStringItem { eventTypeCount: RespEventCount[]; start: moment.Moment; end: moment.Moment; constructor(eventTypeCount: RespEventCount[], start: moment.Moment, end: moment.Moment) { this.eventTypeCount = eventTypeCount; this.start = start; this.end = end; } isEmpty(): boolean { return this.eventTypeCount.length === 0; } isMultiple(): boolean { if (this.eventTypeCount.length > 1) { return true; } return this.eventTypeCount.length === 1 && this.eventTypeCount[0].count > 1; } getEventType(): string { if (this.eventTypeCount.length > 1) { return 'multiple'; } if (this.eventTypeCount.length === 1 ) { return this.eventTypeCount[0].name; } return ''; } getEventTypeLabel(name, count) { let label; switch (name) { case 'item': label = 'data bag item'; break; case 'version': label = 'cookbook version'; break; case 'bag': label = 'data bag'; break; case 'scanjobs': label = 'scan job'; break; default: label = name; } // Pluralize the event label type if necessary if (count > 1) { label = label === 'policy' ? 'policies' : label + 's'; } return label; } } export class GuitarStringCollection { strings: GuitarString[]; start: moment.Moment; end: moment.Moment; constructor(strings: GuitarString[], start: moment.Moment, end: moment.Moment) { this.strings = strings; this.start = start; this.end = end; } } export class GuitarString { eventAction: string; items: GuitarStringItem[]; constructor(eventAction: string, items: GuitarStringItem[]) { this.eventAction = eventAction; this.items = items; } } export interface RespEventCollection { events_count: RespEventCount[]; } export interface ResponseGuitarString { event_action: string; // update, create, delete, ... collection: RespEventCollection[]; } export interface ResponseGuitarStringCollection { start: Date; // When the first item in the string starts end: Date; hours_between: number; // based off the request. example 3 hours strings: ResponseGuitarString[]; // has an equal number of eventTypeItems } export class RespCookbookLock { cookbook: string; policy_identifier: string; } export interface SidebarFilter { organizations?: Array<string>; servers?: Array<string>; } export interface EventFeedFilter { requestorName?: string; searchBar?: Array<Chicklet>; task?: string; collapse?: boolean; pageSize?: number; startDate?: moment.Moment; endDate?: moment.Moment; hoursBetween?: number; } export interface LocalTeam { id: string; name: string; description: string; } // Types export interface DateRange { start: Date | moment.Moment; end: Date | moment.Moment; } export interface NodeCount { total: number; success: number; failure: number; missing: number; } export class EventTaskCount { static Null: EventTaskCount = new EventTaskCount({total: 0, counts: []}); total = 0; update = 0; create = 0; delete = 0; constructor(response: RespEventCounts) { this.total = response.total; response.counts.forEach(count => { switch (count.name) { case 'update': this.update = count.count; break; case 'create': this.create = count.count; break; case 'delete': this.delete = count.count; break; } }); } } export class EventTypeCount { static Null: EventTypeCount = new EventTypeCount({total: 0, counts: []}); total = 0; cookbook = 0; version = 0; bag = 0; item = 0; environment = 0; node = 0; policyfile = 0; profile = 0; scanjobs = 0; role = 0; organization = 0; permission = 0; user = 0; group = 0; client = 0; constructor(response: RespEventCounts) { this.total = response.total; response.counts.forEach(count => { switch (count.name) { case 'policyfile': this.policyfile = count.count; break; case 'node': this.node = count.count; break; case 'cookbook': this.cookbook = count.count; break; case 'version': this.version = count.count; break; case 'item': this.item = count.count; break; case 'bag': this.bag = count.count; break; case 'environment': this.environment = count.count; break; case 'organization': this.organization = count.count; break; case 'permission': this.permission = count.count; break; case 'user': this.user = count.count; break; case 'group': this.group = count.count; break; case 'role': this.role = count.count; break; case 'profile': this.profile = count.count; break; case 'scanjobs': this.scanjobs = count.count; break; case 'client': this.client = count.count; break; } }); } } export interface RespEventCount { name: string; count: number; } export interface RespEventCounts { total: number; counts: RespEventCount[]; } export class RunInfo { runId: string; endTime: Date; constructor(runId: string, endTime: Date) { this.runId = runId; this.endTime = endTime; } } // Copied from https://www.npmjs.com/package/http-status-codes export enum HttpStatus { BAD_REQUEST = 400, FORBIDDEN = 403, NOT_FOUND = 404, CONFLICT = 409, PRECONDITION_FAILED = 412, // Warning! Grpc.FailedPrecondition maps to 400, not 412! INTERNAL_SERVER_ERROR = 500, TIME_OUT_ERROR = 504 } // Map of gRPC codes to HTTP codes is available at: // vendor/github.com/grpc-ecosystem/grpc-gateway/third_party/googleapis/google/rpc/code.proto // The full list of filter types for filtering node and profile reports inclusive of dates export enum ReportingFilterTypes { CHEF_SERVER = 'chef_server', CHEF_TAGS = 'chef_tags', CONTROL_ID = 'control_id', CONTROL_NAME = 'control_name', CONTROL_TAG_KEY = 'control_tag_key', CONTROL_TAG_VALUE = 'control_tag_value', ENVIRONMENT = 'environment', INSPEC_VERSION = 'inspec_version', JOB_ID = 'job_id', NODE_ID = 'node_id', NODE_NAME = 'node_name', ORGANIZATION = 'organization', PLATFORM_WITH_VERSION = 'platform_with_version', POLICY_GROUP = 'policy_group', POLICY_NAME = 'policy_name', PROFILE_ID = 'profile_id', PROFILE_WITH_VERSION = 'profile_with_version', PROFILE_NAME = 'profile_name', RECIPE = 'recipe', ROLE = 'role', END_TIME = 'end_time', DATE_INTERVAL = 'date_interval' }
the_stack
import moment from 'https://deno.land/x/momentjs@2.29.1-deno/mod.ts'; import { List } from 'https://deno.land/x/immutable@4.0.0-rc.12-deno.1/mod.ts'; import { IValue, NotSupported, RegClass, _IRelation, _ISchema, _ISelection, _ITable, _IType, _Transaction } from './interfaces-private.ts'; import { BinaryOperator, DataTypeDef, Expr, ExprRef, ExprValueKeyword, Interval, nil, parse, QName, SelectedColumn } from 'https://deno.land/x/pgsql_ast_parser@9.2.0/mod.ts'; import { ColumnNotFound, ISubscription, IType, QueryError, typeDefToStr } from './interfaces.ts'; import { bufClone, bufCompare, isBuf } from './buffer-deno.ts'; export interface Ctor<T> extends Function { new(...params: any[]): T; prototype: T; } export type Optional<T> = { [key in keyof T]?: T[key] }; export type SRecord<T> = Record<string, T>; export function trimNullish<T>(value: T, depth = 5): T { if (depth < 0) return value; if (value instanceof Array) { value.forEach(x => trimNullish(x, depth - 1)) } if (typeof value !== 'object' || value instanceof Date || moment.isMoment(value) || moment.isDuration(value)) return value; if (!value) { return value; } for (const k of Object.keys(value)) { const val = (value as any)[k]; if (nullIsh(val)) delete (value as any)[k]; else trimNullish(val, depth - 1); } return value; } export function watchUse<T>(rootValue: T): { checked: T; check?: () => string | null; } { if (!rootValue || typeof globalThis !== 'undefined' && (globalThis as any)?.process?.env?.['NOCHECKFULLQUERYUSAGE'] === 'true') { return { checked: rootValue }; } if (typeof rootValue !== 'object') { throw new NotSupported(); } if (Array.isArray(rootValue)) { throw new NotSupported(); } const toUse = new Map<string, any>(); function recurse(value: any, stack: List<string> = List()): any { if (!value || typeof value !== 'object') { return value; } if (Array.isArray(value)) { return value .map((x, i) => recurse(x, stack.push(`[${i}]`))); } // watch object const ret: any = {}; for (const [k, _v] of Object.entries(value)) { if (k[0] === '_') { // ignore properties starting with '_' ret[k] = _v; continue; } const nstack = stack.push('.' + k); let v = recurse(_v, nstack); const nstackKey = nstack.join(''); toUse.set(nstackKey, _v); Object.defineProperty(ret, k, { get() { toUse.delete(nstackKey); return v; }, enumerable: true, }); } return ret; } const final = recurse(rootValue); const check = function () { if (toUse.size) { return `The query you ran generated an AST which parts have not been read by the query planner. \ This means that those parts could be ignored: ⇨ ` + [...toUse.entries()] .map(([k, v]) => k + ' (' + JSON.stringify(v) + ')') .join('\n ⇨ '); } return null; } return { checked: final, check }; } export function deepEqual<T>(a: T, b: T, strict?: boolean, depth = 10, numberDelta = 0.0001) { return deepCompare(a, b, strict, depth, numberDelta) === 0; } export function deepCompare<T>(a: T, b: T, strict?: boolean, depth = 10, numberDelta = 0.0001): number { if (depth < 0) { throw new NotSupported('Comparing too deep entities'); } if (a === b) { return 0; } if (!strict) { // should not use '==' because it could call .toString() on objects when compared to strings. // ... which is not ok. Especially when working with translatable objects, which .toString() returns a transaltion (a string, thus) if (!a && !b) { return 0; } } if (Array.isArray(a)) { if (!Array.isArray(b)) { return -1; // [] < {} } if (a.length !== b.length) { return a.length > b.length ? 1 : -1; } for (let i = 0; i < a.length; i++) { const inner = deepCompare(a[i], b[i], strict, depth - 1, numberDelta); if (inner) return inner; } return 0; } if (Array.isArray(b)) { return 1; } if (isBuf(a) || isBuf(b)) { if (!isBuf(a)) { return 1; } if (!isBuf(b)) { return -1; } return bufCompare(a, b); } // handle dates if (a instanceof Date || b instanceof Date || moment.isMoment(a) || moment.isMoment(b)) { const am = moment(a); const bm = moment(b); if (am.isValid() !== bm.isValid()) { return am.isValid() ? -1 : 1; } const diff = am.diff(bm, 'seconds'); if (Math.abs(diff) < 0.001) { return 0; } return diff > 0 ? 1 : -1; } // handle durations if (moment.isDuration(a) || moment.isDuration(b)) { const da = moment.duration(a); const db = moment.duration(b); if (da.isValid() !== db.isValid()) { return da.isValid() ? -1 : 1; } const diff = da.asMilliseconds() - db.asMilliseconds(); if (Math.abs(diff) < 1) { return 0; } return diff > 0 ? 1 : -1; } const fa = Number.isFinite(<any>a); const fb = Number.isFinite(<any>b); if (fa && fb) { if (Math.abs(<any>a - <any>b) <= numberDelta) { return 0; } return a > b ? 1 : -1; } else if (fa && b) { return -1; } else if (fb && a) { return 1; } // === handle plain objects if (typeof a !== 'object') { return 1; // objects are at the end } if (typeof b !== 'object') { return -1; // objects are at the end } if (!a || !b) { return 0; // nulls } const ak = Object.keys(a); const bk = Object.keys(b); if (strict && ak.length !== bk.length) { // longer objects at the end return ak.length > bk.length ? 1 : -1; } const set: Iterable<string> = strict ? Object.keys(a) : new Set([...Object.keys(a), ...Object.keys(b)]); for (const k of set) { const inner = deepCompare((a as any)[k], (b as any)[k], strict, depth - 1, numberDelta); if (inner) { return inner; } } return 0; } type Json = { [key: string]: Json } | Json[] | string | number | null; export function queryJson(a: Json, b: Json) { if (!a || !b) { return (a ?? null) === (b ?? null); } if (a === b) { return true; } if (typeof a === 'string' || typeof b === 'string') { return false; } if (typeof a === 'number' || typeof b === 'number') { return false; } if (Array.isArray(a)) { // expecting array if (!Array.isArray(b)) { return false; } // => must match all those criteria const toMatch = [...a]; for (const be of b) { for (let i = 0; i < toMatch.length; i++) { if (queryJson(toMatch[i], be)) { // matched this criteria toMatch.splice(i, 1); break; } } if (!toMatch.length) { break; } } return !toMatch.length; } if (Array.isArray(b)) { return false; } if ((typeof a === 'object') !== (typeof b === 'object')) { return false; } const akeys = Object.keys(a); const bkeys = Object.keys(b); if (akeys.length > bkeys.length) { return false; } for (const ak of akeys) { if (!(ak in (b as any))) { return false; } if (!queryJson(a[ak], b[ak])) { return false; } } return true; } export function buildLikeMatcher(likeCondition: string, caseSensitive = true) { // Escape regex characters from likeCondition likeCondition = likeCondition.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&'); let likeRegexString = likeCondition.replace(/\%/g, ".*").replace(/_/g, '.'); likeRegexString = "^" + likeRegexString + "$"; const reg = new RegExp(likeRegexString, caseSensitive ? '' : 'i'); return (stringToMatch: string | number) => { if (nullIsh(stringToMatch)) { return null; } if (typeof stringToMatch != "string") { stringToMatch = stringToMatch.toString(); } return reg.test(stringToMatch); } } export function nullIsh(v: any): boolean { return v === null || v === undefined; } export function hasNullish(...vals: any[]): boolean { return vals.some(v => nullIsh(v)); } export function sum(v: number[]): number { return v.reduce((sum, el) => sum + el, 0); } export function deepCloneSimple<T>(v: T): T { if (!v || typeof v !== 'object' || v instanceof Date) { return v; } if (Array.isArray(v)) { return (v as any[]).map(x => deepCloneSimple(x)) as any; } if (isBuf(v)) { return bufClone(v) as any; } const ret: any = {}; for (const k of Object.keys(v)) { ret[k] = deepCloneSimple((v as any)[k]); } for (const k of Object.getOwnPropertySymbols(v)) { ret[k] = (v as any)[k]; // no need to deep clone that } return ret; } export function isSelectAllArgList(select: Expr[]): boolean { const [first] = select; return select.length === 1 && first.type === 'ref' && first.name === '*' && !first.table; } export function ignore(...val: any[]): void { for (const v of val) { if (!v) { continue; } if (Array.isArray(v)) { ignore(...v); continue; } if (typeof v !== 'object') { continue; } ignore(...Object.values(v)); } } export function combineSubs(...vals: ISubscription[]): ISubscription { return { unsubscribe: () => { vals.forEach(u => u?.unsubscribe()); }, }; } interface Ctx { schema: _ISchema; transaction: _Transaction; } const curCtx: Ctx[] = []; export function getContext(): Ctx { if (!curCtx.length) { throw new Error('Cannot call getFunctionContext() in this context'); } return curCtx[curCtx.length - 1]; } export function pushContext<T>(ctx: Ctx, act: () => T): T { try { curCtx.push(ctx) return act(); } finally { curCtx.pop(); } } export function indexHash(this: void, vals: (IValue | string)[]) { return vals.map(x => typeof x === 'string' ? x : x.hash).sort().join('|'); } export function randomString(length = 8, chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'): string { var result = ''; for (var i = length; i > 0; --i) result += chars[Math.floor(Math.random() * chars.length)]; return result; } export function schemaOf(t: DataTypeDef): string | nil { if (t.kind === 'array') { return schemaOf(t.arrayOf); } return t.schema; } export function isType(t: any): t is (_IType | IType) { return !!t?.[isType.TAG]; } isType.TAG = Symbol(); export function suggestColumnName(expr: Expr | nil): string | null { if (!expr) { return null; } // suggest a column result name switch (expr.type) { case 'call': return expr.function.name; case 'ref': return expr.name; case 'keyword': return expr.keyword; case 'cast': return typeDefToStr(expr.to); } return null; } export function findTemplate<T>(this: void, selection: _ISelection, t: _Transaction, template?: T, columns?: (keyof T)[]): Iterable<T> { // === Build an SQL AST expression that matches // this template let expr: Expr | nil; for (const [k, v] of Object.entries(template ?? {})) { let right: Expr; if (nullIsh(v)) { // handle { myprop: null } right = { type: 'unary', op: 'IS NULL', operand: { type: 'ref', name: k, }, }; } else { let value: Expr; let op: BinaryOperator = '='; switch (typeof v) { case 'number': // handle {myprop: 42} value = Number.isInteger(v) ? { type: 'integer', value: v } : { type: 'numeric', value: v }; break; case 'string': // handle {myprop: 'blah'} value = { type: 'string', value: v }; break; case 'object': // handle {myprop: new Date()} if (moment.isMoment(v)) { value = { type: 'string', value: v.toISOString() }; } else if (v instanceof Date) { value = { type: 'string', value: moment(v).toISOString() }; } else { // handle {myprop: {obj: "test"}} op = '@>'; value = { type: 'string', value: JSON.stringify(v), }; } break; default: throw new Error(`Object type of property "${k}" not supported in template`); } right = { type: 'binary', op, left: { type: 'ref', name: k, }, right: value }; } expr = !expr ? right : { type: 'binary', op: 'AND', left: expr, right, }; } // === perform filter let ret = selection .filter(expr); if (columns) { ret = ret.select(columns.map<SelectedColumn>(x => ({ expr: { type: 'ref', name: x as string }, }))); } return ret.enumerate(t); } function ver(v: string) { if (!v || !/^\d+(\.\d+)+$/.test(v)) { throw new Error('Invalid semver ' + v) } return v.split(/\./g).map(x => parseInt(x, 10)); } export function compareVersions(_a: string, _b: string): number { const a = ver(_a); const b = ver(_b); const m = Math.max(a.length, b.length); for (let i = 0; i < m; i++) { const d = (b[i] || 0) - (a[i] || 0); if (d !== 0) { return d; } } return 0; } export function intervalToSec(v: Interval) { return (v.milliseconds ?? 0) / 1000 + (v.seconds ?? 0) + (v.minutes ?? 0) * 60 + (v.hours ?? 0) * 3600 + (v.days ?? 0) * 3600 * 24 + (v.months ?? 0) * 3600 * 24 * 30 + (v.years ?? 0) * 3600 * 24 * 30 * 12; } export function parseRegClass(_reg: RegClass): QName | number { let reg = _reg; if (typeof reg === 'string' && /^\d+$/.test(reg)) { reg = parseInt(reg); } if (typeof reg === 'number') { return reg; } // todo remove casts after next pgsql-ast-parser release try { const ret = parse(reg, 'qualified_name' as any) as QName; return ret; } catch (e) { return { name: reg }; } } const timeReg = /^(\d+):(\d+)(:(\d+))?(\.\d+)?$/; export function parseTime(str: string): moment.Moment { const [_, a, b, __, c, d] = timeReg.exec(str) ?? []; if (!_) { throw new QueryError(`Invalid time format: ` + str); } const ms = d ? parseFloat(d) * 1000 : undefined; let ret: moment.Moment; if (c) { ret = moment.utc({ h: parseInt(a, 10), m: parseInt(b, 10), s: parseInt(c, 10), ms, }); } else { if (d) { ret = moment.utc({ m: parseInt(a, 10), s: parseInt(b, 10), ms, }); } else { ret = moment.utc({ h: parseInt(a, 10), m: parseInt(b, 10), ms, }); } } if (!ret.isValid()) { throw new QueryError(`Invalid time format: ` + str); } return ret; } export function colByName<T>(refs: Map<string, T>, ref: string | ExprRef, nullIfNotFound: boolean | nil): T | nil { const nm = typeof ref === 'string' ? ref : !ref.table ? ref.name : null; const got = nm ? refs.get(nm) : null; if (!got && !nullIfNotFound) { throw new ColumnNotFound(colToStr(ref)); } return got; } export function colToStr(col: string | ExprRef) { if (typeof col === 'string') { return col; } if (!col.table) { return col.name; } return col.table.name + '.' + col.name; } export function qnameToStr(col: string | QName) { if (typeof col === 'string') { return col; } if (!col.schema) { return col.name; } return col.schema + '.' + col.name; } export function asSingleName(col: string | ExprRef): string | nil { if (typeof col === 'string') { return col; } if (col.table) { return null; } return col.name; } export function asSingleQName(col: string | QName, allowedSchema?: string): string | nil { if (typeof col === 'string') { return col; } if (col.schema && col.schema !== allowedSchema) { return null; } return col.name; } export function errorMessage(error: unknown): string { if (typeof error === 'string') { return error; } if (typeof error !== 'object') { return 'Unkown error message'; } return (error as any)?.message; }
the_stack
import { SENSITIVE_STRING } from "@aws-sdk/smithy-client"; import { MetadataBearer as $MetadataBearer, SmithyException as __SmithyException } from "@aws-sdk/types"; export interface CloseTunnelRequest { /** * <p>The ID of the tunnel to close.</p> */ tunnelId: string | undefined; /** * <p>When set to true, AWS IoT Secure Tunneling deletes the tunnel data * immediately.</p> */ delete?: boolean; } export namespace CloseTunnelRequest { /** * @internal */ export const filterSensitiveLog = (obj: CloseTunnelRequest): any => ({ ...obj, }); } export interface CloseTunnelResponse {} export namespace CloseTunnelResponse { /** * @internal */ export const filterSensitiveLog = (obj: CloseTunnelResponse): any => ({ ...obj, }); } /** * <p>Thrown when an operation is attempted on a resource that does not exist.</p> */ export interface ResourceNotFoundException extends __SmithyException, $MetadataBearer { name: "ResourceNotFoundException"; $fault: "client"; message?: string; } export namespace ResourceNotFoundException { /** * @internal */ export const filterSensitiveLog = (obj: ResourceNotFoundException): any => ({ ...obj, }); } export enum ConnectionStatus { CONNECTED = "CONNECTED", DISCONNECTED = "DISCONNECTED", } /** * <p>The state of a connection.</p> */ export interface ConnectionState { /** * <p>The connection status of the tunnel. Valid values are <code>CONNECTED</code> and * <code>DISCONNECTED</code>.</p> */ status?: ConnectionStatus | string; /** * <p>The last time the connection status was updated.</p> */ lastUpdatedAt?: Date; } export namespace ConnectionState { /** * @internal */ export const filterSensitiveLog = (obj: ConnectionState): any => ({ ...obj, }); } export interface DescribeTunnelRequest { /** * <p>The tunnel to describe.</p> */ tunnelId: string | undefined; } export namespace DescribeTunnelRequest { /** * @internal */ export const filterSensitiveLog = (obj: DescribeTunnelRequest): any => ({ ...obj, }); } /** * <p>The destination configuration.</p> */ export interface DestinationConfig { /** * <p>The name of the IoT thing to which you want to connect.</p> */ thingName?: string; /** * <p>A list of service names that identity the target application. The AWS IoT client running on the destination device reads * this value and uses it to look up a port or an IP address and a port. The AWS IoT client * instantiates the local proxy which uses this information to connect to the destination * application.</p> */ services: string[] | undefined; } export namespace DestinationConfig { /** * @internal */ export const filterSensitiveLog = (obj: DestinationConfig): any => ({ ...obj, }); } export enum TunnelStatus { CLOSED = "CLOSED", OPEN = "OPEN", } /** * <p>An arbitary key/value pair used to add searchable metadata to secure tunnel * resources.</p> */ export interface Tag { /** * <p>The key of the tag.</p> */ key: string | undefined; /** * <p>The value of the tag.</p> */ value: string | undefined; } export namespace Tag { /** * @internal */ export const filterSensitiveLog = (obj: Tag): any => ({ ...obj, }); } /** * <p>Tunnel timeout configuration.</p> */ export interface TimeoutConfig { /** * <p>The maximum amount of time (in minutes) a tunnel can remain open. If not specified, * maxLifetimeTimeoutMinutes defaults to 720 minutes. Valid values are from 1 minute to 12 * hours (720 minutes) </p> */ maxLifetimeTimeoutMinutes?: number; } export namespace TimeoutConfig { /** * @internal */ export const filterSensitiveLog = (obj: TimeoutConfig): any => ({ ...obj, }); } /** * <p>A connection between a source computer and a destination device.</p> */ export interface Tunnel { /** * <p>A unique alpha-numeric ID that identifies a tunnel.</p> */ tunnelId?: string; /** * <p>The Amazon Resource Name (ARN) of a tunnel. The tunnel ARN format is * <code>arn:aws:tunnel:<region>:<account-id>:tunnel/<tunnel-id></code> * </p> */ tunnelArn?: string; /** * <p>The status of a tunnel. Valid values are: Open and Closed.</p> */ status?: TunnelStatus | string; /** * <p>The connection state of the source application.</p> */ sourceConnectionState?: ConnectionState; /** * <p>The connection state of the destination application.</p> */ destinationConnectionState?: ConnectionState; /** * <p>A description of the tunnel.</p> */ description?: string; /** * <p>The destination configuration that specifies the thing name of the destination * device and a service name that the local proxy uses to connect to the destination * application.</p> */ destinationConfig?: DestinationConfig; /** * <p>Timeout configuration for the tunnel.</p> */ timeoutConfig?: TimeoutConfig; /** * <p>A list of tag metadata associated with the secure tunnel.</p> */ tags?: Tag[]; /** * <p>The time when the tunnel was created.</p> */ createdAt?: Date; /** * <p>The last time the tunnel was updated.</p> */ lastUpdatedAt?: Date; } export namespace Tunnel { /** * @internal */ export const filterSensitiveLog = (obj: Tunnel): any => ({ ...obj, }); } export interface DescribeTunnelResponse { /** * <p>The tunnel being described.</p> */ tunnel?: Tunnel; } export namespace DescribeTunnelResponse { /** * @internal */ export const filterSensitiveLog = (obj: DescribeTunnelResponse): any => ({ ...obj, }); } export interface ListTagsForResourceRequest { /** * <p>The resource ARN.</p> */ resourceArn: string | undefined; } export namespace ListTagsForResourceRequest { /** * @internal */ export const filterSensitiveLog = (obj: ListTagsForResourceRequest): any => ({ ...obj, }); } export interface ListTagsForResourceResponse { /** * <p>The tags for the specified resource.</p> */ tags?: Tag[]; } export namespace ListTagsForResourceResponse { /** * @internal */ export const filterSensitiveLog = (obj: ListTagsForResourceResponse): any => ({ ...obj, }); } export interface ListTunnelsRequest { /** * <p>The name of the IoT thing associated with the destination device.</p> */ thingName?: string; /** * <p>The maximum number of results to return at once.</p> */ maxResults?: number; /** * <p>A token to retrieve the next set of results.</p> */ nextToken?: string; } export namespace ListTunnelsRequest { /** * @internal */ export const filterSensitiveLog = (obj: ListTunnelsRequest): any => ({ ...obj, }); } /** * <p>Information about the tunnel.</p> */ export interface TunnelSummary { /** * <p>The unique alpha-numeric identifier for the tunnel.</p> */ tunnelId?: string; /** * <p>The Amazon Resource Name of the tunnel. The tunnel ARN format is * <code>arn:aws:tunnel:<region>:<account-id>:tunnel/<tunnel-id></code> * </p> */ tunnelArn?: string; /** * <p>The status of a tunnel. Valid values are: Open and Closed.</p> */ status?: TunnelStatus | string; /** * <p>A description of the tunnel.</p> */ description?: string; /** * <p>The time the tunnel was created.</p> */ createdAt?: Date; /** * <p>The time the tunnel was last updated.</p> */ lastUpdatedAt?: Date; } export namespace TunnelSummary { /** * @internal */ export const filterSensitiveLog = (obj: TunnelSummary): any => ({ ...obj, }); } export interface ListTunnelsResponse { /** * <p>A short description of the tunnels in an AWS account.</p> */ tunnelSummaries?: TunnelSummary[]; /** * <p>A token to used to retrieve the next set of results.</p> */ nextToken?: string; } export namespace ListTunnelsResponse { /** * @internal */ export const filterSensitiveLog = (obj: ListTunnelsResponse): any => ({ ...obj, }); } /** * <p>Thrown when a tunnel limit is exceeded.</p> */ export interface LimitExceededException extends __SmithyException, $MetadataBearer { name: "LimitExceededException"; $fault: "client"; message?: string; } export namespace LimitExceededException { /** * @internal */ export const filterSensitiveLog = (obj: LimitExceededException): any => ({ ...obj, }); } export interface OpenTunnelRequest { /** * <p>A short text description of the tunnel. </p> */ description?: string; /** * <p>A collection of tag metadata.</p> */ tags?: Tag[]; /** * <p>The destination configuration for the OpenTunnel request.</p> */ destinationConfig?: DestinationConfig; /** * <p>Timeout configuration for a tunnel.</p> */ timeoutConfig?: TimeoutConfig; } export namespace OpenTunnelRequest { /** * @internal */ export const filterSensitiveLog = (obj: OpenTunnelRequest): any => ({ ...obj, }); } export interface OpenTunnelResponse { /** * <p>A unique alpha-numeric tunnel ID.</p> */ tunnelId?: string; /** * <p>The Amazon Resource Name for the tunnel. The tunnel ARN format is * <code>arn:aws:tunnel:<region>:<account-id>:tunnel/<tunnel-id></code> * </p> */ tunnelArn?: string; /** * <p>The access token the source local proxy uses to connect to AWS IoT Secure * Tunneling.</p> */ sourceAccessToken?: string; /** * <p>The access token the destination local proxy uses to connect to AWS IoT Secure * Tunneling.</p> */ destinationAccessToken?: string; } export namespace OpenTunnelResponse { /** * @internal */ export const filterSensitiveLog = (obj: OpenTunnelResponse): any => ({ ...obj, ...(obj.sourceAccessToken && { sourceAccessToken: SENSITIVE_STRING }), ...(obj.destinationAccessToken && { destinationAccessToken: SENSITIVE_STRING }), }); } export interface TagResourceRequest { /** * <p>The ARN of the resource.</p> */ resourceArn: string | undefined; /** * <p>The tags for the resource.</p> */ tags: Tag[] | undefined; } export namespace TagResourceRequest { /** * @internal */ export const filterSensitiveLog = (obj: TagResourceRequest): any => ({ ...obj, }); } export interface TagResourceResponse {} export namespace TagResourceResponse { /** * @internal */ export const filterSensitiveLog = (obj: TagResourceResponse): any => ({ ...obj, }); } export interface UntagResourceRequest { /** * <p>The resource ARN.</p> */ resourceArn: string | undefined; /** * <p>The keys of the tags to remove.</p> */ tagKeys: string[] | undefined; } export namespace UntagResourceRequest { /** * @internal */ export const filterSensitiveLog = (obj: UntagResourceRequest): any => ({ ...obj, }); } export interface UntagResourceResponse {} export namespace UntagResourceResponse { /** * @internal */ export const filterSensitiveLog = (obj: UntagResourceResponse): any => ({ ...obj, }); }
the_stack
import { FastifyRequest } from 'fastify'; import { CardanoService } from '../services/cardano-services'; import { ConstructionService } from '../services/construction-service'; import { constructPayloadsForTransactionBody, decodeExtraData, encodeExtraData, getNetworkIdentifierByRequestParameters, mapAmount, mapToConstructionHashResponse } from '../utils/data-mapper'; import { ErrorFactory, ErrorUtils } from '../utils/errors'; import { withNetworkValidation } from './controllers-helper'; import { CardanoCli } from '../utils/cardano/cli/cardanonode-cli'; import { NetworkService } from '../services/network-service'; import { AddressType } from '../utils/constants'; import { isAddressTypeValid, isKeyValid } from '../utils/validations'; import { BlockService } from '../services/block-service'; import ApiError from '../api-error'; export interface ConstructionController { constructionDerive( request: FastifyRequest<unknown, unknown, unknown, unknown, Components.Schemas.ConstructionDeriveRequest> ): Promise<Components.Schemas.ConstructionDeriveResponse | Components.Schemas.Error>; constructionPreprocess( request: FastifyRequest<unknown, unknown, unknown, unknown, Components.Schemas.ConstructionPreprocessRequest> ): Promise<Components.Schemas.ConstructionPreprocessResponse | Components.Schemas.Error>; constructionMetadata( request: FastifyRequest<unknown, unknown, unknown, unknown, Components.Schemas.ConstructionMetadataRequest> ): Promise<Components.Schemas.ConstructionMetadataResponse | Components.Schemas.Error>; constructionPayloads( request: FastifyRequest<unknown, unknown, unknown, unknown, Components.Schemas.ConstructionPayloadsRequest> ): Promise<Components.Schemas.ConstructionPayloadsResponse | Components.Schemas.Error>; constructionCombine( request: FastifyRequest<unknown, unknown, unknown, unknown, Components.Schemas.ConstructionCombineRequest> ): Promise<Components.Schemas.ConstructionCombineResponse | Components.Schemas.Error>; constructionParse( request: FastifyRequest<unknown, unknown, unknown, unknown, Components.Schemas.ConstructionParseRequest> ): Promise<Components.Schemas.ConstructionParseResponse | Components.Schemas.Error>; constructionHash( request: FastifyRequest<unknown, unknown, unknown, unknown, Components.Schemas.ConstructionHashRequest> ): Promise<Components.Schemas.TransactionIdentifierResponse | Components.Schemas.Error>; constructionSubmit( request: FastifyRequest<unknown, unknown, unknown, unknown, Components.Schemas.ConstructionSubmitRequest> ): Promise<Components.Schemas.TransactionIdentifierResponse | Components.Schemas.Error>; } const configure = ( constructionService: ConstructionService, cardanoService: CardanoService, cardanoCli: CardanoCli, networkService: NetworkService, blockService: BlockService ): ConstructionController => ({ constructionDerive: async request => withNetworkValidation( request.body.network_identifier, request, async () => { const logger = request.log; const publicKey = request.body.public_key; const networkIdentifier = getNetworkIdentifierByRequestParameters(request.body.network_identifier); logger.info('[constructionDerive] About to check if public key has valid length and curve type'); if (!isKeyValid(publicKey.hex_bytes, publicKey.curve_type)) { logger.info('[constructionDerive] Public key has an invalid format'); throw ErrorFactory.invalidPublicKeyFormat(); } logger.info('[constructionDerive] Public key has a valid format'); // eslint-disable-next-line camelcase const stakingCredential = request.body.metadata?.staking_credential; if (stakingCredential) { logger.info('[constructionDerive] About to check if staking credential has valid length and curve type'); if (!isKeyValid(stakingCredential.hex_bytes, stakingCredential.curve_type)) { logger.info('[constructionDerive] Staking credential has an invalid format'); throw ErrorFactory.invalidStakingKeyFormat(); } logger.info('[constructionDerive] Staking credential key has a valid format'); } // eslint-disable-next-line camelcase const addressType = request.body.metadata?.address_type; if (addressType) { logger.info('[constructionDerive] About to check if address type is valid'); if (!isAddressTypeValid(addressType)) { logger.info('[constructionDerive] Address type has an invalid value'); throw ErrorFactory.invalidAddressTypeError(); } logger.info('[constructionDerive] Address type has a valid value'); } logger.info(request.body, '[constructionDerive] About to generate address'); const address = cardanoService.generateAddress( logger, networkIdentifier, publicKey.hex_bytes, // eslint-disable-next-line camelcase stakingCredential?.hex_bytes, addressType as AddressType ); if (!address) { logger.error('[constructionDerive] There was an error generating address'); throw ErrorFactory.addressGenerationError(); } logger.info(`[constructionDerive] new address is ${address}`); return { // eslint-disable-next-line camelcase account_identifier: { address } }; }, request.log, networkService ), constructionHash: async request => withNetworkValidation( request.body.network_identifier, request, async () => { const logger = request.log; const [signedTransaction] = await decodeExtraData(request.body.signed_transaction); logger.info('[constructionHash] About to get hash of signed transaction'); const transactionHash = cardanoService.getHashOfSignedTransaction(logger, signedTransaction); logger.info('[constructionHash] About to return hash of signed transaction'); // eslint-disable-next-line camelcase return mapToConstructionHashResponse(transactionHash); }, request.log, networkService ), constructionPreprocess: async request => withNetworkValidation( request.body.network_identifier, request, async () => { const networkIdentifier = getNetworkIdentifierByRequestParameters(request.body.network_identifier); // eslint-disable-next-line camelcase const relativeTtl = constructionService.calculateRelativeTtl(request.body.metadata?.relative_ttl); const transactionSize = cardanoService.calculateTxSize( request.log, networkIdentifier, request.body.operations, 0 ); // eslint-disable-next-line camelcase return { options: { relative_ttl: relativeTtl, transaction_size: transactionSize } }; }, request.log, networkService ), constructionMetadata: async request => withNetworkValidation( request.body.network_identifier, request, async () => { const logger = request.log; const ttlOffset = request.body.options.relative_ttl; const txSize = request.body.options.transaction_size; logger.debug(`[constructionMetadata] Calculating ttl based on ${ttlOffset} relative ttl`); const ttl = await constructionService.calculateTtl(request.log, ttlOffset); logger.debug(`[constructionMetadata] ttl is ${ttl}`); // As we have calculated tx assuming ttl as 0, we need to properly update the size // now that we have it already logger.debug(`[constructionMetadata] updating tx size from ${txSize}`); const updatedTxSize = cardanoService.updateTxSize(txSize, 0, ttl); const linearFeeParameters = await blockService.getLinearFeeParameters(logger); logger.debug(`[constructionMetadata] gotten linear fee parameters from block-service ${linearFeeParameters}`); logger.debug(`[constructionMetadata] updated txSize size is ${updatedTxSize}`); const suggestedFee: BigInt = cardanoService.calculateTxMinimumFee(updatedTxSize, linearFeeParameters); logger.debug(`[constructionMetadata] suggested fee is ${suggestedFee}`); // eslint-disable-next-line camelcase return { metadata: { ttl: ttl.toString() }, suggested_fee: [mapAmount(suggestedFee.toString())] }; }, request.log, networkService ), constructionPayloads: async request => withNetworkValidation( request.body.network_identifier, request, async () => { const logger = request.log; const ttl = request.body.metadata.ttl; const operations = request.body.operations; const networkIdentifier = getNetworkIdentifierByRequestParameters(request.body.network_identifier); logger.info(operations, '[constuctionPayloads] Operations about to be processed'); const unsignedTransaction = cardanoService.createUnsignedTransaction( logger, networkIdentifier, operations, parseInt(ttl) ); const payloads = constructPayloadsForTransactionBody(unsignedTransaction.hash, unsignedTransaction.addresses); return { /* eslint-disable camelcase */ unsigned_transaction: await encodeExtraData(unsignedTransaction.bytes, { operations: request.body.operations, transactionMetadataHex: unsignedTransaction.metadata }), /* eslint-disable camelcase */ payloads }; }, request.log, networkService ), constructionCombine: async request => withNetworkValidation( request.body.network_identifier, request, async () => { const logger = request.log; logger.info('[constructionCombine] Request received to sign a transaction'); const [transaction, extraData] = await decodeExtraData(request.body.unsigned_transaction); const { transactionMetadataHex } = extraData; const signedTransaction = cardanoService.buildTransaction( logger, transaction, request.body.signatures.map(signature => ({ signature: signature.hex_bytes, publicKey: signature.public_key.hex_bytes, address: signature.signing_payload.account_identifier?.address, chainCode: signature.signing_payload.account_identifier?.metadata?.chain_code })), transactionMetadataHex ); logger.info({ signedTransaction }, '[constructionCombine] About to return signed transaction'); // eslint-disable-next-line camelcase return { signed_transaction: await encodeExtraData(signedTransaction, extraData) }; }, request.log, networkService ), constructionParse: async request => withNetworkValidation( request.body.network_identifier, request, async () => { const logger = request.log; const signed = request.body.signed; const networkIdentifier = getNetworkIdentifierByRequestParameters(request.body.network_identifier); logger.info(request.body.transaction, '[constructionParse] Processing'); const [transaction, extraData] = await decodeExtraData(request.body.transaction); logger.info({ transaction, extraData }, '[constructionParse] Decoded'); if (signed) { return { // eslint-disable-next-line camelcase network_identifier: request.body.network_identifier, ...cardanoService.parseSignedTransaction(logger, networkIdentifier, transaction, extraData) }; } return { // eslint-disable-next-line camelcase network_identifier: request.body.network_identifier, ...cardanoService.parseUnsignedTransaction(logger, networkIdentifier, transaction, extraData) }; }, request.log, networkService ), constructionSubmit: async request => withNetworkValidation( request.body.network_identifier, request, async () => { try { const logger = request.log; const [signedTransaction] = await decodeExtraData(request.body.signed_transaction); logger.info(`[constructionSubmit] About to submit ${signedTransaction}`); await cardanoCli.submitTransaction( logger, signedTransaction, request.body.network_identifier.network === 'mainnet' ); logger.info('[constructionHash] About to get hash of signed transaction'); const transactionHash = cardanoService.getHashOfSignedTransaction(logger, signedTransaction); // eslint-disable-next-line camelcase return { transaction_identifier: { hash: transactionHash } }; } catch (error) { request.log.error(error); return ErrorUtils.resolveApiErrorFromNodeError(error.message) .then((mappedError: ApiError) => mappedError) .catch(() => ErrorFactory.sendTransactionError(error.message)); } }, request.log, networkService ) }); export default configure;
the_stack
* Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ import fetch from 'node-fetch'; import { RequestInfo, RequestInit } from 'node-fetch'; import { LUISRuntimeModels as LuisModels } from '@azure/cognitiveservices-luis-runtime'; import { LuisApplication, LuisRecognizerOptionsV3 } from './luisRecognizer'; import { LuisRecognizerInternal } from './luisRecognizerOptions'; import { NullTelemetryClient, TurnContext, RecognizerResult } from 'botbuilder-core'; import { DialogContext } from 'botbuilder-dialogs'; import { ExternalEntity, validateExternalEntity } from './externalEntity'; import { validateDynamicList } from './dynamicList'; import * as z from 'zod'; const LUIS_TRACE_TYPE = 'https://www.luis.ai/schemas/trace'; const LUIS_TRACE_NAME = 'LuisRecognizer'; const LUIS_TRACE_LABEL = 'LuisV3 Trace'; const _dateSubtypes = ['date', 'daterange', 'datetime', 'datetimerange', 'duration', 'set', 'time', 'timerange']; const _geographySubtypes = ['poi', 'city', 'countryRegion', 'continent', 'state']; const MetadataKey = '$instance'; /** * Validates if the options provided are valid [LuisRecognizerOptionsV3](xref:botbuilder-ai.LuisRecognizerOptionsV3). * * @param {any} options options to type test * @returns {boolean} A boolean value that indicates param options is a [LuisRecognizerOptionsV3](xref:botbuilder-ai.LuisRecognizerOptionsV3). */ export function isLuisRecognizerOptionsV3(options: unknown): options is LuisRecognizerOptionsV3 { // eslint-disable-next-line @typescript-eslint/no-explicit-any return (options as any).apiVersion && (options as any).apiVersion === 'v3'; } /** * Recognize intents in a user utterance using a configured LUIS model. */ export class LuisRecognizerV3 extends LuisRecognizerInternal { /** * Creates a new [LuisRecognizerV3](xref:botbuilder-ai.LuisRecognizerV3) instance. * * @param {LuisApplication} application An object conforming to the [LuisApplication](xref:botbuilder-ai.LuisApplication) definition or a string representing a LUIS application endpoint, usually retrieved from https://luis.ai. * @param {LuisRecognizerOptionsV3} options Optional. Options object used to control predictions. Should conform to the [LuisRecognizerOptionsV3](xref:botbuilder-ai.LuisRecognizerOptionsV3) definition. */ constructor(application: LuisApplication, options?: LuisRecognizerOptionsV3) { super(application); this.predictionOptions = { includeAllIntents: false, includeInstanceData: true, log: true, preferExternalEntities: true, datetimeReference: '', slot: 'production', telemetryClient: new NullTelemetryClient(), logPersonalInformation: false, includeAPIResults: true, ...options, }; } predictionOptions: LuisRecognizerOptionsV3; /** * Calls LUIS to recognize intents and entities in a users utterance. * * @param {TurnContext} context The [TurnContext](xref:botbuilder-core.TurnContext). * @returns {Promise<RecognizerResult>} Analysis of utterance in form of [RecognizerResult](xref:botbuilder-core.RecognizerResult). */ async recognizeInternal(context: DialogContext | TurnContext): Promise<RecognizerResult>; /** * Calls LUIS to recognize intents and entities in a users utterance. * * @param {string} utterance The utterance to be recognized. */ async recognizeInternal(utterance: string): Promise<RecognizerResult>; /** * @internal */ async recognizeInternal(contextOrUtterance: DialogContext | TurnContext | string): Promise<RecognizerResult> { if (typeof contextOrUtterance === 'string') { const utterance = contextOrUtterance; return this.recognize(null, utterance, this.predictionOptions); } else { if (contextOrUtterance instanceof DialogContext) { const dialogContext = contextOrUtterance; const activity = dialogContext.context.activity; let options = this.predictionOptions; if (options.externalEntityRecognizer) { // call external entity recognizer const matches = await options.externalEntityRecognizer.recognize(dialogContext, activity); // TODO: checking for 'text' because we get an extra non-real entity from the text recognizers if (matches.entities && Object.entries(matches.entities).length) { options = { apiVersion: 'v3', externalEntities: [], }; const entities = matches.entities; const instance = entities['$instance']; if (instance) { Object.entries(entities) .filter(([key, _value]) => key !== 'text' && key !== '$instance') .reduce((externalEntities: ExternalEntity[], [key, value]) => { const instances: unknown[] = instance[`${key}`]; const values: unknown[] = Array.isArray(value) ? value : []; if (instances?.length === values?.length) { instances.forEach((childInstance) => { if ( z .object({ startIndex: z.number(), endIndex: z.number() }) .nonstrict() .check(childInstance) ) { const start = childInstance.startIndex; const end = childInstance.endIndex; externalEntities.push({ entityName: key, startIndex: start, entityLength: end - start, resolution: value, }); } }); } return externalEntities; }, options.externalEntities); } } } // call luis recognizer with options.externalEntities populated from externalEntityRecognizer return this.recognize(dialogContext.context, activity?.text ?? '', options); } else { const turnContext = contextOrUtterance; return this.recognize(turnContext, turnContext?.activity?.text ?? '', this.predictionOptions); } } } private async recognize( context: TurnContext, utterance: string, options: LuisRecognizerOptionsV3 ): Promise<RecognizerResult> { if (!utterance.trim()) { // Bypass LUIS if the activity's text is null or whitespace return Promise.resolve({ text: utterance, intents: {}, entities: {}, }); } const uri = this.buildUrl(options); const httpOptions = this.buildRequestBody(utterance, options); const data = await fetch(uri, httpOptions); const response = await data.json(); if (response.error) { const errObj = response.error; const errMessage = errObj.code ? `${errObj.code}: ${errObj.message}` : errObj.message; throw new Error(`[LUIS Recognition Error]: ${errMessage}`); } const result: RecognizerResult = { text: utterance, intents: getIntents(response.prediction), entities: extractEntitiesAndMetadata(response.prediction), sentiment: getSentiment(response.prediction), luisResult: this.predictionOptions.includeAPIResults ? response : null, }; if (this.predictionOptions.includeInstanceData) { result.entities[MetadataKey] = result.entities[MetadataKey] ? result.entities[MetadataKey] : {}; } // Intentionally not using "context != null" (loose inequality) check here because context should explicitly be null from the // internal recognizeInternal() "if (typeof contextOrUtterance === 'string')" block. This route is taken // when recognize is called with a string utterance and not a TurnContext. So, if context is undefined (not null) // at this point, we have a bigger issue that needs to be caught. if (context !== null) { this.emitTraceInfo(context, response.prediction, result, options); } return result; } private buildUrl(options: LuisRecognizerOptionsV3): RequestInfo { const baseUri = this.application.endpoint || 'https://westus.api.cognitive.microsoft.com'; let uri = `${baseUri}/luis/prediction/v3.0/apps/${this.application.applicationId}`; if (options.version) { uri += `/versions/${options.version}/predict`; } else { uri += `/slots/${options.slot}/predict`; } const params = `?verbose=${options.includeInstanceData}&log=${options.log}&show-all-intents=${options.includeAllIntents}`; uri += params; return uri; } private buildRequestBody(utterance: string, options: LuisRecognizerOptionsV3): RequestInit { const content = { query: utterance, options: { preferExternalEntities: options.preferExternalEntities, }, }; if (options.datetimeReference) { content.options['datetimeReference'] = options.datetimeReference; } if (options.dynamicLists) { options.dynamicLists.forEach((list) => validateDynamicList(list)); content['dynamicLists'] = options.dynamicLists; } if (options.externalEntities) { options.externalEntities.forEach((entity) => validateExternalEntity(entity)); content['externalEntities'] = options.externalEntities; } return { method: 'POST', body: JSON.stringify(content), headers: { 'Content-Type': 'application/json', 'Ocp-Apim-Subscription-Key': this.application.endpointKey, }, }; } private emitTraceInfo( context: TurnContext, luisResult: LuisModels.LuisResult, recognizerResult: RecognizerResult, options: LuisRecognizerOptionsV3 ): Promise<unknown> { const traceInfo = { recognizerResult: recognizerResult, luisResult: luisResult, luisOptions: options, luisModel: { ModelID: this.application.applicationId, }, }; return context.sendActivity({ type: 'trace', valueType: LUIS_TRACE_TYPE, name: LUIS_TRACE_NAME, label: LUIS_TRACE_LABEL, value: traceInfo, }); } } function normalizeName(name) { return name.replace(/\.| /g, '_'); } function getIntents(luisResult) { // let intents: { [name: string]: { score: number } } = {}; const intents = {}; if (luisResult.intents) { for (const intent in luisResult.intents) { intents[normalizeName(intent)] = { score: luisResult.intents[intent].score }; } } return intents; } function normalizeEntity(entity) { const splitEntity = entity.split(':'); const entityName = splitEntity[splitEntity.length - 1]; return entityName.replace(/\.| /g, '_'); } function mapProperties(source, inInstance) { let result = source; if (source instanceof Array) { const narr = []; for (const item of source) { // Check if element is geographyV2 let isGeographyV2 = ''; if (item['type'] && _geographySubtypes.includes(item['type'])) { isGeographyV2 = item['type']; } if (!inInstance && isGeographyV2) { const geoEntity: Partial<Record<'location' | 'type', string>> = {}; for (const itemProps in item) { if (itemProps === 'value') { geoEntity.location = item[itemProps]; } } geoEntity.type = isGeographyV2; narr.push(geoEntity); } else { narr.push(mapProperties(item, inInstance)); } } result = narr; } else if (source instanceof Object && typeof source !== 'string') { const nobj: Partial<{ datetime: unknown; datetimeV1: unknown; type: string; timex: unknown[]; units: unknown; }> = {}; // Fix datetime by reverting to simple timex if (!inInstance && source.type && typeof source.type === 'string' && _dateSubtypes.includes(source.type)) { const timexs = source.values; const arr = []; if (timexs) { const unique = []; for (const elt of timexs) { if (elt.timex && !unique.includes(elt.timex)) { unique.push(elt.timex); } } for (const timex of unique) { arr.push(timex); } nobj.timex = arr; } nobj.type = source.type; } else { // Map or remove properties for (const property in source) { const name = normalizeEntity(property); const isArray = source[property] instanceof Array; const isString = typeof source[property] === 'string'; const isInt = Number.isInteger(source[property]); const val = mapProperties(source[property], inInstance || property == MetadataKey); if (name == 'datetime' && isArray) { nobj.datetimeV1 = val; } else if (name == 'datetimeV2' && isArray) { nobj.datetime = val; } else if (inInstance) { // Correct $instance issues if (name == 'length' && isInt) { nobj['endIndex'] = source[name] + source.startIndex; } else if (!((isInt && name === 'modelTypeId') || (isString && name === 'role'))) { nobj[name] = val; } } else { // Correct non-$instance values if (name == 'unit' && isString) { nobj.units = val; } else { nobj[name] = val; } } } } result = nobj; } return result; } function extractEntitiesAndMetadata(prediction) { const entities = prediction.entities; return mapProperties(entities, false); } function getSentiment(luis): Record<'label' | 'score', unknown> | undefined { if (luis.sentiment) { return { label: luis.sentiment.label, score: luis.sentiment.score, }; } }
the_stack
import path from 'path'; import { StructureDefinitionExporter, Package } from '../../src/export'; import { FSHTank, FSHDocument } from '../../src/import'; import { FHIRDefinitions, loadFromPath } from '../../src/fhirdefs'; import { Resource } from '../../src/fshtypes'; import { loggerSpy } from '../testhelpers/loggerSpy'; import { TestFisher } from '../testhelpers'; import { minimalConfig } from '../utils/minimalConfig'; import { AddElementRule, CardRule, CaretValueRule, ContainsRule, FlagRule } from '../../src/fshtypes/rules'; describe('ResourceExporter', () => { let defs: FHIRDefinitions; let doc: FSHDocument; let pkg: Package; let exporter: StructureDefinitionExporter; beforeAll(() => { defs = new FHIRDefinitions(); loadFromPath(path.join(__dirname, '..', 'testhelpers', 'testdefs'), 'r4-definitions', defs); }); beforeEach(() => { loggerSpy.reset(); doc = new FSHDocument('fileName'); const input = new FSHTank([doc], minimalConfig); pkg = new Package(input.config); const fisher = new TestFisher(input, defs, pkg); exporter = new StructureDefinitionExporter(input, pkg, fisher); }); it('should output empty results with empty input', () => { const exported = exporter.export().resources; expect(exported).toEqual([]); }); it('should export a single resource', () => { const resource = new Resource('Foo'); doc.resources.set(resource.name, resource); const exported = exporter.export().resources; expect(exported.length).toBe(1); }); it('should export multiple resources', () => { const resourceFoo = new Resource('Foo'); const resourceBar = new Resource('Bar'); doc.resources.set(resourceFoo.name, resourceFoo); doc.resources.set(resourceBar.name, resourceBar); const exported = exporter.export().resources; expect(exported.length).toBe(2); }); it('should still export resources if one fails', () => { const resourceFoo = new Resource('Foo'); resourceFoo.parent = 'Baz'; // invalid parent cause failure const resourceBar = new Resource('Bar'); doc.resources.set(resourceFoo.name, resourceFoo); doc.resources.set(resourceBar.name, resourceBar); const exported = exporter.export().resources; expect(exported.length).toBe(1); expect(exported[0].name).toBe('Bar'); }); it('should export resource with Resource parent by id', () => { const resource = new Resource('Foo'); resource.parent = 'Resource'; doc.resources.set(resource.name, resource); const exported = exporter.export().resources; expect(exported.length).toBe(1); expect(exported[0].name).toBe('Foo'); expect(exported[0].baseDefinition).toBe('http://hl7.org/fhir/StructureDefinition/Resource'); }); it('should export resource with Resource parent by url', () => { const resource = new Resource('Foo'); resource.parent = 'http://hl7.org/fhir/StructureDefinition/Resource'; doc.resources.set(resource.name, resource); const exported = exporter.export().resources; expect(exported.length).toBe(1); expect(exported[0].name).toBe('Foo'); expect(exported[0].baseDefinition).toBe('http://hl7.org/fhir/StructureDefinition/Resource'); }); it('should export resource with DomainResource parent by id', () => { const resource = new Resource('Foo'); resource.parent = 'DomainResource'; doc.resources.set(resource.name, resource); const exported = exporter.export().resources; expect(exported.length).toBe(1); expect(exported[0].name).toBe('Foo'); expect(exported[0].baseDefinition).toBe( 'http://hl7.org/fhir/StructureDefinition/DomainResource' ); }); it('should export resource with DomainResource parent by url', () => { const resource = new Resource('Foo'); resource.parent = 'http://hl7.org/fhir/StructureDefinition/DomainResource'; doc.resources.set(resource.name, resource); const exported = exporter.export().resources; expect(exported.length).toBe(1); expect(exported[0].name).toBe('Foo'); expect(exported[0].baseDefinition).toBe( 'http://hl7.org/fhir/StructureDefinition/DomainResource' ); }); it('should export resource with DomainResource parent when parent not specified', () => { const resource = new Resource('Foo'); doc.resources.set(resource.name, resource); const exported = exporter.export().resources; expect(exported.length).toBe(1); expect(exported[0].name).toBe('Foo'); expect(exported[0].baseDefinition).toBe( 'http://hl7.org/fhir/StructureDefinition/DomainResource' ); }); it('should log an error with source information when the parent is invalid', () => { const resource = new Resource('BadParent') .withFile('BadParent.fsh') .withLocation([2, 9, 4, 23]); resource.parent = 'Basic'; doc.resources.set(resource.name, resource); exporter.export(); expect(loggerSpy.getLastMessage('error')).toMatch(/File: BadParent\.fsh.*Line: 2 - 4\D*/s); expect(loggerSpy.getLastMessage('error')).toMatch( /The parent of a resource must be Resource or DomainResource./s ); }); it('should log an error with source information when the parent is not found', () => { const resource = new Resource('Bogus').withFile('Bogus.fsh').withLocation([2, 9, 4, 23]); resource.parent = 'BogusParent'; doc.resources.set(resource.name, resource); exporter.export(); expect(loggerSpy.getLastMessage('error')).toMatch(/File: Bogus\.fsh.*Line: 2 - 4\D*/s); expect(loggerSpy.getLastMessage('error')).toMatch(/Parent BogusParent not found for Bogus/s); }); it('should log an error when an inline extension is used', () => { const resource = new Resource('MyResource'); const addElementRule = new AddElementRule('myExtension'); addElementRule.min = 0; addElementRule.max = '*'; addElementRule.types = [{ type: 'Extension' }]; addElementRule.short = 'short definition'; resource.rules.push(addElementRule); const containsRule = new ContainsRule('myExtension') .withFile('MyResource.fsh') .withLocation([3, 8, 3, 25]); containsRule.items.push({ name: 'SomeExtension' }); resource.rules.push(containsRule); doc.resources.set(resource.name, resource); exporter.export(); expect(loggerSpy.getLastMessage('error')).toMatch(/File: MyResource\.fsh.*Line: 3\D*/s); expect(loggerSpy.getLastMessage('error')).toMatch( /Use of 'ContainsRule' is not permitted for 'Resource'/s ); }); it('should allow constraints on newly added elements and sub-elements', () => { const resource = new Resource('ExampleResource'); resource.id = 'ExampleResource'; const addElementRule = new AddElementRule('name'); addElementRule.min = 0; addElementRule.max = '*'; addElementRule.types = [{ type: 'HumanName' }]; addElementRule.short = "A person's full name"; resource.rules.push(addElementRule); const topLevelCardRule = new CardRule('name'); topLevelCardRule.min = 1; topLevelCardRule.max = '1'; resource.rules.push(topLevelCardRule); const subElementCardRule = new CardRule('name.given'); subElementCardRule.min = 1; subElementCardRule.max = '1'; resource.rules.push(subElementCardRule); doc.resources.set(resource.name, resource); exporter.export(); const logs = loggerSpy.getAllMessages('error'); expect(logs).toHaveLength(0); }); it('should allow constraints on root elements', () => { const resource = new Resource('ExampleResource'); resource.id = 'ExampleResource'; const rootElementRule = new CaretValueRule('.'); rootElementRule.caretPath = 'alias'; rootElementRule.value = 'ExampleAlias'; resource.rules.push(rootElementRule); doc.resources.set(resource.name, resource); exporter.export(); const logs = loggerSpy.getAllMessages('error'); expect(logs).toHaveLength(0); }); it('should log an error when constraining a parent element', () => { const resource = new Resource('MyTestResource'); // Parent defaults to DomainResource resource.id = 'MyResource'; const addElementRule1 = new AddElementRule('backboneProp'); addElementRule1.min = 0; addElementRule1.max = '*'; addElementRule1.types = [{ type: 'BackboneElement' }]; addElementRule1.short = 'short of backboneProp'; resource.rules.push(addElementRule1); const addElementRule2 = new AddElementRule('backboneProp.name'); addElementRule2.min = 1; addElementRule2.max = '1'; addElementRule2.types = [{ type: 'HumanName' }]; addElementRule2.short = 'short of backboneProp.name'; resource.rules.push(addElementRule2); const addElementRule3 = new AddElementRule('backboneProp.address'); addElementRule3.min = 0; addElementRule3.max = '*'; addElementRule3.types = [{ type: 'Address' }]; addElementRule3.short = 'short of backboneProp.address'; resource.rules.push(addElementRule3); const flagRule1 = new FlagRule('language') .withFile('ConstrainParent.fsh') .withLocation([6, 1, 6, 16]); flagRule1.summary = true; resource.rules.push(flagRule1); const cardRule1 = new CardRule('language') .withFile('ConstrainParent.fsh') .withLocation([7, 1, 7, 18]); cardRule1.min = 1; cardRule1.max = '1'; resource.rules.push(cardRule1); const flagRule2 = new FlagRule('backboneProp.address'); flagRule2.summary = true; resource.rules.push(flagRule2); const cardRule2 = new CardRule('backboneProp.address'); cardRule2.min = 1; cardRule2.max = '100'; resource.rules.push(cardRule2); doc.resources.set(resource.name, resource); const exported = exporter.export().resources[0]; const logs = loggerSpy.getAllMessages('error'); expect(logs).toHaveLength(2); logs.forEach(log => { expect(log).toMatch( /FHIR prohibits logical models and resources from constraining parent elements. Skipping.*at path 'language'.*File: ConstrainParent\.fsh.*Line:\D*/s ); }); expect(exported.name).toBe('MyTestResource'); expect(exported.id).toBe('MyResource'); expect(exported.type).toBe('MyResource'); expect(exported.baseDefinition).toBe('http://hl7.org/fhir/StructureDefinition/DomainResource'); expect(exported.elements).toHaveLength(12); // 9 AlternateIdentification elements + 3 added elements }); it('should not log a warning when exporting a conformant resource', () => { const resource = new Resource('Foo'); const caretRule = new CaretValueRule(''); caretRule.caretPath = 'url'; caretRule.value = 'http://hl7.org/fhir/StructureDefinition/Foo'; resource.rules.push(caretRule); doc.resources.set(resource.name, resource); const exported = exporter.export().resources; expect(exported.length).toBe(1); expect(loggerSpy.getAllMessages('warn')).toHaveLength(0); }); it('should log a warning when exporting a non-conformant resource', () => { const resource = new Resource('Foo'); doc.resources.set(resource.name, resource); const exported = exporter.export().resources; expect(exported.length).toBe(1); expect(loggerSpy.getLastMessage('warn')).toMatch(/non-conformant Resource.*- Foo/s); }); it('should log a warning when exporting a multiple non-conformant resources', () => { const resource1 = new Resource('Foo'); const resource2 = new Resource('Bar'); doc.resources.set(resource1.name, resource1); doc.resources.set(resource2.name, resource2); const exported = exporter.export().resources; expect(exported.length).toBe(2); expect(loggerSpy.getLastMessage('warn')).toMatch(/non-conformant Resource.*- Foo.*- Bar/s); }); it('should log a warning and truncate the name when exporting a non-conformant resource with a long name', () => { const resource = new Resource( 'SupercalifragilisticexpialidociousIsSurprisinglyNotEvenLongEnoughOnItsOwn' ); doc.resources.set(resource.name, resource); const exported = exporter.export().resources; expect(exported.length).toBe(1); expect(loggerSpy.getLastMessage('warn')).toMatch( /non-conformant Resource.*- SupercalifragilisticexpialidociousIsSurprisinglyNotEvenLon\.\.\./s ); }); });
the_stack
// = Notes = // // == Versioning == // // The Deezer JavaScript SDK is not versioned (confirmed by support). // Definitions reflect SDK as of mid-April 2019. // So, semantic versioning mandates version 0.0.*. // // == Doc == // // Not using @see tags because they are not supported by TSDoc (https://microsoft.github.io/tsdoc/). // // == Usage == // // There may be other ways, but this works for an Angular project: // // 1. Add Deezer library to a script tag, as described in https://developers.deezer.com/sdk/javascript. // // 2. Add // // "devDependencies": { // ... // "@types/deezer-sdk": "...", // ... // } // // to package.json. // // 3. Add // // /// <reference types="@types/youtube"/> // // to the beginning of app.module.ts. /** * See: {@link https://developers.deezer.com/sdk/javascript | Introduction} */ declare const DZ: DeezerSdk.DZ; /** * See: {@link https://developers.deezer.com/sdk/javascript/init | DZ.init} */ // The client may want to set this, so we have to disable a rule: // tslint:disable-next-line:prefer-declare-function declare let dzAsyncInit: () => void; /** * See: {@link https://developers.deezer.com/sdk/javascript | Deezer Javascript SDK} */ declare namespace DeezerSdk { /** * See: {@link https://developers.deezer.com/sdk/javascript | Introduction} */ interface DZ { /** * Allows you to load and play tracks from your page. * * Before using the player, you must define PlayerOptions when initializing init(InitOptions). * * The Deezer web player requires Flash (for stream encryption purposes), the minimum required version * is Flash Player 10.1. On mobile, the player will automatically fall back to 30-second previews. * * See:\ * {@link https://developers.deezer.com/sdk/javascript/player | Initialize a player}\ * {@link https://developers.deezer.com/sdk/javascript/loadtracks | Load tracks to a player} */ readonly player: Player; /** * See: {@link https://developers.deezer.com/sdk/javascript/events-subscribe | Subscribe to an event} */ readonly Event: Event; /** * Initialize the JavaScript SDK in your page. * * See: {@link https://developers.deezer.com/sdk/javascript/init | DZ.init} */ init(options: InitOptions): void; /** * Allows you to interact with the DZ.player object. * * To interact with the player, it needs to be loaded first otherwise you'll get an error message. * Once the player is loaded, the DZ.ready method is executed and you can use it to perform your * player actions. * * The DZ.ready methods accepts a function as argument that will be executed as soon as the * DZ.player object is loaded. * * Another way to make sure that the player is loaded before interacting with it is to use the * onload option when initializing the player with the DZ.init method. * * See: {@link https://developers.deezer.com/sdk/javascript/ready | DZ.ready} */ ready(callback: (sdkOptions: SdkOptions) => void): void; /** * Make calls to the Deezer API. * * See:\ * {@link https://developers.deezer.com/sdk/javascript/api | DZ.api}\ * {@link https://developers.deezer.com/api | API} */ api(path: string, callback: (response: any) => void): void; api(path: string, method: HttpMethod, callback: (response: any) => void): void; api(path: string, method: HttpMethod, data: any, callback: (response: any) => void): void; /** * Prompt the user to connect on Deezer, and to authorize you application. * * The DZ.login method opens up a modal window. Since most browsers block pop-up windows unless they * are initiated from a user event, we advise you to call DZ.login from a JavaScript onclick event. * * See: {@link https://developers.deezer.com/sdk/javascript/login | DZ.login} */ login(callback: (response: LoginResponse) => void): void; /** * Destroy the current user session. * * See: {@link https://developers.deezer.com/sdk/javascript/logout | DZ.logout} */ logout(callback?: () => void): void; /** * Determine if a user is logged in and connected to your app. * * See: {@link https://developers.deezer.com/sdk/javascript/getloginstatus | DZ.getLoginStatus} */ getLoginStatus(callback: (loginStatus: LoginStatus) => void): void; } /** * See:\ * {@link https://developers.deezer.com/sdk/javascript/init | DZ.init}\ * {@link https://developers.deezer.com/sdk/javascript/player | Initialize a player} */ interface InitOptions { readonly appId: string; readonly channelUrl: string; readonly player?: PlayerOptions; } /** * See:\ * {@link https://developers.deezer.com/sdk/javascript/player | Initialize a player}\ * {@link https://developers.deezer.com/musicplugins/player | Widget player} */ interface PlayerOptions { /** * The ID of the div that will contain the widget player * * To implement a Deezer-like player, set this to the ID attribute of HTML div you want to load * the widget player in. * * An invisible player allows you to create your own UI and JavaScript events. * * See: {@link https://developers.deezer.com/sdk/javascript/player#options | Player options} */ readonly container?: string; /** * Whether to display the playlist from the player * * Default: true * * See: {@link https://developers.deezer.com/sdk/javascript/player#options | Player options} */ readonly playlist?: boolean; /** * The layout format of the widget * * Default: classic * * See:\ * {@link https://developers.deezer.com/sdk/javascript/player#options | Player options}\ * {@link https://developers.deezer.com/musicplugins/player | Widget player} */ readonly format?: WidgetFormat; /** * The general layout of the widget * * Default: dark * * See:\ * {@link https://developers.deezer.com/sdk/javascript/player#options | Player options}\ * {@link https://developers.deezer.com/musicplugins/player | Widget player} */ readonly layout?: WidgetLayout; /** * The general color of the widget. Has to be a hexadecimal value without the #. * * Default: 1990DB * * See:\ * {@link https://developers.deezer.com/sdk/javascript/player#options | Player options}\ * {@link https://developers.deezer.com/musicplugins/player | Widget player} */ readonly color?: string; /** * The width of the player in pixels * * Default: 100% * * See: {@link https://developers.deezer.com/sdk/javascript/player#options | Player options} */ readonly width?: number; /** * The height of the player in pixels * * Default: 100% * * See: {@link https://developers.deezer.com/sdk/javascript/player#options | Player options} */ readonly height?: number; /** * The layout size of the widget * * Default: medium * * See: {@link https://developers.deezer.com/sdk/javascript/player#options | Player options} */ readonly size?: WidgetSize; /** * The callback function executed after the player has loaded. * * See: {@link https://developers.deezer.com/sdk/javascript/player#options | Player options} */ onload?: (state: PlayerState) => void; } /** * See: {@link https://developers.deezer.com/sdk/javascript/player#options | Player options} */ type WidgetFormat = "square" | "classic"; /** * See: {@link https://developers.deezer.com/sdk/javascript/player#options | Player options} */ type WidgetLayout = "light" | "dark"; /** * See: {@link https://developers.deezer.com/sdk/javascript/player#options | Player options} */ type WidgetSize = "small" | "medium" | "big"; /** * See: {@link https://developers.deezer.com/sdk/javascript/player#options | Player options} */ interface PlayerState { readonly muted: boolean; readonly repeat: number; readonly shuffle: boolean; readonly volume: number; } /** * See: {@link https://developers.deezer.com/sdk/javascript/ready | DZ.ready} */ interface SdkOptions { readonly token: { readonly access_token: string; readonly expire: string; }; /** * In addition to the PlayerState properties, * {@link https://developers.deezer.com/sdk/javascript/ready | DZ.ready} also documents the * property current_track, but the author of this comment was not able no retrieve it. */ readonly player: PlayerState; } /** * See:\ * {@link https://developers.deezer.com/sdk/javascript/api | DZ.api}\ * {@link https://developers.deezer.com/api | API} */ type HttpMethod = "GET" | "POST" | "DELETE"; /** * See: {@link https://developers.deezer.com/sdk/javascript/login | DZ.login} */ interface LoginResponse { authResponse: { accessToken: string; expire: string; }; status: "connected" | "not_authorized"; userID: string; } /** * See: {@link https://developers.deezer.com/sdk/javascript/getloginstatus | DZ.getLoginStatus} */ interface LoginStatus { status: ConnectionStatus; authResponse: { accessToken: string; expire: string; userID: string; }; } /** * See: {@link https://developers.deezer.com/sdk/javascript/getloginstatus | DZ.getLoginStatus} */ type ConnectionStatus = "connected" | "notConnected" | "unknown" | "not_authorized"; /** * See: * {@link https://developers.deezer.com/sdk/javascript/loadtracks | Load tracks to a player} * {@link https://developers.deezer.com/sdk/javascript/controls | Control a player} * {@link https://developers.deezer.com/sdk/javascript/player_object | The player properties} */ interface Player { //#region Load tracks to a player // There may be more overloads possible, but the defined ones should suffice for all // practical purposes. /** * Load and play a track or list of tracks into the current player. * * @param autoplay Whether to start playing the queue when the player has loaded. * Default: true. Setting this to false will cancel the expected behavior of the offset parameter. * @param index The index of the first track to play in the list * @param offset The position in seconds where to start playing the track * * See: {@link https://developers.deezer.com/sdk/javascript/loadtracks | Load tracks to a player} */ playTracks( trackIds: ReadonlyArray<string>, autoplay?: boolean, index?: number, offset?: number, onTracksLoaded?: (playQueue: PlayQueue) => void, ): void; playTracks( trackIds: ReadonlyArray<string>, autoplay?: boolean, index?: number, onTracksLoaded?: (playQueue: PlayQueue) => void, ): void; playTracks( trackIds: ReadonlyArray<string>, autoplay?: boolean, onTracksLoaded?: (playQueue: PlayQueue) => void, ): void; playTracks( trackIds: ReadonlyArray<string>, onTracksLoaded?: (playQueue: PlayQueue) => void, ): void; /** * Load and play an album into the current player. * * @param autoplay Whether to start playing the queue when the player has loaded. * Default: true. Setting this to false will cancel the expected behavior of the offset parameter. * @param index The index of the first track to play in the list * @param offset The position in seconds where to start playing the track * * See: {@link https://developers.deezer.com/sdk/javascript/loadtracks | Load tracks to a player} */ playAlbum( albumId: number, autoplay?: boolean, index?: number, offset?: number, onTracksLoaded?: (playQueue: PlayQueue) => void, ): void; playAlbum( albumId: number, autoplay?: boolean, index?: number, onTracksLoaded?: (playQueue: PlayQueue) => void, ): void; playAlbum( albumId: number, autoplay?: boolean, onTracksLoaded?: (playQueue: PlayQueue) => void, ): void; playAlbum( albumId: number, onTracksLoaded?: (playQueue: PlayQueue) => void, ): void; /** * Load and play a playlist into the current player. * * @param autoplay Whether to start playing the queue when the player has loaded. * Default: true. Setting this to false will cancel the expected behavior of the offset parameter. * @param index The index of the first track to play in the list * @param offset The position in seconds where to start playing the track * * See: {@link https://developers.deezer.com/sdk/javascript/loadtracks | Load tracks to a player} */ playPlaylist( playlistId: number, autoplay?: boolean, index?: number, offset?: number, onTracksLoaded?: (playQueue: PlayQueue) => void, ): void; playPlaylist( playlistId: number, autoplay?: boolean, index?: number, onTracksLoaded?: (playQueue: PlayQueue) => void, ): void; playPlaylist( playlistId: number, autoplay?: boolean, onTracksLoaded?: (playQueue: PlayQueue) => void, ): void; playPlaylist( playlistId: number, onTracksLoaded?: (playQueue: PlayQueue) => void, ): void; /** * Load and play a podcast into the current player. * * @param autoplay Whether to start playing the queue when the player has loaded. * Default: true. Setting this to false will cancel the expected behavior of the offset parameter. * @param index The index of the first track to play in the list * @param offset The position in seconds where to start playing the track * * See: {@link https://developers.deezer.com/sdk/javascript/loadtracks | Load tracks to a player} */ playPodcast( podcastId: number, autoplay?: boolean, index?: number, offset?: number, onTracksLoaded?: (playQueue: PlayQueue) => void, ): void; playPodcast( podcastId: number, autoplay?: boolean, index?: number, onTracksLoaded?: (playQueue: PlayQueue) => void, ): void; playPodcast( podcastId: number, autoplay?: boolean, onTracksLoaded?: (playQueue: PlayQueue) => void, ): void; playPodcast( podcastId: number, onTracksLoaded?: (playQueue: PlayQueue) => void, ): void; /** * Load and play an episode or a list of episodes into the current player. * * @param autoplay Whether to start playing the queue when the player has loaded. * Default: true. Setting this to false will cancel the expected behavior of the offset parameter. * @param index The index of the first track to play in the list * @param offset The position in seconds where to start playing the track * * See: {@link https://developers.deezer.com/sdk/javascript/loadtracks | Load tracks to a player} */ playEpisodes( episodeIds: ReadonlyArray<string>, autoplay?: boolean, index?: number, offset?: number, onTracksLoaded?: (playQueue: PlayQueue) => void, ): void; playEpisodes( episodeIds: ReadonlyArray<string>, autoplay?: boolean, index?: number, onTracksLoaded?: (playQueue: PlayQueue) => void, ): void; playEpisodes( episodeIds: ReadonlyArray<string>, autoplay?: boolean, onTracksLoaded?: (playQueue: PlayQueue) => void, ): void; playEpisodes( episodeIds: ReadonlyArray<string>, onTracksLoaded?: (playQueue: PlayQueue) => void, ): void; /** * Load and play a radio into the current player. * * @param autoplay Whether to start playing the queue when the player has loaded. * Default: true. Setting this to false will cancel the expected behavior of the offset parameter. * @param offset The position in seconds where to start playing the track * * See: {@link https://developers.deezer.com/sdk/javascript/loadtracks | Load tracks to a player} */ playRadio( id: number, radioType?: RadioType, autoplay?: boolean, offset?: number, onTracksLoaded?: (playQueue: PlayQueue) => void, ): void; playRadio( id: number, radioType?: RadioType, autoplay?: boolean, onTracksLoaded?: (playQueue: PlayQueue) => void, ): void; playRadio( id: number, radioType?: RadioType, onTracksLoaded?: (playQueue: PlayQueue) => void, ): void; /** * The official docs for this method are incomplete, but the existing docs and a * {@link https://github.com/deezer/javascript-samples/blob/master/player_basic.html | usage example} * suggest the same parameters as in {@link playRadio}, * * @param autoplay Whether to start playing the queue when the player has loaded. * Default: true. Setting this to false will cancel the expected behavior of the offset parameter. * @param index The index of the first track to play in the list * @param offset The position in seconds where to start playing the track * * See: {@link https://developers.deezer.com/sdk/javascript/loadtracks | Load tracks to a player} */ playSmartRadio( id: number, radioType?: RadioType, autoplay?: boolean, offset?: number, onTracksLoaded?: (playQueue: PlayQueue) => void, ): void; playSmartRadio( id: number, radioType?: RadioType, autoplay?: boolean, onTracksLoaded?: (playQueue: PlayQueue) => void, ): void; playSmartRadio( id: number, radioType?: RadioType, onTracksLoaded?: (playQueue: PlayQueue) => void, ): void; /** * Load and play external MP3 sources into the current player. * * @param autoplay Whether to start playing the queue when the player has loaded. * Default: true. Setting this to false will cancel the expected behavior of the offset parameter. * @param index The index of the first track to play in the list * @param offset The position in seconds where to start playing the track * * See: {@link https://developers.deezer.com/sdk/javascript/loadtracks | Load tracks to a player} */ playExternalTracks( mp3Sources: ReadonlyArray<Mp3Source>, autoplay?: boolean, index?: number, offset?: number, onTracksLoaded?: (playQueue: PlayQueue) => void, ): void; playExternalTracks( mp3Sources: ReadonlyArray<Mp3Source>, autoplay?: boolean, index?: number, onTracksLoaded?: (playQueue: PlayQueue) => void, ): void; playExternalTracks( mp3Sources: ReadonlyArray<Mp3Source>, autoplay?: boolean, onTracksLoaded?: (playQueue: PlayQueue) => void, ): void; playExternalTracks( mp3Sources: ReadonlyArray<Mp3Source>, onTracksLoaded?: (playQueue: PlayQueue) => void, ): void; /** * Append a track to the queue of the current player. * * To remove a track from the queue, you will need to reset the queue using the playTracks method. * * See: {@link https://developers.deezer.com/sdk/javascript/loadtracks | Load tracks to a player} */ addToQueue(trackIds: ReadonlyArray<string>, onTracksLoaded?: (playQueue: PlayQueue) => void): void; //#endregion //#region Control a player /** * See: {@link https://developers.deezer.com/sdk/javascript/controls | Control a player} */ play(): void; /** * See: {@link https://developers.deezer.com/sdk/javascript/controls | Control a player} */ pause(): void; /** * Tell the player to read the next track. * * The behavior of this method will depend on the RepeatMode of the player. * * See: {@link https://developers.deezer.com/sdk/javascript/controls | Control a player} */ next(): void; /** * Tell the player to read the previous track. * * The behavior of this method will depend on the RepeatMode of the player. * * See: {@link https://developers.deezer.com/sdk/javascript/controls | Control a player} */ prev(): void; /** * Set the position of the reader head in the currently playing track. * * See: {@link https://developers.deezer.com/sdk/javascript/controls | Control a player} */ seek(positionPercentFloat: number): void; /** * See: {@link https://developers.deezer.com/sdk/javascript/controls | Control a player} */ setVolume(volumePercentInt: number): void; /** * See: {@link https://developers.deezer.com/sdk/javascript/controls | Control a player} */ setMute(mute: boolean): void; /** * See: {@link https://developers.deezer.com/sdk/javascript/controls | Control a player} */ setShuffle(shuffle: boolean): void; /** * See: {@link https://developers.deezer.com/sdk/javascript/controls | Control a player} */ setRepeat(repeatMode: RepeatMode): void; /** * Set the order of the current list of tracks. * * Attention, this method does not add or remove tracks from the play queue. * Use the addToQueue method to add a track or the playTracks method to remove a track by resetting * the play queue. * * See: {@link https://developers.deezer.com/sdk/javascript/controls | Control a player} */ changeTrackOrder(trackIds: ReadonlyArray<string>): void; /** * Hide the queue and current track information. * * @param trackInfo Replaces the current track information. * * See: {@link https://developers.deezer.com/sdk/javascript/controls | Control a player} * */ setBlindTestMode( blindTestMode: boolean, trackInfo?: { title: string; artist: string; cover: string ; } ): void; //#endregion //#region The player properties /** * See: {@link https://developers.deezer.com/sdk/javascript/player_object | The player properties} */ isPlaying(): boolean; /** * Get the tracks in the queue of the player. * * See: {@link https://developers.deezer.com/sdk/javascript/player_object | The player properties} */ getTrackList(): Track[]; /** * See: {@link https://developers.deezer.com/sdk/javascript/player_object | The player properties} */ getCurrentTrack(): Track; /** * Get the position in the queue of the currently playing track. * * See: {@link https://developers.deezer.com/sdk/javascript/player_object | The player properties} */ getCurrentIndex(): number; /** * See: {@link https://developers.deezer.com/sdk/javascript/player_object | The player properties} */ getVolume(): number; /** * See: {@link https://developers.deezer.com/sdk/javascript/player_object | The player properties} */ getShuffle(): boolean; /** * See: {@link https://developers.deezer.com/sdk/javascript/player_object | The player properties} */ getRepeat(): RepeatMode; /** * See: {@link https://developers.deezer.com/sdk/javascript/player_object | The player properties} */ getMute(): boolean; //#endregion } /** * See: {@link https://developers.deezer.com/sdk/javascript/loadtracks | Load tracks to a player} */ type RadioType = "radio" | "artist" | "user"; /** * See: {@link https://developers.deezer.com/sdk/javascript/loadtracks | Load tracks to a player} */ interface PlayQueue { readonly tracks: Track[]; } /** * See: {@link https://developers.deezer.com/sdk/javascript/loadtracks | Load tracks to a player} */ interface Mp3Source { readonly url: string; readonly title: string; readonly artist: string; } /** * 0: No repeat\ * 1: Repeat all\ * 2: Repeat one * * See:\ * {@link https://developers.deezer.com/sdk/javascript/controls | Control a player}\ * {@link https://developers.deezer.com/sdk/javascript/player_object | The player properties} */ type RepeatMode = 0 | 1 | 2; /** * See: {@link https://developers.deezer.com/sdk/javascript/player_object | The player properties} */ interface Track { readonly id: string; /** Duration in seconds (int) */ readonly duration: number; readonly title: string; readonly artist: Artist; readonly album: Album; } /** * See: {@link https://developers.deezer.com/sdk/javascript/player_object | The player properties} */ interface Artist { readonly id: string; readonly name: string; } /** * See: {@link https://developers.deezer.com/sdk/javascript/player_object | The player properties} */ interface Album { readonly id: string; readonly title: string; } //#region Player Events /** * Allows you to listen to all player-related events. * * See:\ * {@link https://developers.deezer.com/sdk/javascript/events | List of events}\ * {@link https://developers.deezer.com/sdk/javascript/events-subscribe | Subscribe to an event} */ interface Event { /** * See: {@link https://developers.deezer.com/sdk/javascript/events | List of events} */ subscribe( event: "player_loaded" | "player_play" | "player_paused"| "tracklist_changed", callback: () => void ): void; subscribe( event: "player_position", callback: (positionSecondsFloat_durationSecondsInt: [number, number]) => void ): void; subscribe(event: "player_buffering", callback: (loadedPercentInt: number) => void): void; subscribe(event: "volume_changed", callback: (volumePercentInt: number) => void): void; subscribe(event: "shuffle_changed", callback: (shuffle: boolean) => void): void; subscribe(event: "repeat_changed", callback: (repeatMode: RepeatMode) => void): void; subscribe(event: "mute_changed", callback: (mute: boolean) => void): void; subscribe(event: "track_end", callback: (trackPosition: number) => void): void; subscribe( event: "current_track", callback: (currentTrackInfo: { index: number; track: Track; }) => void ): void; } /** * See:\ * {@link https://developers.deezer.com/sdk/javascript/events | List of events}\ * {@link https://developers.deezer.com/sdk/javascript/events-subscribe | Subscribe to an event} * * @remarks * This type is not needed to define the other types, but users may find it useful * in some situations anyway. */ type PlayerEvent = "player_loaded" | "player_play" | "player_paused" | "player_position" | "player_buffering" | "volume_changed" | "shuffle_changed" | "repeat_changed" | "mute_changed" | "tracklist_changed" | "track_end" | "current_track"; //#endregion }
the_stack
import * as path from 'path'; import * as cp from 'child_process'; import * as os from 'os'; import * as fs from 'fs'; import * as mkdirp from 'mkdirp'; import { tmpName } from 'tmp'; import { IDriver, connect as connectElectronDriver, IDisposable, IElement, Thenable, ILocalizedStrings, ILocaleInfo } from './driver'; import { connect as connectPlaywrightDriver, launch } from './playwrightDriver'; import { Logger } from './logger'; import { ncp } from 'ncp'; import { URI } from 'vscode-uri'; const repoPath = path.join(__dirname, '../../..'); function getDevElectronPath(): string { const buildPath = path.join(repoPath, '.build'); const product = require(path.join(repoPath, 'product.json')); switch (process.platform) { case 'darwin': return path.join(buildPath, 'electron', `${product.nameLong}.app`, 'Contents', 'MacOS', 'Electron'); case 'linux': return path.join(buildPath, 'electron', `${product.applicationName}`); case 'win32': return path.join(buildPath, 'electron', `${product.nameShort}.exe`); default: throw new Error('Unsupported platform.'); } } function getBuildElectronPath(root: string): string { switch (process.platform) { case 'darwin': return path.join(root, 'Contents', 'MacOS', 'Electron'); case 'linux': { const product = require(path.join(root, 'resources', 'app', 'product.json')); return path.join(root, product.applicationName); } case 'win32': { const product = require(path.join(root, 'resources', 'app', 'product.json')); return path.join(root, `${product.nameShort}.exe`); } default: throw new Error('Unsupported platform.'); } } function getDevOutPath(): string { return path.join(repoPath, 'out'); } function getBuildOutPath(root: string): string { switch (process.platform) { case 'darwin': return path.join(root, 'Contents', 'Resources', 'app', 'out'); default: return path.join(root, 'resources', 'app', 'out'); } } async function connect(connectDriver: typeof connectElectronDriver, child: cp.ChildProcess | undefined, outPath: string, handlePath: string, logger: Logger): Promise<Code> { let errCount = 0; while (true) { try { const { client, driver } = await connectDriver(outPath, handlePath); return new Code(client, driver, logger); } catch (err) { if (++errCount > 50) { if (child) { child.kill(); } throw err; } // retry await new Promise(c => setTimeout(c, 100)); } } } // Kill all running instances, when dead const instances = new Set<cp.ChildProcess>(); process.once('exit', () => instances.forEach(code => code.kill())); export interface SpawnOptions { codePath?: string; workspacePath: string; userDataDir: string; extensionsPath: string; logger: Logger; verbose?: boolean; extraArgs?: string[]; log?: string; remote?: boolean; web?: boolean; headless?: boolean; browser?: 'chromium' | 'webkit' | 'firefox'; } async function createDriverHandle(): Promise<string> { if ('win32' === os.platform()) { const name = [...Array(15)].map(() => Math.random().toString(36)[3]).join(''); return `\\\\.\\pipe\\${name}`; } else { return await new Promise<string>((c, e) => tmpName((err, handlePath) => err ? e(err) : c(handlePath))); } } export async function spawn(options: SpawnOptions): Promise<Code> { const handle = await createDriverHandle(); let child: cp.ChildProcess | undefined; let connectDriver: typeof connectElectronDriver; copyExtension(options.extensionsPath, 'vscode-notebook-tests'); if (options.web) { await launch(options.userDataDir, options.workspacePath, options.codePath, options.extensionsPath, Boolean(options.verbose)); connectDriver = connectPlaywrightDriver.bind(connectPlaywrightDriver, options); return connect(connectDriver, child, '', handle, options.logger); } const env = { ...process.env }; const codePath = options.codePath; const outPath = codePath ? getBuildOutPath(codePath) : getDevOutPath(); const args = [ options.workspacePath, '--skip-release-notes', '--skip-welcome', '--disable-telemetry', '--no-cached-data', '--disable-updates', '--disable-keytar', '--disable-crash-reporter', '--disable-workspace-trust', `--extensions-dir=${options.extensionsPath}`, `--user-data-dir=${options.userDataDir}`, `--logsPath=${path.join(repoPath, '.build', 'logs', 'smoke-tests')}`, '--driver', handle ]; if (process.platform === 'linux') { args.push('--disable-gpu'); // Linux has trouble in VMs to render properly with GPU enabled } if (options.remote) { // Replace workspace path with URI args[0] = `--${options.workspacePath.endsWith('.code-workspace') ? 'file' : 'folder'}-uri=vscode-remote://test+test/${URI.file(options.workspacePath).path}`; if (codePath) { // running against a build: copy the test resolver extension copyExtension(options.extensionsPath, 'vscode-test-resolver'); } args.push('--enable-proposed-api=vscode.vscode-test-resolver'); const remoteDataDir = `${options.userDataDir}-server`; mkdirp.sync(remoteDataDir); if (codePath) { // running against a build: copy the test resolver extension into remote extensions dir const remoteExtensionsDir = path.join(remoteDataDir, 'extensions'); mkdirp.sync(remoteExtensionsDir); copyExtension(remoteExtensionsDir, 'vscode-notebook-tests'); } env['TESTRESOLVER_DATA_FOLDER'] = remoteDataDir; } const spawnOptions: cp.SpawnOptions = { env }; args.push('--enable-proposed-api=vscode.vscode-notebook-tests'); if (!codePath) { args.unshift(repoPath); } if (options.verbose) { args.push('--driver-verbose'); spawnOptions.stdio = ['ignore', 'inherit', 'inherit']; } if (options.log) { args.push('--log', options.log); } if (options.extraArgs) { args.push(...options.extraArgs); } const electronPath = codePath ? getBuildElectronPath(codePath) : getDevElectronPath(); child = cp.spawn(electronPath, args, spawnOptions); instances.add(child); child.once('exit', () => instances.delete(child!)); connectDriver = connectElectronDriver; return connect(connectDriver, child, outPath, handle, options.logger); } async function copyExtension(extensionsPath: string, extId: string): Promise<void> { const dest = path.join(extensionsPath, extId); if (!fs.existsSync(dest)) { const orig = path.join(repoPath, 'extensions', extId); await new Promise<void>((c, e) => ncp(orig, dest, err => err ? e(err) : c())); } } async function poll<T>( fn: () => Thenable<T>, acceptFn: (result: T) => boolean, timeoutMessage: string, retryCount: number = 200, retryInterval: number = 100 // millis ): Promise<T> { let trial = 1; let lastError: string = ''; while (true) { if (trial > retryCount) { console.error('** Timeout!'); console.error(lastError); throw new Error(`Timeout: ${timeoutMessage} after ${(retryCount * retryInterval) / 1000} seconds.`); } let result; try { result = await fn(); if (acceptFn(result)) { return result; } else { lastError = 'Did not pass accept function'; } } catch (e: any) { lastError = Array.isArray(e.stack) ? e.stack.join(os.EOL) : e.stack; } await new Promise(resolve => setTimeout(resolve, retryInterval)); trial++; } } export class Code { private _activeWindowId: number | undefined = undefined; private driver: IDriver; constructor( private client: IDisposable, driver: IDriver, readonly logger: Logger ) { this.driver = new Proxy(driver, { get(target, prop, receiver) { if (typeof prop === 'symbol') { throw new Error('Invalid usage'); } const targetProp = (target as any)[prop]; if (typeof targetProp !== 'function') { return targetProp; } return function (this: any, ...args: any[]) { logger.log(`${prop}`, ...args.filter(a => typeof a === 'string')); return targetProp.apply(this, args); }; } }); } async capturePage(): Promise<string> { const windowId = await this.getActiveWindowId(); return await this.driver.capturePage(windowId); } async waitForWindowIds(fn: (windowIds: number[]) => boolean): Promise<void> { await poll(() => this.driver.getWindowIds(), fn, `get window ids`); } async dispatchKeybinding(keybinding: string): Promise<void> { const windowId = await this.getActiveWindowId(); await this.driver.dispatchKeybinding(windowId, keybinding); } async reload(): Promise<void> { const windowId = await this.getActiveWindowId(); await this.driver.reloadWindow(windowId); } async exit(): Promise<void> { const veto = await this.driver.exitApplication(); if (veto === true) { throw new Error('Code exit was blocked by a veto.'); } } async waitForTextContent(selector: string, textContent?: string, accept?: (result: string) => boolean, retryCount?: number): Promise<string> { const windowId = await this.getActiveWindowId(); accept = accept || (result => textContent !== undefined ? textContent === result : !!result); return await poll( () => this.driver.getElements(windowId, selector).then(els => els.length > 0 ? Promise.resolve(els[0].textContent) : Promise.reject(new Error('Element not found for textContent'))), s => accept!(typeof s === 'string' ? s : ''), `get text content '${selector}'`, retryCount ); } async waitAndClick(selector: string, xoffset?: number, yoffset?: number, retryCount: number = 200): Promise<void> { const windowId = await this.getActiveWindowId(); await poll(() => this.driver.click(windowId, selector, xoffset, yoffset), () => true, `click '${selector}'`, retryCount); } async waitAndDoubleClick(selector: string): Promise<void> { const windowId = await this.getActiveWindowId(); await poll(() => this.driver.doubleClick(windowId, selector), () => true, `double click '${selector}'`); } async waitForSetValue(selector: string, value: string): Promise<void> { const windowId = await this.getActiveWindowId(); await poll(() => this.driver.setValue(windowId, selector, value), () => true, `set value '${selector}'`); } async waitForElements(selector: string, recursive: boolean, accept: (result: IElement[]) => boolean = result => result.length > 0): Promise<IElement[]> { const windowId = await this.getActiveWindowId(); return await poll(() => this.driver.getElements(windowId, selector, recursive), accept, `get elements '${selector}'`); } async waitForElement(selector: string, accept: (result: IElement | undefined) => boolean = result => !!result, retryCount: number = 200): Promise<IElement> { const windowId = await this.getActiveWindowId(); return await poll<IElement>(() => this.driver.getElements(windowId, selector).then(els => els[0]), accept, `get element '${selector}'`, retryCount); } async waitForActiveElement(selector: string, retryCount: number = 200): Promise<void> { const windowId = await this.getActiveWindowId(); await poll(() => this.driver.isActiveElement(windowId, selector), r => r, `is active element '${selector}'`, retryCount); } async waitForTitle(fn: (title: string) => boolean): Promise<void> { const windowId = await this.getActiveWindowId(); await poll(() => this.driver.getTitle(windowId), fn, `get title`); } async waitForTypeInEditor(selector: string, text: string): Promise<void> { const windowId = await this.getActiveWindowId(); await poll(() => this.driver.typeInEditor(windowId, selector, text), () => true, `type in editor '${selector}'`); } async waitForTerminalBuffer(selector: string, accept: (result: string[]) => boolean): Promise<void> { const windowId = await this.getActiveWindowId(); await poll(() => this.driver.getTerminalBuffer(windowId, selector), accept, `get terminal buffer '${selector}'`); } async writeInTerminal(selector: string, value: string): Promise<void> { const windowId = await this.getActiveWindowId(); await poll(() => this.driver.writeInTerminal(windowId, selector, value), () => true, `writeInTerminal '${selector}'`); } async getLocaleInfo(): Promise<ILocaleInfo> { const windowId = await this.getActiveWindowId(); return await this.driver.getLocaleInfo(windowId); } async getLocalizedStrings(): Promise<ILocalizedStrings> { const windowId = await this.getActiveWindowId(); return await this.driver.getLocalizedStrings(windowId); } private async getActiveWindowId(): Promise<number> { if (typeof this._activeWindowId !== 'number') { const windows = await this.driver.getWindowIds(); this._activeWindowId = windows[0]; } return this._activeWindowId; } dispose(): void { this.client.dispose(); } } export function findElement(element: IElement, fn: (element: IElement) => boolean): IElement | null { const queue = [element]; while (queue.length > 0) { const element = queue.shift()!; if (fn(element)) { return element; } queue.push(...element.children); } return null; } export function findElements(element: IElement, fn: (element: IElement) => boolean): IElement[] { const result: IElement[] = []; const queue = [element]; while (queue.length > 0) { const element = queue.shift()!; if (fn(element)) { result.push(element); } queue.push(...element.children); } return result; }
the_stack
const BUF_SIZE = 65536 * 4; type BufferEncoding = 'ascii' | 'utf8' | 'utf-8' | 'utf16le' | 'ucs2' | 'ucs-2' | 'base64' | 'latin1' | 'binary' | 'hex'; export class ReadStream { buf: Buffer; bufStart: number; bufEnd: number; bufCapacity: number; readSize: number; atEOF: boolean; errorBuf: Error[] | null; encoding: BufferEncoding; isReadable: boolean; isWritable: boolean; nodeReadableStream: NodeJS.ReadableStream | null; nextPushResolver: (() => void) | null; nextPush: Promise<void>; awaitingPush: boolean; constructor(optionsOrStreamLike: {[k: string]: any} | NodeJS.ReadableStream | string | Buffer = {}) { this.buf = Buffer.allocUnsafe(BUF_SIZE); this.bufStart = 0; this.bufEnd = 0; this.bufCapacity = BUF_SIZE; this.readSize = 0; this.atEOF = false; this.errorBuf = null; this.encoding = 'utf8'; this.isReadable = true; this.isWritable = false; this.nodeReadableStream = null; this.nextPushResolver = null; this.nextPush = new Promise(resolve => { this.nextPushResolver = resolve; }); this.awaitingPush = false; let options; if (typeof optionsOrStreamLike === 'string') { options = {buffer: optionsOrStreamLike}; } else if (optionsOrStreamLike instanceof Buffer) { options = {buffer: optionsOrStreamLike}; } else if (typeof (optionsOrStreamLike as any)._readableState === 'object') { options = {nodeStream: optionsOrStreamLike as NodeJS.ReadableStream}; } else { options = optionsOrStreamLike; } if (options.nodeStream) { const nodeStream: NodeJS.ReadableStream = options.nodeStream; this.nodeReadableStream = nodeStream; nodeStream.on('data', data => { this.push(data); }); nodeStream.on('end', () => { this.pushEnd(); }); options.read = function (this: ReadStream, unusedBytes: number) { this.nodeReadableStream!.resume(); }; options.pause = function (this: ReadStream, unusedBytes: number) { this.nodeReadableStream!.pause(); }; } if (options.read) this._read = options.read; if (options.pause) this._pause = options.pause; if (options.destroy) this._destroy = options.destroy; if (options.encoding) this.encoding = options.encoding; if (options.buffer !== undefined) { this.push(options.buffer); this.pushEnd(); } } get bufSize() { return this.bufEnd - this.bufStart; } moveBuf() { if (this.bufStart !== this.bufEnd) { this.buf.copy(this.buf, 0, this.bufStart, this.bufEnd); } this.bufEnd -= this.bufStart; this.bufStart = 0; } expandBuf(newCapacity = this.bufCapacity * 2) { const newBuf = Buffer.allocUnsafe(newCapacity); this.buf.copy(newBuf, 0, this.bufStart, this.bufEnd); this.bufEnd -= this.bufStart; this.bufStart = 0; this.bufCapacity = newCapacity; this.buf = newBuf; } ensureCapacity(additionalCapacity: number) { if (this.bufEnd + additionalCapacity <= this.bufCapacity) return; const capacity = this.bufEnd - this.bufStart + additionalCapacity; if (capacity <= this.bufCapacity) { return this.moveBuf(); } let newCapacity = this.bufCapacity * 2; while (newCapacity < capacity) newCapacity *= 2; this.expandBuf(newCapacity); } push(buf: Buffer | string, encoding: BufferEncoding = this.encoding) { let size; if (this.atEOF) return; if (typeof buf === 'string') { size = Buffer.byteLength(buf, encoding); this.ensureCapacity(size); this.buf.write(buf, this.bufEnd); } else { size = buf.length; this.ensureCapacity(size); buf.copy(this.buf, this.bufEnd); } this.bufEnd += size; if (this.bufSize > this.readSize && size * 2 < this.bufSize) this._pause(); this.resolvePush(); } pushEnd() { this.atEOF = true; this.resolvePush(); } pushError(err: Error, recoverable?: boolean) { if (!this.errorBuf) this.errorBuf = []; this.errorBuf.push(err); if (!recoverable) this.atEOF = true; this.resolvePush(); } readError() { if (this.errorBuf) { const err = this.errorBuf.shift()!; if (!this.errorBuf.length) this.errorBuf = null; throw err; } } peekError() { if (this.errorBuf) { throw this.errorBuf[0]; } } resolvePush() { if (!this.nextPushResolver) throw new Error(`Push after end of read stream`); this.nextPushResolver(); if (this.atEOF) { this.nextPushResolver = null; return; } this.nextPush = new Promise(resolve => { this.nextPushResolver = resolve; }); } _read(size = 0): void | Promise<void> { throw new Error(`ReadStream needs to be subclassed and the _read function needs to be implemented.`); } _destroy(): void | Promise<void> {} _pause() {} /** * Reads until the internal buffer is non-empty. Does nothing if the * internal buffer is already non-empty. * * If `byteCount` is a number, instead read until the internal buffer * contains at least `byteCount` bytes. * * If `byteCount` is `true`, reads even if the internal buffer is * non-empty. */ loadIntoBuffer(byteCount: number | null | true = null, readError?: boolean) { this[readError ? 'readError' : 'peekError'](); if (byteCount === 0) return; this.readSize = Math.max( byteCount === true ? this.bufSize + 1 : byteCount === null ? 1 : byteCount, this.readSize ); if (!this.errorBuf && !this.atEOF && this.bufSize < this.readSize) { let bytes: number | null = this.readSize - this.bufSize; if (bytes === Infinity || byteCount === null || byteCount === true) bytes = null; return this.doLoad(bytes, readError); } } async doLoad(chunkSize?: number | null, readError?: boolean) { while (!this.errorBuf && !this.atEOF && this.bufSize < this.readSize) { if (chunkSize) void this._read(chunkSize); else void this._read(); await this.nextPush; this[readError ? 'readError' : 'peekError'](); } } peek(byteCount?: number | null, encoding?: BufferEncoding): string | null | Promise<string | null>; peek(encoding: BufferEncoding): string | null | Promise<string | null>; peek(byteCount: number | string | null = null, encoding: BufferEncoding = this.encoding) { if (typeof byteCount === 'string') { encoding = byteCount as BufferEncoding; byteCount = null; } const maybeLoad = this.loadIntoBuffer(byteCount); if (maybeLoad) return maybeLoad.then(() => this.peek(byteCount as number, encoding)); if (!this.bufSize && byteCount !== 0) return null; if (byteCount === null) return this.buf.toString(encoding, this.bufStart, this.bufEnd); if (byteCount > this.bufSize) byteCount = this.bufSize; return this.buf.toString(encoding, this.bufStart, this.bufStart + byteCount); } peekBuffer(byteCount: number | null = null): Buffer | null | Promise<Buffer | null> { const maybeLoad = this.loadIntoBuffer(byteCount); if (maybeLoad) return maybeLoad.then(() => this.peekBuffer(byteCount)); if (!this.bufSize && byteCount !== 0) return null; if (byteCount === null) return this.buf.slice(this.bufStart, this.bufEnd); if (byteCount > this.bufSize) byteCount = this.bufSize; return this.buf.slice(this.bufStart, this.bufStart + byteCount); } async read(byteCount?: number | null, encoding?: BufferEncoding): Promise<string | null>; async read(encoding: BufferEncoding): Promise<string | null>; async read(byteCount: number | string | null = null, encoding: BufferEncoding = this.encoding) { if (typeof byteCount === 'string') { encoding = byteCount as BufferEncoding; byteCount = null; } await this.loadIntoBuffer(byteCount, true); // This MUST NOT be awaited: we MUST synchronously clear byteCount after peeking // if the buffer is written to after peek but before clearing the buffer, the write // will be lost forever const out = this.peek(byteCount, encoding); if (out && typeof out !== 'string') { throw new Error("Race condition; you must not read before a previous read has completed"); } if (byteCount === null || byteCount >= this.bufSize) { this.bufStart = 0; this.bufEnd = 0; this.readSize = 0; } else { this.bufStart += byteCount; this.readSize -= byteCount; } return out; } byChunk(byteCount?: number | null) { // eslint-disable-next-line @typescript-eslint/no-this-alias const byteStream = this; return new ObjectReadStream<string>({ async read(this: ObjectReadStream<string>) { const next = await byteStream.read(byteCount); if (typeof next === 'string') this.push(next); else this.pushEnd(); }, }); } byLine() { // eslint-disable-next-line @typescript-eslint/no-this-alias const byteStream = this; return new ObjectReadStream<string>({ async read(this: ObjectReadStream<string>) { const next = await byteStream.readLine(); if (typeof next === 'string') this.push(next); else this.pushEnd(); }, }); } delimitedBy(delimiter: string) { // eslint-disable-next-line @typescript-eslint/no-this-alias const byteStream = this; return new ObjectReadStream<string>({ async read(this: ObjectReadStream<string>) { const next = await byteStream.readDelimitedBy(delimiter); if (typeof next === 'string') this.push(next); else this.pushEnd(); }, }); } async readBuffer(byteCount: number | null = null) { await this.loadIntoBuffer(byteCount, true); // This MUST NOT be awaited: we must synchronously clear the buffer after peeking // (see `read`) const out = this.peekBuffer(byteCount); if (out && (out as Promise<unknown>).then) { throw new Error("Race condition; you must not read before a previous read has completed"); } if (byteCount === null || byteCount >= this.bufSize) { this.bufStart = 0; this.bufEnd = 0; } else { this.bufStart += byteCount; } return out; } async indexOf(symbol: string, encoding: BufferEncoding = this.encoding) { let idx = this.buf.indexOf(symbol, this.bufStart, encoding); while (!this.atEOF && (idx >= this.bufEnd || idx < 0)) { await this.loadIntoBuffer(true); idx = this.buf.indexOf(symbol, this.bufStart, encoding); } if (idx >= this.bufEnd) return -1; return idx - this.bufStart; } async readAll(encoding: BufferEncoding = this.encoding) { return (await this.read(Infinity, encoding)) || ''; } peekAll(encoding: BufferEncoding = this.encoding) { return this.peek(Infinity, encoding); } async readDelimitedBy(symbol: string, encoding: BufferEncoding = this.encoding) { if (this.atEOF && !this.bufSize) return null; const idx = await this.indexOf(symbol, encoding); if (idx < 0) { return this.readAll(encoding); } else { const out = await this.read(idx, encoding); this.bufStart += Buffer.byteLength(symbol, 'utf8'); return out; } } async readLine(encoding: BufferEncoding = this.encoding) { if (!encoding) throw new Error(`readLine must have an encoding`); let line = await this.readDelimitedBy('\n', encoding); if (line?.endsWith('\r')) line = line.slice(0, -1); return line; } destroy() { this.atEOF = true; this.bufStart = 0; this.bufEnd = 0; if (this.nextPushResolver) this.resolvePush(); return this._destroy(); } async next(byteCount: number | null = null) { const value = await this.read(byteCount); return {value, done: value === null}; } async pipeTo(outStream: WriteStream, options: {noEnd?: boolean} = {}) { let value, done; while (({value, done} = await this.next(), !done)) { await outStream.write(value!); } if (!options.noEnd) return outStream.writeEnd(); } } interface WriteStreamOptions { nodeStream?: NodeJS.WritableStream; write?: (this: WriteStream, data: string | Buffer) => (Promise<undefined> | undefined); writeEnd?: (this: WriteStream) => Promise<any>; } export class WriteStream { isReadable: boolean; isWritable: true; encoding: BufferEncoding; nodeWritableStream: NodeJS.WritableStream | null; drainListeners: (() => void)[]; constructor(optionsOrStream: WriteStreamOptions | NodeJS.WritableStream = {}) { this.isReadable = false; this.isWritable = true; this.encoding = 'utf8'; this.nodeWritableStream = null; this.drainListeners = []; let options: WriteStreamOptions = optionsOrStream as any; if ((options as any)._writableState) { options = {nodeStream: optionsOrStream as NodeJS.WritableStream}; } if (options.nodeStream) { const nodeStream: NodeJS.WritableStream = options.nodeStream; this.nodeWritableStream = nodeStream; options.write = function (data: string | Buffer) { const result = this.nodeWritableStream!.write(data); if (result !== false) return undefined; if (!this.drainListeners.length) { this.nodeWritableStream!.once('drain', () => { for (const listener of this.drainListeners) listener(); this.drainListeners = []; }); } return new Promise(resolve => { // `as () => void` is necessary because TypeScript thinks that it should be a function // that takes an undefined value as its only parameter: `(value: PromiseLike<undefined> | undefined) => void` this.drainListeners.push(resolve as () => void); }); }; // Prior to Node v10.12.0, attempting to close STDOUT or STDERR will throw if (nodeStream !== process.stdout && nodeStream !== process.stderr) { options.writeEnd = function () { return new Promise<void>(resolve => { this.nodeWritableStream!.end(() => resolve()); }); }; } } if (options.write) this._write = options.write; if (options.writeEnd) this._writeEnd = options.writeEnd; } write(chunk: Buffer | string): void | Promise<void> { return this._write(chunk); } writeLine(chunk: string): void | Promise<void> { if (chunk === null) { return this.writeEnd(); } return this.write(chunk + '\n'); } _write(chunk: Buffer | string): void | Promise<void> { throw new Error(`WriteStream needs to be subclassed and the _write function needs to be implemented.`); } _writeEnd(): void | Promise<void> {} async writeEnd(chunk?: string): Promise<void> { if (chunk) { await this.write(chunk); } return this._writeEnd(); } } export class ReadWriteStream extends ReadStream implements WriteStream { isReadable: true; isWritable: true; nodeWritableStream: NodeJS.WritableStream | null; drainListeners: (() => void)[]; constructor(options: AnyObject = {}) { super(options); this.isReadable = true; this.isWritable = true; this.nodeWritableStream = null; this.drainListeners = []; if (options.nodeStream) { const nodeStream: NodeJS.WritableStream = options.nodeStream; this.nodeWritableStream = nodeStream; options.write = function (data: string | Buffer) { const result = this.nodeWritableStream!.write(data); if (result !== false) return undefined; if (!this.drainListeners.length) { this.nodeWritableStream!.once('drain', () => { for (const listener of this.drainListeners) listener(); this.drainListeners = []; }); } return new Promise(resolve => { this.drainListeners.push(resolve); }); }; // Prior to Node v10.12.0, attempting to close STDOUT or STDERR will throw if (nodeStream !== process.stdout && nodeStream !== process.stderr) { options.writeEnd = function () { return new Promise<void>(resolve => { this.nodeWritableStream!.end(() => resolve()); }); }; } } if (options.write) this._write = options.write; if (options.writeEnd) this._writeEnd = options.writeEnd; } write(chunk: Buffer | string): Promise<void> | void { return this._write(chunk); } writeLine(chunk: string): Promise<void> | void { return this.write(chunk + '\n'); } _write(chunk: Buffer | string): Promise<void> | void { throw new Error(`WriteStream needs to be subclassed and the _write function needs to be implemented.`); } /** * In a ReadWriteStream, `_read` does not need to be implemented, * because it's valid for the read stream buffer to be filled only by * `_write`. */ _read(size?: number) {} _writeEnd(): void | Promise<void> {} async writeEnd() { return this._writeEnd(); } } type ObjectReadStreamOptions<T> = { buffer?: T[], read?: (this: ObjectReadStream<T>) => void | Promise<void>, pause?: (this: ObjectReadStream<T>) => void | Promise<void>, destroy?: (this: ObjectReadStream<T>) => void | Promise<void>, nodeStream?: undefined, } | { buffer?: undefined, read?: undefined, pause?: undefined, destroy?: undefined, nodeStream: NodeJS.ReadableStream, }; export class ObjectReadStream<T> { buf: T[]; readSize: number; atEOF: boolean; errorBuf: Error[] | null; isReadable: boolean; isWritable: boolean; nodeReadableStream: NodeJS.ReadableStream | null; nextPushResolver: (() => void) | null; nextPush: Promise<void>; awaitingPush: boolean; constructor(optionsOrStreamLike: ObjectReadStreamOptions<T> | NodeJS.ReadableStream | T[] = {}) { this.buf = []; this.readSize = 0; this.atEOF = false; this.errorBuf = null; this.isReadable = true; this.isWritable = false; this.nodeReadableStream = null; this.nextPushResolver = null; this.nextPush = new Promise(resolve => { this.nextPushResolver = resolve; }); this.awaitingPush = false; let options: ObjectReadStreamOptions<T>; if (Array.isArray(optionsOrStreamLike)) { options = {buffer: optionsOrStreamLike}; } else if (typeof (optionsOrStreamLike as any)._readableState === 'object') { options = {nodeStream: optionsOrStreamLike as NodeJS.ReadableStream}; } else { options = optionsOrStreamLike as ObjectReadStreamOptions<T>; } if ((options as any).nodeStream) { const nodeStream: NodeJS.ReadableStream = (options as any).nodeStream; this.nodeReadableStream = nodeStream; nodeStream.on('data', data => { this.push(data); }); nodeStream.on('end', () => { this.pushEnd(); }); options = { read() { this.nodeReadableStream!.resume(); }, pause() { this.nodeReadableStream!.pause(); }, }; } if (options.read) this._read = options.read; if (options.pause) this._pause = options.pause; if (options.destroy) this._destroy = options.destroy; if (options.buffer !== undefined) { this.buf = options.buffer.slice(); this.pushEnd(); } } push(elem: T) { if (this.atEOF) return; this.buf.push(elem); if (this.buf.length > this.readSize && this.buf.length >= 16) void this._pause(); this.resolvePush(); } pushEnd() { this.atEOF = true; this.resolvePush(); } pushError(err: Error, recoverable?: boolean) { if (!this.errorBuf) this.errorBuf = []; this.errorBuf.push(err); if (!recoverable) this.atEOF = true; this.resolvePush(); } readError() { if (this.errorBuf) { const err = this.errorBuf.shift()!; if (!this.errorBuf.length) this.errorBuf = null; throw err; } } peekError() { if (this.errorBuf) { throw this.errorBuf[0]; } } resolvePush() { if (!this.nextPushResolver) throw new Error(`Push after end of read stream`); this.nextPushResolver(); if (this.atEOF) { this.nextPushResolver = null; return; } this.nextPush = new Promise(resolve => { this.nextPushResolver = resolve; }); } _read(size = 0): void | Promise<void> { throw new Error(`ReadStream needs to be subclassed and the _read function needs to be implemented.`); } _destroy(): void | Promise<void> {} _pause(): void | Promise<void> {} async loadIntoBuffer(count: number | true = 1, readError?: boolean) { this[readError ? 'readError' : 'peekError'](); if (count === true) count = this.buf.length + 1; if (this.buf.length >= count) return; this.readSize = Math.max(count, this.readSize); while (!this.errorBuf && !this.atEOF && this.buf.length < this.readSize) { const readResult = this._read(); if (readResult) { await readResult; } else { await this.nextPush; } this[readError ? 'readError' : 'peekError'](); } } async peek() { if (this.buf.length) return this.buf[0]; await this.loadIntoBuffer(); return this.buf[0]; } async read() { if (this.buf.length) return this.buf.shift(); await this.loadIntoBuffer(1, true); if (!this.buf.length) return null; return this.buf.shift()!; } async peekArray(count: number | null = null) { await this.loadIntoBuffer(count === null ? 1 : count); return this.buf.slice(0, count === null ? Infinity : count); } async readArray(count: number | null = null) { await this.loadIntoBuffer(count === null ? 1 : count, true); const out = this.buf.slice(0, count === null ? Infinity : count); this.buf = this.buf.slice(out.length); return out; } async readAll() { await this.loadIntoBuffer(Infinity, true); const out = this.buf; this.buf = []; return out; } async peekAll() { await this.loadIntoBuffer(Infinity); return this.buf.slice(); } destroy() { this.atEOF = true; this.buf = []; this.resolvePush(); return this._destroy(); } // eslint-disable-next-line no-restricted-globals [Symbol.asyncIterator]() { return this; } async next() { if (this.buf.length) return {value: this.buf.shift() as T, done: false as const}; await this.loadIntoBuffer(1, true); if (!this.buf.length) return {value: undefined, done: true as const}; return {value: this.buf.shift() as T, done: false as const}; } async pipeTo(outStream: ObjectWriteStream<T>, options: {noEnd?: boolean} = {}) { let value, done; while (({value, done} = await this.next(), !done)) { await outStream.write(value!); } if (!options.noEnd) return outStream.writeEnd(); } } interface ObjectWriteStreamOptions<T> { _writableState?: any; nodeStream?: NodeJS.WritableStream; write?: (this: ObjectWriteStream<T>, data: T) => Promise<any> | undefined; writeEnd?: (this: ObjectWriteStream<T>) => Promise<any>; } export class ObjectWriteStream<T> { isReadable: boolean; isWritable: true; nodeWritableStream: NodeJS.WritableStream | null; constructor(optionsOrStream: ObjectWriteStreamOptions<T> | NodeJS.WritableStream = {}) { this.isReadable = false; this.isWritable = true; this.nodeWritableStream = null; let options: ObjectWriteStreamOptions<T> = optionsOrStream as any; if (options._writableState) { options = {nodeStream: optionsOrStream as NodeJS.WritableStream}; } if (options.nodeStream) { const nodeStream: NodeJS.WritableStream = options.nodeStream; this.nodeWritableStream = nodeStream; options.write = function (data: T) { const result = this.nodeWritableStream!.write(data as unknown as string); if (result === false) { return new Promise<void>(resolve => { this.nodeWritableStream!.once('drain', () => { resolve(); }); }); } }; // Prior to Node v10.12.0, attempting to close STDOUT or STDERR will throw if (nodeStream !== process.stdout && nodeStream !== process.stderr) { options.writeEnd = function () { return new Promise<void>(resolve => { this.nodeWritableStream!.end(() => resolve()); }); }; } } if (options.write) this._write = options.write; if (options.writeEnd) this._writeEnd = options.writeEnd; } write(elem: T | null): void | Promise<void> { if (elem === null) { return this.writeEnd(); } return this._write(elem); } _write(elem: T): void | Promise<void> { throw new Error(`WriteStream needs to be subclassed and the _write function needs to be implemented.`); } _writeEnd(): void | Promise<void> {} async writeEnd(elem?: T): Promise<void> { if (elem !== undefined) { await this.write(elem); } return this._writeEnd(); } } interface ObjectReadWriteStreamOptions<T> { read?: (this: ObjectReadStream<T>) => void | Promise<void>; pause?: (this: ObjectReadStream<T>) => void | Promise<void>; destroy?: (this: ObjectReadStream<T>) => void | Promise<void>; write?: (this: ObjectWriteStream<T>, elem: T) => Promise<any> | undefined | void; writeEnd?: () => Promise<any> | undefined | void; } export class ObjectReadWriteStream<T> extends ObjectReadStream<T> implements ObjectWriteStream<T> { isReadable: true; isWritable: true; nodeWritableStream: NodeJS.WritableStream | null; constructor(options: ObjectReadWriteStreamOptions<T> = {}) { super(options); this.isReadable = true; this.isWritable = true; this.nodeWritableStream = null; if (options.write) this._write = options.write; if (options.writeEnd) this._writeEnd = options.writeEnd; } write(elem: T): void | Promise<void> { return this._write(elem); } _write(elem: T): void | Promise<void> { throw new Error(`WriteStream needs to be subclassed and the _write function needs to be implemented.`); } /** In a ReadWriteStream, _read does not need to be implemented. */ _read() {} _writeEnd(): void | Promise<void> {} async writeEnd() { return this._writeEnd(); } } export function readAll(nodeStream: NodeJS.ReadableStream, encoding?: any) { return new ReadStream(nodeStream).readAll(encoding); } export function stdin() { return new ReadStream(process.stdin); } export function stdout() { return new WriteStream(process.stdout); } export function stdpipe(stream: WriteStream | ReadStream | ReadWriteStream) { const promises = []; if ((stream as ReadStream | WriteStream & {pipeTo: undefined}).pipeTo) { promises.push((stream as ReadStream).pipeTo(stdout())); } if ((stream as WriteStream | ReadStream & {write: undefined}).write) { promises.push(stdin().pipeTo(stream as WriteStream)); } return Promise.all(promises); }
the_stack
import { Spreadsheet, DialogBeforeOpenEventArgs } from '../index'; import { formulaOperation, keyUp, keyDown, click, refreshFormulaDatasource, formulaBarOperation, keyCodes } from '../common/index'; import { editOperation, dialog, locale, focus } from '../common/index'; import { AutoComplete } from '@syncfusion/ej2-dropdowns'; import { BeforeOpenEventArgs } from '@syncfusion/ej2-popups'; import { PopupEventArgs, SelectEventArgs, AutoCompleteModel } from '@syncfusion/ej2-dropdowns'; import { KeyboardEventArgs, L10n, detach, isNullOrUndefined, select } from '@syncfusion/ej2-base'; import { checkIsFormula, getSheet, SheetModel, getSheetName, DefineNameModel, getCellIndexes, isCellReference } from '../../workbook/index'; import { workbookFormulaOperation, Workbook } from '../../workbook/index'; import { Dialog } from '../services/index'; /** * @hidden * The `Formula` module is used to handle the formulas and its functionalities in Spreadsheet. */ export class Formula { private parent: Spreadsheet; private isFormulaBar: boolean = false; private isFormula: boolean = false; private isPopupOpened: boolean = false; private isPreventClose: boolean = false; private isSubFormula: boolean = false; public autocompleteInstance: AutoComplete; /** * Constructor for formula module in Spreadsheet. * * @private * @param {Spreadsheet} parent - Constructor for formula module in Spreadsheet. */ constructor(parent: Spreadsheet) { this.parent = parent; this.addEventListener(); //Spreadsheet.Inject(WorkbookFormula); } /** * Get the module name. * * @returns {string} - Get the module name. * @private */ public getModuleName(): string { return 'formula'; } /** * To destroy the formula module. * * @returns {void} - To destroy the formula module. * @hidden */ public destroy(): void { this.removeEventListener(); if (this.autocompleteInstance) { this.autocompleteInstance.destroy(); if (this.autocompleteInstance.element) { this.autocompleteInstance.element.remove(); } } this.autocompleteInstance = null; this.parent = null; } private addEventListener(): void { this.parent.on(formulaOperation, this.performFormulaOperation, this); this.parent.on(keyUp, this.keyUpHandler, this); this.parent.on(keyDown, this.keyDownHandler, this); this.parent.on(click, this.formulaClick, this); this.parent.on(refreshFormulaDatasource, this.refreshFormulaDatasource, this); } private removeEventListener(): void { if (!this.parent.isDestroyed) { this.parent.off(formulaOperation, this.performFormulaOperation); this.parent.off(keyUp, this.keyUpHandler); this.parent.off(keyDown, this.keyDownHandler); this.parent.off(click, this.formulaClick); this.parent.off(refreshFormulaDatasource, this.refreshFormulaDatasource); } } private performFormulaOperation(args: { [key: string]: Object }): void { const action: string = <string>args.action; const l10n: L10n = this.parent.serviceLocator.getService(locale); let dialogInst: Dialog; let dialogContent: string; switch (action) { case 'renderAutoComplete': this.renderAutoComplete(); break; case 'endEdit': this.endEdit(); break; case 'addDefinedName': args.isAdded = this.addDefinedName(<DefineNameModel>args.definedName); break; case 'getNames': if (!args.sheetName) { args.sheetName = getSheetName(this.parent as Workbook); } args.names = this.getNames(<string>args.sheetName); break; case 'getNameFromRange': args.definedName = this.getNameFromRange(<string>args.range); break; case 'isFormulaEditing': args.isFormulaEdit = this.isFormula; break; case 'isCircularReference': dialogInst = (this.parent.serviceLocator.getService(dialog) as Dialog); dialogContent = l10n.getConstant('CircularReference'); if (!(dialogInst.dialogInstance && dialogInst.dialogInstance.visible && dialogInst.dialogInstance.content === dialogContent)) { dialogInst.show({ height: 180, width: 400, isModal: true, showCloseIcon: true, content: l10n.getConstant('CircularReference'), beforeOpen: (args: BeforeOpenEventArgs): void => { const dlgArgs: DialogBeforeOpenEventArgs = { dialogName: 'CircularReferenceDialog', element: args.element, target: args.target, cancel: args.cancel }; this.parent.trigger('dialogBeforeOpen', dlgArgs); if (dlgArgs.cancel) { args.cancel = true; } } }); } args.argValue = '0'; break; } } private renderAutoComplete(): void { if (!select('#' + this.parent.element.id + '_ac', this.parent.element)) { const acElem: HTMLInputElement = this.parent.createElement( 'input', { id: this.parent.element.id + '_ac', className: 'e-ss-ac' }) as HTMLInputElement; this.parent.element.appendChild(acElem); const eventArgs: { action: string, formulaCollection: string[] } = { action: 'getLibraryFormulas', formulaCollection: [] }; this.parent.notify(workbookFormulaOperation, eventArgs); const autoCompleteOptions: AutoCompleteModel = { dataSource: eventArgs.formulaCollection, cssClass: 'e-ss-atc', popupWidth: '130px', allowFiltering: true, filterType: 'StartsWith', sortOrder: 'Ascending', open: this.onSuggestionOpen.bind(this), close: this.onSuggestionClose.bind(this), select: this.onSelect.bind(this), actionComplete: this.onSuggestionComplete.bind(this) }; this.autocompleteInstance = new AutoComplete(autoCompleteOptions, acElem); this.autocompleteInstance.createElement = this.parent.createElement; } } private onSuggestionOpen(e: PopupEventArgs): void { this.isPopupOpened = true; e.popup.relateTo = this.getRelateToElem(); (<HTMLElement>e.popup.element.firstChild).style.maxHeight = '180px'; // eslint-disable-next-line @typescript-eslint/no-unused-vars new Promise((resolve: Function, reject: Function) => { setTimeout(() => { resolve(); }, 100); }).then(() => { this.triggerKeyDownEvent(keyCodes.DOWN); }); } private onSuggestionClose(e: PopupEventArgs): void { if (this.isPreventClose) { e.cancel = true; } else { this.isPopupOpened = false; } } private onSelect(e: SelectEventArgs): void { let updatedFormulaValue: string = '=' + e.itemData.value + '('; if (this.isSubFormula) { const editValue: string = this.getEditingValue(); let parseIndex: number = editValue.lastIndexOf(this.getArgumentSeparator()); if (parseIndex > -1) { updatedFormulaValue = editValue.slice(0, parseIndex + 1); } else { parseIndex = editValue.lastIndexOf('('); if (parseIndex > -1) { updatedFormulaValue = editValue.slice(0, parseIndex + 1); } } updatedFormulaValue += e.itemData.value + '('; } this.parent.notify( editOperation, { action: 'refreshEditor', value: updatedFormulaValue, refreshFormulaBar: true, refreshEditorElem: true, refreshCurPos: !this.isFormulaBar }); if (this.isPopupOpened) { this.hidePopUp(); const suggPopupElem: HTMLElement = select('#' + this.parent.element.id + '_ac_popup'); if (suggPopupElem) { detach(suggPopupElem); } this.isPopupOpened = false; } } private onSuggestionComplete(args: { result: string[], cancel: boolean }): void { this.isPreventClose = args.result.length > 0; if (!this.isPreventClose) { args.cancel = true; this.hidePopUp(); } } private refreshFormulaDatasource(): void { const eventArgs: { action: string, formulaCollection: string[] } = { action: 'getLibraryFormulas', formulaCollection: [] }; this.parent.notify(workbookFormulaOperation, eventArgs); this.autocompleteInstance.dataSource = eventArgs.formulaCollection; } private keyUpHandler(e: KeyboardEventArgs): void { if (this.parent.isEdit) { let editValue: string = this.getEditingValue(); this.isFormula = checkIsFormula(editValue); if (this.isFormula || this.isPopupOpened) { if (e.keyCode !== keyCodes.TAB && this.isFormula) { editValue = this.getSuggestionKeyFromFormula(editValue); } this.refreshFormulaSuggestion(e, editValue); } } else if (this.isPopupOpened) { this.hidePopUp(); } } private keyDownHandler(e: KeyboardEventArgs): void { const keyCode: number = e.keyCode; if (this.isFormula) { if (this.isPopupOpened) { switch (keyCode) { case keyCodes.UP: case keyCodes.DOWN: e.preventDefault(); this.triggerKeyDownEvent(keyCode); break; case keyCodes.TAB: e.preventDefault(); this.triggerKeyDownEvent(keyCodes.ENTER); break; } } } else { const trgtElem: HTMLInputElement = <HTMLInputElement>e.target; if (trgtElem.id === this.parent.element.id + '_name_box') { switch (keyCode) { case keyCodes.ENTER: this.addDefinedName({ name: trgtElem.value }); focus(this.parent.element); break; case keyCodes.ESC: focus(this.parent.element); break; } } } } private formulaClick(e: MouseEvent & TouchEvent): void { if (this.parent.isEdit) { const trgtElem: HTMLElement = <HTMLElement>e.target; this.isFormulaBar = trgtElem.classList.contains('e-formula-bar'); } } private refreshFormulaSuggestion(e: KeyboardEventArgs, formula: string): void { if (formula.length > 0) { const autoCompleteElem: HTMLInputElement = <HTMLInputElement>this.autocompleteInstance.element; const keyCode: number = e.keyCode; const isSuggestionAlreadyOpened: boolean = this.isPopupOpened; if (!this.isNavigationKey(keyCode)) { autoCompleteElem.value = formula; autoCompleteElem.dispatchEvent(new Event('input')); autoCompleteElem.dispatchEvent(new Event('keyup')); if (isSuggestionAlreadyOpened) { this.triggerKeyDownEvent(keyCodes.DOWN); } } } else { if (this.isPopupOpened) { this.isPreventClose = false; this.hidePopUp(); } } } private endEdit(): void { this.isSubFormula = false; this.isPreventClose = false; this.isFormula = false; this.isFormulaBar = false; if (this.isPopupOpened) { this.hidePopUp(); const suggPopupElem: HTMLElement = select('#' + this.parent.element.id + '_ac_popup'); if (suggPopupElem) { detach(suggPopupElem); } this.isPopupOpened = false; } } private hidePopUp(): void { this.autocompleteInstance.hidePopup(); } private getSuggestionKeyFromFormula(formula: string): string { let suggestValue: string = ''; formula = formula.substr(1); //remove = char. if (formula) { const bracketIndex: number = formula.lastIndexOf('('); formula = formula.substr(bracketIndex + 1); const fSplit: string[] = formula.split(this.getArgumentSeparator()); if (fSplit.length === 1) { suggestValue = fSplit[0]; this.isSubFormula = bracketIndex > -1; } else { suggestValue = fSplit[fSplit.length - 1]; this.isSubFormula = true; } const isAlphaNumeric: RegExpMatchArray = suggestValue.match(/\w/); if (!isAlphaNumeric || (isAlphaNumeric && isAlphaNumeric.index !== 0)) { suggestValue = ''; } } return suggestValue; } private getRelateToElem(): HTMLElement { const eventArgs: { action: string, element?: HTMLElement } = { action: 'getElement' }; if (this.isFormulaBar) { this.parent.notify(formulaBarOperation, eventArgs); } else { this.parent.notify(editOperation, eventArgs); } return eventArgs.element; } private getEditingValue(): string { const eventArgs: { action: string, editedValue: string } = { action: 'getCurrentEditValue', editedValue: '' }; this.parent.notify(editOperation, eventArgs); return eventArgs.editedValue; } private isNavigationKey(keyCode: number): boolean { return (keyCode === keyCodes.UP) || (keyCode === keyCodes.DOWN) || (keyCode === keyCodes.LEFT) || (keyCode === keyCodes.RIGHT); } private triggerKeyDownEvent(keyCode: number): void { const autoCompleteElem: HTMLInputElement = <HTMLInputElement>this.autocompleteInstance.element; autoCompleteElem.dispatchEvent(new Event('input')); const eventArg: Event = new Event('keydown'); eventArg['keyCode'] = keyCode; eventArg['which'] = keyCode; eventArg['altKey'] = false; eventArg['shiftKey'] = false; eventArg['ctrlKey'] = false; /* eslint-enable @typescript-eslint/dot-notation */ autoCompleteElem.dispatchEvent(eventArg); } private getArgumentSeparator(): string { const eventArgs: { action: string, argumentSeparator: string } = { action: 'getArgumentSeparator', argumentSeparator: '' }; this.parent.notify(workbookFormulaOperation, eventArgs); return eventArgs.argumentSeparator; } private getNames(sheetName?: string): DefineNameModel[] { const names: DefineNameModel[] = this.parent.definedNames.filter( (name: DefineNameModel) => name.scope === 'Workbook' || name.scope === '' || name.scope === sheetName); return names; } private getNameFromRange(range: string): DefineNameModel { const singleRange: string = range.slice(0, range.indexOf(':')); const sRange: string[] = range.slice(range.indexOf('!') + 1).split(':'); const isSingleCell: boolean = sRange.length > 1 && sRange[0] === sRange[1]; const name: DefineNameModel[] = this.parent.definedNames.filter( (name: DefineNameModel) => { if (isSingleCell && name.refersTo === '=' + singleRange) { return true; } return name.refersTo === '=' + range; }); return name && name[0]; } private addDefinedName(definedName: DefineNameModel): boolean { const name: string = definedName.name; let isAdded: boolean = false; if (name && isCellReference(name.toUpperCase())) { this.parent.goTo(name); return isAdded; } if (!definedName.refersTo) { const sheet: SheetModel = getSheet(this.parent as Workbook, this.parent.activeSheetIndex); let sheetName: string = getSheetName(this.parent as Workbook); sheetName = sheetName.indexOf(' ') !== -1 ? '\'' + sheetName + '\'' : sheetName; let selectRange: string = sheet.selectedRange; if (!isNullOrUndefined(selectRange)) { const colIndex: number = selectRange.indexOf(':'); let left: string = selectRange.substr(0, colIndex); let right: string = selectRange.substr(colIndex + 1, selectRange.length); if (parseInt(right.replace(/\D/g, ''), 10) === sheet.rowCount && parseInt(left.replace(/\D/g, ''), 10) === 1) { right = right.replace(/[0-9]/g, ''); left = left.replace(/[0-9]/g, ''); selectRange = '$' + left + ':$' + right; } else if (getCellIndexes(right)[1] === sheet.colCount - 1 && getCellIndexes(left)[1] === 0) { right = right.replace(/\D/g, ''); left = left.replace(/\D/g, ''); selectRange = '$' + left + ':$' + right; } else { selectRange = left === right ? left : selectRange; } } definedName.refersTo = sheetName + '!' + selectRange; definedName.scope = 'Workbook'; } if (name.length > 0 && (/^([a-zA-Z_0-9.]){0,255}$/.test(name))) { const eventArgs: { [key: string]: Object } = { action: 'addDefinedName', definedName: definedName, isAdded: false }; this.parent.notify(workbookFormulaOperation, eventArgs); isAdded = <boolean>eventArgs.isAdded; if (!eventArgs.isAdded) { (this.parent.serviceLocator.getService(dialog) as Dialog).show({ content: (this.parent.serviceLocator.getService(locale) as L10n).getConstant('DefineNameExists'), width: '300', beforeOpen: (args: BeforeOpenEventArgs): void => { const dlgArgs: DialogBeforeOpenEventArgs = { dialogName: 'DefineNameExistsDialog', element: args.element, target: args.target, cancel: args.cancel }; this.parent.trigger('dialogBeforeOpen', dlgArgs); if (dlgArgs.cancel) { args.cancel = true; } } }); } } else { (this.parent.serviceLocator.getService(dialog) as Dialog).show({ content: (this.parent.serviceLocator.getService(locale) as L10n).getConstant('DefineNameInValid'), width: '300', beforeOpen: (args: BeforeOpenEventArgs): void => { const dlgArgs: DialogBeforeOpenEventArgs = { dialogName: 'DefineNameInValidDialog', element: args.element, target: args.target, cancel: args.cancel }; this.parent.trigger('dialogBeforeOpen', dlgArgs); if (dlgArgs.cancel) { args.cancel = true; } } }); } return isAdded; } }
the_stack
class PartMeshGenerator extends MeshGenerator { private smallBlocks: VectorDictionary<SmallBlock>; private tinyBlocks: VectorDictionary<TinyBlock>; constructor(part: Part, measurements: Measurements) { super(measurements); this.smallBlocks = part.createSmallBlocks(); this.createDummyBlocks(); this.updateRounded(); this.createTinyBlocks(); this.processTinyBlocks(); this.checkInteriors(); this.mergeSimilarBlocks(); this.renderPerpendicularRoundedAdapters(); this.renderRoundedExteriors(); this.renderInteriors(); this.renderAttachments(); this.renderTinyBlockFaces(); } private updateRounded() { var perpendicularRoundedAdapters: SmallBlock[] = []; for (var block of this.smallBlocks.values()) { if (block.isAttachment) { block.rounded = true; continue; } if (!block.rounded) { continue; } var next = this.smallBlocks.getOrNull(block.position.plus(block.forward)); if (next != null && next.orientation == block.orientation && next.quadrant != block.quadrant) { block.rounded = false; continue; } var previous = this.smallBlocks.getOrNull(block.position.minus(block.forward)); if (previous != null && previous.orientation == block.orientation && previous.quadrant != block.quadrant) { block.rounded = false; continue; } var neighbor1 = this.smallBlocks.getOrNull(block.position.plus(block.horizontal)); var neighbor2 = this.smallBlocks.getOrNull(block.position.plus(block.vertical)); if ((neighbor1 == null || (neighbor1.isAttachment && neighbor1.forward.dot(block.right) == 0)) && (neighbor2 == null || (neighbor2.isAttachment && neighbor2.forward.dot(block.up) == 0))) { continue; } if (this.createPerpendicularRoundedAdapterIfPossible(block)) { perpendicularRoundedAdapters.push(block); continue; } block.rounded = false; } // Remove adapters where the neighbor was later changed from rounded to not rounded var anythingChanged: boolean; do { anythingChanged = false; for (var block of perpendicularRoundedAdapters) { if (block.perpendicularRoundedAdapter != null && !block.perpendicularRoundedAdapter.neighbor.rounded) { block.perpendicularRoundedAdapter = null; block.rounded = false; anythingChanged = true; } } } while (anythingChanged); } private createDummyBlocks() { var addedAnything = false; for (var block of this.smallBlocks.values()) { if (!block.isAttachment) { continue; } var affectedPositions = [ block.position, block.position.minus(block.horizontal), block.position.minus(block.vertical), block.position.minus(block.horizontal).minus(block.vertical) ]; for (var forwardDirection = -1; forwardDirection <= 1; forwardDirection += 2) { var count = countInArray(affectedPositions, (p) => this.smallBlocks.containsKey(p.plus(block.forward.times(forwardDirection)))); if (count != 0 && count != 4) { var source = new Block(block.orientation, BlockType.Solid, true); for (var position of affectedPositions) { var targetPosition = position.plus(block.forward.times(forwardDirection)); if (!this.smallBlocks.containsKey(targetPosition)) { this.smallBlocks.set(targetPosition, new SmallBlock(this.smallBlocks.get(position).quadrant, targetPosition, source)); } } addedAnything = true; } } } if (addedAnything) { this.createDummyBlocks(); } } private createPerpendicularRoundedAdapterIfPossible(block: SmallBlock): boolean { var neighbor1 = this.smallBlocks.getOrNull(block.position.plus(block.horizontal)); var neighbor2 = this.smallBlocks.getOrNull(block.position.plus(block.vertical)); var hasHorizontalNeighbor = neighbor2 == null && neighbor1 != null && neighbor1.forward.dot(block.horizontal) != 0 && neighbor1.rounded; var hasVerticalNeighbor = neighbor1 == null && neighbor2 != null && neighbor2.forward.dot(block.vertical) != 0 && neighbor2.rounded; if (hasHorizontalNeighbor == hasVerticalNeighbor) { return false; } var adapter = new PerpendicularRoundedAdapter(); adapter.directionToNeighbor = hasVerticalNeighbor ? block.vertical : block.horizontal; adapter.isVertical = hasVerticalNeighbor; adapter.neighbor = hasHorizontalNeighbor ? neighbor1 : neighbor2; adapter.facesForward = block.forward.dot(adapter.neighbor.horizontal.plus(adapter.neighbor.vertical)) < 0; adapter.sourceBlock = block; if (!this.smallBlocks.containsKey(block.position.plus(block.forward.times(adapter.facesForward ? 1 : -1)))) { return false; } block.perpendicularRoundedAdapter = adapter; return true; } private createTinyBlocks() { this.tinyBlocks = new VectorDictionary<TinyBlock>(); for (let block of this.smallBlocks.values()) { if (block.isAttachment) { continue; } let pos = block.position; for (var a = -1; a <= 1; a++) { for (var b = -1; b <= 1; b++) { for (var c = -1; c <= 1; c++) { if (this.isSmallBlock(pos.plus(new Vector3(a, 0, 0))) && this.isSmallBlock(pos.plus(new Vector3(0, b, 0))) && this.isSmallBlock(pos.plus(new Vector3(0, 0, c))) && this.isSmallBlock(pos.plus(new Vector3(a, b, c))) && this.isSmallBlock(pos.plus(new Vector3(a, b, 0))) && this.isSmallBlock(pos.plus(new Vector3(a, 0, c))) && this.isSmallBlock(pos.plus(new Vector3(0, b, c)))) { this.createTinyBlock(pos.times(3).plus(new Vector3(a, b, c)), block); } } } } } for (let block of this.smallBlocks.values()) { if (!block.isAttachment) { continue; } for (var a = -2; a <= 2; a++) { var neighbor = block.position.plus(block.forward.times(sign(a))); if (!this.smallBlocks.containsKey(neighbor) || (Math.abs(a) >= 2 && this.smallBlocks.get(neighbor).isAttachment)) { continue; } for (var b = -1; b <= 0; b++) { for (var c = -1; c <= 0; c++) { this.createTinyBlock(block.position.times(3).plus(block.forward.times(a)).plus(block.horizontal.times(b)).plus(block.vertical.times(c)), block); } } } } } private isTinyBlock(position: Vector3): boolean { return this.tinyBlocks.containsKey(position) && !this.tinyBlocks.get(position).isAttachment; } private pushBlock(smallBlock: SmallBlock, forwardFactor: number) { var nextBlock = this.smallBlocks.getOrNull(smallBlock.position.plus(smallBlock.forward.times(forwardFactor))); for (var a = -2; a <= 2; a++) { for (var b = -2; b <= 2; b++) { var from = smallBlock.position.times(3) .plus(smallBlock.right.times(a)) .plus(smallBlock.up.times(b)) .plus(smallBlock.forward.times(forwardFactor)); var to = from.plus(smallBlock.forward.times(forwardFactor)); if (!this.tinyBlocks.containsKey(to)) { continue; } if (!this.tinyBlocks.containsKey(from)) { this.tinyBlocks.remove(to); continue; } if (smallBlock.orientation == nextBlock.orientation) { if (Math.abs(a) < 2 && Math.abs(b) < 2) { this.tinyBlocks.get(to).rounded = true; } } else { this.createTinyBlock(to, this.tinyBlocks.get(from)); } } } } private processTinyBlocks() { // Disable interiors when adjacent quadrants are missing for (var block of this.tinyBlocks.values()) { if (block.isCenter && !block.isAttachment && (block.hasInterior || block.rounded) && (!this.isTinyBlock(block.position.minus(block.horizontal.times(3))) || !this.isTinyBlock(block.position.minus(block.vertical.times(3))))) { for (var a = -1; a <= 1; a++) { for (var b = -1; b <= 1; b++) { var position = block.position.plus(block.right.times(a)).plus(block.up.times(b)); if (this.tinyBlocks.containsKey(position)) { this.tinyBlocks.get(position).rounded = false; this.tinyBlocks.get(position).hasInterior = false; } } } } } for (var smallBlock of this.smallBlocks.values()) { var nextBlock = this.smallBlocks.getOrNull(smallBlock.position.plus(smallBlock.forward)); // Offset rounded to non rounded transitions to make them flush if (smallBlock.rounded && nextBlock != null && !nextBlock.rounded && smallBlock.perpendicularRoundedAdapter == null) { this.pushBlock(smallBlock, 1); } var previousBlock = this.smallBlocks.getOrNull(smallBlock.position.minus(smallBlock.forward)); // Offset rounded to non rounded transitions to make them flush if (smallBlock.rounded && previousBlock != null && !previousBlock.rounded && smallBlock.perpendicularRoundedAdapter == null) { this.pushBlock(smallBlock, -1); } if (smallBlock.rounded && nextBlock != null && nextBlock.rounded && smallBlock.orientation != nextBlock.orientation) { this.pushBlock(smallBlock, 1); } if (smallBlock.rounded && previousBlock != null && previousBlock.rounded && smallBlock.orientation != previousBlock.orientation) { this.pushBlock(smallBlock, -1); } } } // Sets HasInterior to false for all tiny blocks that do not form coherent blocks with their neighbors private checkInteriors() { for (var block of this.tinyBlocks.values()) { if (!block.isCenter || !block.hasInterior) { continue; } for (var a = 0; a <= 1; a++) { for (var b = 1 - a; b <= 1; b++) { var neighborPos = block.position.minus(block.horizontal.times(3 * a)).minus(block.vertical.times(3 * b)); if (!this.tinyBlocks.containsKey(neighborPos)) { block.hasInterior = false; } else { var neighbor = this.tinyBlocks.get(neighborPos); if (block.orientation != neighbor.orientation || block.type != neighbor.type || neighbor.localX != block.localX - a * block.directionX || neighbor.localY != block.localY - b * block.directionY) { block.hasInterior = false; } } } } } } private getPerpendicularRoundedNeighborOrNull(block: TinyBlock): SmallBlock { var verticalNeighbor = this.smallBlocks.getOrNull(block.smallBlockPosition.plus(block.vertical)); var horizontalNeighbor = this.smallBlocks.getOrNull(block.smallBlockPosition.plus(block.horizontal)); var neighbor = verticalNeighbor != null ? verticalNeighbor : horizontalNeighbor; var verticalOrHorizontal = verticalNeighbor != null ? block.vertical : block.horizontal; if (neighbor != null && neighbor.rounded && neighbor.forward.dot(verticalOrHorizontal) != 0) { return neighbor; } else { return null; } } private getPerpendicularRoundedNeighborOrNull2(block: TinyBlock): SmallBlock { var smallBlock = this.smallBlocks.get(block.smallBlockPosition); if (smallBlock.perpendicularRoundedAdapter != null) { return smallBlock.perpendicularRoundedAdapter.neighbor; } else { return null; } } private preventMergingForPerpendicularRoundedBlock(block1: TinyBlock, block2: TinyBlock): boolean { if (!block1.rounded || !block2.rounded || !block1.isCenter) { return false; } var neighbor1 = this.getPerpendicularRoundedNeighborOrNull(block1); var neighbor2 = this.getPerpendicularRoundedNeighborOrNull(block2); var inside1 = neighbor1 != null && block1.position.minus(neighbor1.position.times(3)).dot(neighbor1.vertical.plus(neighbor1.horizontal)) <= 0; var inside2 = neighbor2 != null && block2.position.minus(neighbor2.position.times(3)).dot(neighbor2.vertical.plus(neighbor2.horizontal)) <= 0; return inside1 != inside2 || (inside1 && inside2 && !neighbor1.position.equals(neighbor2.position)); } private mergeSimilarBlocks() { for (var block of this.tinyBlocks.values()) { if (block.isExteriorMerged) { continue; } var amount = 0; while (true) { var pos = block.position.plus(block.forward.times(amount + 1)); if (!this.tinyBlocks.containsKey(pos)) { break; } var nextBlock = this.tinyBlocks.get(pos); if (nextBlock.orientation != block.orientation || nextBlock.quadrant != block.quadrant || nextBlock.isAttachment != block.isAttachment || nextBlock.hasInterior != block.hasInterior || (nextBlock.isAttachment && (nextBlock.type != block.type)) || nextBlock.rounded != block.rounded || this.isTinyBlock(block.position.plus(block.right)) != this.isTinyBlock(nextBlock.position.plus(block.right)) || this.isTinyBlock(block.position.minus(block.right)) != this.isTinyBlock(nextBlock.position.minus(block.right)) || this.isTinyBlock(block.position.plus(block.up)) != this.isTinyBlock(nextBlock.position.plus(block.up)) || this.isTinyBlock(block.position.minus(block.up)) != this.isTinyBlock(nextBlock.position.minus(block.up)) || this.preventMergingForPerpendicularRoundedBlock(this.tinyBlocks.get(block.position.plus(block.forward.times(amount))), nextBlock)) { break; } amount += nextBlock.exteriorMergedBlocks; nextBlock.isExteriorMerged = true; if (nextBlock.exteriorMergedBlocks != 1) { break; } } block.exteriorMergedBlocks += amount; } for (var block of this.tinyBlocks.values()) { if (block.isInteriorMerged || !block.hasInterior) { continue; } var amount = 0; while (true) { var pos = block.position.plus(block.forward.times(amount + 1)); if (!this.tinyBlocks.containsKey(pos)) { break; } var nextBlock = this.tinyBlocks.get(pos); if (!nextBlock.hasInterior || nextBlock.orientation != block.orientation || nextBlock.quadrant != block.quadrant || nextBlock.type != block.type) { break; } amount += nextBlock.interiorMergedBlocks; nextBlock.isInteriorMerged = true; if (nextBlock.interiorMergedBlocks != 1) { break; } } block.interiorMergedBlocks += amount; } } private isSmallBlock(position: Vector3): boolean { return this.smallBlocks.containsKey(position) && !this.smallBlocks.get(position).isAttachment; } private createTinyBlock(position: Vector3, source: SmallBlock) { this.tinyBlocks.set(position, new TinyBlock(position, source)); } private getNextBlock(block: TinyBlock, interior: boolean): TinyBlock { var mergedAmount = interior ? block.interiorMergedBlocks : block.exteriorMergedBlocks; return this.tinyBlocks.getOrNull(block.position.plus(block.forward.times(mergedAmount))); } private getPreviousBlock(block: TinyBlock): TinyBlock { return this.tinyBlocks.getOrNull(block.position.minus(block.forward)); } private hasOpenEnd(block: TinyBlock, interior: boolean): boolean { var pos = block.position; var mergedAmount = interior ? block.interiorMergedBlocks : block.exteriorMergedBlocks; return !this.tinyBlocks.containsKey(pos.plus(block.forward.times(mergedAmount))) && !this.tinyBlocks.containsKey(pos.plus(block.forward.times(mergedAmount)).minus(block.horizontal.times(3))) && !this.tinyBlocks.containsKey(pos.plus(block.forward.times(mergedAmount)).minus(block.vertical.times(3))) && !this.tinyBlocks.containsKey(pos.plus(block.forward.times(mergedAmount)).minus(block.horizontal.times(3)).minus(block.vertical.times(3))); } private hasOpenStart(block: TinyBlock): boolean { var pos = block.position; return !this.tinyBlocks.containsKey(pos.minus(block.forward)) && !this.tinyBlocks.containsKey(pos.minus(block.forward).minus(block.horizontal.times(3))) && !this.tinyBlocks.containsKey(pos.minus(block.forward).minus(block.vertical.times(3))) && !this.tinyBlocks.containsKey(pos.minus(block.forward).minus(block.horizontal.times(3)).minus(block.vertical.times(3))); } private hideStartEndFaces(position: Vector3, block: TinyBlock, forward: boolean) { var direction = forward ? block.forward : block.forward.times(-1); this.hideFaceIfExists(position, direction); this.hideFaceIfExists(position.minus(block.horizontal), direction); this.hideFaceIfExists(position.minus(block.vertical), direction); this.hideFaceIfExists(position.minus(block.vertical).minus(block.horizontal), direction); } private hideFaceIfExists(position: Vector3, direction: Vector3) { if (this.tinyBlocks.containsKey(position)) { this.tinyBlocks.get(position).hideFace(direction); } } private hideOutsideFaces(centerBlock: TinyBlock) { var vertical = centerBlock.vertical; var horizontal = centerBlock.horizontal; centerBlock.hideFace(vertical); centerBlock.hideFace(horizontal); this.tinyBlocks.get(centerBlock.position.minus(vertical)).hideFace(horizontal); this.tinyBlocks.get(centerBlock.position.minus(horizontal)).hideFace(vertical); } private renderPerpendicularRoundedAdapters() { for (var block of this.smallBlocks.values()) { if (block.perpendicularRoundedAdapter == null) { continue; } var adapter = block.perpendicularRoundedAdapter; var center = block.forward.times(this.tinyIndexToWorld(block.forward.dot(block.position) * 3 - (adapter.facesForward ? 0 : 1))) .plus(block.right.times((block.position.dot(block.right) + (1 - block.localX)) * 0.5)) .plus(block.up.times((block.position.dot(block.up) + (1 - block.localY)) * 0.5)); var radius = 0.5 - this.measurements.edgeMargin; var forward = block.forward; for (var i = 0; i < this.measurements.subdivisionsPerQuarter; i++) { var angle1 = Math.PI / 2 * i / this.measurements.subdivisionsPerQuarter; var angle2 = Math.PI / 2 * (i + 1) / this.measurements.subdivisionsPerQuarter; var sincos1 = 1 - (block.odd() == adapter.isVertical ? Math.sin(angle1) : Math.cos(angle1)); var sincos2 = 1 - (block.odd() == adapter.isVertical ? Math.sin(angle2) : Math.cos(angle2)); let vertex1 = center.plus(block.getOnCircle(angle1).times(radius)).plus(forward.times(adapter.facesForward ? 0 : radius)); let vertex2 = center.plus(block.getOnCircle(angle2).times(radius)).plus(forward.times(adapter.facesForward ? 0 : radius)); var vertex3 = vertex2.plus(forward.times(sincos2 * (adapter.facesForward ? 1 : -1) * radius)); var vertex4 = vertex1.plus(forward.times(sincos1 * (adapter.facesForward ? 1 : -1) * radius)); var normal1 = block.getOnCircle(angle1).times(adapter.facesForward ? 1 : -1); var normal2 = block.getOnCircle(angle2).times(adapter.facesForward ? 1 : -1); this.createQuadWithNormals( vertex1, vertex2, vertex3, vertex4, normal1, normal2, normal2, normal1, adapter.facesForward); var invertAngle = ((adapter.isVertical ? block.localY : block.localX) != 1) != adapter.facesForward; var vertex5 = vertex4.plus(adapter.directionToNeighbor.times(radius * sincos1)); var vertex6 = vertex3.plus(adapter.directionToNeighbor.times(radius * sincos2)); var normal3 = adapter.neighbor.getOnCircle(invertAngle ? angle1 : Math.PI / 2 - angle1).times(adapter.facesForward ? -1 : 1); var normal4 = adapter.neighbor.getOnCircle(invertAngle ? angle2 : Math.PI / 2 - angle2).times(adapter.facesForward ? -1 : 1); this.createQuadWithNormals( vertex5, vertex6, vertex3, vertex4, normal3, normal4, normal4, normal3, !adapter.facesForward); } } } private isPerpendicularRoundedAdapter(block: TinyBlock) { if (block.perpendicularRoundedAdapter == null) { return false; } var localForward = block.position.minus(block.perpendicularRoundedAdapter.sourceBlock.position.times(3)).dot(block.forward); return localForward == 0 || (localForward > 0) == block.perpendicularRoundedAdapter.facesForward; } private renderRoundedExteriors() { var blockSizeWithoutMargin = 0.5 - this.measurements.edgeMargin; for (let block of this.tinyBlocks.values()) { if (block.isExteriorMerged || !block.isCenter || block.isAttachment) { continue; } var nextBlock = this.getNextBlock(block, false); var previousBlock = this.getPreviousBlock(block); var distance = block.getExteriorDepth(this); var hasOpenEnd = this.hasOpenEnd(block, false); var hasOpenStart = this.hasOpenStart(block); // Back cap if (nextBlock == null && (block.rounded || block.hasInterior)) { this.createCircleWithHole(block, block.hasInterior && hasOpenEnd ? this.measurements.interiorRadius : 0, blockSizeWithoutMargin, distance, false, !block.rounded); this.hideStartEndFaces(block.position.plus(block.forward.times(block.exteriorMergedBlocks - 1)), block, true); } // Front cap if (previousBlock == null && (block.rounded || block.hasInterior)) { this.createCircleWithHole(block, block.hasInterior && hasOpenStart ? this.measurements.interiorRadius : 0, blockSizeWithoutMargin, 0, true, !block.rounded); this.hideStartEndFaces(block.position, block, false); } if (block.rounded) { if (!this.isPerpendicularRoundedAdapter(block)) { this.createCylinder(block, 0, blockSizeWithoutMargin, distance); // Rounded to non rounded adapter if (nextBlock != null && !nextBlock.rounded) { this.createCircleWithHole(block, blockSizeWithoutMargin, blockSizeWithoutMargin, distance, true, true); } if (previousBlock != null && !previousBlock.rounded) { this.createCircleWithHole(block, blockSizeWithoutMargin, blockSizeWithoutMargin, 0, false, true); } } // Rounded corners for (var i = 0; i < block.exteriorMergedBlocks; i++) { this.hideOutsideFaces(this.tinyBlocks.get(block.position.plus(block.forward.times(i)))); } } } } private renderInteriors() { for (let block of this.tinyBlocks.values()) { if (block.isInteriorMerged || !block.isCenter || !block.hasInterior) { continue; } if (block.type == BlockType.PinHole) { this.renderPinHoleInterior(block); } else if (block.type == BlockType.AxleHole) { this.renderAxleHoleInterior(block); } } } private renderAttachments() { for (var block of this.tinyBlocks.values()) { if (block.isExteriorMerged || !block.isCenter) { continue; } switch (block.type) { case BlockType.Pin: this.renderPin(block); break; case BlockType.Axle: this.renderAxle(block); break; case BlockType.BallJoint: this.renderBallJoint(block); break; } } } private renderLip(block: TinyBlock, zOffset: number) { var center = block.getCylinderOrigin(this).plus(block.forward.times(zOffset)); for (var i = 0; i < this.measurements.subdivisionsPerQuarter; i++) { var out1 = block.getOnCircle(i / 2 * Math.PI / this.measurements.subdivisionsPerQuarter); var out2 = block.getOnCircle((i + 1) / 2 * Math.PI / this.measurements.subdivisionsPerQuarter); for (var j = 0; j < this.measurements.lipSubdivisions; j++) { var angleJ = j * Math.PI / this.measurements.lipSubdivisions; var angleJ2 = (j + 1) * Math.PI / this.measurements.lipSubdivisions; this.createQuadWithNormals( center.plus(out1.times(this.measurements.pinRadius)).plus(out1.times(Math.sin(angleJ) * this.measurements.pinLipRadius).plus(block.forward.times(Math.cos(angleJ) * this.measurements.pinLipRadius))), center.plus(out2.times(this.measurements.pinRadius)).plus(out2.times(Math.sin(angleJ) * this.measurements.pinLipRadius).plus(block.forward.times(Math.cos(angleJ) * this.measurements.pinLipRadius))), center.plus(out2.times(this.measurements.pinRadius)).plus(out2.times(Math.sin(angleJ2) * this.measurements.pinLipRadius).plus(block.forward.times(Math.cos(angleJ2) * this.measurements.pinLipRadius))), center.plus(out1.times(this.measurements.pinRadius)).plus(out1.times(Math.sin(angleJ2) * this.measurements.pinLipRadius).plus(block.forward.times(Math.cos(angleJ2) * this.measurements.pinLipRadius))), out1.times(-Math.sin(angleJ)).plus(block.forward.times(-Math.cos(angleJ))), out2.times(-Math.sin(angleJ)).plus(block.forward.times(-Math.cos(angleJ))), out2.times(-Math.sin(angleJ2)).plus(block.forward.times(-Math.cos(angleJ2))), out1.times(-Math.sin(angleJ2)).plus(block.forward.times(-Math.cos(angleJ2)))); } } } private renderPin(block: TinyBlock) { var nextBlock = this.getNextBlock(block, false); var previousBlock = this.getPreviousBlock(block); var distance = block.getExteriorDepth(this); var startOffset = (previousBlock != null && previousBlock.isAttachment && previousBlock.type != BlockType.Pin) ? this.measurements.attachmentAdapterSize : 0; if (previousBlock == null) { startOffset += 2 * this.measurements.pinLipRadius; } var endOffset = (nextBlock != null && nextBlock.isAttachment && nextBlock.type != BlockType.Pin) ? this.measurements.attachmentAdapterSize : 0; if (nextBlock == null) { endOffset += 2 * this.measurements.pinLipRadius; } this.createCylinder(block, startOffset, this.measurements.pinRadius, distance - startOffset - endOffset); if (nextBlock == null) { this.createCircle(block, this.measurements.pinRadius, distance, true); this.renderLip(block, distance - this.measurements.pinLipRadius); } if (previousBlock == null) { this.createCircle(block, this.measurements.pinRadius, 0); this.renderLip(block, this.measurements.pinLipRadius); } if (nextBlock != null && !nextBlock.isAttachment) { this.createCircleWithHole(block, this.measurements.pinRadius, 0.5 - this.measurements.edgeMargin, distance, true, !nextBlock.rounded); this.hideStartEndFaces(nextBlock.position, block, false); } if (previousBlock != null && !previousBlock.isAttachment) { this.createCircleWithHole(block, this.measurements.pinRadius, 0.5 - this.measurements.edgeMargin, 0, false, !previousBlock.rounded); this.hideStartEndFaces(previousBlock.position, block, true); } if (nextBlock != null && nextBlock.isAttachment && nextBlock.type != BlockType.Pin) { this.createCircleWithHole(block, this.measurements.pinRadius, this.measurements.attachmentAdapterRadius, distance - this.measurements.attachmentAdapterSize, true); } if (previousBlock != null && previousBlock.isAttachment && previousBlock.type != BlockType.Pin) { this.createCircleWithHole(block, this.measurements.pinRadius, this.measurements.attachmentAdapterRadius, this.measurements.attachmentAdapterSize); this.createCylinder(block, -this.measurements.attachmentAdapterSize, this.measurements.attachmentAdapterRadius, this.measurements.attachmentAdapterSize * 2); } } private renderAxle(block: TinyBlock) { var nextBlock = this.getNextBlock(block, false); var previousBlock = this.getPreviousBlock(block); var start = block.getCylinderOrigin(this); var end = start.plus(block.forward.times(block.getExteriorDepth(this))); if (previousBlock != null && previousBlock.isAttachment && previousBlock.type != BlockType.Axle) { start = start.plus(block.forward.times(this.measurements.attachmentAdapterSize)); } if (nextBlock != null && nextBlock.isAttachment && nextBlock.type != BlockType.Axle) { end = end.minus(block.forward.times(this.measurements.attachmentAdapterSize)); } var horizontalInner = block.horizontal.times(this.measurements.axleSizeInner); var horizontalOuter = block.horizontal.times(this.measurements.axleSizeOuter); var verticalInner = block.vertical.times(this.measurements.axleSizeInner); var verticalOuter = block.vertical.times(this.measurements.axleSizeOuter); var odd = block.odd(); this.createQuad( start.plus(horizontalInner).plus(verticalInner), start.plus(horizontalInner).plus(verticalOuter), end.plus(horizontalInner).plus(verticalOuter), end.plus(horizontalInner).plus(verticalInner), odd); this.createQuad( start.plus(horizontalInner).plus(verticalInner), start.plus(horizontalOuter).plus(verticalInner), end.plus(horizontalOuter).plus(verticalInner), end.plus(horizontalInner).plus(verticalInner), !odd); this.createQuad( end.plus(horizontalOuter), start.plus(horizontalOuter), start.plus(horizontalOuter).plus(verticalInner), end.plus(horizontalOuter).plus(verticalInner), odd); this.createQuad( end.plus(verticalOuter), start.plus(verticalOuter), start.plus(verticalOuter).plus(horizontalInner), end.plus(verticalOuter).plus(horizontalInner), !odd); if (nextBlock == null) { this.createQuad( end.plus(horizontalInner).plus(verticalInner), end.plus(verticalInner), end, end.plus(horizontalInner), odd); this.createQuad( end.plus(horizontalInner), end.plus(horizontalOuter), end.plus(horizontalOuter).plus(verticalInner), end.plus(horizontalInner).plus(verticalInner), odd); this.createQuad( end.plus(verticalInner), end.plus(verticalOuter), end.plus(verticalOuter).plus(horizontalInner), end.plus(verticalInner).plus(horizontalInner), !odd); } if (previousBlock == null) { this.createQuad( start.plus(horizontalInner).plus(verticalInner), start.plus(verticalInner), start, start.plus(horizontalInner), !odd); this.createQuad( start.plus(horizontalInner), start.plus(horizontalOuter), start.plus(horizontalOuter).plus(verticalInner), start.plus(horizontalInner).plus(verticalInner), !odd); this.createQuad( start.plus(verticalInner), start.plus(verticalOuter), start.plus(verticalOuter).plus(horizontalInner), start.plus(verticalInner).plus(horizontalInner), odd); } var blockSizeWithoutMargin = 0.5 - this.measurements.edgeMargin; if (nextBlock != null && nextBlock.type != block.type && !nextBlock.rounded) { this.createQuad( end.plus(block.horizontal.times(blockSizeWithoutMargin)), end.plus(horizontalOuter), end.plus(horizontalOuter).plus(verticalInner), end.plus(block.horizontal.times(blockSizeWithoutMargin)).plus(verticalInner), odd); this.createQuad( end.plus(block.vertical.times(blockSizeWithoutMargin)), end.plus(verticalOuter), end.plus(verticalOuter).plus(horizontalInner), end.plus(block.vertical.times(blockSizeWithoutMargin)).plus(horizontalInner), !odd); this.createQuad( end.plus(horizontalInner).plus(verticalInner), end.plus(block.horizontal.times(blockSizeWithoutMargin)).plus(verticalInner), end.plus(block.horizontal.times(blockSizeWithoutMargin)).plus(block.vertical.times(blockSizeWithoutMargin)), end.plus(horizontalInner).plus(block.vertical.times(blockSizeWithoutMargin)), !odd); } if (previousBlock != null && previousBlock.type != block.type && !previousBlock.rounded) { this.createQuad( start.plus(block.horizontal.times(blockSizeWithoutMargin)), start.plus(horizontalOuter), start.plus(horizontalOuter).plus(verticalInner), start.plus(block.horizontal.times(blockSizeWithoutMargin)).plus(verticalInner), !odd); this.createQuad( start.plus(block.vertical.times(blockSizeWithoutMargin)), start.plus(verticalOuter), start.plus(verticalOuter).plus(horizontalInner), start.plus(block.vertical.times(blockSizeWithoutMargin)).plus(horizontalInner), odd); this.createQuad( start.plus(horizontalInner).plus(verticalInner), start.plus(block.horizontal.times(blockSizeWithoutMargin)).plus(verticalInner), start.plus(block.horizontal.times(blockSizeWithoutMargin)).plus(block.vertical.times(blockSizeWithoutMargin)), start.plus(horizontalInner).plus(block.vertical.times(blockSizeWithoutMargin)), odd); } if (nextBlock != null && nextBlock.type != block.type && nextBlock.rounded) { this.createAxleToCircleAdapter(end, block, nextBlock.isAttachment ? this.measurements.attachmentAdapterRadius : blockSizeWithoutMargin); } if (previousBlock != null && previousBlock.type != block.type && previousBlock.rounded) { this.createAxleToCircleAdapter(start, block, previousBlock.isAttachment ? this.measurements.attachmentAdapterRadius : blockSizeWithoutMargin, true); } if (nextBlock != null && !nextBlock.isAttachment) { this.hideStartEndFaces(nextBlock.position, block, false); } if (previousBlock != null && !previousBlock.isAttachment) { this.hideStartEndFaces(previousBlock.position, block, true); } if (previousBlock != null && previousBlock.isAttachment && previousBlock.type != BlockType.Axle) { this.createCylinder(block, -this.measurements.attachmentAdapterSize, this.measurements.attachmentAdapterRadius, this.measurements.attachmentAdapterSize * 2); } } private renderBallJoint(block: TinyBlock) { var nextBlock = this.getNextBlock(block, false); var previousBlock = this.getPreviousBlock(block); var distance = block.getExteriorDepth(this); var startOffset = (previousBlock != null && previousBlock.isAttachment && previousBlock.type != BlockType.BallJoint) ? this.measurements.attachmentAdapterSize : 0; if (previousBlock == null) { startOffset += 2 * this.measurements.pinLipRadius; } var endOffset = (nextBlock != null && nextBlock.isAttachment && nextBlock.type != BlockType.BallJoint) ? this.measurements.attachmentAdapterSize : 0; if (nextBlock == null) { endOffset += 2 * this.measurements.pinLipRadius; } var ballCenterDistance: number; if (nextBlock == null) { var offset = mod(block.position.dot(block.forward) - 1, 3) - 1; ballCenterDistance = 0.5 - offset * this.measurements.edgeMargin; } else { var offset = mod(block.position.dot(block.forward) + block.exteriorMergedBlocks - 1, 3) - 1; ballCenterDistance = distance - 0.5 - offset * this.measurements.edgeMargin; } var ballCenter = block.getCylinderOrigin(this).plus(block.forward.times(ballCenterDistance)); var angle = Math.acos(this.measurements.ballBaseRadius / this.measurements.ballRadius); for (var i = 0; i < this.measurements.subdivisionsPerQuarter; i++) { var angleStart = lerp(-angle, +angle, i / this.measurements.subdivisionsPerQuarter); var angleEnd = lerp(-angle, +angle, (i+1) / this.measurements.subdivisionsPerQuarter); var ballCenterStart = ballCenter.plus(block.forward.times(Math.sin(angleStart) * this.measurements.ballRadius)); var ballCenterEnd = ballCenter.plus(block.forward.times(Math.sin(angleEnd) * this.measurements.ballRadius)); var radiusStart = this.measurements.ballRadius * Math.cos(angleStart); var radiusEnd = this.measurements.ballRadius * Math.cos(angleEnd); for (var j = 0; j < this.measurements.subdivisionsPerQuarter; j++) { var out1 = block.getOnCircle(j / 2 * Math.PI / this.measurements.subdivisionsPerQuarter); var out2 = block.getOnCircle((j + 1) / 2 * Math.PI / this.measurements.subdivisionsPerQuarter); this.createQuadWithNormals( ballCenterStart.plus(out2.times(radiusStart)), ballCenterStart.plus(out1.times(radiusStart)), ballCenterEnd.plus(out1.times(radiusEnd)), ballCenterEnd.plus(out2.times(radiusEnd)), out2.times(-Math.cos(angleStart)).minus(block.forward.times(Math.sin(angleStart))), out1.times(-Math.cos(angleStart)).minus(block.forward.times(Math.sin(angleStart))), out1.times(-Math.cos(angleEnd)).minus(block.forward.times(Math.sin(angleEnd))), out2.times(-Math.cos(angleEnd)).minus(block.forward.times(Math.sin(angleEnd))) ); } } var ballStart = ballCenterDistance - Math.sin(angle) * this.measurements.ballRadius; var ballEnd = ballCenterDistance + Math.sin(angle) * this.measurements.ballRadius; if (nextBlock == null) { this.createCircle(block, this.measurements.ballBaseRadius, ballEnd, true); } else { this.createCylinder(block, ballEnd, this.measurements.ballBaseRadius, distance - endOffset - ballEnd); } if (previousBlock == null) { this.createCircle(block, this.measurements.ballBaseRadius, ballStart); } else { this.createCylinder(block, startOffset, this.measurements.ballBaseRadius, ballStart - startOffset); } if (nextBlock != null && !nextBlock.isAttachment) { this.createCircleWithHole(block, this.measurements.ballBaseRadius, 0.5 - this.measurements.edgeMargin, distance, true, !nextBlock.rounded); this.hideStartEndFaces(nextBlock.position, block, false); } if (previousBlock != null && !previousBlock.isAttachment) { this.createCircleWithHole(block, this.measurements.ballBaseRadius, 0.5 - this.measurements.edgeMargin, 0, false, !previousBlock.rounded); this.hideStartEndFaces(previousBlock.position, block, true); } if (nextBlock != null && nextBlock.isAttachment && nextBlock.type != BlockType.BallJoint) { this.createCircleWithHole(block, this.measurements.ballBaseRadius, this.measurements.attachmentAdapterRadius, distance - this.measurements.attachmentAdapterSize, true); } if (previousBlock != null && previousBlock.isAttachment && previousBlock.type != BlockType.BallJoint) { this.createCircleWithHole(block, this.measurements.ballBaseRadius, this.measurements.attachmentAdapterRadius, this.measurements.attachmentAdapterSize); this.createCylinder(block, -this.measurements.attachmentAdapterSize, this.measurements.attachmentAdapterRadius, this.measurements.attachmentAdapterSize * 2); } } private createAxleToCircleAdapter(center: Vector3, block: SmallBlock, radius: number, flipped = false) { var horizontalInner = block.horizontal.times(this.measurements.axleSizeInner); var horizontalOuter = block.horizontal.times(this.measurements.axleSizeOuter); var verticalInner = block.vertical.times(this.measurements.axleSizeInner); var verticalOuter = block.vertical.times(this.measurements.axleSizeOuter); var odd = block.odd(); for (var i = 0; i < this.measurements.subdivisionsPerQuarter; i++) { var focus = center.copy(); if (i < this.measurements.subdivisionsPerQuarter / 2 == !odd) { focus = focus.plus(horizontalInner).plus(verticalOuter); } else { focus = focus.plus(horizontalOuter).plus(verticalInner); } this.triangles.push(new Triangle(focus, center.plus(block.getOnCircle(Math.PI / 2 * i / this.measurements.subdivisionsPerQuarter, radius)), center.plus(block.getOnCircle(Math.PI / 2 * (i + 1) / this.measurements.subdivisionsPerQuarter, radius)), flipped)); } this.triangles.push(new Triangle( center.plus(horizontalInner).plus(verticalOuter), center.plus(verticalOuter), center.plus(block.vertical.times(radius)), odd != flipped)); this.triangles.push(new Triangle( center.plus(verticalInner).plus(horizontalOuter), center.plus(horizontalOuter), center.plus(block.horizontal.times(radius)), odd == flipped)); this.createQuad( center.plus(verticalInner).plus(horizontalInner), center.plus(verticalOuter).plus(horizontalInner), center.plus(block.getOnCircle(45 * DEG_TO_RAD, radius)), center.plus(verticalInner).plus(horizontalOuter), odd != flipped); } private showInteriorCap(currentBlock: SmallBlock, neighbor: SmallBlock): boolean { if (neighbor == null) { return false; } if (neighbor.orientation != currentBlock.orientation || neighbor.quadrant != currentBlock.quadrant || !neighbor.hasInterior) { return true; } if (currentBlock.type == BlockType.AxleHole && neighbor.type == BlockType.PinHole || neighbor.type == BlockType.AxleHole && currentBlock.type == BlockType.PinHole) { // Pin hole to axle hole adapter return false; } return currentBlock.type != neighbor.type; } private renderPinHoleInterior(block: TinyBlock) { var nextBlock = this.getNextBlock(block, true); var previousBlock = this.getPreviousBlock(block); var distance = block.getInteriorDepth(this); var hasOpenEnd = this.hasOpenEnd(block, true); var hasOpenStart = this.hasOpenStart(block); var showInteriorEndCap = this.showInteriorCap(block, nextBlock) || (nextBlock == null && !hasOpenEnd); var showInteriorStartCap = this.showInteriorCap(block, previousBlock) || (previousBlock == null && !hasOpenStart); var offset = this.measurements.pinHoleOffset; var endMargin = showInteriorEndCap ? this.measurements.interiorEndMargin : 0; var startMargin = showInteriorStartCap ? this.measurements.interiorEndMargin : 0; var offsetStart = (hasOpenStart || showInteriorStartCap ? offset : 0) + startMargin; var offsetEnd = (hasOpenEnd || showInteriorEndCap ? offset : 0) + endMargin; var interiorRadius = this.measurements.interiorRadius; this.createCylinder(block, offsetStart, this.measurements.pinHoleRadius, distance - offsetStart - offsetEnd, true); if (hasOpenStart || showInteriorStartCap) { this.createCylinder(block, startMargin, interiorRadius, offset, true); this.createCircleWithHole(block, this.measurements.pinHoleRadius, interiorRadius, offset + startMargin, true); } if (hasOpenEnd || showInteriorEndCap) { this.createCylinder(block, distance - offset - endMargin, interiorRadius, offset, true); this.createCircleWithHole(block, this.measurements.pinHoleRadius, interiorRadius, distance - offset - endMargin, false); } if (showInteriorEndCap) { this.createCircle(block, interiorRadius, distance - endMargin, false); } if (showInteriorStartCap) { this.createCircle(block, interiorRadius, startMargin, true); } } private renderAxleHoleInterior(block: TinyBlock) { var nextBlock = this.getNextBlock(block, true); var previousBlock = this.getPreviousBlock(block); var hasOpenEnd = this.hasOpenEnd(block, true); var hasOpenStart = this.hasOpenStart(block); var showInteriorEndCap = this.showInteriorCap(block, nextBlock) || (nextBlock == null && !hasOpenEnd); var showInteriorStartCap = this.showInteriorCap(block, previousBlock) || (previousBlock == null && !hasOpenStart); var distance = block.getInteriorDepth(this); var holeSize = this.measurements.axleHoleSize; var start = block.getCylinderOrigin(this).plus(showInteriorStartCap ? block.forward.times(this.measurements.interiorEndMargin) : Vector3.zero()); var end = start.plus(block.forward.times(distance - (showInteriorStartCap ? this.measurements.interiorEndMargin : 0) - (showInteriorEndCap ? this.measurements.interiorEndMargin : 0))); var axleWingAngle = Math.asin(holeSize / this.measurements.pinHoleRadius); var axleWingAngle2 = 90 * DEG_TO_RAD - axleWingAngle; var subdivAngle = 90 / this.measurements.subdivisionsPerQuarter * DEG_TO_RAD; var adjustedRadius = this.measurements.pinHoleRadius * Math.cos(subdivAngle / 2) / Math.cos(subdivAngle / 2 - (axleWingAngle - Math.floor(axleWingAngle / subdivAngle) * subdivAngle)); this.createQuad( start.plus(block.horizontal.times(holeSize)).plus(block.vertical.times(holeSize)), start.plus(block.getOnCircle(axleWingAngle, adjustedRadius)), end.plus(block.getOnCircle(axleWingAngle, adjustedRadius)), end.plus(block.horizontal.times(holeSize)).plus(block.vertical.times(holeSize)), true); this.createQuad( start.plus(block.horizontal.times(holeSize)).plus(block.vertical.times(holeSize)), start.plus(block.getOnCircle(axleWingAngle2, adjustedRadius)), end.plus(block.getOnCircle(axleWingAngle2, adjustedRadius)), end.plus(block.horizontal.times(holeSize)).plus(block.vertical.times(holeSize)), false); for (var i = 0; i < this.measurements.subdivisionsPerQuarter; i++) { var angle1 = lerp(0, 90, i / this.measurements.subdivisionsPerQuarter) * DEG_TO_RAD; var angle2 = lerp(0, 90, (i + 1) / this.measurements.subdivisionsPerQuarter) * DEG_TO_RAD; var startAngleInside = angle1; var endAngleInside = angle2; var startAngleOutside = angle1; var endAngleOutside = angle2; var radius1Inside = this.measurements.pinHoleRadius; var radius2Inside = this.measurements.pinHoleRadius; var radius1Outside = this.measurements.pinHoleRadius; var radius2Outside = this.measurements.pinHoleRadius; if (angle1 < axleWingAngle && angle2 > axleWingAngle) { endAngleInside = axleWingAngle; startAngleOutside = axleWingAngle; radius1Outside = adjustedRadius; radius2Inside = adjustedRadius; } if (angle1 < axleWingAngle2 && angle2 > axleWingAngle2) { startAngleInside = axleWingAngle2; endAngleOutside = axleWingAngle2; radius2Outside = adjustedRadius; radius1Inside = adjustedRadius; } // Walls if (angle1 < axleWingAngle || angle2 > axleWingAngle2) { var v1 = block.getOnCircle(startAngleInside); var v2 = block.getOnCircle(endAngleInside); this.createQuadWithNormals( start.plus(v1.times(radius1Inside)), start.plus(v2.times(radius2Inside)), end.plus(v2.times(radius2Inside)), end.plus(v1.times(radius1Inside)), v1, v2, v2, v1, false); } // Outside caps if (hasOpenStart || (previousBlock != null && previousBlock.type == BlockType.PinHole && !showInteriorStartCap)) { if (angle2 > axleWingAngle && angle1 < axleWingAngle2) { this.triangles.push(new Triangle( start.plus(block.horizontal.times(holeSize)).plus(block.vertical.times(holeSize)), start.plus(block.getOnCircle(startAngleOutside, radius1Outside)), start.plus(block.getOnCircle(endAngleOutside, radius2Outside)))); } } if (hasOpenEnd || (nextBlock != null && nextBlock.type == BlockType.PinHole && !showInteriorEndCap)) { if (angle2 > axleWingAngle && angle1 < axleWingAngle2) { this.triangles.push(new Triangle( end.plus(block.horizontal.times(holeSize)).plus(block.vertical.times(holeSize)), end.plus(block.getOnCircle(endAngleOutside, radius2Outside)), end.plus(block.getOnCircle(startAngleOutside, radius1Outside)))); } } // Inside caps if (showInteriorEndCap && (angle1 < axleWingAngle || angle2 > axleWingAngle2)) { this.triangles.push(new Triangle( end, end.plus(block.getOnCircle(startAngleInside, radius1Outside)), end.plus(block.getOnCircle(endAngleInside, radius2Outside)))); } if (showInteriorStartCap && (angle1 < axleWingAngle || angle2 > axleWingAngle2)) { this.triangles.push(new Triangle( start, start.plus(block.getOnCircle(endAngleInside, radius2Outside)), start.plus(block.getOnCircle(startAngleInside, radius1Outside)))); } } if (hasOpenEnd) { this.createCircleWithHole(block, this.measurements.pinHoleRadius, this.measurements.interiorRadius, distance, false); } if (hasOpenStart) { this.createCircleWithHole(block, this.measurements.pinHoleRadius, this.measurements.interiorRadius, 0, true); } if (showInteriorEndCap) { this.triangles.push(new Triangle( end.plus(block.horizontal.times(holeSize)).plus(block.vertical.times(holeSize)), end, end.plus(block.getOnCircle(axleWingAngle, adjustedRadius)))); this.triangles.push(new Triangle( end, end.plus(block.horizontal.times(holeSize)).plus(block.vertical.times(holeSize)), end.plus(block.getOnCircle(axleWingAngle2, adjustedRadius)))); } if (showInteriorStartCap) { this.triangles.push(new Triangle( start, start.plus(block.horizontal.times(holeSize)).plus(block.vertical.times(holeSize)), start.plus(block.getOnCircle(axleWingAngle, adjustedRadius)))); this.triangles.push(new Triangle( start.plus(block.horizontal.times(holeSize)).plus(block.vertical.times(holeSize)), start, start.plus(block.getOnCircle(axleWingAngle2, adjustedRadius)))); } } private isFaceVisible(position: Vector3, direction: Vector3): boolean { var block = this.tinyBlocks.getOrNull(position); return block != null && !this.isTinyBlock(block.position.plus(direction)) && !block.isAttachment && block.isFaceVisible(direction); } private createTinyFace(position: Vector3, size: Vector3, direction: Vector3) { var vertices: Vector3[] = null; if (direction.x > 0) { vertices = RIGHT_FACE_VERTICES; } else if (direction.x < 0) { vertices = LEFT_FACE_VERTICES; } else if (direction.y > 0) { vertices = UP_FACE_VERTICES; } else if (direction.y < 0) { vertices = DOWN_FACE_VERTICES; } else if (direction.z > 0) { vertices = FORWARD_FACE_VERTICES; } else if (direction.z < 0) { vertices = BACK_FACE_VERTICES; } else { throw new Error("Invalid direction: " + direction.toString()); } this.createQuad( this.tinyBlockToWorld(position.plus(vertices[0].elementwiseMultiply(size))), this.tinyBlockToWorld(position.plus(vertices[1].elementwiseMultiply(size))), this.tinyBlockToWorld(position.plus(vertices[2].elementwiseMultiply(size))), this.tinyBlockToWorld(position.plus(vertices[3].elementwiseMultiply(size)))); } private isRowOfVisibleFaces(position: Vector3, rowDirection: Vector3, faceDirection: Vector3, count: number): boolean { for (var i = 0; i < count; i++) { if (!this.isFaceVisible(position.plus(rowDirection.times(i)), faceDirection)) { return false; } } return true; } /* Finds a connected rectangle of visible faces in the given direction by starting with the supplied position and a rectangle of size 1x1 and expanding it in the 4 directions that are tangential to the supplied face direction, until it is no longer possible to expand in any direction. Returns the lower left corner of the rectangle and its size. The component of the size vector of the direction supplied by the direction parameter is always 1. The component of the position vector in the direction supplied by the direction parameter remains unchanged. */ private findConnectedFaces(position: Vector3, direction: Vector3): [Vector3, Vector3] { var tangent1 = new Vector3(direction.x == 0 ? 1 : 0, direction.x == 0 ? 0 : 1, 0); var tangent2 = new Vector3(0, direction.z == 0 ? 0 : 1, direction.z == 0 ? 1 : 0); var size = Vector3.one(); while (true) { var hasChanged = false; if (this.isRowOfVisibleFaces(position.minus(tangent2), tangent1, direction, size.dot(tangent1))) { position = position.minus(tangent2); size = size.plus(tangent2); hasChanged = true; } if (this.isRowOfVisibleFaces(position.minus(tangent1), tangent2, direction, size.dot(tangent2))) { position = position.minus(tangent1); size = size.plus(tangent1); hasChanged = true; } if (this.isRowOfVisibleFaces(position.plus(tangent2.times(size.dot(tangent2))), tangent1, direction, size.dot(tangent1))) { size = size.plus(tangent2); hasChanged = true; } if (this.isRowOfVisibleFaces(position.plus(tangent1.times(size.dot(tangent1))), tangent2, direction, size.dot(tangent2))) { size = size.plus(tangent1); hasChanged = true; } if (!hasChanged) { return [position, size]; } } } private hideFaces(position: Vector3, size: Vector3, direction: Vector3) { for (var x = 0; x < size.x; x++) { for (var y = 0; y < size.y; y++) { for (var z = 0; z < size.z; z++) { this.hideFaceIfExists(new Vector3(position.x + x, position.y + y, position.z + z), direction); } } } } private renderTinyBlockFaces() { for (let block of this.tinyBlocks.values()) { for (let direction of FACE_DIRECTIONS) { if (!this.isFaceVisible(block.position, direction)) { continue; } var expanded = this.findConnectedFaces(block.position, direction); var position = expanded[0]; var size = expanded[1]; this.createTinyFace(position, size, direction); this.hideFaces(position, size, direction); } } } }
the_stack
import { AccessLevelList } from "../shared/access-level"; import { PolicyStatement } from "../shared"; /** * Statement provider for service [rekognition](https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazonrekognition.html). * * @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement */ export class Rekognition extends PolicyStatement { public servicePrefix = 'rekognition'; /** * Statement provider for service [rekognition](https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazonrekognition.html). * * @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement */ constructor (sid?: string) { super(sid); } /** * Compares a face in source input image with each face detected in the target input image. * * Access Level: Read * * https://docs.aws.amazon.com/rekognition/latest/dg/API_CompareFaces.html */ public toCompareFaces() { return this.to('CompareFaces'); } /** * Creates a collection in an AWS region. You can then add faces to the collection using the IndexFaces API. * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/rekognition/latest/dg/API_CreateCollection.html */ public toCreateCollection() { return this.to('CreateCollection'); } /** * Creates a new Amazon Rekognition Custom Labels project. * * Access Level: Write * * https://docs.aws.amazon.com/rekognition/latest/dg/API_CreateProject.html */ public toCreateProject() { return this.to('CreateProject'); } /** * Creates a new version of a model and begins training. * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/rekognition/latest/dg/API_CreateProjectVersion.html */ public toCreateProjectVersion() { return this.to('CreateProjectVersion'); } /** * Creates an Amazon Rekognition stream processor that you can use to detect and recognize faces in a streaming video. * * Access Level: Write * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/rekognition/latest/dg/API_CreateStreamProcessor.html */ public toCreateStreamProcessor() { return this.to('CreateStreamProcessor'); } /** * Deletes the specified collection. Note that this operation removes all faces in the collection. * * Access Level: Write * * https://docs.aws.amazon.com/rekognition/latest/dg/API_DeleteCollection.html */ public toDeleteCollection() { return this.to('DeleteCollection'); } /** * Deletes faces from a collection. * * Access Level: Write * * https://docs.aws.amazon.com/rekognition/latest/dg/API_DeleteFaces.html */ public toDeleteFaces() { return this.to('DeleteFaces'); } /** * Deletes a project. * * Access Level: Write * * https://docs.aws.amazon.com/rekognition/latest/dg/API_DeleteProject.html */ public toDeleteProject() { return this.to('DeleteProject'); } /** * Deletes a model. * * Access Level: Write * * https://docs.aws.amazon.com/rekognition/latest/dg/API_DeleteProjectVersion.html */ public toDeleteProjectVersion() { return this.to('DeleteProjectVersion'); } /** * Deletes the stream processor identified by Name. * * Access Level: Write * * https://docs.aws.amazon.com/rekognition/latest/dg/API_DeleteStreamProcessor.html */ public toDeleteStreamProcessor() { return this.to('DeleteStreamProcessor'); } /** * Describes the specified collection. * * Access Level: Read * * https://docs.aws.amazon.com/rekognition/latest/dg/API_DescribeCollection.html */ public toDescribeCollection() { return this.to('DescribeCollection'); } /** * Lists and describes the model versions in an Amazon Rekognition Custom Labels project. * * Access Level: Read * * https://docs.aws.amazon.com/rekognition/latest/dg/API_DescribeProjectVersions.html */ public toDescribeProjectVersions() { return this.to('DescribeProjectVersions'); } /** * Lists and gets information about your Amazon Rekognition Custom Labels projects. * * Access Level: Read * * https://docs.aws.amazon.com/rekognition/latest/dg/API_DescribeProjects.html */ public toDescribeProjects() { return this.to('DescribeProjects'); } /** * Provides information about a stream processor created by CreateStreamProcessor. * * Access Level: Read * * https://docs.aws.amazon.com/rekognition/latest/dg/API_DescribeStreamProcessorh.html */ public toDescribeStreamProcessor() { return this.to('DescribeStreamProcessor'); } /** * Detects custom labels in a supplied image by using an Amazon Rekognition Custom Labels model version. * * Access Level: Read * * https://docs.aws.amazon.com/rekognition/latest/dg/API_DetectCustomLabels.html */ public toDetectCustomLabels() { return this.to('DetectCustomLabels'); } /** * Detects human faces within an image (JPEG or PNG) provided as input. * * Access Level: Read * * https://docs.aws.amazon.com/rekognition/latest/dg/API_DetectFaces.html */ public toDetectFaces() { return this.to('DetectFaces'); } /** * Detects instances of real-world labels within an image (JPEG or PNG) provided as input. * * Access Level: Read * * https://docs.aws.amazon.com/rekognition/latest/dg/API_DetectLabels.html */ public toDetectLabels() { return this.to('DetectLabels'); } /** * Detects moderation labels within input image. * * Access Level: Read * * https://docs.aws.amazon.com/rekognition/latest/dg/API_DetectModerationLabels.html */ public toDetectModerationLabels() { return this.to('DetectModerationLabels'); } /** * Detects Protective Equipment in the input image. * * Access Level: Read * * https://docs.aws.amazon.com/rekognition/latest/dg/API_DetectProtectiveEquipment.html */ public toDetectProtectiveEquipment() { return this.to('DetectProtectiveEquipment'); } /** * Detects text in the input image and converts it into machine-readable text. * * Access Level: Read * * https://docs.aws.amazon.com/rekognition/latest/dg/API_DetectText.html */ public toDetectText() { return this.to('DetectText'); } /** * Gets the name and additional information about a celebrity based on his or her Rekognition ID. * * Access Level: Read * * https://docs.aws.amazon.com/rekognition/latest/dg/API_GetCelebrityInfo.html */ public toGetCelebrityInfo() { return this.to('GetCelebrityInfo'); } /** * Gets the celebrity recognition results for a Rekognition Video analysis started by StartCelebrityRecognition. * * Access Level: Read * * https://docs.aws.amazon.com/rekognition/latest/dg/API_GetCelebrityRecognition.html */ public toGetCelebrityRecognition() { return this.to('GetCelebrityRecognition'); } /** * Gets the content moderation analysis results for a Rekognition Video analysis started by StartContentModeration. * * Access Level: Read * * https://docs.aws.amazon.com/rekognition/latest/dg/API_GetContentModeration.html */ public toGetContentModeration() { return this.to('GetContentModeration'); } /** * Gets face detection results for a Rekognition Video analysis started by StartFaceDetection. * * Access Level: Read * * https://docs.aws.amazon.com/rekognition/latest/dg/API_GetFaceDetection.html */ public toGetFaceDetection() { return this.to('GetFaceDetection'); } /** * Gets the face search results for Rekognition Video face search started by StartFaceSearch. * * Access Level: Read * * https://docs.aws.amazon.com/rekognition/latest/dg/API_GetFaceSearch.html */ public toGetFaceSearch() { return this.to('GetFaceSearch'); } /** * Gets the label detection results of a Rekognition Video analysis started by StartLabelDetection. * * Access Level: Read * * https://docs.aws.amazon.com/rekognition/latest/dg/API_GetLabelDetection.html */ public toGetLabelDetection() { return this.to('GetLabelDetection'); } /** * Gets information about people detected within a video. * * Access Level: Read * * https://docs.aws.amazon.com/rekognition/latest/dg/API_GetPersonTracking.html */ public toGetPersonTracking() { return this.to('GetPersonTracking'); } /** * Gets segment detection results for a Rekognition Video analysis started by StartSegmentDetection. * * Access Level: Read * * https://docs.aws.amazon.com/rekognition/latest/dg/API_GetSegmentDetection.html */ public toGetSegmentDetection() { return this.to('GetSegmentDetection'); } /** * Gets text detection results for a Rekognition Video analysis started by StartTextDetection. * * Access Level: Read * * https://docs.aws.amazon.com/rekognition/latest/dg/API_GetTextDetection.html */ public toGetTextDetection() { return this.to('GetTextDetection'); } /** * Detects faces in the input image and adds them to the specified collection. * * Access Level: Write * * https://docs.aws.amazon.com/rekognition/latest/dg/API_IndexFaces.html */ public toIndexFaces() { return this.to('IndexFaces'); } /** * Returns a list of collection IDs in your account. * * Access Level: Read * * https://docs.aws.amazon.com/rekognition/latest/dg/API_ListCollections.html */ public toListCollections() { return this.to('ListCollections'); } /** * Returns metadata for faces in the specified collection. * * Access Level: Read * * https://docs.aws.amazon.com/rekognition/latest/dg/API_ListFaces.html */ public toListFaces() { return this.to('ListFaces'); } /** * Gets a list of stream processors that you have created with CreateStreamProcessor. * * Access Level: List * * https://docs.aws.amazon.com/rekognition/latest/dg/API_ListStreamProcessors.html */ public toListStreamProcessors() { return this.to('ListStreamProcessors'); } /** * Returns a list of tags associated with a resource. * * Access Level: Read * * https://docs.aws.amazon.com/rekognition/latest/dg/API_ListTagsForResource.html */ public toListTagsForResource() { return this.to('ListTagsForResource'); } /** * Returns an array of celebrities recognized in the input image. * * Access Level: Read * * https://docs.aws.amazon.com/rekognition/latest/dg/API_RecognizeCelebrities.html */ public toRecognizeCelebrities() { return this.to('RecognizeCelebrities'); } /** * For a given input face ID, searches the specified collection for matching faces. * * Access Level: Read * * https://docs.aws.amazon.com/rekognition/latest/dg/API_SearchFaces.html */ public toSearchFaces() { return this.to('SearchFaces'); } /** * For a given input image, first detects the largest face in the image, and then searches the specified collection for matching faces. * * Access Level: Read * * https://docs.aws.amazon.com/rekognition/latest/dg/API_SearchFacesByImage.html */ public toSearchFacesByImage() { return this.to('SearchFacesByImage'); } /** * Starts asynchronous recognition of celebrities in a video. * * Access Level: Write * * https://docs.aws.amazon.com/rekognition/latest/dg/API_StartCelebrityRecognition.html */ public toStartCelebrityRecognition() { return this.to('StartCelebrityRecognition'); } /** * Starts asynchronous detection of explicit or suggestive adult content in a video. * * Access Level: Write * * https://docs.aws.amazon.com/rekognition/latest/dg/API_StartContentModeration.html */ public toStartContentModeration() { return this.to('StartContentModeration'); } /** * Starts asynchronous detection of faces in a video. * * Access Level: Write * * https://docs.aws.amazon.com/rekognition/latest/dg/API_StartFaceDetection.html */ public toStartFaceDetection() { return this.to('StartFaceDetection'); } /** * Starts the asynchronous search for faces in a collection that match the faces of persons detected in a video. * * Access Level: Write * * https://docs.aws.amazon.com/rekognition/latest/dg/API_StartFaceSearch.html */ public toStartFaceSearch() { return this.to('StartFaceSearch'); } /** * Starts asynchronous detection of labels in a video. * * Access Level: Write * * https://docs.aws.amazon.com/rekognition/latest/dg/API_StartLabelDetection.html */ public toStartLabelDetection() { return this.to('StartLabelDetection'); } /** * Starts the asynchronous tracking of persons in a video. * * Access Level: Write * * https://docs.aws.amazon.com/rekognition/latest/dg/API_StartPersonTracking.html */ public toStartPersonTracking() { return this.to('StartPersonTracking'); } /** * Starts the deployment of a model version. * * Access Level: Write * * https://docs.aws.amazon.com/rekognition/latest/dg/API_StartProjectVersion.html */ public toStartProjectVersion() { return this.to('StartProjectVersion'); } /** * Starts asynchronous detection of segments in a video. * * Access Level: Write * * https://docs.aws.amazon.com/rekognition/latest/dg/API_StartSegmentDetection.html */ public toStartSegmentDetection() { return this.to('StartSegmentDetection'); } /** * Starts processing a stream processor. * * Access Level: Write * * https://docs.aws.amazon.com/rekognition/latest/dg/API_StartStreamProcessor.html */ public toStartStreamProcessor() { return this.to('StartStreamProcessor'); } /** * Starts asynchronous detection of text in a video. * * Access Level: Write * * https://docs.aws.amazon.com/rekognition/latest/dg/API_StartTextDetection.html */ public toStartTextDetection() { return this.to('StartTextDetection'); } /** * Stops a deployed model version. * * Access Level: Write * * https://docs.aws.amazon.com/rekognition/latest/dg/API_StopProjectVersion.html */ public toStopProjectVersion() { return this.to('StopProjectVersion'); } /** * Stops a running stream processor that was created by CreateStreamProcessor. * * Access Level: Write * * https://docs.aws.amazon.com/rekognition/latest/dg/API_StopStreamProcessor.html */ public toStopStreamProcessor() { return this.to('StopStreamProcessor'); } /** * Adds one or more tags to a resource. * * Access Level: Tagging * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/rekognition/latest/dg/API_TagResource.html */ public toTagResource() { return this.to('TagResource'); } /** * Removes one or more tags from a resource. * * Access Level: Tagging * * Possible conditions: * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/rekognition/latest/dg/API_UntagResource.html */ public toUntagResource() { return this.to('UntagResource'); } protected accessLevelList: AccessLevelList = { "Read": [ "CompareFaces", "DescribeCollection", "DescribeProjectVersions", "DescribeProjects", "DescribeStreamProcessor", "DetectCustomLabels", "DetectFaces", "DetectLabels", "DetectModerationLabels", "DetectProtectiveEquipment", "DetectText", "GetCelebrityInfo", "GetCelebrityRecognition", "GetContentModeration", "GetFaceDetection", "GetFaceSearch", "GetLabelDetection", "GetPersonTracking", "GetSegmentDetection", "GetTextDetection", "ListCollections", "ListFaces", "ListTagsForResource", "RecognizeCelebrities", "SearchFaces", "SearchFacesByImage" ], "Write": [ "CreateCollection", "CreateProject", "CreateProjectVersion", "CreateStreamProcessor", "DeleteCollection", "DeleteFaces", "DeleteProject", "DeleteProjectVersion", "DeleteStreamProcessor", "IndexFaces", "StartCelebrityRecognition", "StartContentModeration", "StartFaceDetection", "StartFaceSearch", "StartLabelDetection", "StartPersonTracking", "StartProjectVersion", "StartSegmentDetection", "StartStreamProcessor", "StartTextDetection", "StopProjectVersion", "StopStreamProcessor" ], "List": [ "ListStreamProcessors" ], "Tagging": [ "TagResource", "UntagResource" ] }; /** * Adds a resource of type collection to the statement * * https://docs.aws.amazon.com/rekognition/latest/dg/howitworks-collection.html * * @param collectionId - Identifier for the collectionId. * @param account - Account of the resource; defaults to empty string: all accounts. * @param region - Region of the resource; defaults to empty string: all regions. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. */ public onCollection(collectionId: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:rekognition:${Region}:${Account}:collection/${CollectionId}'; arn = arn.replace('${CollectionId}', collectionId); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Region}', region || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } /** * Adds a resource of type streamprocessor to the statement * * @param streamprocessorId - Identifier for the streamprocessorId. * @param account - Account of the resource; defaults to empty string: all accounts. * @param region - Region of the resource; defaults to empty string: all regions. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. */ public onStreamprocessor(streamprocessorId: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:rekognition:${Region}:${Account}:streamprocessor/${StreamprocessorId}'; arn = arn.replace('${StreamprocessorId}', streamprocessorId); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Region}', region || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } /** * Adds a resource of type project to the statement * * @param projectName - Identifier for the projectName. * @param creationTimestamp - Identifier for the creationTimestamp. * @param account - Account of the resource; defaults to empty string: all accounts. * @param region - Region of the resource; defaults to empty string: all regions. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. */ public onProject(projectName: string, creationTimestamp: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:rekognition:${Region}:${Account}:project/${ProjectName}/${CreationTimestamp}'; arn = arn.replace('${ProjectName}', projectName); arn = arn.replace('${CreationTimestamp}', creationTimestamp); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Region}', region || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } /** * Adds a resource of type projectversion to the statement * * @param projectName - Identifier for the projectName. * @param versionName - Identifier for the versionName. * @param creationTimestamp - Identifier for the creationTimestamp. * @param account - Account of the resource; defaults to empty string: all accounts. * @param region - Region of the resource; defaults to empty string: all regions. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. */ public onProjectversion(projectName: string, versionName: string, creationTimestamp: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:rekognition:${Region}:${Account}:project/${ProjectName}/version/${VersionName}/${CreationTimestamp}'; arn = arn.replace('${ProjectName}', projectName); arn = arn.replace('${VersionName}', versionName); arn = arn.replace('${CreationTimestamp}', creationTimestamp); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Region}', region || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } }
the_stack
import type ReactModule from "react"; import { Constructable, FASTElementDefinition, Observable, } from "@microsoft/fast-element"; import { Container, DesignSystem, FoundationElementDefinition, FoundationElementRegistry, Registry, } from "@microsoft/fast-foundation"; const reservedReactProperties = new Set([ "children", "localName", "ref", "style", "className", ]); const emptyProps = Object.freeze(Object.create(null)); /** * Event signatures for a React wrapper. * @public */ export type ReactEvents<T> = { [P in keyof T]?: (e: Event) => unknown; }; /** * Maps React event names to DOM event types for special handling. * @public */ export type ReactEventMap<T> = { [P in keyof T]: string; }; /** * Optional configuration for the React wrapper. * @public */ export type ReactWrapperConfig<TEvents> = { /** * The tag that the React component will generate. */ name?: string; /** * A mapping of React event name to DOM event type to be handled * by attaching event listeners to the underlying web component. * @remarks * Typically only needed for non-FAST web components. */ events?: ReactEventMap<TEvents>; /** * A list of properties to be handled directly by the wrapper. * @remarks * Typically only needed for vanilla web components. */ properties?: string[]; }; /** * The props used by a ReactWrapper. * @public */ export type ReactWrapperProps< TElement extends HTMLElement, TEvents > = ReactModule.PropsWithChildren< ReactModule.PropsWithRef< Partial<Omit<TElement, "children" | "style">> & ReactEvents<TEvents> & ReactModule.HTMLAttributes<HTMLElement> > & { style?: ReactModule.CSSProperties } >; /** * A React component that wraps a Web Component. * @public */ export type ReactWrapper<TElement extends HTMLElement, TEvents> = Constructable< ReactModule.Component<ReactWrapperProps<TElement, TEvents>> >; /** * Extracts the element type from a FoundationElementRegistry * @public */ export type FoundationElementRegistryElement< TRegistry > = TRegistry extends FoundationElementRegistry< FoundationElementDefinition, infer TElement > ? TElement extends typeof HTMLElement ? InstanceType<TElement> : any : any; // There are 2 kinds of refs and there's no built in React API to set one. function setRef(ref: React.Ref<unknown>, value: Element | null) { if (typeof ref === "function") { (ref as (e: Element | null) => void)(value); } else { (ref as { current: Element | null }).current = value; } } function getTagName<TElement, TEvents>( type: Constructable<TElement>, config: ReactWrapperConfig<TEvents> ) { if (!config.name) { /* eslint-disable-next-line @typescript-eslint/no-non-null-assertion */ const definition = FASTElementDefinition.forType(type)!; if (definition) { config.name = definition.name; } else { throw new Error( "React wrappers must wrap a FASTElement or be configured with a name." ); } } return config.name; } function getElementEvents<TEvents>(config: ReactWrapperConfig<TEvents>) { return config.events || (config.events = {} as ReactEventMap<TEvents>); } function keyIsValid<TElement, TEvents>( type: Constructable<TElement>, config: ReactWrapperConfig<TEvents>, name: string ): boolean { if (reservedReactProperties.has(name)) { console.warn( `${getTagName(type, config)} contains property ${name} which is a React ` + `reserved property. It will be used by React and not set on ` + `the element.` ); return false; } return true; } function getElementKeys<TElement, TEvents>( type: Constructable<TElement>, config: ReactWrapperConfig<TEvents> ) { if (!(config as any).keys) { if (config.properties) { (config as any).keys = new Set( config.properties.concat(Object.keys(getElementEvents(config))) ); } else { const keys = new Set(Object.keys(getElementEvents(config))); const accessors = Observable.getAccessors(type.prototype); if (accessors.length > 0) { for (const a of accessors) { if (keyIsValid(type, config, a.name)) { keys.add(a.name); } } } else { for (const p in type.prototype) { if (!(p in HTMLElement.prototype) && keyIsValid(type, config, p)) { keys.add(p); } } } (config as any).keys = keys; } } return (config as any).keys; } /** * @param React - The React module, typically imported from the `react` npm * package * @param designSystem - A design system to register the components with. * @public */ export function provideReactWrapper(React: any, designSystem?: DesignSystem) { let registrations: Registry[] = []; const registry: Registry = { register(container: Container, ...rest: any[]) { registrations.forEach(x => x.register(container, ...rest)); registrations = []; }, }; /** * Creates a React component for a custom element. Properties are distinguished * from attributes automatically, and events can be configured so they are * added to the custom element as event listeners. * * @param type - The custom element class to wrap. * @param registry - A FoundationElement registry for the component to wrap. * @param config - Special configuration for the wrapper. */ function wrap< TRegistry extends FoundationElementRegistry<FoundationElementDefinition, any>, TEvents >( registry: TRegistry, config?: ReactWrapperConfig<TEvents> ): ReactWrapper<FoundationElementRegistryElement<TRegistry>, TEvents>; function wrap<TElement extends HTMLElement, TEvents>( type: Constructable<TElement>, config?: ReactWrapperConfig<TEvents> ): ReactWrapper<TElement, TEvents>; function wrap<TElement extends HTMLElement, TEvents>( type: any, config: ReactWrapperConfig<TEvents> = {} ): ReactWrapper<TElement, TEvents> { // Props used by this component wrapper. This is the ComponentProps and the // special `__forwardedRef` property. Note, this ref is special because // it's both needed in this component to get access to the rendered element // and must fulfill any ref passed by the user. type InternalProps = ReactWrapperProps<TElement, TEvents> & { __forwardedRef?: ReactModule.Ref<unknown>; }; if (type instanceof FoundationElementRegistry) { if (designSystem) { designSystem.register(type); } else { registrations.push(type); } type = type.type as any; } class ReactComponent extends React.Component<InternalProps> { private _element: TElement | null = null; private _elementProps!: { [index: string]: unknown }; private _userRef?: ReactModule.Ref<unknown>; private _ref?: (element: TElement | null) => void; private _updateElement(oldProps?: InternalProps) { const element = this._element; if (element === null) { return; } const currentProps = this.props; const previousProps = oldProps || emptyProps; const events = getElementEvents(config); for (const key in this._elementProps) { const newValue = currentProps[key]; const event = events[key as keyof TEvents]; if (event === undefined) { element[ key as keyof TElement ] = newValue as TElement[keyof TElement]; } else { const oldValue = previousProps[key]; if (newValue === oldValue) { continue; } if (oldValue !== undefined) { element.removeEventListener(event, oldValue); } if (newValue !== undefined) { element.addEventListener(event, newValue); } } } } componentDidMount() { this._updateElement(); } componentDidUpdate(old: InternalProps) { this._updateElement(old); } render() { // Since refs only get fulfilled once, pass a new one if the user's // ref changed. This allows refs to be fulfilled as expected, going from // having a value to null. const userRef = this.props.__forwardedRef as ReactModule.Ref<unknown>; if (this._ref === undefined || this._userRef !== userRef) { this._ref = (value: TElement | null) => { if (this._element === null) { this._element = value; } if (userRef !== null) { setRef(userRef, value); } this._userRef = userRef; }; } // Filter class properties and pass the remaining attributes to React. // This allows attributes to use framework rules // for setting attributes and render correctly under SSR. const newReactProps: any = { ref: this._ref }; const newElementProps = (this._elementProps = {} as any); const elementKeys = getElementKeys(type, config); const currentProps = this.props; for (const k in currentProps) { const v = currentProps[k]; if (elementKeys.has(k)) { newElementProps[k] = v; } else { // React does *not* handle `className` for custom elements so // coerce it to `class` so it's handled correctly. newReactProps[k === "className" ? "class" : k] = v; } } return React.createElement(getTagName(type, config), newReactProps); } } return React.forwardRef( ( props?: ReactWrapperProps<TElement, TEvents>, ref?: ReactModule.Ref<unknown> ) => React.createElement( ReactComponent, { ...props, __forwardedRef: ref } as InternalProps, props?.children ) ) as ReactWrapper<TElement, TEvents>; } return { wrap, registry }; }
the_stack
import * as React from "react"; import styles from "./StaffDirectory.module.scss"; import { IStaffDirectoryProps } from "./IStaffDirectoryProps"; import { IStaffDirectoryState } from "./IStaffDirectoryState"; import { escape } from "@microsoft/sp-lodash-subset"; import { WebPartTitle } from "@pnp/spfx-controls-react"; import { MSGraphClient } from "@microsoft/sp-http"; import { IStackTokens, mergeStyleSets, IBasePickerStyles, IPersonaProps, Spinner, SpinnerSize, MessageBar, MessageBarType, IPersonaStyleProps, ValidationState, Customizer, Stack, FontIcon, NormalPeoplePicker, ImageFit, Image, Text, ActionButton, Link, ILinkStyles, warnConditionallyRequiredProps, LinkBase, mergeStyles, } from "office-ui-fabric-react"; import { IAppContext } from "../../common/IAppContext"; import { IUser } from "../../entites/IUser"; import { useGetUsersByDepartment, useGetUserId, useSearchUsers, useGetUsersPresence, useGetUsersNextPage, } from "../../hooks/useSearchUsers"; import { useInterval } from '../../hooks/useInterval'; import { IUserExtended } from "../../entites/IUserExtended"; import { presenceStatus } from "../../common/PresenceStatus"; import { AppContext } from "../../common/AppContext"; import { UserCard } from "../UserCard/UserCard"; import { useRef } from "react"; import strings from "StaffDirectoryWebPartStrings"; import {Theme} from 'spfx-uifabric-themes'; const imageNoData: string = require("../../../assets/Nodatarafiki.svg"); const stackTokens: IStackTokens = { childrenGap: 10, }; // Component Styles const stackStyles = { root: { width: "100%", }, }; const suggestionProps = { suggestionsHeaderText: "Suggested People", mostRecentlyUsedHeaderText: "Suggested Contacts", noResultsFoundText: "No results found", loadingText: "Loading", showRemoveButtons: false, suggestionsAvailableAlertText: "People Picker Suggestions available", suggestionsContainerAriaLabel: "Suggested contacts", }; export const StaffDirectory: React.FunctionComponent<IStaffDirectoryProps> = ( props: IStaffDirectoryProps ) => { const { showBox, maxHeight } = props; const _theme = window.__themeState__.theme; const styleClasses = mergeStyleSets({ webPartTitle: { marginBottom: 20, }, separator: { paddingLeft: 30, paddingRight: 30, margin: 20, borderBottomStyle: "solid", borderWidth: 1, borderBottomColor: props.themeVariant?.palette?.themeLighter ?? _theme.themeLighter, }, styleIcon: { maxWidth: 44, minWidth: 44, minHeight: 30, height: 30, borderColor: props.themeVariant?.palette?.themePrimary ?? _theme.themePrimary, borderRightWidth: 0, borderRightStyle: "none", borderLeftWidth: 1, borderLeftStyle: "solid", borderTopWidth: 1, borderTopStyle: "solid", borderBottomWidth: 1, borderBottomStyle: "solid", display: "flex", alignItems: "center", justifyContent: "center", }, listContainer: { maxWidth: "100%", overflowY: "auto", marginTop: 20, padding: 10, boxShadow: showBox ? "0 2px 4px 0 rgba(0, 0, 0, 0.2), 0 25px 50px 0 rgba(0, 0, 0, 0.1)" : "", }, }); const pickerStyles: Partial<IBasePickerStyles> = { root: { width: "100%", maxHeight: 32, minHeight: 32, borderColor: props.themeVariant?.palette?.themePrimary ?? _theme.themePrimary, }, itemsWrapper: { borderColor: props.themeVariant?.palette?.themePrimary ?? _theme.themePrimary, }, text: { borderLeftWidth: 0, minHeight: 32, borderColor: props.themeVariant?.palette?.themePrimary ?? _theme.themePrimary, selectors: { ":focus": { borderColor:props.themeVariant?.palette?.themePrimary ?? _theme.themePrimary, }, ":hover": { borderColor: props.themeVariant?.palette?.themePrimary ?? _theme.themePrimary, }, "::after": { borderColor: props.themeVariant?.palette?.themePrimary ?? _theme.themePrimary, borderWidth: 1, borderLeftWidth: 0, }, }, }, }; const nextPageStyle: ILinkStyles = { root: { fontWeight: 600, fontSize: props.themeVariant?.fonts?.mediumPlus?.fontSize ?? window.__themeState__.theme["ms-font-mediumPlus-fontSize"], selectors: { ":hover": { textDecoration: "underline" } }, }, }; const _appContext = React.useRef<IAppContext>({} as IAppContext); const _msGraphClient = React.useRef<MSGraphClient>(); const _currentUser= React.useRef<any>(''); const _currentUserDepartment = React.useRef<string>(''); const [state, setState] = React.useState<IStaffDirectoryState>({ listUsers: [], hasError: false, errorMessage: "", isLoading: true, updateUsersPresence: false, nextPageLink: undefined, isLoadingNextPage: false, }); const picker = React.useRef(null); _currentUser.current = props.context.pageContext.user; let _currentuserProperties: IUser = {} as IUser; let _listUsers: IUserExtended[] = []; const _interval = props.refreshInterval * 60000; const _updatePresenceStatus: boolean = props.updatePresenceStatus; useInterval( async () => { _listUsers = state.listUsers; if (_listUsers) { _listUsers = await useGetUsersPresence(_listUsers, _msGraphClient.current); setState({ ...state, listUsers: _listUsers, isLoading: false, updateUsersPresence: true, }); } },(!_updatePresenceStatus || isNaN(_interval) ? null : _interval )); React.useEffect(() => { (async () => { try { _msGraphClient.current = await props.context.msGraphClientFactory.getClient(); _currentUser.current = props.context.pageContext.user; _appContext.current.currentUser = _currentUser.current ; _appContext.current.msGraphClient = _msGraphClient.current; _appContext.current.themeVariant = props.themeVariant; _currentuserProperties = await useGetUserId( _currentUser.current.email, _msGraphClient.current ); setState({ ...state, isLoading: true, }); _currentUserDepartment.current = _currentuserProperties.department; const _usersResults = await useGetUsersByDepartment( _currentUserDepartment.current, _msGraphClient.current, props.pageSize ); _listUsers = _usersResults.usersExtended; setState({ ...state, listUsers: _listUsers, isLoading: false, updateUsersPresence: false, nextPageLink: _usersResults.nextPage, }); // Pooling status each x min ( value define as property in webpart) } catch (error) { setState({ ...state, errorMessage: error.message ? error.message : " Error searching users, please try later or contact support.", hasError: true, isLoading: false, }); console.log(error); } })(); }, [props]); // on Filter changed const _onFilterChanged = async ( filterText: string, currentPersonas: IPersonaProps[], limitResults?: number ): Promise<IPersonaProps[]> => { let filteredPersonas: IPersonaProps[] = []; if (filterText.trim().length > 0) { try { const _usersResults = await useSearchUsers( "displayName:" + filterText, _msGraphClient.current ); filteredPersonas = []; for (const _user of _usersResults.usersExtended) { filteredPersonas.push({ text: _user.displayName, presence:presenceStatus[_user.availability].presenceStatus, presenceTitle: presenceStatus[_user.availability].presenceStatusLabel, imageUrl: _user.pictureBase64, secondaryText: _user.department, }); } filteredPersonas = removeDuplicates(filteredPersonas, currentPersonas); return filteredPersonas; } catch (error) { console.log(error); return []; } } else { return []; } }; // On Picker Changed const _onPickerChange = async (items: IPersonaProps[]) => { if (!(items.length === 0)) return; try { setState({ ...state, isLoading: true, }); const _usersResults = await useGetUsersByDepartment( _currentUserDepartment.current, _msGraphClient.current, props.pageSize ); setState({ ...state, nextPageLink: _usersResults.nextPage, listUsers: _usersResults.usersExtended, updateUsersPresence: false, }); } catch (error) { console.log(error); setState({ ...state, listUsers: [], hasError: true, errorMessage: error.message ? error.message : " Error searching users, please try later or contact support.", }); } }; const _onNextPage = async ( event: React.MouseEvent< HTMLElement | HTMLAnchorElement | HTMLButtonElement | LinkBase, MouseEvent > ) => { event.preventDefault(); let { listUsers, nextPageLink } = state; setState({ ...state, isLoadingNextPage: true, }); try { const _usersResults = await useGetUsersNextPage( nextPageLink, _msGraphClient.current ); const _newlistUsers = listUsers.concat(_usersResults.usersExtended); setState({ ...state, listUsers: _newlistUsers, isLoadingNextPage: false, nextPageLink: _usersResults.nextPage, }); } catch (error) { console.log(error); setState({ ...state, listUsers: [], hasError: true, isLoadingNextPage: false, errorMessage: error.message ? error.message : strings.ErrorMessage }); } }; // Render compoent // Has Error if (state.hasError) { return ( <MessageBar messageBarType={MessageBarType.error}>{state.errorMessage}</MessageBar> ); } return ( <AppContext.Provider value={_appContext.current}> <Customizer settings={{ theme: props.themeVariant }}> <WebPartTitle displayMode={props.displayMode} title={props.title} themeVariant={props.themeVariant} updateProperty={props.updateProperty} className={styleClasses.webPartTitle} /> <Stack tokens={stackTokens} style={{ width: "100%" }}> <Stack style={{ width: "100%" }} horizontal={true} verticalAlign="center" tokens={{ childrenGap: 0 }} > <div className={styleClasses.styleIcon}> <FontIcon iconName="Search" style={{ verticalAlign: "center", fontSize: props.themeVariant?.fonts?.mediumPlus?.fontSize ?? window.__themeState__.theme["ms-font-mediumPlus-fontSize"], color: props.themeVariant?.palette.themePrimary ?? _theme.themePrimary, }} /> </div> <NormalPeoplePicker itemLimit={1} onResolveSuggestions={_onFilterChanged} getTextFromItem={getTextFromItem} pickerSuggestionsProps={suggestionProps} className="ms-PeoplePicker" key="normal" onValidateInput={validateInput} onChange={_onPickerChange} styles={pickerStyles} componentRef={picker} onInputChange={onInputChange} resolveDelay={300} disabled={state.isLoading} onItemSelected={async (selectedItem: IPersonaProps) => { const _useSearchUsers = await useSearchUsers( `displayName:${selectedItem.text.trim()}`, _msGraphClient.current, props.pageSize ); setState({ ...state, nextPageLink: _useSearchUsers.nextPage, listUsers: _useSearchUsers.usersExtended, isLoading: false, updateUsersPresence: false, }); return selectedItem; }} /> </Stack> {state.isLoading ? ( <Spinner size={SpinnerSize.medium}></Spinner> ) : ( <div className={`${styleClasses.listContainer} ${styles.hideScrollBar}`} style={{ maxHeight: props.maxHeight }} > {state.listUsers.length > 0 ? ( state.listUsers.map((user, i) => { return ( <> <UserCard userData={user} userAttributes={props.userAttributes} updateUsersPresence={state.updateUsersPresence} ></UserCard> <div className={styleClasses.separator}></div> </> ); }) ) : ( <> <Stack horizontalAlign="center" verticalAlign="center" style={{ marginBottom: 25 }} > <Image src={imageNoData} imageFit={ImageFit.cover} width={250} height={300} ></Image> <Text variant="large">No colleagues found </Text> </Stack> </> )} {state.nextPageLink && ( <Stack horizontal horizontalAlign="end" verticalAlign="center" style={{ marginTop: 10, marginRight: 20, marginBottom: 20, }} > <Link styles={nextPageStyle} disabled={state.isLoadingNextPage} onClick={_onNextPage} > Next Page </Link> {state.isLoadingNextPage && ( <Spinner style={{ marginLeft: 5 }} size={SpinnerSize.small} ></Spinner> )} </Stack> )} </div> )} </Stack> </Customizer> </AppContext.Provider> ); }; // Get text from Persona const getTextFromItem = (persona) => { return persona.text; }; // Remove dumplicate Items const removeDuplicates = (personas, possibleDupes) => { return personas.filter((persona) => { return !listContainsPersona(persona, possibleDupes); }); }; // Check if selecte list has a persona selected const listContainsPersona = (persona, personas) => { if (!personas || !personas.length || personas.length === 0) { return false; } return ( personas.filter((item) => { return item.text === persona.text; }).length > 0 ); }; // Validate Input Function const validateInput = (input) => { if (input.trim().length > 1) { return ValidationState.valid; } else { return ValidationState.invalid; } }; /** * * * @param input The text entered into the picker. */ const onInputChange = (input) => { /* const outlookRegEx = /<.*>/g; const emailAddress = outlookRegEx.exec(input); if (emailAddress && emailAddress[0]) { return emailAddress[0].substring(1, emailAddress[0].length - 1); } */ return input; };
the_stack
import { Computed, Agile, StateObserver, Observer, State, ComputedTracker, } from '../../../src'; import * as Utils from '../../../src/utils'; import { LogMock } from '../../helper/logMock'; import waitForExpect from 'wait-for-expect'; describe('Computed Tests', () => { let dummyAgile: Agile; beforeEach(() => { LogMock.mockLogs(); dummyAgile = new Agile(); jest.spyOn(Computed.prototype, 'recompute'); jest.spyOn(Utils, 'extractRelevantObservers'); jest.clearAllMocks(); }); it('should create Computed with a not async compute method (default config)', () => { const computedFunction = () => 'computedValue'; const computed = new Computed(dummyAgile, computedFunction); expect(computed.computeFunction).toBe(computedFunction); expect(computed.config).toStrictEqual({ autodetect: true }); expect(computed.isComputed).toBeTruthy(); expect(Array.from(computed.deps)).toStrictEqual([]); expect(computed.hardCodedDeps).toStrictEqual([]); expect(Utils.extractRelevantObservers).toHaveBeenCalledWith([]); expect(computed.recompute).toHaveBeenCalledWith({ autodetect: computed.config.autodetect, overwrite: true, }); // Check if State was called with correct parameters expect(computed._key).toBeUndefined(); expect(computed.isSet).toBeFalsy(); expect(computed.isPlaceholder).toBeFalsy(); expect(computed.initialStateValue).toBe(computedFunction()); expect(computed._value).toBe(computedFunction()); expect(computed.previousStateValue).toBe(computedFunction()); expect(computed.nextStateValue).toBe(computedFunction()); expect(computed.observers['value']).toBeInstanceOf(StateObserver); expect(Array.from(computed.observers['value'].dependents)).toStrictEqual( [] ); expect(computed.observers['value'].key).toBeUndefined(); expect(computed.sideEffects).toStrictEqual({}); }); it('should create Computed with a not async compute method (specific config)', () => { const dummyObserver1 = new Observer(dummyAgile); dummyObserver1.addDependent = jest.fn(); const dummyObserver2 = new Observer(dummyAgile); dummyObserver2.addDependent = jest.fn(); const dummyState = new State(dummyAgile, undefined); const dummyStateObserver = new StateObserver(dummyState); dummyStateObserver.addDependent = jest.fn(); dummyState.observers['value'] = dummyStateObserver; const computedFunction = () => 'computedValue'; const computed = new Computed(dummyAgile, computedFunction, { key: 'coolComputed', dependents: [dummyObserver1], computedDeps: [dummyObserver2, undefined as any, dummyState], autodetect: false, initialValue: 'initialValue', }); expect(computed.computeFunction).toBe(computedFunction); expect(computed.config).toStrictEqual({ autodetect: false }); expect(computed.isComputed).toBeTruthy(); expect(Array.from(computed.deps)).toStrictEqual([ dummyObserver2, dummyStateObserver, ]); expect(computed.hardCodedDeps).toStrictEqual([ dummyObserver2, dummyStateObserver, ]); expect(Utils.extractRelevantObservers).toHaveBeenCalledWith([ dummyObserver2, undefined, dummyState, ]); expect(computed.recompute).toHaveBeenCalledWith({ autodetect: computed.config.autodetect, overwrite: true, }); expect(dummyObserver1.addDependent).not.toHaveBeenCalled(); // Because no Computed dependent expect(dummyObserver2.addDependent).toHaveBeenCalledWith( computed.observers['value'] ); expect(dummyStateObserver.addDependent).toHaveBeenCalledWith( computed.observers['value'] ); // Check if State was called with correct parameters expect(computed._key).toBe('coolComputed'); expect(computed.isSet).toBeFalsy(); expect(computed.isPlaceholder).toBeFalsy(); expect(computed.initialStateValue).toBe('initialValue'); expect(computed._value).toBe('initialValue'); expect(computed.previousStateValue).toBe('initialValue'); expect(computed.nextStateValue).toBe('initialValue'); expect(computed.observers['value']).toBeInstanceOf(StateObserver); expect(Array.from(computed.observers['value'].dependents)).toStrictEqual([ dummyObserver1, ]); expect(computed.observers['value'].key).toBe('coolComputed'); expect(computed.sideEffects).toStrictEqual({}); }); it('should create Computed with an async compute method (default config)', () => { const computedFunction = async () => 'computedValue'; const computed = new Computed(dummyAgile, computedFunction); expect(computed.computeFunction).toBe(computedFunction); expect(computed.config).toStrictEqual({ autodetect: false }); expect(computed.isComputed).toBeTruthy(); expect(Array.from(computed.deps)).toStrictEqual([]); expect(computed.hardCodedDeps).toStrictEqual([]); expect(Utils.extractRelevantObservers).toHaveBeenCalledWith([]); expect(computed.recompute).toHaveBeenCalledWith({ autodetect: computed.config.autodetect, overwrite: true, }); // Check if State was called with correct parameters expect(computed._key).toBeUndefined(); expect(computed.isSet).toBeFalsy(); expect(computed.isPlaceholder).toBeFalsy(); expect(computed.initialStateValue).toBe(null); expect(computed._value).toBe(null); expect(computed.previousStateValue).toBe(null); expect(computed.nextStateValue).toBe(null); expect(computed.observers['value']).toBeInstanceOf(StateObserver); expect(Array.from(computed.observers['value'].dependents)).toStrictEqual( [] ); expect(computed.observers['value'].key).toBeUndefined(); expect(computed.sideEffects).toStrictEqual({}); }); describe('Computed Function Tests', () => { let computed: Computed; const dummyComputeFunction = jest.fn(() => 'computedValue'); beforeEach(() => { computed = new Computed(dummyAgile, dummyComputeFunction); }); describe('recompute function tests', () => { beforeEach(() => { computed.observers['value'].ingestValue = jest.fn(); }); it('should ingest Computed Class into the Runtime (default config)', async () => { computed.compute = jest.fn(() => Promise.resolve('jeff')); computed.recompute(); expect(computed.compute).toHaveBeenCalledWith({ autodetect: false }); await waitForExpect(() => { expect(computed.observers['value'].ingestValue).toHaveBeenCalledWith( 'jeff', { autodetect: false, // Not required but passed for simplicity } ); }); }); it('should ingest Computed Class into the Runtime (specific config)', async () => { computed.compute = jest.fn(() => Promise.resolve('jeff')); computed.recompute({ autodetect: true, background: true, sideEffects: { enabled: false, }, force: false, key: 'jeff', }); expect(computed.compute).toHaveBeenCalledWith({ autodetect: true }); await waitForExpect(() => { expect(computed.observers['value'].ingestValue).toHaveBeenCalledWith( 'jeff', { background: true, sideEffects: { enabled: false, }, force: false, key: 'jeff', autodetect: true, // Not required but passed for simplicity } ); }); }); }); describe('updateComputeFunction function tests', () => { const newComputeFunction = () => 'newComputedValue'; let dummyObserver: Observer; let oldDummyObserver: Observer; let dummyStateObserver: StateObserver; let dummyState: State; beforeEach(() => { dummyObserver = new Observer(dummyAgile); dummyObserver.removeDependent = jest.fn(); dummyObserver.addDependent = jest.fn(); oldDummyObserver = new Observer(dummyAgile); oldDummyObserver.removeDependent = jest.fn(); oldDummyObserver.addDependent = jest.fn(); dummyState = new State(dummyAgile, undefined); dummyStateObserver = new StateObserver(dummyState); dummyStateObserver.removeDependent = jest.fn(); dummyStateObserver.addDependent = jest.fn(); dummyState.observers['value'] = dummyStateObserver; computed.hardCodedDeps = [oldDummyObserver]; computed.deps = new Set([oldDummyObserver]); }); it('should updated computeFunction and overwrite its dependencies (default config)', () => { computed.config.autodetect = 'dummyBoolean' as any; computed.updateComputeFunction(newComputeFunction, [ dummyState, dummyObserver, ]); expect(computed.hardCodedDeps).toStrictEqual([ dummyStateObserver, dummyObserver, ]); expect(Array.from(computed.deps)).toStrictEqual([ dummyStateObserver, dummyObserver, ]); expect(computed.computeFunction).toBe(newComputeFunction); expect(computed.recompute).toHaveBeenCalledWith({ autodetect: computed.config.autodetect, }); expect(Utils.extractRelevantObservers).toHaveBeenCalledWith([ dummyState, dummyObserver, ]); // Make this Observer no longer depend on the old dep Observers expect(oldDummyObserver.removeDependent).toHaveBeenCalledWith( computed.observers['value'] ); expect(dummyStateObserver.removeDependent).not.toHaveBeenCalled(); expect(dummyObserver.removeDependent).not.toHaveBeenCalled(); // Make this Observer depend on the new hard coded dep Observers expect(oldDummyObserver.addDependent).not.toHaveBeenCalled(); expect(dummyStateObserver.addDependent).toHaveBeenCalledWith( computed.observers['value'] ); expect(dummyObserver.addDependent).toHaveBeenCalledWith( computed.observers['value'] ); }); it('should updated computeFunction and overwrite its dependencies (specific config)', () => { computed.updateComputeFunction( newComputeFunction, [dummyState, dummyObserver], { background: true, sideEffects: { enabled: false, }, key: 'jeff', force: true, autodetect: false, } ); expect(computed.hardCodedDeps).toStrictEqual([ dummyStateObserver, dummyObserver, ]); expect(Array.from(computed.deps)).toStrictEqual([ dummyStateObserver, dummyObserver, ]); expect(computed.computeFunction).toBe(newComputeFunction); expect(computed.recompute).toHaveBeenCalledWith({ background: true, sideEffects: { enabled: false, }, key: 'jeff', force: true, autodetect: false, }); expect(Utils.extractRelevantObservers).toHaveBeenCalledWith([ dummyState, dummyObserver, ]); // Make this Observer no longer depend on the old dep Observers expect(oldDummyObserver.removeDependent).toHaveBeenCalledWith( computed.observers['value'] ); expect(dummyStateObserver.removeDependent).not.toHaveBeenCalled(); expect(dummyObserver.removeDependent).not.toHaveBeenCalled(); // Make this Observer depend on the new hard coded dep Observers expect(oldDummyObserver.addDependent).not.toHaveBeenCalled(); expect(dummyStateObserver.addDependent).toHaveBeenCalledWith( computed.observers['value'] ); expect(dummyObserver.addDependent).toHaveBeenCalledWith( computed.observers['value'] ); }); }); describe('compute function tests', () => { let dummyObserver1: Observer; let dummyObserver2: Observer; let dummyObserver3: Observer; let dummyObserver4: Observer; beforeEach(() => { dummyObserver1 = new Observer(dummyAgile); jest.spyOn(dummyObserver1, 'addDependent'); jest.spyOn(dummyObserver1, 'removeDependent'); dummyObserver2 = new Observer(dummyAgile); jest.spyOn(dummyObserver2, 'addDependent'); jest.spyOn(dummyObserver2, 'removeDependent'); dummyObserver3 = new Observer(dummyAgile); jest.spyOn(dummyObserver3, 'addDependent'); jest.spyOn(dummyObserver3, 'removeDependent'); dummyObserver4 = new Observer(dummyAgile); jest.spyOn(dummyObserver4, 'addDependent'); jest.spyOn(dummyObserver4, 'removeDependent'); computed.hardCodedDeps = [dummyObserver3]; computed.deps = new Set([dummyObserver3, dummyObserver4]); // mockClear because otherwise the static mock doesn't get reset after each '.it()' test jest.spyOn(ComputedTracker, 'track').mockClear(); jest.spyOn(ComputedTracker, 'getTrackedObservers').mockClear(); }); it( 'should call computeFunction ' + 'and track dependencies the computeFunction depends on (config.autodetect = true)', async () => { jest .spyOn(ComputedTracker, 'getTrackedObservers') .mockReturnValueOnce([dummyObserver1, dummyObserver2]); computed.computeFunction = jest.fn(() => 'newComputedValue'); const response = await computed.compute({ autodetect: true }); expect(response).toBe('newComputedValue'); expect(dummyComputeFunction).toHaveBeenCalled(); // Tracking expect(ComputedTracker.track).toHaveBeenCalled(); expect(ComputedTracker.getTrackedObservers).toHaveBeenCalled(); expect(computed.hardCodedDeps).toStrictEqual([dummyObserver3]); expect(Array.from(computed.deps)).toStrictEqual([ dummyObserver3, dummyObserver1, dummyObserver2, ]); // Clean up old dependencies expect(dummyObserver1.removeDependent).not.toHaveBeenCalled(); expect(dummyObserver2.removeDependent).not.toHaveBeenCalled(); expect(dummyObserver3.removeDependent).not.toHaveBeenCalled(); expect(dummyObserver4.removeDependent).toHaveBeenCalledWith( computed.observers['value'] ); // Make this Observer depend on the newly found dep Observers expect(dummyObserver1.addDependent).toHaveBeenCalledWith( computed.observers['value'] ); expect(dummyObserver2.addDependent).toHaveBeenCalledWith( computed.observers['value'] ); expect(dummyObserver3.addDependent).not.toHaveBeenCalled(); // Because Computed already depends on the 'dummyObserver3' expect(dummyObserver4.addDependent).not.toHaveBeenCalled(); } ); it( 'should call computeFunction ' + "and shouldn't track dependencies the computeFunction depends on (config.autodetect = false)", async () => { computed.computeFunction = jest.fn(async () => { await new Promise((resolve) => setTimeout(resolve, 500)); return 'newComputedValue'; }); const response = await computed.compute({ autodetect: false }); expect(response).toBe('newComputedValue'); expect(dummyComputeFunction).toHaveBeenCalled(); // Tracking expect(ComputedTracker.track).not.toHaveBeenCalled(); expect(ComputedTracker.getTrackedObservers).not.toHaveBeenCalled(); expect(computed.hardCodedDeps).toStrictEqual([dummyObserver3]); expect(Array.from(computed.deps)).toStrictEqual([ dummyObserver3, dummyObserver4, ]); expect(dummyObserver1.removeDependent).not.toHaveBeenCalled(); expect(dummyObserver2.removeDependent).not.toHaveBeenCalled(); expect(dummyObserver3.removeDependent).not.toHaveBeenCalled(); expect(dummyObserver4.removeDependent).not.toHaveBeenCalled(); expect(dummyObserver1.addDependent).not.toHaveBeenCalled(); expect(dummyObserver2.addDependent).not.toHaveBeenCalled(); expect(dummyObserver3.addDependent).not.toHaveBeenCalled(); expect(dummyObserver4.addDependent).not.toHaveBeenCalled(); } ); }); }); });
the_stack
import IPython = require('base/js/namespace'); import $ = require('jquery'); import dialog = require('base/js/dialog'); import utils = require('base/js/utils'); declare var gapi:any; declare var Promise:any; interface LocalWindow extends Window { gapi: any; } declare var window: LocalWindow; var default_config = { /** * Google API Client ID * @type {string} **/ CLIENT_ID : '763546234320-uvcktfp0udklafjqv00qjgivpjh0t33p.apps.googleusercontent.com', APP_ID : '763546234320', FILE_SCOPE : true, METADATA_SCOPE : true, }; /** * Google API App ID * @type {string} */ export var APP_ID:string = '763546234320'; /** * OAuth scope for accessing specific files that have been opened/created * by this app. * @type {string} */ var FILES_OAUTH_SCOPE = 'https://www.googleapis.com/auth/drive.file'; /** * OAuth scope for accessing file metadata (for tree view) * @type {string} */ var METADATA_OAUTH_SCOPE = 'https://www.googleapis.com/auth/drive.readonly.metadata'; /** * Error message for origin mismatch error. * @type {string} */ var ORIGIN_MISMATCH_MSG = ( 'An origin_mismatch error has been receieved from Google Drive. This' + ' may be beacuse you are running IPython notebook on a URL other than' + ' 127.0.0.1 or a port that is not in the range 8888-8899. Please see' + ' https://github.com/jupyter/jupyter-drive/issues/21 for more details'); /** * Helper functions */ /** * Perform an authenticated download. * @param {string} url The download URL. * @return {Promise} resolved with the contents of the file, or rejected * with an Error. */ export var download = function(url:string):Promise<any> { // Sends request to load file to drive. var token = gapi.auth.getToken().access_token; var settings = { headers: { 'Authorization': 'Bearer ' + token } }; return utils.promising_ajax(url, settings); }; /** * Wrap a Google API result as an Promise, which is immediate resolved * or rejected based on whether an error is detected. * @param {Object} result The result of a Google API call, as returned * by a request.execute method. * @return {Promise} The result wrapped as a promise. */ var wrap_result = function<T>(result:T):Promise<T> { if (!result) { // Error type 1: result is False var error = new Error('Unknown error during Google API call'); error.name = 'GapiError'; return Promise.reject(error); } else if (result['error']) { // Error type 2: an error resource (see // https://developers.google.com/drive/web/handle-errors) var error = new Error(result['error']['message']); error['gapi_error'] = result; return Promise.reject(error); } else { return Promise.resolve(result); } }; /** * Executes a Google API request. This wraps the request.execute() method, * by returning a Promise, which may be resolved or rejected. The raw * return value of execute() has errors detected, and errors are wrapped as * an Error object. * * Typical usage: * var request = gapi.client.drive.files.get({ * 'fileId': fileId * }); * execute(request, success, error); * * @param {Object} request The request, generated by the Google JavaScript * client API. * @param {boolean} [attemptReauth=true] Boolean indicating whether * re-authorization should be attempted if a 401 status is returned. * @return {Promise} Fullfilled with the result on success, or the * result wrapped as an Error on error. */ export var execute = function(request, attemptReauth:boolean = true) { return new Promise(function(resolve, reject) { request.execute(function(result) { /* Special case: although the user authorizes jupyter-drive on first * load, the authorization has a timeout. (Google seem to use 3600 * seconds == 1 hour as default.) After this time, even * authenticated requests will fail. If we have failed with a 401, * attempt to execute again after authorizing once more. */ if(attemptReauth && (result.statusCode === 401)) { console.warn("[gapiutils.js] Got 401 status. Will re-authorize."); resolve(_conf_prm.then(function(config) { return authorize(false, config); }).then(execute(request, false))); } else { resolve(wrap_result(result)); } }); }); }; /** * Authorization and Loading Google API * * Utilities for doing OAuth flow with the Google API. */ /** * Utility method that polls for a condition to hold. * @param {Function} condition Function called with no args, that returns * true when the condition is fullfilled * @param {Number} interval Polling interval in milliseconds * @return Promise fullfilled when condition holds */ var poll = function(condition, interval:number):Promise<any> { return new Promise(function(resolve, reject) { var polling_function = function() { if (condition()) { resolve(); } else { setTimeout(polling_function, interval); } }; polling_function(); }); }; /** * (Internal use only) Returns a promise that is fullfilled when client * library loads. * @return {Promise} empty value on success or error on failure. */ var load_gapi_1 = function():Promise<any> { return Promise.resolve($.getScript('https://apis.google.com/js/client.js')) .then(function() { // poll every 100ms until window.gapi and gapi.client exist. return poll(function() { return !!(window.gapi && gapi.client); }, 100); }, utils.wrap_ajax_error); }; /** * (Internal use only) Returns a promise fullfilled when client library * loads. */ var load_gapi_2 = function(d):Promise<any> { return new Promise(function(resolve, reject) { gapi.load('auth:client,drive-realtime,drive-share,picker', function() { gapi.client.load('drive', 'v2', resolve); }); }); }; /* {set,clear}Timeout handle for the authorization refresh timeout. */ var _authorizeTimeout = null; /** * Returns a promise fullfilled when the Google API has authorized. * @param {boolean} opt_withPopup If true, display popup without first * trying to authorize without a popup. */ var authorize = function(opt_withPopup:boolean, conf:any):Promise<any> { var config = $.extend({}, default_config, (conf.data||{})['gdrive']); var scope = []; if(config.FILE_SCOPE){ scope.push(FILES_OAUTH_SCOPE) } if(config.METADATA_SCOPE){ scope.push(METADATA_OAUTH_SCOPE) } var authorize_internal = function() { return new Promise(function(resolve, reject) { gapi.auth.authorize({ 'client_id': config.CLIENT_ID, 'scope': scope, 'immediate': !opt_withPopup }, function(result) { // Google API auth tokens have an inbuilt expiry, usually 3600 // seconds == 1 hour. The Google-blessed approach to long-lived // web apps is to refresh the auth token after 45 minutes (=== // 3/4 of expirty time). If we are given an expiry time (and if // that expiry time is numeric) set a timeout to refresh the // token. if(result.expires_in && (+result.expires_in > 0)) { // Clear any existing timeout if(_authorizeTimeout !== null) { clearTimeout(_authorizeTimeout); } // Set a reauthorization timeout to be 3/4 of expires_in. // Note that expires_in is in seconds and setTimeout takes a // milliseconds argument, hence the multiplication by 750. _authorizeTimeout = setTimeout(function() { console.log("Refreshing Google API token."); _authorizeTimeout = null; _conf_prm.then(function(config) { authorize(false, config); }); }, 750 * (+result.expires_in)); } resolve(wrap_result(result)); }); }); }; if (opt_withPopup) { return new Promise(function(resolve, reject) { // Gets user to initiate the authorization with a dialog, // to prevent popup blockers. var options = { title: 'Authentication needed', body: ('Accessing Google Drive requires authentication. Click' + ' ok to proceed.'), buttons: { 'ok': { click : function() { resolve(authorize_internal()); }, }, 'cancel': { click : reject } } } dialog.modal(options); }); } else { // Return result of authorize, trying again with withPopup=true // in case of failure. return authorize_internal().catch(function(error) { if (error['gapi_error'] && error['gapi_error']['error_subtype'] == 'origin_mismatch') { // An origin mismatch error almost always indicates that the user // has tried to launch IPython from a port or origin unknown to // the client ID. Therefore inform them of this. var _error = new Error(ORIGIN_MISMATCH_MSG); _error.name = 'GapiError'; return Promise.reject(_error); } return authorize(true, {'data': {'gdrive': config}}); }); } }; var _handle = {resolve:(any) => Object}; var _conf_prm = new Promise(function(resolve){ _handle.resolve = resolve; }) /** * calling config with conf, results in the promise _conf_prm being resolved with conf. * This then triggers the rest of the gapi loading **/ export var config = function(conf):void{ _handle.resolve(conf); } /** * Promise fullfilled when gapi is loaded, and authorization is complete. */ var load_gapi = load_gapi_1().then(load_gapi_2) export var gapi_ready = Promise.all([load_gapi, _conf_prm]).then( function(values){ var config = values[1]; return authorize(null, config); } );
the_stack
* @packageDocumentation * @module pipeline */ import { ccclass, displayOrder, serializable, type } from 'cc.decorator'; import { sceneCulling } from './scene-culling'; import { Asset } from '../assets/asset'; import { AccessType, Address, Attribute, Buffer, BufferInfo, BufferUsageBit, ClearFlagBit, ClearFlags, ColorAttachment, CommandBuffer, DepthStencilAttachment, DescriptorSet, Device, Feature, Filter, Format, Framebuffer, FramebufferInfo, InputAssembler, InputAssemblerInfo, LoadOp, MemoryUsageBit, Rect, RenderPass, RenderPassInfo, Sampler, SamplerInfo, StoreOp, SurfaceTransform, Swapchain, Texture, TextureInfo, TextureType, TextureUsageBit, Viewport } from '../gfx'; import { legacyCC } from '../global-exports'; import { MacroRecord } from '../renderer/core/pass-utils'; import { RenderWindow } from '../renderer/core/render-window'; import { Camera, SKYBOX_FLAG } from '../renderer/scene/camera'; import { Model } from '../renderer/scene/model'; import { Root } from '../root'; import { GlobalDSManager } from './global-descriptor-set-manager'; import { PipelineSceneData } from './pipeline-scene-data'; import { PipelineUBO } from './pipeline-ubo'; import { RenderFlow } from './render-flow'; import { IPipelineEvent, PipelineEventProcessor, PipelineEventType } from './pipeline-event'; /** * @en Render pipeline information descriptor * @zh 渲染管线描述信息。 */ export interface IRenderPipelineInfo { flows: RenderFlow[]; tag?: number; } export const MAX_BLOOM_FILTER_PASS_NUM = 6; export class BloomRenderData { renderPass: RenderPass = null!; sampler: Sampler = null!; prefiterTex: Texture = null!; downsampleTexs: Texture[] = []; upsampleTexs: Texture[] = []; combineTex: Texture = null!; prefilterFramebuffer: Framebuffer = null!; downsampleFramebuffers: Framebuffer[] = []; upsampleFramebuffers: Framebuffer[] = []; combineFramebuffer: Framebuffer = null!; } export class PipelineRenderData { outputFrameBuffer: Framebuffer = null!; outputRenderTargets: Texture[] = []; outputDepth: Texture = null!; sampler: Sampler = null!; bloom: BloomRenderData | null = null; } export class PipelineInputAssemblerData { quadIB: Buffer|null = null; quadVB: Buffer|null = null; quadIA: InputAssembler|null = null; } /** * @en Render pipeline describes how we handle the rendering process for all render objects in the related render scene root. * It contains some general pipeline configurations, necessary rendering resources and some [[RenderFlow]]s. * The rendering process function [[render]] is invoked by [[Root]] for all [[Camera]]s. * @zh 渲染管线对象决定了引擎对相关渲染场景下的所有渲染对象实施的完整渲染流程。 * 这个类主要包含一些通用的管线配置,必要的渲染资源和一些 [[RenderFlow]]。 * 渲染流程函数 [[render]] 会由 [[Root]] 发起调用并对所有 [[Camera]] 执行预设的渲染流程。 */ @ccclass('cc.RenderPipeline') export abstract class RenderPipeline extends Asset implements IPipelineEvent { /** * @en The tag of pipeline. * @zh 管线的标签。 * @readonly */ get tag (): number { return this._tag; } /** * @en The flows of pipeline. * @zh 管线的渲染流程列表。 * @readonly */ get flows (): RenderFlow[] { return this._flows; } /** * @en Tag * @zh 标签 * @readonly */ @displayOrder(0) @serializable protected _tag = 0; /** * @en Flows * @zh 渲染流程列表 * @readonly */ @displayOrder(1) @type([RenderFlow]) @serializable protected _flows: RenderFlow[] = []; protected _quadIB: Buffer | null = null; protected _quadVBOnscreen: Buffer | null = null; protected _quadVBOffscreen: Buffer | null = null; protected _quadIAOnscreen: InputAssembler | null = null; protected _quadIAOffscreen: InputAssembler | null = null; protected _eventProcessor: PipelineEventProcessor = new PipelineEventProcessor(); /** * @zh * 四边形输入汇集器。 */ public get quadIAOnscreen (): InputAssembler { return this._quadIAOnscreen!; } public get quadIAOffscreen (): InputAssembler { return this._quadIAOffscreen!; } public getPipelineRenderData (): PipelineRenderData { return this._pipelineRenderData!; } /** * @en * Constant macro string, static throughout the whole runtime. * Used to pass device-specific parameters to shader. * @zh 常量宏定义字符串,运行时全程不会改变,用于给 shader 传一些只和平台相关的参数。 * @readonly */ get constantMacros () { return this._constantMacros; } /** * @en * The current global-scoped shader macros. * Used to control effects like IBL, fog, etc. * @zh 当前的全局宏定义,用于控制如 IBL、雾效等模块。 * @readonly */ get macros () { return this._macros; } get device () { return this._device; } get globalDSManager () { return this._globalDSManager; } get descriptorSetLayout () { return this._globalDSManager.descriptorSetLayout; } get descriptorSet () { return this._descriptorSet; } get commandBuffers () { return this._commandBuffers; } get pipelineUBO () { return this._pipelineUBO; } get pipelineSceneData () { return this._pipelineSceneData; } set profiler (value) { this._profiler = value; } get profiler () { return this._profiler; } set clusterEnabled (value) { this._clusterEnabled = value; } get clusterEnabled () { return this._clusterEnabled; } set bloomEnabled (value) { this._bloomEnabled = value; } get bloomEnabled () { return this._bloomEnabled; } protected _device!: Device; protected _globalDSManager!: GlobalDSManager; protected _descriptorSet!: DescriptorSet; protected _commandBuffers: CommandBuffer[] = []; protected _pipelineUBO = new PipelineUBO(); protected _macros: MacroRecord = {}; protected _constantMacros = ''; protected _profiler: Model | null = null; protected declare _pipelineSceneData: PipelineSceneData; protected _pipelineRenderData: PipelineRenderData | null = null; protected _renderPasses = new Map<ClearFlags, RenderPass>(); protected _width = 0; protected _height = 0; protected _lastUsedRenderArea: Rect = new Rect(); protected _clusterEnabled = false; protected _bloomEnabled = false; /** * @en The initialization process, user shouldn't use it in most case, only useful when need to generate render pipeline programmatically. * @zh 初始化函数,正常情况下不会用到,仅用于程序化生成渲染管线的情况。 * @param info The render pipeline information */ public initialize (info: IRenderPipelineInfo): boolean { this._flows = info.flows; if (info.tag) { this._tag = info.tag; } return true; } public createRenderPass (clearFlags: ClearFlags, colorFmt: Format, depthFmt: Format): RenderPass { const device = this._device; const colorAttachment = new ColorAttachment(); const depthStencilAttachment = new DepthStencilAttachment(); colorAttachment.format = colorFmt; depthStencilAttachment.format = depthFmt; depthStencilAttachment.stencilStoreOp = StoreOp.DISCARD; depthStencilAttachment.depthStoreOp = StoreOp.DISCARD; if (!(clearFlags & ClearFlagBit.COLOR)) { if (clearFlags & SKYBOX_FLAG) { colorAttachment.loadOp = LoadOp.DISCARD; } else { colorAttachment.loadOp = LoadOp.LOAD; colorAttachment.beginAccesses = [AccessType.COLOR_ATTACHMENT_WRITE]; } } if ((clearFlags & ClearFlagBit.DEPTH_STENCIL) !== ClearFlagBit.DEPTH_STENCIL) { if (!(clearFlags & ClearFlagBit.DEPTH)) depthStencilAttachment.depthLoadOp = LoadOp.LOAD; if (!(clearFlags & ClearFlagBit.STENCIL)) depthStencilAttachment.stencilLoadOp = LoadOp.LOAD; } depthStencilAttachment.beginAccesses = [AccessType.DEPTH_STENCIL_ATTACHMENT_WRITE]; const renderPassInfo = new RenderPassInfo([colorAttachment], depthStencilAttachment); return device.createRenderPass(renderPassInfo); } public getRenderPass (clearFlags: ClearFlags, swapchain: Swapchain): RenderPass { let renderPass = this._renderPasses.get(clearFlags); if (renderPass) { return renderPass; } renderPass = this.createRenderPass(clearFlags, swapchain.colorTexture.format, swapchain.depthStencilTexture.format); this._renderPasses.set(clearFlags, renderPass); return renderPass; } public applyFramebufferRatio (framebuffer: Framebuffer) { const sceneData = this.pipelineSceneData; const width = this._width * sceneData.shadingScale; const height = this._height * sceneData.shadingScale; const colorTexArr: any = framebuffer.colorTextures; for (let i = 0; i < colorTexArr.length; i++) { colorTexArr[i]!.resize(width, height); } if (framebuffer.depthStencilTexture) { framebuffer.depthStencilTexture.resize(width, height); } framebuffer.destroy(); framebuffer.initialize(new FramebufferInfo( framebuffer.renderPass, colorTexArr, framebuffer.depthStencilTexture, )); } /** * @en generate renderArea by camera * @zh 生成renderArea * @param camera the camera * @returns */ public generateRenderArea (camera: Camera, out?: Rect): Rect { const res = out || new Rect(); const vp = camera.viewport; // render area is not oriented const swapchain = camera.window!.swapchain; const w = swapchain && swapchain.surfaceTransform % 2 ? camera.height : camera.width; const h = swapchain && swapchain.surfaceTransform % 2 ? camera.width : camera.height; res.x = vp.x * w; res.y = vp.y * h; res.width = vp.width * w; res.height = vp.height * h; return res; } public generateViewport (camera: Camera, out?: Viewport): Viewport { const rect = this.generateRenderArea(camera); const shadingScale = this.pipelineSceneData.shadingScale; const viewport = out || new Viewport(rect.x * shadingScale, rect.y * shadingScale, rect.width * shadingScale, rect.height * shadingScale); return viewport; } public generateScissor (camera: Camera, out?: Rect): Rect { const rect = this.generateRenderArea(camera); const shadingScale = this.pipelineSceneData.shadingScale; const scissor = out || new Rect(rect.x * shadingScale, rect.y * shadingScale, rect.width * shadingScale, rect.height * shadingScale); return scissor; } /** * @en Activate the render pipeline after loaded, it mainly activate the flows * @zh 当渲染管线资源加载完成后,启用管线,主要是启用管线内的 flow * TODO: remove swapchain dependency at this stage * after deferred pipeline can handle multiple swapchains */ public activate (swapchain: Swapchain): boolean { const root = legacyCC.director.root as Root; this._device = root.device; this._generateConstantMacros(); this._globalDSManager = new GlobalDSManager(this); this._descriptorSet = this._globalDSManager.globalDescriptorSet; this._pipelineUBO.activate(this._device, this); // update global defines in advance here for deferred pipeline may tryCompile shaders. this._macros.CC_USE_HDR = this._pipelineSceneData.isHDR; this._generateConstantMacros(); this._pipelineSceneData.activate(this._device, this); for (let i = 0; i < this._flows.length; i++) { this._flows[i].activate(this); } return true; } protected _ensureEnoughSize (cameras: Camera[]) {} /** * @en Render function, it basically run the render process of all flows in sequence for the given view. * @zh 渲染函数,对指定的渲染视图按顺序执行所有渲染流程。 * @param view Render view。 */ public render (cameras: Camera[]) { if (cameras.length === 0) { return; } this._commandBuffers[0].begin(); this.emit(PipelineEventType.RENDER_FRAME_BEGIN, cameras); this._ensureEnoughSize(cameras); for (let i = 0; i < cameras.length; i++) { const camera = cameras[i]; if (camera.scene) { this.emit(PipelineEventType.RENDER_CAMERA_BEGIN, camera); sceneCulling(this, camera); this._pipelineUBO.updateGlobalUBO(camera.window!); this._pipelineUBO.updateCameraUBO(camera); for (let j = 0; j < this._flows.length; j++) { this._flows[j].render(camera); } this.emit(PipelineEventType.RENDER_CAMERA_END, camera); } } this.emit(PipelineEventType.RENDER_FRAME_END, cameras); this._commandBuffers[0].end(); this._device.queue.submit(this._commandBuffers); } /** * @zh * 销毁四边形输入汇集器。 */ protected _destroyQuadInputAssembler () { if (this._quadIB) { this._quadIB.destroy(); this._quadIB = null; } if (this._quadVBOnscreen) { this._quadVBOnscreen.destroy(); this._quadVBOnscreen = null; } if (this._quadVBOffscreen) { this._quadVBOffscreen.destroy(); this._quadVBOffscreen = null; } if (this._quadIAOnscreen) { this._quadIAOnscreen.destroy(); this._quadIAOnscreen = null; } if (this._quadIAOffscreen) { this._quadIAOffscreen.destroy(); this._quadIAOffscreen = null; } } protected _destroyBloomData () { const bloom = this._pipelineRenderData!.bloom; if (bloom === null || this.bloomEnabled === false) return; if (bloom.prefiterTex) bloom.prefiterTex.destroy(); if (bloom.prefilterFramebuffer) bloom.prefilterFramebuffer.destroy(); for (let i = 0; i < bloom.downsampleTexs.length; ++i) { bloom.downsampleTexs[i].destroy(); bloom.downsampleFramebuffers[i].destroy(); } bloom.downsampleTexs.length = 0; bloom.downsampleFramebuffers.length = 0; for (let i = 0; i < bloom.upsampleTexs.length; ++i) { bloom.upsampleTexs[i].destroy(); bloom.upsampleFramebuffers[i].destroy(); } bloom.upsampleTexs.length = 0; bloom.upsampleFramebuffers.length = 0; if (bloom.combineTex) bloom.combineTex.destroy(); if (bloom.combineFramebuffer) bloom.combineFramebuffer.destroy(); bloom.renderPass?.destroy(); this._pipelineRenderData!.bloom = null; } private _genQuadVertexData (surfaceTransform: SurfaceTransform, renderArea: Rect) : Float32Array { const vbData = new Float32Array(4 * 4); const minX = renderArea.x / this._width; const maxX = (renderArea.x + renderArea.width) / this._width; let minY = renderArea.y / this._height; let maxY = (renderArea.y + renderArea.height) / this._height; if (this.device.capabilities.screenSpaceSignY > 0) { const temp = maxY; maxY = minY; minY = temp; } let n = 0; switch (surfaceTransform) { case (SurfaceTransform.IDENTITY): n = 0; vbData[n++] = -1.0; vbData[n++] = -1.0; vbData[n++] = minX; vbData[n++] = maxY; vbData[n++] = 1.0; vbData[n++] = -1.0; vbData[n++] = maxX; vbData[n++] = maxY; vbData[n++] = -1.0; vbData[n++] = 1.0; vbData[n++] = minX; vbData[n++] = minY; vbData[n++] = 1.0; vbData[n++] = 1.0; vbData[n++] = maxX; vbData[n++] = minY; break; case (SurfaceTransform.ROTATE_90): n = 0; vbData[n++] = -1.0; vbData[n++] = -1.0; vbData[n++] = maxX; vbData[n++] = maxY; vbData[n++] = 1.0; vbData[n++] = -1.0; vbData[n++] = maxX; vbData[n++] = minY; vbData[n++] = -1.0; vbData[n++] = 1.0; vbData[n++] = minX; vbData[n++] = maxY; vbData[n++] = 1.0; vbData[n++] = 1.0; vbData[n++] = minX; vbData[n++] = minY; break; case (SurfaceTransform.ROTATE_180): n = 0; vbData[n++] = -1.0; vbData[n++] = -1.0; vbData[n++] = minX; vbData[n++] = minY; vbData[n++] = 1.0; vbData[n++] = -1.0; vbData[n++] = maxX; vbData[n++] = minY; vbData[n++] = -1.0; vbData[n++] = 1.0; vbData[n++] = minX; vbData[n++] = maxY; vbData[n++] = 1.0; vbData[n++] = 1.0; vbData[n++] = maxX; vbData[n++] = maxY; break; case (SurfaceTransform.ROTATE_270): n = 0; vbData[n++] = -1.0; vbData[n++] = -1.0; vbData[n++] = minX; vbData[n++] = minY; vbData[n++] = 1.0; vbData[n++] = -1.0; vbData[n++] = minX; vbData[n++] = maxY; vbData[n++] = -1.0; vbData[n++] = 1.0; vbData[n++] = maxX; vbData[n++] = minY; vbData[n++] = 1.0; vbData[n++] = 1.0; vbData[n++] = maxX; vbData[n++] = maxY; break; default: break; } return vbData; } /** * @zh * 创建四边形输入汇集器。 */ protected _createQuadInputAssembler (): PipelineInputAssemblerData { // create vertex buffer const inputAssemblerData = new PipelineInputAssemblerData(); const vbStride = Float32Array.BYTES_PER_ELEMENT * 4; const vbSize = vbStride * 4; const quadVB = this._device.createBuffer(new BufferInfo( BufferUsageBit.VERTEX | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.DEVICE, vbSize, vbStride, )); if (!quadVB) { return inputAssemblerData; } // create index buffer const ibStride = Uint8Array.BYTES_PER_ELEMENT; const ibSize = ibStride * 6; const quadIB = this._device.createBuffer(new BufferInfo( BufferUsageBit.INDEX | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.DEVICE, ibSize, ibStride, )); if (!quadIB) { return inputAssemblerData; } const indices = new Uint8Array(6); indices[0] = 0; indices[1] = 1; indices[2] = 2; indices[3] = 1; indices[4] = 3; indices[5] = 2; quadIB.update(indices); // create input assembler const attributes = new Array<Attribute>(2); attributes[0] = new Attribute('a_position', Format.RG32F); attributes[1] = new Attribute('a_texCoord', Format.RG32F); const quadIA = this._device.createInputAssembler(new InputAssemblerInfo( attributes, [quadVB], quadIB, )); inputAssemblerData.quadIB = quadIB; inputAssemblerData.quadVB = quadVB; inputAssemblerData.quadIA = quadIA; return inputAssemblerData; } public updateQuadVertexData (renderArea: Rect, window: RenderWindow) { if (this._lastUsedRenderArea === renderArea) { return; } this._lastUsedRenderArea = renderArea; const offData = this._genQuadVertexData(SurfaceTransform.IDENTITY, renderArea); this._quadVBOffscreen!.update(offData); const onData = this._genQuadVertexData(window.swapchain && window.swapchain.surfaceTransform || SurfaceTransform.IDENTITY, renderArea); this._quadVBOnscreen!.update(onData); } /** * @en Internal destroy function * @zh 内部销毁函数。 */ public destroy (): boolean { for (let i = 0; i < this._flows.length; i++) { this._flows[i].destroy(); } this._flows.length = 0; if (this._descriptorSet) { this._descriptorSet.destroy(); } this._globalDSManager?.destroy(); for (let i = 0; i < this._commandBuffers.length; i++) { this._commandBuffers[i].destroy(); } this._commandBuffers.length = 0; this._pipelineUBO.destroy(); this._pipelineSceneData?.destroy(); return super.destroy(); } protected _generateConstantMacros () { let str = ''; str += `#define CC_DEVICE_SUPPORT_FLOAT_TEXTURE ${this.device.hasFeature(Feature.TEXTURE_FLOAT) ? 1 : 0}\n`; str += `#define CC_ENABLE_CLUSTERED_LIGHT_CULLING ${this._clusterEnabled ? 1 : 0}\n`; str += `#define CC_DEVICE_MAX_VERTEX_UNIFORM_VECTORS ${this.device.capabilities.maxVertexUniformVectors}\n`; str += `#define CC_DEVICE_MAX_FRAGMENT_UNIFORM_VECTORS ${this.device.capabilities.maxFragmentUniformVectors}\n`; str += `#define CC_DEVICE_CAN_BENEFIT_FROM_INPUT_ATTACHMENT ${this.device.hasFeature(Feature.INPUT_ATTACHMENT_BENEFIT) ? 1 : 0}\n`; this._constantMacros = str; } protected _generateBloomRenderData () { if (this.bloomEnabled === false) return; const bloom = this._pipelineRenderData!.bloom = new BloomRenderData(); const device = this.device; // create renderPass const colorAttachment = new ColorAttachment(); colorAttachment.format = Format.BGRA8; colorAttachment.loadOp = LoadOp.CLEAR; colorAttachment.storeOp = StoreOp.STORE; colorAttachment.endAccesses = [AccessType.COLOR_ATTACHMENT_WRITE]; bloom.renderPass = device.createRenderPass(new RenderPassInfo([colorAttachment])); let curWidth = this._width; let curHeight = this._height; // prefilter bloom.prefiterTex = device.createTexture(new TextureInfo( TextureType.TEX2D, TextureUsageBit.COLOR_ATTACHMENT | TextureUsageBit.SAMPLED, Format.BGRA8, curWidth >> 1, curHeight >> 1, )); bloom.prefilterFramebuffer = device.createFramebuffer(new FramebufferInfo( bloom.renderPass, [bloom.prefiterTex], )); // downsample & upsample curWidth >>= 1; curHeight >>= 1; for (let i = 0; i < MAX_BLOOM_FILTER_PASS_NUM; ++i) { bloom.downsampleTexs.push(device.createTexture(new TextureInfo( TextureType.TEX2D, TextureUsageBit.COLOR_ATTACHMENT | TextureUsageBit.SAMPLED, Format.BGRA8, curWidth >> 1, curHeight >> 1, ))); bloom.downsampleFramebuffers[i] = device.createFramebuffer(new FramebufferInfo( bloom.renderPass, [bloom.downsampleTexs[i]], )); bloom.upsampleTexs.push(device.createTexture(new TextureInfo( TextureType.TEX2D, TextureUsageBit.COLOR_ATTACHMENT | TextureUsageBit.SAMPLED, Format.BGRA8, curWidth, curHeight, ))); bloom.upsampleFramebuffers[i] = device.createFramebuffer(new FramebufferInfo( bloom.renderPass, [bloom.upsampleTexs[i]], )); curWidth >>= 1; curHeight >>= 1; } // combine bloom.combineTex = device.createTexture(new TextureInfo( TextureType.TEX2D, TextureUsageBit.COLOR_ATTACHMENT | TextureUsageBit.SAMPLED, Format.BGRA8, this._width, this._height, )); bloom.combineFramebuffer = device.createFramebuffer(new FramebufferInfo( bloom.renderPass, [bloom.combineTex], )); // sampler bloom.sampler = this.globalDSManager.linearSampler; } /** * @en * Register an callback of the pipeline event type on the RenderPipeline. * @zh * 在渲染管线中注册管线事件类型的回调。 */ public on (type: PipelineEventType, callback: any, target?: any, once?: boolean): typeof callback { return this._eventProcessor.on(type, callback, target, once); } /** * @en * Register an callback of the pipeline event type on the RenderPipeline, * the callback will remove itself after the first time it is triggered. * @zh * 在渲染管线中注册管线事件类型的回调, 回调后会在第一时间删除自身。 */ public once (type: PipelineEventType, callback: any, target?: any): typeof callback { return this._eventProcessor.once(type, callback, target); } /** * @en * Removes the listeners previously registered with the same type, callback, target and or useCapture, * if only type is passed as parameter, all listeners registered with that type will be removed. * @zh * 删除之前用同类型、回调、目标或 useCapture 注册的事件监听器,如果只传递 type,将会删除 type 类型的所有事件监听器。 */ public off (type: PipelineEventType, callback?: any, target?: any) { this._eventProcessor.off(type, callback, target); } /** * @zh 派发一个指定事件,并传递需要的参数 * @en Trigger an event directly with the event name and necessary arguments. * @param type - event type * @param args - Arguments when the event triggered */ public emit (type: PipelineEventType, arg0?: any, arg1?: any, arg2?: any, arg3?: any, arg4?: any) { this._eventProcessor.emit(type, arg0, arg1, arg2, arg3, arg4); } /** * @en Removes all callbacks previously registered with the same target (passed as parameter). * This is not for removing all listeners in the current event target, * and this is not for removing all listeners the target parameter have registered. * It's only for removing all listeners (callback and target couple) registered on the current event target by the target parameter. * @zh 在当前 EventTarget 上删除指定目标(target 参数)注册的所有事件监听器。 * 这个函数无法删除当前 EventTarget 的所有事件监听器,也无法删除 target 参数所注册的所有事件监听器。 * 这个函数只能删除 target 参数在当前 EventTarget 上注册的所有事件监听器。 * @param typeOrTarget - The target to be searched for all related listeners */ public targetOff (typeOrTarget: any) { this._eventProcessor.targetOff(typeOrTarget); } /** * @zh 移除在特定事件类型中注册的所有回调或在某个目标中注册的所有回调。 * @en Removes all callbacks registered in a certain event type or all callbacks registered with a certain target * @param typeOrTarget - The event type or target with which the listeners will be removed */ public removeAll (typeOrTarget: any) { this._eventProcessor.removeAll(typeOrTarget); } /** * @zh 检查指定事件是否已注册回调。 * @en Checks whether there is correspond event listener registered on the given event. * @param type - Event type. * @param callback - Callback function when event triggered. * @param target - Callback callee. */ public hasEventListener (type: PipelineEventType, callback?: any, target?: any): boolean { return this._eventProcessor.hasEventListener(type, callback, target); } } // Do not delete, for the class detection of editor legacyCC.RenderPipeline = RenderPipeline;
the_stack
import { products } from '../sample-data/apparel-checkout-flow'; import { cart, cartWithCheapProduct, cheapProduct, product, SampleCartProduct, SampleProduct, SampleUser, user, } from '../sample-data/checkout-flow'; import { addProductToCart as addToCart } from './applied-promotions'; import { login, register } from './auth-forms'; import { AddressData, fillPaymentDetails, fillShippingAddress, PaymentDetails, } from './checkout-forms'; import { DeepPartial } from './form'; import { productItemSelector } from './product-search'; export const ELECTRONICS_BASESITE = 'electronics-spa'; export const ELECTRONICS_CURRENCY = 'USD'; export const GET_CHECKOUT_DETAILS_ENDPOINT_ALIAS = 'GET_CHECKOUT_DETAILS'; export const firstAddToCartSelector = `${productItemSelector} cx-add-to-cart:first`; export function interceptCheckoutB2CDetailsEndpoint() { cy.intercept( 'GET', `${Cypress.env('OCC_PREFIX')}/${Cypress.env( 'BASE_SITE' )}/users/**/carts/**/*?fields=deliveryAddress(FULL),deliveryMode(FULL),paymentInfo(FULL)*` ).as(GET_CHECKOUT_DETAILS_ENDPOINT_ALIAS); return GET_CHECKOUT_DETAILS_ENDPOINT_ALIAS; } /** * Clicks the main menu (on mobile only) */ export function clickHamburger() { cy.onMobile(() => { cy.get('cx-hamburger-menu [aria-label="Menu"]').click(); }); } /** * Creates a routing alias for a given page * @param page Suffix of the url (page) to wait for * @param alias Name of the routing alias to obtain * @returns a Routing alias */ export function waitForPage(page: string, alias: string): string { // homepage is not explicitly being asked as it's driven by the backend. const route = page === 'homepage' ? { method: 'GET', path: `${Cypress.env('OCC_PREFIX')}/${Cypress.env( 'BASE_SITE' )}/cms/pages?lang=en&curr=*`, } : { method: 'GET', pathname: `${Cypress.env('OCC_PREFIX')}/${Cypress.env( 'BASE_SITE' )}/cms/pages`, query: { pageLabelOrId: page, }, }; cy.intercept(route).as(alias); return alias; } export function waitForProductPage(productCode: string, alias: string): string { cy.intercept({ method: 'GET', pathname: `${Cypress.env('OCC_PREFIX')}/${Cypress.env( 'BASE_SITE' )}/cms/pages`, query: { pageType: 'ProductPage', code: productCode, }, }).as(alias); return alias; } export function waitForCategoryPage( categoryCode: string, alias: string ): string { cy.intercept({ method: 'GET', pathname: `${Cypress.env('OCC_PREFIX')}/${Cypress.env( 'BASE_SITE' )}/cms/pages`, query: { pageType: 'CategoryPage', code: categoryCode, }, }).as(alias); return alias; } /** * Visits the homepage and waits for corresponding xhr call * @param queryStringParams Query string params */ export function visitHomePage(queryStringParams?: string) { const homePageAlias = waitForPage('homepage', 'getHomePage'); if (queryStringParams) { cy.visit(`/?${queryStringParams}`); } else { cy.visit('/'); } cy.wait(`@${homePageAlias}`); } export function signOut() { cy.selectUserMenuOption({ option: 'Sign Out', }); cy.get('cx-global-message div').should( 'contain', 'You have successfully signed out.' ); } export function registerUser( giveRegistrationConsent: boolean = false, sampleUser: SampleUser = user ) { const loginPage = waitForPage('/login', 'getLoginPage'); cy.findByText(/Sign in \/ Register/i).click(); cy.wait(`@${loginPage}`); const registerPage = waitForPage('/login/register', 'getRegisterPage'); cy.findByText('Register').click(); cy.wait(`@${registerPage}`); register(sampleUser, giveRegistrationConsent); cy.get('cx-breadcrumb').contains('Login'); return sampleUser; } export function signInUser(sampleUser: SampleUser = user) { const loginPage = waitForPage('/login', 'getLoginPage'); cy.findByText(/Sign in \/ Register/i).click(); cy.wait(`@${loginPage}`); login(sampleUser.email, sampleUser.password); } export function signOutUser() { const logoutPage = waitForPage('/logout', 'getLogoutPage'); signOut(); cy.wait(`@${logoutPage}`); cy.get('.cx-login-greet').should('not.exist'); } export function goToProductDetailsPage() { cy.visit('/'); // click big banner cy.get('.Section1 cx-banner').first().find('img').click({ force: true }); // click small banner number 6 (would be good if label or alt text would be available) cy.get('.Section2 cx-banner:nth-of-type(6) img').click({ force: true }); cy.get('cx-product-intro').within(() => { cy.get('.code').should('contain', product.code); }); cy.get('cx-breadcrumb').within(() => { cy.get('h1').should('contain', product.name); }); } export function addProductToCart() { cy.get('cx-item-counter').findByText('+').click(); addToCart(); cy.get('cx-added-to-cart-dialog').within(() => { cy.get('.cx-name .cx-link').should('contain', product.name); cy.findByText(/proceed to checkout/i).click(); }); } export function loginUser(sampleUser: SampleUser = user) { login(sampleUser.email, sampleUser.password); } export function fillAddressForm(shippingAddressData: AddressData = user) { cy.get('.cx-checkout-title').should('contain', 'Delivery Address'); cy.get('cx-order-summary .cx-summary-partials .cx-summary-row') .first() .find('.cx-summary-amount') .should('contain', cart.total); /** * Delivery mode PUT intercept is not in verifyDeliveryMethod() * because it doesn't choose a delivery mode and the intercept might have missed timing depending on cypress's performance */ const getCheckoutDetailsAlias = interceptCheckoutB2CDetailsEndpoint(); cy.intercept({ method: 'PUT', path: `${Cypress.env('OCC_PREFIX')}/${Cypress.env( 'BASE_SITE' )}/**/deliverymode?deliveryModeId=*`, }).as('putDeliveryMode'); const deliveryPage = waitForPage( '/checkout/delivery-mode', 'getDeliveryPage' ); fillShippingAddress(shippingAddressData); cy.wait(`@${deliveryPage}`).its('response.statusCode').should('eq', 200); cy.wait('@putDeliveryMode').its('response.statusCode').should('eq', 200); cy.wait(`@${getCheckoutDetailsAlias}`); } export function verifyDeliveryMethod() { cy.log('🛒 Selecting delivery method'); cy.get('.cx-checkout-title').should('contain', 'Delivery Method'); cy.get('cx-delivery-mode input').first().should('be.checked'); const paymentPage = waitForPage( '/checkout/payment-details', 'getPaymentPage' ); cy.get('.cx-checkout-btns button.btn-primary') .should('be.enabled') .click({ force: true }); cy.wait(`@${paymentPage}`).its('response.statusCode').should('eq', 200); } export function fillPaymentForm( paymentDetailsData: PaymentDetails = user, billingAddress?: AddressData ) { cy.get('.cx-checkout-title').should('contain', 'Payment'); cy.get('cx-order-summary .cx-summary-partials .cx-summary-total') .find('.cx-summary-amount') .should('not.be.empty'); fillPaymentDetails(paymentDetailsData, billingAddress); } export function verifyReviewOrderPage() { cy.get('.cx-review-title').should('contain', 'Review'); } export function placeOrder() { verifyReviewOrderPage(); cy.get('.cx-review-summary-card') .contains('cx-card', 'Ship To') .find('.cx-card-container') .within(() => { cy.findByText(user.fullName); cy.findByText(user.address.line1); cy.findByText(user.address.line2); }); cy.get('.cx-review-summary-card') .contains('cx-card', 'Delivery Method') .find('.cx-card-container') .within(() => { cy.findByText('Standard Delivery'); }); cy.get('cx-order-summary .cx-summary-row .cx-summary-amount') .eq(0) .should('contain', cart.total); cy.get('cx-order-summary .cx-summary-row .cx-summary-amount') .eq(1) .should('not.be.empty'); cy.get('cx-order-summary .cx-summary-total .cx-summary-amount').should( 'not.be.empty' ); cy.findByText('Terms & Conditions') .should('have.attr', 'target', '_blank') .should( 'have.attr', 'href', `/${Cypress.env('BASE_SITE')}/en/USD/terms-and-conditions` ); cy.get('.form-check-input').check(); cy.get('cx-place-order button.btn-primary').click(); } export function viewOrderHistory() { cy.selectUserMenuOption({ option: 'Order History', }); cy.get('cx-order-history h2').should('contain', 'Order history'); cy.get('.cx-order-history-table tr') .first() .find('.cx-order-history-total .cx-order-history-value') .should('not.be.empty'); } export function goToPaymentDetails() { cy.get('cx-checkout-progress li:nth-child(3) > a').click(); } export function clickAddNewPayment() { cy.findByText('Add New Payment').click(); } export function goToCheapProductDetailsPage( sampleProduct: SampleProduct = cheapProduct ) { visitHomePage(); clickCheapProductDetailsFromHomePage(sampleProduct); } export function clickCheapProductDetailsFromHomePage( sampleProduct: SampleProduct = cheapProduct ) { const productPage = waitForProductPage(sampleProduct.code, 'getProductPage'); cy.get('.Section4 cx-banner').first().find('img').click({ force: true }); cy.wait(`@${productPage}`).its('response.statusCode').should('eq', 200); cy.get('cx-product-intro').within(() => { cy.get('.code').should('contain', sampleProduct.code); }); cy.get('cx-breadcrumb').within(() => { cy.get('h1').should('contain', sampleProduct.name); }); } export function addCheapProductToCartAndLogin( sampleUser: SampleUser = user, sampleProduct: SampleProduct = cheapProduct ) { addCheapProductToCart(sampleProduct); const loginPage = waitForPage('/login', 'getLoginPage'); cy.findByText(/proceed to checkout/i).click(); cy.wait(`@${loginPage}`).its('response.statusCode').should('eq', 200); const deliveryAddressPage = waitForPage( '/checkout/delivery-address', 'getDeliveryPage' ); loginUser(sampleUser); // Double timeout, because we have here a cascade of requests (login, load /checkout page, merge cart, load shipping page) cy.wait(`@${deliveryAddressPage}`, { timeout: 30000 }) .its('response.statusCode') .should('eq', 200); } export function addCheapProductToCartAndProceedToCheckout( sampleProduct: SampleProduct = cheapProduct ) { addCheapProductToCart(sampleProduct); const loginPage = waitForPage('/login', 'getLoginPage'); cy.findByText(/proceed to checkout/i).click(); cy.wait(`@${loginPage}`); } export function addCheapProductToCartAndBeginCheckoutForSignedInCustomer( sampleProduct: SampleProduct = cheapProduct ) { addCheapProductToCart(sampleProduct); const deliveryAddressPage = waitForPage( '/checkout/delivery-address', 'getDeliveryAddressPage' ); cy.findByText(/proceed to checkout/i).click(); cy.wait(`@${deliveryAddressPage}`) .its('response.statusCode') .should('eq', 200); } export function addCheapProductToCart( sampleProduct: SampleProduct = cheapProduct ) { addToCart(); cy.get('cx-added-to-cart-dialog').within(() => { cy.get('.cx-name .cx-link').should('contain', sampleProduct.name); }); } export function proceedWithEmptyShippingAdressForm() { cy.log('🛒 Trying to proceed with empty address form'); fillShippingAddress(null); cy.get('cx-form-errors').should('exist'); } export function proceedWithIncorrectShippingAddressForm( shippingAddressData: Partial<AddressData> = user ) { cy.log('🛒 Trying to proceed with incorrect address form'); fillShippingAddress(shippingAddressData); cy.get('cx-form-errors').should('exist'); } export function checkSummaryAmount( cartData: SampleCartProduct = cartWithCheapProduct ) { cy.get('cx-order-summary .cx-summary-partials .cx-summary-total') .find('.cx-summary-amount') .should('contain', cartData.total); } export function fillAddressFormWithCheapProduct( shippingAddressData: Partial<AddressData> = user ) { cy.log('🛒 Filling shipping address form'); /** * Delivery mode PUT intercept is not in verifyDeliveryMethod() * because it doesn't choose a delivery mode and the intercept might have missed timing depending on cypress's performance */ const getCheckoutDetailsAlias = interceptCheckoutB2CDetailsEndpoint(); cy.intercept({ method: 'PUT', path: `${Cypress.env('OCC_PREFIX')}/${Cypress.env( 'BASE_SITE' )}/**/deliverymode?deliveryModeId=*`, }).as('putDeliveryMode'); const deliveryPage = waitForPage( '/checkout/delivery-mode', 'getDeliveryPage' ); fillShippingAddress(shippingAddressData); cy.wait(`@${deliveryPage}`).its('response.statusCode').should('eq', 200); cy.wait('@putDeliveryMode').its('response.statusCode').should('eq', 200); cy.wait(`@${getCheckoutDetailsAlias}`); } export function proceedWithEmptyPaymentForm() { cy.log('🛒 Trying to proceed with empty payment method form'); fillPaymentDetails(null); cy.get('cx-form-errors').should('exist'); } export function proceedWithIncorrectPaymentForm( paymentDetailsData: Partial<PaymentDetails> = user ) { cy.log('🛒 Trying to proceed with incorrect payment method form'); fillPaymentDetails(paymentDetailsData); cy.get('cx-form-errors').should('exist'); } export function fillPaymentFormWithCheapProduct( paymentDetailsData: DeepPartial<PaymentDetails> = user, billingAddress?: AddressData ) { cy.log('🛒 Filling payment method form'); cy.get('.cx-checkout-title').should('contain', 'Payment'); cy.get('cx-order-summary .cx-summary-partials .cx-summary-total') .find('.cx-summary-amount') .should('not.be.empty'); const reviewPage = waitForPage('/checkout/review-order', 'getReviewPage'); fillPaymentDetails(paymentDetailsData, billingAddress); cy.wait(`@${reviewPage}`).its('response.statusCode').should('eq', 200); } export function placeOrderWithCheapProduct( sampleUser: SampleUser = user, cartData: SampleCartProduct = cartWithCheapProduct, currency: string = 'USD' ) { cy.log('🛒 Placing order'); verifyReviewOrderPage(); cy.get('.cx-review-summary-card') .contains('cx-card', 'Ship To') .find('.cx-card-container') .within(() => { cy.findByText(sampleUser.fullName); cy.findByText(sampleUser.address.line1); cy.findByText(sampleUser.address.line2); }); cy.get('.cx-review-summary-card') .contains('cx-card', 'Delivery Method') .find('.cx-card-container') .within(() => { cy.findByText('Standard Delivery'); }); cy.get('cx-order-summary .cx-summary-row .cx-summary-amount') .eq(0) .should('contain', cartData.total); cy.get('cx-order-summary .cx-summary-row .cx-summary-amount') .eq(1) .should('contain', cartData.estimatedShipping); cy.get('cx-order-summary .cx-summary-total .cx-summary-amount').should( 'not.be.empty' ); cy.findByText('Terms & Conditions') .should('have.attr', 'target', '_blank') .should( 'have.attr', 'href', `/${Cypress.env('BASE_SITE')}/en/${currency}/terms-and-conditions` ); cy.get('input[formcontrolname="termsAndConditions"]').check(); const orderConfirmationPage = waitForPage( '/order-confirmation', 'getOrderConfirmationPage' ); cy.get('cx-place-order button.btn-primary').should('be.enabled').click(); cy.wait(`@${orderConfirmationPage}`) .its('response.statusCode') .should('eq', 200); } export function verifyOrderConfirmationPageWithCheapProduct( sampleUser: SampleUser = user, sampleProduct: SampleProduct = cheapProduct, isApparel: boolean = false ) { cy.get('.cx-page-title').should('contain', 'Confirmation of Order'); cy.get('h2').should('contain', 'Thank you for your order!'); cy.get('.cx-order-summary .container').within(() => { cy.get('.cx-summary-card:nth-child(1)').within(() => { cy.get('cx-card:nth-child(1)').within(() => { cy.get('.cx-card-title').should('contain', 'Order Number'); cy.get('.cx-card-label').should('not.be.empty'); }); cy.get('cx-card:nth-child(2)').within(() => { cy.get('.cx-card-title').should('contain', 'Placed on'); cy.get('.cx-card-label').should('not.be.empty'); }); cy.get('cx-card:nth-child(3)').within(() => { cy.get('.cx-card-title').should('contain', 'Status'); cy.get('.cx-card-label').should('not.be.empty'); }); }); cy.get('.cx-summary-card:nth-child(2) .cx-card').within(() => { cy.contains(sampleUser.fullName); cy.contains(sampleUser.address.line1); cy.contains('Standard Delivery'); }); cy.get('.cx-summary-card:nth-child(3) .cx-card').within(() => { cy.contains(sampleUser.fullName); cy.contains(sampleUser.address.line1); }); }); if (!isApparel) { cy.get('.cx-item-list-row .cx-code').should('contain', sampleProduct.code); } else { cy.get('.cx-item-list-row .cx-code') .should('have.length', products.length) .each((_, index) => { console.log('products', products[index]); cy.get('.cx-item-list-row .cx-code').should( 'contain', products[index].code ); }); } cy.get('cx-order-summary .cx-summary-amount').should('not.be.empty'); } export function viewOrderHistoryWithCheapProduct() { const orderHistoryPage = waitForPage( '/my-account/orders', 'getOrderHistoryPage' ); cy.selectUserMenuOption({ option: 'Order History', }); cy.wait(`@${orderHistoryPage}`).its('response.statusCode').should('eq', 200); cy.get('cx-order-history h2').should('contain', 'Order history'); cy.get('.cx-order-history-table tr') .first() .find('.cx-order-history-total .cx-order-history-value') .should('not.be.empty'); } export function addFirstResultToCartFromSearchAndLogin(sampleUser: SampleUser) { addToCart(); const loginPage = waitForPage('/login', 'getLoginPage'); cy.findByText(/proceed to checkout/i).click(); cy.wait(`@${loginPage}`).its('response.statusCode').should('eq', 200); const deliveryAddressPage = waitForPage( '/checkout/delivery-address', 'getDeliveryAddressPage' ); loginUser(sampleUser); cy.wait(`@${deliveryAddressPage}`, { timeout: 30000 }) .its('response.statusCode') .should('eq', 200); } export function checkoutFirstDisplayedProduct(user: SampleUser) { cy.intercept( 'POST', `${Cypress.env('OCC_PREFIX')}/${Cypress.env( 'BASE_SITE' )}/users/*/carts/*/entries?lang=en&curr=USD` ).as('addToCart'); cy.intercept( 'POST', `${Cypress.env('OCC_PREFIX')}/${Cypress.env( 'BASE_SITE' )}/users/current/carts?fields*` ).as('carts'); addFirstResultToCartFromSearchAndLogin(user); cy.wait('@addToCart').its('response.statusCode').should('eq', 200); cy.wait('@carts').its('response.statusCode').should('eq', 201); cy.get('@carts').then((xhr: any) => { const cartData = { total: xhr.response.body.totalPrice.formattedValue }; const code = xhr.response.body.code; checkSummaryAmount(cartData); proceedWithEmptyShippingAdressForm(); proceedWithIncorrectShippingAddressForm({ ...user, firstName: '', }); cy.intercept( 'GET', `${Cypress.env('OCC_PREFIX')}/${Cypress.env( 'BASE_SITE' )}/users/current/carts/${code}?fields=DEFAULT*` ).as('userCart'); fillAddressFormWithCheapProduct({ firstName: user.firstName }); cy.wait('@userCart').its('response.statusCode').should('eq', 200); verifyDeliveryMethod(); fillPaymentFormWithCheapProduct(user as PaymentDetails); cy.get('@userCart').then((xhr: any) => { const cart = xhr.response.body; const cartData = { total: cart.subTotal.formattedValue, estimatedShipping: cart.deliveryCost.formattedValue, }; placeOrderWithCheapProduct(user, cartData); }); cy.get('@addToCart').then((xhr: any) => { const responseProduct = xhr.response.body.entry.product; const sampleProduct = { code: responseProduct.code }; verifyOrderConfirmationPageWithCheapProduct(user, sampleProduct); }); }); }
the_stack
import {Element, List} from '@svgdotjs/svg.js' declare module "@svgdotjs/svg.js" { type EffectOrString = Effect | string type componentsOrFn = { r: number, g: number, b: number, a: number } | number | ((componentTransfer: ComponentTransferEffect) => void) export class Filter extends Element { constructor (node?: SVGFilterElement) constructor (attr: Object) targets (): List<Element> node: SVGFilterElement $source: 'SourceGraphic' $sourceAlpha: 'SourceAlpha' $background: 'BackgroundImage' $backgroundAlpha: 'BackgroundAlpha' $fill: 'FillPaint' $stroke: 'StrokePaint' $autoSetIn: boolean blend (in1: EffectOrString, in2: EffectOrString, mode: string): BlendEffect colorMatrix (type: string, values: Array<number> | string ): ColorMatrixEffect componentTransfer (components: componentsOrFn): ComponentTransferEffect composite (in1: EffectOrString, in2: EffectOrString, operator: string): CompositeEffect convolveMatrix (matrix: Array<number> | string): ConvolveMatrixEffect diffuseLighting (surfaceScale: number, lightingColor: string, diffuseConstant: number, kernelUnitLength: number): DiffuseLightingEffect displacementMap (in1: EffectOrString, in2: EffectOrString, scale: number, xChannelSelector: string, yChannelSelector: string): DisplacementMapEffect dropShadow (in1: EffectOrString, dx: number, dy: number, stdDeviation: number): DropShadowEffect flood (color: string, opacity: number): FloodEffect gaussianBlur (x: number, y: number): GaussianBlurEffect image (src: string): ImageEffect merge (input: Array<Effect> | ((mergeEffect: MergeEffect) => void)): MergeEffect morphology (operator: string, radius: number): MorphologyEffect offset (x: number, y: number): OffsetEffect specularLighting (surfaceScale: number, lightingColor: string, diffuseConstant: number, specularExponent: number, kernelUnitLength: number): SpecularLightingEffect tile (): TileEffect turbulence (baseFrequency: number, numOctaves: number, seed: number, stitchTiles: string, type: string): TurbulenceEffect } interface SVGFEDropShadowElement extends SVGElement, SVGFilterPrimitiveStandardAttributes { readonly in1: SVGAnimatedString; readonly dx: SVGAnimatedNumber; readonly dy: SVGAnimatedNumber; readonly stdDeviationX: SVGAnimatedNumber; readonly stdDeviationY: SVGAnimatedNumber; setStdDeviation(stdDeviationX: number, stdDeviationY: number): void; addEventListener<K extends keyof SVGElementEventMap>(type: K, listener: (this: SVGFEDisplacementMapElement, ev: SVGElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; removeEventListener<K extends keyof SVGElementEventMap>(type: K, listener: (this: SVGFEDisplacementMapElement, ev: SVGElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } type SVGEffectElement = SVGFEBlendElement | SVGFEBlendElement | SVGFEColorMatrixElement | SVGFEComponentTransferElement | SVGFECompositeElement | SVGFEConvolveMatrixElement | SVGFEDiffuseLightingElement | SVGFEDisplacementMapElement | SVGFEDropShadowElement | SVGFEFloodElement | SVGFEGaussianBlurElement | SVGFEImageElement | SVGFEMergeElement | SVGFEMorphologyElement | SVGFEOffsetElement | SVGFESpecularLightingElement | SVGFETileElement | SVGFETurbulenceElement // Base class for all effects class Effect extends Element { constructor (node?: SVGEffectElement) constructor (attr: Object) in (): Effect | string in (effect: Effect | string): this result (): string result (result: string): this blend (in2: EffectOrString, mode: string): BlendEffect colorMatrix (type: string, values: Array<number> | string ): ColorMatrixEffect componentTransfer (components: componentsOrFn): ComponentTransferEffect composite (in2: EffectOrString, operator: string): CompositeEffect convolveMatrix (matrix: Array<number> | string): ConvolveMatrixEffect diffuseLighting (surfaceScale: number, lightingColor: string, diffuseConstant: number, kernelUnitLength: number): DiffuseLightingEffect displacementMap (in2: EffectOrString, scale: number, xChannelSelector: string, yChannelSelector: string): DisplacementMapEffect dropShadow (dx: number, dy: number, stdDeviation: number): DropShadowEffect flood (color: string, opacity: number): FloodEffect gaussianBlur (x: number, y: number): GaussianBlurEffect image (src: string): ImageEffect merge (input: Array<Effect> | ((mergeEffect: MergeEffect) => void)): MergeEffect morphology (operator: string, radius: number): MorphologyEffect offset (x: number, y: number): OffsetEffect specularLighting (surfaceScale: number, lightingColor: string, diffuseConstant: number, specularExponent: number, kernelUnitLength: number): SpecularLightingEffect tile (): TileEffect turbulence (baseFrequency: number, numOctaves: number, seed: number, stitchTiles: string, type: string): TurbulenceEffect } interface LightEffects { distandLight (attr?: Object | SVGFEDistantLightElement): DistantLight pointLight (attr?: Object | SVGFEPointLightElement): PointLight spotLight (attr?: Object | SVGFESpotLightElement): SpotLight } // The following classes are all available effects // which can be used with filter class BlendEffect extends Effect { constructor (node: SVGFEBlendElement) constructor (attr: Object) in2 (effect: EffectOrString): this in2 (): EffectOrString } class ColorMatrixEffect extends Effect { constructor (node: SVGFEColorMatrixElement) constructor (attr: Object) } class ComponentTransferEffect extends Effect { constructor (node: SVGFEComponentTransferElement) constructor (attr: Object) funcR (attr?: Object | SVGFEFuncRElement): FuncR funcG (attr?: Object | SVGFEFuncGElement): FuncG funcB (attr?: Object | SVGFEFuncBElement): FuncB funcA (attr?: Object | SVGFEFuncAElement): FuncA } class CompositeEffect extends Effect { constructor (node: SVGFECompositeElement) constructor (attr: Object) in2 (effect: EffectOrString): this in2 (): EffectOrString } class ConvolveMatrixEffect extends Effect { constructor (node: SVGFEConvolveMatrixElement) constructor (attr: Object) } class DiffuseLightingEffect extends Effect implements LightEffects { constructor (node: SVGFEDiffuseLightingElement) constructor (attr: Object) distandLight (attr?: Object | SVGFEDistantLightElement): DistantLight pointLight (attr?: Object | SVGFEPointLightElement): PointLight spotLight (attr?: Object | SVGFESpotLightElement): SpotLight } class DisplacementMapEffect extends Effect { constructor (node: SVGFEDisplacementMapElement) constructor (attr: Object) in2 (effect: EffectOrString): this in2 (): EffectOrString } class DropShadowEffect extends Effect { constructor (node: SVGFEDropShadowElement) constructor (attr: Object) } class FloodEffect extends Effect { constructor (node: SVGFEFloodElement) constructor (attr: Object) } class GaussianBlurEffect extends Effect { constructor (node: SVGFEGaussianBlurElement) constructor (attr: Object) } class ImageEffect extends Effect { constructor (node: SVGFEImageElement) constructor (attr: Object) } class MergeEffect extends Effect { constructor (node: SVGFEMergeElement) constructor (attr: Object) mergeNode (attr?: Object | SVGFEMergeNodeElement): MergeNode } class MorphologyEffect extends Effect { constructor (node: SVGFEMorphologyElement) constructor (attr: Object) } class OffsetEffect extends Effect { constructor (node: SVGFEOffsetElement) constructor (attr: Object) } class SpecularLightingEffect extends Effect { constructor (node: SVGFESpecularLightingElement) constructor (attr: Object) distandLight (attr?: Object | SVGFEDistantLightElement): DistantLight pointLight (attr?: Object | SVGFEPointLightElement): PointLight spotLight (attr?: Object | SVGFESpotLightElement): SpotLight } class TileEffect extends Effect { constructor (node: SVGFETileElement) constructor (attr: Object) } class TurbulenceEffect extends Effect { constructor (node: SVGFETurbulenceElement) constructor (attr: Object) } // These are the lightsources for the following effects: // - DiffuseLightingEffect // - SpecularLightingEffect class DistantLight extends Effect { constructor (node: SVGFEDistantLightElement) constructor (attr: Object) } class PointLight extends Effect { constructor (node: SVGFEPointLightElement) constructor (attr: Object) } class SpotLight extends Effect { constructor (node: SVGFESpotLightElement) constructor (attr: Object) } // Mergenode is the element required for the MergeEffect class MergeNode extends Effect { constructor (node: SVGFEMergeNodeElement) constructor (attr: Object) } // Component elements for the ComponentTransferEffect class FuncR extends Effect { constructor (node: SVGFEFuncRElement) constructor (attr: Object) } class FuncG extends Effect { constructor (node: SVGFEFuncGElement) constructor (attr: Object) } class FuncB extends Effect { constructor (node: SVGFEFuncBElement) constructor (attr: Object) } class FuncA extends Effect { constructor (node: SVGFEFuncAElement) constructor (attr: Object) } // Extensions of the core lib interface Element { filterWith(filterOrFn?: Filter | ((filter: Filter) => void)): this filterer(): Filter | null unfilter(): this } interface Defs { filter(fn?: (filter: Filter) => void): Filter } interface Container { filter(fn?: (filter: Filter) => void): Filter } }
the_stack
import { AccessLevelList } from "../shared/access-level"; import { PolicyStatement } from "../shared"; /** * Statement provider for service [wisdom](https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazonconnectwisdom.html). * * @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement */ export class Wisdom extends PolicyStatement { public servicePrefix = 'wisdom'; /** * Statement provider for service [wisdom](https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazonconnectwisdom.html). * * @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement */ constructor (sid?: string) { super(sid); } /** * Grants permission to create an assistant * * Access Level: Write * * Possible conditions: * - .ifAwsTagKeys() * - .ifAwsRequestTag() * * https://docs.aws.amazon.com/wisdom/latest/APIReference/API_CreateAssistant.html */ public toCreateAssistant() { return this.to('CreateAssistant'); } /** * Grants permission to create an association between an assistant and another resource * * Access Level: Write * * Possible conditions: * - .ifAwsTagKeys() * - .ifAwsRequestTag() * * https://docs.aws.amazon.com/wisdom/latest/APIReference/API_CreateAssistantAssociation.html */ public toCreateAssistantAssociation() { return this.to('CreateAssistantAssociation'); } /** * Grants permission to create content * * Access Level: Write * * Possible conditions: * - .ifAwsTagKeys() * - .ifAwsRequestTag() * * https://docs.aws.amazon.com/wisdom/latest/APIReference/API_CreateContent.html */ public toCreateContent() { return this.to('CreateContent'); } /** * Grants permission to create a knowledge base * * Access Level: Write * * Possible conditions: * - .ifAwsTagKeys() * - .ifAwsRequestTag() * * https://docs.aws.amazon.com/wisdom/latest/APIReference/API_CreateKnowledgeBase.html */ public toCreateKnowledgeBase() { return this.to('CreateKnowledgeBase'); } /** * Grants permission to create a session * * Access Level: Write * * Possible conditions: * - .ifAwsTagKeys() * - .ifAwsRequestTag() * * https://docs.aws.amazon.com/wisdom/latest/APIReference/API_CreateSession.html */ public toCreateSession() { return this.to('CreateSession'); } /** * Grants permission to delete an assistant * * Access Level: Write * * https://docs.aws.amazon.com/wisdom/latest/APIReference/API_DeleteAssistant.html */ public toDeleteAssistant() { return this.to('DeleteAssistant'); } /** * Grants permission to delete an assistant association * * Access Level: Write * * https://docs.aws.amazon.com/wisdom/latest/APIReference/API_DeleteAssistantAssociation.html */ public toDeleteAssistantAssociation() { return this.to('DeleteAssistantAssociation'); } /** * Grants permission to delete content * * Access Level: Write * * https://docs.aws.amazon.com/wisdom/latest/APIReference/API_DeleteContent.html */ public toDeleteContent() { return this.to('DeleteContent'); } /** * Grants permission to delete a knowledge base * * Access Level: Write * * https://docs.aws.amazon.com/wisdom/latest/APIReference/API_DeleteKnowledgeBase.html */ public toDeleteKnowledgeBase() { return this.to('DeleteKnowledgeBase'); } /** * Grants permission to retrieve information about an assistant * * Access Level: Read * * https://docs.aws.amazon.com/wisdom/latest/APIReference/API_GetAssistant.html */ public toGetAssistant() { return this.to('GetAssistant'); } /** * Grants permission to retrieve information about an assistant association * * Access Level: Read * * https://docs.aws.amazon.com/wisdom/latest/APIReference/API_GetAssistantAssociation.html */ public toGetAssistantAssociation() { return this.to('GetAssistantAssociation'); } /** * Grants permission to retrieve content, including a pre-signed URL to download the content * * Access Level: Read * * https://docs.aws.amazon.com/wisdom/latest/APIReference/API_GetContent.html */ public toGetContent() { return this.to('GetContent'); } /** * Grants permission to retrieve summary information about the content * * Access Level: Read * * https://docs.aws.amazon.com/wisdom/latest/APIReference/API_GetContentSummary.html */ public toGetContentSummary() { return this.to('GetContentSummary'); } /** * Grants permission to retrieve information about the knowledge base * * Access Level: Read * * https://docs.aws.amazon.com/wisdom/latest/APIReference/API_GetKnowledgeBase.html */ public toGetKnowledgeBase() { return this.to('GetKnowledgeBase'); } /** * Grants permission to retrieve recommendations for the specified session * * Access Level: Read * * https://docs.aws.amazon.com/wisdom/latest/APIReference/API_GetRecommendations.html */ public toGetRecommendations() { return this.to('GetRecommendations'); } /** * Grants permission to retrieve information for a specified session * * Access Level: Read * * https://docs.aws.amazon.com/wisdom/latest/APIReference/API_GetSession.html */ public toGetSession() { return this.to('GetSession'); } /** * Grants permission to list information about assistant associations * * Access Level: List * * https://docs.aws.amazon.com/wisdom/latest/APIReference/API_ListAssistantAssociations.html */ public toListAssistantAssociations() { return this.to('ListAssistantAssociations'); } /** * Grants permission to list information about assistants * * Access Level: List * * https://docs.aws.amazon.com/wisdom/latest/APIReference/API_ListAssistants.html */ public toListAssistants() { return this.to('ListAssistants'); } /** * Grants permission to list the content with a knowledge base * * Access Level: List * * https://docs.aws.amazon.com/wisdom/latest/APIReference/API_ListContents.html */ public toListContents() { return this.to('ListContents'); } /** * Grants permission to list information about knowledge bases * * Access Level: List * * https://docs.aws.amazon.com/wisdom/latest/APIReference/API_ListKnowledgeBases.html */ public toListKnowledgeBases() { return this.to('ListKnowledgeBases'); } /** * Grants permission to list the tags for the specified resource * * Access Level: Read * * https://docs.aws.amazon.com/wisdom/latest/APIReference/API_ListTagsForResource.html */ public toListTagsForResource() { return this.to('ListTagsForResource'); } /** * Grants permission to remove the specified recommendations from the specified assistant's queue of newly available recommendations * * Access Level: Write * * https://docs.aws.amazon.com/wisdom/latest/APIReference/API_NotifyRecommendationsReceived.html */ public toNotifyRecommendationsReceived() { return this.to('NotifyRecommendationsReceived'); } /** * Grants permission to perform a manual search against the specified assistant * * Access Level: Read * * https://docs.aws.amazon.com/wisdom/latest/APIReference/API_QueryAssistant.html */ public toQueryAssistant() { return this.to('QueryAssistant'); } /** * Grants permission to remove a URI template from a knowledge base * * Access Level: Write * * https://docs.aws.amazon.com/wisdom/latest/APIReference/API_RemoveKnowledgeBaseTemplateUri.html */ public toRemoveKnowledgeBaseTemplateUri() { return this.to('RemoveKnowledgeBaseTemplateUri'); } /** * Grants permission to search for content referencing a specified knowledge base. Can be used to get a specific content resource by its name * * Access Level: Read * * https://docs.aws.amazon.com/wisdom/latest/APIReference/API_SearchContent.html */ public toSearchContent() { return this.to('SearchContent'); } /** * Grants permission to search for sessions referencing a specified assistant. Can be used to et a specific session resource by its name * * Access Level: Read * * https://docs.aws.amazon.com/wisdom/latest/APIReference/API_SearchSessions.html */ public toSearchSessions() { return this.to('SearchSessions'); } /** * Grants permission to get a URL to upload content to a knowledge base * * Access Level: Write * * https://docs.aws.amazon.com/wisdom/latest/APIReference/API_StartContentUpload.html */ public toStartContentUpload() { return this.to('StartContentUpload'); } /** * Grants permission to add the specified tags to the specified resource * * Access Level: Tagging * * Possible conditions: * - .ifAwsTagKeys() * - .ifAwsRequestTag() * * https://docs.aws.amazon.com/wisdom/latest/APIReference/API_TagResource.html */ public toTagResource() { return this.to('TagResource'); } /** * Grants permission to remove the specified tags from the specified resource * * Access Level: Tagging * * Possible conditions: * - .ifAwsTagKeys() * * https://docs.aws.amazon.com/wisdom/latest/APIReference/API_UntagResource.html */ public toUntagResource() { return this.to('UntagResource'); } /** * Grants permission to update information about the content * * Access Level: Write * * https://docs.aws.amazon.com/wisdom/latest/APIReference/API_UpdateContent.html */ public toUpdateContent() { return this.to('UpdateContent'); } /** * Grants permission to update the template URI of a knowledge base * * Access Level: Write * * https://docs.aws.amazon.com/wisdom/latest/APIReference/API_UpdateKnowledgeBaseTemplateUri.html */ public toUpdateKnowledgeBaseTemplateUri() { return this.to('UpdateKnowledgeBaseTemplateUri'); } protected accessLevelList: AccessLevelList = { "Write": [ "CreateAssistant", "CreateAssistantAssociation", "CreateContent", "CreateKnowledgeBase", "CreateSession", "DeleteAssistant", "DeleteAssistantAssociation", "DeleteContent", "DeleteKnowledgeBase", "NotifyRecommendationsReceived", "RemoveKnowledgeBaseTemplateUri", "StartContentUpload", "UpdateContent", "UpdateKnowledgeBaseTemplateUri" ], "Read": [ "GetAssistant", "GetAssistantAssociation", "GetContent", "GetContentSummary", "GetKnowledgeBase", "GetRecommendations", "GetSession", "ListTagsForResource", "QueryAssistant", "SearchContent", "SearchSessions" ], "List": [ "ListAssistantAssociations", "ListAssistants", "ListContents", "ListKnowledgeBases" ], "Tagging": [ "TagResource", "UntagResource" ] }; /** * Adds a resource of type Assistant to the statement * * https://docs.aws.amazon.com/wisdom/latest/APIReference/API_AssistantData.html * * @param assistantId - Identifier for the assistantId. * @param account - Account of the resource; defaults to empty string: all accounts. * @param region - Region of the resource; defaults to empty string: all regions. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. * * Possible conditions: * - .ifAwsResourceTag() */ public onAssistant(assistantId: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:wisdom:${Region}:${Account}:assistant/${AssistantId}'; arn = arn.replace('${AssistantId}', assistantId); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Region}', region || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } /** * Adds a resource of type AssistantAssociation to the statement * * https://docs.aws.amazon.com/wisdom/latest/APIReference/API_AssistantAssociationData.html * * @param assistantId - Identifier for the assistantId. * @param assistantAssociationId - Identifier for the assistantAssociationId. * @param account - Account of the resource; defaults to empty string: all accounts. * @param region - Region of the resource; defaults to empty string: all regions. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. * * Possible conditions: * - .ifAwsResourceTag() */ public onAssistantAssociation(assistantId: string, assistantAssociationId: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:wisdom:${Region}:${Account}:association/${AssistantId}/${AssistantAssociationId}'; arn = arn.replace('${AssistantId}', assistantId); arn = arn.replace('${AssistantAssociationId}', assistantAssociationId); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Region}', region || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } /** * Adds a resource of type Content to the statement * * https://docs.aws.amazon.com/wisdom/latest/APIReference/API_ContentData.html * * @param knowledgeBaseId - Identifier for the knowledgeBaseId. * @param contentId - Identifier for the contentId. * @param account - Account of the resource; defaults to empty string: all accounts. * @param region - Region of the resource; defaults to empty string: all regions. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. * * Possible conditions: * - .ifAwsResourceTag() */ public onContent(knowledgeBaseId: string, contentId: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:wisdom:${Region}:${Account}:content/${KnowledgeBaseId}/${ContentId}'; arn = arn.replace('${KnowledgeBaseId}', knowledgeBaseId); arn = arn.replace('${ContentId}', contentId); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Region}', region || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } /** * Adds a resource of type KnowledgeBase to the statement * * https://docs.aws.amazon.com/wisdom/latest/APIReference/API_KnowledgeBaseData.html * * @param knowledgeBaseId - Identifier for the knowledgeBaseId. * @param account - Account of the resource; defaults to empty string: all accounts. * @param region - Region of the resource; defaults to empty string: all regions. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. * * Possible conditions: * - .ifAwsResourceTag() */ public onKnowledgeBase(knowledgeBaseId: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:wisdom:${Region}:${Account}:knowledge-base/${KnowledgeBaseId}'; arn = arn.replace('${KnowledgeBaseId}', knowledgeBaseId); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Region}', region || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } /** * Adds a resource of type Session to the statement * * https://docs.aws.amazon.com/wisdom/latest/APIReference/API_SessionData.html * * @param assistantId - Identifier for the assistantId. * @param sessionId - Identifier for the sessionId. * @param account - Account of the resource; defaults to empty string: all accounts. * @param region - Region of the resource; defaults to empty string: all regions. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. * * Possible conditions: * - .ifAwsResourceTag() */ public onSession(assistantId: string, sessionId: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:wisdom:${Region}:${Account}:session/${AssistantId}/${SessionId}'; arn = arn.replace('${AssistantId}', assistantId); arn = arn.replace('${SessionId}', sessionId); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Region}', region || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } }
the_stack